From 440ccd6cb70248f1778f0b1130ef16ae806f01db Mon Sep 17 00:00:00 2001 From: Devanarayanan Date: Fri, 4 Dec 2026 19:14:09 +0000 Subject: [PATCH 1/5] chore(release): decouple component versioning, pre-push bumping, and CI workflows - Decouple Web (package.json), Mobile (mobile/pubspec.yaml, X.Y.Z without +build), and Backup (backup/VERSION) versioning with rollover-at-9 support - Add scripts/bump-version.js, scripts/pre-push-bump.js, and per-component scripts/sync-version.js; automate signed version bumps in .husky/pre-push - Path-filter .husky/pre-commit and lint-staged.config.js to staged files only - Centralize APP_NAME and inject internal APP_VERSION via next.config.ts and Dockerfile, removing NEXT_PUBLIC_APP_NAME and NEXT_PUBLIC_APP_VERSION from Infisical/env checks - Switch /api/security/attestation to runtime MIN_APP_VERSION and LATEST_APP_VERSION - Refactor release.yml for dual triggers (path-filtered main merges + signed web-v*/mobile-v*/backup-v* tags) and per-component GitHub Releases + deploy.yml - Path-gate test.yml, mobile-test.yml, and codeql.yml while keeping required check names - Update .example.env, docs/VERSIONING.md, docs/CONTRIBUTING.md, README.md, and tests --- .example.env | 19 +- .github/copilot-instructions.md | 45 +- .github/workflows/codeql.yml | 85 ++ .github/workflows/deploy.yml | 83 +- .github/workflows/mobile-test.yml | 46 +- .github/workflows/release.yml | 1014 +++++++++-------- .github/workflows/test.yml | 77 +- .husky/pre-commit | 21 +- .husky/pre-push | 3 + Dockerfile | 12 +- README.md | 7 +- backup/VERSION | 1 + docs/CONTRIBUTING.md | 44 +- docs/VERSIONING.md | 51 +- lint-staged.config.js | 29 +- mobile/pubspec.yaml | 2 +- next.config.ts | 4 + package.json | 2 + scripts/__tests__/version-scripts.test.ts | 197 ++++ scripts/bump-version.js | 288 +++++ scripts/pre-push-bump.js | 242 ++++ scripts/sync-version.js | 337 +++--- .../build-info/__tests__/page.test.tsx | 2 +- src/app/(public)/build-info/page.tsx | 2 +- .../api/provenance/__tests__/route.test.ts | 8 +- src/app/api/provenance/route.ts | 2 +- .../attestation/__tests__/route.test.ts | 34 +- src/app/api/security/attestation/route.ts | 4 +- .../layout/__tests__/footer.test.tsx | 6 +- src/components/layout/footer.tsx | 2 +- src/hooks/__tests__/use-build-info.test.ts | 4 +- src/hooks/use-build-info.ts | 2 +- src/lib/__tests__/validate-env.test.ts | 9 +- src/lib/constants/app.ts | 2 + src/lib/email.ts | 6 +- src/lib/validate-env.ts | 24 +- 36 files changed, 1922 insertions(+), 794 deletions(-) create mode 100644 .husky/pre-push create mode 100644 backup/VERSION create mode 100644 scripts/__tests__/version-scripts.test.ts create mode 100644 scripts/bump-version.js create mode 100644 scripts/pre-push-bump.js create mode 100644 src/lib/constants/app.ts diff --git a/.example.env b/.example.env index 5ff66ff0..0f4b58ba 100644 --- a/.example.env +++ b/.example.env @@ -35,16 +35,10 @@ # ============================================================================ # ---------------------------------------------------------------------------- -# App identity +# App identity & domains # ---------------------------------------------------------------------------- - -# âš ī¸ Application name displayed in UI and emails -# 🔨 Build-time (Infisical `/build-time` folder) -NEXT_PUBLIC_APP_NAME=GhostClass - -# âš ī¸ App version displayed in footer and health checks -# 🔨 Build-time (Infisical `/build-time` folder) -NEXT_PUBLIC_APP_VERSION=4.7.2 +# Note: APP_NAME ("GhostClass") and Web APP_VERSION (from package.json) are +# centralized in code/build config — they do not belong in Infisical. # âš ī¸ Your production domain WITHOUT https:// # All URL-based variables are derived from this. @@ -377,10 +371,15 @@ REQUEST_SIGNATURE_MAX_AGE=600 # Mobile Security & Attestation (Zero-Trust) # ---------------------------------------------------------------------------- -# âš ī¸ Minimum supported app version required to bypass forced update +# âš ī¸ Minimum supported mobile app version required to bypass forced update # 🚀 Runtime (Infisical `/runtime` folder → Server Env Var) MIN_APP_VERSION=4.7.2 +# âš ī¸ Latest published mobile app version advertised by /api/security/attestation +# Manage independently of Web releases whenever a new mobile binary ships. +# 🚀 Runtime (Infisical `/runtime` folder → Server Env Var) +LATEST_APP_VERSION=4.7.2 + # â„šī¸ Enforce Firebase App Check for all mobile clients in production # Valid: "true", "false" (default: false in dev, true recommended in prod) # 🚀 Runtime (Infisical `/runtime` folder → Server Env Var) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index be0a5d7d..25e17b91 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -263,34 +263,34 @@ Important mocking patterns: ### Version bumping -Version bumping is automated via workflows (see -`.github/workflows/auto-version-bump.yml`). +Version bumping is handled locally in `.husky/pre-push` (`scripts/pre-push-bump.js`) +on a per-component basis (`web`, `mobile`, `backup`) using Conventional Commits +and the rollover-at-9 rules in `docs/VERSIONING.md`, or manually via: -- Same-repo PRs: workflow handles bump -- Fork PRs: run bump script manually, then commit versioned artifacts +```bash +npm run version:bump -- --component web --type patch +``` -Files that must stay in sync for version bumps: +Files that stay in sync per component: -- `package.json` -- `package-lock.json` (or `pnpm-lock.yaml` / `yarn.lock`) -- `.example.env` (`NEXT_PUBLIC_APP_VERSION`) -- `public/openapi/openapi.yaml` +- **Web**: `package.json`, `package-lock.json`, `public/openapi/openapi.yaml` +- **Mobile**: `mobile/pubspec.yaml`, `mobile/lib/config/app_config.dart` +- **Backup**: `backup/VERSION` When updating core dependency versions, update `package.json` and run the install command for the chosen package manager. ### Main workflows -| Workflow | Purpose | -| --------------------------- | -------------------------------------- | -| `test.yml` | Web unit coverage + web Playwright E2E | -| `pipeline.yml` | Guard + auto-tag on merge to main | -| `auto-version-bump.yml` | PR version bump automation | -| `release.yml` | Signed release build + deploy pipeline | -| `deploy-egress-proxies.yml` | Deploy CF/AWS proxies | -| `deploy-supabase.yaml` | Supabase migration deployment | -| `provenance.yml` | Build provenance attestations | -| `scorecard.yml` | OpenSSF scorecard checks | +| Workflow | Purpose | +| ----------------- | --------------------------------------------------------------- | +| `build-guard.yml` | Trivy FS scan + commit signature & Dependabot schema checks | +| `test.yml` | Path-gated Web unit coverage + Playwright E2E | +| `mobile-test.yml` | Path-gated Flutter format, analyze & unit coverage | +| `codeql.yml` | Path-gated CodeQL analysis (JS/TS, GitHub Actions, Android) | +| `release.yml` | Decoupled component builds, Cosign/SLSA signing & GitHub Releases | +| `deploy.yml` | Supabase migrations, CF/AWS proxies & Coolify digest deployment | +| `scorecard.yml` | OpenSSF Scorecard checks | Dependabot PRs do not have repository secrets; secret-dependent jobs must stay guarded. @@ -325,10 +325,9 @@ guarded. ## Where to update versions and references -- Web: update `package.json` and `tsconfig.json` as needed -- Mobile: update `mobile/pubspec.yaml` -- OpenAPI: update `public/openapi/openapi.yaml` and run any generation scripts - in `scripts/` +- Web: `npm run version:bump -- --component web --type patch` (updates `package.json`, `package-lock.json`, `public/openapi/openapi.yaml`) +- Mobile: `npm run version:bump -- --component mobile --type patch` (updates `mobile/pubspec.yaml`, `mobile/lib/config/app_config.dart`) +- Backup: `npm run version:bump -- --component backup --type patch` (updates `backup/VERSION`) --- diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 3845c76f..33f6c585 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -16,70 +16,148 @@ permissions: contents: read jobs: + changes: + name: Detect CodeQL Targets + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + outputs: + js: ${{ steps.decide.outputs.js }} + actions: ${{ steps.decide.outputs.actions }} + android: ${{ steps.decide.outputs.android }} + steps: + - name: Checkout + if: github.event_name == 'pull_request' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + fetch-depth: 0 + + - name: Filter PR paths + if: github.event_name == 'pull_request' + uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2 + id: filter + with: + filters: | + js: + - 'src/**' + - 'e2e/**' + - 'scripts/**' + - 'workers/**' + - '*.ts' + - '*.js' + - '*.mjs' + - 'package.json' + - 'package-lock.json' + actions: + - '.github/workflows/**' + - '.github/actions/**' + android: + - 'mobile/**' + + - name: Decide CodeQL targets + id: decide + run: | + if [ "${{ github.event_name }}" != "pull_request" ]; then + echo "js=true" >> "$GITHUB_OUTPUT" + echo "actions=true" >> "$GITHUB_OUTPUT" + echo "android=true" >> "$GITHUB_OUTPUT" + else + echo "js=${{ steps.filter.outputs.js }}" >> "$GITHUB_OUTPUT" + echo "actions=${{ steps.filter.outputs.actions }}" >> "$GITHUB_OUTPUT" + echo "android=${{ steps.filter.outputs.android }}" >> "$GITHUB_OUTPUT" + fi + codeql-js: name: CodeQL JavaScript/TypeScript + needs: changes runs-on: ubuntu-latest permissions: contents: read security-events: write steps: + - name: Skip notice + if: needs.changes.outputs.js != 'true' + run: echo "â­ī¸ Skipping JS/TS CodeQL (no JS/TS files changed in PR)." + - name: Checkout + if: needs.changes.outputs.js == 'true' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - name: Initialize CodeQL (JS/TS) + if: needs.changes.outputs.js == 'true' uses: github/codeql-action/init@52cf1852265d99e9bea071b03366fc777a602909 with: languages: javascript-typescript - name: Autobuild (JS/TS) + if: needs.changes.outputs.js == 'true' uses: github/codeql-action/autobuild@52cf1852265d99e9bea071b03366fc777a602909 - name: Run CodeQL analysis (JS/TS) + if: needs.changes.outputs.js == 'true' uses: github/codeql-action/analyze@52cf1852265d99e9bea071b03366fc777a602909 with: category: "/language:javascript-typescript" codeql-actions: name: CodeQL Actions + needs: changes runs-on: ubuntu-latest permissions: contents: read security-events: write actions: read steps: + - name: Skip notice + if: needs.changes.outputs.actions != 'true' + run: echo "â­ī¸ Skipping Actions CodeQL (no workflow/action files changed in PR)." + - name: Checkout + if: needs.changes.outputs.actions == 'true' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - name: Initialize CodeQL (Actions) + if: needs.changes.outputs.actions == 'true' uses: github/codeql-action/init@52cf1852265d99e9bea071b03366fc777a602909 with: languages: actions - name: Autobuild (Actions) + if: needs.changes.outputs.actions == 'true' uses: github/codeql-action/autobuild@52cf1852265d99e9bea071b03366fc777a602909 - name: Run CodeQL analysis (Actions) + if: needs.changes.outputs.actions == 'true' uses: github/codeql-action/analyze@52cf1852265d99e9bea071b03366fc777a602909 with: category: "/language:actions" codeql-android: name: CodeQL Android (Java/Kotlin) + needs: changes runs-on: ubuntu-latest permissions: contents: read security-events: write steps: + - name: Skip notice + if: needs.changes.outputs.android != 'true' + run: echo "â­ī¸ Skipping Android CodeQL (no mobile files changed in PR)." + - name: Checkout + if: needs.changes.outputs.android == 'true' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - name: Download Gradle Wrapper + if: needs.changes.outputs.android == 'true' run: | mkdir -p mobile/android/gradle/wrapper curl -fSL -o mobile/android/gradle/wrapper/gradle-wrapper.jar https://raw.githubusercontent.com/gradle/gradle/v9.6.1/gradle/wrapper/gradle-wrapper.jar echo "497c8c2a7e5031f6aa847f88104aa80a93532ec32ee17bdb8d1d2f67a194a9c7 mobile/android/gradle/wrapper/gradle-wrapper.jar" | sha256sum -c - - name: Set up JDK + if: needs.changes.outputs.android == 'true' uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 with: distribution: "temurin" @@ -88,20 +166,24 @@ jobs: cache-dependency-path: "mobile/android/gradle/wrapper/gradle-wrapper.properties" - name: Set up Flutter + if: needs.changes.outputs.android == 'true' uses: ./.github/actions/flutter-action with: channel: stable cache: true - name: Fetch Flutter dependencies + if: needs.changes.outputs.android == 'true' working-directory: mobile run: flutter pub get - name: Prepare app_secrets.dart + if: needs.changes.outputs.android == 'true' working-directory: mobile run: cp lib/config/app_secrets.dart.example lib/config/app_secrets.dart - name: Prepare google-services.json + if: needs.changes.outputs.android == 'true' working-directory: mobile env: GOOGLE_SERVICES_JSON_BASE64: ${{ env.GOOGLE_SERVICES_JSON_BASE64 || secrets.GOOGLE_SERVICES_JSON_BASE64 }} @@ -132,16 +214,19 @@ jobs: fi - name: Initialize CodeQL (Java + Kotlin) + if: needs.changes.outputs.android == 'true' uses: github/codeql-action/init@52cf1852265d99e9bea071b03366fc777a602909 with: languages: java-kotlin build-mode: manual - name: Build Android Kotlin source (Triggers CodeQL extraction) + if: needs.changes.outputs.android == 'true' working-directory: mobile/android run: ./gradlew :app:compileDebugSources --no-daemon - name: Run CodeQL analysis (Android) + if: needs.changes.outputs.android == 'true' uses: github/codeql-action/analyze@52cf1852265d99e9bea071b03366fc777a602909 with: category: "/language:java-kotlin" diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 3b9d9842..c6c04cf7 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -4,15 +4,52 @@ on: workflow_dispatch: inputs: image_digest: - description: "Exact immutable image digest to deploy (e.g. sha256:...)" + description: "Exact immutable Web image digest to deploy (e.g. sha256:...)" required: false type: string default: "" image_tag: - description: "Image tag to deploy if digest is unset (defaults to version/latest)" + description: "Image tag to deploy if digest is unset (defaults to commit SHA)" required: false type: string default: "" + deploy_web: + description: "Deploy Web application to Coolify" + required: false + type: boolean + default: true + deploy_backup: + description: "Deploy Backup service to Coolify" + required: false + type: boolean + default: false + deploy_infra: + description: "Deploy Supabase migrations and CF/AWS proxies" + required: false + type: boolean + default: true + workflow_call: + inputs: + deploy_web: + required: false + type: boolean + default: false + web_image_digest: + required: false + type: string + default: "" + deploy_backup: + required: false + type: boolean + default: false + backup_image_digest: + required: false + type: string + default: "" + deploy_infra: + required: false + type: boolean + default: false permissions: {} @@ -25,6 +62,8 @@ jobs: # ──────────────────────────────────────────────────────────────────────────── deploy-supabase: name: Deploy Supabase + if: (github.event_name == 'workflow_dispatch' && inputs.deploy_infra != false) || inputs.deploy_infra == true + environment: production runs-on: ubuntu-latest permissions: contents: read @@ -77,7 +116,8 @@ jobs: deploy-proxy: name: Deploy Proxy needs: deploy-supabase - if: github.actor != 'dependabot[bot]' + if: always() && !cancelled() && (needs.deploy-supabase.result == 'success' || needs.deploy-supabase.result == 'skipped') && github.actor != 'dependabot[bot]' && ((github.event_name == 'workflow_dispatch' && inputs.deploy_infra != false) || inputs.deploy_infra == true) + environment: production runs-on: ubuntu-latest permissions: contents: read @@ -376,7 +416,9 @@ jobs: # ──────────────────────────────────────────────────────────────────────────── deploy-prod: name: Deploy Production - needs: deploy-proxy + needs: [deploy-supabase, deploy-proxy] + if: always() && !cancelled() && (needs.deploy-supabase.result == 'success' || needs.deploy-supabase.result == 'skipped') && (needs.deploy-proxy.result == 'success' || needs.deploy-proxy.result == 'skipped') && ((github.event_name == 'workflow_dispatch' && (inputs.deploy_web != false || inputs.deploy_backup != false)) || inputs.deploy_web == true || inputs.deploy_backup == true) + environment: production runs-on: ubuntu-latest permissions: contents: read @@ -399,19 +441,20 @@ jobs: secret-path: "/ci" continue-on-error: true - - name: Trigger Coolify deployment + - name: Trigger Coolify Web deployment + if: (github.event_name == 'workflow_dispatch' && inputs.deploy_web != false) || inputs.deploy_web == true env: COOLIFY_BASE_URL: ${{ env.COOLIFY_BASE_URL || secrets.COOLIFY_BASE_URL }} COOLIFY_APP_ID: ${{ env.COOLIFY_APP_ID || secrets.COOLIFY_APP_ID }} COOLIFY_API_TOKEN: ${{ env.COOLIFY_API_TOKEN || secrets.COOLIFY_API_TOKEN }} - INPUT_DIGEST: ${{ github.event.inputs.image_digest || '' }} - INPUT_TAG: ${{ github.event.inputs.image_tag || '' }} + INPUT_WEB_DIGEST: ${{ inputs.web_image_digest || '' }} + INPUT_DIGEST: ${{ inputs.image_digest || '' }} + INPUT_TAG: ${{ inputs.image_tag || '' }} REPO_OWNER: ${{ github.repository_owner }} run: | set -euo pipefail set +x - # Validate required Coolify configuration : "${COOLIFY_BASE_URL:?COOLIFY_BASE_URL secret is required}" : "${COOLIFY_APP_ID:?COOLIFY_APP_ID secret is required}" : "${COOLIFY_API_TOKEN:?COOLIFY_API_TOKEN secret is required}" @@ -421,37 +464,35 @@ jobs: [ -n "$COOLIFY_APP_ID" ] && echo "::add-mask::$COOLIFY_APP_ID" REPO_NAME=$(echo "${{ github.repository }}" | cut -d'/' -f2 | tr '[:upper:]' '[:lower:]') - VERSION="${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION || 'latest' }}" - - TARGET_TAG="${INPUT_DIGEST:-${INPUT_TAG:-${{ github.sha }}}}" + TARGET_TAG="${INPUT_WEB_DIGEST:-${INPUT_DIGEST:-${INPUT_TAG:-${{ github.sha }}}}}" REPO_OWNER_LOWER=$(echo "${REPO_OWNER}" | tr '[:upper:]' '[:lower:]') IMAGE_REPO="ghcr.io/${REPO_OWNER_LOWER}/${REPO_NAME}" - echo "Updating Coolify application to image: ${IMAGE_REPO}:${TARGET_TAG}" + echo "Updating Coolify Web application to image: ${IMAGE_REPO}@${TARGET_TAG}" - # 1. Update application image reference to the exact repository and tag curl --fail-with-body --silent --show-error -X PATCH \ "${COOLIFY_BASE_URL}/api/v1/applications/${COOLIFY_APP_ID}" \ -H "Authorization: Bearer ${COOLIFY_API_TOKEN}" \ -H "Content-Type: application/json" \ -d "{\"docker_registry_image_name\": \"${IMAGE_REPO}\", \"docker_registry_image_tag\": \"${TARGET_TAG}\"}" - echo "✓ Coolify application image reference updated" + echo "✓ Coolify Web image reference updated" - # 2. Trigger deployment curl --fail-with-body --silent --show-error -X POST \ "${COOLIFY_BASE_URL}/api/v1/deploy?uuid=$COOLIFY_APP_ID" \ -H "Authorization: Bearer $COOLIFY_API_TOKEN" - echo "✓ Deployment triggered successfully" + echo "✓ Web deployment triggered successfully" - - name: Trigger Coolify backup deployment (optional) + - name: Trigger Coolify Backup deployment (optional) + if: (github.event_name == 'workflow_dispatch' && inputs.deploy_backup != false) || inputs.deploy_backup == true env: COOLIFY_BASE_URL: ${{ env.COOLIFY_BASE_URL || secrets.COOLIFY_BASE_URL }} COOLIFY_BACKUP_APP_ID: ${{ env.COOLIFY_BACKUP_APP_ID || secrets.COOLIFY_BACKUP_APP_ID || vars.COOLIFY_BACKUP_APP_ID || '' }} COOLIFY_API_TOKEN: ${{ env.COOLIFY_API_TOKEN || secrets.COOLIFY_API_TOKEN }} REPO_OWNER: ${{ github.repository_owner }} - INPUT_TAG: ${{ github.event.inputs.image_tag || '' }} + INPUT_BACKUP_DIGEST: ${{ inputs.backup_image_digest || '' }} + INPUT_TAG: ${{ inputs.image_tag || '' }} run: | set -euo pipefail set +x @@ -464,20 +505,18 @@ jobs: [ -n "$COOLIFY_BASE_URL" ] && echo "::add-mask::$COOLIFY_BASE_URL" [ -n "$COOLIFY_BACKUP_APP_ID" ] && echo "::add-mask::$COOLIFY_BACKUP_APP_ID" - TARGET_TAG="${INPUT_TAG:-${{ github.sha }}}" + TARGET_TAG="${INPUT_BACKUP_DIGEST:-${INPUT_TAG:-${{ github.sha }}}}" REPO_OWNER_LOWER=$(echo "${REPO_OWNER}" | tr '[:upper:]' '[:lower:]') BACKUP_IMAGE_REPO="ghcr.io/${REPO_OWNER_LOWER}/ghostclass-backup" - echo "Updating Coolify backup service (${COOLIFY_BACKUP_APP_ID}) to immutable hash: ${BACKUP_IMAGE_REPO}:${TARGET_TAG}" + echo "Updating Coolify backup service (${COOLIFY_BACKUP_APP_ID}) to: ${BACKUP_IMAGE_REPO}:${TARGET_TAG}" - # 1. Update application image reference to the exact repository and tag curl --fail-with-body --silent --show-error -X PATCH \ "${COOLIFY_BASE_URL}/api/v1/applications/${COOLIFY_BACKUP_APP_ID}" \ -H "Authorization: Bearer ${COOLIFY_API_TOKEN}" \ -H "Content-Type: application/json" \ -d "{\"docker_registry_image_name\": \"${BACKUP_IMAGE_REPO}\", \"docker_registry_image_tag\": \"${TARGET_TAG}\"}" - # 2. Trigger deployment echo "Deploying backup service to Coolify (${COOLIFY_BACKUP_APP_ID})" curl --fail-with-body --silent --show-error -X POST \ "${COOLIFY_BASE_URL}/api/v1/deploy?uuid=${COOLIFY_BACKUP_APP_ID}" \ diff --git a/.github/workflows/mobile-test.yml b/.github/workflows/mobile-test.yml index 4499ddce..a1cb4351 100644 --- a/.github/workflows/mobile-test.yml +++ b/.github/workflows/mobile-test.yml @@ -2,9 +2,9 @@ name: Mobile Tests on: push: - branches: [main, "release/*"] + branches: [main] pull_request: - branches: [main, "release/*"] + branches: [main] env: FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true" @@ -12,7 +12,33 @@ env: permissions: {} jobs: + changes: + name: Detect Mobile Changes + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + outputs: + mobile: ${{ steps.filter.outputs.mobile }} + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + fetch-depth: 0 + + - name: Filter changed paths + uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2 + id: filter + with: + filters: | + mobile: + - 'mobile/**' + - 'scripts/generate-firebase-json.js' + - '.github/actions/flutter-action/**' + - '.github/workflows/mobile-test.yml' + flutter-unit-tests: + needs: changes runs-on: ubuntu-latest permissions: contents: read @@ -20,40 +46,55 @@ jobs: run: working-directory: mobile steps: + - name: Skip notice + if: needs.changes.outputs.mobile != 'true' + working-directory: . + run: echo "â­ī¸ Skipping Flutter tests (no mobile files changed)." + - name: Checkout + if: needs.changes.outputs.mobile == 'true' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - name: Set up Java + if: needs.changes.outputs.mobile == 'true' uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 with: distribution: temurin java-version: "25" - name: Set up Flutter + if: needs.changes.outputs.mobile == 'true' uses: ./.github/actions/flutter-action with: channel: stable cache: true - name: Install dependencies + if: needs.changes.outputs.mobile == 'true' run: flutter pub get - name: Verify formatting + if: needs.changes.outputs.mobile == 'true' run: dart format --output=none --set-exit-if-changed . lib/config/app_secrets.dart.example - name: Prepare app_secrets.dart + if: needs.changes.outputs.mobile == 'true' run: cp lib/config/app_secrets.dart.example lib/config/app_secrets.dart - name: Generate dynamic firebase.json + if: needs.changes.outputs.mobile == 'true' run: node ../scripts/generate-firebase-json.js - name: Run static analysis (Audit) + if: needs.changes.outputs.mobile == 'true' run: flutter analyze --fatal-infos --fatal-warnings - name: Run unit tests with coverage + if: needs.changes.outputs.mobile == 'true' run: flutter test --coverage - name: Enforce minimum code coverage threshold + if: needs.changes.outputs.mobile == 'true' env: MIN_COVERAGE: "25.0" run: | @@ -81,6 +122,7 @@ jobs: fi - name: Upload coverage to Codecov + if: needs.changes.outputs.mobile == 'true' uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 with: files: ./mobile/coverage/lcov.info diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0d62704f..27dacbd5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,31 +1,65 @@ name: Release on: + push: + branches: + - main + tags: + - "web-v*" + - "mobile-v*" + - "backup-v*" workflow_dispatch: inputs: + build_web: + description: "Build & release Web Docker image" + required: false + type: boolean + default: false + build_mobile: + description: "Build & release Flutter Android APK/AAB" + required: false + type: boolean + default: false + build_backup: + description: "Build & release Backup Runner Docker image" + required: false + type: boolean + default: false build_arm64: description: "Build ARM64 architecture (slower, ~5min extra)" required: false type: boolean default: false - push: - branches: - - main env: FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true" permissions: {} + jobs: - # Initial repository check guard + # ──────────────────────────────────────────────────────────────────────────── + # Job 0: Security Guard, Tag Verification & Component Plan + # ──────────────────────────────────────────────────────────────────────────── guard: name: Build Guard runs-on: ubuntu-latest permissions: contents: read + pull-requests: read + outputs: + build_web: ${{ steps.plan.outputs.build_web }} + build_mobile: ${{ steps.plan.outputs.build_mobile }} + build_backup: ${{ steps.plan.outputs.build_backup }} + deploy_infra: ${{ steps.plan.outputs.deploy_infra }} + web_version: ${{ steps.plan.outputs.web_version }} + mobile_version: ${{ steps.plan.outputs.mobile_version }} + backup_version: ${{ steps.plan.outputs.backup_version }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + fetch-depth: 0 + persist-credentials: false - name: Run Trivy vulnerability scanner uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 @@ -36,13 +70,200 @@ jobs: exit-code: "1" severity: "CRITICAL,HIGH" - # Build, sign, and push Docker images + - name: Import GPG and SSH public keys for tag verification + if: startsWith(github.ref, 'refs/tags/') + run: | + set -euo pipefail + + mkdir -p -m 700 ~/.gnupg + mkdir -p -m 700 ~/.ssh + touch ~/.ssh/allowed_signers + git config --global gpg.ssh.allowedSignersFile ~/.ssh/allowed_signers + + CANDIDATES=( + "${{ github.actor }}" + "${{ github.repository_owner }}" + "web-flow" + ) + + for user in "${CANDIDATES[@]}"; do + clean_user=$(echo "$user" | tr -d '[:space:]') + if [ -n "$clean_user" ]; then + curl -fsSL --retry 3 --retry-connrefused --max-time 10 \ + "https://github.com/${clean_user}.gpg" 2>/dev/null | gpg --batch --import 2>/dev/null || true + + curl -fsSL --retry 3 --retry-connrefused --max-time 10 \ + "https://github.com/${clean_user}.keys" 2>/dev/null | while IFS= read -r key || [ -n "$key" ]; do + if [[ "$key" =~ ^(ssh-|ecdsa-|sk-) ]]; then + echo "* $key" >> ~/.ssh/allowed_signers + fi + done || true + fi + done + + if [ -f ~/.ssh/allowed_signers ]; then + sort -u ~/.ssh/allowed_signers -o ~/.ssh/allowed_signers + fi + + # Attempt keyserver lookup if tag uses a GPG key not yet imported + TAG_KEY_ID=$(git for-each-ref --format='%(objectname)' "refs/tags/${GITHUB_REF_NAME}" | xargs -I{} git cat-file -p {} | grep -oE 'keyid [A-F0-9]+' | awk '{print $2}' || true) + if [ -n "$TAG_KEY_ID" ]; then + gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$TAG_KEY_ID" 2>/dev/null || \ + gpg --batch --keyserver keys.openpgp.org --recv-keys "$TAG_KEY_ID" 2>/dev/null || true + fi + + - name: Verify signed component tag + if: startsWith(github.ref, 'refs/tags/') + run: | + set -euo pipefail + echo "Verifying cryptographic signature on tag: ${GITHUB_REF_NAME}" + git verify-tag "${GITHUB_REF_NAME}" + echo "✓ Tag ${GITHUB_REF_NAME} signature verified." + + - name: Filter changed component paths on main push + if: github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/') + uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2 + id: paths + with: + filters: | + web: + - 'src/**' + - 'public/**' + - 'package.json' + - 'package-lock.json' + - 'next.config.ts' + - 'Dockerfile' + - '.dockerignore' + - 'tsconfig.json' + - 'postcss.config.mjs' + - 'components.json' + - 'next-env.d.ts' + mobile: + - 'mobile/**' + backup: + - 'backup/**' + infra: + - 'supabase/**' + - 'workers/**' + + - name: Determine release plan & component versions + id: plan + env: + EVENT_NAME: ${{ github.event_name }} + REF_NAME: ${{ github.ref_name }} + IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }} + PATH_WEB: ${{ steps.paths.outputs.web || 'false' }} + PATH_MOBILE: ${{ steps.paths.outputs.mobile || 'false' }} + PATH_BACKUP: ${{ steps.paths.outputs.backup || 'false' }} + PATH_INFRA: ${{ steps.paths.outputs.infra || 'false' }} + INPUT_WEB: ${{ github.event.inputs.build_web || 'false' }} + INPUT_MOBILE: ${{ github.event.inputs.build_mobile || 'false' }} + INPUT_BACKUP: ${{ github.event.inputs.build_backup || 'false' }} + run: | + set -euo pipefail + + WEB_VER=$(node -p "require('./package.json').version") + MOBILE_VER=$(grep -E '^version:' mobile/pubspec.yaml | head -n1 | sed -E 's/^version:[[:space:]]*([0-9]+\.[0-9]+\.[0-9]+).*/\1/') + BACKUP_VER=$(tr -d '[:space:]' < backup/VERSION) + + echo "Repository versions: web=${WEB_VER}, mobile=${MOBILE_VER}, backup=${BACKUP_VER}" + echo "web_version=${WEB_VER}" >> "$GITHUB_OUTPUT" + echo "mobile_version=${MOBILE_VER}" >> "$GITHUB_OUTPUT" + echo "backup_version=${BACKUP_VER}" >> "$GITHUB_OUTPUT" + + BUILD_WEB=false + BUILD_MOBILE=false + BUILD_BACKUP=false + DEPLOY_INFRA=false + + if [ "$IS_TAG" = "true" ]; then + case "$REF_NAME" in + web-v*) + TAG_VER="${REF_NAME#web-v}" + if [ "$TAG_VER" != "$WEB_VER" ]; then + echo "::error::Tag ${REF_NAME} does not match package.json version (${WEB_VER})." + exit 1 + fi + BUILD_WEB=true + DEPLOY_INFRA=true + ;; + mobile-v*) + TAG_VER="${REF_NAME#mobile-v}" + if [ "$TAG_VER" != "$MOBILE_VER" ]; then + echo "::error::Tag ${REF_NAME} does not match mobile/pubspec.yaml version (${MOBILE_VER})." + exit 1 + fi + BUILD_MOBILE=true + ;; + backup-v*) + TAG_VER="${REF_NAME#backup-v}" + if [ "$TAG_VER" != "$BACKUP_VER" ]; then + echo "::error::Tag ${REF_NAME} does not match backup/VERSION (${BACKUP_VER})." + exit 1 + fi + BUILD_BACKUP=true + ;; + *) + echo "::error::Unsupported component tag pattern: ${REF_NAME}" + exit 1 + ;; + esac + elif [ "$EVENT_NAME" = "workflow_dispatch" ]; then + BUILD_WEB="$INPUT_WEB" + BUILD_MOBILE="$INPUT_MOBILE" + BUILD_BACKUP="$INPUT_BACKUP" + if [ "$BUILD_WEB" = "true" ]; then + DEPLOY_INFRA=true + fi + else + # push to main + COMMIT_MSG=$(git log -1 --format=%B) + if echo "$COMMIT_MSG" | grep -qiE '\[(skip release|manual-release)\]'; then + echo "â„šī¸ Release skipped due to [skip release] / [manual-release] marker." + else + if [ "$PATH_WEB" = "true" ]; then + if git rev-parse -q --verify "refs/tags/web-v${WEB_VER}" >/dev/null 2>&1; then + echo "â„šī¸ Tag web-v${WEB_VER} already exists; skipping auto-release for Web." + else + BUILD_WEB=true + fi + fi + + if [ "$PATH_MOBILE" = "true" ]; then + if git rev-parse -q --verify "refs/tags/mobile-v${MOBILE_VER}" >/dev/null 2>&1; then + echo "â„šī¸ Tag mobile-v${MOBILE_VER} already exists; skipping auto-release for Mobile." + else + BUILD_MOBILE=true + fi + fi + + if [ "$PATH_BACKUP" = "true" ]; then + if git rev-parse -q --verify "refs/tags/backup-v${BACKUP_VER}" >/dev/null 2>&1; then + echo "â„šī¸ Tag backup-v${BACKUP_VER} already exists; skipping auto-release for Backup." + else + BUILD_BACKUP=true + fi + fi + fi + + if [ "$PATH_INFRA" = "true" ] || [ "$BUILD_WEB" = "true" ]; then + DEPLOY_INFRA=true + fi + fi + + echo "Release plan: build_web=${BUILD_WEB}, build_mobile=${BUILD_MOBILE}, build_backup=${BUILD_BACKUP}, deploy_infra=${DEPLOY_INFRA}" + echo "build_web=${BUILD_WEB}" >> "$GITHUB_OUTPUT" + echo "build_mobile=${BUILD_MOBILE}" >> "$GITHUB_OUTPUT" + echo "build_backup=${BUILD_BACKUP}" >> "$GITHUB_OUTPUT" + echo "deploy_infra=${DEPLOY_INFRA}" >> "$GITHUB_OUTPUT" + # ──────────────────────────────────────────────────────────────────────────── # Job 1: Build Web Next.js Docker Image # ──────────────────────────────────────────────────────────────────────────── build-web: name: Build Web Docker Image needs: guard + if: needs.guard.outputs.build_web == 'true' runs-on: ubuntu-latest permissions: contents: read @@ -56,6 +277,7 @@ jobs: env: INFISICAL_CLIENT_ID: ${{ secrets.INFISICAL_CLIENT_ID }} INFISICAL_CLIENT_SECRET: ${{ secrets.INFISICAL_CLIENT_SECRET }} + WEB_VERSION: ${{ needs.guard.outputs.web_version }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 @@ -79,13 +301,7 @@ jobs: INFISICAL_ENV_SLUG: "prod" INFISICAL_SECRET_PATH: "/build-time" run: node scripts/fetch-build-time-vars.js - continue-on-error: true # Gracefully fallback to GitHub native sync variables if action credentials aren't populated yet - - - name: Synchronize workspace versions - env: - TARGET_VERSION: ${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION }} - run: | - node scripts/sync-version.js "${TARGET_VERSION}" + continue-on-error: true - name: Prepare derived values id: prep @@ -99,72 +315,48 @@ jobs: BUILD_ARM64: ${{ github.event.inputs.build_arm64 }} HEAD_COMMIT_TIMESTAMP: ${{ github.event.head_commit.timestamp }} run: | - # Set APP_DOMAIN with validation; avoid silent localhost fallback for real releases APP_DOMAIN="${NEXT_PUBLIC_APP_DOMAIN:-}" if [ -z "$APP_DOMAIN" ] || [ "$APP_DOMAIN" = "null" ]; then - # For non-push events, allow localhost fallback only with explicit opt-in if [ "${ALLOW_APP_DOMAIN_LOCALHOST_FALLBACK:-}" != "true" ]; then - echo "::warning::NEXT_PUBLIC_APP_DOMAIN (repo variable) is not configured. Falling back to APP_DOMAIN=localhost." - echo "::warning::To explicitly allow this fallback without warnings, set vars.ALLOW_APP_DOMAIN_LOCALHOST_FALLBACK=true." + echo "::warning::NEXT_PUBLIC_APP_DOMAIN is not configured. Falling back to APP_DOMAIN=localhost." fi APP_DOMAIN="localhost" fi echo "APP_DOMAIN=${APP_DOMAIN}" >> $GITHUB_ENV - # Derive BACKEND_URL if not set BACKEND_URL="${NEXT_PUBLIC_BACKEND_URL:-}" if [ -z "$BACKEND_URL" ] || [ "$BACKEND_URL" = "null" ]; then - if [ "$APP_DOMAIN" = "localhost" ]; then - BACKEND_URL="http://localhost:3000" - else - BACKEND_URL="https://${APP_DOMAIN}" - fi + if [ "$APP_DOMAIN" = "localhost" ]; then + BACKEND_URL="http://localhost:3000" + else + BACKEND_URL="https://${APP_DOMAIN}" + fi fi echo "BACKEND_URL=${BACKEND_URL}" >> $GITHUB_ENV + IMAGE_NAME=$(echo "$REPO" | cut -d'/' -f2 | tr '[:upper:]' '[:lower:]') echo "image_name=${IMAGE_NAME}" >> $GITHUB_OUTPUT - # Debug: Show what will be used - echo "đŸŗ Image name: ${IMAGE_NAME}" - echo " Full path: ghcr.io/${REPO_OWNER}/${IMAGE_NAME}" - - # Determine build platforms - # Default to amd64 for faster, more reliable release builds. - # ARM64 remains available as an explicit manual opt-in. - if [ "${EVENT_NAME}" == "push" ]; then - PLATFORMS="linux/amd64" - echo "đŸ“Ļ Main push detected - building amd64 only" - elif [ "${EVENT_NAME}" == "workflow_dispatch" ]; then - if [ "${BUILD_ARM64}" == "true" ]; then - PLATFORMS="linux/amd64,linux/arm64" - echo "đŸ“Ļ Manual dispatch with ARM64 enabled" - else - PLATFORMS="linux/amd64" - echo "đŸ“Ļ Manual dispatch - AMD64 only (faster build)" - fi + if [ "${EVENT_NAME}" == "workflow_dispatch" ] && [ "${BUILD_ARM64}" == "true" ]; then + PLATFORMS="linux/amd64,linux/arm64" else - # Default fallback PLATFORMS="linux/amd64" fi echo "platforms=${PLATFORMS}" >> $GITHUB_OUTPUT - echo " Build platforms: ${PLATFORMS}" echo "app_url=https://${APP_DOMAIN}" >> $GITHUB_OUTPUT echo "sitemap_url=https://${APP_DOMAIN}/sitemap.xml" >> $GITHUB_OUTPUT echo "app_email=@${APP_DOMAIN}" >> $GITHUB_OUTPUT echo "legal_email=legal@${APP_DOMAIN}" >> $GITHUB_OUTPUT - # Use a consistent timestamp for reproducibility + TIMESTAMP="${HEAD_COMMIT_TIMESTAMP:-}" if [ -z "$TIMESTAMP" ] || [ "$TIMESTAMP" == "null" ]; then TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ') fi echo "created=$TIMESTAMP" >> $GITHUB_OUTPUT - # SOURCE_DATE_EPOCH: use the Unix timestamp of the checked-out commit. - # This makes Docker layer timestamps deterministic per commit. SOURCE_DATE_EPOCH=$(git log -1 --format=%ct) echo "source_date_epoch=${SOURCE_DATE_EPOCH}" >> $GITHUB_OUTPUT - echo "🕒 SOURCE_DATE_EPOCH: ${SOURCE_DATE_EPOCH}" - name: Build & push Docker image id: build-push @@ -176,16 +368,16 @@ jobs: push: true tags: | ghcr.io/${{ github.repository_owner }}/${{ steps.prep.outputs.image_name }}:${{ github.sha }} - ghcr.io/${{ github.repository_owner }}/${{ steps.prep.outputs.image_name }}:${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION || 'latest' }} + ghcr.io/${{ github.repository_owner }}/${{ steps.prep.outputs.image_name }}:${{ env.WEB_VERSION }} ghcr.io/${{ github.repository_owner }}/${{ steps.prep.outputs.image_name }}:latest secrets: | sentry_token=${{ env.SENTRY_AUTH_TOKEN || secrets.SENTRY_AUTH_TOKEN }} platforms: ${{ steps.prep.outputs.platforms }} - # Enable layer caching for faster builds cache-from: type=gha cache-to: type=gha,mode=max build-args: | APP_COMMIT_SHA=${{ github.sha }} + APP_VERSION=${{ env.WEB_VERSION }} SOURCE_DATE_EPOCH=${{ steps.prep.outputs.source_date_epoch }} NEXT_PUBLIC_BACKEND_URL=${{ env.NEXT_PUBLIC_BACKEND_URL || vars.NEXT_PUBLIC_BACKEND_URL }} NEXT_PUBLIC_SUPABASE_URL=${{ env.NEXT_PUBLIC_SUPABASE_URL || vars.NEXT_PUBLIC_SUPABASE_URL }} @@ -200,9 +392,6 @@ jobs: NEXT_PUBLIC_ANDROID_SHA256_FINGERPRINTS=${{ env.NEXT_PUBLIC_ANDROID_SHA256_FINGERPRINTS || vars.NEXT_PUBLIC_ANDROID_SHA256_FINGERPRINTS }} SENTRY_ORG=${{ env.SENTRY_ORG || vars.SENTRY_ORG }} SENTRY_PROJECT=${{ env.SENTRY_PROJECT || vars.SENTRY_PROJECT }} - NEXT_PUBLIC_APP_NAME=${{ env.NEXT_PUBLIC_APP_NAME || vars.NEXT_PUBLIC_APP_NAME }} - NEXT_PUBLIC_APP_VERSION=${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION || 'latest' }} - MIN_APP_VERSION=${{ env.MIN_APP_VERSION || vars.MIN_APP_VERSION || 'latest' }} NEXT_PUBLIC_APP_DOMAIN=${{ env.NEXT_PUBLIC_APP_DOMAIN || vars.NEXT_PUBLIC_APP_DOMAIN }} NEXT_PUBLIC_AUTHOR_NAME=${{ env.NEXT_PUBLIC_AUTHOR_NAME || vars.NEXT_PUBLIC_AUTHOR_NAME }} NEXT_PUBLIC_AUTHOR_URL=${{ env.NEXT_PUBLIC_AUTHOR_URL || vars.NEXT_PUBLIC_AUTHOR_URL }} @@ -225,9 +414,8 @@ jobs: org.opencontainers.image.revision=${{ github.sha }} org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} org.opencontainers.image.created=${{ steps.prep.outputs.created }} - org.opencontainers.image.version=${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION || 'latest' }} + org.opencontainers.image.version=${{ env.WEB_VERSION }} - # Attest build provenance for web image - name: Attest Build Provenance (Web Image) uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 with: @@ -235,58 +423,36 @@ jobs: subject-digest: ${{ steps.build-push.outputs.digest }} push-to-registry: true - # Download SLSA provenance attestation for OpenSSF Scorecard - name: Download SLSA provenance attestation env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -euo pipefail - echo "=== Downloading SLSA Provenance Attestation ===" - - # Retry logic: attestation may take a moment to be available MAX_ATTEMPTS=5 ATTEMPT=1 SLEEP_TIME=10 while [ $ATTEMPT -le $MAX_ATTEMPTS ]; do echo "Attempt $ATTEMPT of $MAX_ATTEMPTS..." - if gh attestation download \ oci://ghcr.io/${{ github.repository_owner }}/${{ steps.prep.outputs.image_name }}@${{ steps.build-push.outputs.digest }} \ --owner ${{ github.repository_owner }}; then shopt -s nullglob digest_files=(sha256*.jsonl) if [ ${#digest_files[@]} -gt 0 ]; then - DIGEST_FILE="${digest_files[0]}" - else - DIGEST_FILE="" - fi - if [ -n "$DIGEST_FILE" ]; then - mv "$DIGEST_FILE" provenance.intoto.jsonl - echo "✓ SLSA provenance attestation downloaded successfully" - ls -lh provenance.intoto.jsonl + mv "${digest_files[0]}" provenance.intoto.jsonl + echo "✓ SLSA provenance attestation downloaded" exit 0 - else - echo "⚠ Could not find downloaded attestation file" - echo "Current directory contents:" - ls -la - echo "Waiting ${SLEEP_TIME}s before retry..." - sleep $SLEEP_TIME - ATTEMPT=$((ATTEMPT + 1)) - continue fi - else - echo "⚠ Download failed, waiting ${SLEEP_TIME}s before retry..." - sleep $SLEEP_TIME - ATTEMPT=$((ATTEMPT + 1)) fi + sleep $SLEEP_TIME + ATTEMPT=$((ATTEMPT + 1)) done echo "❌ Failed to download attestation after $MAX_ATTEMPTS attempts" exit 1 - # Generate SBOM for Web Image - name: Generate SBOM (Web Image) uses: anchore/sbom-action@66cbf4bc1f1c0d2edc94016e65bc221b6bb0ad6c with: @@ -294,7 +460,6 @@ jobs: format: cyclonedx-json output-file: sbom.json - # Attest SBOM for Web Image - name: Attest SBOM (Web Image) uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 with: @@ -304,7 +469,6 @@ jobs: predicate-path: sbom.json push-to-registry: true - # Sign web image with cosign (keyless signing using OIDC) - name: Install cosign uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 @@ -322,21 +486,12 @@ jobs: IMAGE_URI: ghcr.io/${{ github.repository_owner }}/${{ steps.prep.outputs.image_name }}@${{ steps.build-push.outputs.digest }} run: | set -euo pipefail - - echo "=== Cosign Web Image Signing ===" - VERSION="${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION || 'latest' }}" - echo "Signing Web Image: ${IMAGE_URI}" timeout 300 cosign sign \ -a "repo=${{ github.repository }}" \ -a "workflow=${{ github.workflow }}" \ -a "ref=${{ github.ref }}" \ - -a "version=${VERSION}" \ - "${IMAGE_URI}" || { - echo "ERROR: Cosign web image signing failed or timed out" - exit 1 - } - - echo "✓ Web container image signed successfully" + -a "version=${WEB_VERSION}" \ + "${IMAGE_URI}" cosign triangulate "${IMAGE_URI}" - name: Verify web image signature @@ -344,49 +499,35 @@ jobs: IMAGE_URI: ghcr.io/${{ github.repository_owner }}/${{ steps.prep.outputs.image_name }}@${{ steps.build-push.outputs.digest }} run: | set -euo pipefail - - echo "Verifying web image signature..." cosign verify \ --certificate-identity-regexp="^https://github.com/${{ github.repository }}/.github/workflows/" \ --certificate-oidc-issuer="https://token.actions.githubusercontent.com" \ "${IMAGE_URI}" - echo "✓ Web container image signature verified" - - # Sign Web SBOM file - name: Sign Web SBOM artifact run: | set -euo pipefail - - echo "=== Signing Web SBOM ===" timeout 60 cosign sign-blob --yes \ --bundle sbom.json.bundle \ - sbom.json || { - echo "ERROR: Web SBOM signing failed or timed out" - exit 1 - } - - echo "✓ Web SBOM signed successfully" + sbom.json - # Generate SHA256 checksums (after all web artifacts are created) - name: Generate web checksums run: | - echo "# Web Release Artifact Checksums" > web-checksums.txt - echo "" >> web-checksums.txt - echo "## Web SBOM" >> web-checksums.txt - sha256sum sbom.json >> web-checksums.txt - echo "" >> web-checksums.txt - echo "## Web Signature Bundle" >> web-checksums.txt - sha256sum sbom.json.bundle >> web-checksums.txt - echo "" >> web-checksums.txt - echo "## SLSA Provenance Attestation" >> web-checksums.txt - sha256sum provenance.intoto.jsonl >> web-checksums.txt - echo "" >> web-checksums.txt - echo "Generated at: $(date -u +'%Y-%m-%d %H:%M:%S UTC')" >> web-checksums.txt - echo "" >> web-checksums.txt - cat web-checksums.txt - - # Upload artifacts for the release job + { + echo "# Web Release Artifact Checksums" + echo "" + echo "## Web SBOM" + sha256sum sbom.json + echo "" + echo "## Web Signature Bundle" + sha256sum sbom.json.bundle + echo "" + echo "## SLSA Provenance Attestation" + sha256sum provenance.intoto.jsonl + echo "" + echo "Generated at: $(date -u +'%Y-%m-%d %H:%M:%S UTC')" + } > web-checksums.txt + - name: Upload web release artifacts uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 with: @@ -403,6 +544,7 @@ jobs: build-backup: name: Build Backup Runner Docker Image needs: guard + if: needs.guard.outputs.build_backup == 'true' runs-on: ubuntu-latest permissions: contents: read @@ -411,9 +553,9 @@ jobs: attestations: write outputs: backup_image_digest: ${{ steps.build-push-backup.outputs.digest }} + platforms: ${{ steps.prep.outputs.platforms }} env: - INFISICAL_CLIENT_ID: ${{ secrets.INFISICAL_CLIENT_ID }} - INFISICAL_CLIENT_SECRET: ${{ secrets.INFISICAL_CLIENT_SECRET }} + BACKUP_VERSION: ${{ needs.guard.outputs.backup_version }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 @@ -428,23 +570,6 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - name: Fetch build-time variables from Infisical (Unmasked) - if: env.INFISICAL_CLIENT_ID != '' && env.INFISICAL_CLIENT_SECRET != '' - env: - INFISICAL_CLIENT_ID: ${{ secrets.INFISICAL_CLIENT_ID }} - INFISICAL_CLIENT_SECRET: ${{ secrets.INFISICAL_CLIENT_SECRET }} - INFISICAL_PROJECT_SLUG: ${{ secrets.INFISICAL_PROJECT_SLUG || secrets.INFISICAL_PROJECT_ID }} - INFISICAL_ENV_SLUG: "prod" - INFISICAL_SECRET_PATH: "/build-time" - run: node scripts/fetch-build-time-vars.js - continue-on-error: true - - - name: Synchronize workspace versions - env: - TARGET_VERSION: ${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION }} - run: | - node scripts/sync-version.js "${TARGET_VERSION}" - - name: Prepare derived values id: prep env: @@ -452,14 +577,8 @@ jobs: BUILD_ARM64: ${{ github.event.inputs.build_arm64 }} HEAD_COMMIT_TIMESTAMP: ${{ github.event.head_commit.timestamp }} run: | - if [ "${EVENT_NAME}" == "push" ]; then - PLATFORMS="linux/amd64" - elif [ "${EVENT_NAME}" == "workflow_dispatch" ]; then - if [ "${BUILD_ARM64}" == "true" ]; then - PLATFORMS="linux/amd64,linux/arm64" - else - PLATFORMS="linux/amd64" - fi + if [ "${EVENT_NAME}" == "workflow_dispatch" ] && [ "${BUILD_ARM64}" == "true" ]; then + PLATFORMS="linux/amd64,linux/arm64" else PLATFORMS="linux/amd64" fi @@ -482,7 +601,7 @@ jobs: push: true tags: | ghcr.io/${{ github.repository_owner }}/ghostclass-backup:${{ github.sha }} - ghcr.io/${{ github.repository_owner }}/ghostclass-backup:${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION || 'latest' }} + ghcr.io/${{ github.repository_owner }}/ghostclass-backup:${{ env.BACKUP_VERSION }} ghcr.io/${{ github.repository_owner }}/ghostclass-backup:latest platforms: ${{ steps.prep.outputs.platforms }} cache-from: type=gha @@ -493,9 +612,8 @@ jobs: org.opencontainers.image.revision=${{ github.sha }} org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} org.opencontainers.image.created=${{ steps.prep.outputs.created }} - org.opencontainers.image.version=${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION || 'latest' }} + org.opencontainers.image.version=${{ env.BACKUP_VERSION }} - # Attest build provenance for backup image - name: Attest Build Provenance (Backup Runner Image) uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 with: @@ -503,7 +621,6 @@ jobs: subject-digest: ${{ steps.build-push-backup.outputs.digest }} push-to-registry: true - # Generate SBOM for Backup Runner Image - name: Generate SBOM (Backup Runner Image) uses: anchore/sbom-action@66cbf4bc1f1c0d2edc94016e65bc221b6bb0ad6c with: @@ -511,7 +628,6 @@ jobs: format: cyclonedx-json output-file: ghostclass-backup-runner-sbom.json - # Attest SBOM for Backup Runner Image - name: Attest SBOM (Backup Runner Image) uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 with: @@ -521,7 +637,6 @@ jobs: predicate-path: ghostclass-backup-runner-sbom.json push-to-registry: true - # Sign backup image with cosign (keyless signing using OIDC) - name: Install cosign uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 @@ -539,21 +654,12 @@ jobs: BACKUP_IMAGE_URI: ghcr.io/${{ github.repository_owner }}/ghostclass-backup@${{ steps.build-push-backup.outputs.digest }} run: | set -euo pipefail - - echo "=== Cosign Backup Runner Image Signing ===" - VERSION="${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION || 'latest' }}" - echo "Signing Backup Runner Image: ${BACKUP_IMAGE_URI}" timeout 300 cosign sign \ -a "repo=${{ github.repository }}" \ -a "workflow=${{ github.workflow }}" \ -a "ref=${{ github.ref }}" \ - -a "version=${VERSION}" \ - "${BACKUP_IMAGE_URI}" || { - echo "ERROR: Cosign backup runner image signing failed or timed out" - exit 1 - } - - echo "✓ Backup runner container image signed successfully" + -a "version=${BACKUP_VERSION}" \ + "${BACKUP_IMAGE_URI}" cosign triangulate "${BACKUP_IMAGE_URI}" - name: Verify backup runner image signature @@ -561,46 +667,32 @@ jobs: BACKUP_IMAGE_URI: ghcr.io/${{ github.repository_owner }}/ghostclass-backup@${{ steps.build-push-backup.outputs.digest }} run: | set -euo pipefail - - echo "Verifying backup runner image signature..." cosign verify \ --certificate-identity-regexp="^https://github.com/${{ github.repository }}/.github/workflows/" \ --certificate-oidc-issuer="https://token.actions.githubusercontent.com" \ "${BACKUP_IMAGE_URI}" - echo "✓ Backup runner container image signature verified" - - # Sign Backup SBOM file - name: Sign Backup Runner SBOM artifact run: | set -euo pipefail - - echo "=== Signing Backup Runner SBOM ===" timeout 60 cosign sign-blob --yes \ --bundle ghostclass-backup-runner-sbom.json.bundle \ - ghostclass-backup-runner-sbom.json || { - echo "ERROR: Backup Runner SBOM signing failed or timed out" - exit 1 - } - - echo "✓ Backup Runner SBOM signed successfully" + ghostclass-backup-runner-sbom.json - # Generate SHA256 checksums (after all backup artifacts are created) - name: Generate backup runner checksums run: | - echo "# Backup Runner Release Artifact Checksums" > ghostclass-backup-runner-checksums.txt - echo "" >> ghostclass-backup-runner-checksums.txt - echo "## Backup Runner SBOM" >> ghostclass-backup-runner-checksums.txt - sha256sum ghostclass-backup-runner-sbom.json >> ghostclass-backup-runner-checksums.txt - echo "" >> ghostclass-backup-runner-checksums.txt - echo "## Backup Runner Signature Bundle" >> ghostclass-backup-runner-checksums.txt - sha256sum ghostclass-backup-runner-sbom.json.bundle >> ghostclass-backup-runner-checksums.txt - echo "" >> ghostclass-backup-runner-checksums.txt - echo "Generated at: $(date -u +'%Y-%m-%d %H:%M:%S UTC')" >> ghostclass-backup-runner-checksums.txt - echo "" >> ghostclass-backup-runner-checksums.txt - cat ghostclass-backup-runner-checksums.txt - - # Upload artifacts for the release job + { + echo "# Backup Runner Release Artifact Checksums" + echo "" + echo "## Backup Runner SBOM" + sha256sum ghostclass-backup-runner-sbom.json + echo "" + echo "## Backup Runner Signature Bundle" + sha256sum ghostclass-backup-runner-sbom.json.bundle + echo "" + echo "Generated at: $(date -u +'%Y-%m-%d %H:%M:%S UTC')" + } > ghostclass-backup-runner-checksums.txt + - name: Upload backup runner release artifacts uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 with: @@ -610,9 +702,13 @@ jobs: ghostclass-backup-runner-sbom.json.bundle ghostclass-backup-runner-checksums.txt + # ──────────────────────────────────────────────────────────────────────────── + # Job 3: Build Flutter Android APK & AAB + # ──────────────────────────────────────────────────────────────────────────── build-mobile: name: Build Flutter Android needs: guard + if: needs.guard.outputs.build_mobile == 'true' runs-on: ubuntu-latest permissions: contents: read @@ -621,6 +717,7 @@ jobs: env: INFISICAL_CLIENT_ID: ${{ secrets.INFISICAL_CLIENT_ID }} INFISICAL_CLIENT_SECRET: ${{ secrets.INFISICAL_CLIENT_SECRET }} + MOBILE_VERSION: ${{ needs.guard.outputs.mobile_version }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 @@ -652,13 +749,7 @@ jobs: INFISICAL_ENV_SLUG: "prod" INFISICAL_SECRET_PATH: "/build-time" run: node scripts/fetch-build-time-vars.js - continue-on-error: true # Gracefully fallback to GitHub native sync variables if action credentials aren't populated yet - - - name: Synchronize workspace versions - env: - TARGET_VERSION: ${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION }} - run: | - node scripts/sync-version.js "${TARGET_VERSION}" + continue-on-error: true - name: Prepare mobile release paths id: mobile-prep @@ -667,7 +758,7 @@ jobs: mkdir -p mobile/release-assets - echo "build_name=${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION || 'latest' }}" >> "$GITHUB_OUTPUT" + echo "build_name=${MOBILE_VERSION}" >> "$GITHUB_OUTPUT" echo "build_number=${{ github.run_number }}" >> "$GITHUB_OUTPUT" BUILD_TIMESTAMP="${{ github.event.head_commit.timestamp }}" @@ -676,7 +767,6 @@ jobs: fi echo "build_timestamp=${BUILD_TIMESTAMP}" >> "$GITHUB_OUTPUT" - # Derive APP_DOMAIN and BACKEND_URL APP_DOMAIN="${{ env.NEXT_PUBLIC_APP_DOMAIN || vars.NEXT_PUBLIC_APP_DOMAIN }}" if [ -z "$APP_DOMAIN" ] || [ "$APP_DOMAIN" = "null" ]; then APP_DOMAIN="localhost" @@ -685,11 +775,11 @@ jobs: BACKEND_URL="${{ env.NEXT_PUBLIC_BACKEND_URL || vars.NEXT_PUBLIC_BACKEND_URL }}" if [ -z "$BACKEND_URL" ] || [ "$BACKEND_URL" = "null" ]; then - if [ "$APP_DOMAIN" = "localhost" ]; then - BACKEND_URL="http://localhost:3000" - else - BACKEND_URL="https://${APP_DOMAIN}" - fi + if [ "$APP_DOMAIN" = "localhost" ]; then + BACKEND_URL="http://localhost:3000" + else + BACKEND_URL="https://${APP_DOMAIN}" + fi fi echo "BACKEND_URL=${BACKEND_URL}" >> $GITHUB_ENV @@ -749,13 +839,11 @@ jobs: mkdir -p app printf '%s' "$GOOGLE_SERVICES_JSON_BASE64" | base64 --decode > app/google-services.json - # Derive dynamic API key directly from the decoded file if not set manually if [ -z "${FIREBASE_API_KEY_ANDROID:-}" ]; then DERIVED_KEY=$(jq -r '.client[0].api_key[0].current_key // empty' app/google-services.json) if [ -n "$DERIVED_KEY" ]; then echo "::add-mask::$DERIVED_KEY" echo "FIREBASE_API_KEY_ANDROID=$DERIVED_KEY" >> "$GITHUB_ENV" - echo "✓ Derived FIREBASE_API_KEY_ANDROID directly from google-services.json" fi fi @@ -764,40 +852,27 @@ jobs: if [ -n "$DERIVED_PROJECT_ID" ]; then echo "::add-mask::$DERIVED_PROJECT_ID" echo "FIREBASE_PROJECT_ID=$DERIVED_PROJECT_ID" >> "$GITHUB_ENV" - echo "✓ Derived FIREBASE_PROJECT_ID directly from google-services.json" fi fi if [ -z "${FIREBASE_MESSAGING_SENDER_ID:-}" ]; then DERIVED_SENDER_ID=$(jq -r '.project_info.project_number // empty' app/google-services.json) - if [ -n "$DERIVED_SENDER_ID" ]; then - echo "FIREBASE_MESSAGING_SENDER_ID=$DERIVED_SENDER_ID" >> "$GITHUB_ENV" - echo "✓ Derived FIREBASE_MESSAGING_SENDER_ID directly from google-services.json" - fi + [ -n "$DERIVED_SENDER_ID" ] && echo "FIREBASE_MESSAGING_SENDER_ID=$DERIVED_SENDER_ID" >> "$GITHUB_ENV" fi if [ -z "${FIREBASE_STORAGE_BUCKET:-}" ]; then DERIVED_BUCKET=$(jq -r '.project_info.storage_bucket // empty' app/google-services.json) - if [ -n "$DERIVED_BUCKET" ]; then - echo "FIREBASE_STORAGE_BUCKET=$DERIVED_BUCKET" >> "$GITHUB_ENV" - echo "✓ Derived FIREBASE_STORAGE_BUCKET directly from google-services.json" - fi + [ -n "$DERIVED_BUCKET" ] && echo "FIREBASE_STORAGE_BUCKET=$DERIVED_BUCKET" >> "$GITHUB_ENV" fi if [ -z "${FIREBASE_ANDROID_APP_ID:-}" ]; then DERIVED_APP_ID=$(jq -r '.client[0].client_info.mobilesdk_app_id // empty' app/google-services.json) - if [ -n "$DERIVED_APP_ID" ]; then - echo "FIREBASE_ANDROID_APP_ID=$DERIVED_APP_ID" >> "$GITHUB_ENV" - echo "✓ Derived FIREBASE_ANDROID_APP_ID directly from google-services.json" - fi + [ -n "$DERIVED_APP_ID" ] && echo "FIREBASE_ANDROID_APP_ID=$DERIVED_APP_ID" >> "$GITHUB_ENV" fi if [ -z "${ANDROID_PACKAGE_NAME:-}" ]; then DERIVED_PKG=$(jq -r '.client[0].client_info.android_client_info.package_name // empty' app/google-services.json) - if [ -n "$DERIVED_PKG" ]; then - echo "ANDROID_PACKAGE_NAME=$DERIVED_PKG" >> "$GITHUB_ENV" - echo "✓ Derived ANDROID_PACKAGE_NAME directly from google-services.json" - fi + [ -n "$DERIVED_PKG" ] && echo "ANDROID_PACKAGE_NAME=$DERIVED_PKG" >> "$GITHUB_ENV" fi - name: Generate mobile/lib/config/app_secrets.dart @@ -810,11 +885,9 @@ jobs: run: | set -euo pipefail - # Resolve values from GITHUB_ENV (exported in previous step) APP_DOMAIN="${APP_DOMAIN:-ghostclass.devakesu.com}" BACKEND_URL="${BACKEND_URL:-https://${APP_DOMAIN}}" - # Helper to treat "null" string as empty and apply fallback safe_val() { local val="$1" local fallback="$2" @@ -825,8 +898,6 @@ jobs: fi } - # Encode all sensitive strings to Base64 for uniform obfuscation - # Fallbacks ensure no empty strings or "null" literals are baked in S_PROXY=$(safe_val "$SUPABASE_CF_PROXY_URL_PROD" "$SUPABASE_URL_PROD") ENCODED_SUPABASE_PROXY_URL_PROD=$(echo -n "$S_PROXY" | base64 | tr -d '\n') ENCODED_SUPABASE_ANON_KEY_PROD=$(echo -n "$(safe_val "$SUPABASE_ANON_KEY_PROD" "")" | base64 | tr -d '\n') @@ -842,16 +913,12 @@ jobs: class AppSecrets { AppSecrets._(); - // Forced to false for production release builds static const bool isDev = false; - - // Dev credentials stripped for production security static const String supabaseUrlDev = ''; static const String supabasePublishableKeyDev = ''; static const String supabaseProxyUrlProd = '${ENCODED_SUPABASE_PROXY_URL_PROD}'; static const String supabasePublishableKeyProd = '${ENCODED_SUPABASE_ANON_KEY_PROD}'; - static const String sentryDsn = '${ENCODED_SENTRY_DSN}'; static const String ghostclassApiUrlDev = ''; @@ -869,7 +936,6 @@ jobs: BUILD_TIMESTAMP: ${{ steps.mobile-prep.outputs.build_timestamp }} SENTRY_AUTH_TOKEN: ${{ env.MOBILE_SENTRY_AUTH_TOKEN || secrets.MOBILE_SENTRY_AUTH_TOKEN || env.SENTRY_AUTH_TOKEN || secrets.SENTRY_AUTH_TOKEN }} APP_DOMAIN: ${{ env.APP_DOMAIN }} - APP_NAME: ${{ env.APP_NAME || env.NEXT_PUBLIC_APP_NAME || vars.APP_NAME || vars.NEXT_PUBLIC_APP_NAME }} AUTHOR_NAME: ${{ env.AUTHOR_NAME || env.NEXT_PUBLIC_AUTHOR_NAME || vars.AUTHOR_NAME || vars.NEXT_PUBLIC_AUTHOR_NAME }} AUTHOR_URL: ${{ env.AUTHOR_URL || env.NEXT_PUBLIC_AUTHOR_URL || vars.AUTHOR_URL || vars.NEXT_PUBLIC_AUTHOR_URL }} GITHUB_URL: ${{ env.GITHUB_URL || env.NEXT_PUBLIC_GITHUB_URL || vars.GITHUB_URL || vars.NEXT_PUBLIC_GITHUB_URL }} @@ -891,13 +957,13 @@ jobs: --extra-gen-snapshot-options=--save-obfuscation-map=build/app/obfuscation.map.json \ --build-name="${{ steps.mobile-prep.outputs.build_name }}" \ --build-number="${{ steps.mobile-prep.outputs.build_number }}" \ + --dart-define=APP_NAME="GhostClass" \ --dart-define=APP_VERSION="${{ steps.mobile-prep.outputs.build_name }}" \ --dart-define=APP_COMMIT_SHA=${{ github.sha }} \ --dart-define=BUILD_TIMESTAMP=${BUILD_TIMESTAMP} \ --dart-define=GITHUB_RUN_ID=${{ github.run_id }} \ --dart-define=GITHUB_RUN_NUMBER=${{ github.run_number }} \ --dart-define=APP_DOMAIN="${APP_DOMAIN}" \ - --dart-define=APP_NAME="${APP_NAME:-}" \ --dart-define=AUTHOR_NAME="${AUTHOR_NAME:-}" \ --dart-define=AUTHOR_URL="${AUTHOR_URL:-}" \ --dart-define=GITHUB_URL="${GITHUB_URL:-}" \ @@ -916,7 +982,6 @@ jobs: env: BUILD_TIMESTAMP: ${{ steps.mobile-prep.outputs.build_timestamp }} APP_DOMAIN: ${{ env.APP_DOMAIN }} - APP_NAME: ${{ env.APP_NAME || env.NEXT_PUBLIC_APP_NAME || vars.APP_NAME || vars.NEXT_PUBLIC_APP_NAME }} AUTHOR_NAME: ${{ env.AUTHOR_NAME || env.NEXT_PUBLIC_AUTHOR_NAME || vars.AUTHOR_NAME || vars.NEXT_PUBLIC_AUTHOR_NAME }} AUTHOR_URL: ${{ env.AUTHOR_URL || env.NEXT_PUBLIC_AUTHOR_URL || vars.AUTHOR_URL || vars.NEXT_PUBLIC_AUTHOR_URL }} GITHUB_URL: ${{ env.GITHUB_URL || env.NEXT_PUBLIC_GITHUB_URL || vars.GITHUB_URL || vars.NEXT_PUBLIC_GITHUB_URL }} @@ -938,13 +1003,13 @@ jobs: --extra-gen-snapshot-options=--save-obfuscation-map=build/app/obfuscation.map.json \ --build-name="${{ steps.mobile-prep.outputs.build_name }}" \ --build-number="${{ steps.mobile-prep.outputs.build_number }}" \ + --dart-define=APP_NAME="GhostClass" \ --dart-define=APP_VERSION="${{ steps.mobile-prep.outputs.build_name }}" \ --dart-define=APP_COMMIT_SHA=${{ github.sha }} \ --dart-define=BUILD_TIMESTAMP=${BUILD_TIMESTAMP} \ --dart-define=GITHUB_RUN_ID=${{ github.run_id }} \ --dart-define=GITHUB_RUN_NUMBER=${{ github.run_number }} \ --dart-define=APP_DOMAIN="${APP_DOMAIN}" \ - --dart-define=APP_NAME="${APP_NAME:-}" \ --dart-define=AUTHOR_NAME="${AUTHOR_NAME:-}" \ --dart-define=AUTHOR_URL="${AUTHOR_URL:-}" \ --dart-define=GITHUB_URL="${GITHUB_URL:-}" \ @@ -961,7 +1026,6 @@ jobs: run: | set -euo pipefail - # Unset credential-like variables to prevent environment audit exposure warnings during SBOM generation unset ACTIONS_ID_TOKEN_REQUEST_TOKEN \ INFISICAL_CLIENT_SECRET \ MOBILE_SENTRY_AUTH_TOKEN \ @@ -1036,8 +1100,6 @@ jobs: if [ -f build/app/outputs/mapping/release/mapping.txt ]; then cp build/app/outputs/mapping/release/mapping.txt play-console-assets/mapping.txt - else - echo "mapping.txt not found, skipping" fi cd play-console-assets @@ -1067,347 +1129,321 @@ jobs: [ -n "$AWS_ACCESS_KEY_ID" ] && echo "::add-mask::$AWS_ACCESS_KEY_ID" if [ -z "${AWS_S3_PRIVATE_BUCKET:-}" ]; then - echo "::warning::AWS_S3_PRIVATE_BUCKET is not configured. Internal artifacts (.aab, mapping.txt) will not be archived to cloud storage." - echo "::warning::To enable secure private storage, populate the AWS_S3_PRIVATE_BUCKET secret." + echo "::warning::AWS_S3_PRIVATE_BUCKET is not configured. Skipping private S3 archival." exit 0 fi - echo "Uploading private internal release assets to s3://${AWS_S3_PRIVATE_BUCKET}/releases/v${BUILD_NAME}/" - - aws s3 cp . "s3://${AWS_S3_PRIVATE_BUCKET}/releases/v${BUILD_NAME}/" --recursive - + aws s3 cp . "s3://${AWS_S3_PRIVATE_BUCKET}/releases/mobile-v${BUILD_NAME}/" --recursive echo "✓ Internal artifacts securely archived to private S3 bucket" - # Create GitHub Release with artifacts - create-github-release: - name: Create GitHub Release - needs: [build-web, build-backup, build-mobile] + # ──────────────────────────────────────────────────────────────────────────── + # Job 4A: GitHub Release — Web (web-vX.Y.Z) + # ──────────────────────────────────────────────────────────────────────────── + release-web: + name: Release Web + needs: [guard, build-web] + if: needs.build-web.result == 'success' runs-on: ubuntu-latest permissions: contents: write actions: read - env: - INFISICAL_CLIENT_ID: ${{ secrets.INFISICAL_CLIENT_ID }} - INFISICAL_CLIENT_SECRET: ${{ secrets.INFISICAL_CLIENT_SECRET }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 with: fetch-depth: 0 - - name: Fetch build-time variables from Infisical (Unmasked) - if: env.INFISICAL_CLIENT_ID != '' && env.INFISICAL_CLIENT_SECRET != '' - env: - INFISICAL_CLIENT_ID: ${{ secrets.INFISICAL_CLIENT_ID }} - INFISICAL_CLIENT_SECRET: ${{ secrets.INFISICAL_CLIENT_SECRET }} - INFISICAL_PROJECT_SLUG: ${{ secrets.INFISICAL_PROJECT_SLUG || secrets.INFISICAL_PROJECT_ID }} - INFISICAL_ENV_SLUG: "prod" - INFISICAL_SECRET_PATH: "/build-time" - run: node scripts/fetch-build-time-vars.js - continue-on-error: true - - - name: Determine release version - id: version - env: - APP_VERSION: ${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION || 'latest' }} - run: | - VERSION="${APP_VERSION}" - if [[ "${VERSION}" != v* ]]; then - VERSION_TAG="v${VERSION}" - else - VERSION_TAG="${VERSION}" - VERSION="${VERSION#v}" - fi - echo "version=${VERSION}" >> "$GITHUB_OUTPUT" - echo "version_tag=${VERSION_TAG}" >> "$GITHUB_OUTPUT" - echo "Targeting release tag: ${VERSION_TAG}" - - name: Download web artifacts uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c with: name: web-release-artifacts path: ./artifacts/web - - name: Download backup runner artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c - with: - name: ghostclass-backup-runner-release-artifacts - path: ./artifacts/backup - - - name: Download mobile APK artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c - with: - name: ghostclass-android-apk-v${{ env.NEXT_PUBLIC_APP_VERSION || vars.NEXT_PUBLIC_APP_VERSION || 'latest' }} - path: ./artifacts/mobile - - - name: Download mobile security metadata artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c - with: - name: android-release-artifacts - path: ./artifacts/mobile - - - name: Verify downloaded artifacts - run: | - echo "Downloaded artifacts:" - find ./artifacts -maxdepth 2 -type f | sort - echo "" - cat ./artifacts/web/web-checksums.txt ./artifacts/backup/ghostclass-backup-runner-checksums.txt > ./artifacts/checksums.txt - echo "Combined Checksums:" - cat ./artifacts/checksums.txt - echo "" - echo "Mobile Checksums:" - cat ./artifacts/mobile/mobile-checksums.txt - - - name: Calculate previous version for changelog - id: prev_version - env: - VERSION_TAG: ${{ steps.version.outputs.version_tag }} - run: | - # Get the previous semantic version tag (strict pattern matching) - PREV_TAG=$(git tag -l 'v*.*.*' --sort=-version:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | grep -v "^${VERSION_TAG}$" | head -n1 || echo "") - - if [ -z "$PREV_TAG" ]; then - echo "No previous version tag found, using initial commit" - PREV_REF=$(git rev-list --max-parents=0 HEAD) - echo "changelog_text=${PREV_REF}...${VERSION_TAG}" >> "$GITHUB_OUTPUT" - else - echo "Previous tag: ${PREV_TAG}" - echo "changelog_text=${PREV_TAG}...${VERSION_TAG}" >> "$GITHUB_OUTPUT" - fi - - - name: Generate verification instructions + - name: Create Web GitHub Release env: - PLATFORMS: ${{ needs.build-web.outputs.platforms }} - VERSION_TAG: ${{ steps.version.outputs.version_tag }} + VERSION: ${{ needs.guard.outputs.web_version }} DIGEST: ${{ needs.build-web.outputs.image_digest }} - BACKUP_DIGEST: ${{ needs.build-backup.outputs.backup_image_digest }} - VERSION: ${{ steps.version.outputs.version }} + PLATFORMS: ${{ needs.build-web.outputs.platforms }} + IMAGE_NAME: ${{ needs.build-web.outputs.image_name }} REPOSITORY: ${{ github.repository }} REPOSITORY_OWNER: ${{ github.repository_owner }} + SERVER_URL: ${{ github.server_url }} COMMIT_SHA: ${{ github.sha }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - # Derive image name from repository name - IMAGE_NAME=$(echo "${{ github.repository }}" | cut -d'/' -f2 | tr '[:upper:]' '[:lower:]') - - # Convert platforms to readable format + set -euo pipefail + VERSION_TAG="web-v${VERSION}" PLATFORM_LIST=$(echo "${PLATFORMS}" | sed 's/linux\///g; s/,/, /g') - cat > ./artifacts/VERIFY.md << EOF - # Release Verification Instructions - - This release includes signed web and mobile artifacts with attestations for supply chain security. - - ## Verify Docker Image Signature + PREV_TAG=$(git tag -l 'web-v*.*.*' --sort=-version:refname | grep -E '^web-v[0-9]+\.[0-9]+\.[0-9]+$' | grep -v "^${VERSION_TAG}$" | head -n1 || echo "") + if [ -z "$PREV_TAG" ]; then + PREV_TAG=$(git tag -l 'v*.*.*' --sort=-version:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -n1 || echo "") + fi + if [ -z "$PREV_TAG" ]; then + PREV_REF=$(git rev-list --max-parents=0 HEAD) + CHANGELOG_TEXT="${PREV_REF}...${VERSION_TAG}" + else + CHANGELOG_TEXT="${PREV_TAG}...${VERSION_TAG}" + fi - Using cosign with immutable digest (Recommended): + cat > ./artifacts/web/VERIFY.md << EOF + # Web Release Verification Instructions (${VERSION_TAG}) \`\`\`bash - # Web Image cosign verify \\ - --certificate-identity-regexp="^https://github.com/${REPOSITORY}" \\ + --certificate-identity-regexp="^https://github.com/${REPOSITORY}/\\.github/workflows/" \\ --certificate-oidc-issuer="https://token.actions.githubusercontent.com" \\ ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}@${DIGEST} - # Backup Image - cosign verify \\ - --certificate-identity-regexp="^https://github.com/${REPOSITORY}" \\ - --certificate-oidc-issuer="https://token.actions.githubusercontent.com" \\ - ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}-backup@${BACKUP_DIGEST} + gh attestation verify oci://ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}@${DIGEST} --owner ${REPOSITORY_OWNER} + cosign verify-blob --bundle sbom.json.bundle sbom.json + grep -E '^[0-9a-f]{64} ' web-checksums.txt | sha256sum -c \`\`\` + EOF + sed -i 's/^ //' ./artifacts/web/VERIFY.md - Using cosign by immutable commit hash or version tag: + cat > ./artifacts/web/RELEASE_NOTES.md << EOF + ## Web Release ${VERSION_TAG} - \`\`\`bash - cosign verify \\ - --certificate-identity-regexp="^https://github.com/${REPOSITORY}" \\ - --certificate-oidc-issuer="https://token.actions.githubusercontent.com" \\ - ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}:${COMMIT_SHA} - \`\`\` - - ## Verify Build Attestation + - đŸŗ Docker image (${PLATFORM_LIST}) + - 🔐 Signed image and SBOM using Sigstore cosign + - 📋 CycloneDX SBOM & ✅ SLSA provenance attestation - Using GitHub CLI with immutable digest (Recommended): + ### Docker Image \`\`\`bash - gh attestation verify oci://ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}@${DIGEST} --owner ${REPOSITORY_OWNER} - gh attestation verify oci://ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}-backup@${BACKUP_DIGEST} --owner ${REPOSITORY_OWNER} + docker pull ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}@${DIGEST} + docker pull ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}:${VERSION} \`\`\` - ## Verify SBOM Signature + **Image Digest**: \`${DIGEST}\` + **Commit SHA**: \`${COMMIT_SHA}\` + **Full Changelog**: ${SERVER_URL}/${REPOSITORY}/compare/${CHANGELOG_TEXT} + EOF + sed -i 's/^ //' ./artifacts/web/RELEASE_NOTES.md - Using cosign: + TAG_ARGS=() + if ! git rev-parse -q --verify "refs/tags/${VERSION_TAG}" >/dev/null 2>&1; then + TAG_ARGS=(--target "${COMMIT_SHA}") + fi - \`\`\`bash - # Web SBOM - cosign verify-blob \\ - --bundle sbom.json.bundle \\ - sbom.json + gh release create "${VERSION_TAG}" \ + "${TAG_ARGS[@]}" \ + --title "Web ${VERSION_TAG}" \ + --latest \ + --notes-file ./artifacts/web/RELEASE_NOTES.md \ + ./artifacts/web/sbom.json \ + ./artifacts/web/sbom.json.bundle \ + ./artifacts/web/web-checksums.txt \ + ./artifacts/web/provenance.intoto.jsonl \ + ./artifacts/web/VERIFY.md \ + --draft=false - # Backup SBOM - cosign verify-blob \\ - --bundle ghostclass-backup-runner-sbom.json.bundle \\ - ghostclass-backup-runner-sbom.json - \`\`\` + # ──────────────────────────────────────────────────────────────────────────── + # Job 4B: GitHub Release — Mobile (mobile-vX.Y.Z) + # ──────────────────────────────────────────────────────────────────────────── + release-mobile: + name: Release Mobile + needs: [guard, build-mobile] + if: needs.build-mobile.result == 'success' + runs-on: ubuntu-latest + permissions: + contents: write + actions: read + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + fetch-depth: 0 - ## Verify Checksums + - name: Download mobile APK artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c + with: + name: ghostclass-android-apk-v${{ needs.guard.outputs.mobile_version }} + path: ./artifacts/mobile - Download the checksums file and verify the artifacts: + - name: Download mobile security metadata artifacts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c + with: + name: android-release-artifacts + path: ./artifacts/mobile - \`\`\`bash - # Verify all artifacts (extract only checksum lines) - grep -E '^[0-9a-f]{64} ' checksums.txt | sha256sum -c + - name: Create Mobile GitHub Release + env: + VERSION: ${{ needs.guard.outputs.mobile_version }} + REPOSITORY: ${{ github.repository }} + REPOSITORY_OWNER: ${{ github.repository_owner }} + SERVER_URL: ${{ github.server_url }} + COMMIT_SHA: ${{ github.sha }} + ANDROID_PACKAGE_NAME: ${{ vars.NEXT_PUBLIC_ANDROID_PACKAGE_NAME || 'com.devakesu.apps.ghostclass' }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + VERSION_TAG="mobile-v${VERSION}" + PLAY_STORE_URL="https://play.google.com/store/apps/details?id=${ANDROID_PACKAGE_NAME}" - # Or verify individual files - sha256sum sbom.json sbom.json.bundle ghostclass-backup-runner-sbom.json ghostclass-backup-runner-sbom.json.bundle - \`\`\` + PREV_TAG=$(git tag -l 'mobile-v*.*.*' --sort=-version:refname | grep -E '^mobile-v[0-9]+\.[0-9]+\.[0-9]+$' | grep -v "^${VERSION_TAG}$" | head -n1 || echo "") + if [ -z "$PREV_TAG" ]; then + PREV_TAG=$(git tag -l 'v*.*.*' --sort=-version:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -n1 || echo "") + fi + if [ -z "$PREV_TAG" ]; then + PREV_REF=$(git rev-list --max-parents=0 HEAD) + CHANGELOG_TEXT="${PREV_REF}...${VERSION_TAG}" + else + CHANGELOG_TEXT="${PREV_TAG}...${VERSION_TAG}" + fi - ## Verify Mobile APK + cat > ./artifacts/mobile/VERIFY.md << EOF + # Mobile Release Verification Instructions (${VERSION_TAG}) \`\`\`bash gh attestation verify ghostclass-android-v${VERSION}.apk --owner ${REPOSITORY_OWNER} grep -E '^[0-9a-f]{64} ' mobile-checksums.txt | sha256sum -c \`\`\` + EOF + sed -i 's/^ //' ./artifacts/mobile/VERIFY.md - ## Image Information - - - **Image (Digest)**: \`ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}@${DIGEST}\` - - **Image (Commit SHA)**: \`ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}:${COMMIT_SHA}\` - - **Backup Image (Digest)**: \`ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}-backup@${BACKUP_DIGEST}\` - - **Platforms**: \`${PLATFORM_LIST}\` - - **Version**: \`${VERSION}\` + cat > ./artifacts/mobile/RELEASE_NOTES.md << EOF + ## Mobile Release ${VERSION_TAG} - ## Additional Version Tags + - 📱 Signed Flutter Android APK with provenance attestation + - 📋 CycloneDX SBOM & SHA256 checksums - This release is also available under mutable semantic tags: - - \`ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}:${VERSION_TAG}\` - - \`ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}:latest\` - - \`ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}-backup:${VERSION_TAG}\` - - \`ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}-backup:latest\` + [![Get it on Google Play](https://img.shields.io/badge/Get%20it%20on-Google%20Play-34A853?style=for-the-badge&logo=googleplay&logoColor=white)](${PLAY_STORE_URL}) - ## Learn More + > We recommend downloading from Google Play. GhostClass enforces Firebase App Check (Play Integrity). - - [Sigstore Cosign Documentation](https://docs.sigstore.dev/cosign/overview/) - - [GitHub Attestations Documentation](https://docs.github.com/en/actions/security-guides/using-artifact-attestations-to-establish-provenance-for-builds) - - [SBOM Overview](https://www.cisa.gov/sbom) + **Commit SHA**: \`${COMMIT_SHA}\` + **Full Changelog**: ${SERVER_URL}/${REPOSITORY}/compare/${CHANGELOG_TEXT} EOF + sed -i 's/^ //' ./artifacts/mobile/RELEASE_NOTES.md + + TAG_ARGS=() + if ! git rev-parse -q --verify "refs/tags/${VERSION_TAG}" >/dev/null 2>&1; then + TAG_ARGS=(--target "${COMMIT_SHA}") + fi + + gh release create "${VERSION_TAG}" \ + "${TAG_ARGS[@]}" \ + --title "Mobile ${VERSION_TAG}" \ + --latest \ + --notes-file ./artifacts/mobile/RELEASE_NOTES.md \ + ./artifacts/mobile/ghostclass-android-v${VERSION}.apk \ + ./artifacts/mobile/mobile-sbom.json \ + ./artifacts/mobile/mobile-checksums.txt \ + ./artifacts/mobile/mobile-provenance.intoto.jsonl \ + ./artifacts/mobile/VERIFY.md \ + --draft=false + + # ──────────────────────────────────────────────────────────────────────────── + # Job 4C: GitHub Release — Backup Runner (backup-vX.Y.Z) + # ──────────────────────────────────────────────────────────────────────────── + release-backup: + name: Release Backup Runner + needs: [guard, build-backup] + if: needs.build-backup.result == 'success' + runs-on: ubuntu-latest + permissions: + contents: write + actions: read + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + fetch-depth: 0 - - name: Create GitHub Release + - name: Download backup runner artifacts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c + with: + name: ghostclass-backup-runner-release-artifacts + path: ./artifacts/backup + + - name: Create Backup GitHub Release env: - DIGEST: ${{ needs.build-web.outputs.image_digest }} + VERSION: ${{ needs.guard.outputs.backup_version }} BACKUP_DIGEST: ${{ needs.build-backup.outputs.backup_image_digest }} - VERSION_TAG: ${{ steps.version.outputs.version_tag }} - VERSION_RAW: ${{ steps.version.outputs.version }} + PLATFORMS: ${{ needs.build-backup.outputs.platforms }} REPOSITORY: ${{ github.repository }} REPOSITORY_OWNER: ${{ github.repository_owner }} SERVER_URL: ${{ github.server_url }} - CHANGELOG_TEXT: ${{ steps.prev_version.outputs.changelog_text }} - PLATFORMS: ${{ needs.build-web.outputs.platforms }} - ANDROID_PACKAGE_NAME: ${{ env.NEXT_PUBLIC_ANDROID_PACKAGE_NAME || vars.NEXT_PUBLIC_ANDROID_PACKAGE_NAME || 'com.devakesu.apps.ghostclass' }} COMMIT_SHA: ${{ github.sha }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -euo pipefail - - IMAGE_NAME=$(echo "$REPOSITORY" | cut -d'/' -f2 | tr '[:upper:]' '[:lower:]') + VERSION_TAG="backup-v${VERSION}" PLATFORM_LIST=$(echo "${PLATFORMS}" | sed 's/linux\///g; s/,/, /g') - PLAY_STORE_URL="https://play.google.com/store/apps/details?id=${ANDROID_PACKAGE_NAME}" - if [[ "${PLATFORMS}" == *","* ]]; then - PLATFORM_DESC="Multi-platform Docker images (${PLATFORM_LIST})" + PREV_TAG=$(git tag -l 'backup-v*.*.*' --sort=-version:refname | grep -E '^backup-v[0-9]+\.[0-9]+\.[0-9]+$' | grep -v "^${VERSION_TAG}$" | head -n1 || echo "") + if [ -z "$PREV_TAG" ]; then + PREV_REF=$(git rev-list --max-parents=0 HEAD) + CHANGELOG_TEXT="${PREV_REF}...${VERSION_TAG}" else - PLATFORM_DESC="Docker image (${PLATFORM_LIST})" + CHANGELOG_TEXT="${PREV_TAG}...${VERSION_TAG}" fi - cat > ./artifacts/RELEASE_NOTES.md << EOF - ## Release ${VERSION_TAG} - - This release includes: - - đŸŗ ${PLATFORM_DESC} - - 📱 Flutter Android APK with provenance attestation - - 🔐 Signed images and artifacts using Sigstore cosign - - 📋 Software Bill of Materials (SBOM) in CycloneDX format - - ✅ Build provenance attestations - - 🔍 SHA256 checksums for all artifacts - - ### Mobile App - - [![Get it on Google Play](https://img.shields.io/badge/Get%20it%20on-Google%20Play-34A853?style=for-the-badge&logo=googleplay&logoColor=white)](${PLAY_STORE_URL}) - - > We recommend downloading from Google Play. GhostClass enforces Firebase App Check (Play Integrity), and Play-distributed builds provide the most reliable attestation path. - - ### Docker Images - - #### Pull by Immutable Content Hash (Recommended) + cat > ./artifacts/backup/VERIFY.md << EOF + # Backup Runner Verification Instructions (${VERSION_TAG}) \`\`\`bash - # Web App - docker pull ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}@${DIGEST} - - # Database Backup Service - docker pull ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}-backup@${BACKUP_DIGEST} - \`\`\` - - #### Pull by Immutable Commit SHA - - \`\`\`bash - # Web App - docker pull ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}:${COMMIT_SHA} - - # Database Backup Service - docker pull ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}-backup:${COMMIT_SHA} - \`\`\` - - #### Pull by Version Tag - - \`\`\`bash - # Web App - docker pull ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}:${VERSION_TAG} + cosign verify \\ + --certificate-identity-regexp="^https://github.com/${REPOSITORY}/\\.github/workflows/" \\ + --certificate-oidc-issuer="https://token.actions.githubusercontent.com" \\ + ghcr.io/${REPOSITORY_OWNER}/ghostclass-backup@${BACKUP_DIGEST} - # Database Backup Service - docker pull ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}-backup:${VERSION_TAG} + gh attestation verify oci://ghcr.io/${REPOSITORY_OWNER}/ghostclass-backup@${BACKUP_DIGEST} --owner ${REPOSITORY_OWNER} + cosign verify-blob --bundle ghostclass-backup-runner-sbom.json.bundle ghostclass-backup-runner-sbom.json + grep -E '^[0-9a-f]{64} ' ghostclass-backup-runner-checksums.txt | sha256sum -c \`\`\` + EOF + sed -i 's/^ //' ./artifacts/backup/VERIFY.md - **Image Digest**: \`${DIGEST}\` - **Commit SHA**: \`${COMMIT_SHA}\` - - ### Verification - - See [VERIFY.md](https://github.com/${REPOSITORY}/releases/download/${VERSION_TAG}/VERIFY.md) for detailed verification instructions. + cat > ./artifacts/backup/RELEASE_NOTES.md << EOF + ## Backup Runner Release ${VERSION_TAG} - ### Quick Verification + - đŸ—„ī¸ Database Backup Runner Docker image (${PLATFORM_LIST}) + - 🔐 Signed image and SBOM using Sigstore cosign \`\`\`bash - # Verify image signature by digest - cosign verify \\ - --certificate-identity-regexp="^https://github.com/${REPOSITORY}" \\ - --certificate-oidc-issuer="https://token.actions.githubusercontent.com" \\ - ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}@${DIGEST} - - # Verify attestation - gh attestation verify oci://ghcr.io/${REPOSITORY_OWNER}/${IMAGE_NAME}@${DIGEST} --owner ${REPOSITORY_OWNER} + docker pull ghcr.io/${REPOSITORY_OWNER}/ghostclass-backup@${BACKUP_DIGEST} + docker pull ghcr.io/${REPOSITORY_OWNER}/ghostclass-backup:${VERSION} \`\`\` - --- - + **Image Digest**: \`${BACKUP_DIGEST}\` + **Commit SHA**: \`${COMMIT_SHA}\` **Full Changelog**: ${SERVER_URL}/${REPOSITORY}/compare/${CHANGELOG_TEXT} EOF + sed -i 's/^ //' ./artifacts/backup/RELEASE_NOTES.md - # Remove leading indentation from here-doc - sed -i 's/^[[:space:]]\{10\}//' ./artifacts/RELEASE_NOTES.md + TAG_ARGS=() + if ! git rev-parse -q --verify "refs/tags/${VERSION_TAG}" >/dev/null 2>&1; then + TAG_ARGS=(--target "${COMMIT_SHA}") + fi gh release create "${VERSION_TAG}" \ - --title "Release ${VERSION_TAG}" \ - --latest \ - --notes-file ./artifacts/RELEASE_NOTES.md \ - ./artifacts/web/sbom.json \ - ./artifacts/web/sbom.json.bundle \ + "${TAG_ARGS[@]}" \ + --title "Backup Runner ${VERSION_TAG}" \ + --latest=false \ + --notes-file ./artifacts/backup/RELEASE_NOTES.md \ ./artifacts/backup/ghostclass-backup-runner-sbom.json \ ./artifacts/backup/ghostclass-backup-runner-sbom.json.bundle \ - ./artifacts/checksums.txt \ - ./artifacts/VERIFY.md \ - ./artifacts/web/provenance.intoto.jsonl \ - ./artifacts/mobile/ghostclass-android-v${VERSION_RAW}.apk \ - ./artifacts/mobile/mobile-sbom.json \ - ./artifacts/mobile/mobile-checksums.txt \ - ./artifacts/mobile/mobile-provenance.intoto.jsonl \ + ./artifacts/backup/ghostclass-backup-runner-checksums.txt \ + ./artifacts/backup/VERIFY.md \ --draft=false + + # ──────────────────────────────────────────────────────────────────────────── + # Job 5: Trigger Immutable Digest Deployment + # ──────────────────────────────────────────────────────────────────────────── + deploy: + name: Trigger Production Deploy + needs: [guard, build-web, build-backup] + if: always() && !cancelled() && needs.guard.result == 'success' && needs.build-web.result != 'failure' && needs.build-backup.result != 'failure' && (needs.build-web.result == 'success' || needs.build-backup.result == 'success' || needs.guard.outputs.deploy_infra == 'true') + permissions: + contents: read + uses: ./.github/workflows/deploy.yml + with: + deploy_web: ${{ needs.build-web.result == 'success' }} + web_image_digest: ${{ needs.build-web.outputs.image_digest || '' }} + deploy_backup: ${{ needs.build-backup.result == 'success' }} + backup_image_digest: ${{ needs.build-backup.outputs.backup_image_digest || '' }} + deploy_infra: ${{ needs.guard.outputs.deploy_infra == 'true' }} + secrets: inherit diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index def682e5..50a526b7 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,9 +2,9 @@ name: Tests on: push: - branches: [main, "release/*"] + branches: [main] pull_request: - branches: [main, "release/*"] + branches: [main] env: FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true" @@ -12,34 +12,82 @@ env: permissions: {} jobs: + changes: + name: Detect Web Changes + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + outputs: + web: ${{ steps.filter.outputs.web }} + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + fetch-depth: 0 + + - name: Filter changed paths + uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2 + id: filter + with: + filters: | + web: + - 'src/**' + - 'public/**' + - 'e2e/**' + - 'scripts/**' + - 'mocks/**' + - 'package.json' + - 'package-lock.json' + - 'next.config.*' + - 'tsconfig.json' + - 'vitest.*' + - 'playwright.*' + - 'eslint.config.*' + - 'postcss.config.*' + - 'components.json' + - '.github/workflows/test.yml' + unit-tests: + needs: changes runs-on: ubuntu-latest permissions: contents: read steps: + - name: Skip notice + if: needs.changes.outputs.web != 'true' + run: echo "â­ī¸ Skipping web unit tests (no web or test files changed)." + - name: Checkout + if: needs.changes.outputs.web == 'true' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 + if: needs.changes.outputs.web == 'true' with: node-version: "26.13.1" cache: "npm" - name: Install dependencies + if: needs.changes.outputs.web == 'true' run: npm ci --legacy-peer-deps - name: Run ESLint & SonarJS Audit + if: needs.changes.outputs.web == 'true' # Fails the pipeline if there is even a single warning or error run: npx eslint . --max-warnings=0 - name: TypeScript Compiler Check + if: needs.changes.outputs.web == 'true' # Verifies type safety without outputting compiled files run: npm run typecheck - name: Run unit tests with coverage + if: needs.changes.outputs.web == 'true' run: npm run test:coverage - name: Upload coverage to Codecov + if: needs.changes.outputs.web == 'true' uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 with: files: ./coverage/lcov.info @@ -47,6 +95,7 @@ jobs: fail_ci_if_error: false e2e-tests: + needs: changes runs-on: ubuntu-latest permissions: contents: read @@ -62,12 +111,12 @@ jobs: PROXY_RATE_LIMIT_REQUESTS: "120" PROXY_RATE_LIMIT_WINDOW: "60" BREVO_API_KEY: "test-brevo-key" - NEXT_PUBLIC_TURNSTILE_SITE_KEY: "1x000000000000000000000AA" + NEXT_PUBLIC_TURNSTILE_SITE_KEY: "1x00000000000000000000AA" TURNSTILE_SECRET_KEY: "1x0000000000000000000000000000000AA" JWE_PRIVATE_KEY: "test-jwe-private-key-pem" - NEXT_PUBLIC_APP_NAME: "GhostClass" - NEXT_PUBLIC_APP_VERSION: "3.0.8" - MIN_APP_VERSION: "3.0.8" + APP_VERSION: "4.7.2" + MIN_APP_VERSION: "4.7.2" + LATEST_APP_VERSION: "4.7.2" NEXT_PUBLIC_BACKEND_URL: "http://localhost:8080" NEXT_PUBLIC_APP_URL: "http://localhost:3000" NEXT_PUBLIC_APP_DOMAIN: "localhost" @@ -81,24 +130,33 @@ jobs: FIREBASE_APP_ID_IOS: "1:123:ios:abc" NODE_ENV: "test" steps: + - name: Skip notice + if: needs.changes.outputs.web != 'true' + run: echo "â­ī¸ Skipping E2E tests (no web or test files changed)." + - name: Checkout + if: needs.changes.outputs.web == 'true' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 + if: needs.changes.outputs.web == 'true' with: node-version: "26.13.1" cache: "npm" - name: Install dependencies + if: needs.changes.outputs.web == 'true' run: npm ci --legacy-peer-deps - name: Get Playwright version id: playwright-version + if: needs.changes.outputs.web == 'true' run: | PLAYWRIGHT_VERSION=$(node -p "require('./package-lock.json').packages['node_modules/@playwright/test'].version") echo "PLAYWRIGHT_VERSION=$PLAYWRIGHT_VERSION" >> $GITHUB_OUTPUT - name: Cache Playwright browsers + if: needs.changes.outputs.web == 'true' uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 id: playwright-cache with: @@ -107,17 +165,18 @@ jobs: - name: Install Playwright Chromium only run: npx playwright install --with-deps chromium - if: steps.playwright-cache.outputs.cache-hit != 'true' + if: needs.changes.outputs.web == 'true' && steps.playwright-cache.outputs.cache-hit != 'true' - name: Install Chromium dependencies (cache hit) run: npx playwright install-deps chromium - if: steps.playwright-cache.outputs.cache-hit == 'true' + if: needs.changes.outputs.web == 'true' && steps.playwright-cache.outputs.cache-hit == 'true' - name: Run E2E tests (Chromium only) + if: needs.changes.outputs.web == 'true' run: npm run test:e2e -- --project=chromium - name: Upload test results - if: always() + if: always() && needs.changes.outputs.web == 'true' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 with: name: playwright-report diff --git a/.husky/pre-commit b/.husky/pre-commit index dd3cc422..dde9749b 100644 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,22 +1,3 @@ set -e -# 1. Sync repository version -node scripts/sync-version.js --pre-commit - -# 2. Format frontend code -npx prettier --write src/ - -# 3. Format mobile Dart code -(cd mobile && dart format .) - -# 4. Stage formatted and synchronized files -git add -u - -# 5. Run lint-staged (tsc typecheck and eslint --fix) -npx lint-staged - -# 6. Analyze mobile Dart code -(cd mobile && flutter analyze) - -# 7. Ensure any remaining auto-fixes are staged -git add -u +npx lint-staged --concurrent false diff --git a/.husky/pre-push b/.husky/pre-push new file mode 100644 index 00000000..f10dad13 --- /dev/null +++ b/.husky/pre-push @@ -0,0 +1,3 @@ +set -e + +node scripts/pre-push-bump.js "$1" "$2" diff --git a/Dockerfile b/Dockerfile index aa95ef97..20b8d96f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -68,6 +68,7 @@ ARG BUILD_TIMESTAMP ARG AUDIT_STATUS ARG SIGNATURE_STATUS ARG IMAGE_DIGEST +ARG APP_VERSION ARG SENTRY_ORG ARG SENTRY_PROJECT ARG NEXT_PUBLIC_SENTRY_DSN @@ -75,6 +76,8 @@ ARG NEXT_PUBLIC_SENTRY_DSN ENV SOURCE_DATE_EPOCH=${SOURCE_DATE_EPOCH} ENV APP_COMMIT_SHA=${APP_COMMIT_SHA} ENV NEXT_PUBLIC_GIT_COMMIT_SHA=${APP_COMMIT_SHA} +ENV APP_VERSION=${APP_VERSION} +ENV NEXT_PUBLIC_APP_NAME="GhostClass" ENV IMAGE_DIGEST=${IMAGE_DIGEST} ENV GITHUB_REPOSITORY=${GITHUB_REPOSITORY} ENV GITHUB_RUN_ID=${GITHUB_RUN_ID} @@ -108,8 +111,6 @@ ARG NEXT_PUBLIC_SUPABASE_DEV_PUBLISHABLE_KEY ARG NEXT_PUBLIC_SUPABASE_CF_PROXY_URL ARG NEXT_PUBLIC_SUPABASE_AWS_PROXY_URL ARG NEXT_PUBLIC_GITHUB_URL -ARG NEXT_PUBLIC_APP_NAME -ARG NEXT_PUBLIC_APP_VERSION ARG NEXT_PUBLIC_APP_DOMAIN ARG NEXT_PUBLIC_APP_URL ARG NEXT_PUBLIC_SITEMAP_URL @@ -136,8 +137,6 @@ ENV NEXT_PUBLIC_SUPABASE_DEV_PUBLISHABLE_KEY=${NEXT_PUBLIC_SUPABASE_DEV_PUBLISHA ENV NEXT_PUBLIC_SUPABASE_CF_PROXY_URL=${NEXT_PUBLIC_SUPABASE_CF_PROXY_URL} ENV NEXT_PUBLIC_SUPABASE_AWS_PROXY_URL=${NEXT_PUBLIC_SUPABASE_AWS_PROXY_URL} ENV NEXT_PUBLIC_GITHUB_URL=${NEXT_PUBLIC_GITHUB_URL} -ENV NEXT_PUBLIC_APP_NAME=${NEXT_PUBLIC_APP_NAME} -ENV NEXT_PUBLIC_APP_VERSION=${NEXT_PUBLIC_APP_VERSION} ENV NEXT_PUBLIC_APP_DOMAIN=${NEXT_PUBLIC_APP_DOMAIN} ENV NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL} ENV NEXT_PUBLIC_SITEMAP_URL=${NEXT_PUBLIC_SITEMAP_URL} @@ -162,8 +161,6 @@ RUN set -e; \ : "${NEXT_PUBLIC_BACKEND_URL:?NEXT_PUBLIC_BACKEND_URL is required}"; \ : "${NEXT_PUBLIC_SUPABASE_URL:?NEXT_PUBLIC_SUPABASE_URL is required}"; \ : "${NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY:?NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY is required}"; \ - : "${NEXT_PUBLIC_APP_NAME:?NEXT_PUBLIC_APP_NAME is required}"; \ - : "${NEXT_PUBLIC_APP_VERSION:?NEXT_PUBLIC_APP_VERSION is required}"; \ : "${NEXT_PUBLIC_APP_DOMAIN:?NEXT_PUBLIC_APP_DOMAIN is required}"; \ : "${NEXT_PUBLIC_APP_URL:?NEXT_PUBLIC_APP_URL is required}"; \ : "${NEXT_PUBLIC_SITEMAP_URL:?NEXT_PUBLIC_SITEMAP_URL is required}"; \ @@ -217,8 +214,11 @@ ARG BUILD_TIMESTAMP ARG AUDIT_STATUS ARG SIGNATURE_STATUS ARG IMAGE_DIGEST +ARG APP_VERSION ENV SOURCE_DATE_EPOCH=${SOURCE_DATE_EPOCH} ENV APP_COMMIT_SHA=${APP_COMMIT_SHA} +ENV APP_VERSION=${APP_VERSION} +ENV NEXT_PUBLIC_APP_NAME="GhostClass" ENV IMAGE_DIGEST=${IMAGE_DIGEST} ENV GITHUB_REPOSITORY=${GITHUB_REPOSITORY} ENV GITHUB_RUN_ID=${GITHUB_RUN_ID} diff --git a/README.md b/README.md index 4b358968..6e9acc25 100644 --- a/README.md +++ b/README.md @@ -404,12 +404,12 @@ infisical run --env=dev --projectId=xxxx --path=/build-time -- sh -c ' export DART_VM_OPTIONS="--bind-address=0.0.0.0" flutter run \ --dart-define=APP_DOMAIN="$NEXT_PUBLIC_APP_DOMAIN" \ - --dart-define=APP_VERSION="$NEXT_PUBLIC_APP_VERSION" \ + --dart-define=APP_VERSION="4.7.2" \ --dart-define=AUTHOR_NAME="$NEXT_PUBLIC_AUTHOR_NAME" \ --dart-define=AUTHOR_URL="$NEXT_PUBLIC_AUTHOR_URL" \ --dart-define=GITHUB_URL="$NEXT_PUBLIC_GITHUB_URL" \ --dart-define=DONATE_URL="$NEXT_PUBLIC_DONATE_URL" \ - --dart-define=APP_NAME="$APP_NAME" \ + --dart-define=APP_NAME="GhostClass" \ --dart-define=ANDROID_PACKAGE_NAME="$ANDROID_PACKAGE_NAME" \ --dart-define=IOS_APP_ID="$IOS_APP_ID" \ --dart-define=FIREBASE_API_KEY_ANDROID="$FIREBASE_API_KEY_ANDROID" \ @@ -518,8 +518,7 @@ directly from their own device IPs, avoiding this shared bottleneck. ## 🤝 Contributing -We welcome contributions! GhostClass uses an **automatic version bumping -system**. See **[CONTRIBUTING.md](docs/CONTRIBUTING.md)** for details. +We welcome contributions! GhostClass uses **Trunk-Based Development with decoupled component versioning** (`web`, `mobile`, `backup`) and signed `pre-push` version bumping. See **[CONTRIBUTING.md](docs/CONTRIBUTING.md)** for details. ## đŸ‘Ĩ Maintained by diff --git a/backup/VERSION b/backup/VERSION new file mode 100644 index 00000000..3eefcb9d --- /dev/null +++ b/backup/VERSION @@ -0,0 +1 @@ +1.0.0 diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index d9a43ad7..21d58881 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -76,45 +76,48 @@ flutter build apk # Build Android APK 5. Commit with clear messages (see [Commit Messages](#commit-messages)) 6. Push and create a Pull Request -**Important**: Centralized version values apply automatically! See +**Important**: Component versions are bumped automatically on `git push`! See [Versioning System](#versioning-system) below. ## Versioning System -GhostClass derives its build versions dynamically via centralized Infisical -runtime and CI configurations (`NEXT_PUBLIC_APP_VERSION`). Contributors do not -need to manually compute or inject git semantic rollover tags when proposing -features. Maintainers synchronize version thresholds directly in the project -dashboard prior to production releases. +GhostClass uses **Trunk-Based Development with Decoupled Component Versioning** (`web`, `mobile`, and `backup`). When you push a feature/fix branch, `.husky/pre-push` compares `origin/main...HEAD`, bumps only the components whose files changed (using the rollover-at-9 rules in [VERSIONING.md](VERSIONING.md) and Conventional Commits), creates a signed commit, and pushes the updated branch. + +You can also bump a component manually before pushing: + +```bash +npm run version:bump -- --component web --type minor +npm run version:bump -- --component mobile --type patch +``` ## Pull Request Process ### Creating a PR -1. Push your branch to GitHub -2. Open a Pull Request against `main` -3. Fill in the PR template: +1. Create a short-lived branch from `main` (`feat/*`, `fix/*`, `chore/*`, `hotfix/*`) +2. Push your branch to GitHub (`.husky/pre-push` creates a signed bump commit if needed) +3. Open a Pull Request against `main` +4. Fill in the PR template: - Description of changes - Related issue numbers - Testing notes -4. Wait for auto-bump (same-repo) or manually bump (fork) 5. Request review from maintainers ### PR Checklist -- [ ] Tests pass locally (`npm run test`) -- [ ] Linter passes (`npm run lint`) -- [ ] Version bumped (automatic or manual) +- [ ] Tests pass locally (`npm run test` / `flutter test`) +- [ ] Linter passes (`npm run lint` / `flutter analyze`) +- [ ] Commits are GPG/SSH signed (`git commit -S`) - [ ] Documentation updated (if needed) - [ ] Commit messages follow conventions ### Review & Merge -1. Automated tests run on your PR +1. Automated checks run on your PR (`Build Guard`, path-gated `Tests`, `Mobile Tests`, `CodeQL`) 2. Maintainers review your code 3. Address feedback or requested changes -4. Once approved, maintainer merges -5. Auto-tagging and release workflows run automatically +4. Once approved, maintainer merges (`Create a merge commit` to preserve signed commits) +5. `release.yml` builds & releases only changed components on `main` (or when a signed `web-v*` / `mobile-v*` / `backup-v*` tag is pushed) ## Code Quality & Testing @@ -256,10 +259,11 @@ Closes #123 ### Version Management -- App Versioning: Controlled directly via `NEXT_PUBLIC_APP_VERSION` injected - dynamically at runtime/compile-time. -- Release Automation: Dynamic multi-arch bundles and attestation manual updates - are published synchronously upon successful merges to the primary main trunk. +- **Web (`web-vX.Y.Z`)**: Version stored in `package.json` (`package-lock.json`, `public/openapi/openapi.yaml`), injected as `APP_VERSION` at Docker build time. +- **Mobile (`mobile-vX.Y.Z`)**: Version stored in `mobile/pubspec.yaml` (`X.Y.Z`), with Play Store `versionCode` supplied by CI (`--build-number=${{ github.run_number }}`). +- **Backup (`backup-vX.Y.Z`)**: Version stored in `backup/VERSION`. +- **Mobile Update Policy**: `MIN_APP_VERSION` and `LATEST_APP_VERSION` are managed dynamically in Infisical `/runtime` and read by `/api/security/attestation`. +- **Signed Component Tags**: Push `git tag -s web-vX.Y.Z` (or `mobile-v*` / `backup-v*`) to cut a tag-verified release, or include `[skip release]` in a merge commit to batch PRs before tagging. --- diff --git a/docs/VERSIONING.md b/docs/VERSIONING.md index 9067753e..719b8d5a 100644 --- a/docs/VERSIONING.md +++ b/docs/VERSIONING.md @@ -1,23 +1,42 @@ # Versioning System -GhostClass follows a modified [Semantic Versioning 2.0.0](https://semver.org/) -system with a **rollover mechanism** for patch and minor versions. +GhostClass uses **Trunk-Based Development with Decoupled Component Versioning**. +Each deployable component maintains its own independent semantic version (`X.Y.Z`) with GhostClass's **rollover-at-9** increment rule for patch and minor numbers. -## Version Format: `X.Y.Z` +## Component Versions & Tags -- **X (Major)**: Significant structural changes, breaking API changes, or major - project milestones. Can exceed `9`. -- **Y (Minor)**: New features or significant enhancements. Rollover at `9` - (increments X and resets Y to 0). -- **Z (Patch)**: Bug fixes, security patches, or minor documentation updates. - Rollover at `9` (increments Y and resets Z to 0). +| Component | Source of Truth | Signed Tag Pattern | Release Target | +| :--- | :--- | :--- | :--- | +| **Web** | `package.json` (+ `package-lock.json`, `public/openapi/openapi.yaml`) | `web-vX.Y.Z` | Next.js Docker image (`ghcr.io//ghostclass`) | +| **Mobile** | `mobile/pubspec.yaml` (+ `mobile/lib/config/app_config.dart`) | `mobile-vX.Y.Z` | Signed Android APK & Play Store AAB (`--build-number=${{ github.run_number }}`) | +| **Backup** | `backup/VERSION` | `backup-vX.Y.Z` | Backup Runner Docker image (`ghcr.io//ghostclass-backup`) | + +> **Runtime Mobile Policy (`MIN_APP_VERSION` & `LATEST_APP_VERSION`)**: +> Force-update thresholds and latest advertised mobile versions are managed dynamically in Infisical `/runtime` (`MIN_APP_VERSION`, `LATEST_APP_VERSION`) and served by `/api/security/attestation` without rebuilding Web or Mobile. + +## Version Format: `X.Y.Z` (Rollover at 9) + +- **X (Major)**: Significant structural changes, breaking API changes, or major milestones. Can exceed `9`. +- **Y (Minor)**: New features (`feat:`). Rollover at `9` (increments `X` and resets `Y` to `0`). +- **Z (Patch)**: Bug fixes (`fix:`, `chore:`, etc.). Rollover at `9` (increments `Y` and resets `Z` to `0`). ### Rollover Examples -| Current Version | Bump Type | New Version | Reason | -| --------------- | --------- | ----------- | ----------------------------------------- | -| `1.5.5` | Patch | `1.5.6` | Normal increment | -| `1.5.9` | Patch | `1.6.0` | Patch rollover (Z=9 → Y+1, Z=0) | -| `1.9.9` | Patch | `2.0.0` | Minor rollover (Y=9, Z=9 → X+1, Y=0, Z=0) | -| `10.3.5` | Minor | `10.4.0` | Normal increment | -| `10.9.2` | Minor | `11.0.0` | Minor rollover (Y=9 → X+1, Y=0) | +| Current Version | Bump Type | New Version | Reason | +| :--- | :--- | :--- | :--- | +| `1.5.5` | Patch | `1.5.6` | Normal increment | +| `1.5.9` | Patch | `1.6.0` | Patch rollover (`Z=9 → Y+1, Z=0`) | +| `1.9.9` | Patch | `2.0.0` | Minor rollover (`Y=9, Z=9 → X+1, Y=0, Z=0`) | +| `10.3.5` | Minor | `10.4.0` | Normal increment | +| `10.9.2` | Minor | `11.0.0` | Minor rollover (`Y=9 → X+1, Y=0`) | + +## Automated & Manual Bumping + +- **Automatic (`pre-push`)**: `.husky/pre-push` (`scripts/pre-push-bump.js`) compares `origin/main...HEAD`. Only changed components whose version still equals `origin/main` are bumped (using Conventional Commits scoped to that component's paths), signed with `git commit -S`, and pushed automatically. +- **Manual CLI**: + +```bash +npm run version:bump -- --component web --type patch +npm run version:bump -- --component mobile --type minor +npm run version:bump -- --component backup --type major +``` diff --git a/lint-staged.config.js b/lint-staged.config.js index 7dce447b..baedaf64 100644 --- a/lint-staged.config.js +++ b/lint-staged.config.js @@ -10,13 +10,28 @@ function getTscCommand() { return "tsc --noEmit"; } +function quoteFiles(files) { + return files.map((file) => `"${file}"`).join(" "); +} + module.exports = { - // 1. Type Check: Runs on the whole project (function form = ignore file args, run once) - "**/*.{ts,tsx}": () => getTscCommand(), + // Format and lint staged web/E2E JS/TS files sequentially + "{src,e2e}/**/*.{js,jsx,ts,tsx}": (files) => [ + `npx prettier --write ${quoteFiles(files)}`, + `node node_modules/eslint/bin/eslint.js --no-warn-ignored --fix ${quoteFiles(files)}`, + ], - // 2. Linting: Runs on the whole project (function form = ignore file args, run once) - "**/*.{js,jsx,ts,tsx}": () => { - return "node node_modules/eslint/bin/eslint.js . --fix"; - }, -}; + // Format staged scripts and non-JS/TS web assets + "scripts/**/*.{js,ts}": (files) => `npx prettier --write ${quoteFiles(files)}`, + "{src,e2e}/**/*.{css,json,md}": (files) => + `npx prettier --write ${quoteFiles(files)}`, + // Typecheck only when TypeScript files are staged + "{src,e2e}/**/*.{ts,tsx}": () => getTscCommand(), + + // Format only staged Dart files + "mobile/**/*.dart": (files) => `dart format ${quoteFiles(files)}`, + + // Run Flutter static analysis only when Dart/pubspec files are staged + "mobile/**/*.{dart,yaml}": () => 'sh -c "cd mobile && flutter analyze"', +}; diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml index 072b928b..565fabe5 100644 --- a/mobile/pubspec.yaml +++ b/mobile/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 4.7.2+1 +version: 4.7.2 environment: sdk: ^3.11.4 diff --git a/next.config.ts b/next.config.ts index b7de2e4b..52d6886f 100644 --- a/next.config.ts +++ b/next.config.ts @@ -1,6 +1,8 @@ import { withSentryConfig } from "@sentry/nextjs/config"; import withSerwistInit from "@serwist/next"; import type { NextConfig } from "next"; +import packageJson from "./package.json"; +import { APP_NAME } from "./src/lib/constants/app"; if (process.env.NODE_ENV === "production") { process.env.SERWIST_SUPPRESS_TURBOPACK_WARNING = "1"; @@ -232,6 +234,8 @@ const nextConfig = { env: { NEXT_PUBLIC_GIT_COMMIT_SHA: process.env.APP_COMMIT_SHA || "unknown", + NEXT_PUBLIC_APP_NAME: APP_NAME, + APP_VERSION: process.env.APP_VERSION || packageJson.version, }, images: { diff --git a/package.json b/package.json index e1b2535f..498786b0 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,8 @@ "test:e2e:headed": "playwright test --headed", "test:all": "npm run test:coverage && npm run test:e2e", "generate:firebase-json": "node scripts/generate-firebase-json.js", + "version:bump": "node scripts/bump-version.js", + "version:sync": "node scripts/sync-version.js", "prepare": "husky" }, "browserslist": [ diff --git a/scripts/__tests__/version-scripts.test.ts b/scripts/__tests__/version-scripts.test.ts new file mode 100644 index 00000000..a45f4f7a --- /dev/null +++ b/scripts/__tests__/version-scripts.test.ts @@ -0,0 +1,197 @@ +/** @vitest-environment node */ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +const { + parseComponentVersionContent, + readComponentVersion, + syncComponentVersion, +} = require("../sync-version"); +const { + isComponentPath, + bumpSemver, + detectBumpTypeFromCommits, + bumpComponent, +} = require("../bump-version"); +const { parsePushRefs } = require("../pre-push-bump"); + +const tempDirs: string[] = []; + +function createTempRepoFixture(): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ghostclass-ver-")); + tempDirs.push(dir); + + fs.mkdirSync(path.join(dir, "public", "openapi"), { recursive: true }); + fs.mkdirSync(path.join(dir, "mobile", "lib", "config"), { recursive: true }); + fs.mkdirSync(path.join(dir, "backup"), { recursive: true }); + + fs.writeFileSync( + path.join(dir, "package.json"), + JSON.stringify({ name: "ghostclass", version: "4.7.2" }, null, 2) + "\n", + ); + fs.writeFileSync( + path.join(dir, "package-lock.json"), + JSON.stringify( + { + name: "ghostclass", + version: "4.7.2", + packages: { "": { name: "ghostclass", version: "4.7.2" } }, + }, + null, + 2, + ) + "\n", + ); + fs.writeFileSync( + path.join(dir, "public", "openapi", "openapi.yaml"), + "openapi: 3.1.0\ninfo:\n title: GhostClass API\n version: 4.7.2\n", + ); + fs.writeFileSync( + path.join(dir, "mobile", "pubspec.yaml"), + "name: ghostclass\nversion: 4.7.2+1\n", + ); + fs.writeFileSync( + path.join(dir, "mobile", "lib", "config", "app_config.dart"), + "static String get appVersion => const String.fromEnvironment('APP_VERSION', defaultValue: '4.7.2');\n", + ); + fs.writeFileSync(path.join(dir, "backup", "VERSION"), "1.0.0\n"); + fs.writeFileSync( + path.join(dir, ".env"), + "MIN_APP_VERSION=4.7.2\nLATEST_APP_VERSION=4.7.2\n", + ); + + return dir; +} + +afterEach(() => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir && fs.existsSync(dir)) { + fs.rmSync(dir, { recursive: true, force: true }); + } + } +}); + +describe("versioning scripts", () => { + it("implements rollover-at-9 rules from docs/VERSIONING.md", () => { + expect(bumpSemver("1.5.5", "patch")).toBe("1.5.6"); + expect(bumpSemver("1.5.9", "patch")).toBe("1.6.0"); + expect(bumpSemver("1.9.9", "patch")).toBe("2.0.0"); + expect(bumpSemver("10.3.5", "minor")).toBe("10.4.0"); + expect(bumpSemver("10.9.2", "minor")).toBe("11.0.0"); + expect(bumpSemver("4.7.2", "major")).toBe("5.0.0"); + expect(bumpSemver("4.7.2", "6.1.0")).toBe("6.1.0"); + }); + + it("detects bump level from Conventional Commits", () => { + expect( + detectBumpTypeFromCommits([ + { subject: "fix(ui): align button" }, + { subject: "chore: tidy scripts" }, + ]), + ).toBe("patch"); + + expect( + detectBumpTypeFromCommits([ + { subject: "fix(ui): align button" }, + { subject: "feat(dashboard): add export" }, + ]), + ).toBe("minor"); + + expect( + detectBumpTypeFromCommits([ + { subject: "feat(api)!: change auth response" }, + ]), + ).toBe("major"); + + expect( + detectBumpTypeFromCommits([ + { + subject: "feat(api): update endpoint", + body: "BREAKING CHANGE: drops v1", + }, + ]), + ).toBe("major"); + }); + + it("isolates paths by component", () => { + expect(isComponentPath("web", "src/app/page.tsx")).toBe(true); + expect(isComponentPath("web", "Dockerfile")).toBe(true); + expect(isComponentPath("web", "mobile/lib/main.dart")).toBe(false); + + expect(isComponentPath("mobile", "mobile/lib/main.dart")).toBe(true); + expect(isComponentPath("mobile", "src/app/page.tsx")).toBe(false); + + expect(isComponentPath("backup", "backup/backup-db.sh")).toBe(true); + expect(isComponentPath("backup", "README.md")).toBe(false); + }); + + it("strips legacy +build suffix when parsing/syncing mobile pubspec.yaml", () => { + expect( + parseComponentVersionContent( + "mobile", + "name: ghostclass\nversion: 4.7.2+9\n", + ), + ).toBe("4.7.2"); + + const dir = createTempRepoFixture(); + const res = bumpComponent("mobile", "patch", { rootDir: dir, quiet: true }); + + expect(res.from).toBe("4.7.2"); + expect(res.to).toBe("4.7.3"); + expect( + fs.readFileSync(path.join(dir, "mobile", "pubspec.yaml"), "utf8"), + ).toContain("version: 4.7.3\n"); + expect( + fs.readFileSync( + path.join(dir, "mobile", "lib", "config", "app_config.dart"), + "utf8", + ), + ).toContain("defaultValue: '4.7.3'"); + // Web and backup remain untouched + expect(readComponentVersion("web", dir)).toBe("4.7.2"); + expect(readComponentVersion("backup", dir)).toBe("1.0.0"); + expect(fs.readFileSync(path.join(dir, ".env"), "utf8")).toContain( + "MIN_APP_VERSION=4.7.2", + ); + }); + + it("syncs web component independently without touching mobile or .env", () => { + const dir = createTempRepoFixture(); + syncComponentVersion("web", "4.8.0", { rootDir: dir, quiet: true }); + + expect(readComponentVersion("web", dir)).toBe("4.8.0"); + expect( + JSON.parse(fs.readFileSync(path.join(dir, "package-lock.json"), "utf8")) + .packages[""].version, + ).toBe("4.8.0"); + expect( + fs.readFileSync( + path.join(dir, "public", "openapi", "openapi.yaml"), + "utf8", + ), + ).toContain(" version: 4.8.0"); + expect(readComponentVersion("mobile", dir)).toBe("4.7.2"); + expect(readComponentVersion("backup", dir)).toBe("1.0.0"); + }); + + it("parses pre-push stdin refs and ignores tag pushes and deletions", () => { + const refs = parsePushRefs( + [ + "refs/heads/feat/test abc123 refs/heads/feat/test 000000", + "refs/tags/web-v4.7.3 def456 refs/tags/web-v4.7.3 000000", + "(delete) 0000000000000000000000000000000000000000 refs/heads/old abc123", + ].join("\n"), + ); + + expect(refs).toEqual([ + { + localRef: "refs/heads/feat/test", + localSha: "abc123", + remoteRef: "refs/heads/feat/test", + remoteSha: "000000", + }, + ]); + }); +}); diff --git a/scripts/bump-version.js b/scripts/bump-version.js new file mode 100644 index 00000000..981b96e8 --- /dev/null +++ b/scripts/bump-version.js @@ -0,0 +1,288 @@ +#!/usr/bin/env node + +const { execFileSync } = require("node:child_process"); +const path = require("node:path"); +const { + VALID_COMPONENTS, + SEMVER_REGEX, + readComponentVersion, + syncComponentVersion, +} = require("./sync-version"); + +const ROOT_DIR = path.join(__dirname, ".."); + +const COMPONENT_PATH_FILTERS = { + web: { + prefixes: ["src/", "public/"], + exact: new Set([ + "package.json", + "package-lock.json", + "next.config.ts", + "Dockerfile", + ".dockerignore", + "tsconfig.json", + "postcss.config.mjs", + "components.json", + "next-env.d.ts", + ]), + }, + mobile: { + prefixes: ["mobile/"], + exact: new Set(), + }, + backup: { + prefixes: ["backup/"], + exact: new Set(), + }, +}; + +const COMPONENT_GIT_PATHSPECS = { + web: [ + "src", + "public", + "package.json", + "package-lock.json", + "next.config.ts", + "Dockerfile", + ".dockerignore", + "tsconfig.json", + "postcss.config.mjs", + "components.json", + "next-env.d.ts", + ], + mobile: ["mobile"], + backup: ["backup"], +}; + +/** + * Returns true if a repository-relative POSIX path belongs to the given component. + * @param {"web"|"mobile"|"backup"} component + * @param {string} filePath + * @returns {boolean} + */ +function isComponentPath(component, filePath) { + const normalized = filePath.replace(/\\/g, "/"); + const filter = COMPONENT_PATH_FILTERS[component]; + if (!filter) return false; + if (filter.exact.has(normalized)) return true; + return filter.prefixes.some((prefix) => normalized.startsWith(prefix)); +} + +/** + * Increments a X.Y.Z version using GhostClass's rollover-at-9 rule (docs/VERSIONING.md). + * @param {string} version + * @param {"patch"|"minor"|"major"|string} [type="patch"] + * @returns {string} + */ +function bumpSemver(version, type = "patch") { + const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(String(version).trim()); + if (!match) { + throw new Error(`Invalid version "${version}". Expected X.Y.Z.`); + } + let [major, minor, patch] = match.slice(1).map(Number); + + if (type === "major") { + major += 1; + minor = 0; + patch = 0; + } else if (type === "minor") { + if (minor >= 9) { + major += 1; + minor = 0; + } else { + minor += 1; + } + patch = 0; + } else if (type === "patch") { + if (patch >= 9) { + patch = 0; + if (minor >= 9) { + major += 1; + minor = 0; + } else { + minor += 1; + } + } else { + patch += 1; + } + } else if (SEMVER_REGEX.test(type)) { + return type; + } else { + throw new Error( + `Invalid bump type "${type}". Expected patch, minor, major, or X.Y.Z.`, + ); + } + + return `${major}.${minor}.${patch}`; +} + +/** + * Determines the highest SemVer bump level from Conventional Commit messages. + * @param {Array<{ subject: string, body?: string }>} commits + * @returns {"major"|"minor"|"patch"} + */ +function detectBumpTypeFromCommits(commits) { + let level = "patch"; + + for (const commit of commits) { + const subject = (commit.subject || "").trim(); + const body = commit.body || ""; + + if ( + /^[a-z]+(?:\([^)]+\))?!:/i.test(subject) || + /^BREAKING[ -]CHANGE:/im.test(body) + ) { + return "major"; + } + + if (/^feat(?:\([^)]+\))?:/i.test(subject)) { + level = "minor"; + } + } + + return level; +} + +/** + * Reads commit subjects/bodies in a git revision range scoped to a component's paths. + * @param {"web"|"mobile"|"backup"} component + * @param {string} range + * @param {string} [rootDir] + * @returns {Array<{ subject: string, body: string }>} + */ +function readComponentCommits(component, range, rootDir = ROOT_DIR) { + const pathspecs = COMPONENT_GIT_PATHSPECS[component]; + const raw = execFileSync( + "git", + ["log", range, "--no-merges", "--format=%s%x1f%b%x1e", "--", ...pathspecs], + { cwd: rootDir, encoding: "utf8" }, + ); + + return raw + .split("\x1e") + .map((entry) => entry.trim()) + .filter(Boolean) + .map((entry) => { + const [subject = "", body = ""] = entry.split("\x1f"); + return { subject: subject.trim(), body: body.trim() }; + }); +} + +/** + * Bumps a single component's version and updates its files. + * @param {"web"|"mobile"|"backup"} component + * @param {string} [type="patch"] + * @param {{ rootDir?: string, dryRun?: boolean, quiet?: boolean }} [options] + */ +function bumpComponent(component, type = "patch", options = {}) { + const rootDir = options.rootDir || ROOT_DIR; + const dryRun = Boolean(options.dryRun); + const quiet = Boolean(options.quiet); + + const currentVersion = readComponentVersion(component, rootDir); + const nextVersion = bumpSemver(currentVersion, type); + + if (dryRun) { + if (!quiet) { + console.log( + `[dry-run] ${component}: ${currentVersion} -> ${nextVersion} (${type})`, + ); + } + return { + component, + from: currentVersion, + to: nextVersion, + bumpType: type, + updatedFiles: [], + }; + } + + const syncResult = syncComponentVersion(component, nextVersion, { + rootDir, + quiet, + }); + + return { + component, + from: currentVersion, + to: nextVersion, + bumpType: type, + updatedFiles: syncResult.updatedFiles, + }; +} + +function parseCliArgs(argv) { + let component = null; + let type = "patch"; + let fromCommits = null; + let dryRun = false; + let quiet = false; + + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === "--dry-run") { + dryRun = true; + } else if (arg === "--quiet" || arg === "-q") { + quiet = true; + } else if (arg === "--component" || arg === "-c") { + component = argv[i + 1]; + i += 1; + } else if (arg.startsWith("--component=")) { + component = arg.slice("--component=".length); + } else if (arg === "--type" || arg === "-t") { + type = argv[i + 1]; + i += 1; + } else if (arg.startsWith("--type=")) { + type = arg.slice("--type=".length); + } else if (arg === "--from-commits") { + fromCommits = argv[i + 1]; + i += 1; + } else if (arg.startsWith("--from-commits=")) { + fromCommits = arg.slice("--from-commits=".length); + } else if (!arg.startsWith("-")) { + if (!component && VALID_COMPONENTS.includes(arg)) { + component = arg; + } else { + type = arg; + } + } + } + + return { component, type, fromCommits, dryRun, quiet }; +} + +if (require.main === module) { + const { component, type, fromCommits, dryRun, quiet } = parseCliArgs( + process.argv.slice(2), + ); + if (!component || !VALID_COMPONENTS.includes(component)) { + console.error( + "Usage: node scripts/bump-version.js --component [--type patch|minor|major|X.Y.Z] [--from-commits origin/main..HEAD] [--dry-run]", + ); + process.exit(1); + } + try { + const resolvedType = fromCommits + ? detectBumpTypeFromCommits(readComponentCommits(component, fromCommits)) + : type; + const result = bumpComponent(component, resolvedType, { dryRun, quiet }); + if (!quiet && !dryRun) { + console.log( + `🚀 Bumped ${result.component}: ${result.from} -> ${result.to} (${result.bumpType})`, + ); + } + } catch (err) { + console.error(`❌ ${err.message}`); + process.exit(1); + } +} + +module.exports = { + COMPONENT_PATH_FILTERS, + COMPONENT_GIT_PATHSPECS, + isComponentPath, + bumpSemver, + detectBumpTypeFromCommits, + readComponentCommits, + bumpComponent, +}; diff --git a/scripts/pre-push-bump.js b/scripts/pre-push-bump.js new file mode 100644 index 00000000..a823cb1d --- /dev/null +++ b/scripts/pre-push-bump.js @@ -0,0 +1,242 @@ +#!/usr/bin/env node + +const fs = require("node:fs"); +const path = require("node:path"); +const { execFileSync } = require("node:child_process"); +const { + VALID_COMPONENTS, + getPrimaryVersionFile, + parseComponentVersionContent, + readComponentVersion, +} = require("./sync-version"); +const { + isComponentPath, + readComponentCommits, + detectBumpTypeFromCommits, + bumpComponent, +} = require("./bump-version"); + +const ROOT_DIR = path.join(__dirname, ".."); + +function git(args, options = {}) { + return execFileSync("git", args, { + cwd: ROOT_DIR, + encoding: "utf8", + ...options, + }); +} + +function tryGit(args) { + try { + return git(args, { stdio: ["ignore", "pipe", "pipe"] }).trim(); + } catch { + return null; + } +} + +/** + * Parses ` ` lines from stdin. + * @param {string} stdinText + */ +function parsePushRefs(stdinText) { + return stdinText + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean) + .map((line) => { + const [localRef, localSha, remoteRef, remoteSha] = line.split(/\s+/); + return { localRef, localSha, remoteRef, remoteSha }; + }) + .filter( + ({ localRef, localSha }) => + localRef && + localSha && + !/^0+$/.test(localSha) && + !localRef.startsWith("refs/tags/"), + ); +} + +/** + * Reads a component's version from a git ref (e.g. `origin/main`). + * Returns null if the version file does not exist on that ref yet. + * @param {string} ref + * @param {"web"|"mobile"|"backup"} component + */ +function readVersionAtRef(ref, component) { + const file = getPrimaryVersionFile(component); + const content = tryGit(["show", `${ref}:${file}`]); + if (content === null) return null; + return parseComponentVersionContent(component, content); +} + +function main() { + if (process.env.SKIP_VERSION_BUMP === "1") { + process.exit(0); + } + + const remoteName = process.argv[2] || "origin"; + const stdinText = fs.readFileSync(0, "utf8"); + const branchPushes = parsePushRefs(stdinText); + + if (branchPushes.length === 0) { + process.exit(0); + } + + const currentBranch = tryGit(["rev-parse", "--abbrev-ref", "HEAD"]); + if (!currentBranch || currentBranch === "HEAD" || currentBranch === "main") { + process.exit(0); + } + + // Refresh origin/main best-effort so comparisons reflect latest trunk + try { + git(["fetch", remoteName, "main", "--quiet"], { + stdio: ["ignore", "ignore", "ignore"], + }); + } catch { + // Offline or non-standard remote; fall back to local tracking ref if available + } + + const baseRef = tryGit(["rev-parse", "--verify", `${remoteName}/main`]) + ? `${remoteName}/main` + : tryGit(["rev-parse", "--verify", "origin/main"]) + ? "origin/main" + : null; + + if (!baseRef) { + console.log( + `â„šī¸ pre-push: ${remoteName}/main not found locally; skipping automatic version bump.`, + ); + process.exit(0); + } + + // Ensure working tree does not have uncommitted changes in tracked version files + const dirtyStatus = tryGit([ + "status", + "--porcelain", + "--", + "package.json", + "package-lock.json", + "public/openapi/openapi.yaml", + "mobile/pubspec.yaml", + "mobile/lib/config/app_config.dart", + "backup/VERSION", + ]); + if (dirtyStatus) { + console.error( + "❌ pre-push: Uncommitted changes detected in version files. Commit or stash them before pushing:", + ); + console.error(dirtyStatus); + process.exit(1); + } + + const changedFilesRaw = tryGit(["diff", "--name-only", `${baseRef}...HEAD`]); + if (!changedFilesRaw) { + process.exit(0); + } + + const changedFiles = changedFilesRaw + .split(/\r?\n/) + .map((f) => f.trim()) + .filter(Boolean); + + const bumps = []; + const allUpdatedFiles = new Set(); + + for (const component of VALID_COMPONENTS) { + const componentChanged = changedFiles.some((file) => + isComponentPath(component, file), + ); + if (!componentChanged) continue; + + const baseVersion = readVersionAtRef(baseRef, component); + if (!baseVersion) { + // Version file did not exist on base branch yet (initial adoption) + continue; + } + + const headVersion = readComponentVersion(component, ROOT_DIR); + if (headVersion !== baseVersion) { + // Already bumped on this branch relative to origin/main + continue; + } + + const commits = readComponentCommits( + component, + `${baseRef}..HEAD`, + ROOT_DIR, + ); + const bumpType = detectBumpTypeFromCommits(commits); + const result = bumpComponent(component, bumpType, { + rootDir: ROOT_DIR, + quiet: true, + }); + + bumps.push(result); + for (const file of result.updatedFiles) { + allUpdatedFiles.add(file); + } + } + + if (bumps.length === 0 || allUpdatedFiles.size === 0) { + process.exit(0); + } + + const summary = bumps.map((b) => `${b.component} ${b.to}`).join(", "); + const commitMsg = `chore(version): ${summary}`; + + try { + git(["add", "--", ...allUpdatedFiles], { stdio: "inherit" }); + git(["commit", "-S", "-m", commitMsg], { stdio: "inherit" }); + } catch (err) { + console.error( + `❌ pre-push: Failed to create signed version bump commit (${err.message}).`, + ); + console.error( + " Ensure your SSH/GPG signing key is configured (git commit -S).", + ); + process.exit(1); + } + + console.log(`✓ Created signed commit: "${commitMsg}"`); + + // Automatically push the updated HEAD so a manual 2nd `git push` is not required. + const hasUpstream = Boolean( + tryGit(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]), + ); + const refSpecs = branchPushes.map( + ({ localRef, remoteRef }) => `${localRef}:${remoteRef}`, + ); + const pushArgs = [ + "push", + ...(hasUpstream ? [] : ["-u"]), + remoteName, + ...refSpecs, + ]; + + console.log(`🚀 Automatically pushing bumped branch to ${remoteName}...`); + try { + execFileSync("git", pushArgs, { + cwd: ROOT_DIR, + stdio: "inherit", + env: { ...process.env, SKIP_VERSION_BUMP: "1" }, + }); + } catch { + console.error( + `❌ pre-push: Bump commit "${commitMsg}" was created locally, but the automatic push failed. Fix the error above and re-run 'git push'.`, + ); + process.exit(1); + } + + // Exit non-zero so the outer git push aborts cleanly instead of pushing the stale pre-bump SHA. + console.log(`\n✅ Branch bumped and pushed (${summary})!`); + console.log( + `â„šī¸ Git will display "failed to push some refs" below solely because the superseded pre-bump push was cancelled — your signed bump commit is already on ${remoteName}.`, + ); + process.exit(1); +} + +if (require.main === module) { + main(); +} + +module.exports = { parsePushRefs }; diff --git a/scripts/sync-version.js b/scripts/sync-version.js index 4cf7c0a6..4924a7ae 100644 --- a/scripts/sync-version.js +++ b/scripts/sync-version.js @@ -1,149 +1,232 @@ +#!/usr/bin/env node + const fs = require("node:fs"); const path = require("node:path"); -const { execFileSync } = require("node:child_process"); - -// 1. Determine running mode and target version -const isPreCommit = process.argv.includes("--pre-commit"); -let targetVersion = process.env.NEXT_PUBLIC_APP_VERSION; -if (!targetVersion && !isPreCommit && process.argv[2]) { - targetVersion = process.argv[2]; +const ROOT_DIR = path.join(__dirname, ".."); +const SEMVER_REGEX = /^\d+\.\d+\.\d+$/; +const VALID_COMPONENTS = ["web", "mobile", "backup"]; + +/** + * Parses a version string from file contents for a given component. + * Mobile pubspec may still contain a legacy `+build` suffix, which is stripped. + * @param {"web"|"mobile"|"backup"} component + * @param {string} content + * @returns {string | null} + */ +function parseComponentVersionContent(component, content) { + if (component === "web") { + const json = JSON.parse(content); + return typeof json.version === "string" && + SEMVER_REGEX.test(json.version.trim()) + ? json.version.trim() + : null; + } + if (component === "mobile") { + const match = /^version:\s*(\d+\.\d+\.\d+)(?:\+\d+)?/m.exec(content); + return match ? match[1] : null; + } + if (component === "backup") { + const trimmed = content.trim(); + return SEMVER_REGEX.test(trimmed) ? trimmed : null; + } + throw new Error(`Unknown component: ${component}`); } -// Pre-commit hook mode: automatically derive target version from package.json -const packageJsonPath = path.join(__dirname, "..", "package.json"); -if (isPreCommit) { - if (fs.existsSync(packageJsonPath)) { - const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8")); - targetVersion = packageJson.version; - } else { - console.log( - " Husky Pre-commit: package.json not found. Skipping version sync.", - ); - process.exit(0); +/** + * Returns the primary version-tracking file (relative to repo root) for a component. + * @param {"web"|"mobile"|"backup"} component + * @returns {string} + */ +function getPrimaryVersionFile(component) { + switch (component) { + case "web": + return "package.json"; + case "mobile": + return "mobile/pubspec.yaml"; + case "backup": + return "backup/VERSION"; + default: + throw new Error(`Unknown component: ${component}`); } } -// Fail-fast validation: ensure targetVersion is present and is a valid semver string -if (!targetVersion) { - console.error( - "❌ Error: Target version is missing. Please set NEXT_PUBLIC_APP_VERSION, provide a target version CLI argument, or run in --pre-commit mode.", - ); - process.exit(1); +/** + * Reads the current X.Y.Z version for a component from disk. + * @param {"web"|"mobile"|"backup"} component + * @param {string} [rootDir] + * @returns {string} + */ +function readComponentVersion(component, rootDir = ROOT_DIR) { + const relPath = getPrimaryVersionFile(component); + const fullPath = path.join(rootDir, relPath); + if (!fs.existsSync(fullPath)) { + throw new Error(`Version file not found for ${component}: ${relPath}`); + } + const content = fs.readFileSync(fullPath, "utf8"); + const version = parseComponentVersionContent(component, content); + if (!version) { + throw new Error(`Could not parse semver version from ${relPath}`); + } + return version; } -const semverRegex = /^\d+\.\d+\.\d+$/; -if (!semverRegex.test(targetVersion)) { - console.error( - `❌ Error: Invalid version format "${targetVersion}". Version must be a valid major.minor.patch semver string (e.g., "1.2.3").`, - ); - process.exit(1); +function updateFile(filePath, modifier, updatedFiles) { + if (!fs.existsSync(filePath)) return; + const original = fs.readFileSync(filePath, "utf8"); + const modified = modifier(original); + if (original !== modified) { + fs.writeFileSync(filePath, modified); + updatedFiles.push(filePath); + } } -console.log(`🚀 Syncing repository files to version v${targetVersion}...`); +/** + * Synchronizes all version-bearing files belonging to a single component. + * Never touches .env files, MIN_APP_VERSION, or other components. + * @param {"web"|"mobile"|"backup"} component + * @param {string} targetVersion + * @param {{ rootDir?: string, quiet?: boolean }} [options] + * @returns {{ component: string, version: string, updatedFiles: string[] }} + */ +function syncComponentVersion(component, targetVersion, options = {}) { + const rootDir = options.rootDir || ROOT_DIR; + const quiet = Boolean(options.quiet); + + if (!VALID_COMPONENTS.includes(component)) { + throw new Error( + `Invalid component "${component}". Expected one of: ${VALID_COMPONENTS.join(", ")}.`, + ); + } + if (!SEMVER_REGEX.test(targetVersion)) { + throw new Error( + `Invalid version format "${targetVersion}". Expected X.Y.Z semver string.`, + ); + } + + const updatedFiles = []; + + if (component === "web") { + updateFile( + path.join(rootDir, "package.json"), + (content) => { + const json = JSON.parse(content); + json.version = targetVersion; + return JSON.stringify(json, null, 2) + "\n"; + }, + updatedFiles, + ); + + updateFile( + path.join(rootDir, "package-lock.json"), + (content) => { + const json = JSON.parse(content); + json.version = targetVersion; + if (json.packages && json.packages[""]) { + json.packages[""].version = targetVersion; + } + return JSON.stringify(json, null, 2) + "\n"; + }, + updatedFiles, + ); -const updatedFiles = []; + updateFile( + path.join(rootDir, "public", "openapi", "openapi.yaml"), + (content) => + content.replace( + /^ {2}version:\s*\d+\.\d+\.\d+/m, + ` version: ${targetVersion}`, + ), + updatedFiles, + ); + } else if (component === "mobile") { + updateFile( + path.join(rootDir, "mobile", "pubspec.yaml"), + (content) => + content.replace( + /^version:\s*\d+\.\d+\.\d+(?:\+\d+)?/m, + `version: ${targetVersion}`, + ), + updatedFiles, + ); -// Helper to write file and track changes -function updateFile(filePath, modifier) { - if (fs.existsSync(filePath)) { - const original = fs.readFileSync(filePath, "utf8"); - const modified = modifier(original); - if (original !== modified) { - fs.writeFileSync(filePath, modified); - updatedFiles.push(filePath); - console.log(`✓ Updated ${path.basename(filePath)}`); + updateFile( + path.join(rootDir, "mobile", "lib", "config", "app_config.dart"), + (content) => + content.replace( + /('APP_VERSION',\s*defaultValue:\s*')\d+\.\d+\.\d+(')/g, + `$1${targetVersion}$2`, + ), + updatedFiles, + ); + } else if (component === "backup") { + const versionFile = path.join(rootDir, "backup", "VERSION"); + const nextContent = `${targetVersion}\n`; + const prevContent = fs.existsSync(versionFile) + ? fs.readFileSync(versionFile, "utf8") + : null; + if (prevContent !== nextContent) { + fs.writeFileSync(versionFile, nextContent); + updatedFiles.push(versionFile); } } + + if (!quiet) { + console.log( + `✓ Synced ${component} to v${targetVersion} (${updatedFiles.length} file(s) updated)`, + ); + } + + return { component, version: targetVersion, updatedFiles }; } -// 1. Update package.json -updateFile(packageJsonPath, (content) => { - const json = JSON.parse(content); - json.version = targetVersion; - return JSON.stringify(json, null, 2) + "\n"; -}); - -// 2. Update package-lock.json -const packageLockPath = path.join(__dirname, "..", "package-lock.json"); -updateFile(packageLockPath, (content) => { - const json = JSON.parse(content); - json.version = targetVersion; - if (json.packages && json.packages[""]) { - json.packages[""].version = targetVersion; +function parseCliArgs(argv) { + let component = null; + let version = null; + let quiet = false; + + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === "--quiet" || arg === "-q") { + quiet = true; + } else if (arg === "--component" || arg === "-c") { + component = argv[i + 1]; + i += 1; + } else if (arg.startsWith("--component=")) { + component = arg.slice("--component=".length); + } else if (!arg.startsWith("-")) { + if (!component && VALID_COMPONENTS.includes(arg)) { + component = arg; + } else if (!version) { + version = arg; + } + } } - return JSON.stringify(json, null, 2) + "\n"; -}); - -// 3. Update public/openapi/openapi.yaml -const openApiPath = path.join( - __dirname, - "..", - "public", - "openapi", - "openapi.yaml", -); -updateFile(openApiPath, (content) => { - return content.replace( - /^ {2}version:\s*\d+\.\d+\.\d+/m, - ` version: ${targetVersion}`, - ); -}); - -// 4. Update mobile/pubspec.yaml -const pubspecPath = path.join(__dirname, "..", "mobile", "pubspec.yaml"); -updateFile(pubspecPath, (content) => { - return content.replace( - /^version:\s*\d+\.\d+\.\d+\+\d+/m, - `version: ${targetVersion}+1`, - ); -}); - -// 6. Update environment files -[".example.env", ".env", ".env.local"].forEach((file) => { - const filePath = path.join(__dirname, "..", file); - updateFile(filePath, (content) => { - const res = content.replace( - /^(NEXT_PUBLIC_APP_VERSION=)\d+\.\d+\.\d+/gm, - `$1${targetVersion}`, - ); - return res.replace( - /^(MIN_APP_VERSION=)\d+\.\d+\.\d+/gm, - `$1${targetVersion}`, + + return { component, version, quiet }; +} + +if (require.main === module) { + const { component, version, quiet } = parseCliArgs(process.argv.slice(2)); + if (!component || !version) { + console.error( + "Usage: node scripts/sync-version.js --component ", ); - }); -}); - -// 7. Update mobile/lib/config/app_config.dart -const appConfigPath = path.join( - __dirname, - "..", - "mobile", - "lib", - "config", - "app_config.dart", -); -updateFile(appConfigPath, (content) => { - return content.replace( - /('APP_VERSION',\s*defaultValue:\s*')\d+\.\d+\.\d+(')/g, - `$1${targetVersion}$2`, - ); -}); - -// In pre-commit mode, stage all updated files automatically -if (isPreCommit && updatedFiles.length > 0) { - console.log( - "🚀 Husky Pre-commit: Staging auto-synchronized version files...", - ); - updatedFiles.forEach((file) => { - try { - /* eslint-disable-next-line */ - execFileSync("git", ["add", file]); - console.log(`✓ Staged ${path.basename(file)}`); - } catch { - console.error(`❌ Failed to stage ${path.basename(file)}`); - } - }); + process.exit(1); + } + try { + syncComponentVersion(component, version, { quiet }); + } catch (err) { + console.error(`❌ ${err.message}`); + process.exit(1); + } } -console.log(`🎉 Version sync complete!`); +module.exports = { + VALID_COMPONENTS, + SEMVER_REGEX, + getPrimaryVersionFile, + parseComponentVersionContent, + readComponentVersion, + syncComponentVersion, +}; diff --git a/src/app/(public)/build-info/__tests__/page.test.tsx b/src/app/(public)/build-info/__tests__/page.test.tsx index 745f0384..f0ce31f7 100644 --- a/src/app/(public)/build-info/__tests__/page.test.tsx +++ b/src/app/(public)/build-info/__tests__/page.test.tsx @@ -27,7 +27,7 @@ describe("BuildInfoPage", () => { // Set base environment variables using vi.stubEnv vi.stubEnv("APP_COMMIT_SHA", "abc123def456"); - vi.stubEnv("NEXT_PUBLIC_APP_VERSION", "1.8.0"); + vi.stubEnv("APP_VERSION", "1.8.0"); vi.stubEnv("BUILD_TIMESTAMP", "2026-02-18T15:30:45Z"); vi.stubEnv("GITHUB_REPOSITORY", "owner/repo"); vi.stubEnv("GITHUB_RUN_ID", "12345"); diff --git a/src/app/(public)/build-info/page.tsx b/src/app/(public)/build-info/page.tsx index ee7d8b1f..17a65810 100644 --- a/src/app/(public)/build-info/page.tsx +++ b/src/app/(public)/build-info/page.tsx @@ -62,7 +62,7 @@ function getBuildMeta(): BuildMeta { github_run_id: githubRunId, github_run_number: githubRunNumber, github_repo: githubRepo, - app_version: process.env.NEXT_PUBLIC_APP_VERSION ?? "dev", + app_version: process.env.APP_VERSION ?? "dev", image_digest: imageDigest, container: !!process.env.APP_COMMIT_SHA && diff --git a/src/app/api/provenance/__tests__/route.test.ts b/src/app/api/provenance/__tests__/route.test.ts index bba93b3b..ebfcc956 100644 --- a/src/app/api/provenance/__tests__/route.test.ts +++ b/src/app/api/provenance/__tests__/route.test.ts @@ -20,7 +20,7 @@ function makeFullRequest(): NextRequest { describe("Provenance API Route", () => { const originalCommitSha = process.env.APP_COMMIT_SHA; - const originalAppVersion = process.env.NEXT_PUBLIC_APP_VERSION; + const originalAppVersion = process.env.APP_VERSION; const originalGithubRunId = process.env.GITHUB_RUN_ID; const originalGithubRunNumber = process.env.GITHUB_RUN_NUMBER; const originalGithubRepository = process.env.GITHUB_REPOSITORY; @@ -33,7 +33,7 @@ describe("Provenance API Route", () => { afterEach(() => { const envs = [ ["APP_COMMIT_SHA", originalCommitSha], - ["NEXT_PUBLIC_APP_VERSION", originalAppVersion], + ["APP_VERSION", originalAppVersion], ["GITHUB_RUN_ID", originalGithubRunId], ["GITHUB_RUN_NUMBER", originalGithubRunNumber], ["GITHUB_REPOSITORY", originalGithubRepository], @@ -76,7 +76,7 @@ describe("Provenance API Route", () => { }); it("should return app version from environment", async () => { - process.env.NEXT_PUBLIC_APP_VERSION = "3.0.0"; + process.env.APP_VERSION = "3.0.0"; const response = GET(makeRequest()); const data = await response.json(); @@ -85,7 +85,7 @@ describe("Provenance API Route", () => { }); it("should return 'dev' for app version when not set", async () => { - delete process.env.NEXT_PUBLIC_APP_VERSION; + delete process.env.APP_VERSION; const response = GET(makeRequest()); const data = await response.json(); diff --git a/src/app/api/provenance/route.ts b/src/app/api/provenance/route.ts index 41a653dd..077a6271 100644 --- a/src/app/api/provenance/route.ts +++ b/src/app/api/provenance/route.ts @@ -28,7 +28,7 @@ export function GET(req: Request) { commit: commitSha, commit_sha: commitSha, build_id: githubRunId || commitSha, - app_version: process.env.NEXT_PUBLIC_APP_VERSION ?? "dev", + app_version: process.env.APP_VERSION ?? "dev", image_digest: imageDigest, container: Boolean( process.env.APP_COMMIT_SHA && diff --git a/src/app/api/security/attestation/__tests__/route.test.ts b/src/app/api/security/attestation/__tests__/route.test.ts index 60990745..eaba3ef9 100644 --- a/src/app/api/security/attestation/__tests__/route.test.ts +++ b/src/app/api/security/attestation/__tests__/route.test.ts @@ -18,7 +18,7 @@ describe("GET /api/security/attestation", () => { vi.clearAllMocks(); process.env.FIREBASE_APP_ID_ANDROID = "android-app-id"; process.env.FIREBASE_APP_ID_IOS = "ios-app-id"; - process.env.NEXT_PUBLIC_APP_VERSION = "3.0.8"; + process.env.LATEST_APP_VERSION = "3.0.8"; process.env.MIN_APP_VERSION = "3.0.8"; }); @@ -137,7 +137,7 @@ describe("GET /api/security/attestation", () => { }); it("clamps latestVersion to minVersion when latestVersion is older than minVersion", async () => { - process.env.NEXT_PUBLIC_APP_VERSION = "4.2.9"; + process.env.LATEST_APP_VERSION = "4.2.9"; process.env.MIN_APP_VERSION = "4.7.0"; const { getAppCheck } = await import("@/lib/firebase/admin"); @@ -172,7 +172,7 @@ describe("GET /api/security/attestation", () => { }); it("keeps latestVersion when it is newer than minVersion", async () => { - process.env.NEXT_PUBLIC_APP_VERSION = "4.7.1"; + process.env.LATEST_APP_VERSION = "4.7.1"; process.env.MIN_APP_VERSION = "4.7.0"; const { getAppCheck } = await import("@/lib/firebase/admin"); @@ -198,7 +198,7 @@ describe("GET /api/security/attestation", () => { }); it("uses MIN_APP_VERSION when present", async () => { - process.env.NEXT_PUBLIC_APP_VERSION = "4.2.9"; + process.env.LATEST_APP_VERSION = "4.2.9"; process.env.MIN_APP_VERSION = "4.3.0"; const { getAppCheck } = await import("@/lib/firebase/admin"); @@ -223,6 +223,32 @@ describe("GET /api/security/attestation", () => { expect(data.latestVersion).toBe("4.3.0"); }); + it("falls back latestVersion to MIN_APP_VERSION when LATEST_APP_VERSION is unset", async () => { + delete process.env.LATEST_APP_VERSION; + process.env.MIN_APP_VERSION = "4.7.2"; + + const { getAppCheck } = await import("@/lib/firebase/admin"); + vi.mocked(getAppCheck).mockReturnValue({ + verifyToken: vi.fn().mockResolvedValue({ + appId: "android-app-id", + token: { iss: "test-iss", app_id: "android-app-id" }, + }), + } as never); + + const req = new NextRequest("http://localhost/api/security/attestation", { + method: "GET", + headers: { + "X-Firebase-AppCheck": "valid-token", + }, + }); + + const res = await GET(req); + const data = await res.json(); + + expect(data.minVersion).toBe("4.7.2"); + expect(data.latestVersion).toBe("4.7.2"); + }); + it("returns 429 when rate limit is exceeded", async () => { const { authRateLimiter } = await import("@/lib/ratelimit"); vi.mocked(authRateLimiter.limit).mockResolvedValueOnce({ diff --git a/src/app/api/security/attestation/route.ts b/src/app/api/security/attestation/route.ts index a13718cc..97fe61f5 100644 --- a/src/app/api/security/attestation/route.ts +++ b/src/app/api/security/attestation/route.ts @@ -65,8 +65,8 @@ export async function GET(req: Request | NextRequest) { } } - const minVersion = process.env.MIN_APP_VERSION || "3.0.8"; - let latestVersion = process.env.NEXT_PUBLIC_APP_VERSION || "3.0.8"; + const minVersion = process.env.MIN_APP_VERSION || "4.7.2"; + let latestVersion = process.env.LATEST_APP_VERSION || minVersion; if (isVersionOlder(latestVersion, minVersion)) { latestVersion = minVersion; diff --git a/src/components/layout/__tests__/footer.test.tsx b/src/components/layout/__tests__/footer.test.tsx index c53083e2..688abe8d 100644 --- a/src/components/layout/__tests__/footer.test.tsx +++ b/src/components/layout/__tests__/footer.test.tsx @@ -7,13 +7,13 @@ vi.mock("@/lib/logger", () => ({ })); describe("Footer", () => { - it("displays the version from NEXT_PUBLIC_APP_VERSION", () => { - vi.stubEnv("NEXT_PUBLIC_APP_VERSION", "1.9.2"); + it("displays the version from APP_VERSION", () => { + vi.stubEnv("APP_VERSION", "1.9.2"); render(