From 69d3e2342e2b6d54643721aa39c608bf27a35821 Mon Sep 17 00:00:00 2001 From: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com> Date: Wed, 7 Oct 2026 19:56:17 -0400 Subject: [PATCH 01/12] =?UTF-8?q?=F0=9F=90=9B=20[fix]=20Repair=20macOS=20s?= =?UTF-8?q?ignatures=20and=20verify=20packaged=20startup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿ› [fix] Sign final macOS bundles after fuse mutation and Universal merging, and verify signature integrity even without publisher credentials. ๐Ÿ› [fix] Deliver the MapLibre factory across the renderer vendor boundary and load its self-contained worker with the production file origin and CSP. ๐Ÿงช [test] Require renderer initialization, preload IPC, FIT parsing, a visible route, and a fresh completion report from packaged smoke launches. ๐Ÿ‘ท [build] Exercise real distributables across Linux, Windows x64 and ia32, and macOS ARM64, Intel, and Universal; protect existing Windows installations and retain failure evidence. ๐Ÿ‘ท [build] Validate updater payload metadata, pin changelog and upgrade workflow revisions, and retain screenshots and logs for installer upgrades. ๐Ÿงน [chore] Update Electron, Electron Builder, MapLibre, DOMPurify, and affected build dependencies while retaining the existing audit thresholds. ๐Ÿ“ [docs] Describe release rehearsals, ad hoc signing, integrity verification, and explicit manual publication. --- .github/workflows/Build.yml | 86 ++-- .github/workflows/candidate-upgrade-smoke.yml | 17 +- .github/workflows/published-upgrade-smoke.yml | 19 +- .github/workflows/release-rehearsal.yml | 79 +++- docs/DEVELOPMENT_GUIDE.md | 62 ++- docusaurus/docs/development/build-release.md | 92 ++-- docusaurus/package-lock.json | 91 ++-- docusaurus/package.json | 5 +- electron-app/main.ts | 2 + electron-app/main/runtime/packagedSmoke.ts | 189 ++++++++ electron-app/renderer/rendererVendorMap.ts | 23 +- electron-app/renderer/rendererVendorShared.ts | 2 + electron-app/renderer/vendorBundleLoader.ts | 5 +- electron-builder.config.cjs | 12 + package-lock.json | 404 +++++++---------- package.json | 21 +- packaging/macos/entitlements.adhoc.plist | 12 + renderer-style-imports.d.ts | 5 + scripts/build-ci-matrix.mjs | 82 +--- scripts/commit-changelog-workflow.mjs | 7 +- scripts/get-windows-install-registrations.ps1 | 38 ++ scripts/run-distributable-smoke.mjs | 356 +++++++++++++++ scripts/run-electron-builder.mjs | 3 + scripts/run-packaged-smoke.mjs | 142 ++++-- scripts/verify-release-assets.mjs | 59 ++- scripts/verify-signed-artifacts.mjs | 33 +- tests/playwright/app-ui.spec.ts | 159 +++++++ .../packaging/architectureBoundaries.test.ts | 2 +- tests/unit/packaging/buildCiMatrix.test.ts | 29 ++ .../candidateUpgradeWorkflow.test.ts | 13 +- .../packaging/commitChangelogWorkflow.test.ts | 2 +- .../packaging/electronBuilderConfig.test.ts | 41 ++ .../packaging/packagedSmokeRuntime.test.ts | 175 ++++++++ .../publishedUpgradeWorkflow.test.ts | 18 +- .../releaseRehearsalWorkflow.test.ts | 13 +- .../packaging/runDistributableSmoke.test.ts | 418 ++++++++++++++++++ .../unit/packaging/runElectronBuilder.test.ts | 38 ++ tests/unit/packaging/runPackagedSmoke.test.ts | 354 ++++++++------- .../packaging/verifyReleaseAssets.test.ts | 175 ++++++++ .../packaging/verifySignedArtifacts.test.ts | 171 ++++++- .../workspacePackageBoundaries.test.ts | 7 +- .../renderer/rendererVendorShared.test.ts | 5 +- .../unit/renderer/vendorBundleLoader.test.ts | 29 +- 43 files changed, 2798 insertions(+), 697 deletions(-) create mode 100644 electron-app/main/runtime/packagedSmoke.ts create mode 100644 packaging/macos/entitlements.adhoc.plist create mode 100644 scripts/get-windows-install-registrations.ps1 create mode 100644 scripts/run-distributable-smoke.mjs create mode 100644 tests/unit/packaging/packagedSmokeRuntime.test.ts create mode 100644 tests/unit/packaging/runDistributableSmoke.test.ts diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index d8546bf63..3de27ba56 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -3,7 +3,7 @@ run-name: Build and Release Electron App (${{ github.ref_name }}) concurrency: group: build-${{ github.ref }} - cancel-in-progress: true + cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }} on: workflow_dispatch: @@ -137,48 +137,21 @@ jobs: # Keep this aligned with the known-good workflow pattern. NODE_OPTIONS: --max_old_space_size=8192 strategy: + fail-fast: ${{ github.event_name == 'pull_request' }} matrix: - os: - - ubuntu-latest - - ubuntu-24.04-arm - - windows-latest - - macos-15 - - macos-latest - - macos-15-intel - - arch: [x64, ia32, arm64] - exclude: - # Exclude macOS with ia32 architecture as it is not supported by Electron - - os: macos-latest - arch: ia32 - - os: macos-latest - arch: arm64 - - os: macos-15 - arch: ia32 - - os: macos-15 - arch: x64 - - os: macos-15-intel - arch: ia32 - - os: macos-15-intel - arch: arm64 - # Exclude Ubuntu with ia32 and arm64 architectures as they are not commonly used and not officially supported except for ubuntu-24.04-arm/arm64 - - os: ubuntu-latest - arch: ia32 + include: - os: ubuntu-latest - arch: arm64 - # Exclude ubuntu-24.04-arm with x64 and ia32 - - os: ubuntu-24.04-arm arch: x64 - - os: ubuntu-24.04-arm - arch: ia32 - - os: ubuntu-24.04-arm - arch: arm64 - # Exclude Windows with arm64 (not supported) - os: windows-latest + arch: x64 + - os: windows-latest + arch: ia32 + - os: macos-15 arch: arm64 - # Exclude Windows with ia32 (if not supported, uncomment) - # - os: windows-latest - # arch: ia32 + - os: macos-latest + arch: universal + - os: macos-15-intel + arch: x64 steps: - name: Harden the runner (Audit all outbound calls) uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4 @@ -324,9 +297,39 @@ jobs: npm run test:packaged fi env: - FFV_PACKAGED_SMOKE_TIMEOUT_MS: "15000" + FFV_PACKAGED_SMOKE_TIMEOUT_MS: "60000" RUNNER_OS: ${{ runner.os }} + - name: Enable Intel slice testing on Apple Silicon + if: runner.os == 'macOS' && matrix.arch == 'universal' + shell: bash + run: softwareupdate --install-rosetta --agree-to-license + + - name: Smoke test installed distributable artifacts + shell: bash + run: | + if [ "$RUNNER_OS" = "Linux" ]; then + xvfb-run -a node scripts/run-distributable-smoke.mjs + else + node scripts/run-distributable-smoke.mjs + fi + env: + CI: true + FFV_PACKAGED_SMOKE_TIMEOUT_MS: "60000" + MATRIX_ARCH: ${{ matrix.arch }} + RUNNER_OS: ${{ runner.os }} + + - name: Upload distributable smoke diagnostics + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: smoke-diagnostics-${{ matrix.os }}-${{ matrix.arch }} + path: | + release-dist/distributable-smoke-*.json + release-dist/smoke-diagnostics/** + if-no-files-found: ignore + retention-days: 14 + - name: Print distributable hashes (debug) id: print_hashes shell: bash @@ -394,6 +397,7 @@ jobs: - name: Download all build artifacts from build job uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: + pattern: dist-* path: ./artifacts - name: Print artifact hashes (debug) @@ -449,8 +453,6 @@ jobs: body: | ## ๐Ÿš€ Release Notes - This release removes the unused Squirrel.Windows packaging path so the Windows installers and portable build no longer bundle its ExecutionStub helper. - ${{ inputs.require-code-signing && 'Windows and macOS release artifacts were built with required code signing.' || 'Release artifacts are intentionally unsigned, consistent with previous FitFileViewer releases.' }} ${{ steps.release_notes.outputs.notes }} @@ -591,7 +593,7 @@ jobs: - name: Checkout repository uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 with: - ref: main + ref: ${{ needs.bump-version.outputs.bump_sha }} fetch-depth: 0 fetch-tags: true diff --git a/.github/workflows/candidate-upgrade-smoke.yml b/.github/workflows/candidate-upgrade-smoke.yml index c538f7114..1a505219e 100644 --- a/.github/workflows/candidate-upgrade-smoke.yml +++ b/.github/workflows/candidate-upgrade-smoke.yml @@ -85,7 +85,7 @@ jobs: $installer = Resolve-Path ( "release-inputs/Fit-File-Viewer-nsis-x64-$env:FROM_VERSION.exe" ) - $process = Start-Process -FilePath $installer ` + $process = Start-Process -WindowStyle Hidden -FilePath $installer ` -ArgumentList @("/S", "/D=$env:FFV_UPGRADE_INSTALL_DIR") ` -Wait -PassThru if ($process.ExitCode -ne 0) { @@ -117,7 +117,7 @@ jobs: $candidate = Resolve-Path ( "release-dist/Fit-File-Viewer-nsis-x64-$env:FFV_CANDIDATE_VERSION.exe" ) - $process = Start-Process -FilePath $candidate ` + $process = Start-Process -WindowStyle Hidden -FilePath $candidate ` -ArgumentList @("/S", "--updated") -Wait -PassThru if ($process.ExitCode -ne 0) { throw "Candidate installer exited with $($process.ExitCode)." @@ -176,10 +176,14 @@ jobs: } - name: Smoke test upgraded executable + env: + FFV_SMOKE_EXPECTED_ARCH: x64 + FFV_SMOKE_EXPECTED_VERSION: ${{ env.FFV_CANDIDATE_VERSION }} + FFV_SMOKE_DIAGNOSTICS_DIRECTORY: ${{ runner.temp }}/candidate-upgrade-smoke run: >- node scripts/run-packaged-smoke.mjs --executable "$env:FFV_UPGRADE_EXECUTABLE" - --startup-timeout-ms 15000 + --startup-timeout-ms 60000 - name: Upload candidate upgrade evidence if: always() @@ -187,7 +191,10 @@ jobs: with: name: candidate-upgrade-evidence-${{ inputs.from-version }} if-no-files-found: ignore - path: ${{ runner.temp }}/candidate-upgrade-registry.json + retention-days: 14 + path: | + ${{ runner.temp }}/candidate-upgrade-registry.json + ${{ runner.temp }}/candidate-upgrade-smoke/ - name: Clean up isolated installation if: always() @@ -198,5 +205,5 @@ jobs: "Uninstall Fit File Viewer.exe" ) if (Test-Path -LiteralPath $uninstaller -PathType Leaf) { - Start-Process -FilePath $uninstaller -ArgumentList "/S" -Wait + Start-Process -WindowStyle Hidden -FilePath $uninstaller -ArgumentList "/S" -Wait } diff --git a/.github/workflows/published-upgrade-smoke.yml b/.github/workflows/published-upgrade-smoke.yml index 149605bfc..81ccc0dbc 100644 --- a/.github/workflows/published-upgrade-smoke.yml +++ b/.github/workflows/published-upgrade-smoke.yml @@ -13,7 +13,7 @@ on: required: false type: string workflow_run: - workflows: ["Build And Release Electron App"] + workflows: ["Build and Release Electron App"] types: - completed branches: @@ -44,6 +44,11 @@ jobs: - name: Checkout repository uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + # The release source revision precedes its automated version bump. + # Validate the installed release version independently below. + ref: ${{ github.event.workflow_run.head_sha || github.sha }} + - name: Set up Node.js uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 with: @@ -114,7 +119,7 @@ jobs: "FFV_UPGRADE_EVIDENCE=$evidence" >> $env:GITHUB_ENV "FFV_UPGRADE_INSTALL_DIR=$installDirectory" >> $env:GITHUB_ENV - $process = Start-Process -FilePath $installer -ArgumentList @("/S", "/D=$installDirectory") -Wait -PassThru + $process = Start-Process -WindowStyle Hidden -FilePath $installer -ArgumentList @("/S", "/D=$installDirectory") -Wait -PassThru if ($process.ExitCode -ne 0) { throw "Previous installer exited with $($process.ExitCode)." } @@ -191,10 +196,14 @@ jobs: } - name: Smoke test upgraded executable + env: + FFV_SMOKE_EXPECTED_ARCH: x64 + FFV_SMOKE_EXPECTED_VERSION: ${{ env.FFV_UPGRADE_TO_VERSION }} + FFV_SMOKE_DIAGNOSTICS_DIRECTORY: ${{ runner.temp }}/published-upgrade-smoke run: | Get-Process -Name "Fit File Viewer" -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue - node scripts/run-packaged-smoke.mjs --executable "$env:FFV_UPGRADE_EXECUTABLE" --startup-timeout-ms 15000 + node scripts/run-packaged-smoke.mjs --executable "$env:FFV_UPGRADE_EXECUTABLE" --startup-timeout-ms 60000 - name: Collect upgrade diagnostics if: always() @@ -227,11 +236,13 @@ jobs: uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: published-windows-upgrade-evidence + retention-days: 14 if-no-files-found: ignore path: | ${{ runner.temp }}/upgrade-handoff.json ${{ runner.temp }}/upgrade-registry.json ${{ runner.temp }}/published-upgrade-evidence/ + ${{ runner.temp }}/published-upgrade-smoke/ test-results/ - name: Clean up isolated installation @@ -244,6 +255,6 @@ jobs: "Uninstall Fit File Viewer.exe" ) if (Test-Path -LiteralPath $uninstaller -PathType Leaf) { - Start-Process -FilePath $uninstaller -ArgumentList "/S" -Wait + Start-Process -WindowStyle Hidden -FilePath $uninstaller -ArgumentList "/S" -Wait } } diff --git a/.github/workflows/release-rehearsal.yml b/.github/workflows/release-rehearsal.yml index a95dcac32..752d8fda3 100644 --- a/.github/workflows/release-rehearsal.yml +++ b/.github/workflows/release-rehearsal.yml @@ -19,7 +19,7 @@ on: smoke-timeout-ms: description: "Packaged app smoke timeout in milliseconds" required: true - default: "15000" + default: "60000" type: string fail-fast: description: "Cancel remaining platform rehearsals after the first failure" @@ -35,7 +35,7 @@ permissions: jobs: release-rehearsal: - name: Verify Unsigned Release Package (${{ matrix.runner-os }}) + name: Verify Unsigned Release Package (${{ matrix.os }}, ${{ matrix.arch }}) runs-on: ${{ matrix.os }} timeout-minutes: 60 strategy: @@ -44,13 +44,23 @@ jobs: include: - os: ubuntu-latest runner-os: Linux + arch: x64 release-verify-command: xvfb-run -a npm run release:verify - os: windows-latest runner-os: Windows - release-verify-command: npm run release:verify + arch: x64 + - os: windows-latest + runner-os: Windows + arch: ia32 - os: macos-latest runner-os: macOS - release-verify-command: npm run release:verify + arch: universal + - os: macos-15 + runner-os: macOS + arch: arm64 + - os: macos-15-intel + runner-os: macOS + arch: x64 env: CI: true NODE_OPTIONS: --max_old_space_size=8192 @@ -111,6 +121,7 @@ jobs: WIN_CSC_LINK: ${{ matrix.runner-os == 'Windows' && secrets.WINDOWS_CSC_LINK || '' }} - name: Run release verification and packaged smoke + if: runner.os == 'Linux' run: | ${{ matrix.release-verify-command }} & verify_pid=$! @@ -128,6 +139,57 @@ jobs: REQUIRE_CODE_SIGNING: "false" RUNNER_OS: ${{ matrix.runner-os }} + - name: Install platform build dependencies + run: node scripts/install-build-dependencies.mjs + + - name: Install dmg-license workaround for Mac Builder + if: runner.os == 'macOS' + run: npm run build:macos-deps + + - name: Build actual release distributables without publishing + run: npm run build:ci-matrix + env: + MATRIX_ARCH: ${{ matrix.arch }} + MATRIX_OS: ${{ matrix.os }} + RUNNER_OS: ${{ matrix.runner-os }} + REQUIRE_CODE_SIGNING: "false" + CSC_IDENTITY_AUTO_DISCOVERY: "false" + FFV_FORCE_UNSIGNED_PACKAGE: "true" + + - name: Verify release artifact signing policy + if: runner.os == 'Windows' || runner.os == 'macOS' + run: npm run release:verify-signing-artifacts -- --runner-os "$RUNNER_OS" + env: + REQUIRE_CODE_SIGNING: "false" + RUNNER_OS: ${{ matrix.runner-os }} + + - name: Enable Intel slice testing on Apple Silicon + if: runner.os == 'macOS' && matrix.arch == 'universal' + run: softwareupdate --install-rosetta --agree-to-license + + - name: Smoke test installed distributable artifacts + run: | + if [ "$RUNNER_OS" = "Linux" ]; then + xvfb-run -a node scripts/run-distributable-smoke.mjs + else + node scripts/run-distributable-smoke.mjs + fi + env: + FFV_PACKAGED_SMOKE_TIMEOUT_MS: ${{ inputs.smoke-timeout-ms }} + MATRIX_ARCH: ${{ matrix.arch }} + RUNNER_OS: ${{ matrix.runner-os }} + + - name: Upload distributable smoke diagnostics + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: smoke-diagnostics-${{ matrix.os }}-${{ matrix.arch }} + path: | + release-dist/distributable-smoke-*.json + release-dist/smoke-diagnostics/** + if-no-files-found: ignore + retention-days: 14 + - name: List unsigned rehearsal artifacts if: always() run: npm run release:list-release-dist-files @@ -136,7 +198,12 @@ jobs: if: success() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: release-rehearsal-${{ matrix.runner-os }} - path: release-dist/** + name: release-rehearsal-${{ matrix.os }}-${{ matrix.arch }} + path: | + release-dist/Fit-File-Viewer-* + release-dist/latest*.yml + release-dist/*-report.json + release-dist/distributable-smoke-*.json + retention-days: 7 if-no-files-found: error include-hidden-files: true diff --git a/docs/DEVELOPMENT_GUIDE.md b/docs/DEVELOPMENT_GUIDE.md index 7966796f3..97f706c14 100644 --- a/docs/DEVELOPMENT_GUIDE.md +++ b/docs/DEVELOPMENT_GUIDE.md @@ -417,25 +417,28 @@ npm run build -- --mac npm run build -- --linux # Publish release (automated via GitHub Actions) -# Triggered by creating a new release tag +# Dispatch Build and Release Electron App with the target branch and release type. ``` ### Signing Preflight -`npm run verify:release` runs `npm run release:check-signing` before unsigned -local packaging. Use `npm run release:check-signing:required` before ad hoc -signed packaging; it fails before electron-builder starts and lists each -missing variable. +`npm run verify:release` runs `npm run release:check-signing` before local +packaging. Use `npm run release:check-signing:required` before packaging with +Windows publisher or Apple Developer ID certificates; it fails before +electron-builder starts and lists each missing variable. macOS ad hoc signing +does not need publisher credentials. - Local `npm run package`, `npm run package:unsigned`, and release rehearsal - builds are unsigned by default. The electron-builder wrapper strips signing - variables and disables Windows executable signing unless - `REQUIRE_CODE_SIGNING=true`. -- Production releases are also unsigned by default, matching the project's - historical release policy. The **Build And Release Electron App** workflow - exposes a `require-code-signing` input; leave it `false` for the normal - unsigned release path and set it to `true` only after the required Windows - and macOS credentials have been configured. + builds do not use publisher credentials by default. The electron-builder + wrapper strips those credentials and disables Windows executable signing + unless `REQUIRE_CODE_SIGNING=true`. macOS bundles receive an ad hoc signature + after all executable changes, including the final Universal merge. This + maintains the signature integrity required by Apple Silicon; it does not + provide a trusted publisher identity or notarization. +- Production releases follow the same default policy. The **Build and Release + Electron App** workflow exposes a `require-code-signing` input; leave it + `false` for the normal release path and set it to `true` only after the + required Windows and macOS credentials have been configured. - Select `release-type=patch`, `minor`, or `major` explicitly when dispatching the production workflow. Patch is the default and increments only the final SemVer component. @@ -450,6 +453,11 @@ missing variable. - Electron fuses are applied from the electron-builder `afterPack` hook. That keeps fuse mutation before signing and artifact creation, so signed builds are not modified by a separate post-packaging step. +- The ad hoc macOS entitlement file enables Electron's JIT and allows its + nested libraries to load without a publisher Team ID. Signature integrity + verification remains mandatory for ad hoc bundles and every architecture + inside Universal bundles. Removing quarantine attributes with `xattr` cannot + repair a signature invalidated by later binary changes. - Use `npm run verify:release:signed` when signing credentials are available and you want the full signed release path in one command: fast verification, docs build, audit, Playwright smoke, signed packaging, signature artifact @@ -477,13 +485,16 @@ missing variable. also recognizes the short-lived v30 identity and removes its stale registry entry after a successful upgrade. -After signed Windows or macOS packaging completes, use +After macOS packaging or signed Windows packaging completes, use `npm run release:verify-signing-artifacts` to verify the produced artifacts. `npm run verify:release:signed` runs that verifier automatically after signed packaging. The release matrix runs this automatically after `build:ci-matrix`: Windows artifacts are checked with `Get-AuthenticodeSignature`, and macOS `.app` -bundles are checked with `codesign --verify --deep --strict`. The verifier +bundles are checked with `codesign --verify --deep --strict --all-architectures`. +macOS integrity verification also runs when publisher signing is disabled; +required publisher builds additionally verify an Apple Developer ID certificate +requirement. The verifier writes `release-dist/signing-verification-report.json`, and the release workflow uploads that report with the platform artifacts so the signed files, status, platform, verifier command, sanitized verifier arguments, and per-file @@ -494,16 +505,27 @@ results to the job summary through `GITHUB_STEP_SUMMARY`. ### Release Rehearsal Before tagging a release, run the manual GitHub Actions workflow **Release -Rehearsal** from the target branch or tag. It runs the full release gate across -Linux, Windows, and macOS, checks signing availability without publishing, -builds unsigned artifacts, runs packaged startup smoke checks, and uploads the -`release-dist` outputs as workflow artifacts. +Rehearsal** from the target branch or tag. It runs the full release gate and +builds the distribution matrix without publishing: Linux x64, Windows x64 and +ia32, and macOS ARM64, Intel, and Universal. Artifact checks install or extract +the resulting distributions into fresh temporary directories and launch those +copies. macOS DMG copies are signature-verified before launch, and Universal +checks exercise both architectures. The rehearsal packaging step sets `FFV_FORCE_UNSIGNED_PACKAGE=true` and `CSC_IDENTITY_AUTO_DISCOVERY=false`, so it strips signing variables before electron-builder starts. Keep this separate from signed release packaging; use the signing preflight to prove credentials are present, then build rehearsal -artifacts unsigned. +artifacts without publisher credentials. macOS ad hoc signing and integrity +verification still run. + +The packaged smoke test uses an isolated application profile and an explicit +self-test mode. A successful process exit must be accompanied by a matching +structured report confirming a visible window, initialized renderer, working +file IPC, and a parsed FIT fixture. Unexpected signals, early exits, missing +reports, and timeouts fail the check. Logs, a window screenshot, and the report +are retained for diagnosis. This test does not enable remote debugging or +weaken the production Electron fuses. Run **Candidate Windows Upgrade Smoke** from the release branch for both the latest published version and the `29.9.0` migration baseline. It builds an diff --git a/docusaurus/docs/development/build-release.md b/docusaurus/docs/development/build-release.md index 768563641..50ae2b20c 100644 --- a/docusaurus/docs/development/build-release.md +++ b/docusaurus/docs/development/build-release.md @@ -103,55 +103,39 @@ module.exports = { ## CI/CD Pipeline -Builds are automated via GitHub Actions: - -```yaml -# .github/workflows/Build.yml -name: Build -on: - push: - branches: [main] - release: - types: [published] - -jobs: - build: - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, windows-latest, macos-latest] - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - - run: npm ci - - run: npm run build -``` +The manual **Release Rehearsal** workflow runs the full release gate and builds +the real distribution matrix without publishing: Linux x64, Windows x64 and +ia32, and macOS ARM64, Intel, and Universal. The production workflow is +**Build and Release Electron App** in `.github/workflows/Build.yml`. + +Each platform verifies its build output and exercises the distributable: +macOS mounts the DMG, copies the app to a fresh location, verifies every +architecture's signature, and launches through both the executable and +LaunchServices. Universal builds exercise ARM64 and x64. Windows checks its +ZIP, NSIS installer, and portable executable; Linux checks its tarball and +extracted AppImage. Reports, screenshots, logs, and artifact hashes are saved +as workflow diagnostics. ## Release Process -### 1. Update Version +### 1. Validate the Candidate -```bash -# Update the Electron app version -npm run release:bump-version -``` +Run `npm run release:verify`, then dispatch **Release Rehearsal** on the +candidate branch. Check every platform result and the Windows installer +upgrade workflow before publishing. -### 2. Update Changelog +The packaged smoke test requires a fresh completion report after renderer +initialization, preload IPC, real FIT decoding, and visible map rendering. +Crashes, signals, timeouts, and missing or stale reports fail the test. -```bash -npm run changelog -``` +### 2. Publish -### 3. Create Release +Dispatch **Build and Release Electron App** with the target `branch` and +`release-type` (`patch`, `minor`, or `major`). The workflow creates the version +commit and tag, builds and verifies the artifacts, publishes the release, and +updates the changelog on that branch. -```bash -# Push tag -git push --tags - -# GitHub Actions builds and publishes -``` - -### 4. Verify Release +### 3. Verify Release Check GitHub Releases for: @@ -159,21 +143,29 @@ Check GitHub Releases for: - Checksums - Release notes +The release asset verifier checks updater metadata references, including +architecture-specific web installer payloads, against asset sizes and hashes. +The published upgrade workflow verifies installation over previous releases. + ## Code Signing Run `npm run release:check-signing` before signed packaging when `REQUIRE_CODE_SIGNING=true`. The command reports missing variables before electron-builder starts. -Local and rehearsal builds are unsigned by default: +Local and rehearsal builds do not use publisher credentials by default: ```bash npm run package npm run package:unsigned ``` -Production releases follow the same unsigned-by-default policy. The **Build -And Release Electron App** workflow exposes a `require-code-signing` input; +macOS bundles still receive ad hoc signatures after fuse changes and the final +Universal merge. Apple Silicon requires valid signature integrity; ad hoc +signing does not provide a trusted publisher identity or notarization. + +Production releases follow the same default policy. The **Build +and Release Electron App** workflow exposes a `require-code-signing` input; leave it disabled for the established release path and enable it only after the Windows and macOS signing credentials have been configured. @@ -228,7 +220,7 @@ Linux release builds do not require signing variables. Windows 7 compatibility is limited to carried-forward legacy release assets from `build-win7.yml`; the current app is not rebuilt for Windows 7. -After signed Windows or macOS packaging, run: +After macOS packaging or signed Windows packaging, run: ```bash npm run release:verify-signing-artifacts @@ -244,9 +236,13 @@ That command runs fast checks, the docs build, audit, Playwright smoke, signed packaging, signature artifact verification, and packaged smoke in order. The verifier checks Windows `.exe` and `.msi` files with -`Get-AuthenticodeSignature`, checks macOS `.app` bundles with `codesign`, and -writes `release-dist/signing-verification-report.json`. The primary release -workflow uploads that report with the platform artifacts. +`Get-AuthenticodeSignature` when publisher signing is required. It always +checks macOS `.app` bundles with +`codesign --verify --deep --strict --all-architectures`; required publisher +builds additionally verify the Apple Developer ID certificate requirement. +It writes `release-dist/signing-verification-report.json`. The primary release +workflow uploads that report with the platform artifacts. Removing quarantine +attributes with `xattr` cannot repair an invalid executable signature. ## Troubleshooting Builds diff --git a/docusaurus/package-lock.json b/docusaurus/package-lock.json index 348dfea71..88f3f0dfc 100644 --- a/docusaurus/package-lock.json +++ b/docusaurus/package-lock.json @@ -7408,9 +7408,9 @@ } }, "node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "license": "MIT", "dependencies": { "balanced-match": "^1.0.0" @@ -8000,14 +8000,15 @@ } }, "node_modules/compression": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.1.tgz", - "integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==", + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.2.tgz", + "integrity": "sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==", "license": "MIT", "dependencies": { "bytes": "3.1.2", "compressible": "~2.0.18", "debug": "2.6.9", + "destroy": "1.2.0", "negotiator": "~0.6.4", "on-headers": "~1.1.0", "safe-buffer": "5.2.1", @@ -8015,6 +8016,10 @@ }, "engines": { "node": ">= 0.8.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/compression/node_modules/bytes": { @@ -9617,9 +9622,9 @@ } }, "node_modules/dompurify": { - "version": "3.4.14", - "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.14.tgz", - "integrity": "sha512-dVoH9z+MY+C9IilgGCk3YfFqjLi3fChm2OiKJMzh6axrJ5qwxqWaZamgmHrpv22CN/KdbZJuGEGgfQoL00LTdg==", + "version": "3.4.16", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz", + "integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==", "license": "(MPL-2.0 OR Apache-2.0)", "optionalDependencies": { "@types/trusted-types": "^2.0.7" @@ -10248,9 +10253,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", - "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", + "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", "funding": [ { "type": "github", @@ -11269,9 +11274,9 @@ } }, "node_modules/http-cache-semantics": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz", - "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz", + "integrity": "sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA==", "license": "BSD-2-Clause" }, "node_modules/http-deceiver": { @@ -11421,15 +11426,15 @@ } }, "node_modules/image-size": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/image-size/-/image-size-2.0.2.tgz", - "integrity": "sha512-IRqXKlaXwgSMAMtpNzZa1ZAe8m+Sa1770Dhk8VkSsP9LS+iHD62Zd8FQKs8fbPiagBE7BzoFX23cxFnwshpV6w==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/image-size/-/image-size-2.0.4.tgz", + "integrity": "sha512-QRUkFFsRV/6fuESxb9Vkq+a0LkSrgKXuc2NEqfikiXxxN/G3tjWt5EVUlMaImRBZRZK/jRBEbYvpPYZL8t08Zw==", "license": "MIT", "bin": { "image-size": "bin/image-size.js" }, "engines": { - "node": ">=16.x" + "node": ">=18" } }, "node_modules/immediate": { @@ -11941,9 +11946,9 @@ } }, "node_modules/joi": { - "version": "18.2.1", - "resolved": "https://registry.npmjs.org/joi/-/joi-18.2.1.tgz", - "integrity": "sha512-2/OKlogiESf2Nh3TFCrRjrr9z1DRHeW0I+KReF67+4J0Ns+8hBtHRmoWAZ2OFU6I5+TWLEe6sVlSdXPjHm5UbQ==", + "version": "18.2.9", + "resolved": "https://registry.npmjs.org/joi/-/joi-18.2.9.tgz", + "integrity": "sha512-2mD929bUVKUhOLQQEVhlf6EZ0Mlo0DeRb5MO7cViR9AXLtBauuccEtB1py9Ocxpo/P7ucnh442iY/iOwrh3IQw==", "license": "BSD-3-Clause", "dependencies": { "@hapi/address": "^5.1.1", @@ -17172,9 +17177,9 @@ "license": "ISC" }, "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", "license": "MIT", "dependencies": { "forwarded": "0.2.0", @@ -17182,6 +17187,10 @@ }, "engines": { "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/proxy-addr/node_modules/ipaddr.js": { @@ -18359,9 +18368,9 @@ } }, "node_modules/serve-handler/node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "license": "MIT", "dependencies": { "balanced-match": "^1.0.0", @@ -18556,9 +18565,9 @@ } }, "node_modules/shell-quote": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.10.0.tgz", - "integrity": "sha512-w1aiOKwKuRgtwAReIIj89puqg+I7GvX4IbLrvmhXbzQsj1+Zwi4VO3+fa6ZF91TWSjIxoEkKnMeHcLEODK5ZXA==", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz", + "integrity": "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==", "license": "MIT", "engines": { "node": ">= 0.4" @@ -18764,9 +18773,9 @@ } }, "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -19374,12 +19383,12 @@ } }, "node_modules/tinypool": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", - "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.2.0.tgz", + "integrity": "sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ==", "license": "MIT", "engines": { - "node": "^18.0.0 || >=20.0.0" + "node": "^20.0.0 || >=22.0.0" } }, "node_modules/to-regex-range": { @@ -19543,9 +19552,9 @@ } }, "node_modules/undici": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz", - "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==", + "version": "7.30.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.0.tgz", + "integrity": "sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==", "license": "MIT", "engines": { "node": ">=20.18.1" diff --git a/docusaurus/package.json b/docusaurus/package.json index 90f3aada1..f0e094078 100644 --- a/docusaurus/package.json +++ b/docusaurus/package.json @@ -16,13 +16,16 @@ ] }, "overrides": { + "@docusaurus/core": { + "tinypool": "^2.1.2" + }, "copy-webpack-plugin": { "serialize-javascript": "7.0.5" }, "css-minimizer-webpack-plugin": { "serialize-javascript": "7.0.5" }, - "joi": "18.2.1", + "joi": "18.2.9", "qs": "6.16.0", "sockjs": { "uuid": "11.1.1" diff --git a/electron-app/main.ts b/electron-app/main.ts index 925e94de7..951460f35 100644 --- a/electron-app/main.ts +++ b/electron-app/main.ts @@ -11,6 +11,7 @@ import { setupMenuAndEventHandlers } from "./main/menu/setupMenuAndEventHandlers import { appRef, browserWindowRef } from "./main/runtime/electronAccess.js"; import { initializeApplication } from "./main/runtime/initializeApplication.js"; import { primeTestEnvironment } from "./main/runtime/primeTestEnvironment.js"; +import { configurePackagedSmoke } from "./main/runtime/packagedSmoke.js"; import { setupMainLifecycle } from "./main/runtime/setupMainLifecycle.js"; import { getMainWindow } from "./main/state/appState.js"; @@ -72,6 +73,7 @@ const setupIPCHandlersForLifecycle: LifecycleDependencies["setupIPCHandlers"] = setupIPCHandlers(win as Parameters[0]); }; +configurePackagedSmoke(appRef()); primeTestEnvironment(initializeApplicationForPrime); setupMainLifecycle({ diff --git a/electron-app/main/runtime/packagedSmoke.ts b/electron-app/main/runtime/packagedSmoke.ts new file mode 100644 index 000000000..0a6f45e05 --- /dev/null +++ b/electron-app/main/runtime/packagedSmoke.ts @@ -0,0 +1,189 @@ +import { mkdirSync, writeFileSync } from "node:fs"; +import * as path from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import type { App, BrowserWindow } from "electron"; + +import { approveFilePath } from "../security/fileAccessPolicy.js"; +import { setAutoUpdaterInitialized } from "../state/appState.js"; + +/** Configure the opt-in release self-test before any windows or sessions exist. */ +export function configurePackagedSmoke(app: App | undefined): void { + if (!process.argv.includes("--ffv-smoke-test")) { + return; + } + const directory = process.env["FFV_SMOKE_DIRECTORY"]; + const nonce = process.env["FFV_SMOKE_NONCE"]; + const fixture = process.env["FFV_SMOKE_FIXTURE"]; + if ( + !app || + directory === undefined || + directory.length === 0 || + !path.isAbsolute(directory) || + nonce === undefined || + nonce.length === 0 || + fixture === undefined || + fixture.length === 0 || + !path.isAbsolute(fixture) + ) { + throw new Error( + "Packaged smoke requires an absolute report directory, fixture and nonce" + ); + } + const profile = path.join(directory, "user-data"); + mkdirSync(profile, { recursive: true }); + app.setPath("userData", profile); + // Release verification must never download or install another release. + setAutoUpdaterInitialized(true); + approveFilePath(fixture, { source: "packaged-smoke" }); + let started = false; + app.on("browser-window-created", (_event, mainWindow) => { + if (started) { + return; + } + started = true; + void verifyPackagedWindow(mainWindow, fixture, directory, nonce, app); + }); +} + +async function verifyPackagedWindow( + mainWindow: BrowserWindow, + fixture: string, + directory: string, + nonce: string, + app: App +): Promise { + const failures: string[] = []; + mainWindow.webContents.on("render-process-gone", (_event, details) => { + failures.push( + `Renderer terminated: ${details.reason} (${details.exitCode})` + ); + }); + mainWindow.webContents.on( + "preload-error", + (_event, _preloadPath, error) => { + failures.push(`Preload failed: ${error.message}`); + } + ); + mainWindow.webContents.on( + "did-fail-load", + (_event, code, description, url, isMainFrame) => { + if (isMainFrame) { + failures.push( + `Main frame failed: ${code} ${description} ${url}` + ); + } + } + ); + try { + // Poll actual readiness: did-finish-load alone does not prove module initialization. + let ready = false; + for (let attempt = 0; attempt < 200; attempt += 1) { + if (failures.length > 0 || mainWindow.isDestroyed()) { + throw new Error( + failures.join("; ") || "Window closed during startup" + ); + } + if ( + mainWindow.isVisible() && + mainWindow.webContents.getURL().startsWith("file:") + ) { + ready = await mainWindow.webContents.executeJavaScript( + `(async () => { + const { getState } = await import(new URL('./utils/state/core/stateManager.js', location.href).href); + return getState('app.initialized') === true && Boolean(document.querySelector('#open_file_btn') && !document.querySelector('#open_file_btn').disabled && document.querySelector('#tab_map')); + })()` + ); + if (ready) { + break; + } + } + await delay(100); + } + if (!ready) { + throw new Error("Visible renderer UI did not initialize"); + } + // Only fixed, packaged modules are imported. The fixture is a JSON string, + // never executable input. Existing file IPC performs the read and parse. + const activity: unknown = await mainWindow.webContents + .executeJavaScript(`(async () => { + const { openFitFileFromPath } = await import(new URL('./utils/files/import/openFitFileFromPath.js', location.href).href); + const { getActiveFitActivityData } = await import(new URL('./utils/state/domain/fitActivityDataState.js', location.href).href); + const { getBrowserElectronApiCandidate } = await import(new URL('./utils/runtime/browserRuntime.js', location.href).href); + const { getState } = await import(new URL('./utils/state/core/stateManager.js', location.href).href); + const notifications = []; + const loaded = await openFitFileFromPath({electronApiScope: {getElectronAPI: getBrowserElectronApiCandidate}, filePath: ${JSON.stringify(fixture)}, showNotification: (message, type) => { if (type === 'error') notifications.push(message); }}); + const data = getActiveFitActivityData(); + const recordCount = Array.isArray(data?.recordMesgs) ? data.recordMesgs.length : 0; + const sessionCount = Array.isArray(data?.sessionMesgs) ? data.sessionMesgs.length : 0; + const activeFileName = document.querySelector('#active_file_name')?.textContent?.trim() || ''; + if (!loaded || recordCount < 1 || sessionCount < 1 || !activeFileName.includes(${JSON.stringify(path.basename(fixture))})) throw new Error('FIT smoke failed: ' + JSON.stringify({ loaded, recordCount, sessionCount, activeFileName, notifications })); + const mapTab = document.querySelector('#tab_map'); + mapTab.click(); + mapTab.scrollIntoView({block: 'start'}); + let routeCount = 0; + let mapReady = false; + for (let attempt = 0; attempt < 200; attempt += 1) { + const readiness = getState('ui.tabReadiness.map'); + if (readiness?.error || readiness?.status === 'error') throw new Error('Map smoke failed: ' + JSON.stringify(readiness)); + const map = document.querySelector('#leaflet-map'); + routeCount = map?.querySelectorAll('.leaflet-marker-icon, .leaflet-interactive').length || 0; + if (readiness?.status === 'ready' && map?.getClientRects().length > 0 && routeCount > 0) { + mapReady = true; + break; + } + await new Promise(resolve => setTimeout(resolve, 100)); + } + if (!mapReady) throw new Error('Map did not render the FIT route before the smoke deadline'); + document.querySelector('#leaflet-map').scrollIntoView({block: 'center', behavior: 'instant'}); + await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); + const mapBounds = document.querySelector('#leaflet-map').getBoundingClientRect(); + if (mapBounds.bottom <= 0 || mapBounds.top >= document.documentElement.clientHeight) throw new Error('Rendered map was outside the visible viewport'); + return {recordCount, sessionCount, activeFileName, title: document.title, appInitialized: getState('app.initialized') === true, mapReady, routeCount}; + })()`); + if (failures.length > 0 || !mainWindow.isVisible()) { + throw new Error(failures.join("; ") || "Window became hidden"); + } + // Let Chromium present the completed scroll before capturing its surface. + await delay(500); + const screenshot = await mainWindow.webContents.capturePage(); + if ( + failures.length > 0 || + mainWindow.isDestroyed() || + !mainWindow.isVisible() + ) { + throw new Error( + failures.join("; ") || "Window closed before capture completed" + ); + } + writeFileSync( + path.join(directory, "screenshot.png"), + screenshot.toPNG() + ); + writeFileSync( + path.join(directory, "report.json"), + JSON.stringify({ + activity, + nonce, + platform: process.platform, + arch: process.arch, + version: app.getVersion(), + status: "passed", + visible: true, + }) + ); + app.exit(0); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + writeFileSync( + path.join(directory, "report.json"), + JSON.stringify({ + nonce, + status: "failed", + error: message, + failures, + }) + ); + console.error(`[packaged-smoke] ${message}`); + app.exit(1); + } +} diff --git a/electron-app/renderer/rendererVendorMap.ts b/electron-app/renderer/rendererVendorMap.ts index 47965e705..8de069105 100644 --- a/electron-app/renderer/rendererVendorMap.ts +++ b/electron-app/renderer/rendererVendorMap.ts @@ -14,6 +14,8 @@ import { FullScreen } from "leaflet.fullscreen"; import "leaflet.fullscreen/dist/Control.FullScreen.css"; /* eslint-enable import-x/no-unassigned-import */ import { LocateControl } from "leaflet.locatecontrol"; +import { setWorkerUrl } from "maplibre-gl"; +import mapLibreWorkerSource from "maplibre-gl/dist/maplibre-gl-worker.mjs?raw"; /* eslint-disable import-x/no-unassigned-import -- Leaflet control stylesheets must be loaded through the bundle entry. */ import "leaflet.locatecontrol/dist/L.Control.Locate.css"; /* eslint-enable import-x/no-unassigned-import */ @@ -27,10 +29,17 @@ import { type RendererVendorMapRuntime, } from "./rendererVendorMapRuntime.js"; import { markRendererVendorEntryLoaded } from "./rendererVendorShared.js"; -import { - registerMapLibreLayerFactory, - resolveMapLibreLayerFactoryFromCandidate, -} from "../utils/maps/layers/mapLibreLayerRuntime.js"; +import { resolveMapLibreLayerFactoryFromCandidate } from "../utils/maps/layers/mapLibreLayerRuntime.js"; + +// Chromium cannot start a worker directly from the app's file:// origin. +// MapLibre 6.13+ ships a self-contained worker; keep its blob URL for the +// renderer lifetime so workers can restart after the last map is removed. +// The production CSP already permits blob workers, with webSecurity enabled. +setWorkerUrl( + URL.createObjectURL( + new Blob([mapLibreWorkerSource], { type: "text/javascript" }) + ) +); const leafletRuntime = Leaflet as typeof Leaflet & { Control: typeof Leaflet.Control & { @@ -95,14 +104,14 @@ export async function installRendererMapVendorEntry( await import("@maplibre/maplibre-gl-leaflet"); const mapLibreLayerFactory = resolveMapLibreLayerFactoryFromCandidate(leafletRuntime); - if (mapLibreLayerFactory) { - registerMapLibreLayerFactory(mapLibreLayerFactory); + if (!mapLibreLayerFactory) { + throw new Error("MapLibre Leaflet layer factory did not initialize"); } installLeafletMeasureLite(Leaflet); runtime.removeTemporaryLeafletGlobals(); markRendererVendorEntryLoaded("map", { - map: { leafletRuntime: Leaflet }, + map: { leafletRuntime: Leaflet, mapLibreLayerFactory }, }); } diff --git a/electron-app/renderer/rendererVendorShared.ts b/electron-app/renderer/rendererVendorShared.ts index 658e9718b..e53555bbf 100644 --- a/electron-app/renderer/rendererVendorShared.ts +++ b/electron-app/renderer/rendererVendorShared.ts @@ -10,6 +10,7 @@ import type { import type { DomPurifyRuntime } from "../utils/dom/domPurifyRuntime.js"; import type { ExportZipConstructor } from "../utils/files/export/exportZipRuntime.js"; import type { RegisteredLeafletRuntime } from "../utils/maps/core/leafletRuntime.js"; +import type { MapLibreLayerFactory } from "../utils/maps/layers/mapLibreLayerRuntime.js"; import type { ArqueroRuntime } from "../utils/rendering/helpers/arqueroRuntime.js"; import type { RegisteredDataTableRuntime } from "../utils/rendering/core/dataTableRuntime.js"; import type { ScreenfullRuntime } from "../utils/ui/controls/screenfullRuntime.js"; @@ -50,6 +51,7 @@ export type RendererVendorCoreRuntimePayload = Readonly<{ export type RendererVendorMapRuntimePayload = Readonly<{ leafletRuntime: RegisteredLeafletRuntime; + mapLibreLayerFactory: MapLibreLayerFactory; }>; export const rendererVendorEntryLoadedEventName = diff --git a/electron-app/renderer/vendorBundleLoader.ts b/electron-app/renderer/vendorBundleLoader.ts index 5159225a9..874500be7 100644 --- a/electron-app/renderer/vendorBundleLoader.ts +++ b/electron-app/renderer/vendorBundleLoader.ts @@ -34,6 +34,7 @@ import { isRegisteredLeafletRuntime, registerLeafletRuntime, } from "../utils/maps/core/leafletRuntime.js"; +import { registerMapLibreLayerFactory } from "../utils/maps/layers/mapLibreLayerRuntime.js"; import { isArqueroRuntime, registerArqueroRuntime, @@ -132,12 +133,14 @@ function registerMapRuntimePayload( ): boolean { if ( payload === undefined || - !isRegisteredLeafletRuntime(payload.leafletRuntime) + !isRegisteredLeafletRuntime(payload.leafletRuntime) || + typeof payload.mapLibreLayerFactory !== "function" ) { return false; } registerLeafletRuntime(payload.leafletRuntime); + registerMapLibreLayerFactory(payload.mapLibreLayerFactory); return true; } diff --git a/electron-builder.config.cjs b/electron-builder.config.cjs index 29fba7cb4..e7bee8aca 100644 --- a/electron-builder.config.cjs +++ b/electron-builder.config.cjs @@ -181,6 +181,18 @@ module.exports = { }, mac: { icon: appPackageExportPath("./icons/favicon-512x512.icns"), + // Even releases without an Apple certificate need valid Mach-O signatures + // after fuse changes. Let builder sign the final app, including universal + // merges, instead of resetting signatures in each afterPack invocation. + ...(shouldCodeSign + ? {} + : { + identity: "-", + entitlements: "packaging/macos/entitlements.adhoc.plist", + entitlementsInherit: + "packaging/macos/entitlements.adhoc.plist", + notarize: false, + }), target: [ "dmg", "zip", diff --git a/package-lock.json b/package-lock.json index cf0bde40a..2fdd8f896 100644 --- a/package-lock.json +++ b/package-lock.json @@ -48,9 +48,9 @@ "cross-env": "^10.1.0", "datatables.net-dt": "^2.3.8", "date-fns": "^4.4.0", - "dompurify": "^3.4.14", - "electron": "^43.5.1", - "electron-builder": "^26.16.0", + "dompurify": "^3.4.16", + "electron": "^43.7.9", + "electron-builder": "^26.17.0", "esbuild": "^0.28.2", "eslint": "^10.9.1", "eslint-config-nick2bad4u": ">=1.2.7 <1.2.8", @@ -73,7 +73,7 @@ "leaflet.locatecontrol": "^0.90.1", "lychee-config-nick2bad4u": "^2.0.0", "makensis": "^3.0.6", - "maplibre-gl": "^5.24.0", + "maplibre-gl": "^6.13.0", "markdownlint-cli": "^0.49.1", "ncu-config-nick2bad4u": "^0.2.1", "npm-check-updates": "^22.2.9", @@ -158,9 +158,9 @@ } }, "node_modules/@actions/github/node_modules/undici": { - "version": "6.28.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz", - "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==", + "version": "6.29.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz", + "integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==", "dev": true, "license": "MIT", "optional": true, @@ -181,9 +181,9 @@ } }, "node_modules/@actions/http-client/node_modules/undici": { - "version": "6.28.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz", - "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==", + "version": "6.29.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz", + "integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==", "dev": true, "license": "MIT", "optional": true, @@ -224,9 +224,9 @@ } }, "node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.1.tgz", - "integrity": "sha512-28R/k+NAjeuf7+CKlTxWZVExJGwVVLwY06DgEnOMz2gEpfNkDcD7QvyiVPT0xy0XXhU8vHsd4Ot42OOPdJG7dQ==", + "version": "5.4.3", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.3.tgz", + "integrity": "sha512-yzzNtgczwgoVHNigCyKTXcQJU4Y8t/ikU4UxXW0BvrLfHTGWZhsNcOT2s/a7vn81/4KqVnNmHjaUEPlvWnNwVw==", "dev": true, "funding": [ { @@ -247,9 +247,9 @@ } }, "node_modules/@apidevtools/json-schema-ref-parser/node_modules/undici": { - "version": "6.28.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz", - "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==", + "version": "6.29.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz", + "integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==", "dev": true, "license": "MIT", "engines": { @@ -1754,9 +1754,9 @@ "license": "MIT" }, "node_modules/@electron/asar/node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -1877,9 +1877,9 @@ } }, "node_modules/@electron/rebuild": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.2.0.tgz", - "integrity": "sha512-RKL/O+jGoXJMxrx/5771y1n0xTKmFuOYGO3gMmwypBM6rsH0kou0mswwdXA2JrhIkE4xyC7v9vGk0n6NPzgOxQ==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.2.1.tgz", + "integrity": "sha512-IS4pG3BysRrCLJ8xTAfvg+IQDbiUoAzdJy2SfjcYKnLDy5DpCdjnPdhS5Zf5UMfrkB24xu0KC+TqcOxg+eG+6w==", "dev": true, "license": "MIT", "dependencies": { @@ -1924,9 +1924,9 @@ "license": "MIT" }, "node_modules/@electron/universal/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { @@ -1934,9 +1934,9 @@ } }, "node_modules/@electron/universal/node_modules/fs-extra": { - "version": "11.4.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.0.tgz", - "integrity": "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==", + "version": "11.4.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz", + "integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==", "dev": true, "license": "MIT", "dependencies": { @@ -1987,9 +1987,9 @@ } }, "node_modules/@electron/windows-sign/node_modules/fs-extra": { - "version": "11.4.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.0.tgz", - "integrity": "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==", + "version": "11.4.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz", + "integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==", "dev": true, "license": "MIT", "optional": true, @@ -3401,38 +3401,28 @@ "license": "BSD-2-Clause" }, "node_modules/@mapbox/unitbezier": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/@mapbox/unitbezier/-/unitbezier-0.0.1.tgz", - "integrity": "sha512-nMkuDXFv60aBr9soUG5q+GvZYL+2KZHVvsqFCzqnkGEf46U2fvmytHaEVc1/YZbiLn8X+eR3QzX1+dwDO1lxlw==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@mapbox/unitbezier/-/unitbezier-1.0.0.tgz", + "integrity": "sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ==", "dev": true, "license": "BSD-2-Clause" }, "node_modules/@mapbox/vector-tile": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@mapbox/vector-tile/-/vector-tile-2.0.5.tgz", - "integrity": "sha512-pXj8m7KTsqZt+1jsE0xIpGvqTSbblfkuEJL/NJmNePMtEwxO8V3XMDo9WMSfDeqHvCtBI9Lmt4mGcGR10zecmw==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@mapbox/vector-tile/-/vector-tile-3.0.0.tgz", + "integrity": "sha512-Qf10S1uIHMk20ri/IVBnpS+esUEkVaR5Hftmz88jTInrpmWgPGJfPe3LVjjlE77trLx8tH6qjTG7uWH9hIq/0Q==", "dev": true, "license": "BSD-3-Clause", "dependencies": { "@mapbox/point-geometry": "~1.1.0", "@types/geojson": "^7946.0.16", - "pbf": "^4.0.2" - } - }, - "node_modules/@mapbox/whoots-js": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@mapbox/whoots-js/-/whoots-js-3.1.0.tgz", - "integrity": "sha512-Es6WcD0nO5l+2BOQS4uLfNPYQaNDfbot3X1XUoloz+x0mPDS3eeORZJl06HXjwBG1fOGwCRnzK88LMdxKRrd6Q==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=6.0.0" + "pbf": "^5.0.0" } }, "node_modules/@maplibre/geojson-vt": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-6.1.1.tgz", - "integrity": "sha512-FVMOcmSP/yqol45t7StApEyTL5/vmqBCuFhH9n+fFuINenhaX+YgHHIt1yJ86S8kln3uJLcMvmEU2cfn6E2eCQ==", + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-6.1.2.tgz", + "integrity": "sha512-2ZYhobdAY+y4/P/z1xe0698165LywD0yDdWugdu3NRUrajgVWut+tLkcz7i/RJguMTURwK7gxwmwYMFJbgbQFw==", "dev": true, "license": "ISC", "dependencies": { @@ -3452,13 +3442,13 @@ } }, "node_modules/@maplibre/maplibre-gl-style-spec": { - "version": "24.10.0", - "resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-24.10.0.tgz", - "integrity": "sha512-lichxSiagMEBBrqHF0trtMQH9RKh+9jUlIJl0qW0QHvt2H/tbvUWdE+ZzI2Jd0/pT7j/iavLonlPu7EQ/ixTOw==", + "version": "26.4.4", + "resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.4.4.tgz", + "integrity": "sha512-hG4RZR4PBd/+6A3ODdZ3AnQRF106ZQk1y3bhwDg8bH/A4Oz2tnRUJVVWs9BZa6gXZ1d3UKe89C+Mm+olGBELvA==", "dev": true, "license": "ISC", "dependencies": { - "@mapbox/jsonlint-lines-primitives": "~2.0.2", + "@mapbox/jsonlint-lines-primitives": "^2.0.3", "@mapbox/unitbezier": "^1.0.0", "json-stringify-pretty-compact": "^4.0.0", "minimist": "^1.2.8", @@ -3471,17 +3461,10 @@ "gl-style-validate": "dist/gl-style-validate.mjs" } }, - "node_modules/@maplibre/maplibre-gl-style-spec/node_modules/@mapbox/unitbezier": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@mapbox/unitbezier/-/unitbezier-1.0.0.tgz", - "integrity": "sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ==", - "dev": true, - "license": "BSD-2-Clause" - }, "node_modules/@maplibre/mlt": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@maplibre/mlt/-/mlt-1.2.0.tgz", - "integrity": "sha512-g45M8gEI4sMO3X9ib4K7n3ZKFf0qQOL+NMkHCnEK51lOrYFHiEssOuZncx1+miIgi1IEE2NcbRMcq8RBkL+QHA==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@maplibre/mlt/-/mlt-1.3.0.tgz", + "integrity": "sha512-7M2O7ABM80Oi8XPkfkrjKB8mOBIxGoVgkA52Mu4RMWoBvvMdagQ522+WxVYujZsMpqIr3BpzrTbXrm4k8lCzCQ==", "dev": true, "license": "(MIT OR Apache-2.0)", "dependencies": { @@ -3500,19 +3483,6 @@ "pbf": "^5.1.0" } }, - "node_modules/@maplibre/vt-pbf/node_modules/pbf": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz", - "integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "resolve-protobuf-schema": "^2.1.0" - }, - "bin": { - "pbf": "bin/pbf" - } - }, "node_modules/@microsoft/tsdoc": { "version": "0.16.0", "resolved": "https://registry.npmjs.org/@microsoft/tsdoc/-/tsdoc-0.16.0.tgz", @@ -3836,9 +3806,9 @@ "license": "MIT" }, "node_modules/@npmcli/map-workspaces/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { @@ -3920,9 +3890,9 @@ "license": "MIT" }, "node_modules/@npmcli/package-json/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { @@ -4306,9 +4276,9 @@ } }, "node_modules/@peculiar/asn1-schema": { - "version": "2.9.4", - "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.9.4.tgz", - "integrity": "sha512-GjzePcT9Iw8NzeOPf73iNS9xM+TBhd/FilAfP+RQGkTMQJTVWtytN3JHJACCjf/ABNau5S7mS3g+DcuxmRgYEg==", + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.10.0.tgz", + "integrity": "sha512-GhokD41lV4gQrrLYm3wCkHfBOnJrnhDMgt4XeMW8gzfE1UdJqIuSwsE+ggf82XBjUXRJylcm+KIGQFa4utIVLw==", "dev": true, "license": "MIT", "dependencies": { @@ -7079,9 +7049,9 @@ "license": "MIT" }, "node_modules/app-builder-lib": { - "version": "26.16.0", - "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.16.0.tgz", - "integrity": "sha512-jJGAhKF4TQPYm/r/gvkqWhI0pt9PsGB5xMIqZHh2Cox/Ua8mtT4ayn/na9ZxEqk7jvF3ptyk/duv0A+7uUsxEA==", + "version": "26.17.0", + "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.17.0.tgz", + "integrity": "sha512-wfL7EhujuODDW3uMSD8RPcr/MLzmT0dmpVfWV0wFUWXI0rIdaukzAJ7EFUSyHXOpxuBZqaIGlQt6VeQhtHhetw==", "dev": true, "license": "MIT", "dependencies": { @@ -7131,8 +7101,8 @@ "node": ">=14.0.0" }, "peerDependencies": { - "dmg-builder": "26.16.0", - "electron-builder-squirrel-windows": "26.16.0" + "dmg-builder": "26.17.0", + "electron-builder-squirrel-windows": "26.17.0" } }, "node_modules/app-builder-lib/node_modules/@electron/fuses": { @@ -7955,9 +7925,9 @@ } }, "node_modules/basic-ftp": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.3.1.tgz", - "integrity": "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw==", + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-6.2.2.tgz", + "integrity": "sha512-LIkJcf/F6bTTfvE3k2YcTxrJsLKKVXiEpHZYkQP6JoqTb7khng7c13ckRTDQbqRh5IkehVH3F00sSlAa2F6DwA==", "dev": true, "license": "MIT", "engines": { @@ -7984,9 +7954,9 @@ "optional": true }, "node_modules/bidi-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", - "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz", + "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", "dev": true, "license": "MIT", "dependencies": { @@ -8087,9 +8057,9 @@ "license": "BSD-2-Clause" }, "node_modules/brace-expansion": { - "version": "5.0.9", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", - "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "dev": true, "license": "MIT", "dependencies": { @@ -9540,9 +9510,9 @@ } }, "node_modules/dead-or-alive/node_modules/undici": { - "version": "8.10.1", - "resolved": "https://registry.npmjs.org/undici/-/undici-8.10.1.tgz", - "integrity": "sha512-YQ3WlbqjYMmNpdvDH64jAgLjxuAR9+649calDWhbshYaeQGO2bR4nI94ORJmwI3J9YhoKQnpyGOK+0zlWS5N5Q==", + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.11.2.tgz", + "integrity": "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==", "dev": true, "license": "MIT", "engines": { @@ -9884,9 +9854,9 @@ "license": "MIT" }, "node_modules/dir-compare/node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -9942,13 +9912,13 @@ "license": "MIT" }, "node_modules/dmg-builder": { - "version": "26.16.0", - "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.16.0.tgz", - "integrity": "sha512-1s7GZgxPNLLxStA0wu2a4gpIhgmOai+UL72iACha+uyQDbdRcGTjOZcN3PCJ8c/P+Z2cESSZTmUM1B0xop9cqQ==", + "version": "26.17.0", + "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.17.0.tgz", + "integrity": "sha512-EAw1f2iGkICmUvAVBOjm7v5mxJdB7/+OZSycHFhKBimiTkCXtvkCC6wBKzHo7ZQYi58C2MmwIleRbgRnROlK2Q==", "dev": true, "license": "MIT", "dependencies": { - "app-builder-lib": "26.16.0", + "app-builder-lib": "26.17.0", "builder-util": "26.16.0", "fs-extra": "^10.1.0", "js-yaml": "^4.1.0" @@ -10084,9 +10054,9 @@ } }, "node_modules/dompurify": { - "version": "3.4.14", - "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.14.tgz", - "integrity": "sha512-dVoH9z+MY+C9IilgGCk3YfFqjLi3fChm2OiKJMzh6axrJ5qwxqWaZamgmHrpv22CN/KdbZJuGEGgfQoL00LTdg==", + "version": "3.4.16", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz", + "integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==", "dev": true, "license": "(MPL-2.0 OR Apache-2.0)", "optionalDependencies": { @@ -10205,9 +10175,9 @@ "license": "MIT" }, "node_modules/earcut": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/earcut/-/earcut-3.2.3.tgz", - "integrity": "sha512-vnS4AVwp1KHAF13i1vp1/2D5evWy3k5u/iW/B81QVsUZtV8cv2tU0b2VNFlqvh4kYwrFMDdjPCfAmfyJW9y14Q==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/earcut/-/earcut-3.2.4.tgz", + "integrity": "sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==", "dev": true, "license": "ISC" }, @@ -10252,9 +10222,9 @@ } }, "node_modules/electron": { - "version": "43.5.1", - "resolved": "https://registry.npmjs.org/electron/-/electron-43.5.1.tgz", - "integrity": "sha512-lRHSwzZimdWWeqcTHFRCpicWwxBE6kotKIyGTusums/jvmVVC27rLPFikUz8LsLwV7gVWlYaiEYQAWzitbN6nA==", + "version": "43.7.9", + "resolved": "https://registry.npmjs.org/electron/-/electron-43.7.9.tgz", + "integrity": "sha512-wZkQ/R9F5Bv8dM5vX6vWboNo5ZCBC/IYQV195dtG9JvFAlNbebzlkWWSE5esgpCVy3rVYQ/g09GeknJwvQnS9A==", "license": "MIT", "dependencies": { "@electron-internal/extract-zip": "^1.0.1", @@ -10270,18 +10240,18 @@ } }, "node_modules/electron-builder": { - "version": "26.16.0", - "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.16.0.tgz", - "integrity": "sha512-FQAUWjdcLMXtCKYkvVqhV5N+EH1uiw50RxJnrLDZtDiOykW8ywhkrbysSi7J3mZjp+Jb2B7Y1pQD3urOEYXvIg==", + "version": "26.17.0", + "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.17.0.tgz", + "integrity": "sha512-iYHBRiagS9sDIbZx1ZD113f5rEGQvtpvTvHf70ovHKJ8mRvxwIkWX7JCwfmVQmVS4eX735p7TZmoxHnBPwF3vA==", "dev": true, "license": "MIT", "dependencies": { - "app-builder-lib": "26.16.0", + "app-builder-lib": "26.17.0", "builder-util": "26.16.0", "builder-util-runtime": "9.7.0", "chalk": "^4.1.2", "ci-info": "^4.2.0", - "dmg-builder": "26.16.0", + "dmg-builder": "26.17.0", "fs-extra": "^10.1.0", "lazy-val": "^1.0.5", "simple-update-notifier": "2.0.0", @@ -10296,14 +10266,14 @@ } }, "node_modules/electron-builder-squirrel-windows": { - "version": "26.16.0", - "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-26.16.0.tgz", - "integrity": "sha512-pEYkKfa/fr+X7BCx/p4UOPmtoCkbwkQnf0yfBhsJoHgeztdqGmpc19qvM/xuQo1adqZr3R2w7Jg2mdiHM+OUsg==", + "version": "26.17.0", + "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-26.17.0.tgz", + "integrity": "sha512-uyh+D+B0m12qCRp9c/7dwBirHTh7JcvAzj5eTEbb4dXPPGAhYPx1nozzbu1fC6AdULfat6ZNqgWhipTFpb82lQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "app-builder-lib": "26.16.0", + "app-builder-lib": "26.17.0", "builder-util": "26.16.0", "electron-winstaller": "5.4.0" } @@ -13101,9 +13071,9 @@ "license": "MIT" }, "node_modules/eslint-plugin-undefined-css-classes/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { @@ -13148,20 +13118,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/eslint-plugin-undefined-css-classes/node_modules/postcss-selector-parser": { - "version": "6.1.4", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.4.tgz", - "integrity": "sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "cssesc": "^3.0.0", - "util-deprecate": "^1.0.2" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/eslint-plugin-unicorn": { "version": "64.0.0", "resolved": "https://registry.npmjs.org/eslint-plugin-unicorn/-/eslint-plugin-unicorn-64.0.0.tgz", @@ -13637,9 +13593,9 @@ } }, "node_modules/fast-uri": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", - "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", + "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", "funding": [ { "type": "github", @@ -13799,9 +13755,9 @@ "license": "MIT" }, "node_modules/filelist/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { @@ -14398,9 +14354,9 @@ "license": "MIT" }, "node_modules/glob/node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -15165,9 +15121,9 @@ } }, "node_modules/http-cache-semantics": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz", - "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz", + "integrity": "sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA==", "dev": true, "license": "BSD-2-Clause" }, @@ -15358,9 +15314,9 @@ } }, "node_modules/ip-address": { - "version": "10.7.0", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.0.tgz", - "integrity": "sha512-BGFsyJd5mpXp3rK6jIdADLNgpJUK1jnjzvYF8lK+VyDab9JAmqN0YOKDdP17HlgKb2+ehPgDc8EtnRLbGCAMhA==", + "version": "10.7.3", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.3.tgz", + "integrity": "sha512-A1kdq/tSb5QjvKvAMgIoEvDBIgL7qaqVP/jkvSwYYRZ9iEzvPpopxp2wQfu3SuZRHtpHNxMn8Fs0bS+gf5Xmwg==", "dev": true, "license": "MIT", "engines": { @@ -17422,28 +17378,27 @@ } }, "node_modules/maplibre-gl": { - "version": "5.24.0", - "resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-5.24.0.tgz", - "integrity": "sha512-ALyFxgtd5R+65UqZ/++lOqwWcC0SNho9c27fYSyLmG7AfnAul2o46F05aDJGPbFU57wos9dgcIySHs0Xe6ia3A==", + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.13.0.tgz", + "integrity": "sha512-ELXk4h+xl0URFQEnVbAN6MGn61P6jq4amUWHiskLVsvHCaKdf1Zq6G8UNOD0AQ3UaXoL5ECc8ovz8yqYEBGPKw==", "dev": true, "license": "BSD-3-Clause", "dependencies": { - "@mapbox/jsonlint-lines-primitives": "^2.0.2", "@mapbox/point-geometry": "^1.1.0", - "@mapbox/tiny-sdf": "^2.1.0", - "@mapbox/unitbezier": "^0.0.1", - "@mapbox/vector-tile": "^2.0.4", - "@mapbox/whoots-js": "^3.1.0", - "@maplibre/geojson-vt": "^6.1.0", - "@maplibre/maplibre-gl-style-spec": "^24.8.1", - "@maplibre/mlt": "^1.1.8", - "@maplibre/vt-pbf": "^4.3.0", + "@mapbox/tiny-sdf": "^2.2.0", + "@mapbox/unitbezier": "^1.0.0", + "@mapbox/vector-tile": "^3.0.0", + "@maplibre/geojson-vt": "^6.1.2", + "@maplibre/maplibre-gl-style-spec": "^26.4.4", + "@maplibre/mlt": "^1.3.0", + "@maplibre/vt-pbf": "^4.3.2", "@types/geojson": "^7946.0.16", - "earcut": "^3.0.2", + "bidi-js": "^1.1.0", + "earcut": "^3.2.4", "gl-matrix": "^3.4.4", - "kdbush": "^4.0.2", + "kdbush": "^4.1.0", "murmurhash-js": "^1.0.0", - "pbf": "^4.0.1", + "pbf": "^5.1.2", "potpack": "^2.1.0", "quickselect": "^3.0.0", "tinyqueue": "^3.0.0" @@ -17593,9 +17548,9 @@ } }, "node_modules/markdownlint-cli/node_modules/js-yaml": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.2.3.tgz", - "integrity": "sha512-n+mUVyUX5bVv7G/G2zyIHOhdxfuU1dY2NOFzTQUWiMUbFss8b57NFlgCCaggU78wSw5KVS9cllzeLyzyR+n5nw==", + "version": "5.4.3", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.3.tgz", + "integrity": "sha512-yzzNtgczwgoVHNigCyKTXcQJU4Y8t/ikU4UxXW0BvrLfHTGWZhsNcOT2s/a7vn81/4KqVnNmHjaUEPlvWnNwVw==", "dev": true, "funding": [ { @@ -17615,19 +17570,6 @@ "js-yaml": "bin/js-yaml.mjs" } }, - "node_modules/markdownlint-cli/node_modules/smol-toml": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.7.2.tgz", - "integrity": "sha512-pXFZ9B2WinEPzxWkMmlYE/oYx2BP+qLrE95wP8tCuK901uLSMGdCb6QSr82z+wnhXkG4+cO+OMLbZB2Cn+97zw==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">= 18" - }, - "funding": { - "url": "https://github.com/sponsors/cyyynthia" - } - }, "node_modules/matcher": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz", @@ -19279,9 +19221,9 @@ "license": "MIT" }, "node_modules/multimatch/node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -19523,9 +19465,9 @@ } }, "node_modules/node-abi": { - "version": "4.35.0", - "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.35.0.tgz", - "integrity": "sha512-ymk4aIzxdPopw2giv8Fs1Ec6vybGkjmyxUwVqhkI4MCy2tVfXdkOGGWieWVjL0THgH+7a8lRdevyupoYj3Js/Q==", + "version": "4.36.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.36.0.tgz", + "integrity": "sha512-zrvE1Qy5ElbZVqmJFSiNfwzNZzUCepasgp/4dw0Z0fsn40LJkAk9FA9oMh2SKMeNFRRe/3IfeOKvWwWr8u4SmQ==", "dev": true, "license": "MIT", "dependencies": { @@ -19620,9 +19562,9 @@ } }, "node_modules/node-gyp/node_modules/undici": { - "version": "6.28.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz", - "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==", + "version": "6.29.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz", + "integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==", "dev": true, "license": "MIT", "engines": { @@ -20668,9 +20610,9 @@ "license": "MIT" }, "node_modules/pbf": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/pbf/-/pbf-4.0.2.tgz", - "integrity": "sha512-J0ajxARhZfpUEebxYs1vhMGMuLSXtBe1e+fFPDrf2uA2hgo+UshKfNUWOz92HJNz6/NFEXseQPddnHkTreWRqg==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz", + "integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -20730,13 +20672,16 @@ } }, "node_modules/pkijs": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.0.tgz", - "integrity": "sha512-emEcLuomt2j03vxD54giVB4SxTjnsqkU692xZOZXHDVoYyypEm+b3jpiTcc+Cf+myooc+/Ly0z01jqeNHVgJGw==", + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.1.tgz", + "integrity": "sha512-Oo/NZcSWccq8KyoG7gLE9fnltgHns+pNCjCAp/WmjsUySi+sX7y4z4Xqu4fVb42CDHzRPl33fjzT15V1wvcyhA==", "dev": true, "license": "BSD-3-Clause", + "workspaces": [ + "website" + ], "dependencies": { - "@noble/hashes": "1.4.0", + "@noble/hashes": "1.8.0", "asn1js": "^3.0.6", "bytestreamjs": "^2.0.1", "pvtsutils": "^1.3.6", @@ -20747,19 +20692,6 @@ "node": ">=16.0.0" } }, - "node_modules/pkijs/node_modules/@noble/hashes": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.4.0.tgz", - "integrity": "sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, "node_modules/playwright": { "version": "1.62.1", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz", @@ -20981,9 +20913,9 @@ } }, "node_modules/postcss-selector-parser": { - "version": "7.1.5", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.5.tgz", - "integrity": "sha512-KvvtD7SrlBP7dlgkBghEE3r84CABm5SmV2aNcG4oCA+qDnJ/tvKonFVvwWAyyWUEwxuNawdfEAZKP9zM3oZ2Uw==", + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz", + "integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==", "dev": true, "license": "MIT", "dependencies": { @@ -26409,9 +26341,9 @@ } }, "node_modules/smol-toml": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.8.0.tgz", - "integrity": "sha512-kCZr2V3ch9i00x8zXRhjUNVcjG9ijES5dDudkXvUVCT5QlJNQWElSJdZqyPemffHoLNUYwOcou0Fy+ojN0uHSQ==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.0.tgz", + "integrity": "sha512-hpd+HLON7HdZXqYchMM/+LaTTbdK0AU3NngIJ4KVyWbY9bfQqdL9cD+4yf6dUoU2Ap4VsU0JkQi6FxAI1B2mXQ==", "dev": true, "license": "BSD-3-Clause", "engines": { @@ -26501,9 +26433,9 @@ } }, "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "dev": true, "license": "BSD-3-Clause", "engines": { @@ -29469,9 +29401,9 @@ } }, "node_modules/undici": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz", - "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==", + "version": "7.30.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.0.tgz", + "integrity": "sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==", "devOptional": true, "license": "MIT", "engines": { @@ -29634,9 +29566,9 @@ "license": "MIT" }, "node_modules/unified-engine/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index 2506a408b..5d00e4372 100644 --- a/package.json +++ b/package.json @@ -263,6 +263,7 @@ "test:coverage": "node --max-old-space-size=8192 ./node_modules/vitest/vitest.mjs --config vitest.config.ts --coverage --run --reporter=dot --silent --maxWorkers 1", "test:coverage:changed": "node --max-old-space-size=8192 ./node_modules/vitest/vitest.mjs --config vitest.config.ts --coverage --changed --run --reporter=dot --silent --maxWorkers 1", "test:coverage:codecov": "npm run build:runtime-ts && node --max-old-space-size=8192 ./node_modules/vitest/vitest.mjs --config vitest.config.ts --coverage --run --reporter=dot --silent --maxWorkers 1 --coverage.include electron-app/preload/mainStateBridge.ts --coverage.include electron-app/utils/files/export/createExportGPXButton.ts --coverage.include electron-app/utils/files/import/openFileSelector.ts --coverage.include electron-app/utils/files/import/sendFitFileToAltFitReader.ts --coverage.include electron-app/utils/maps/controls/mapActionButtons.ts --coverage.include electron-app/utils/maps/controls/mapLapSelector.ts --coverage.include electron-app/utils/maps/controls/mapMeasureTool.ts --coverage.include electron-app/utils/theming/core/theme.ts --coverage.thresholds.lines 0 --coverage.thresholds.functions 0 --coverage.thresholds.branches 0 --coverage.thresholds.statements 0 tests/unit/preload.mainStateBridge.test.ts tests/unit/utils/files/export/createExportGPXButton.test.ts tests/unit/utils/files/import/openFileSelector.test.ts tests/unit/utils/files/import/sendFitFileToAltFitReader.test.ts tests/unit/maps/controls/mapActionButtons.test.ts tests/unit/maps/controls/mapLapSelector.test.ts tests/unit/maps/controls/mapMeasureTool.test.ts tests/unit/utils/theming/core/theme.test.ts", + "test:distributable": "node scripts/run-distributable-smoke.mjs", "test:integration": "npm run build:runtime-ts && node --max-old-space-size=8192 ./node_modules/vitest/vitest.mjs --config vitest.config.ts --run tests/integration --maxWorkers 1", "test:packaged": "node scripts/run-packaged-smoke.mjs", "test:playwright": "npm run build:runtime-ts && playwright test tests/playwright/app-ui.spec.ts --config playwright.config.ts", @@ -277,7 +278,7 @@ "update-actions": "npx actions-up --yes --style sha", "update-deps": "ncu --configFileName .ncurc.json --configFilePath node_modules/ncu-config-nick2bad4u && npm update --force && npm install --force && npm run sync:node-version-files", "verify:fast": "npm run sync:node-version-files:check && npm run prettier && npm run lint && npm run lint:css && npm run docs:typecheck && npm test", - "verify:full": "npm run verify:fast && npm run docs:build && npm run audit && npm run test:playwright && npm run release:check-signing && npm run package:unsigned && npm run test:packaged", + "verify:full": "npm run verify:fast && npm run docs:build && npm run audit && npm run test:playwright && npm run release:check-signing && npm run package:unsigned && npm run release:verify-signing-artifacts && npm run test:packaged", "verify:release": "npm run verify:full", "verify:release:signed": "npm run verify:fast && npm run docs:build && npm run audit && npm run test:playwright && npm run package:signed && cross-env REQUIRE_CODE_SIGNING=true npm run release:verify-signing-artifacts && npm run test:packaged" }, @@ -287,8 +288,18 @@ "eslint-plugin-n": "18.2.2", "eslint-plugin-sdl-2": "1.2.7", "eslint-plugin-test-signal": "1.2.12", + "eslint-plugin-undefined-css-classes": { + "postcss-selector-parser": "^7.1.6" + }, "eslint-plugin-unicorn": "64.0.0", "eslint-plugin-yml": "3.6.0", + "get-uri": { + "basic-ftp": "^6.2.2" + }, + "markdownlint-cli": { + "js-yaml": "^5.4.3", + "smol-toml": "^1.9.0" + }, "remark-lint-frontmatter-schema": { "@apidevtools/json-schema-ref-parser": "^15.3.5", "ajv": "^8.20.0", @@ -326,9 +337,9 @@ "cross-env": "^10.1.0", "datatables.net-dt": "^2.3.8", "date-fns": "^4.4.0", - "dompurify": "^3.4.14", - "electron": "^43.5.1", - "electron-builder": "^26.16.0", + "dompurify": "^3.4.16", + "electron": "^43.7.9", + "electron-builder": "^26.17.0", "esbuild": "^0.28.2", "eslint": "^10.9.1", "eslint-config-nick2bad4u": ">=1.2.7 <1.2.8", @@ -351,7 +362,7 @@ "leaflet.locatecontrol": "^0.90.1", "lychee-config-nick2bad4u": "^2.0.0", "makensis": "^3.0.6", - "maplibre-gl": "^5.24.0", + "maplibre-gl": "^6.13.0", "markdownlint-cli": "^0.49.1", "ncu-config-nick2bad4u": "^0.2.1", "npm-check-updates": "^22.2.9", diff --git a/packaging/macos/entitlements.adhoc.plist b/packaging/macos/entitlements.adhoc.plist new file mode 100644 index 000000000..79ce6725c --- /dev/null +++ b/packaging/macos/entitlements.adhoc.plist @@ -0,0 +1,12 @@ + + + + + + com.apple.security.cs.allow-jit + + + com.apple.security.cs.disable-library-validation + + + diff --git a/renderer-style-imports.d.ts b/renderer-style-imports.d.ts index b67e63e42..7211de9b0 100644 --- a/renderer-style-imports.d.ts +++ b/renderer-style-imports.d.ts @@ -1,6 +1,11 @@ declare module "*.css"; declare module "*.svg"; +declare module "maplibre-gl/dist/maplibre-gl-worker.mjs?raw" { + const source: string; + export default source; +} + declare module "@maplibre/maplibre-gl-leaflet"; declare module "fitfileviewer:leaflet-draw-runtime"; declare module "leaflet-draw"; diff --git a/scripts/build-ci-matrix.mjs b/scripts/build-ci-matrix.mjs index f20fd63f7..e4978533d 100644 --- a/scripts/build-ci-matrix.mjs +++ b/scripts/build-ci-matrix.mjs @@ -77,58 +77,23 @@ export function getDryRunSummary(options) { } export function getElectronBuilderArgs({ arch, matrixOs, runnerOs }) { - if (runnerOs === "Windows") { - return getWindowsBuilderArgs(arch); - } - - if (matrixOs === "macos-15") { - return [ - "--arm64", - "--publish", - "never", - ]; - } - - if (matrixOs === "macos-latest") { - return [ - "--universal", - "--publish", - "never", - ]; - } - - if (matrixOs === "macos-15-intel") { - return [ - "--mac", - `--${arch}`, - "--publish", - "never", - ]; - } - - if (matrixOs === "windows-latest") { - return getWindowsBuilderArgs(arch); - } - - if (matrixOs === "ubuntu-24.04-arm") { - return [ - "--linux", - "--arm64", - "--publish", - "never", - ]; - } - - if (matrixOs === "ubuntu-latest") { - return [ - "--linux", - `--${arch}`, - "--publish", - "never", - ]; + const platform = { Windows: "win", macOS: "mac", Linux: "linux" }[runnerOs]; + const supported = { + Windows: ["x64", "ia32"], + macOS: [ + "x64", + "arm64", + "universal", + ], + Linux: ["x64", "arm64"], + }[runnerOs]; + if (!platform || !supported.includes(arch)) { + throw new Error( + `Unsupported build matrix: ${runnerOs}/${arch} (${matrixOs})` + ); } - return [ + `--${platform}`, `--${arch}`, "--publish", "never", @@ -331,23 +296,6 @@ export function shouldRetryElectronBuilder({ matrixOs }) { ].includes(matrixOs); } -function getWindowsBuilderArgs(arch) { - if (arch === "x64") { - return [ - "--win", - "--publish", - "never", - ]; - } - - return [ - "--win", - "--ia32", - "--publish", - "never", - ]; -} - function printUsage() { console.log(`Usage: node scripts/build-ci-matrix.mjs [options] diff --git a/scripts/commit-changelog-workflow.mjs b/scripts/commit-changelog-workflow.mjs index 169a86618..a4e118cba 100644 --- a/scripts/commit-changelog-workflow.mjs +++ b/scripts/commit-changelog-workflow.mjs @@ -96,9 +96,12 @@ export function commitChangelogWorkflow(options) { [ "push", "origin", - options.targetBranch, + `HEAD:refs/heads/${options.targetBranch}`, ], - { cwd, runCommand } + { + cwd, + runCommand, + } ); log("Changelogs updated and pushed to repository"); diff --git a/scripts/get-windows-install-registrations.ps1 b/scripts/get-windows-install-registrations.ps1 new file mode 100644 index 000000000..ff9c1951f --- /dev/null +++ b/scripts/get-windows-install-registrations.ps1 @@ -0,0 +1,38 @@ +#Requires -Version 5.1 +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' +$installerGuids = @( + '141b3184-244b-5640-abaf-338415dd90dc', # Stable v29/current NSIS registration. + '2eccf151-6603-512f-93c6-ea96e8d92a75' # Transitional v30 registration. +) +$registrations = @( + foreach ($hive in @([Microsoft.Win32.RegistryHive]::CurrentUser, [Microsoft.Win32.RegistryHive]::LocalMachine)) { + foreach ($view in @([Microsoft.Win32.RegistryView]::Registry32, [Microsoft.Win32.RegistryView]::Registry64)) { + $baseKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey($hive, $view) + try { + foreach ($installerGuid in $installerGuids) { + foreach ($keyPath in @("Software\$installerGuid", "Software\Microsoft\Windows\CurrentVersion\Uninstall\$installerGuid")) { + $installationKey = $baseKey.OpenSubKey($keyPath, $false) + if ($null -ne $installationKey) { + try { + [PSCustomObject]@{ + Hive = $hive.ToString() + View = $view.ToString() + Key = $keyPath + InstallLocation = $installationKey.GetValue('InstallLocation') + } + } finally { + $installationKey.Dispose() + } + } + } + } + } finally { + $baseKey.Dispose() + } + } + } +) +ConvertTo-Json -InputObject $registrations -Compress diff --git a/scripts/run-distributable-smoke.mjs b/scripts/run-distributable-smoke.mjs new file mode 100644 index 000000000..f405f6e1e --- /dev/null +++ b/scripts/run-distributable-smoke.mjs @@ -0,0 +1,356 @@ +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import process from "node:process"; +import { pathToFileURL } from "node:url"; + +import { + repositoryRoot, + rootReleaseDistAbsolutePath, +} from "./lib/workspaces.mjs"; +import { + findPackagedElectronExecutable, + runPackagedSmoke, +} from "./run-packaged-smoke.mjs"; + +// These are the artifacts users install or extract, rather than the builder's +// intermediate unpacked tree. Exact names prevent silently testing stale builds. +export function getDistributableNames({ platform, arch, version }) { + const separator = version.indexOf("-"); + const core = separator === -1 ? version : version.slice(0, separator); + const prerelease = + separator === -1 ? undefined : version.slice(separator + 1); + if ( + !/^\d+\.\d+\.\d+$/u.test(core) || + (prerelease !== undefined && !/^[\dA-Za-z.-]+$/u.test(prerelease)) + ) { + throw new Error(`Invalid package version: ${version}`); + } + const supported = + platform === "darwin" + ? [ + "arm64", + "x64", + "universal", + ] + : platform === "win32" + ? ["x64", "ia32"] + : platform === "linux" + ? ["x64"] + : []; + if (!supported.includes(arch)) { + throw new Error( + `Unsupported distributable smoke platform/architecture: ${platform}/${arch}` + ); + } + if (platform === "darwin") { + return [`Fit-File-Viewer-dmg-${arch}-${version}.dmg`]; + } + if (platform === "win32") { + return [ + `Fit-File-Viewer-msi-${arch}-${version}.zip`, + `Fit-File-Viewer-nsis-${arch}-${version}.exe`, + `Fit-File-Viewer-portable-${arch}-${version}.exe`, + ]; + } + return [ + `Fit-File-Viewer-linux-${arch}-${version}.tar.gz`, + `Fit-File-Viewer-appimage-${arch === "x64" ? "x86_64" : arch}-${version}.AppImage`, + ]; +} + +export function runChecked(command, args, options = {}, runner = spawnSync) { + const result = runner(command, args, { + encoding: "utf8", + timeout: 300_000, + ...options, + }); + if (result.error) throw result.error; + if (result.status !== 0 || result.signal) { + throw new Error( + `${command} failed (status ${result.status}, signal ${result.signal ?? "none"}):\n${result.stdout ?? ""}\n${result.stderr ?? ""}` + ); + } + return result; +} + +export function getWindowsInstallRegistrations(run = runChecked) { + const result = run("powershell.exe", [ + "-NoProfile", + "-NonInteractive", + "-File", + path.join( + repositoryRoot, + "scripts/get-windows-install-registrations.ps1" + ), + ]); + const registrations = JSON.parse(result.stdout); + if (!Array.isArray(registrations)) { + throw new TypeError( + "Windows installation registration inspection returned invalid data" + ); + } + return registrations; +} + +export function assertNoWindowsInstallRegistrations( + inspect = getWindowsInstallRegistrations +) { + const registrations = inspect(); + if (registrations.length > 0) { + throw new Error( + `Refusing NSIS smoke installation: existing Fit File Viewer registration found. Use a clean disposable Windows runner. ${JSON.stringify(registrations)}` + ); + } +} + +export function runDistributableSmoke( + { + arch = process.env.MATRIX_ARCH ?? process.arch, + platform = process.platform, + version = JSON.parse( + fs.readFileSync(path.join(repositoryRoot, "package.json"), "utf8") + ).version, + releaseDirectory = rootReleaseDistAbsolutePath, + environment = process.env, + } = {}, + dependencies = {} +) { + const run = dependencies.run ?? runChecked; + const smoke = dependencies.smoke ?? runPackagedSmoke; + const inspectWindowsRegistrations = + dependencies.inspectWindowsRegistrations ?? + getWindowsInstallRegistrations; + const names = getDistributableNames({ platform, arch, version }); + const evidence = []; + const reportPath = path.join( + releaseDirectory, + `distributable-smoke-${platform}-${arch}.json` + ); + const writeReport = () => { + fs.writeFileSync( + reportPath, + `${JSON.stringify({ version, platform, arch, artifacts: evidence }, null, 2)}\n` + ); + }; + // Remove stale success evidence before doing any work. + fs.rmSync(reportPath, { force: true }); + for (const name of names) { + if ( + !fs + .statSync(path.join(releaseDirectory, name), { + throwIfNoEntry: false, + }) + ?.isFile() + ) { + const error = `Required distributable is missing: ${name}`; + evidence.push({ artifact: name, passed: false, error }); + writeReport(); + throw new Error(error); + } + } + for (const name of names) { + const artifact = path.resolve(releaseDirectory, name); + const directory = fs.mkdtempSync( + path.join(tmpdir(), "ffv-distributable-") + ); + let mounted = false; + let installationAttempted = false; + const mountpoint = path.join(directory, "volume"); + const destination = path.join(directory, "installed"); + fs.mkdirSync(destination); + const cleanup = () => { + let cleanupVerified = false; + try { + if (mounted) run("hdiutil", ["detach", mountpoint]); + if (installationAttempted) { + const uninstaller = path.join( + destination, + "Uninstall Fit File Viewer.exe" + ); + if (fs.existsSync(uninstaller)) + run(uninstaller, [ + "/S", + "/currentuser", + `_?=${destination}`, + ]); + // Do not remove files while an active registration points to + // them. Preserve partial installs for cleanup/diagnosis. + assertNoWindowsInstallRegistrations( + inspectWindowsRegistrations + ); + } + cleanupVerified = true; + } catch (error) { + const message = `Distributable cleanup failed; preserved ${directory}: ${error instanceof Error ? error.message : String(error)}`; + evidence.push({ + artifact: name, + passed: false, + phase: "cleanup", + error: message, + }); + writeReport(); + throw new Error(message, { cause: error }); + } finally { + // The only recursive removal is our freshly-created temp directory. + if (cleanupVerified) + fs.rmSync(directory, { + recursive: true, + force: true, + maxRetries: 5, + retryDelay: 500, + }); + } + }; + try { + console.log(`[distributable-smoke] Testing ${name}`); + if (platform === "darwin") { + run("hdiutil", [ + "attach", + "-readonly", + "-nobrowse", + "-mountpoint", + mountpoint, + artifact, + ]); + mounted = true; + run("ditto", [ + path.join(mountpoint, "Fit File Viewer.app"), + path.join(destination, "Fit File Viewer.app"), + ]); + run("hdiutil", ["detach", mountpoint]); + mounted = false; + run("codesign", [ + "--verify", + "--deep", + "--strict", + "--all-architectures", + "--verbose=2", + path.join(destination, "Fit File Viewer.app"), + ]); + } else if (platform === "win32" && name.includes("-nsis-")) { + // /D only selects files. NSIS still upgrades the global app GUID, + // and migration code can replace /D with an existing location. + assertNoWindowsInstallRegistrations( + inspectWindowsRegistrations + ); + installationAttempted = true; + run(artifact, [ + "/S", + "/currentuser", + `/D=${destination}`, + ]); + } else if (platform === "linux" && name.endsWith(".AppImage")) { + fs.chmodSync(artifact, 0o755); + run(artifact, ["--appimage-extract"], { cwd: destination }); + } else if (!name.includes("-portable-")) { + run("tar", [ + "-xf", + artifact, + "-C", + destination, + ]); + } + const executable = name.includes("-portable-") + ? artifact + : findPackagedElectronExecutable({ + releaseDistPath: destination, + platform, + }); + const architectures = + platform === "darwin" && arch === "universal" + ? ["arm64", "x64"] + : [arch]; + for (const architecture of architectures) { + let launchPath = executable; + if (platform === "darwin") { + launchPath = path.join( + directory, + `launch-${architecture}.sh` + ); + // Paths are generated locally, but quote them as shell data. + const quoted = `'${executable.replaceAll("'", String.raw`'\''`)}'`; + fs.writeFileSync( + launchPath, + `#!/bin/sh\nexec /usr/bin/arch -${architecture === "x64" ? "x86_64" : architecture} ${quoted} "$@"\n`, + { mode: 0o755 } + ); + } + if ( + smoke(["--executable", launchPath], { + ...environment, + FFV_SMOKE_EXPECTED_ARCH: architecture, + FFV_SMOKE_EXPECTED_VERSION: version, + FFV_SMOKE_DIAGNOSTICS_DIRECTORY: path.join( + releaseDirectory, + "smoke-diagnostics" + ), + }) !== 0 + ) { + throw new Error( + `Distributable smoke failed: ${name} (${architecture})` + ); + } + } + if (platform === "darwin") { + const launchPath = path.join(directory, "launch-services.sh"); + const bundle = path.join(destination, "Fit File Viewer.app"); + const quoted = `'${bundle.replaceAll("'", String.raw`'\''`)}'`; + fs.writeFileSync( + launchPath, + `#!/bin/sh\nexec /usr/bin/open -W -n -a ${quoted} --env "FFV_SMOKE_DIRECTORY=$FFV_SMOKE_DIRECTORY" --env "FFV_SMOKE_NONCE=$FFV_SMOKE_NONCE" --env "FFV_SMOKE_FIXTURE=$FFV_SMOKE_FIXTURE" --env NODE_ENV=production --env ELECTRON_IS_DEV=0 --env FFV_DISABLE_WEB_SECURITY=false --args "$@"\n`, + { mode: 0o755 } + ); + if ( + smoke(["--executable", launchPath], { + ...environment, + FFV_SMOKE_EXPECTED_ARCH: + arch === "universal" ? process.arch : arch, + FFV_SMOKE_EXPECTED_VERSION: version, + FFV_SMOKE_DIAGNOSTICS_DIRECTORY: path.join( + releaseDirectory, + "smoke-diagnostics" + ), + }) !== 0 + ) { + throw new Error(`LaunchServices smoke failed: ${name}`); + } + } + evidence.push({ + artifact: name, + architectures, + sha256: createHash("sha256") + .update(fs.readFileSync(artifact)) + .digest("hex"), + signatureVerified: platform === "darwin", + launchServicesVerified: platform === "darwin", + passed: true, + }); + writeReport(); + } catch (error) { + evidence.push({ + artifact: name, + passed: false, + error: error instanceof Error ? error.message : String(error), + }); + writeReport(); + throw error; + } finally { + cleanup(); + } + } + writeReport(); + console.log( + `[distributable-smoke] Verified ${evidence.length} final artifacts; evidence: ${reportPath}` + ); + return 0; +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + process.exitCode = runDistributableSmoke(); +} diff --git a/scripts/run-electron-builder.mjs b/scripts/run-electron-builder.mjs index 365887b96..62739b210 100644 --- a/scripts/run-electron-builder.mjs +++ b/scripts/run-electron-builder.mjs @@ -159,6 +159,9 @@ export function getUnsignedElectronBuilderEnvironment(environment) { return { ...unsignedEnvironment, + // Builder otherwise skips even ad hoc signing on pull requests. This + // environment has no publisher credentials and identity discovery is off. + CSC_FOR_PULL_REQUEST: "true", CSC_IDENTITY_AUTO_DISCOVERY: "false", REQUIRE_CODE_SIGNING: "false", }; diff --git a/scripts/run-packaged-smoke.mjs b/scripts/run-packaged-smoke.mjs index 78fad4008..ab80c39fe 100644 --- a/scripts/run-packaged-smoke.mjs +++ b/scripts/run-packaged-smoke.mjs @@ -1,14 +1,15 @@ import { spawnSync } from "node:child_process"; +import { randomUUID } from "node:crypto"; import { accessSync, closeSync, constants, existsSync, + mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, - rmSync, } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -20,7 +21,7 @@ import { rootReleaseDistAbsolutePath, } from "./lib/workspaces.mjs"; -const defaultStartupTimeoutMs = 10_000; +const defaultStartupTimeoutMs = 60_000; const failureOutputMarkers = [ "cannot find module", "err_file_not_found", @@ -35,10 +36,27 @@ export function parseArgs(argv = []) { let executablePath; let releaseDistPath; let startupTimeoutMs; + let fixturePath; for (let index = 0; index < argv.length; index += 1) { const arg = argv[index]; + if (arg === "--fixture") { + fixturePath = argv[index + 1]; + if (!fixturePath || fixturePath.startsWith("-")) { + throw new Error("--fixture requires a value"); + } + index += 1; + continue; + } + if (arg.startsWith("--fixture=")) { + fixturePath = arg.slice("--fixture=".length); + if (!fixturePath) { + throw new Error("--fixture must not be empty"); + } + continue; + } + if (arg === "--executable") { executablePath = argv[index + 1]; if (!executablePath || executablePath.startsWith("-")) { @@ -89,7 +107,7 @@ export function parseArgs(argv = []) { throw new Error(`Unknown argument: ${arg}`); } - return { executablePath, releaseDistPath, startupTimeoutMs }; + return { executablePath, releaseDistPath, startupTimeoutMs, fixturePath }; } export function getPackagedExecutableCandidates({ @@ -178,7 +196,7 @@ export function runPackagedSmoke( commandRunner = spawnSync, logger = console.log ) { - const { executablePath, releaseDistPath, startupTimeoutMs } = + const { executablePath, releaseDistPath, startupTimeoutMs, fixturePath } = parseArgs(argv); const configuredExecutablePath = executablePath ?? environment.FFV_PACKAGED_APP; @@ -206,12 +224,26 @@ export function runPackagedSmoke( `[packaged-smoke] Launching ${resolvedExecutablePath} for ${timeoutMs}ms` ); - const { outputFiles, result } = runWithCapturedOutput( - commandRunner, - resolvedExecutablePath, - timeoutMs, - environment + const resolvedFixturePath = path.resolve( + fixturePath ?? + path.join( + repositoryRoot, + "fit-test-files", + "_Fenton_Michigan_Afternoon_Ride_5_27_miles.fit" + ) ); + if (!existsSync(resolvedFixturePath)) { + throw new Error(`Smoke FIT fixture not found: ${resolvedFixturePath}`); + } + const { outputFiles, result, captureDirectory, nonce } = + runWithCapturedOutput( + commandRunner, + resolvedExecutablePath, + timeoutMs, + environment, + resolvedFixturePath, + logger + ); const output = [ outputFiles.stdout, outputFiles.stderr, @@ -222,17 +254,18 @@ export function runPackagedSmoke( .join("\n"); const timedOut = result.error?.code === "ETIMEDOUT"; - assertNoStartupFailureOutput(output, { timedOut }); + assertNoStartupFailureOutput(output); if (result.error && !timedOut) { throw result.error; } - if (!timedOut && result.status !== null && result.status !== undefined) { + if (timedOut || result.signal || result.status !== 0) { throw new Error( [ - `Packaged app exited before the ${timeoutMs}ms startup smoke window.`, - `Exit status: ${result.status}`, + `Packaged app did not complete its startup smoke within ${timeoutMs}ms.`, + `Exit status: ${result.status}; signal: ${result.signal ?? "none"}; timed out: ${timedOut}`, + `Diagnostics: ${captureDirectory}`, output.trim() ? `Output:\n${output.trim()}` : "", ] .filter(Boolean) @@ -240,7 +273,52 @@ export function runPackagedSmoke( ); } - logger("[packaged-smoke] Packaged app stayed alive without fatal output"); + const reportPath = path.join(captureDirectory, "report.json"); + if (!existsSync(reportPath)) { + throw new Error( + `Packaged app exited without a readiness report. Diagnostics: ${captureDirectory}` + ); + } + const report = JSON.parse(readFileSync(reportPath, "utf8")); + if ( + report === null || + typeof report !== "object" || + report.nonce !== nonce || + report.status !== "passed" || + report.visible !== true || + !Number.isSafeInteger(report.activity?.recordCount) || + report.activity.recordCount < 1 || + report.activity.appInitialized !== true || + report.activity.mapReady !== true || + !Number.isSafeInteger(report.activity.routeCount) || + report.activity.routeCount < 1 || + !Number.isSafeInteger(report.activity?.sessionCount) || + report.activity.sessionCount < 1 + ) { + throw new Error( + `Packaged app returned an invalid readiness report. Diagnostics: ${captureDirectory}` + ); + } + if ( + environment.FFV_SMOKE_EXPECTED_ARCH && + report.arch !== environment.FFV_SMOKE_EXPECTED_ARCH + ) { + throw new Error( + `Packaged app architecture ${report.arch} does not match ${environment.FFV_SMOKE_EXPECTED_ARCH}. Diagnostics: ${captureDirectory}` + ); + } + if ( + environment.FFV_SMOKE_EXPECTED_VERSION && + report.version !== environment.FFV_SMOKE_EXPECTED_VERSION + ) { + throw new Error( + `Packaged app version ${report.version} does not match ${environment.FFV_SMOKE_EXPECTED_VERSION}. Diagnostics: ${captureDirectory}` + ); + } + logger( + `[packaged-smoke] Verified visible renderer, preload IPC, FIT activity and rendered map: ${JSON.stringify(report)}` + ); + logger(`[packaged-smoke] Diagnostics: ${captureDirectory}`); return 0; } @@ -311,11 +389,19 @@ function runWithCapturedOutput( commandRunner, resolvedExecutablePath, timeoutMs, - environment + environment, + fixturePath, + logger ) { + const diagnosticsRoot = environment.FFV_SMOKE_DIAGNOSTICS_DIRECTORY + ? path.resolve(environment.FFV_SMOKE_DIAGNOSTICS_DIRECTORY) + : tmpdir(); + mkdirSync(diagnosticsRoot, { recursive: true }); const captureDirectory = mkdtempSync( - path.join(tmpdir(), "ffv-packaged-smoke-") + path.join(diagnosticsRoot, "ffv-packaged-smoke-") ); + const nonce = randomUUID(); + logger(`[packaged-smoke] Diagnostics: ${captureDirectory}`); const stderrPath = path.join(captureDirectory, "stderr.log"), stdoutPath = path.join(captureDirectory, "stdout.log"); const stderrDescriptor = openSync(stderrPath, "w"), @@ -324,13 +410,20 @@ function runWithCapturedOutput( try { const result = commandRunner( resolvedExecutablePath, - getPackagedLaunchArgs(environment), + [ + ...getPackagedLaunchArgs(environment), + "--ffv-smoke-test", + `--user-data-dir=${path.join(captureDirectory, "user-data")}`, + ], { cwd: repositoryRoot, env: { ...environment, ELECTRON_IS_DEV: "0", FFV_DISABLE_WEB_SECURITY: "false", + FFV_SMOKE_DIRECTORY: captureDirectory, + FFV_SMOKE_NONCE: nonce, + FFV_SMOKE_FIXTURE: fixturePath, NODE_ENV: "production", }, encoding: "utf8", @@ -345,6 +438,8 @@ function runWithCapturedOutput( ); return { + captureDirectory, + nonce, outputFiles: { stderr: readFileSync(stderrPath, "utf8"), stdout: readFileSync(stdoutPath, "utf8"), @@ -354,7 +449,6 @@ function runWithCapturedOutput( } finally { closeFileDescriptor(stdoutDescriptor); closeFileDescriptor(stderrDescriptor); - rmSync(captureDirectory, { force: true, recursive: true }); } } @@ -372,21 +466,13 @@ function closeFileDescriptor(descriptor) { } } -function assertNoStartupFailureOutput(output, { timedOut = false } = {}) { +function assertNoStartupFailureOutput(output) { const normalizedOutput = output.toLowerCase(); for (const marker of failureOutputMarkers) { if (!normalizedOutput.includes(marker)) { continue; } - if ( - marker === "error loading main html file" && - timedOut && - normalizedOutput.includes("window displayed successfully") - ) { - continue; - } - throw new Error( [ `Packaged app startup output matched failure marker "${marker}".`, @@ -463,7 +549,7 @@ function parseStartupTimeoutMs(value) { throw new Error("--startup-timeout-ms requires a value"); } - const parsed = Number.parseInt(value, 10); + const parsed = Number(value); if (!Number.isSafeInteger(parsed) || parsed < 1000) { throw new Error("--startup-timeout-ms must be an integer >= 1000"); } diff --git a/scripts/verify-release-assets.mjs b/scripts/verify-release-assets.mjs index 55717a733..94a61b93e 100644 --- a/scripts/verify-release-assets.mjs +++ b/scripts/verify-release-assets.mjs @@ -198,13 +198,25 @@ export function verifyReleaseAssets({ const referencedAssetNames = new Set(); for (const metadataName of requiredUpdaterMetadataNames) { - const releaseMetadataAsset = releaseAssetsByName.get(metadataName); - if (!releaseMetadataAsset) { + if (!releaseAssetsByName.has(metadataName)) { throw new Error( `Release is missing required updater metadata: ${metadataName}` ); } + } + const metadataNames = new Set( + [...localFilesByName.keys(), ...releaseAssetsByName.keys()].filter( + (name) => /^latest.*\.yml$/u.test(name) + ) + ); + for (const metadataName of metadataNames) { + const releaseMetadataAsset = releaseAssetsByName.get(metadataName); + if (!releaseMetadataAsset) { + throw new Error( + `Updater metadata was not uploaded: ${metadataName}` + ); + } const metadataPath = getUniqueLocalFile(localFilesByName, metadataName); const metadata = parseUpdaterMetadata(metadataPath, metadataName); if (metadata.version !== expectedVersion) { @@ -228,6 +240,39 @@ export function verifyReleaseAssets({ referencedAssetNames.add(fileEntry.url); } + if (metadata.packages !== undefined) { + if ( + !metadata.packages || + typeof metadata.packages !== "object" || + Array.isArray(metadata.packages) + ) { + throw new Error(`${metadataName} contains invalid packages`); + } + for (const [arch, packageEntry] of Object.entries( + metadata.packages + )) { + if ( + !packageEntry || + typeof packageEntry !== "object" || + !Number.isSafeInteger(packageEntry.size) || + packageEntry.size < 0 || + (packageEntry.file !== undefined && + packageEntry.file !== packageEntry.path) + ) { + throw new Error( + `${metadataName} contains an invalid ${arch} package` + ); + } + verifyUpdaterFileEntry({ + fileEntry: { ...packageEntry, url: packageEntry.path }, + localFilesByName, + metadataName, + releaseAssetsByName, + }); + referencedAssetNames.add(packageEntry.path); + } + } + const primaryEntry = metadata.files.find( (fileEntry) => fileEntry.url === metadata.path ); @@ -239,7 +284,7 @@ export function verifyReleaseAssets({ } return { - metadataCount: requiredUpdaterMetadataNames.length, + metadataCount: metadataNames.size, referencedAssetCount: referencedAssetNames.size, }; } @@ -297,8 +342,14 @@ function verifyUpdaterFileEntry({ if ( !fileEntry || typeof fileEntry !== "object" || + Array.isArray(fileEntry) || typeof fileEntry.url !== "string" || - typeof fileEntry.sha512 !== "string" + !/^[^/\\:?#%]+$/u.test(fileEntry.url) || + fileEntry.url === "." || + fileEntry.url === ".." || + typeof fileEntry.sha512 !== "string" || + (fileEntry.size !== undefined && + (!Number.isSafeInteger(fileEntry.size) || fileEntry.size < 0)) ) { throw new Error(`${metadataName} contains an invalid files entry`); } diff --git a/scripts/verify-signed-artifacts.mjs b/scripts/verify-signed-artifacts.mjs index ccd3d9256..a9f318d36 100644 --- a/scripts/verify-signed-artifacts.mjs +++ b/scripts/verify-signed-artifacts.mjs @@ -146,7 +146,11 @@ export function collectSigningVerificationArtifacts(releaseDir, platform) { return []; } -export function createSigningVerificationCommand(artifactPath, platform) { +export function createSigningVerificationCommand( + artifactPath, + platform, + { signingRequired = false } = {} +) { if (platform === "win32") { return { args: [ @@ -167,7 +171,14 @@ export function createSigningVerificationCommand(artifactPath, platform) { "--verify", "--deep", "--strict", + "--all-architectures", "--verbose=2", + ...(signingRequired + ? [ + "--test-requirement", + "=anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists", + ] + : []), artifactPath, ], command: "codesign", @@ -184,13 +195,16 @@ export function verifySignedArtifacts( logger = console.log ) { const { platform, releaseDir, reportPath } = parseArgs(argv); + const signingRequired = environment.REQUIRE_CODE_SIGNING === "true"; - if (environment.REQUIRE_CODE_SIGNING !== "true" || platform === "linux") { + // Apple Silicon requires intact code signatures even without a publisher + // certificate. Unsigned Windows artifacts have no equivalent requirement. + if ((!signingRequired && platform !== "darwin") || platform === "linux") { const report = writeSigningVerificationReport(reportPath, { artifacts: [], platform, releaseDir, - signingRequired: environment.REQUIRE_CODE_SIGNING === "true", + signingRequired, status: "skipped", }); appendSigningVerificationSummary( @@ -209,7 +223,7 @@ export function verifySignedArtifacts( error: `No signed artifact candidates found in ${releaseDir} for ${platform}`, platform, releaseDir, - signingRequired: true, + signingRequired, status: "failed", }); appendSigningVerificationSummary( @@ -224,7 +238,8 @@ export function verifySignedArtifacts( for (const artifactPath of artifacts) { const { args, command } = createSigningVerificationCommand( artifactPath, - platform + platform, + { signingRequired } ); const result = commandRunner(command, args, { cwd: repositoryRoot, @@ -252,7 +267,7 @@ export function verifySignedArtifacts( error: result.error.message, platform, releaseDir, - signingRequired: true, + signingRequired, status: "failed", verificationResults, }); @@ -269,7 +284,7 @@ export function verifySignedArtifacts( error: `Signing verification command exited with status ${result.status ?? 1}`, platform, releaseDir, - signingRequired: true, + signingRequired, status: "failed", verificationResults, }); @@ -285,7 +300,7 @@ export function verifySignedArtifacts( artifacts, platform, releaseDir, - signingRequired: true, + signingRequired, status: "verified", verificationResults, }); @@ -304,7 +319,7 @@ export function appendSigningVerificationSummary(summaryPath, report) { "", `- Status: \`${report.status}\``, `- Platform: \`${report.platform}\``, - `- Signing required: \`${String(report.signingRequired)}\``, + `- Publisher signing required: \`${String(report.signingRequired)}\``, `- Artifact count: \`${String(report.artifactCount)}\``, ]; diff --git a/tests/playwright/app-ui.spec.ts b/tests/playwright/app-ui.spec.ts index 7016ec39a..382357ca3 100644 --- a/tests/playwright/app-ui.spec.ts +++ b/tests/playwright/app-ui.spec.ts @@ -586,6 +586,165 @@ test.describe("FitFileViewer renderer environment fallbacks", () => { }); }); +test("renders offline MapLibre GeoJSON under the production file CSP after map recreation", async () => { + const profile = createElectronLaunchProfile(); + const app = await electron.launch({ + args: profile.args, + cwd: repositoryRoot, + env: createElectronLaunchEnv(), + }); + + try { + const mapPage = await app.firstWindow(); + const errors: string[] = []; + const workerUrls: string[] = []; + mapPage.on("pageerror", (error) => errors.push(error.message)); + mapPage.on("worker", (worker) => workerUrls.push(worker.url())); + await mapPage.waitForLoadState("domcontentloaded"); + expect(new URL(mapPage.url()).protocol).toBe("file:"); + expect( + await app.evaluate( + ({ BrowserWindow }) => + BrowserWindow.getAllWindows()[0]?.webContents.getLastWebPreferences() + .webSecurity + ) + ).toBe(true); + + const results = await mapPage.evaluate(async () => { + const loadModule = async (relativePath: string): Promise => { + const moduleUrl = new URL(relativePath, window.location.href) + .href; + // eslint-disable-next-line no-unsanitized/method -- Only fixed application module paths are passed below. + return import(moduleUrl) as Promise; + }; + const vendors = await loadModule<{ + ensureRendererVendorBundle: (entry: "map") => Promise; + }>("./renderer/vendorBundleLoader.js"); + await vendors.ensureRendererVendorBundle("map"); + const leafletRegistry = await loadModule<{ + resolveLeafletRuntime: ( + predicate: (candidate: unknown) => boolean + ) => typeof import("leaflet") | null; + }>("./utils/maps/core/leafletRuntime.js"); + const factoryRegistry = await loadModule<{ + resolveMapLibreLayerFactory: () => + | (( + options: Record + ) => import("leaflet").Layer & { + getMaplibreMap: () => import("maplibre-gl").Map; + }) + | null; + }>("./utils/maps/layers/mapLibreLayerRuntime.js"); + const leaflet = leafletRegistry.resolveLeafletRuntime( + (candidate) => + typeof candidate === "object" && candidate !== null + ); + const createLayer = factoryRegistry.resolveMapLibreLayerFactory(); + if (!leaflet || !createLayer) { + throw new Error( + "The production MapLibre Leaflet bridge did not register" + ); + } + + const renders: number[] = []; + // Exercise the worker-backed renderer again after removing the map; + // MapLibre may retain shared workers for its global dispatcher. + for (let cycle = 0; cycle < 2; cycle += 1) { + const container = document.createElement("div"); + container.style.cssText = + "position:fixed;inset:0;width:512px;height:512px;z-index:99999"; + document.body.append(container); + const map = new leaflet.Map(container, { + zoomControl: false, + }).setView([0, 0], 3); + try { + const layer = createLayer({ + attributionControl: false, + style: { + version: 8, + sources: { + fixture: { + type: "geojson", + data: { + type: "FeatureCollection", + features: [ + { + type: "Feature", + properties: { + fixture: "offline-worker", + }, + geometry: { + type: "Point", + coordinates: [0, 0], + }, + }, + ], + }, + }, + }, + layers: [ + { + id: "fixture-circle", + type: "circle", + source: "fixture", + paint: { + "circle-radius": 24, + "circle-color": "#ff0000", + }, + }, + ], + }, + }); + layer.addTo(map); + const glMap = layer.getMaplibreMap(); + await new Promise((resolve, reject) => { + const timeout = window.setTimeout( + () => + reject( + new Error( + "Offline MapLibre worker/render timed out" + ) + ), + 15_000 + ); + glMap.once("error", (event) => { + window.clearTimeout(timeout); + reject(event.error); + }); + glMap.once("idle", () => { + window.clearTimeout(timeout); + resolve(); + }); + }); + renders.push( + glMap + .queryRenderedFeatures({ + layers: ["fixture-circle"], + }) + .filter( + (feature) => + feature.properties.fixture === + "offline-worker" + ).length + ); + } finally { + map.remove(); + container.remove(); + } + } + return renders; + }); + + expect(results).toStrictEqual([1, 1]); + expect(workerUrls.length).toBeGreaterThanOrEqual(1); + expect(workerUrls.every((url) => url.startsWith("blob:"))).toBe(true); + expect(errors).toStrictEqual([]); + } finally { + await closeElectronApp(app); + removeElectronLaunchProfile(profile); + } +}); + test.describe("FitFileViewer Playwright fixtures", () => { test("keeps the sample FIT file stable", () => { expect({ diff --git a/tests/unit/packaging/architectureBoundaries.test.ts b/tests/unit/packaging/architectureBoundaries.test.ts index 687372bda..a33267c95 100644 --- a/tests/unit/packaging/architectureBoundaries.test.ts +++ b/tests/unit/packaging/architectureBoundaries.test.ts @@ -36111,7 +36111,7 @@ describe("architecture boundaries", () => { "setMapLibreLayerFactory" ); expect(rendererVendorMapSource).toContain( - "registerMapLibreLayerFactory" + "map: { leafletRuntime: Leaflet, mapLibreLayerFactory }" ); expect(violations).toStrictEqual([]); }); diff --git a/tests/unit/packaging/buildCiMatrix.test.ts b/tests/unit/packaging/buildCiMatrix.test.ts index 770ffec31..26155ccec 100644 --- a/tests/unit/packaging/buildCiMatrix.test.ts +++ b/tests/unit/packaging/buildCiMatrix.test.ts @@ -90,6 +90,30 @@ async function importBuildCiMatrix(): Promise { } describe("build-ci-matrix script", () => { + it("uses the requested architecture independently of the runner label and rejects unsupported Windows architectures", async () => { + expect.assertions(2); + const { getElectronBuilderArgs } = await importBuildCiMatrix(); + expect( + getElectronBuilderArgs({ + runnerOs: "macOS", + matrixOs: "macos-latest", + arch: "arm64", + }) + ).toStrictEqual([ + "--mac", + "--arm64", + "--publish", + "never", + ]); + expect(() => + getElectronBuilderArgs({ + runnerOs: "Windows", + matrixOs: "windows-latest", + arch: "arm64", + }) + ).toThrow("Unsupported build matrix"); + }); + it("selects electron-builder args for the GitHub build matrix", async () => { expect.assertions(1); @@ -99,6 +123,7 @@ describe("build-ci-matrix script", () => { arch: "x64", builderArgs: [ "--win", + "--x64", "--publish", "never", ], @@ -119,6 +144,7 @@ describe("build-ci-matrix script", () => { { arch: "arm64", builderArgs: [ + "--mac", "--arm64", "--publish", "never", @@ -129,6 +155,7 @@ describe("build-ci-matrix script", () => { { arch: "universal", builderArgs: [ + "--mac", "--universal", "--publish", "never", @@ -172,6 +199,7 @@ describe("build-ci-matrix script", () => { { arch: "arm64", builderArgs: [ + "--linux", "--arm64", "--publish", "never", @@ -255,6 +283,7 @@ describe("build-ci-matrix script", () => { args: [ runElectronBuilderScriptPath, "--win", + "--x64", "--publish", "never", ], diff --git a/tests/unit/packaging/candidateUpgradeWorkflow.test.ts b/tests/unit/packaging/candidateUpgradeWorkflow.test.ts index 46e736698..77bab5835 100644 --- a/tests/unit/packaging/candidateUpgradeWorkflow.test.ts +++ b/tests/unit/packaging/candidateUpgradeWorkflow.test.ts @@ -5,7 +5,7 @@ import { describe, expect, it } from "vitest"; describe("candidate upgrade workflow", () => { it("builds and installs the unsigned Windows candidate over a published release", () => { - expect.assertions(18); + expect.assertions(23); const workflow = fs.readFileSync( path.join( @@ -15,6 +15,17 @@ describe("candidate upgrade workflow", () => { "utf8" ); + expect(workflow).toContain("--startup-timeout-ms 60000"); + expect(workflow).toContain("FFV_SMOKE_EXPECTED_ARCH: x64"); + expect(workflow).toContain( + "FFV_SMOKE_EXPECTED_VERSION: ${{ env.FFV_CANDIDATE_VERSION }}" + ); + expect(workflow).toContain( + "FFV_SMOKE_DIAGNOSTICS_DIRECTORY: ${{ runner.temp }}/candidate-upgrade-smoke" + ); + expect(workflow).toContain( + "${{ runner.temp }}/candidate-upgrade-smoke/" + ); expect(workflow).toContain("workflow_dispatch:"); expect(workflow).toContain("from-version:"); expect(workflow).toContain('"ffv-candidate-upgrade-$env:FROM_VERSION"'); diff --git a/tests/unit/packaging/commitChangelogWorkflow.test.ts b/tests/unit/packaging/commitChangelogWorkflow.test.ts index 9b25c0435..b7b13f5aa 100644 --- a/tests/unit/packaging/commitChangelogWorkflow.test.ts +++ b/tests/unit/packaging/commitChangelogWorkflow.test.ts @@ -152,7 +152,7 @@ describe("commit-changelog-workflow script", () => { `add ${rootChangelogPath}`, "diff --staged --quiet", "commit -m ๐Ÿ“ [docs] Update changelog for v30.0.0 [skip ci]", - "push origin release", + "push origin HEAD:refs/heads/release", ], didCommit: true, messages: ["Changelogs updated and pushed to repository"], diff --git a/tests/unit/packaging/electronBuilderConfig.test.ts b/tests/unit/packaging/electronBuilderConfig.test.ts index 28fc8914d..8f094018f 100644 --- a/tests/unit/packaging/electronBuilderConfig.test.ts +++ b/tests/unit/packaging/electronBuilderConfig.test.ts @@ -24,7 +24,12 @@ type ElectronBuilderConfig = { maintainer: string; }; mac: { + entitlements?: string; + entitlementsInherit?: string; + hardenedRuntime: boolean; icon: string; + identity?: string; + notarize?: boolean; }; nsis: { guid: string; @@ -160,6 +165,42 @@ describe("electron-builder config", () => { expect(builderConfig.squirrelWindows).toBeUndefined(); }); + it("signs macOS builds without a publisher certificate using ad hoc entitlements", () => { + expect.assertions(7); + + const builderConfig = loadBuilderConfig("false"); + const entitlements = readFileSync( + path.join(process.cwd(), builderConfig.mac.entitlements ?? ""), + "utf8" + ); + + expect(builderConfig.mac.identity).toBe("-"); + expect(builderConfig.mac.hardenedRuntime).toBe(true); + expect(builderConfig.mac.entitlementsInherit).toBe( + builderConfig.mac.entitlements + ); + expect(builderConfig.mac.notarize).toBe(false); + expect(entitlements).toMatch( + /com\.apple\.security\.cs\.allow-jit<\/key>\s*/u + ); + expect(entitlements).toMatch( + /com\.apple\.security\.cs\.disable-library-validation<\/key>\s*/u + ); + expect(entitlements).not.toContain("allow-unsigned-executable-memory"); + }); + + it("preserves certificate discovery and notarization for publisher-signed macOS builds", () => { + expect.assertions(5); + + const builderConfig = loadBuilderConfig("true"); + + expect(builderConfig.mac.identity).toBeUndefined(); + expect(builderConfig.mac.entitlements).toBeUndefined(); + expect(builderConfig.mac.entitlementsInherit).toBeUndefined(); + expect(builderConfig.mac.notarize).toBeUndefined(); + expect(builderConfig.mac.hardenedRuntime).toBe(true); + }); + it("applies Electron fuses through afterPack before signing", async () => { expect.assertions(3); diff --git a/tests/unit/packaging/packagedSmokeRuntime.test.ts b/tests/unit/packaging/packagedSmokeRuntime.test.ts new file mode 100644 index 000000000..c862f8320 --- /dev/null +++ b/tests/unit/packaging/packagedSmokeRuntime.test.ts @@ -0,0 +1,175 @@ +import { EventEmitter } from "node:events"; +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import type { App, BrowserWindow } from "electron"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { configurePackagedSmoke } from "../../../electron-app/main/runtime/packagedSmoke.js"; +import { approveFilePath } from "../../../electron-app/main/security/fileAccessPolicy.js"; +import { setAutoUpdaterInitialized } from "../../../electron-app/main/state/appState.js"; + +vi.mock("../../../electron-app/main/security/fileAccessPolicy.js", () => ({ + approveFilePath: vi.fn(), +})); +vi.mock("../../../electron-app/main/state/appState.js", () => ({ + setAutoUpdaterInitialized: vi.fn(), +})); + +let directory = ""; +const originalArguments = [...process.argv]; + +beforeEach(() => { + vi.clearAllMocks(); + directory = mkdtempSync(path.join(os.tmpdir(), "ffv-smoke-runtime-test-")); + vi.stubEnv("FFV_SMOKE_DIRECTORY", directory); + vi.stubEnv("FFV_SMOKE_NONCE", "test-nonce"); + vi.stubEnv("FFV_SMOKE_FIXTURE", path.join(directory, "activity.fit")); + process.argv = [...originalArguments, "--ffv-smoke-test"]; +}); + +afterEach(() => { + process.argv = originalArguments; + vi.unstubAllEnvs(); + rmSync(directory, { recursive: true, force: true }); +}); + +function createApp() { + return Object.assign(new EventEmitter(), { + setPath: vi.fn(), + getVersion: () => "30.0.3", + exit: vi.fn(), + }); +} + +function createWindow() { + return { + isVisible: vi.fn().mockReturnValue(true), + isDestroyed: vi.fn().mockReturnValue(false), + webContents: Object.assign(new EventEmitter(), { + getURL: () => "file:///app/dist/index.html", + executeJavaScript: vi + .fn() + .mockResolvedValueOnce(true) + .mockResolvedValueOnce({ recordCount: 1285, sessionCount: 1 }), + capturePage: vi + .fn() + .mockResolvedValue({ toPNG: () => Buffer.from("screenshot") }), + }), + }; +} + +describe("packaged smoke runtime", () => { + it("leaves normal startup untouched", () => { + expect.assertions(3); + process.argv = originalArguments; + const app = createApp(); + configurePackagedSmoke(app as unknown as App); + expect(app.setPath).not.toHaveBeenCalled(); + expect(setAutoUpdaterInitialized).not.toHaveBeenCalled(); + expect(existsSync(path.join(directory, "user-data"))).toBe(false); + }); + + it("rejects incomplete opt-in configuration before startup", () => { + expect.assertions(1); + vi.stubEnv("FFV_SMOKE_NONCE", ""); + expect(() => + configurePackagedSmoke(createApp() as unknown as App) + ).toThrow("requires an absolute report directory"); + }); + + it("isolates the profile, prevents updates and writes a successful visible FIT report", async () => { + expect.assertions(6); + const app = createApp(); + const window = createWindow(); + configurePackagedSmoke(app as unknown as App); + app.emit( + "browser-window-created", + {}, + window as unknown as BrowserWindow + ); + await vi.waitUntil(() => app.exit.mock.calls.length > 0); + expect(app.exit).toHaveBeenCalledWith(0); + expect(app.setPath).toHaveBeenCalledWith( + "userData", + path.join(directory, "user-data") + ); + expect(setAutoUpdaterInitialized).toHaveBeenCalledWith(true); + expect(approveFilePath).toHaveBeenCalledWith( + path.join(directory, "activity.fit"), + { source: "packaged-smoke" } + ); + expect( + JSON.parse( + readFileSync(path.join(directory, "report.json"), "utf8") + ) + ).toMatchObject({ + nonce: "test-nonce", + status: "passed", + visible: true, + activity: { recordCount: 1285, sessionCount: 1 }, + }); + expect( + readFileSync(path.join(directory, "screenshot.png"), "utf8") + ).toBe("screenshot"); + }); + + it("reports FIT parsing failures and exits unsuccessfully", async () => { + expect.assertions(2); + const app = createApp(); + const window = createWindow(); + window.webContents.executeJavaScript + .mockReset() + .mockResolvedValueOnce(true) + .mockRejectedValueOnce(new Error("FIT smoke failed: read denied")); + configurePackagedSmoke(app as unknown as App); + app.emit( + "browser-window-created", + {}, + window as unknown as BrowserWindow + ); + await vi.waitUntil(() => app.exit.mock.calls.length > 0); + expect(app.exit).toHaveBeenCalledWith(1); + expect( + JSON.parse( + readFileSync(path.join(directory, "report.json"), "utf8") + ) + ).toMatchObject({ + status: "failed", + error: "FIT smoke failed: read denied", + }); + }); + + it("fails renderer crashes even if the load probe later resolves", async () => { + expect.assertions(2); + const app = createApp(); + const window = createWindow(); + window.webContents.executeJavaScript + .mockReset() + .mockImplementationOnce(async () => { + window.webContents.emit( + "render-process-gone", + {}, + { reason: "crashed", exitCode: 11 } + ); + return true; + }) + .mockResolvedValueOnce({ recordCount: 1285, sessionCount: 1 }); + configurePackagedSmoke(app as unknown as App); + app.emit( + "browser-window-created", + {}, + window as unknown as BrowserWindow + ); + await vi.waitUntil(() => app.exit.mock.calls.length > 0); + expect(app.exit).toHaveBeenCalledWith(1); + expect( + JSON.parse( + readFileSync(path.join(directory, "report.json"), "utf8") + ) + ).toMatchObject({ + status: "failed", + error: "Renderer terminated: crashed (11)", + }); + }); +}); diff --git a/tests/unit/packaging/publishedUpgradeWorkflow.test.ts b/tests/unit/packaging/publishedUpgradeWorkflow.test.ts index db0b4bb61..3a8969b18 100644 --- a/tests/unit/packaging/publishedUpgradeWorkflow.test.ts +++ b/tests/unit/packaging/publishedUpgradeWorkflow.test.ts @@ -5,7 +5,7 @@ import { describe, expect, it } from "vitest"; describe("published upgrade smoke workflow", () => { it("upgrades the previous Windows release after successful publication", () => { - expect.assertions(17); + expect.assertions(23); const workflow = readFileSync( path.join( @@ -22,9 +22,23 @@ describe("published upgrade smoke workflow", () => { "utf8" ); + expect(workflow).toContain("--startup-timeout-ms 60000"); + expect(workflow).toContain("FFV_SMOKE_EXPECTED_ARCH: x64"); + expect(workflow).toContain( + "FFV_SMOKE_EXPECTED_VERSION: ${{ env.FFV_UPGRADE_TO_VERSION }}" + ); + expect(workflow).toContain( + "FFV_SMOKE_DIAGNOSTICS_DIRECTORY: ${{ runner.temp }}/published-upgrade-smoke" + ); + expect(workflow).toContain( + "${{ runner.temp }}/published-upgrade-smoke/" + ); + expect(workflow).toContain( + "ref: ${{ github.event.workflow_run.head_sha || github.sha }}" + ); expect(workflow).toContain("workflow_run:"); expect(workflow).toContain( - 'workflows: ["Build And Release Electron App"]' + 'workflows: ["Build and Release Electron App"]' ); expect(workflow).toContain( "github.event.workflow_run.conclusion == 'success'" diff --git a/tests/unit/packaging/releaseRehearsalWorkflow.test.ts b/tests/unit/packaging/releaseRehearsalWorkflow.test.ts index e4fb897c1..596a68863 100644 --- a/tests/unit/packaging/releaseRehearsalWorkflow.test.ts +++ b/tests/unit/packaging/releaseRehearsalWorkflow.test.ts @@ -16,7 +16,7 @@ function readReleaseRehearsalWorkflow(): string { describe("release rehearsal workflow", () => { it("runs the release gate, signing preflight, packaged smoke, and artifact upload without publishing", () => { - expect.assertions(43); + expect.assertions(46); const workflow = readReleaseRehearsalWorkflow(); @@ -84,9 +84,10 @@ describe("release rehearsal workflow", () => { "WIN_CSC_LINK: ${{ matrix.runner-os == 'Windows' && secrets.WINDOWS_CSC_LINK || '' }}" ); expect(workflow).toContain("xvfb-run -a npm run release:verify"); - expect(workflow).toContain( - "release-verify-command: npm run release:verify" - ); + expect(workflow).toContain("npm run build:ci-matrix"); + expect(workflow).toContain("node scripts/run-distributable-smoke.mjs"); + expect(workflow).toContain("arch: universal"); + expect(workflow).toContain("arch: ia32"); expect(workflow).toContain("FFV_PACKAGED_SMOKE_TIMEOUT_MS:"); expect(workflow).toContain('FFV_FORCE_UNSIGNED_PACKAGE: "true"'); expect(workflow).toContain('CSC_IDENTITY_AUTO_DISCOVERY: "false"'); @@ -94,9 +95,9 @@ describe("release rehearsal workflow", () => { expect(workflow).toContain('REQUIRE_CODE_SIGNING: "false"'); expect(workflow).toContain("actions/upload-artifact@"); expect(workflow).toContain( - "name: release-rehearsal-${{ matrix.runner-os }}" + "name: release-rehearsal-${{ matrix.os }}-${{ matrix.arch }}" ); - expect(workflow).toContain("path: release-dist/**"); + expect(workflow).toContain("release-dist/distributable-smoke-*.json"); expect(workflow).not.toContain("softprops/action-gh-release"); expect(workflow).not.toContain("npm run package:signed"); }); diff --git a/tests/unit/packaging/runDistributableSmoke.test.ts b/tests/unit/packaging/runDistributableSmoke.test.ts new file mode 100644 index 000000000..e86d6ecb3 --- /dev/null +++ b/tests/unit/packaging/runDistributableSmoke.test.ts @@ -0,0 +1,418 @@ +import fs from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + assertNoWindowsInstallRegistrations, + getDistributableNames, + getWindowsInstallRegistrations, + runChecked, + runDistributableSmoke, +} from "../../../scripts/run-distributable-smoke.mjs"; + +const directories: string[] = []; + +function makeRelease(platform: string, arch: string): string { + const directory = fs.mkdtempSync(path.join(tmpdir(), "ffv-artifact-test-")); + directories.push(directory); + for (const name of getDistributableNames({ + platform, + arch, + version: "30.0.3", + })) { + fs.writeFileSync(path.join(directory, name), "fixture artifact"); + } + return directory; +} + +function createExecutable(destination: string, platform: string): void { + const executable = + platform === "darwin" + ? path.join(destination, "Contents", "MacOS", "Fit File Viewer") + : path.join(destination, "Fit File Viewer.exe"); + fs.mkdirSync(path.dirname(executable), { recursive: true }); + fs.writeFileSync(executable, "fixture executable"); +} + +afterEach(() => { + for (const directory of directories.splice(0)) { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +describe("final distributable smoke", () => { + it.each([ + [ + "CurrentUser", + "Registry32", + "141b3184-244b-5640-abaf-338415dd90dc", + ], + [ + "CurrentUser", + "Registry64", + "2eccf151-6603-512f-93c6-ea96e8d92a75", + ], + [ + "LocalMachine", + "Registry32", + "2eccf151-6603-512f-93c6-ea96e8d92a75", + ], + [ + "LocalMachine", + "Registry64", + "141b3184-244b-5640-abaf-338415dd90dc", + ], + ])("refuses existing registrations in %s/%s for %s", (hive, view, guid) => { + expect.assertions(1); + expect(() => + assertNoWindowsInstallRegistrations(() => [ + { Hive: hive, View: view, Key: `Software\\${guid}` }, + ]) + ).toThrow("Use a clean disposable Windows runner"); + }); + + it("fails closed when registry inspection fails or returns unexpected data", () => { + expect.assertions(2); + expect(() => + getWindowsInstallRegistrations(() => { + throw new Error("Access denied"); + }) + ).toThrow("Access denied"); + expect(() => + getWindowsInstallRegistrations(() => ({ stdout: "null" })) + ).toThrow("invalid data"); + }); + + it("never starts the installer or uninstaller when an existing user install is registered", () => { + expect.assertions(2); + const releaseDirectory = makeRelease("win32", "x64"); + const calls: string[] = []; + const run = (command: string, args: string[]): void => { + calls.push(command); + if (command === "tar") createExecutable(args[3] ?? "", "win32"); + }; + expect(() => + runDistributableSmoke( + { + arch: "x64", + platform: "win32", + version: "30.0.3", + releaseDirectory, + }, + { + run, + smoke: () => 0, + inspectWindowsRegistrations: () => [ + { + Key: "Software\\fixture", + InstallLocation: + "C:\\Users\\fixture\\AppData\\Local\\Programs\\Fit File Viewer", + }, + ], + } + ) + ).toThrow("Refusing NSIS smoke installation"); + expect(calls).toStrictEqual(["tar"]); + }); + + it("preserves a partial install if registration cleanup cannot be verified", () => { + expect.assertions(3); + const releaseDirectory = makeRelease("win32", "x64"); + let installation = ""; + const inspectWindowsRegistrations = vi + .fn() + .mockReturnValueOnce([]) + .mockReturnValue([{ Key: "Software\\fixture" }]); + const run = (command: string, args: string[]): void => { + if (command === "tar") createExecutable(args[3] ?? "", "win32"); + if (command.includes("-nsis-")) { + installation = args[2]?.slice(3) ?? ""; + directories.push(path.dirname(installation)); + createExecutable(installation, "win32"); + throw new Error("Installer failed after registration"); + } + }; + expect(() => + runDistributableSmoke( + { + arch: "x64", + platform: "win32", + version: "30.0.3", + releaseDirectory, + }, + { run, smoke: () => 0, inspectWindowsRegistrations } + ) + ).toThrow("cleanup failed; preserved"); + expect( + fs.existsSync(path.join(installation, "Fit File Viewer.exe")) + ).toBeTruthy(); + expect( + JSON.parse( + fs.readFileSync( + path.join( + releaseDirectory, + "distributable-smoke-win32-x64.json" + ), + "utf8" + ) + ) + ).toMatchObject({ + artifacts: expect.arrayContaining([ + { + artifact: "Fit-File-Viewer-nsis-x64-30.0.3.exe", + passed: false, + phase: "cleanup", + error: expect.stringContaining("preserved"), + }, + ]), + }); + }); + + it("replaces stale success evidence when a required artifact is missing", () => { + expect.assertions(2); + const releaseDirectory = makeRelease("darwin", "arm64"); + fs.rmSync( + path.join(releaseDirectory, "Fit-File-Viewer-dmg-arm64-30.0.3.dmg") + ); + const report = path.join( + releaseDirectory, + "distributable-smoke-darwin-arm64.json" + ); + fs.writeFileSync(report, '{"passed":true}'); + expect(() => + runDistributableSmoke({ + arch: "arm64", + platform: "darwin", + version: "30.0.3", + releaseDirectory, + }) + ).toThrow("Required distributable is missing"); + expect(JSON.parse(fs.readFileSync(report, "utf8"))).toMatchObject({ + artifacts: [{ passed: false }], + }); + }); + + it("launches Linux tar and extracted AppImage payloads from fresh directories", () => { + expect.assertions(3); + const releaseDirectory = makeRelease("linux", "x64"); + const smoke = vi.fn(() => 0); + const calls: string[] = []; + const run = ( + command: string, + args: string[], + options?: { cwd: string } + ): void => { + calls.push(command); + const destination = command === "tar" ? args[3] : options?.cwd; + if (!destination) throw new Error("Missing extraction directory"); + fs.writeFileSync( + path.join(destination, "fitfileviewer"), + "fixture executable", + { mode: 0o755 } + ); + }; + expect( + runDistributableSmoke( + { + arch: "x64", + platform: "linux", + version: "30.0.3", + releaseDirectory, + }, + { run, smoke } + ) + ).toBe(0); + expect(calls).toEqual([ + "tar", + expect.stringContaining("appimage-x86_64-30.0.3.AppImage"), + ]); + expect(smoke).toHaveBeenCalledTimes(2); + }); + + it("requires exact architecture/version artifacts and rejects unsupported combinations", () => { + expect.assertions(3); + expect( + getDistributableNames({ + platform: "linux", + arch: "x64", + version: "30.0.3", + }) + ).toStrictEqual([ + "Fit-File-Viewer-linux-x64-30.0.3.tar.gz", + "Fit-File-Viewer-appimage-x86_64-30.0.3.AppImage", + ]); + expect(() => + getDistributableNames({ + platform: "win32", + arch: "universal", + version: "30.0.3", + }) + ).toThrow("Unsupported"); + expect(() => + getDistributableNames({ + platform: "darwin", + arch: "arm64", + version: "../latest", + }) + ).toThrow("Invalid package version"); + }); + + it("fails command signal termination and nonzero exits", () => { + expect.assertions(2); + expect(() => + runChecked("fixture", [], {}, () => ({ + status: null, + signal: "SIGSEGV", + })) + ).toThrow("SIGSEGV"); + expect(() => + runChecked("fixture", [], {}, () => ({ + status: 3, + stderr: "invalid signature", + })) + ).toThrow("invalid signature"); + }); + + it("copies a mounted universal DMG, verifies signatures, then launches both slices and LaunchServices", () => { + expect.assertions(7); + const releaseDirectory = makeRelease("darwin", "universal"); + const commands: string[][] = []; + const wrappers: string[] = []; + const run = (command: string, args: string[]): void => { + commands.push([command, ...args]); + if (command === "ditto") createExecutable(args[1] ?? "", "darwin"); + }; + const smoke = (args: string[]): number => { + wrappers.push(fs.readFileSync(args[1] ?? "", "utf8")); + return 0; + }; + expect( + runDistributableSmoke( + { + arch: "universal", + platform: "darwin", + version: "30.0.3", + releaseDirectory, + }, + { run, smoke } + ) + ).toBe(0); + expect(commands.map((command) => command[0])).toStrictEqual([ + "hdiutil", + "ditto", + "hdiutil", + "codesign", + ]); + expect(commands[0]).toContain("-readonly"); + expect(commands[3]).toContain("--all-architectures"); + expect(wrappers.map((wrapper) => wrapper.split("\n")[1])).toEqual([ + expect.stringContaining("arch -arm64"), + expect.stringContaining("arch -x86_64"), + expect.stringContaining("open -W -n"), + ]); + expect(wrappers[2]).toContain('"FFV_SMOKE_NONCE=$FFV_SMOKE_NONCE"'); + expect( + JSON.parse( + fs.readFileSync( + path.join( + releaseDirectory, + "distributable-smoke-darwin-universal.json" + ), + "utf8" + ) + ) + ).toMatchObject({ + artifacts: [ + { + passed: true, + signatureVerified: true, + architectures: ["arm64", "x64"], + }, + ], + }); + }); + + it("rejects an invalid final signature before launch and preserves failure evidence", () => { + expect.assertions(3); + const releaseDirectory = makeRelease("darwin", "arm64"); + const smoke = vi.fn(); + const run = (command: string, args: string[]): void => { + if (command === "ditto") createExecutable(args[1] ?? "", "darwin"); + if (command === "codesign") + throw new Error("invalid code-page hash"); + }; + expect(() => + runDistributableSmoke( + { + arch: "arm64", + platform: "darwin", + version: "30.0.3", + releaseDirectory, + }, + { run, smoke } + ) + ).toThrow("invalid code-page hash"); + expect(smoke).not.toHaveBeenCalled(); + expect( + JSON.parse( + fs.readFileSync( + path.join( + releaseDirectory, + "distributable-smoke-darwin-arm64.json" + ), + "utf8" + ) + ) + ).toMatchObject({ + artifacts: [{ passed: false, error: "invalid code-page hash" }], + }); + }); + + it("tests the extracted ZIP, installed NSIS app, and portable launcher separately", () => { + expect.assertions(6); + const releaseDirectory = makeRelease("win32", "ia32"); + const smoke = vi.fn(() => 0); + const calls: string[][] = []; + const inspectWindowsRegistrations = vi.fn(() => []); + const run = (command: string, args: string[]): void => { + calls.push([command, ...args]); + if (command === "tar") createExecutable(args[3] ?? "", "win32"); + if (command.includes("-nsis-")) { + const destination = args[2]?.slice(3) ?? ""; + createExecutable(destination, "win32"); + fs.writeFileSync( + path.join(destination, "Uninstall Fit File Viewer.exe"), + "fixture uninstaller" + ); + } + }; + expect( + runDistributableSmoke( + { + arch: "ia32", + platform: "win32", + version: "30.0.3", + releaseDirectory, + }, + { run, smoke, inspectWindowsRegistrations } + ) + ).toBe(0); + expect(smoke).toHaveBeenCalledTimes(3); + expect(calls[1]?.slice(1, 3)).toStrictEqual(["/S", "/currentuser"]); + expect(calls[2]).toEqual([ + expect.stringContaining("Uninstall Fit File Viewer.exe"), + "/S", + "/currentuser", + expect.stringContaining("_?="), + ]); + expect(inspectWindowsRegistrations).toHaveBeenCalledTimes(2); + expect(smoke.mock.calls[2]).toEqual([ + expect.arrayContaining([ + expect.stringContaining("portable-ia32-30.0.3.exe"), + ]), + expect.any(Object), + ]); + }); +}); diff --git a/tests/unit/packaging/runElectronBuilder.test.ts b/tests/unit/packaging/runElectronBuilder.test.ts index bb489270e..77a86fee4 100644 --- a/tests/unit/packaging/runElectronBuilder.test.ts +++ b/tests/unit/packaging/runElectronBuilder.test.ts @@ -134,6 +134,7 @@ describe("run-electron-builder script", () => { options: { cwd: path.resolve(process.cwd()), env: { + CSC_FOR_PULL_REQUEST: "true", CSC_IDENTITY_AUTO_DISCOVERY: "false", FFV_TEST_ENV: "1", NODE_ENV: "production", @@ -184,6 +185,7 @@ describe("run-electron-builder script", () => { }).toStrictEqual({ cwd: path.resolve(process.cwd()), env: { + CSC_FOR_PULL_REQUEST: "true", CSC_IDENTITY_AUTO_DISCOVERY: "false", FFV_TEST_ENV: "1", REQUIRE_CODE_SIGNING: "false", @@ -201,6 +203,7 @@ describe("run-electron-builder script", () => { expect( getElectronBuilderEnvironment({ FFV_TEST_ENV: "1" }, "win32") ).toStrictEqual({ + CSC_FOR_PULL_REQUEST: "true", CSC_IDENTITY_AUTO_DISCOVERY: "false", FFV_TEST_ENV: "1", REQUIRE_CODE_SIGNING: "false", @@ -216,6 +219,7 @@ describe("run-electron-builder script", () => { "win32" ) ).toStrictEqual({ + CSC_FOR_PULL_REQUEST: "true", CSC_IDENTITY_AUTO_DISCOVERY: "false", FFV_TEST_ENV: "1", REQUIRE_CODE_SIGNING: "false", @@ -241,6 +245,7 @@ describe("run-electron-builder script", () => { WIN_CSC_LINK: "windows.pfx", }; const unsignedEnvironment = { + CSC_FOR_PULL_REQUEST: "true", CSC_IDENTITY_AUTO_DISCOVERY: "false", FFV_FORCE_UNSIGNED_PACKAGE: "true", FFV_TEST_ENV: "1", @@ -255,6 +260,39 @@ describe("run-electron-builder script", () => { ).toStrictEqual(unsignedEnvironment); }); + it("allows credential-free ad hoc signing on pull requests while preserving publisher restrictions", async () => { + expect.assertions(4); + + const { getElectronBuilderEnvironment } = + await importRunElectronBuilder(); + const environment = { + APPLE_KEYCHAIN_PROFILE: "notary-profile", + CSC_FOR_PULL_REQUEST: "false", + CSC_INSTALLER_KEY_PASSWORD: "installer-password", + CSC_INSTALLER_LINK: "installer.p12", + CSC_KEY_PASSWORD: "password", + CSC_LINK: "application.p12", + GITHUB_EVENT_NAME: "pull_request", + REQUIRE_CODE_SIGNING: "true", + }; + const unsignedEnvironment = getElectronBuilderEnvironment( + { ...environment, REQUIRE_CODE_SIGNING: "false" }, + "darwin" + ); + + expect(unsignedEnvironment).toStrictEqual({ + CSC_FOR_PULL_REQUEST: "true", + CSC_IDENTITY_AUTO_DISCOVERY: "false", + GITHUB_EVENT_NAME: "pull_request", + REQUIRE_CODE_SIGNING: "false", + }); + expect(getElectronBuilderEnvironment(environment, "darwin")).toBe( + environment + ); + expect(environment.CSC_FOR_PULL_REQUEST).toBe("false"); + expect(environment.CSC_LINK).toBe("application.p12"); + }); + it("validates required Windows signing secrets for release builds", async () => { expect.assertions(2); diff --git a/tests/unit/packaging/runPackagedSmoke.test.ts b/tests/unit/packaging/runPackagedSmoke.test.ts index 1ade97d61..cfa1ffa70 100644 --- a/tests/unit/packaging/runPackagedSmoke.test.ts +++ b/tests/unit/packaging/runPackagedSmoke.test.ts @@ -27,6 +27,7 @@ type CommandRunner = ( } ) => { error?: NodeJS.ErrnoException; + signal?: string | null; status: number | null; stderr?: string; stdout?: string; @@ -59,11 +60,13 @@ describe("run-packaged-smoke script", () => { expect(parseArgs(["--executable", "app.exe"])).toStrictEqual({ executablePath: "app.exe", + fixturePath: undefined, releaseDistPath: undefined, startupTimeoutMs: undefined, }); expect(parseArgs(["--release-dist=dist"])).toStrictEqual({ executablePath: undefined, + fixturePath: undefined, releaseDistPath: "dist", startupTimeoutMs: undefined, }); @@ -212,211 +215,264 @@ describe("run-packaged-smoke script", () => { ).toStrictEqual([]); }); - it("launches the packaged executable and treats timeout as a healthy startup", () => { - expect.assertions(7); - - const releaseDistPath = createTemporaryRoot(); - const executablePath = path.join( - releaseDistPath, - "win-unpacked", - "Fit File Viewer.exe" - ); + it("requires a nonce-bound report from a visible UI with parsed FIT data", () => { + expect.assertions(6); + const executablePath = path.join(createTemporaryRoot(), "app.exe"); writeExecutable(executablePath); - - const commandRunner = vi.fn().mockReturnValue({ - error: Object.assign(new Error("timed out"), { - code: "ETIMEDOUT", - }), - status: null, - }); - const logger = vi.fn<(message: string) => void>(); - + const commandRunner = vi + .fn() + .mockImplementation((_command, _args, options) => { + writeFileSync( + path.join( + String(options.env.FFV_SMOKE_DIRECTORY), + "report.json" + ), + JSON.stringify({ + nonce: options.env.FFV_SMOKE_NONCE, + status: "passed", + visible: true, + activity: { + recordCount: 1285, + sessionCount: 1, + appInitialized: true, + mapReady: true, + routeCount: 58, + }, + }) + ); + return { status: 0 }; + }); + const logger = vi.fn(); expect( runPackagedSmoke( ["--executable", executablePath], - { PATH: process.env.PATH }, + {}, commandRunner, logger ) ).toBe(0); - const [ - command, + _command, args, options, - ] = commandRunner.mock.calls[0] ?? []; - - expect(command).toBe(executablePath); - expect(args).toStrictEqual(["--disable-http-cache"]); - expect(options?.env.ELECTRON_IS_DEV).toBe("0"); - expect(options?.stdio).toHaveLength(3); - expect(options?.timeout).toBe(10_000); + ] = commandRunner.mock.calls[0]!; + expect(args).toContain("--ffv-smoke-test"); + expect(options.env.FFV_SMOKE_FIXTURE).toMatch(/\.fit$/u); + expect(options.env.NODE_ENV).toBe("production"); + expect(options.timeout).toBe(60_000); expect(logger).toHaveBeenCalledWith( - `[packaged-smoke] Launching ${executablePath} for 10000ms` + expect.stringContaining("Verified visible renderer") ); + rmSync(String(options.env.FFV_SMOKE_DIRECTORY), { + force: true, + recursive: true, + }); }); - it("treats a clean timeout shutdown as a healthy startup", () => { + it.each([ + { status: null, signal: "SIGSEGV" }, + { status: null, signal: "SIGABRT" }, + { status: null, signal: "SIGKILL" }, + { status: 1 }, + { status: null }, + { + status: 0, + error: Object.assign(new Error("timeout"), { code: "ETIMEDOUT" }), + }, + ])("rejects unsuccessful process completion %j", (result) => { expect.assertions(1); - - const releaseDistPath = createTemporaryRoot(); - const executablePath = path.join( - releaseDistPath, - "win-unpacked", - "Fit File Viewer.exe" - ); + const executablePath = path.join(createTemporaryRoot(), "app.exe"); writeExecutable(executablePath); - - const commandRunner = vi.fn().mockReturnValue({ - error: Object.assign(new Error("timed out"), { - code: "ETIMEDOUT", - }), - status: 0, - }); - - expect( + const commandRunner = vi.fn().mockReturnValue(result); + expect(() => runPackagedSmoke( ["--executable", executablePath], {}, commandRunner ) - ).toBe(0); - }); - - it("disables Chromium's setuid sandbox only on Linux CI runners", () => { - expect.assertions(3); - - expect(getPackagedLaunchArgs({ CI: "true" }, "linux")).toStrictEqual([ - "--disable-http-cache", - "--no-sandbox", - ]); - expect(getPackagedLaunchArgs({}, "linux")).toStrictEqual([ - "--disable-http-cache", - ]); - expect(getPackagedLaunchArgs({ CI: "true" }, "darwin")).toStrictEqual([ - "--disable-http-cache", - ]); + ).toThrow("did not complete"); + const options = commandRunner.mock.calls[0]![2]; + rmSync(String(options.env.FFV_SMOKE_DIRECTORY), { + force: true, + recursive: true, + }); }); - it("fails when packaged startup output contains fatal renderer or asset errors", () => { + it.each([ + undefined, + { + nonce: "forged", + status: "passed", + visible: true, + activity: { recordCount: 1, sessionCount: 1 }, + }, + { + status: "failed", + visible: true, + activity: { recordCount: 1, sessionCount: 1 }, + }, + { + status: "passed", + visible: false, + activity: { recordCount: 1, sessionCount: 1 }, + }, + { + status: "passed", + visible: true, + activity: { recordCount: 0, sessionCount: 1 }, + }, + { + status: "passed", + visible: true, + activity: { + recordCount: 1285, + sessionCount: 1, + appInitialized: false, + mapReady: true, + routeCount: 58, + }, + }, + { + status: "passed", + visible: true, + activity: { + recordCount: 1285, + sessionCount: 1, + appInitialized: true, + mapReady: false, + routeCount: 0, + }, + }, + ])("rejects missing or invalid readiness evidence %j", (report) => { expect.assertions(1); - - const releaseDistPath = createTemporaryRoot(); - const executablePath = path.join( - releaseDistPath, - "win-unpacked", - "Fit File Viewer.exe" - ); + const executablePath = path.join(createTemporaryRoot(), "app.exe"); writeExecutable(executablePath); - - const commandRunner = vi.fn().mockReturnValue({ - error: Object.assign(new Error("timed out"), { - code: "ETIMEDOUT", - }), - status: null, - stderr: "Failed to load URL: file:///app.asar/dist/index.html", - }); - + const commandRunner = vi + .fn() + .mockImplementation((_command, _args, options) => { + if (report) + writeFileSync( + path.join( + String(options.env.FFV_SMOKE_DIRECTORY), + "report.json" + ), + JSON.stringify({ + nonce: options.env.FFV_SMOKE_NONCE, + ...report, + }) + ); + return { status: 0 }; + }); expect(() => runPackagedSmoke( ["--executable", executablePath], {}, commandRunner ) - ).toThrow("Failed to load URL"); + ).toThrow(/readiness report/u); + const options = commandRunner.mock.calls[0]![2]; + rmSync(String(options.env.FFV_SMOKE_DIRECTORY), { + force: true, + recursive: true, + }); }); - it("accepts a macOS HTML load rejection caused by timeout shutdown after display", () => { + it.each([ + [ + "FFV_SMOKE_EXPECTED_ARCH", + "arm64", + "architecture", + ], + [ + "FFV_SMOKE_EXPECTED_VERSION", + "30.0.4", + "version", + ], + ])("checks reported identity against %s", (key, value, failure) => { expect.assertions(1); - - const releaseDistPath = createTemporaryRoot(); - const executablePath = path.join( - releaseDistPath, - "mac", - "Fit File Viewer.app", - "Contents", - "MacOS", - "Fit File Viewer" - ); + const executablePath = path.join(createTemporaryRoot(), "app.exe"); writeExecutable(executablePath); - - const commandRunner = vi.fn().mockReturnValue({ - error: Object.assign(new Error("timed out"), { - code: "ETIMEDOUT", - }), - status: 0, - stderr: [ - "[main.js] Window displayed successfully", - "[main.js] Error loading main HTML file ERR_FAILED (-2)", - ].join("\n"), - }); - - expect( + const commandRunner = vi + .fn() + .mockImplementation((_command, _args, options) => { + writeFileSync( + path.join( + String(options.env.FFV_SMOKE_DIRECTORY), + "report.json" + ), + JSON.stringify({ + nonce: options.env.FFV_SMOKE_NONCE, + status: "passed", + visible: true, + activity: { + recordCount: 1285, + sessionCount: 1, + appInitialized: true, + mapReady: true, + routeCount: 58, + }, + arch: "x64", + version: "30.0.3", + }) + ); + return { status: 0 }; + }); + expect(() => runPackagedSmoke( ["--executable", executablePath], - {}, + { [key]: value }, commandRunner ) - ).toBe(0); + ).toThrow(failure); + rmSync( + String(commandRunner.mock.calls[0]![2].env.FFV_SMOKE_DIRECTORY), + { force: true, recursive: true } + ); }); - it("rejects an HTML load failure when the packaged window never displayed", () => { + it("never excuses failed HTML loading based on a display log", () => { expect.assertions(1); - - const releaseDistPath = createTemporaryRoot(); - const executablePath = path.join( - releaseDistPath, - "mac", - "Fit File Viewer.app", - "Contents", - "MacOS", - "Fit File Viewer" - ); + const executablePath = path.join(createTemporaryRoot(), "app.exe"); writeExecutable(executablePath); - const commandRunner = vi.fn().mockReturnValue({ - error: Object.assign(new Error("timed out"), { - code: "ETIMEDOUT", - }), status: 0, - stderr: "[main.js] Error loading main HTML file ERR_FAILED (-2)", + stderr: "Window displayed successfully\nError loading main HTML file ERR_FAILED", }); - expect(() => runPackagedSmoke( ["--executable", executablePath], {}, commandRunner ) - ).toThrow('failure marker "error loading main html file"'); + ).toThrow("failure marker"); + rmSync( + String(commandRunner.mock.calls[0]![2].env.FFV_SMOKE_DIRECTORY), + { force: true, recursive: true } + ); }); - it("fails when the packaged executable exits before the startup window", () => { - expect.assertions(1); - - const releaseDistPath = createTemporaryRoot(); - const executablePath = path.join( - releaseDistPath, - "win-unpacked", - "Fit File Viewer.exe" + it("disables Chromium's setuid sandbox only on Linux CI runners", () => { + expect.assertions(3); + expect(getPackagedLaunchArgs({ CI: "true" }, "linux")).toContain( + "--no-sandbox" ); - writeExecutable(executablePath); - - const commandRunner = vi.fn().mockReturnValue({ - status: 0, - }); + expect(getPackagedLaunchArgs({}, "linux")).not.toContain( + "--no-sandbox" + ); + expect(getPackagedLaunchArgs({ CI: "true" }, "darwin")).not.toContain( + "--no-sandbox" + ); + }); - expect(() => - runPackagedSmoke( - [ - "--executable", - executablePath, - "--startup-timeout-ms", - "1000", - ], - {}, - commandRunner - ) - ).toThrow("exited before the 1000ms startup smoke window"); + it.each([ + "1000oops", + "1500.5", + "999", + "Infinity", + ])("rejects invalid timeout %s", (timeout) => { + expect.assertions(1); + expect(() => parseArgs(["--startup-timeout-ms", timeout])).toThrow( + "integer >= 1000" + ); }); }); diff --git a/tests/unit/packaging/verifyReleaseAssets.test.ts b/tests/unit/packaging/verifyReleaseAssets.test.ts index 449b26ad3..802c48b5b 100644 --- a/tests/unit/packaging/verifyReleaseAssets.test.ts +++ b/tests/unit/packaging/verifyReleaseAssets.test.ts @@ -137,6 +137,54 @@ function createReleaseAsset(filePath: string, name: string): ReleaseAsset { }; } +function addWebInstallerFixture( + fixture: ReleaseFixture, + packageOverrides: Record = {}, + installerUrl = "Fit-File-Viewer-nsis-web-x64-30.0.0.exe" +): { metadataPath: string; packagePath: string } { + const installerName = "Fit-File-Viewer-nsis-web-x64-30.0.0.exe"; + const packageName = "fitfileviewer-30.0.0-x64.nsis.7z"; + const installerPath = path.join( + fixture.releaseDistDirectory, + installerName + ); + const packagePath = path.join(fixture.releaseDistDirectory, packageName); + const metadataName = "latest-nsis-web.yml"; + const metadataPath = path.join(fixture.releaseDistDirectory, metadataName); + const installerContents = "web installer"; + const packageContents = "web installer payload"; + const installerSha512 = createHash("sha512") + .update(installerContents) + .digest("base64"); + const packageEntry = { + file: packageName, + path: packageName, + sha512: createHash("sha512").update(packageContents).digest("base64"), + size: packageContents.length, + ...packageOverrides, + }; + + fs.writeFileSync(installerPath, installerContents); + fs.writeFileSync(packagePath, packageContents); + fs.writeFileSync( + metadataPath, + stringifyYaml({ + files: [{ sha512: installerSha512, url: installerUrl }], + // Shared package objects exercise YAML aliases and duplicate references. + packages: { ia32: packageEntry, x64: packageEntry }, + path: installerUrl, + sha512: installerSha512, + version: "30.0.0", + }) + ); + fixture.assets.push( + createReleaseAsset(installerPath, installerName), + createReleaseAsset(packagePath, packageName), + createReleaseAsset(metadataPath, metadataName) + ); + return { metadataPath, packagePath }; +} + afterEach(() => { for (const temporaryRoot of temporaryRoots.splice(0)) { fs.rmSync(temporaryRoot, { force: true, recursive: true }); @@ -144,6 +192,133 @@ afterEach(() => { }); describe("verify-release-assets script", () => { + it("verifies optional web channels and aliased payloads without double counting", async () => { + expect.assertions(1); + const { verifyReleaseAssets } = await importVerifyReleaseAssets(); + const fixture = createReleaseFixture(); + addWebInstallerFixture(fixture); + + expect( + verifyReleaseAssets({ + expectedVersion: "30.0.0", + release: { assets: fixture.assets, draft: true }, + releaseDistDirectory: fixture.releaseDistDirectory, + }) + ).toStrictEqual({ metadataCount: 5, referencedAssetCount: 6 }); + }); + + it.each([ + [ + "hash", + { sha512: "incorrect" }, + "sha512 mismatch", + ], + [ + "size", + { size: 999 }, + "size mismatch", + ], + [ + "invalid size", + { size: "21" }, + "invalid ia32 package", + ], + [ + "conflicting filename", + { file: "different.nsis.7z" }, + "invalid ia32 package", + ], + [ + "unsafe path", + { file: "../payload.7z", path: "../payload.7z" }, + "invalid files entry", + ], + ])( + "rejects a web package with an invalid %s", + async (_label, overrides, message) => { + expect.assertions(1); + const { verifyReleaseAssets } = await importVerifyReleaseAssets(); + const fixture = createReleaseFixture(); + addWebInstallerFixture( + fixture, + overrides as Record + ); + + expect(() => + verifyReleaseAssets({ + expectedVersion: "30.0.0", + release: { assets: fixture.assets, draft: true }, + releaseDistDirectory: fixture.releaseDistDirectory, + }) + ).toThrow(String(message)); + } + ); + + it.each(["metadata", "payload"])( + "rejects web %s omitted from uploaded assets", + async (missing) => { + expect.assertions(1); + const { verifyReleaseAssets } = await importVerifyReleaseAssets(); + const fixture = createReleaseFixture(); + addWebInstallerFixture(fixture); + const missingName = + missing === "metadata" + ? "latest-nsis-web.yml" + : "fitfileviewer-30.0.0-x64.nsis.7z"; + + expect(() => + verifyReleaseAssets({ + expectedVersion: "30.0.0", + release: { + assets: fixture.assets.filter( + ({ name }) => name !== missingName + ), + draft: true, + }, + releaseDistDirectory: fixture.releaseDistDirectory, + }) + ).toThrow("not uploaded"); + } + ); + + it("rejects a web payload missing locally", async () => { + expect.assertions(1); + const { verifyReleaseAssets } = await importVerifyReleaseAssets(); + const fixture = createReleaseFixture(); + const { packagePath } = addWebInstallerFixture(fixture); + fs.unlinkSync(packagePath); + + expect(() => + verifyReleaseAssets({ + expectedVersion: "30.0.0", + release: { assets: fixture.assets, draft: true }, + releaseDistDirectory: fixture.releaseDistDirectory, + }) + ).toThrow( + "Expected exactly one local fitfileviewer-30.0.0-x64.nsis.7z, found 0" + ); + }); + + it.each([ + "../installer.exe", + "https://example.test/installer.exe", + "..\\installer.exe", + "installer.exe?download=1", + ])("rejects non-filename update references: %s", async (url) => { + expect.assertions(1); + const { verifyReleaseAssets } = await importVerifyReleaseAssets(); + const fixture = createReleaseFixture(); + addWebInstallerFixture(fixture, {}, url); + + expect(() => + verifyReleaseAssets({ + expectedVersion: "30.0.0", + release: { assets: fixture.assets, draft: true }, + releaseDistDirectory: fixture.releaseDistDirectory, + }) + ).toThrow("invalid files entry"); + }); + it("verifies canonical updater metadata against local and uploaded artifacts", async () => { expect.assertions(1); diff --git a/tests/unit/packaging/verifySignedArtifacts.test.ts b/tests/unit/packaging/verifySignedArtifacts.test.ts index 22a0cdaef..cbe928025 100644 --- a/tests/unit/packaging/verifySignedArtifacts.test.ts +++ b/tests/unit/packaging/verifySignedArtifacts.test.ts @@ -41,7 +41,8 @@ type VerifySignedArtifactsModule = { ) => string[]; createSigningVerificationCommand: ( artifactPath: string, - platform: string + platform: string, + options?: { signingRequired?: boolean } ) => { args: string[]; command: string; @@ -205,7 +206,7 @@ describe("verify-signed-artifacts script", () => { expect(macosCommand.args).toContain("--verify"); }); - it("runs verification commands only when signing is required", async () => { + it("runs Windows verification when publisher signing is required and skips Linux", async () => { expect.assertions(7); const releaseDir = createTemporaryReleaseDir(); @@ -267,6 +268,172 @@ describe("verify-signed-artifacts script", () => { ]); }); + it.each([ + "mac", + "mac-arm64", + "mac-universal", + ])( + "verifies every architecture of %s bundles without requiring a publisher certificate", + async (directoryName) => { + expect.assertions(4); + + const releaseDir = createTemporaryReleaseDir(); + const appBundlePath = path.join( + releaseDir, + directoryName, + "Fit File Viewer.app" + ); + fs.mkdirSync(appBundlePath, { recursive: true }); + const commandRunner = vi.fn(() => ({ status: 0 })); + const { verifySignedArtifacts } = + await importVerifySignedArtifacts(); + + expect( + verifySignedArtifacts( + [ + "--platform", + "darwin", + "--release-dir", + releaseDir, + ], + { REQUIRE_CODE_SIGNING: "false" }, + commandRunner + ) + ).toBe(0); + expect(commandRunner).toHaveBeenCalledOnce(); + expect(commandRunner.mock.calls[0]).toStrictEqual([ + "codesign", + [ + "--verify", + "--deep", + "--strict", + "--all-architectures", + "--verbose=2", + appBundlePath, + ], + expect.objectContaining({ stdio: "inherit" }), + ]); + expect( + JSON.parse( + fs.readFileSync( + path.join( + releaseDir, + "signing-verification-report.json" + ), + "utf8" + ) + ) + ).toMatchObject({ + artifactCount: 1, + signingRequired: false, + status: "verified", + }); + } + ); + + it("requires a Developer ID certificate chain when publisher signing is required", async () => { + expect.assertions(2); + + const { createSigningVerificationCommand } = + await importVerifySignedArtifacts(); + const verification = createSigningVerificationCommand( + "/Applications/Fit File Viewer.app", + "darwin", + { signingRequired: true } + ); + + expect(verification.args).toContain("--all-architectures"); + expect(verification.args).toContain( + "=anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists" + ); + }); + + it.each([1, null])( + "fails macOS integrity verification when codesign returns %s", + async (status) => { + expect.assertions(2); + + const releaseDir = createTemporaryReleaseDir(); + fs.mkdirSync( + path.join(releaseDir, "mac-arm64", "Fit File Viewer.app"), + { recursive: true } + ); + const { verifySignedArtifacts } = + await importVerifySignedArtifacts(); + + expect( + verifySignedArtifacts( + [ + "--platform", + "darwin", + "--release-dir", + releaseDir, + ], + { REQUIRE_CODE_SIGNING: "false" }, + vi.fn(() => ({ status })) + ) + ).toBe(1); + expect( + JSON.parse( + fs.readFileSync( + path.join( + releaseDir, + "signing-verification-report.json" + ), + "utf8" + ) + ) + ).toMatchObject({ + signingRequired: false, + status: "failed", + }); + } + ); + + it("fails missing macOS integrity candidates even without publisher signing", async () => { + expect.assertions(2); + + const releaseDir = createTemporaryReleaseDir(); + const { verifySignedArtifacts } = await importVerifySignedArtifacts(); + const commandRunner = vi.fn(() => ({ status: 0 })); + + expect(() => + verifySignedArtifacts( + [ + "--platform", + "darwin", + "--release-dir", + releaseDir, + ], + { REQUIRE_CODE_SIGNING: "false" }, + commandRunner + ) + ).toThrow("No signed artifact candidates found"); + expect(commandRunner).not.toHaveBeenCalled(); + }); + + it("skips unsigned Windows publisher verification", async () => { + expect.assertions(2); + + const releaseDir = createTemporaryReleaseDir(); + const { verifySignedArtifacts } = await importVerifySignedArtifacts(); + const commandRunner = vi.fn(() => ({ status: 0 })); + + expect( + verifySignedArtifacts( + [ + "--platform", + "win32", + "--release-dir", + releaseDir, + ], + { REQUIRE_CODE_SIGNING: "false" }, + commandRunner + ) + ).toBe(0); + expect(commandRunner).not.toHaveBeenCalled(); + }); + it("appends a GitHub job summary when summary output is available", async () => { expect.assertions(4); diff --git a/tests/unit/packaging/workspacePackageBoundaries.test.ts b/tests/unit/packaging/workspacePackageBoundaries.test.ts index aa8b7acfc..689d20ad2 100644 --- a/tests/unit/packaging/workspacePackageBoundaries.test.ts +++ b/tests/unit/packaging/workspacePackageBoundaries.test.ts @@ -282,7 +282,7 @@ const expectedRootToolingScripts = { "verify:fast": "npm run sync:node-version-files:check && npm run prettier && npm run lint && npm run lint:css && npm run docs:typecheck && npm test", "verify:full": - "npm run verify:fast && npm run docs:build && npm run audit && npm run test:playwright && npm run release:check-signing && npm run package:unsigned && npm run test:packaged", + "npm run verify:fast && npm run docs:build && npm run audit && npm run test:playwright && npm run release:check-signing && npm run package:unsigned && npm run release:verify-signing-artifacts && npm run test:packaged", "verify:release": "npm run verify:full", "verify:release:signed": "npm run verify:fast && npm run docs:build && npm run audit && npm run test:playwright && npm run package:signed && cross-env REQUIRE_CODE_SIGNING=true npm run release:verify-signing-artifacts && npm run test:packaged", @@ -377,13 +377,16 @@ describe("workspace package boundaries", () => { expect(rootPackage).not.toHaveProperty("workspaces"); expect(docusaurusPackage.overrides).toStrictEqual({ + "@docusaurus/core": { + tinypool: "^2.1.2", + }, "copy-webpack-plugin": { "serialize-javascript": "7.0.5", }, "css-minimizer-webpack-plugin": { "serialize-javascript": "7.0.5", }, - joi: "18.2.1", + joi: "18.2.9", qs: "6.16.0", sockjs: { uuid: "11.1.1", diff --git a/tests/unit/renderer/rendererVendorShared.test.ts b/tests/unit/renderer/rendererVendorShared.test.ts index 128557bfb..c5eaefedb 100644 --- a/tests/unit/renderer/rendererVendorShared.test.ts +++ b/tests/unit/renderer/rendererVendorShared.test.ts @@ -27,10 +27,11 @@ describe("rendererVendorShared", () => { const vendorSharedRuntime: RendererVendorSharedRuntime = { dispatchRendererVendorEntryLoadedEvent: vi.fn(() => true), }; + const mapLibreLayerFactory = () => ({}); markRendererVendorEntryLoaded( "map", - { map: { leafletRuntime } }, + { map: { leafletRuntime, mapLibreLayerFactory } }, { runtime: vendorSharedRuntime } ); @@ -44,7 +45,7 @@ describe("rendererVendorShared", () => { vendorSharedRuntime.dispatchRendererVendorEntryLoadedEvent ).toHaveBeenCalledWith(rendererVendorEntryLoadedEventName, { entryName: "map", - map: { leafletRuntime }, + map: { leafletRuntime, mapLibreLayerFactory }, }); expect( vendorSharedRuntime.dispatchRendererVendorEntryLoadedEvent diff --git a/tests/unit/renderer/vendorBundleLoader.test.ts b/tests/unit/renderer/vendorBundleLoader.test.ts index 2863967e5..5bd968542 100644 --- a/tests/unit/renderer/vendorBundleLoader.test.ts +++ b/tests/unit/renderer/vendorBundleLoader.test.ts @@ -32,6 +32,10 @@ import { clearLeafletRuntimeForTests, resolveLeafletRuntime, } from "../../../electron-app/utils/maps/core/leafletRuntime.js"; +import { + clearMapLibreLayerFactoryForTests, + resolveMapLibreLayerFactory, +} from "../../../electron-app/utils/maps/layers/mapLibreLayerRuntime.js"; import { clearArqueroRuntimeForTests, resolveArqueroRuntime, @@ -119,6 +123,7 @@ describe("renderer vendor bundle loader", () => { clearDomPurifyRuntimeForTests(); clearExportZipRuntimeForTests(); clearLeafletRuntimeForTests(); + clearMapLibreLayerFactoryForTests(); clearDataTableRuntimeForTests(); clearScreenfullRuntimeForTests(); resetRendererVendorBundleState(); @@ -583,8 +588,8 @@ describe("renderer vendor bundle loader", () => { } }); - it("registers the Leaflet payload from the split map vendor event", async () => { - expect.assertions(2); + it("registers Leaflet and the MapLibre factory from the split map vendor event", async () => { + expect.assertions(3); const leafletRuntime = { Layer: class Layer {}, @@ -595,9 +600,10 @@ describe("renderer vendor bundle loader", () => { }; const vendorReadiness = [ensureVendorBundle("map")]; const script = getVendorScript("map"); + const mapLibreLayerFactory = () => ({}); markRendererVendorEntryLoaded("map", { - map: { leafletRuntime }, + map: { leafletRuntime, mapLibreLayerFactory }, }); script.dispatchEvent(new Event("load")); @@ -608,10 +614,11 @@ describe("renderer vendor bundle loader", () => { value === leafletRuntime ) ).toBe(leafletRuntime); + expect(resolveMapLibreLayerFactory()).toBe(mapLibreLayerFactory); }); it("waits for a valid map payload instead of accepting malformed readiness", async () => { - expect.assertions(4); + expect.assertions(6); vi.useFakeTimers(); try { @@ -653,8 +660,20 @@ describe("renderer vendor bundle loader", () => { map() {}, tileLayer() {}, }; + globalThis.dispatchEvent( + new CustomEvent("ffv-renderer-vendor-entry-loaded", { + detail: { + entryName: "map", + map: { leafletRuntime }, + }, + }) + ); + await vi.advanceTimersByTimeAsync(20); + expect(resolved).toBe(false); + expect(resolveMapLibreLayerFactory()).toBeNull(); + markRendererVendorEntryLoaded("map", { - map: { leafletRuntime }, + map: { leafletRuntime, mapLibreLayerFactory: () => ({}) }, }); await vi.advanceTimersByTimeAsync(20); From ef320866a5a8330c34273c05f9ab2243fc5b9189 Mon Sep 17 00:00:00 2001 From: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:11:24 -0400 Subject: [PATCH 02/12] =?UTF-8?q?=F0=9F=9A=9C=20[refactor]=20Clarify=20pac?= =?UTF-8?q?kaged=20smoke=20validation=20and=20diagnostics?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿšœ [refactor] Separate smoke configuration, readiness checks, failure observation, renderer probes, and report capture into focused helpers while retaining every startup and map assertion. ๐Ÿ› [fix] Validate the report activity object explicitly before inspecting its fields, and remove the unused smoke test import reported by DeepScan. ๐Ÿงช [test] Cover invalid diagnostic configuration and a renderer failure during screenshot capture; split signature verification fixtures without dropping platform assertions. ๐Ÿ“ [docs] Explain the narrowly scoped filesystem operations used only by explicit local smoke mode. --- electron-app/main/runtime/packagedSmoke.ts | 298 ++++++++++++------ scripts/run-distributable-smoke.mjs | 44 +-- scripts/run-packaged-smoke.mjs | 6 +- .../packaging/packagedSmokeRuntime.test.ts | 52 +++ .../packaging/runDistributableSmoke.test.ts | 26 +- tests/unit/packaging/runPackagedSmoke.test.ts | 15 +- .../packaging/verifySignedArtifacts.test.ts | 62 ++-- 7 files changed, 339 insertions(+), 164 deletions(-) diff --git a/electron-app/main/runtime/packagedSmoke.ts b/electron-app/main/runtime/packagedSmoke.ts index 0a6f45e05..36a25e412 100644 --- a/electron-app/main/runtime/packagedSmoke.ts +++ b/electron-app/main/runtime/packagedSmoke.ts @@ -1,57 +1,84 @@ import { mkdirSync, writeFileSync } from "node:fs"; import * as path from "node:path"; import { setTimeout as delay } from "node:timers/promises"; -import type { App, BrowserWindow } from "electron"; +import type { App, BrowserWindow, WebContents } from "electron"; import { approveFilePath } from "../security/fileAccessPolicy.js"; import { setAutoUpdaterInitialized } from "../state/appState.js"; +type SmokeConfiguration = Readonly<{ + directory: string; + fixture: string; + nonce: string; +}>; + +type SmokeApp = Readonly>; +type SmokeWindow = Readonly< + Pick +> & { + readonly webContents: Readonly< + Pick + >; +}; + +const configurationError = + "Packaged smoke requires an absolute report directory, fixture and nonce"; + /** Configure the opt-in release self-test before any windows or sessions exist. */ -export function configurePackagedSmoke(app: App | undefined): void { +export function configurePackagedSmoke(app?: SmokeApp): void { if (!process.argv.includes("--ffv-smoke-test")) { return; } - const directory = process.env["FFV_SMOKE_DIRECTORY"]; - const nonce = process.env["FFV_SMOKE_NONCE"]; - const fixture = process.env["FFV_SMOKE_FIXTURE"]; - if ( - !app || - directory === undefined || - directory.length === 0 || - !path.isAbsolute(directory) || - nonce === undefined || - nonce.length === 0 || - fixture === undefined || - fixture.length === 0 || - !path.isAbsolute(fixture) - ) { - throw new Error( - "Packaged smoke requires an absolute report directory, fixture and nonce" - ); + if (!app) { + throw new Error(configurationError); } - const profile = path.join(directory, "user-data"); + const configuration = readSmokeConfiguration(); + const profile = path.join(configuration.directory, "user-data"); + // eslint-disable-next-line security/detect-non-literal-fs-filename -- Explicit local smoke opt-in supplies an absolute diagnostics directory; the profile child name is fixed. mkdirSync(profile, { recursive: true }); app.setPath("userData", profile); // Release verification must never download or install another release. setAutoUpdaterInitialized(true); - approveFilePath(fixture, { source: "packaged-smoke" }); + approveFilePath(configuration.fixture, { source: "packaged-smoke" }); let started = false; app.on("browser-window-created", (_event, mainWindow) => { if (started) { return; } started = true; - void verifyPackagedWindow(mainWindow, fixture, directory, nonce, app); + void verifyPackagedWindow(mainWindow, configuration, app); }); } -async function verifyPackagedWindow( - mainWindow: BrowserWindow, - fixture: string, - directory: string, - nonce: string, - app: App -): Promise { +function requireSmokeValue(value?: string): string { + if (value === undefined || value.length === 0) { + throw new Error(configurationError); + } + return value; +} + +function requireAbsoluteSmokePath(value?: string): string { + const candidate = requireSmokeValue(value); + if (!path.isAbsolute(candidate)) { + throw new Error(configurationError); + } + return candidate; +} + +function readSmokeConfiguration(): SmokeConfiguration { + const { + FFV_SMOKE_DIRECTORY: directory, + FFV_SMOKE_NONCE: nonce, + FFV_SMOKE_FIXTURE: fixture, + } = process.env; + return { + directory: requireAbsoluteSmokePath(directory), + fixture: requireAbsoluteSmokePath(fixture), + nonce: requireSmokeValue(nonce), + }; +} + +function observeWindowFailures(mainWindow: SmokeWindow): string[] { const failures: string[] = []; mainWindow.webContents.on("render-process-gone", (_event, details) => { failures.push( @@ -74,38 +101,57 @@ async function verifyPackagedWindow( } } ); - try { - // Poll actual readiness: did-finish-load alone does not prove module initialization. - let ready = false; - for (let attempt = 0; attempt < 200; attempt += 1) { - if (failures.length > 0 || mainWindow.isDestroyed()) { - throw new Error( - failures.join("; ") || "Window closed during startup" - ); - } - if ( - mainWindow.isVisible() && - mainWindow.webContents.getURL().startsWith("file:") - ) { - ready = await mainWindow.webContents.executeJavaScript( - `(async () => { - const { getState } = await import(new URL('./utils/state/core/stateManager.js', location.href).href); - return getState('app.initialized') === true && Boolean(document.querySelector('#open_file_btn') && !document.querySelector('#open_file_btn').disabled && document.querySelector('#tab_map')); - })()` - ); - if (ready) { - break; - } + return failures; +} + +function assertWindowHealthy( + mainWindow: SmokeWindow, + failures: readonly string[], + message: string, + requireVisible = false +): void { + if ( + failures.length > 0 || + mainWindow.isDestroyed() || + (requireVisible && !mainWindow.isVisible()) + ) { + throw new Error(failures.join("; ") || message); + } +} + +async function waitForRendererReady( + mainWindow: SmokeWindow, + failures: readonly string[] +): Promise { + // did-finish-load alone does not prove module initialization. + for (let attempt = 0; attempt < 200; attempt += 1) { + assertWindowHealthy( + mainWindow, + failures, + "Window closed during startup" + ); + if ( + mainWindow.isVisible() && + mainWindow.webContents.getURL().startsWith("file:") + ) { + const ready: boolean = await mainWindow.webContents + .executeJavaScript(`(async () => { + const { getState } = await import(new URL('./utils/state/core/stateManager.js', location.href).href); + return getState('app.initialized') === true && Boolean(document.querySelector('#open_file_btn') && !document.querySelector('#open_file_btn').disabled && document.querySelector('#tab_map')); + })()`); + if (ready) { + return; } - await delay(100); } - if (!ready) { - throw new Error("Visible renderer UI did not initialize"); - } - // Only fixed, packaged modules are imported. The fixture is a JSON string, - // never executable input. Existing file IPC performs the read and parse. - const activity: unknown = await mainWindow.webContents - .executeJavaScript(`(async () => { + await delay(100); + } + throw new Error("Visible renderer UI did not initialize"); +} + +// Only fixed, packaged modules are imported. The fixture is a JSON string, +// never executable input. Existing file IPC performs the read and parse. +function createFixtureProbeScript(fixture: string): string { + return ` const { openFitFileFromPath } = await import(new URL('./utils/files/import/openFitFileFromPath.js', location.href).href); const { getActiveFitActivityData } = await import(new URL('./utils/state/domain/fitActivityDataState.js', location.href).href); const { getBrowserElectronApiCandidate } = await import(new URL('./utils/runtime/browserRuntime.js', location.href).href); @@ -117,7 +163,11 @@ async function verifyPackagedWindow( const sessionCount = Array.isArray(data?.sessionMesgs) ? data.sessionMesgs.length : 0; const activeFileName = document.querySelector('#active_file_name')?.textContent?.trim() || ''; if (!loaded || recordCount < 1 || sessionCount < 1 || !activeFileName.includes(${JSON.stringify(path.basename(fixture))})) throw new Error('FIT smoke failed: ' + JSON.stringify({ loaded, recordCount, sessionCount, activeFileName, notifications })); - const mapTab = document.querySelector('#tab_map'); +`; +} + +function createMapProbeScript(): string { + return ` const mapTab = document.querySelector('#tab_map'); mapTab.click(); mapTab.scrollIntoView({block: 'start'}); let routeCount = 0; @@ -139,51 +189,91 @@ async function verifyPackagedWindow( const mapBounds = document.querySelector('#leaflet-map').getBoundingClientRect(); if (mapBounds.bottom <= 0 || mapBounds.top >= document.documentElement.clientHeight) throw new Error('Rendered map was outside the visible viewport'); return {recordCount, sessionCount, activeFileName, title: document.title, appInitialized: getState('app.initialized') === true, mapReady, routeCount}; - })()`); - if (failures.length > 0 || !mainWindow.isVisible()) { - throw new Error(failures.join("; ") || "Window became hidden"); - } - // Let Chromium present the completed scroll before capturing its surface. - await delay(500); - const screenshot = await mainWindow.webContents.capturePage(); - if ( - failures.length > 0 || - mainWindow.isDestroyed() || - !mainWindow.isVisible() - ) { - throw new Error( - failures.join("; ") || "Window closed before capture completed" +`; +} + +function createActivityProbeScript(fixture: string): string { + return `(async () => {${createFixtureProbeScript(fixture)}${createMapProbeScript()}})()`; +} + +async function captureWindow( + mainWindow: SmokeWindow, + directory: string, + failures: readonly string[] +): Promise { + assertWindowHealthy(mainWindow, failures, "Window became hidden", true); + // Let Chromium present the completed scroll before capturing its surface. + await delay(500); + const screenshot = await mainWindow.webContents.capturePage(); + assertWindowHealthy( + mainWindow, + failures, + "Window closed before capture completed", + true + ); + const screenshotPath = path.join(directory, "screenshot.png"); + // eslint-disable-next-line security/detect-non-literal-fs-filename -- Fixed diagnostic filename inside the absolute directory validated for explicit local smoke mode. + writeFileSync(screenshotPath, screenshot.toPNG()); +} + +function writeReport( + directory: string, + report: Readonly> +): void { + const reportPath = path.join(directory, "report.json"); + // eslint-disable-next-line security/detect-non-literal-fs-filename -- Fixed report filename inside the absolute directory validated for explicit local smoke mode. + writeFileSync(reportPath, JSON.stringify(report)); +} + +function reportSuccess( + app: SmokeApp, + configuration: SmokeConfiguration, + activity: unknown +): void { + writeReport(configuration.directory, { + activity, + nonce: configuration.nonce, + platform: process.platform, + arch: process.arch, + version: app.getVersion(), + status: "passed", + visible: true, + }); + app.exit(0); +} + +function reportFailure( + app: SmokeApp, + configuration: SmokeConfiguration, + failures: readonly string[], + error: unknown +): void { + const message = error instanceof Error ? error.message : String(error); + writeReport(configuration.directory, { + nonce: configuration.nonce, + status: "failed", + error: message, + failures, + }); + console.error(`[packaged-smoke] ${message}`); + app.exit(1); +} + +async function verifyPackagedWindow( + mainWindow: SmokeWindow, + configuration: SmokeConfiguration, + app: SmokeApp +): Promise { + const failures = observeWindowFailures(mainWindow); + try { + await waitForRendererReady(mainWindow, failures); + const activity: unknown = + await mainWindow.webContents.executeJavaScript( + createActivityProbeScript(configuration.fixture) ); - } - writeFileSync( - path.join(directory, "screenshot.png"), - screenshot.toPNG() - ); - writeFileSync( - path.join(directory, "report.json"), - JSON.stringify({ - activity, - nonce, - platform: process.platform, - arch: process.arch, - version: app.getVersion(), - status: "passed", - visible: true, - }) - ); - app.exit(0); + await captureWindow(mainWindow, configuration.directory, failures); + reportSuccess(app, configuration, activity); } catch (error) { - const message = error instanceof Error ? error.message : String(error); - writeFileSync( - path.join(directory, "report.json"), - JSON.stringify({ - nonce, - status: "failed", - error: message, - failures, - }) - ); - console.error(`[packaged-smoke] ${message}`); - app.exit(1); + reportFailure(app, configuration, failures, error); } } diff --git a/scripts/run-distributable-smoke.mjs b/scripts/run-distributable-smoke.mjs index f405f6e1e..fe592ccea 100644 --- a/scripts/run-distributable-smoke.mjs +++ b/scripts/run-distributable-smoke.mjs @@ -18,28 +18,17 @@ import { // These are the artifacts users install or extract, rather than the builder's // intermediate unpacked tree. Exact names prevent silently testing stale builds. export function getDistributableNames({ platform, arch, version }) { - const separator = version.indexOf("-"); - const core = separator === -1 ? version : version.slice(0, separator); - const prerelease = - separator === -1 ? undefined : version.slice(separator + 1); - if ( - !/^\d+\.\d+\.\d+$/u.test(core) || - (prerelease !== undefined && !/^[\dA-Za-z.-]+$/u.test(prerelease)) - ) { - throw new Error(`Invalid package version: ${version}`); - } + assertValidVersion(version); const supported = - platform === "darwin" - ? [ - "arm64", - "x64", - "universal", - ] - : platform === "win32" - ? ["x64", "ia32"] - : platform === "linux" - ? ["x64"] - : []; + { + darwin: [ + "arm64", + "x64", + "universal", + ], + win32: ["x64", "ia32"], + linux: ["x64"], + }[platform] ?? []; if (!supported.includes(arch)) { throw new Error( `Unsupported distributable smoke platform/architecture: ${platform}/${arch}` @@ -61,6 +50,19 @@ export function getDistributableNames({ platform, arch, version }) { ]; } +function assertValidVersion(version) { + const separator = version.indexOf("-"); + const core = separator === -1 ? version : version.slice(0, separator); + const prerelease = + separator === -1 ? undefined : version.slice(separator + 1); + if ( + !/^\d+\.\d+\.\d+$/u.test(core) || + (prerelease !== undefined && !/^[\dA-Za-z.-]+$/u.test(prerelease)) + ) { + throw new Error(`Invalid package version: ${version}`); + } +} + export function runChecked(command, args, options = {}, runner = spawnSync) { const result = runner(command, args, { encoding: "utf8", diff --git a/scripts/run-packaged-smoke.mjs b/scripts/run-packaged-smoke.mjs index ab80c39fe..8ad553b7f 100644 --- a/scripts/run-packaged-smoke.mjs +++ b/scripts/run-packaged-smoke.mjs @@ -286,13 +286,15 @@ export function runPackagedSmoke( report.nonce !== nonce || report.status !== "passed" || report.visible !== true || - !Number.isSafeInteger(report.activity?.recordCount) || + report.activity === null || + typeof report.activity !== "object" || + !Number.isSafeInteger(report.activity.recordCount) || report.activity.recordCount < 1 || report.activity.appInitialized !== true || report.activity.mapReady !== true || !Number.isSafeInteger(report.activity.routeCount) || report.activity.routeCount < 1 || - !Number.isSafeInteger(report.activity?.sessionCount) || + !Number.isSafeInteger(report.activity.sessionCount) || report.activity.sessionCount < 1 ) { throw new Error( diff --git a/tests/unit/packaging/packagedSmokeRuntime.test.ts b/tests/unit/packaging/packagedSmokeRuntime.test.ts index c862f8320..d56845dac 100644 --- a/tests/unit/packaging/packagedSmokeRuntime.test.ts +++ b/tests/unit/packaging/packagedSmokeRuntime.test.ts @@ -78,6 +78,27 @@ describe("packaged smoke runtime", () => { ).toThrow("requires an absolute report directory"); }); + it.each([ + ["FFV_SMOKE_DIRECTORY", undefined], + ["FFV_SMOKE_DIRECTORY", "relative-directory"], + ["FFV_SMOKE_FIXTURE", ""], + ["FFV_SMOKE_FIXTURE", "relative.fit"], + ])("rejects invalid %s before creating a profile", (name, value) => { + expect.assertions(2); + vi.stubEnv(name, value); + expect(() => + configurePackagedSmoke(createApp() as unknown as App) + ).toThrow("requires an absolute report directory"); + expect(existsSync(path.join(directory, "user-data"))).toBe(false); + }); + + it("requires Electron when smoke mode is explicitly requested", () => { + expect.assertions(1); + expect(() => configurePackagedSmoke()).toThrow( + "requires an absolute report directory" + ); + }); + it("isolates the profile, prevents updates and writes a successful visible FIT report", async () => { expect.assertions(6); const app = createApp(); @@ -172,4 +193,35 @@ describe("packaged smoke runtime", () => { error: "Renderer terminated: crashed (11)", }); }); + + it("does not publish success when the renderer crashes during capture", async () => { + expect.assertions(3); + const app = createApp(); + const mainWindow = createWindow(); + mainWindow.webContents.capturePage.mockImplementation(async () => { + mainWindow.webContents.emit( + "render-process-gone", + {}, + { reason: "crashed", exitCode: 11 } + ); + return { toPNG: () => Buffer.from("stale screenshot") }; + }); + configurePackagedSmoke(app as unknown as App); + app.emit( + "browser-window-created", + {}, + mainWindow as unknown as BrowserWindow + ); + await vi.waitUntil(() => app.exit.mock.calls.length > 0); + expect(app.exit).toHaveBeenCalledWith(1); + expect( + JSON.parse( + readFileSync(path.join(directory, "report.json"), "utf8") + ) + ).toMatchObject({ + status: "failed", + error: "Renderer terminated: crashed (11)", + }); + expect(existsSync(path.join(directory, "screenshot.png"))).toBe(false); + }); }); diff --git a/tests/unit/packaging/runDistributableSmoke.test.ts b/tests/unit/packaging/runDistributableSmoke.test.ts index e86d6ecb3..3bfc3354c 100644 --- a/tests/unit/packaging/runDistributableSmoke.test.ts +++ b/tests/unit/packaging/runDistributableSmoke.test.ts @@ -27,6 +27,22 @@ function makeRelease(platform: string, arch: string): string { return directory; } +function readSmokeReport( + releaseDirectory: string, + platform: string, + arch: string +): unknown { + return JSON.parse( + fs.readFileSync( + path.join( + releaseDirectory, + `distributable-smoke-${platform}-${arch}.json` + ), + "utf8" + ) + ); +} + function createExecutable(destination: string, platform: string): void { const executable = platform === "darwin" @@ -314,15 +330,7 @@ describe("final distributable smoke", () => { ]); expect(wrappers[2]).toContain('"FFV_SMOKE_NONCE=$FFV_SMOKE_NONCE"'); expect( - JSON.parse( - fs.readFileSync( - path.join( - releaseDirectory, - "distributable-smoke-darwin-universal.json" - ), - "utf8" - ) - ) + readSmokeReport(releaseDirectory, "darwin", "universal") ).toMatchObject({ artifacts: [ { diff --git a/tests/unit/packaging/runPackagedSmoke.test.ts b/tests/unit/packaging/runPackagedSmoke.test.ts index cfa1ffa70..2ab7686be 100644 --- a/tests/unit/packaging/runPackagedSmoke.test.ts +++ b/tests/unit/packaging/runPackagedSmoke.test.ts @@ -1,7 +1,6 @@ import { chmodSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; -import process from "node:process"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -300,6 +299,20 @@ describe("run-packaged-smoke script", () => { it.each([ undefined, + { + status: "passed", + visible: true, + }, + { + status: "passed", + visible: true, + activity: null, + }, + { + status: "passed", + visible: true, + activity: "untrusted report data", + }, { nonce: "forged", status: "passed", diff --git a/tests/unit/packaging/verifySignedArtifacts.test.ts b/tests/unit/packaging/verifySignedArtifacts.test.ts index cbe928025..7298a0d7a 100644 --- a/tests/unit/packaging/verifySignedArtifacts.test.ts +++ b/tests/unit/packaging/verifySignedArtifacts.test.ts @@ -101,6 +101,13 @@ function createTemporaryReleaseDir() { return releaseDir; } +function readSigningReport( + releaseDir: string, + fileName = "signing-verification-report.json" +): ReturnType { + return JSON.parse(fs.readFileSync(path.join(releaseDir, fileName), "utf8")); +} + afterEach(() => { for (const temporaryDirectory of temporaryDirectories.splice(0)) { fs.rmSync(temporaryDirectory, { force: true, recursive: true }); @@ -206,14 +213,11 @@ describe("verify-signed-artifacts script", () => { expect(macosCommand.args).toContain("--verify"); }); - it("runs Windows verification when publisher signing is required and skips Linux", async () => { - expect.assertions(7); + it("skips Linux verification even when publisher signing is required", async () => { + expect.assertions(3); const releaseDir = createTemporaryReleaseDir(); - const reportPath = path.join(releaseDir, "signing-report.json"); - fs.writeFileSync(path.join(releaseDir, "Fit-File-Viewer.exe"), ""); const commandRunner = vi.fn(() => ({ status: 0 })); - const logger = vi.fn<(message: string) => void>(); const { verifySignedArtifacts } = await importVerifySignedArtifacts(); expect( @@ -223,14 +227,29 @@ describe("verify-signed-artifacts script", () => { "linux", "--release-dir", releaseDir, - "--report", - reportPath, ], { REQUIRE_CODE_SIGNING: "true" }, - commandRunner, - logger + commandRunner ) ).toBe(0); + expect(commandRunner).not.toHaveBeenCalled(); + expect(readSigningReport(releaseDir)).toMatchObject({ + platform: "linux", + signingRequired: true, + status: "skipped", + }); + }); + + it("runs Windows verification when publisher signing is required", async () => { + expect.assertions(6); + + const releaseDir = createTemporaryReleaseDir(); + const reportPath = path.join(releaseDir, "signing-report.json"); + fs.writeFileSync(path.join(releaseDir, "Fit-File-Viewer.exe"), ""); + const commandRunner = vi.fn(() => ({ status: 0 })); + const logger = vi.fn<(message: string) => void>(); + const { verifySignedArtifacts } = await importVerifySignedArtifacts(); + expect( verifySignedArtifacts( [ @@ -248,18 +267,17 @@ describe("verify-signed-artifacts script", () => { ).toBe(0); expect(commandRunner).toHaveBeenCalledOnce(); expect(commandRunner.mock.calls[0]?.[0]).toBe("powershell.exe"); - expect(JSON.parse(fs.readFileSync(reportPath, "utf8"))).toMatchObject({ + const report = readSigningReport(releaseDir, "signing-report.json"); + expect(report).toMatchObject({ artifactCount: 1, platform: "win32", signingRequired: true, status: "verified", }); - expect( - JSON.parse(fs.readFileSync(reportPath, "utf8")).artifacts - ).toStrictEqual([{ path: "Fit-File-Viewer.exe", type: "file" }]); - expect( - JSON.parse(fs.readFileSync(reportPath, "utf8")).verificationResults - ).toStrictEqual([ + expect(report.artifacts).toStrictEqual([ + { path: "Fit-File-Viewer.exe", type: "file" }, + ]); + expect(report.verificationResults).toStrictEqual([ expect.objectContaining({ command: "powershell.exe", path: "Fit-File-Viewer.exe", @@ -313,17 +331,7 @@ describe("verify-signed-artifacts script", () => { ], expect.objectContaining({ stdio: "inherit" }), ]); - expect( - JSON.parse( - fs.readFileSync( - path.join( - releaseDir, - "signing-verification-report.json" - ), - "utf8" - ) - ) - ).toMatchObject({ + expect(readSigningReport(releaseDir)).toMatchObject({ artifactCount: 1, signingRequired: false, status: "verified", From 85df650e7a64be52449f9a23c3b5181394b91819 Mon Sep 17 00:00:00 2001 From: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:29:55 -0400 Subject: [PATCH 03/12] =?UTF-8?q?=F0=9F=90=9B=20[fix]=20Harden=20native=20?= =?UTF-8?q?smoke=20execution=20and=20failure=20diagnostics?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿ› [fix] Always exit unsuccessful smoke runs when diagnostic reporting fails, and select the native Windows archive extractor for drive-letter paths. ๐Ÿงช [test] Cover readiness deadlines, missing report directories, archive extraction, and child-process failures. ๐Ÿ‘ท [build] Run the complete release gate independently of platform artifacts while preserving its failure status. ๐Ÿงช [test] Probe Rosetta and sample stalled Universal smoke processes without changing the application timeout; retain failed packages for diagnosis. --- .github/workflows/Build.yml | 17 +- .github/workflows/release-rehearsal.yml | 99 +++++-- electron-app/main/runtime/packagedSmoke.ts | 38 ++- scripts/run-distributable-smoke.mjs | 41 ++- scripts/run-macos-smoke-diagnostics.mjs | 258 ++++++++++++++++++ .../packaging/packagedSmokeRuntime.test.ts | 57 ++++ .../releaseRehearsalWorkflow.test.ts | 33 +++ .../packaging/runDistributableSmoke.test.ts | 114 ++++++-- .../runMacosSmokeDiagnostics.test.ts | 241 ++++++++++++++++ 9 files changed, 841 insertions(+), 57 deletions(-) create mode 100644 scripts/run-macos-smoke-diagnostics.mjs create mode 100644 tests/unit/packaging/runMacosSmokeDiagnostics.test.ts diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 3de27ba56..f6759d692 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -303,13 +303,17 @@ jobs: - name: Enable Intel slice testing on Apple Silicon if: runner.os == 'macOS' && matrix.arch == 'universal' shell: bash - run: softwareupdate --install-rosetta --agree-to-license + run: | + softwareupdate --install-rosetta --agree-to-license + node scripts/run-macos-smoke-diagnostics.mjs --probe-rosetta - name: Smoke test installed distributable artifacts shell: bash run: | if [ "$RUNNER_OS" = "Linux" ]; then xvfb-run -a node scripts/run-distributable-smoke.mjs + elif [ "$RUNNER_OS" = "macOS" ] && [ "$MATRIX_ARCH" = "universal" ]; then + node scripts/run-macos-smoke-diagnostics.mjs else node scripts/run-distributable-smoke.mjs fi @@ -330,6 +334,17 @@ jobs: if-no-files-found: ignore retention-days: 14 + - name: Preserve failed Universal package for diagnosis + if: failure() && runner.os == 'macOS' && matrix.arch == 'universal' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: failed-universal-package-${{ github.run_attempt }} + path: | + release-dist/Fit-File-Viewer-dmg-universal-*.dmg + release-dist/signing-verification-report.json + if-no-files-found: ignore + retention-days: 7 + - name: Print distributable hashes (debug) id: print_hashes shell: bash diff --git a/.github/workflows/release-rehearsal.yml b/.github/workflows/release-rehearsal.yml index 752d8fda3..09640ab28 100644 --- a/.github/workflows/release-rehearsal.yml +++ b/.github/workflows/release-rehearsal.yml @@ -34,6 +34,68 @@ permissions: contents: read jobs: + release-verification: + name: Verify Complete Release Gate + runs-on: ubuntu-latest + timeout-minutes: 60 + env: + CI: true + NODE_OPTIONS: --max_old_space_size=8192 + defaults: + run: + shell: bash + steps: + - name: Harden the runner (Audit all outbound calls) + uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4 + with: + egress-policy: audit + + - name: Checkout Repo code + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + fetch-depth: 0 + + - name: Setup Node.js environment + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version-file: .node-version + + - name: Setup npm version + run: npm install --global npm@12.0.2 + + - name: Install app and docs dependencies + run: | + npm ci --no-audit --no-fund + npm ci --prefix docusaurus --no-audit --no-fund + + - name: Run release verification and packaged smoke + run: | + xvfb-run -a npm run release:verify & + verify_pid=$! + while kill -0 "$verify_pid" 2>/dev/null; do + sleep 60 + if kill -0 "$verify_pid" 2>/dev/null; then + echo "Release verification is still running..." + fi + done + wait "$verify_pid" + env: + CSC_IDENTITY_AUTO_DISCOVERY: "false" + FFV_SMOKE_DIAGNOSTICS_DIRECTORY: release-dist/smoke-diagnostics + FFV_PACKAGED_SMOKE_TIMEOUT_MS: ${{ inputs.smoke-timeout-ms }} + FFV_FORCE_UNSIGNED_PACKAGE: "true" + REQUIRE_CODE_SIGNING: "false" + RUNNER_OS: Linux + + - name: Upload release gate smoke diagnostics + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: release-gate-smoke-diagnostics + path: release-dist/smoke-diagnostics/** + if-no-files-found: ignore + retention-days: 14 + release-rehearsal: name: Verify Unsigned Release Package (${{ matrix.os }}, ${{ matrix.arch }}) runs-on: ${{ matrix.os }} @@ -45,7 +107,6 @@ jobs: - os: ubuntu-latest runner-os: Linux arch: x64 - release-verify-command: xvfb-run -a npm run release:verify - os: windows-latest runner-os: Windows arch: x64 @@ -120,25 +181,6 @@ jobs: CSC_LINK: ${{ matrix.runner-os == 'macOS' && secrets.MACOS_CSC_LINK || '' }} WIN_CSC_LINK: ${{ matrix.runner-os == 'Windows' && secrets.WINDOWS_CSC_LINK || '' }} - - name: Run release verification and packaged smoke - if: runner.os == 'Linux' - run: | - ${{ matrix.release-verify-command }} & - verify_pid=$! - while kill -0 "$verify_pid" 2>/dev/null; do - sleep 60 - if kill -0 "$verify_pid" 2>/dev/null; then - echo "Release verification is still running..." - fi - done - wait "$verify_pid" - env: - CSC_IDENTITY_AUTO_DISCOVERY: "false" - FFV_PACKAGED_SMOKE_TIMEOUT_MS: ${{ inputs.smoke-timeout-ms }} - FFV_FORCE_UNSIGNED_PACKAGE: "true" - REQUIRE_CODE_SIGNING: "false" - RUNNER_OS: ${{ matrix.runner-os }} - - name: Install platform build dependencies run: node scripts/install-build-dependencies.mjs @@ -165,12 +207,16 @@ jobs: - name: Enable Intel slice testing on Apple Silicon if: runner.os == 'macOS' && matrix.arch == 'universal' - run: softwareupdate --install-rosetta --agree-to-license + run: | + softwareupdate --install-rosetta --agree-to-license + node scripts/run-macos-smoke-diagnostics.mjs --probe-rosetta - name: Smoke test installed distributable artifacts run: | if [ "$RUNNER_OS" = "Linux" ]; then xvfb-run -a node scripts/run-distributable-smoke.mjs + elif [ "$RUNNER_OS" = "macOS" ] && [ "$MATRIX_ARCH" = "universal" ]; then + node scripts/run-macos-smoke-diagnostics.mjs else node scripts/run-distributable-smoke.mjs fi @@ -190,6 +236,17 @@ jobs: if-no-files-found: ignore retention-days: 14 + - name: Preserve failed Universal package for diagnosis + if: failure() && runner.os == 'macOS' && matrix.arch == 'universal' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: failed-universal-package-${{ github.run_attempt }} + path: | + release-dist/Fit-File-Viewer-dmg-universal-*.dmg + release-dist/signing-verification-report.json + if-no-files-found: ignore + retention-days: 7 + - name: List unsigned rehearsal artifacts if: always() run: npm run release:list-release-dist-files diff --git a/electron-app/main/runtime/packagedSmoke.ts b/electron-app/main/runtime/packagedSmoke.ts index 36a25e412..9c6c53ae3 100644 --- a/electron-app/main/runtime/packagedSmoke.ts +++ b/electron-app/main/runtime/packagedSmoke.ts @@ -122,7 +122,7 @@ function assertWindowHealthy( async function waitForRendererReady( mainWindow: SmokeWindow, failures: readonly string[] -): Promise { +): Promise { // did-finish-load alone does not prove module initialization. for (let attempt = 0; attempt < 200; attempt += 1) { assertWindowHealthy( @@ -140,12 +140,12 @@ async function waitForRendererReady( return getState('app.initialized') === true && Boolean(document.querySelector('#open_file_btn') && !document.querySelector('#open_file_btn').disabled && document.querySelector('#tab_map')); })()`); if (ready) { - return; + return true; } } await delay(100); } - throw new Error("Visible renderer UI did not initialize"); + return false; } // Only fixed, packaged modules are imported. The fixture is a JSON string, @@ -249,14 +249,25 @@ function reportFailure( error: unknown ): void { const message = error instanceof Error ? error.message : String(error); - writeReport(configuration.directory, { - nonce: configuration.nonce, - status: "failed", - error: message, - failures, - }); - console.error(`[packaged-smoke] ${message}`); - app.exit(1); + try { + console.error(`[packaged-smoke] ${message}`); + writeReport(configuration.directory, { + nonce: configuration.nonce, + status: "failed", + error: message, + failures, + }); + } catch (reportError) { + const diagnosticMessage = + reportError instanceof Error + ? reportError.message + : String(reportError); + console.error( + `[packaged-smoke] Unable to write failure report: ${diagnosticMessage}` + ); + } finally { + app.exit(1); + } } async function verifyPackagedWindow( @@ -266,7 +277,10 @@ async function verifyPackagedWindow( ): Promise { const failures = observeWindowFailures(mainWindow); try { - await waitForRendererReady(mainWindow, failures); + const ready = await waitForRendererReady(mainWindow, failures); + if (!ready) { + throw new Error("Visible renderer UI did not initialize"); + } const activity: unknown = await mainWindow.webContents.executeJavaScript( createActivityProbeScript(configuration.fixture) diff --git a/scripts/run-distributable-smoke.mjs b/scripts/run-distributable-smoke.mjs index fe592ccea..75799b354 100644 --- a/scripts/run-distributable-smoke.mjs +++ b/scripts/run-distributable-smoke.mjs @@ -78,6 +78,36 @@ export function runChecked(command, args, options = {}, runner = spawnSync) { return result; } +export function getArchiveExtractionCommand( + { platform, environment, artifact, destination }, + exists = fs.existsSync +) { + let command = "tar"; + if (platform === "win32") { + const systemRoot = environment.SystemRoot; + if (!systemRoot || !path.win32.isAbsolute(systemRoot)) { + throw new Error( + "An absolute SystemRoot is required to locate the native Windows archive extractor" + ); + } + command = path.win32.join(systemRoot, "System32", "tar.exe"); + if (!exists(command)) { + throw new Error( + `Native Windows archive extractor is unavailable: ${command}` + ); + } + } + return { + command, + args: [ + "-xf", + artifact, + "-C", + destination, + ], + }; +} + export function getWindowsInstallRegistrations(run = runChecked) { const result = run("powershell.exe", [ "-NoProfile", @@ -248,12 +278,11 @@ export function runDistributableSmoke( fs.chmodSync(artifact, 0o755); run(artifact, ["--appimage-extract"], { cwd: destination }); } else if (!name.includes("-portable-")) { - run("tar", [ - "-xf", - artifact, - "-C", - destination, - ]); + const extraction = getArchiveExtractionCommand( + { platform, environment, artifact, destination }, + dependencies.archiveExtractorExists + ); + run(extraction.command, extraction.args); } const executable = name.includes("-portable-") ? artifact diff --git a/scripts/run-macos-smoke-diagnostics.mjs b/scripts/run-macos-smoke-diagnostics.mjs new file mode 100644 index 000000000..c377ac716 --- /dev/null +++ b/scripts/run-macos-smoke-diagnostics.mjs @@ -0,0 +1,258 @@ +import { execFile, spawn } from "node:child_process"; +import { once } from "node:events"; +import fs from "node:fs"; +import path from "node:path"; +import process from "node:process"; +import { pathToFileURL } from "node:url"; + +import { + repositoryRoot, + rootReleaseDistAbsolutePath, +} from "./lib/workspaces.mjs"; + +const smokeExecutable = "Fit File Viewer.app/Contents/MacOS/Fit File Viewer"; +const rosettaLogPredicate = + 'process == "oahd" OR process == "oahd-helper" OR (process == "kernel" AND (eventMessage CONTAINS[c] "rosetta" OR eventMessage CONTAINS[c] "code sign"))'; + +async function execFileAsync(command, args, options) { + return new Promise((resolve, reject) => { + execFile(command, args, options, (error, stdout, stderr) => { + if (error) { + const failure = new Error(error.message, { cause: error }); + Object.assign(failure, { stdout, stderr }); + reject(failure); + return; + } + resolve({ stdout, stderr }); + }); + }); +} + +export function findSmokeProcesses(output, harnessPid) { + const processes = output.split("\n").flatMap((line) => { + const match = /^\s*(\d+)\s+(\d+)\s+(.+)$/u.exec(line); + return match + ? [ + { + pid: Number(match[1]), + parentPid: Number(match[2]), + command: match[3], + }, + ] + : []; + }); + const descendants = new Set([harnessPid]); + let changed = true; + while (changed) { + changed = false; + for (const candidate of processes) { + if ( + descendants.has(candidate.parentPid) && + !descendants.has(candidate.pid) + ) { + descendants.add(candidate.pid); + changed = true; + } + } + } + return processes.filter( + ({ pid, command }) => + descendants.has(pid) && + command.includes(smokeExecutable) && + command.includes("--ffv-smoke-test") + ); +} + +export function selectProcessesToSample(processes, observations, now) { + const selected = []; + for (const candidate of processes) { + const observation = observations.get(candidate.pid); + if (!observation) { + observations.set(candidate.pid, { firstSeen: now, sampled: false }); + } else if ( + !observation.sampled && + now - observation.firstSeen >= 20_000 + ) { + observation.sampled = true; + selected.push(candidate); + } + } + return selected; +} + +export async function captureDiagnosticCommand( + command, + args, + runner = execFileAsync +) { + try { + return { + status: 0, + ...(await runner(command, args, { + encoding: "utf8", + timeout: 15_000, + maxBuffer: 4 * 1024 * 1024, + })), + }; + } catch (error) { + return { + status: 1, + stdout: error.stdout ?? "", + stderr: error.stderr || error.message, + }; + } +} + +function writeDiagnostic(directory, name, result) { + fs.writeFileSync( + path.join(directory, name), + `status=${result.status}\n${result.stdout}\n${result.stderr}\n` + ); +} + +export async function verifyRosetta( + directory, + capture = captureDiagnosticCommand +) { + fs.mkdirSync(directory, { recursive: true }); + console.log("[macos-smoke] Probing /usr/bin/arch -x86_64 /usr/bin/true"); + const result = await capture("/usr/bin/arch", ["-x86_64", "/usr/bin/true"]); + writeDiagnostic(directory, "rosetta-probe.log", result); + if (result.status !== 0) + throw new Error(`Rosetta execution probe failed: ${result.stderr}`); +} + +export async function sampleHungSmokeProcesses( + harnessPid, + directory, + observations, + dependencies = {} +) { + const capture = dependencies.capture ?? captureDiagnosticCommand; + const now = dependencies.now ?? Date.now; + const processList = await capture("/bin/ps", [ + "-axo", + "pid=,ppid=,command=", + ]); + if (processList.status !== 0) { + // Never persist a full process listing: other CI processes may carry secrets. + writeDiagnostic(directory, "process-inspection-error.txt", { + ...processList, + stdout: "", + }); + return; + } + const candidates = findSmokeProcesses(processList.stdout, harnessPid); + for (const candidate of selectProcessesToSample( + candidates, + observations, + now() + )) { + fs.writeFileSync( + path.join(directory, `process-${candidate.pid}.json`), + `${JSON.stringify(candidate, null, 2)}\n` + ); + const samplePath = path.join(directory, `sample-${candidate.pid}.txt`); + const result = await capture("/usr/bin/sample", [ + String(candidate.pid), + "5", + "1", + "-file", + samplePath, + ]); + writeDiagnostic( + directory, + `sample-${candidate.pid}-command.txt`, + result + ); + } +} + +export async function runMacosSmokeDiagnostics( + options = {}, + dependencies = {} +) { + const platform = options.platform ?? process.platform; + if (platform !== "darwin") + throw new Error("macOS smoke diagnostics require macOS"); + const directory = + options.directory ?? + path.join( + rootReleaseDistAbsolutePath, + "smoke-diagnostics", + "native-processes" + ); + fs.mkdirSync(directory, { recursive: true }); + const spawnHarness = dependencies.spawn ?? spawn; + const capture = dependencies.capture ?? captureDiagnosticCommand; + const child = spawnHarness( + process.execPath, + [path.join(repositoryRoot, "scripts/run-distributable-smoke.mjs")], + { + cwd: repositoryRoot, + env: options.environment ?? process.env, + stdio: "inherit", + timeout: 15 * 60 * 1000, + } + ); + const stopMonitor = startSmokeProcessMonitor(child, directory, { + capture, + inspect: dependencies.inspect ?? sampleHungSmokeProcesses, + }); + try { + const [status, signal] = await once(child, "close"); + return signal ? 1 : (status ?? 1); + } finally { + await stopMonitor(); + const logs = await capture("/usr/bin/log", [ + "show", + "--last", + "5m", + "--style", + "compact", + "--predicate", + rosettaLogPredicate, + ]); + writeDiagnostic(directory, "rosetta-system.log", logs); + } +} + +function startSmokeProcessMonitor(child, directory, { capture, inspect }) { + const observations = new Map(); + let pending; + const timer = setInterval(() => { + if (pending || !child.pid) return; + pending = inspect(child.pid, directory, observations, { capture }) + .catch((error) => { + writeDiagnostic(directory, "monitor-error.txt", { + status: 1, + stdout: "", + stderr: String(error), + }); + }) + .finally(() => { + pending = undefined; + }); + }, 5000); + return async () => { + clearInterval(timer); + await pending; + }; +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + if (process.argv.includes("--probe-rosetta")) { + await verifyRosetta( + path.join( + rootReleaseDistAbsolutePath, + "smoke-diagnostics", + "native-processes" + ) + ); + } else { + process.exitCode = await runMacosSmokeDiagnostics(); + } +} diff --git a/tests/unit/packaging/packagedSmokeRuntime.test.ts b/tests/unit/packaging/packagedSmokeRuntime.test.ts index d56845dac..b81c715f3 100644 --- a/tests/unit/packaging/packagedSmokeRuntime.test.ts +++ b/tests/unit/packaging/packagedSmokeRuntime.test.ts @@ -30,6 +30,7 @@ beforeEach(() => { afterEach(() => { process.argv = originalArguments; + vi.restoreAllMocks(); vi.unstubAllEnvs(); rmSync(directory, { recursive: true, force: true }); }); @@ -161,6 +162,62 @@ describe("packaged smoke runtime", () => { }); }); + it("reports an explicit readiness deadline failure without loading a fixture", async () => { + expect.assertions(3); + const app = createApp(); + const mainWindow = createWindow(); + mainWindow.isVisible.mockReturnValue(false); + configurePackagedSmoke(app as unknown as App); + app.emit( + "browser-window-created", + {}, + mainWindow as unknown as BrowserWindow + ); + await vi.waitUntil(() => app.exit.mock.calls.length > 0, { + timeout: 35_000, + }); + expect(app.exit).toHaveBeenCalledWith(1); + expect( + JSON.parse( + readFileSync(path.join(directory, "report.json"), "utf8") + ) + ).toMatchObject({ + status: "failed", + error: "Visible renderer UI did not initialize", + }); + expect(mainWindow.webContents.executeJavaScript).not.toHaveBeenCalled(); + }, 40_000); + + it("preserves the original failure and exits if the report directory disappears", async () => { + expect.assertions(4); + const errorLogger = vi + .spyOn(console, "error") + .mockImplementation(() => undefined); + const app = createApp(); + const mainWindow = createWindow(); + mainWindow.webContents.executeJavaScript + .mockReset() + .mockImplementationOnce(async () => { + rmSync(directory, { recursive: true, force: true }); + throw new Error("Original renderer failure"); + }); + configurePackagedSmoke(app as unknown as App); + app.emit( + "browser-window-created", + {}, + mainWindow as unknown as BrowserWindow + ); + await vi.waitUntil(() => app.exit.mock.calls.length > 0); + expect(app.exit).toHaveBeenCalledWith(1); + expect(errorLogger).toHaveBeenCalledWith( + "[packaged-smoke] Original renderer failure" + ); + expect(errorLogger).toHaveBeenCalledWith( + expect.stringContaining("Unable to write failure report:") + ); + expect(existsSync(path.join(directory, "report.json"))).toBe(false); + }); + it("fails renderer crashes even if the load probe later resolves", async () => { expect.assertions(2); const app = createApp(); diff --git a/tests/unit/packaging/releaseRehearsalWorkflow.test.ts b/tests/unit/packaging/releaseRehearsalWorkflow.test.ts index 596a68863..7e085634a 100644 --- a/tests/unit/packaging/releaseRehearsalWorkflow.test.ts +++ b/tests/unit/packaging/releaseRehearsalWorkflow.test.ts @@ -2,6 +2,7 @@ import { readFileSync } from "node:fs"; import path from "node:path"; import { describe, expect, it } from "vitest"; +import { parse as parseYaml } from "yaml"; const releaseRehearsalWorkflowPath = path.join( process.cwd(), @@ -15,6 +16,38 @@ function readReleaseRehearsalWorkflow(): string { } describe("release rehearsal workflow", () => { + it("requires the complete gate independently of all six native artifact jobs", () => { + expect.assertions(9); + type RehearsalJob = { + "runs-on": string; + "timeout-minutes": number; + steps: { run?: string }[]; + strategy?: { matrix: { include: unknown[] } }; + }; + const { jobs } = parseYaml(readReleaseRehearsalWorkflow()) as { + jobs: Record< + "release-verification" | "release-rehearsal", + RehearsalJob + >; + }; + const gate = jobs["release-verification"]; + const artifacts = jobs["release-rehearsal"]; + const gateCommands = gate.steps + .map((step) => step.run ?? "") + .join("\n"); + expect(gate["runs-on"]).toBe("ubuntu-latest"); + expect(gate["timeout-minutes"]).toBe(60); + expect(gate).not.toHaveProperty("continue-on-error"); + expect(gate).not.toHaveProperty("if"); + expect(artifacts).not.toHaveProperty("needs"); + expect(gateCommands).toContain("xvfb-run -a npm run release:verify &"); + expect(gateCommands).toContain('wait "$verify_pid"'); + expect( + artifacts.steps.map((step) => step.run ?? "").join("\n") + ).not.toMatch(/npm run release:verify(?:\s|$)/u); + expect(artifacts.strategy?.matrix.include).toHaveLength(6); + }); + it("runs the release gate, signing preflight, packaged smoke, and artifact upload without publishing", () => { expect.assertions(46); diff --git a/tests/unit/packaging/runDistributableSmoke.test.ts b/tests/unit/packaging/runDistributableSmoke.test.ts index 3bfc3354c..d2546f983 100644 --- a/tests/unit/packaging/runDistributableSmoke.test.ts +++ b/tests/unit/packaging/runDistributableSmoke.test.ts @@ -6,6 +6,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { assertNoWindowsInstallRegistrations, + getArchiveExtractionCommand, getDistributableNames, getWindowsInstallRegistrations, runChecked, @@ -13,6 +14,10 @@ import { } from "../../../scripts/run-distributable-smoke.mjs"; const directories: string[] = []; +const windowsSmokeEnvironment = { SystemRoot: "C:\\Windows" }; +const nativeWindowsTar = "C:\\Windows\\System32\\tar.exe"; +const archiveExtractorExists = (command: string): boolean => + command === nativeWindowsTar; function makeRelease(platform: string, arch: string): string { const directory = fs.mkdtempSync(path.join(tmpdir(), "ffv-artifact-test-")); @@ -52,6 +57,24 @@ function createExecutable(destination: string, platform: string): void { fs.writeFileSync(executable, "fixture executable"); } +function makeWindowsArtifactRunner( + calls: string[][] +): (command: string, args: string[]) => void { + return (command, args) => { + calls.push([command, ...args]); + if (command === nativeWindowsTar) + createExecutable(args[3] ?? "", "win32"); + if (command.includes("-nsis-")) { + const destination = args[2]?.slice(3) ?? ""; + createExecutable(destination, "win32"); + fs.writeFileSync( + path.join(destination, "Uninstall Fit File Viewer.exe"), + "fixture uninstaller" + ); + } + }; +} + afterEach(() => { for (const directory of directories.splice(0)) { fs.rmSync(directory, { recursive: true, force: true }); @@ -59,6 +82,58 @@ afterEach(() => { }); describe("final distributable smoke", () => { + it("uses native Windows tar and preserves D drive archive paths under a Git Bash environment", () => { + expect.assertions(1); + expect( + getArchiveExtractionCommand( + { + platform: "win32", + environment: { + ...windowsSmokeEnvironment, + PATH: "C:\\Program Files\\Git\\usr\\bin", + }, + artifact: + "D:\\a\\release-dist\\Fit-File-Viewer-msi-x64-30.0.3.zip", + destination: "D:\\a\\_temp\\installed", + }, + archiveExtractorExists + ) + ).toStrictEqual({ + command: nativeWindowsTar, + args: [ + "-xf", + "D:\\a\\release-dist\\Fit-File-Viewer-msi-x64-30.0.3.zip", + "-C", + "D:\\a\\_temp\\installed", + ], + }); + }); + + it("fails clearly without a native Windows archive extractor and preserves Linux tar", () => { + expect.assertions(3); + const options = { + platform: "win32", + environment: windowsSmokeEnvironment, + artifact: "fixture.zip", + destination: "installed", + }; + expect(() => getArchiveExtractionCommand(options, () => false)).toThrow( + "Native Windows archive extractor is unavailable" + ); + expect(() => + getArchiveExtractionCommand( + { ...options, environment: {} }, + () => true + ) + ).toThrow("An absolute SystemRoot is required"); + expect( + getArchiveExtractionCommand( + { ...options, platform: "linux", environment: {} }, + () => false + ).command + ).toBe("tar"); + }); + it.each([ [ "CurrentUser", @@ -107,19 +182,22 @@ describe("final distributable smoke", () => { const calls: string[] = []; const run = (command: string, args: string[]): void => { calls.push(command); - if (command === "tar") createExecutable(args[3] ?? "", "win32"); + if (command === nativeWindowsTar) + createExecutable(args[3] ?? "", "win32"); }; expect(() => runDistributableSmoke( { arch: "x64", platform: "win32", + environment: windowsSmokeEnvironment, version: "30.0.3", releaseDirectory, }, { run, smoke: () => 0, + archiveExtractorExists, inspectWindowsRegistrations: () => [ { Key: "Software\\fixture", @@ -130,7 +208,7 @@ describe("final distributable smoke", () => { } ) ).toThrow("Refusing NSIS smoke installation"); - expect(calls).toStrictEqual(["tar"]); + expect(calls).toStrictEqual([nativeWindowsTar]); }); it("preserves a partial install if registration cleanup cannot be verified", () => { @@ -142,7 +220,8 @@ describe("final distributable smoke", () => { .mockReturnValueOnce([]) .mockReturnValue([{ Key: "Software\\fixture" }]); const run = (command: string, args: string[]): void => { - if (command === "tar") createExecutable(args[3] ?? "", "win32"); + if (command === nativeWindowsTar) + createExecutable(args[3] ?? "", "win32"); if (command.includes("-nsis-")) { installation = args[2]?.slice(3) ?? ""; directories.push(path.dirname(installation)); @@ -155,10 +234,16 @@ describe("final distributable smoke", () => { { arch: "x64", platform: "win32", + environment: windowsSmokeEnvironment, version: "30.0.3", releaseDirectory, }, - { run, smoke: () => 0, inspectWindowsRegistrations } + { + run, + smoke: () => 0, + inspectWindowsRegistrations, + archiveExtractorExists, + } ) ).toThrow("cleanup failed; preserved"); expect( @@ -384,27 +469,22 @@ describe("final distributable smoke", () => { const smoke = vi.fn(() => 0); const calls: string[][] = []; const inspectWindowsRegistrations = vi.fn(() => []); - const run = (command: string, args: string[]): void => { - calls.push([command, ...args]); - if (command === "tar") createExecutable(args[3] ?? "", "win32"); - if (command.includes("-nsis-")) { - const destination = args[2]?.slice(3) ?? ""; - createExecutable(destination, "win32"); - fs.writeFileSync( - path.join(destination, "Uninstall Fit File Viewer.exe"), - "fixture uninstaller" - ); - } - }; + const run = makeWindowsArtifactRunner(calls); expect( runDistributableSmoke( { arch: "ia32", platform: "win32", + environment: windowsSmokeEnvironment, version: "30.0.3", releaseDirectory, }, - { run, smoke, inspectWindowsRegistrations } + { + run, + smoke, + inspectWindowsRegistrations, + archiveExtractorExists, + } ) ).toBe(0); expect(smoke).toHaveBeenCalledTimes(3); diff --git a/tests/unit/packaging/runMacosSmokeDiagnostics.test.ts b/tests/unit/packaging/runMacosSmokeDiagnostics.test.ts new file mode 100644 index 000000000..4a63e283e --- /dev/null +++ b/tests/unit/packaging/runMacosSmokeDiagnostics.test.ts @@ -0,0 +1,241 @@ +import { EventEmitter } from "node:events"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import process from "node:process"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + captureDiagnosticCommand, + findSmokeProcesses, + runMacosSmokeDiagnostics, + sampleHungSmokeProcesses, + selectProcessesToSample, + verifyRosetta, +} from "../../../scripts/run-macos-smoke-diagnostics.mjs"; + +type DiagnosticResult = { status: number; stdout: string; stderr: string }; +const directories: string[] = []; +const processCommand = + "/tmp/extracted/Fit File Viewer.app/Contents/MacOS/Fit File Viewer --ffv-smoke-test"; + +function createDirectory() { + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), "ffv-native-diagnostics-") + ); + directories.push(directory); + return directory; +} + +function successfulCapture() { + return vi + .fn<(...args: unknown[]) => Promise>() + .mockResolvedValue({ status: 0, stdout: "", stderr: "" }); +} + +afterEach(() => { + vi.useRealTimers(); + for (const directory of directories.splice(0)) + fs.rmSync(directory, { recursive: true, force: true }); +}); + +describe("macOS smoke diagnostics", () => { + it("selects only smoke app descendants without exposing unrelated commands", () => { + expect.assertions(1); + const listing = `40 20 ${processCommand}\n20 10 /usr/bin/arch -x86_64 executable\n80 1 ${processCommand}\n90 40 Fit File Viewer Helper\n10 1 node smoke\n100 1 secret-command --token secret`; + expect(findSmokeProcesses(listing, 10)).toStrictEqual([ + { pid: 40, parentPid: 20, command: processCommand }, + ]); + }); + + it("samples a stalled process once after twenty seconds", () => { + expect.assertions(4); + const processes = [{ pid: 40, parentPid: 10, command: processCommand }]; + const observations = new Map(); + expect( + selectProcessesToSample(processes, observations, 0) + ).toStrictEqual([]); + expect( + selectProcessesToSample(processes, observations, 19_999) + ).toStrictEqual([]); + expect( + selectProcessesToSample(processes, observations, 20_000) + ).toStrictEqual(processes); + expect( + selectProcessesToSample(processes, observations, 40_000) + ).toStrictEqual([]); + }); + + it("captures bounded native samples while preserving only the target process", async () => { + expect.assertions(3); + const directory = createDirectory(); + const capture = successfulCapture(); + capture.mockResolvedValueOnce({ + status: 0, + stdout: `40 10 ${processCommand}\n80 1 secret-command`, + stderr: "", + }); + const observations = new Map([[40, { firstSeen: 0, sampled: false }]]); + await sampleHungSmokeProcesses(10, directory, observations, { + capture, + now: () => 20_000, + }); + expect(capture).toHaveBeenLastCalledWith("/usr/bin/sample", [ + "40", + "5", + "1", + "-file", + path.join(directory, "sample-40.txt"), + ]); + expect( + fs.readFileSync(path.join(directory, "process-40.json"), "utf8") + ).not.toContain("secret-command"); + expect( + fs.existsSync(path.join(directory, "sample-40-command.txt")) + ).toBe(true); + }); + + it("bounds diagnostic commands and records command failures", async () => { + expect.assertions(2); + const runner = vi.fn().mockRejectedValue( + Object.assign(new Error("timed out"), { + stdout: "partial sample", + stderr: "timeout", + }) + ); + await expect( + captureDiagnosticCommand("/usr/bin/sample", ["40"], runner) + ).resolves.toStrictEqual({ + status: 1, + stdout: "partial sample", + stderr: "timeout", + }); + expect(runner).toHaveBeenCalledWith( + "/usr/bin/sample", + ["40"], + expect.objectContaining({ + timeout: 15_000, + maxBuffer: 4 * 1024 * 1024, + }) + ); + }); + + it("captures a real diagnostic child command without a shell", async () => { + expect.assertions(1); + await expect( + captureDiagnosticCommand(process.execPath, [ + "-e", + "process.stdout.write('diagnostic-ready')", + ]) + ).resolves.toMatchObject({ + status: 0, + stdout: "diagnostic-ready", + stderr: "", + }); + }); + + it("preserves harness spawn errors while collecting system diagnostics", async () => { + expect.assertions(2); + const directory = createDirectory(); + const child = Object.assign(new EventEmitter(), { pid: undefined }); + const running = runMacosSmokeDiagnostics( + { platform: "darwin", directory }, + { spawn: () => child, capture: successfulCapture() } + ); + queueMicrotask(() => { + child.emit("error", new Error("spawn denied")); + }); + await expect(running).rejects.toThrow("spawn denied"); + expect(fs.existsSync(path.join(directory, "rosetta-system.log"))).toBe( + true + ); + }); + + it("does not overlap inspections or keep polling after the harness exits", async () => { + expect.assertions(3); + vi.useFakeTimers(); + const directory = createDirectory(); + const child = Object.assign(new EventEmitter(), { pid: 10 }); + let finishInspection: (() => void) | undefined; + const inspection = new Promise((resolve) => { + finishInspection = resolve; + }); + const inspect = vi.fn(() => inspection); + const running = runMacosSmokeDiagnostics( + { platform: "darwin", directory }, + { spawn: () => child, capture: successfulCapture(), inspect } + ); + await vi.advanceTimersByTimeAsync(15_000); + expect(inspect).toHaveBeenCalledOnce(); + child.emit("close", 0, null); + finishInspection?.(); + await expect(running).resolves.toBe(0); + await vi.advanceTimersByTimeAsync(15_000); + expect(inspect).toHaveBeenCalledOnce(); + }); + + it("probes real Intel execution and rejects a failed Rosetta probe", async () => { + expect.assertions(3); + const directory = createDirectory(); + const capture = successfulCapture(); + await verifyRosetta(directory, capture); + expect(capture).toHaveBeenCalledWith("/usr/bin/arch", [ + "-x86_64", + "/usr/bin/true", + ]); + capture.mockResolvedValueOnce({ + status: 1, + stdout: "", + stderr: "translation unavailable", + }); + await expect(verifyRosetta(directory, capture)).rejects.toThrow( + "Rosetta execution probe failed" + ); + expect( + fs.readFileSync(path.join(directory, "rosetta-probe.log"), "utf8") + ).toContain("translation unavailable"); + }); + + it.each([ + [ + 0, + null, + 0, + ], + [ + 1, + null, + 1, + ], + [ + null, + "SIGTERM", + 1, + ], + ] as const)( + "preserves harness status %s and signal %s", + async (status, signal, expected) => { + expect.assertions(3); + vi.useFakeTimers(); + const directory = createDirectory(); + const child = Object.assign(new EventEmitter(), { pid: 10 }); + const capture = successfulCapture(); + const inspect = vi.fn().mockResolvedValue(undefined); + const running = runMacosSmokeDiagnostics( + { platform: "darwin", directory }, + { spawn: () => child, capture, inspect } + ); + await vi.advanceTimersByTimeAsync(5000); + expect(inspect).toHaveBeenCalledOnce(); + child.emit("close", status, signal); + await expect(running).resolves.toBe(expected); + expect( + fs.readFileSync( + path.join(directory, "rosetta-system.log"), + "utf8" + ) + ).toContain("status=0"); + } + ); +}); From 8844c5fa7689768230acc92315ed4f528734b273 Mon Sep 17 00:00:00 2001 From: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:41:51 -0400 Subject: [PATCH 04/12] =?UTF-8?q?=F0=9F=A7=AA=20[test]=20Verify=20existing?= =?UTF-8?q?=20Mac=20packages=20on=20macOS=2027?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿงช [test] Validate rehearsal artifact provenance and hashes before checking direct startup and LaunchServices on the macOS 27 preview runner. ๐Ÿ‘ท [build] Expose compatibility checks through the existing rehearsal without skipping release gates, and register the official preview label for actionlint. ๐Ÿšœ [refactor] Separate diagnostic option resolution from process monitoring and retain failure propagation. ๐Ÿ“ [docs] Document compatibility checks and distinguish ad hoc integrity signatures from trusted publisher signing. --- .github/actionlint.yaml | 6 + .github/workflows/Build.yml | 2 +- .../workflows/macos-compatibility-smoke.yml | 132 ++++++++++++++++++ .github/workflows/release-rehearsal.yml | 15 ++ docs/DEVELOPMENT_GUIDE.md | 7 + docusaurus/docs/development/build-release.md | 6 + scripts/run-macos-smoke-diagnostics.mjs | 29 ++-- .../macosCompatibilityWorkflow.test.ts | 113 +++++++++++++++ .../releaseRehearsalWorkflow.test.ts | 23 +++ .../workspacePackageBoundaries.test.ts | 2 +- 10 files changed, 325 insertions(+), 10 deletions(-) create mode 100644 .github/actionlint.yaml create mode 100644 .github/workflows/macos-compatibility-smoke.yml create mode 100644 tests/unit/packaging/macosCompatibilityWorkflow.test.ts diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 000000000..01688384e --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,6 @@ +# GitHub's hosted macOS 27 preview label predates actionlint's built-in catalog. +# This configuration key extends accepted labels; this is not a self-hosted runner. +# https://github.com/actions/runner-images/blob/main/images/macos/xcode-27-arm64-Readme.md +self-hosted-runner: + labels: + - xcode-27 diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index f6759d692..feac4da31 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -468,7 +468,7 @@ jobs: body: | ## ๐Ÿš€ Release Notes - ${{ inputs.require-code-signing && 'Windows and macOS release artifacts were built with required code signing.' || 'Release artifacts are intentionally unsigned, consistent with previous FitFileViewer releases.' }} + ${{ inputs.require-code-signing && 'Windows and macOS release artifacts were built with required publisher code signing.' || 'Release artifacts do not have trusted publisher signatures. macOS apps have verified ad hoc signatures for executable integrity, but are not notarized by Apple.' }} ${{ steps.release_notes.outputs.notes }} diff --git a/.github/workflows/macos-compatibility-smoke.yml b/.github/workflows/macos-compatibility-smoke.yml new file mode 100644 index 000000000..a6f0356b1 --- /dev/null +++ b/.github/workflows/macos-compatibility-smoke.yml @@ -0,0 +1,132 @@ +name: macOS Compatibility Smoke +run-name: macOS 27 Compatibility (rehearsal ${{ inputs.rehearsal-run-id }}) + +on: + workflow_call: + inputs: + rehearsal-run-id: + description: Run ID containing a successful ARM64 Release Rehearsal artifact + required: true + type: string + workflow_dispatch: + inputs: + rehearsal-run-id: + description: Run ID containing a successful ARM64 Release Rehearsal artifact + required: true + type: string + +concurrency: + group: macos-compatibility-${{ inputs.rehearsal-run-id }} + cancel-in-progress: true + +permissions: + actions: read + contents: read + +jobs: + compatibility: + name: Test existing ARM64 DMG on macOS 27 + runs-on: xcode-27 + timeout-minutes: 15 + defaults: + run: + shell: bash + steps: + - name: Harden the runner (Audit all outbound calls) + uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4 + with: + egress-policy: audit + + - name: Validate rehearsal artifact provenance + id: source + env: + GH_TOKEN: ${{ github.token }} + REHEARSAL_RUN_ID: ${{ inputs.rehearsal-run-id }} + run: | + [[ "$REHEARSAL_RUN_ID" =~ ^[1-9][0-9]*$ ]] || { echo "Invalid rehearsal run ID" >&2; exit 1; } + evidence="$RUNNER_TEMP/ffv-macos-compatibility" + mkdir -p "$evidence" + gh api "repos/$GITHUB_REPOSITORY/actions/runs/$REHEARSAL_RUN_ID" > "$evidence/source-run.json" + jq -e --arg repo "$GITHUB_REPOSITORY" ' + .path == ".github/workflows/release-rehearsal.yml" and + .event == "workflow_dispatch" and + .repository.full_name == $repo and + .head_repository.full_name == $repo and + (.head_sha | test("^[0-9a-f]{40}$")) + ' "$evidence/source-run.json" > /dev/null + sha=$(jq -r '.head_sha' "$evidence/source-run.json") + gh api --paginate --slurp "repos/$GITHUB_REPOSITORY/actions/runs/$REHEARSAL_RUN_ID/jobs?per_page=100" > "$evidence/source-jobs.json" + jq -e 'any(.[].jobs[]; + .name == "Verify Unsigned Release Package (macos-15, arm64)" and + .conclusion == "success" + )' "$evidence/source-jobs.json" > /dev/null + gh api --paginate --slurp "repos/$GITHUB_REPOSITORY/actions/runs/$REHEARSAL_RUN_ID/artifacts?per_page=100" > "$evidence/source-artifacts.json" + jq -e --arg sha "$sha" --argjson run "$REHEARSAL_RUN_ID" ' + [.[].artifacts[] | select(.name == "release-rehearsal-macos-15-arm64")] | + if length != 1 then error("Expected one ARM64 rehearsal artifact") else .[0] end | + select(.expired == false and .workflow_run.id == $run and .workflow_run.head_sha == $sha) + ' "$evidence/source-artifacts.json" > "$evidence/source-artifact.json" + artifact_id=$(jq -r '.id' "$evidence/source-artifact.json") + [[ "$artifact_id" =~ ^[1-9][0-9]*$ ]] + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "artifact-id=$artifact_id" >> "$GITHUB_OUTPUT" + sw_vers > "$evidence/os-version.txt" + uname -a >> "$evidence/os-version.txt" + printf 'ImageOS=%s\nImageVersion=%s\n' "$ImageOS" "$ImageVersion" >> "$evidence/os-version.txt" + + - name: Checkout exact artifact source + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + ref: ${{ steps.source.outputs.sha }} + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version-file: .node-version + + - name: Download verified ARM64 rehearsal artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ steps.source.outputs.artifact-id }} + run-id: ${{ inputs.rehearsal-run-id }} + repository: ${{ github.repository }} + github-token: ${{ github.token }} + path: release-dist + merge-multiple: true + digest-mismatch: error + + - name: Verify DMG matches original successful smoke + run: | + evidence="$RUNNER_TEMP/ffv-macos-compatibility" + cp release-dist/distributable-smoke-darwin-arm64.json "$evidence/source-smoke-report.json" + rm release-dist/distributable-smoke-darwin-arm64.json + version=$(node -p 'require("./package.json").version') + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] + artifact="Fit-File-Viewer-dmg-arm64-$version.dmg" + expected=$(jq -er --arg artifact "$artifact" ' + .artifacts[] | select(.artifact == $artifact and .passed == true and + .signatureVerified == true and .launchServicesVerified == true) | .sha256 + ' "$evidence/source-smoke-report.json") + [[ "$expected" =~ ^[0-9a-f]{64}$ ]] + actual=$(shasum -a 256 "release-dist/$artifact" | cut -d ' ' -f 1) + [[ "$actual" == "$expected" ]] || { echo "DMG differs from original tested artifact" >&2; exit 1; } + printf '%s %s\n' "$actual" "$artifact" > "$evidence/dmg-sha256.txt" + + - name: Smoke test copied DMG through direct launch and LaunchServices + run: node scripts/run-distributable-smoke.mjs + env: + MATRIX_ARCH: arm64 + FFV_PACKAGED_SMOKE_TIMEOUT_MS: "60000" + + - name: Preserve macOS compatibility evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: macos-27-compatibility-${{ inputs.rehearsal-run-id }} + path: | + ${{ runner.temp }}/ffv-macos-compatibility/** + release-dist/distributable-smoke-darwin-arm64.json + release-dist/smoke-diagnostics/** + retention-days: 14 + if-no-files-found: error diff --git a/.github/workflows/release-rehearsal.yml b/.github/workflows/release-rehearsal.yml index 09640ab28..5595028f7 100644 --- a/.github/workflows/release-rehearsal.yml +++ b/.github/workflows/release-rehearsal.yml @@ -8,6 +8,11 @@ concurrency: on: workflow_dispatch: inputs: + compatibility-rehearsal-run-id: + description: Optional completed ARM64 rehearsal source for macOS 27 compatibility testing + required: false + default: "" + type: string require-code-signing: description: "Fail if the configured signing environment is incomplete" required: true @@ -34,6 +39,16 @@ permissions: contents: read jobs: + macos-compatibility: + name: Verify existing ARM64 package on macOS 27 + if: inputs.compatibility-rehearsal-run-id != '' + permissions: + actions: read + contents: read + uses: ./.github/workflows/macos-compatibility-smoke.yml + with: + rehearsal-run-id: ${{ inputs.compatibility-rehearsal-run-id }} + release-verification: name: Verify Complete Release Gate runs-on: ubuntu-latest diff --git a/docs/DEVELOPMENT_GUIDE.md b/docs/DEVELOPMENT_GUIDE.md index 97f706c14..74bcc5d80 100644 --- a/docs/DEVELOPMENT_GUIDE.md +++ b/docs/DEVELOPMENT_GUIDE.md @@ -512,6 +512,13 @@ the resulting distributions into fresh temporary directories and launch those copies. macOS DMG copies are signature-verified before launch, and Universal checks exercise both architectures. +For an additional macOS 27 compatibility check, set the rehearsal's +`compatibility-rehearsal-run-id` input to a prior run with a successful ARM64 +artifact. The compatibility job checks the artifact's provenance and original +DMG hash, then tests that same DMG on GitHub's `xcode-27` preview runner through +direct launch and LaunchServices. It records the exact OS version and fresh +smoke evidence. The complete release gate and normal platform matrix still run. + The rehearsal packaging step sets `FFV_FORCE_UNSIGNED_PACKAGE=true` and `CSC_IDENTITY_AUTO_DISCOVERY=false`, so it strips signing variables before electron-builder starts. Keep this separate from signed release packaging; use diff --git a/docusaurus/docs/development/build-release.md b/docusaurus/docs/development/build-release.md index 50ae2b20c..e1bff3f3e 100644 --- a/docusaurus/docs/development/build-release.md +++ b/docusaurus/docs/development/build-release.md @@ -128,6 +128,12 @@ The packaged smoke test requires a fresh completion report after renderer initialization, preload IPC, real FIT decoding, and visible map rendering. Crashes, signals, timeouts, and missing or stale reports fail the test. +For macOS 27 compatibility, set `compatibility-rehearsal-run-id` on **Release +Rehearsal** to a prior run containing a successful ARM64 artifact. An additional +job verifies the original DMG hash and tests that same artifact through direct +launch and LaunchServices on GitHub's `xcode-27` preview runner. The normal +release gate and platform matrix remain required. + ### 2. Publish Dispatch **Build and Release Electron App** with the target `branch` and diff --git a/scripts/run-macos-smoke-diagnostics.mjs b/scripts/run-macos-smoke-diagnostics.mjs index c377ac716..49dc3b95a 100644 --- a/scripts/run-macos-smoke-diagnostics.mjs +++ b/scripts/run-macos-smoke-diagnostics.mjs @@ -168,10 +168,7 @@ export async function sampleHungSmokeProcesses( } } -export async function runMacosSmokeDiagnostics( - options = {}, - dependencies = {} -) { +function resolveDiagnosticOptions(options) { const platform = options.platform ?? process.platform; if (platform !== "darwin") throw new Error("macOS smoke diagnostics require macOS"); @@ -182,22 +179,38 @@ export async function runMacosSmokeDiagnostics( "smoke-diagnostics", "native-processes" ); + return { directory, environment: options.environment ?? process.env }; +} + +function resolveDiagnosticDependencies(dependencies) { + return { + spawnHarness: dependencies.spawn ?? spawn, + capture: dependencies.capture ?? captureDiagnosticCommand, + inspect: dependencies.inspect ?? sampleHungSmokeProcesses, + }; +} + +export async function runMacosSmokeDiagnostics( + options = {}, + dependencies = {} +) { + const { directory, environment } = resolveDiagnosticOptions(options); + const { spawnHarness, capture, inspect } = + resolveDiagnosticDependencies(dependencies); fs.mkdirSync(directory, { recursive: true }); - const spawnHarness = dependencies.spawn ?? spawn; - const capture = dependencies.capture ?? captureDiagnosticCommand; const child = spawnHarness( process.execPath, [path.join(repositoryRoot, "scripts/run-distributable-smoke.mjs")], { cwd: repositoryRoot, - env: options.environment ?? process.env, + env: environment, stdio: "inherit", timeout: 15 * 60 * 1000, } ); const stopMonitor = startSmokeProcessMonitor(child, directory, { capture, - inspect: dependencies.inspect ?? sampleHungSmokeProcesses, + inspect, }); try { const [status, signal] = await once(child, "close"); diff --git a/tests/unit/packaging/macosCompatibilityWorkflow.test.ts b/tests/unit/packaging/macosCompatibilityWorkflow.test.ts new file mode 100644 index 000000000..943bb980a --- /dev/null +++ b/tests/unit/packaging/macosCompatibilityWorkflow.test.ts @@ -0,0 +1,113 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; +import { parse as parseYaml } from "yaml"; + +type WorkflowStep = { + env?: Record; + if?: string; + name: string; + run?: string; + uses?: string; + with?: Record; +}; + +const workflow = parseYaml( + readFileSync( + path.join( + process.cwd(), + ".github/workflows/macos-compatibility-smoke.yml" + ), + "utf8" + ) +) as { + jobs: { + compatibility: { + "runs-on": string; + steps: WorkflowStep[]; + }; + }; + on: Record; + permissions: Record; +}; + +const { compatibility } = workflow.jobs; + +describe("macOS compatibility workflow", () => { + it("validates same-repository rehearsal provenance before checking out its source", () => { + expect.assertions(11); + const provenanceIndex = compatibility.steps.findIndex( + (step) => step.name === "Validate rehearsal artifact provenance" + ); + const provenance = compatibility.steps[provenanceIndex]; + const checkoutIndex = compatibility.steps.findIndex((step) => + step.uses?.startsWith("actions/checkout@") + ); + const checkout = compatibility.steps[checkoutIndex]; + expect(Object.keys(workflow.on)).toEqual([ + "workflow_call", + "workflow_dispatch", + ]); + expect(workflow.permissions).toEqual({ + actions: "read", + contents: "read", + }); + expect(provenance?.run).toContain("^[1-9][0-9]*$"); + expect(provenance?.run).toContain( + '.path == ".github/workflows/release-rehearsal.yml"' + ); + expect(provenance?.run).toContain('.event == "workflow_dispatch"'); + expect(provenance?.run).toContain( + ".head_repository.full_name == $repo" + ); + expect(provenance?.run).toContain('.conclusion == "success"'); + expect(provenance?.run).toContain( + ".workflow_run.id == $run and .workflow_run.head_sha == $sha" + ); + expect(checkout?.with?.ref).toBe("${{ steps.source.outputs.sha }}"); + expect(checkout?.with?.["persist-credentials"]).toBe(false); + expect(provenanceIndex).toBeLessThan(checkoutIndex); + }); + + it("downloads the immutable artifact and checks the original tested DMG hash", () => { + expect.assertions(5); + const download = compatibility.steps.find((step) => + step.uses?.startsWith("actions/download-artifact@") + ); + const verify = compatibility.steps.find((step) => + step.name.startsWith("Verify DMG") + ); + expect(download?.with?.["artifact-ids"]).toBe( + "${{ steps.source.outputs.artifact-id }}" + ); + expect(download?.with?.["digest-mismatch"]).toBe("error"); + expect(verify?.run).toContain(".signatureVerified == true"); + expect(verify?.run).toContain(".launchServicesVerified == true"); + expect(verify?.run).toContain('[[ "$actual" == "$expected" ]]'); + }); + + it("tests existing DMG on macOS 27 and preserves evidence without building or publishing", () => { + expect.assertions(7); + const commands = compatibility.steps + .map((step) => step.run ?? "") + .join("\n"); + const smoke = compatibility.steps.find((step) => + step.run?.includes("node scripts/run-distributable-smoke.mjs") + ); + const upload = compatibility.steps.find((step) => + step.uses?.startsWith("actions/upload-artifact@") + ); + expect(compatibility["runs-on"]).toBe("xcode-27"); + expect(smoke?.env?.MATRIX_ARCH).toBe("arm64"); + expect(commands).not.toMatch(/npm (?:ci|install|run build)|--publish/u); + expect(commands).toContain("sw_vers"); + expect(upload?.if).toBe("always()"); + expect(upload?.with?.path).toContain( + "release-dist/smoke-diagnostics/**" + ); + expect(upload?.with?.path).toContain( + "${{ runner.temp }}/ffv-macos-compatibility/**" + ); + }); +}); diff --git a/tests/unit/packaging/releaseRehearsalWorkflow.test.ts b/tests/unit/packaging/releaseRehearsalWorkflow.test.ts index 7e085634a..def9b6f77 100644 --- a/tests/unit/packaging/releaseRehearsalWorkflow.test.ts +++ b/tests/unit/packaging/releaseRehearsalWorkflow.test.ts @@ -16,6 +16,29 @@ function readReleaseRehearsalWorkflow(): string { } describe("release rehearsal workflow", () => { + it("adds optional macOS compatibility without bypassing the release gates", () => { + expect.assertions(6); + const { jobs } = parseYaml(readReleaseRehearsalWorkflow()) as { + jobs: Record>; + }; + const compatibility = jobs["macos-compatibility"]; + expect(compatibility?.if).toBe( + "inputs.compatibility-rehearsal-run-id != ''" + ); + expect(compatibility?.uses).toBe( + "./.github/workflows/macos-compatibility-smoke.yml" + ); + expect(compatibility?.with).toEqual({ + "rehearsal-run-id": "${{ inputs.compatibility-rehearsal-run-id }}", + }); + expect(compatibility?.permissions).toEqual({ + actions: "read", + contents: "read", + }); + expect(jobs["release-verification"]).not.toHaveProperty("if"); + expect(jobs["release-rehearsal"]).not.toHaveProperty("if"); + }); + it("requires the complete gate independently of all six native artifact jobs", () => { expect.assertions(9); type RehearsalJob = { diff --git a/tests/unit/packaging/workspacePackageBoundaries.test.ts b/tests/unit/packaging/workspacePackageBoundaries.test.ts index 689d20ad2..897cfba9e 100644 --- a/tests/unit/packaging/workspacePackageBoundaries.test.ts +++ b/tests/unit/packaging/workspacePackageBoundaries.test.ts @@ -574,7 +574,7 @@ describe("workspace package boundaries", () => { ); expect(releaseWorkflow).toContain("npm run test:packaged"); expect(releaseWorkflow).toContain( - "Release artifacts are intentionally unsigned" + "macOS apps have verified ad hoc signatures for executable integrity, but are not notarized by Apple." ); expect(releaseVersioningFilesWithWorkspaceFlags).toStrictEqual([]); }); From eda089cf1a9c24ddd16b4c079b2dc32a5f309646 Mon Sep 17 00:00:00 2001 From: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:48:13 -0400 Subject: [PATCH 05/12] =?UTF-8?q?=F0=9F=91=B7=20[build]=20Test=20macOS=20c?= =?UTF-8?q?ompatibility=20against=20each=20rehearsal=20artifact?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/macos-compatibility-smoke.yml | 6 ------ .github/workflows/release-rehearsal.yml | 10 +++------- docs/DEVELOPMENT_GUIDE.md | 11 +++++------ docusaurus/docs/development/build-release.md | 10 +++++----- .../unit/packaging/macosCompatibilityWorkflow.test.ts | 5 +---- tests/unit/packaging/releaseRehearsalWorkflow.test.ts | 11 +++++------ 6 files changed, 19 insertions(+), 34 deletions(-) diff --git a/.github/workflows/macos-compatibility-smoke.yml b/.github/workflows/macos-compatibility-smoke.yml index a6f0356b1..44930313e 100644 --- a/.github/workflows/macos-compatibility-smoke.yml +++ b/.github/workflows/macos-compatibility-smoke.yml @@ -8,12 +8,6 @@ on: description: Run ID containing a successful ARM64 Release Rehearsal artifact required: true type: string - workflow_dispatch: - inputs: - rehearsal-run-id: - description: Run ID containing a successful ARM64 Release Rehearsal artifact - required: true - type: string concurrency: group: macos-compatibility-${{ inputs.rehearsal-run-id }} diff --git a/.github/workflows/release-rehearsal.yml b/.github/workflows/release-rehearsal.yml index 5595028f7..183c794b9 100644 --- a/.github/workflows/release-rehearsal.yml +++ b/.github/workflows/release-rehearsal.yml @@ -8,11 +8,6 @@ concurrency: on: workflow_dispatch: inputs: - compatibility-rehearsal-run-id: - description: Optional completed ARM64 rehearsal source for macOS 27 compatibility testing - required: false - default: "" - type: string require-code-signing: description: "Fail if the configured signing environment is incomplete" required: true @@ -41,13 +36,14 @@ permissions: jobs: macos-compatibility: name: Verify existing ARM64 package on macOS 27 - if: inputs.compatibility-rehearsal-run-id != '' + needs: release-rehearsal + if: always() && !cancelled() permissions: actions: read contents: read uses: ./.github/workflows/macos-compatibility-smoke.yml with: - rehearsal-run-id: ${{ inputs.compatibility-rehearsal-run-id }} + rehearsal-run-id: ${{ github.run_id }} release-verification: name: Verify Complete Release Gate diff --git a/docs/DEVELOPMENT_GUIDE.md b/docs/DEVELOPMENT_GUIDE.md index 74bcc5d80..26bf83e23 100644 --- a/docs/DEVELOPMENT_GUIDE.md +++ b/docs/DEVELOPMENT_GUIDE.md @@ -512,12 +512,11 @@ the resulting distributions into fresh temporary directories and launch those copies. macOS DMG copies are signature-verified before launch, and Universal checks exercise both architectures. -For an additional macOS 27 compatibility check, set the rehearsal's -`compatibility-rehearsal-run-id` input to a prior run with a successful ARM64 -artifact. The compatibility job checks the artifact's provenance and original -DMG hash, then tests that same DMG on GitHub's `xcode-27` preview runner through -direct launch and LaunchServices. It records the exact OS version and fresh -smoke evidence. The complete release gate and normal platform matrix still run. +After the platform matrix finishes, an additional macOS 27 compatibility job +checks the rehearsal's successful ARM64 artifact provenance and original DMG +hash. It tests that same DMG on GitHub's `xcode-27` preview runner through direct +launch and LaunchServices, recording the exact OS version and fresh smoke +evidence. The complete release gate and normal platform matrix remain required. The rehearsal packaging step sets `FFV_FORCE_UNSIGNED_PACKAGE=true` and `CSC_IDENTITY_AUTO_DISCOVERY=false`, so it strips signing variables before diff --git a/docusaurus/docs/development/build-release.md b/docusaurus/docs/development/build-release.md index e1bff3f3e..79691ebed 100644 --- a/docusaurus/docs/development/build-release.md +++ b/docusaurus/docs/development/build-release.md @@ -128,11 +128,11 @@ The packaged smoke test requires a fresh completion report after renderer initialization, preload IPC, real FIT decoding, and visible map rendering. Crashes, signals, timeouts, and missing or stale reports fail the test. -For macOS 27 compatibility, set `compatibility-rehearsal-run-id` on **Release -Rehearsal** to a prior run containing a successful ARM64 artifact. An additional -job verifies the original DMG hash and tests that same artifact through direct -launch and LaunchServices on GitHub's `xcode-27` preview runner. The normal -release gate and platform matrix remain required. +After the platform matrix finishes, **Release Rehearsal** automatically checks +macOS 27 compatibility. It verifies the successful ARM64 artifact's provenance +and original DMG hash, then tests that same artifact through direct launch and +LaunchServices on GitHub's `xcode-27` preview runner. The normal release gate and +platform matrix remain required. ### 2. Publish diff --git a/tests/unit/packaging/macosCompatibilityWorkflow.test.ts b/tests/unit/packaging/macosCompatibilityWorkflow.test.ts index 943bb980a..c86afe430 100644 --- a/tests/unit/packaging/macosCompatibilityWorkflow.test.ts +++ b/tests/unit/packaging/macosCompatibilityWorkflow.test.ts @@ -45,10 +45,7 @@ describe("macOS compatibility workflow", () => { step.uses?.startsWith("actions/checkout@") ); const checkout = compatibility.steps[checkoutIndex]; - expect(Object.keys(workflow.on)).toEqual([ - "workflow_call", - "workflow_dispatch", - ]); + expect(Object.keys(workflow.on)).toEqual(["workflow_call"]); expect(workflow.permissions).toEqual({ actions: "read", contents: "read", diff --git a/tests/unit/packaging/releaseRehearsalWorkflow.test.ts b/tests/unit/packaging/releaseRehearsalWorkflow.test.ts index def9b6f77..97e1fa7d5 100644 --- a/tests/unit/packaging/releaseRehearsalWorkflow.test.ts +++ b/tests/unit/packaging/releaseRehearsalWorkflow.test.ts @@ -16,20 +16,19 @@ function readReleaseRehearsalWorkflow(): string { } describe("release rehearsal workflow", () => { - it("adds optional macOS compatibility without bypassing the release gates", () => { - expect.assertions(6); + it("tests its own ARM64 artifact after packaging without bypassing the release gates", () => { + expect.assertions(7); const { jobs } = parseYaml(readReleaseRehearsalWorkflow()) as { jobs: Record>; }; const compatibility = jobs["macos-compatibility"]; - expect(compatibility?.if).toBe( - "inputs.compatibility-rehearsal-run-id != ''" - ); + expect(compatibility?.needs).toBe("release-rehearsal"); + expect(compatibility?.if).toBe("always() && !cancelled()"); expect(compatibility?.uses).toBe( "./.github/workflows/macos-compatibility-smoke.yml" ); expect(compatibility?.with).toEqual({ - "rehearsal-run-id": "${{ inputs.compatibility-rehearsal-run-id }}", + "rehearsal-run-id": "${{ github.run_id }}", }); expect(compatibility?.permissions).toEqual({ actions: "read", From cfc03d807b69ca453aadd5797b5902ec1840f492 Mon Sep 17 00:00:00 2001 From: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com> Date: Wed, 7 Oct 2026 21:23:11 -0400 Subject: [PATCH 06/12] =?UTF-8?q?=F0=9F=A7=AA=20[test]=20Require=20native?= =?UTF-8?q?=20verification=20of=20both=20Universal=20DMG=20slices?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿงช [test] Verify the same ARM64-tested Universal DMG on a native Intel runner using its exact source, version, workflow run, attempt, and SHA-256. Require successful Intel verification before release publication. ๐Ÿงช [test] Default Universal smoke to the native host architecture and retain explicit Rosetta diagnostics. Preserve strict all-architecture signatures, fresh direct and LaunchServices readiness evidence, and the normal startup timeout. ๐Ÿ“ [docs] Document native release coverage and the observed hosted-runner Rosetta translation limitation. --- .github/workflows/Build.yml | 49 +++- .github/workflows/release-rehearsal.yml | 42 ++- .../verify-universal-native-intel.yml | 92 +++++++ docs/DEVELOPMENT_GUIDE.md | 14 +- docusaurus/docs/development/build-release.md | 3 +- scripts/run-distributable-smoke.mjs | 67 ++++- scripts/run-macos-smoke-diagnostics.mjs | 9 +- scripts/verify-universal-native-source.mjs | 151 +++++++++++ .../packaging/runDistributableSmoke.test.ts | 243 ++++++++++++++---- .../runMacosSmokeDiagnostics.test.ts | 25 ++ .../packaging/universalNativeWorkflow.test.ts | 179 +++++++++++++ .../verifyUniversalNativeSource.test.ts | 236 +++++++++++++++++ 12 files changed, 1030 insertions(+), 80 deletions(-) create mode 100644 .github/workflows/verify-universal-native-intel.yml create mode 100644 scripts/verify-universal-native-source.mjs create mode 100644 tests/unit/packaging/universalNativeWorkflow.test.ts create mode 100644 tests/unit/packaging/verifyUniversalNativeSource.test.ts diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index feac4da31..95f530c50 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -300,20 +300,11 @@ jobs: FFV_PACKAGED_SMOKE_TIMEOUT_MS: "60000" RUNNER_OS: ${{ runner.os }} - - name: Enable Intel slice testing on Apple Silicon - if: runner.os == 'macOS' && matrix.arch == 'universal' - shell: bash - run: | - softwareupdate --install-rosetta --agree-to-license - node scripts/run-macos-smoke-diagnostics.mjs --probe-rosetta - - name: Smoke test installed distributable artifacts shell: bash run: | if [ "$RUNNER_OS" = "Linux" ]; then xvfb-run -a node scripts/run-distributable-smoke.mjs - elif [ "$RUNNER_OS" = "macOS" ] && [ "$MATRIX_ARCH" = "universal" ]; then - node scripts/run-macos-smoke-diagnostics.mjs else node scripts/run-distributable-smoke.mjs fi @@ -323,6 +314,30 @@ jobs: MATRIX_ARCH: ${{ matrix.arch }} RUNNER_OS: ${{ runner.os }} + - name: Record Universal native verification source + if: runner.os == 'macOS' && matrix.arch == 'universal' + shell: bash + env: + SOURCE_SHA: ${{ needs.bump-version.outputs.bump_sha }} + run: | + test "$(git rev-parse HEAD)" = "$SOURCE_SHA" + version=$(node -p 'require("./package.json").version') + jq -n --arg sha "$SOURCE_SHA" --arg version "$version" --arg run "$GITHUB_RUN_ID" --arg attempt "$GITHUB_RUN_ATTEMPT" \ + '{sourceSha: $sha, version: $version, runId: $run, runAttempt: $attempt}' > release-dist/universal-native-source.json + + - name: Upload Universal DMG for required native Intel verification + if: runner.os == 'macOS' && matrix.arch == 'universal' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: universal-native-verification-${{ github.run_attempt }} + path: | + release-dist/Fit-File-Viewer-dmg-universal-*.dmg + release-dist/distributable-smoke-darwin-universal.json + release-dist/signing-verification-report.json + release-dist/universal-native-source.json + retention-days: 7 + if-no-files-found: error + - name: Upload distributable smoke diagnostics if: always() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -376,10 +391,22 @@ jobs: PACKAGED_SMOKE_OUTCOME: ${{ steps.smoke_packaged_app.outcome }} SIGNING_VERIFICATION_OUTCOME: ${{ steps.verify_signed_artifacts.outcome }} + verify-universal-intel: + name: Verify Universal DMG on native Intel + needs: [build, bump-version] + if: always() && !cancelled() && needs.bump-version.result == 'success' + permissions: + actions: read + contents: read + uses: ./.github/workflows/verify-universal-native-intel.yml + with: + source-sha: ${{ needs.bump-version.outputs.bump_sha }} + expected-version: ${{ needs.bump-version.outputs.new_version }} + release: name: Create Release - needs: [build, bump-version] - if: ${{ needs.build.result == 'success' && needs.bump-version.result == 'success' }} + needs: [build, bump-version, verify-universal-intel] + if: ${{ needs.build.result == 'success' && needs.bump-version.result == 'success' && needs.verify-universal-intel.result == 'success' }} runs-on: ubuntu-latest timeout-minutes: 45 defaults: diff --git a/.github/workflows/release-rehearsal.yml b/.github/workflows/release-rehearsal.yml index 183c794b9..a8b2c2699 100644 --- a/.github/workflows/release-rehearsal.yml +++ b/.github/workflows/release-rehearsal.yml @@ -34,6 +34,17 @@ permissions: contents: read jobs: + verify-universal-intel: + name: Verify Universal DMG on native Intel + needs: release-rehearsal + if: always() && !cancelled() + permissions: + actions: read + contents: read + uses: ./.github/workflows/verify-universal-native-intel.yml + with: + source-sha: ${{ github.sha }} + macos-compatibility: name: Verify existing ARM64 package on macOS 27 needs: release-rehearsal @@ -216,18 +227,10 @@ jobs: REQUIRE_CODE_SIGNING: "false" RUNNER_OS: ${{ matrix.runner-os }} - - name: Enable Intel slice testing on Apple Silicon - if: runner.os == 'macOS' && matrix.arch == 'universal' - run: | - softwareupdate --install-rosetta --agree-to-license - node scripts/run-macos-smoke-diagnostics.mjs --probe-rosetta - - name: Smoke test installed distributable artifacts run: | if [ "$RUNNER_OS" = "Linux" ]; then xvfb-run -a node scripts/run-distributable-smoke.mjs - elif [ "$RUNNER_OS" = "macOS" ] && [ "$MATRIX_ARCH" = "universal" ]; then - node scripts/run-macos-smoke-diagnostics.mjs else node scripts/run-distributable-smoke.mjs fi @@ -236,6 +239,29 @@ jobs: MATRIX_ARCH: ${{ matrix.arch }} RUNNER_OS: ${{ matrix.runner-os }} + - name: Record Universal native verification source + if: runner.os == 'macOS' && matrix.arch == 'universal' + env: + SOURCE_SHA: ${{ github.sha }} + run: | + test "$(git rev-parse HEAD)" = "$SOURCE_SHA" + version=$(node -p 'require("./package.json").version') + jq -n --arg sha "$SOURCE_SHA" --arg version "$version" --arg run "$GITHUB_RUN_ID" --arg attempt "$GITHUB_RUN_ATTEMPT" \ + '{sourceSha: $sha, version: $version, runId: $run, runAttempt: $attempt}' > release-dist/universal-native-source.json + + - name: Upload Universal DMG for required native Intel verification + if: runner.os == 'macOS' && matrix.arch == 'universal' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: universal-native-verification-${{ github.run_attempt }} + path: | + release-dist/Fit-File-Viewer-dmg-universal-*.dmg + release-dist/distributable-smoke-darwin-universal.json + release-dist/signing-verification-report.json + release-dist/universal-native-source.json + retention-days: 7 + if-no-files-found: error + - name: Upload distributable smoke diagnostics if: always() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 diff --git a/.github/workflows/verify-universal-native-intel.yml b/.github/workflows/verify-universal-native-intel.yml new file mode 100644 index 000000000..294da8ce8 --- /dev/null +++ b/.github/workflows/verify-universal-native-intel.yml @@ -0,0 +1,92 @@ +name: Verify Universal DMG on Native Intel + +on: + workflow_call: + inputs: + source-sha: + description: Exact source commit that produced the Universal DMG + required: true + type: string + expected-version: + description: Release version when supplied by the version bump job + required: false + default: "" + type: string + +permissions: + actions: read + contents: read + +jobs: + native-intel: + name: Verify the ARM64-tested Universal DMG on native Intel + runs-on: macos-15-intel + timeout-minutes: 15 + defaults: + run: + shell: bash + steps: + - name: Harden the runner (Audit all outbound calls) + uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4 + with: + egress-policy: audit + + - name: Validate exact source revision + env: + SOURCE_SHA: ${{ inputs.source-sha }} + run: | + [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "Invalid Universal source SHA" >&2; exit 1; } + + - name: Checkout exact Universal artifact source + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + ref: ${{ inputs.source-sha }} + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version-file: .node-version + + - name: Download this run's ARM64-tested Universal DMG + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: universal-native-verification-${{ github.run_attempt }} + run-id: ${{ github.run_id }} + repository: ${{ github.repository }} + github-token: ${{ github.token }} + path: source-artifact + digest-mismatch: error + + - name: Verify source revision, version, ARM64 smoke and DMG hash + env: + SOURCE_SHA: ${{ inputs.source-sha }} + EXPECTED_VERSION: ${{ inputs.expected-version }} + run: | + test "$(git rev-parse HEAD)" = "$SOURCE_SHA" + test "$(node -p 'process.arch')" = x64 + node scripts/verify-universal-native-source.mjs > source-artifact/native-source-verification.json + mkdir -p release-dist + version=$(node -p 'require("./package.json").version') + mv "source-artifact/Fit-File-Viewer-dmg-universal-$version.dmg" release-dist/ + sw_vers > source-artifact/intel-os-version.txt + uname -a >> source-artifact/intel-os-version.txt + + - name: Verify signatures and smoke native x64 direct launch and LaunchServices + run: node scripts/run-distributable-smoke.mjs + env: + MATRIX_ARCH: universal + FFV_PACKAGED_SMOKE_TIMEOUT_MS: "60000" + + - name: Preserve native Universal verification evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: universal-native-intel-evidence-${{ github.run_attempt }} + path: | + source-artifact/*.json + source-artifact/intel-os-version.txt + release-dist/distributable-smoke-darwin-universal.json + release-dist/smoke-diagnostics/** + retention-days: 14 + if-no-files-found: error diff --git a/docs/DEVELOPMENT_GUIDE.md b/docs/DEVELOPMENT_GUIDE.md index 26bf83e23..eb08d35c8 100644 --- a/docs/DEVELOPMENT_GUIDE.md +++ b/docs/DEVELOPMENT_GUIDE.md @@ -509,8 +509,10 @@ Rehearsal** from the target branch or tag. It runs the full release gate and builds the distribution matrix without publishing: Linux x64, Windows x64 and ia32, and macOS ARM64, Intel, and Universal. Artifact checks install or extract the resulting distributions into fresh temporary directories and launch those -copies. macOS DMG copies are signature-verified before launch, and Universal -checks exercise both architectures. +copies. macOS DMG copies are signature-verified before launch. The Universal +DMG must pass on native ARM64 and native Intel runners; the Intel job verifies +the hash of the exact DMG already tested on ARM64 before testing its x64 slice. +Both native results are required before publication. After the platform matrix finishes, an additional macOS 27 compatibility job checks the rehearsal's successful ARM64 artifact provenance and original DMG @@ -518,6 +520,14 @@ hash. It tests that same DMG on GitHub's `xcode-27` preview runner through direc launch and LaunchServices, recording the exact OS version and fresh smoke evidence. The complete release gate and normal platform matrix remain required. +Rosetta cold translation on hosted ARM runners can dominate startup: even an +unchanged upstream Electron binary exceeded the normal 60-second process +budget. Native startup remains limited to 60 seconds. To investigate translation +separately on an Apple Silicon Mac, install Rosetta, set `MATRIX_ARCH=universal`, +and run `node scripts/run-macos-smoke-diagnostics.mjs --include-rosetta`. This +explicit diagnostic exercises both slices and retains process samples; a timeout +still fails and is never counted as a successful app startup. + The rehearsal packaging step sets `FFV_FORCE_UNSIGNED_PACKAGE=true` and `CSC_IDENTITY_AUTO_DISCOVERY=false`, so it strips signing variables before electron-builder starts. Keep this separate from signed release packaging; use diff --git a/docusaurus/docs/development/build-release.md b/docusaurus/docs/development/build-release.md index 79691ebed..c001a930e 100644 --- a/docusaurus/docs/development/build-release.md +++ b/docusaurus/docs/development/build-release.md @@ -111,7 +111,8 @@ ia32, and macOS ARM64, Intel, and Universal. The production workflow is Each platform verifies its build output and exercises the distributable: macOS mounts the DMG, copies the app to a fresh location, verifies every architecture's signature, and launches through both the executable and -LaunchServices. Universal builds exercise ARM64 and x64. Windows checks its +LaunchServices. The same Universal DMG must pass on native ARM64 and native Intel +runners, with its hash verified before testing the x64 slice. Windows checks its ZIP, NSIS installer, and portable executable; Linux checks its tarball and extracted AppImage. Reports, screenshots, logs, and artifact hashes are saved as workflow diagnostics. diff --git a/scripts/run-distributable-smoke.mjs b/scripts/run-distributable-smoke.mjs index 75799b354..bd67c41a7 100644 --- a/scripts/run-distributable-smoke.mjs +++ b/scripts/run-distributable-smoke.mjs @@ -138,10 +138,61 @@ export function assertNoWindowsInstallRegistrations( } } +export function parseDistributableSmokeArguments(args) { + if ( + args.length > 1 || + (args.length === 1 && args[0] !== "--include-rosetta") + ) { + throw new Error( + "Usage: node scripts/run-distributable-smoke.mjs [--include-rosetta]" + ); + } + return { includeRosetta: args.length === 1 }; +} + +function assertValidRosettaRequest({ + platform, + arch, + hostArch, + includeRosetta, +}) { + if (typeof includeRosetta !== "boolean") { + throw new TypeError("includeRosetta must be a boolean"); + } + if ( + includeRosetta && + (platform !== "darwin" || arch !== "universal" || hostArch !== "arm64") + ) { + throw new Error( + "--include-rosetta requires a Universal macOS artifact and an ARM64 host" + ); + } +} + +export function getSmokeArchitectures(options) { + assertValidRosettaRequest(options); + const { platform, arch, hostArch, includeRosetta } = options; + if (platform !== "darwin") return [arch]; + if (!["arm64", "x64"].includes(hostArch)) { + throw new Error(`Unsupported macOS host architecture: ${hostArch}`); + } + if (arch === "universal") { + return includeRosetta ? ["arm64", "x64"] : [hostArch]; + } + if (arch !== hostArch) { + throw new Error( + `macOS ${arch} distributable requires a native ${arch} host; received ${hostArch}` + ); + } + return [arch]; +} + export function runDistributableSmoke( { arch = process.env.MATRIX_ARCH ?? process.arch, platform = process.platform, + hostArch = process.arch, + includeRosetta = false, version = JSON.parse( fs.readFileSync(path.join(repositoryRoot, "package.json"), "utf8") ).version, @@ -156,6 +207,12 @@ export function runDistributableSmoke( dependencies.inspectWindowsRegistrations ?? getWindowsInstallRegistrations; const names = getDistributableNames({ platform, arch, version }); + const architectures = getSmokeArchitectures({ + platform, + arch, + hostArch, + includeRosetta, + }); const evidence = []; const reportPath = path.join( releaseDirectory, @@ -290,10 +347,6 @@ export function runDistributableSmoke( releaseDistPath: destination, platform, }); - const architectures = - platform === "darwin" && arch === "universal" - ? ["arm64", "x64"] - : [arch]; for (const architecture of architectures) { let launchPath = executable; if (platform === "darwin") { @@ -338,7 +391,7 @@ export function runDistributableSmoke( smoke(["--executable", launchPath], { ...environment, FFV_SMOKE_EXPECTED_ARCH: - arch === "universal" ? process.arch : arch, + arch === "universal" ? hostArch : arch, FFV_SMOKE_EXPECTED_VERSION: version, FFV_SMOKE_DIAGNOSTICS_DIRECTORY: path.join( releaseDirectory, @@ -383,5 +436,7 @@ if ( process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href ) { - process.exitCode = runDistributableSmoke(); + process.exitCode = runDistributableSmoke( + parseDistributableSmokeArguments(process.argv.slice(2)) + ); } diff --git a/scripts/run-macos-smoke-diagnostics.mjs b/scripts/run-macos-smoke-diagnostics.mjs index 49dc3b95a..6fdc7da38 100644 --- a/scripts/run-macos-smoke-diagnostics.mjs +++ b/scripts/run-macos-smoke-diagnostics.mjs @@ -200,7 +200,10 @@ export async function runMacosSmokeDiagnostics( fs.mkdirSync(directory, { recursive: true }); const child = spawnHarness( process.execPath, - [path.join(repositoryRoot, "scripts/run-distributable-smoke.mjs")], + [ + path.join(repositoryRoot, "scripts/run-distributable-smoke.mjs"), + ...(options.includeRosetta ? ["--include-rosetta"] : []), + ], { cwd: repositoryRoot, env: environment, @@ -266,6 +269,8 @@ if ( ) ); } else { - process.exitCode = await runMacosSmokeDiagnostics(); + process.exitCode = await runMacosSmokeDiagnostics({ + includeRosetta: process.argv.includes("--include-rosetta"), + }); } } diff --git a/scripts/verify-universal-native-source.mjs b/scripts/verify-universal-native-source.mjs new file mode 100644 index 000000000..956aae13b --- /dev/null +++ b/scripts/verify-universal-native-source.mjs @@ -0,0 +1,151 @@ +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import process from "node:process"; +import { pathToFileURL } from "node:url"; + +function readJson(directory, name) { + return JSON.parse(fs.readFileSync(path.join(directory, name), "utf8")); +} + +function isPackageVersion(value) { + if (typeof value !== "string") return false; + const [core, ...prerelease] = value.split("-"); + return ( + /^\d+\.\d+\.\d+$/u.test(core) && + (prerelease.length === 0 || + /^[\dA-Za-z.-]+$/u.test(prerelease.join("-"))) + ); +} + +function isSha256Digest(value) { + return typeof value === "string" && /^[0-9a-f]{64}$/u.test(value); +} + +function validateExpectedSource(options) { + if (!isPackageVersion(options.version)) + throw new Error("Invalid Universal verification package version"); + const required = [ + [ + options.sourceSha, + /^[0-9a-f]{40}$/u, + "source SHA", + ], + [ + options.runId, + /^[1-9]\d*$/u, + "workflow run ID", + ], + [ + options.runAttempt, + /^[1-9]\d*$/u, + "workflow run attempt", + ], + ]; + for (const [ + value, + pattern, + description, + ] of required) { + if (typeof value !== "string" || !pattern.test(value)) + throw new Error(`Invalid Universal verification ${description}`); + } + if (options.expectedVersion && options.expectedVersion !== options.version) + throw new Error( + "Universal source package does not match the release version" + ); +} + +function verifySourceManifest(source, options) { + if ( + source?.sourceSha !== options.sourceSha || + source?.version !== options.version || + source?.runId !== options.runId || + source?.runAttempt !== options.runAttempt + ) { + throw new Error( + "Universal artifact does not match this source revision and workflow run" + ); + } +} + +function getArm64SmokeArtifact(report, version) { + if ( + report?.version !== version || + report?.platform !== "darwin" || + report?.arch !== "universal" || + !Array.isArray(report.artifacts) || + report.artifacts.length !== 1 + ) { + throw new Error( + "Universal ARM64 smoke report has an unexpected version or artifact set" + ); + } + return report.artifacts[0]; +} + +function verifyArm64Report(report, version, artifactName) { + const artifact = getArm64SmokeArtifact(report, version); + if ( + artifact?.artifact !== artifactName || + artifact?.passed !== true || + artifact?.signatureVerified !== true || + artifact?.launchServicesVerified !== true || + JSON.stringify(artifact?.architectures) !== '["arm64"]' || + !isSha256Digest(artifact?.sha256) + ) { + throw new Error( + "Universal DMG lacks successful native ARM64 and LaunchServices evidence" + ); + } + return artifact.sha256; +} + +export function verifyUniversalNativeSource(options) { + validateExpectedSource(options); + const directory = options.artifactDirectory; + verifySourceManifest( + readJson(directory, "universal-native-source.json"), + options + ); + const artifact = `Fit-File-Viewer-dmg-universal-${options.version}.dmg`; + const sha256 = verifyArm64Report( + readJson(directory, "distributable-smoke-darwin-universal.json"), + options.version, + artifact + ); + const signing = readJson(directory, "signing-verification-report.json"); + if (signing?.status !== "verified" || signing?.platform !== "darwin") + throw new Error("Universal source signing verification did not pass"); + const actual = createHash("sha256") + .update(fs.readFileSync(path.join(directory, artifact))) + .digest("hex"); + if (actual !== sha256) + throw new Error( + "Universal DMG hash differs from the ARM64-tested artifact" + ); + return { + artifact, + sha256, + sourceSha: options.sourceSha, + version: options.version, + runId: options.runId, + runAttempt: options.runAttempt, + verifiedArchitectures: ["arm64"], + }; +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + const result = verifyUniversalNativeSource({ + artifactDirectory: path.resolve("source-artifact"), + sourceSha: process.env.SOURCE_SHA, + expectedVersion: process.env.EXPECTED_VERSION, + version: readJson(process.cwd(), "package.json").version, + runId: process.env.GITHUB_RUN_ID, + runAttempt: process.env.GITHUB_RUN_ATTEMPT, + }); + console.log(JSON.stringify(result, null, 2)); +} diff --git a/tests/unit/packaging/runDistributableSmoke.test.ts b/tests/unit/packaging/runDistributableSmoke.test.ts index d2546f983..062eda43d 100644 --- a/tests/unit/packaging/runDistributableSmoke.test.ts +++ b/tests/unit/packaging/runDistributableSmoke.test.ts @@ -9,6 +9,7 @@ import { getArchiveExtractionCommand, getDistributableNames, getWindowsInstallRegistrations, + parseDistributableSmokeArguments, runChecked, runDistributableSmoke, } from "../../../scripts/run-distributable-smoke.mjs"; @@ -82,6 +83,105 @@ afterEach(() => { }); describe("final distributable smoke", () => { + it("accepts only the explicit Rosetta diagnostic CLI flag", () => { + expect.assertions(5); + expect(parseDistributableSmokeArguments([])).toStrictEqual({ + includeRosetta: false, + }); + expect( + parseDistributableSmokeArguments(["--include-rosetta"]) + ).toStrictEqual({ includeRosetta: true }); + for (const args of [ + ["--include-rosetta=false"], + ["--include-rosetta", "--include-rosetta"], + ["--arch", "x64"], + ]) { + expect(() => parseDistributableSmokeArguments(args)).toThrow( + "Usage:" + ); + } + }); + + it.each([ + [ + "darwin", + "universal", + "x64", + true, + ], + [ + "darwin", + "arm64", + "arm64", + true, + ], + [ + "darwin", + "x64", + "arm64", + true, + ], + [ + "linux", + "x64", + "arm64", + true, + ], + [ + "win32", + "x64", + "arm64", + true, + ], + [ + "darwin", + "universal", + "ia32", + false, + ], + [ + "darwin", + "arm64", + "x64", + false, + ], + [ + "darwin", + "x64", + "arm64", + false, + ], + [ + "darwin", + "universal", + "arm64", + "true", + ], + ])( + "rejects invalid architecture requests %s/%s on %s with includeRosetta=%s before launching", + (platform, arch, hostArch, includeRosetta) => { + expect.assertions(3); + const releaseDirectory = makeRelease(platform, arch); + const run = vi.fn(); + const smoke = vi.fn(); + expect(() => + runDistributableSmoke( + { + platform, + arch, + hostArch, + includeRosetta, + version: "30.0.3", + releaseDirectory, + }, + { run, smoke } + ) + ).toThrow(/requires|Unsupported|boolean/u); + expect(run).not.toHaveBeenCalled(); + expect(smoke).not.toHaveBeenCalled(); + } + ); + it("uses native Windows tar and preserves D drive archive paths under a Git Bash environment", () => { expect.assertions(1); expect( @@ -286,6 +386,7 @@ describe("final distributable smoke", () => { runDistributableSmoke({ arch: "arm64", platform: "darwin", + hostArch: "arm64", version: "30.0.3", releaseDirectory, }) @@ -376,56 +477,97 @@ describe("final distributable smoke", () => { ).toThrow("invalid signature"); }); - it("copies a mounted universal DMG, verifies signatures, then launches both slices and LaunchServices", () => { - expect.assertions(7); - const releaseDirectory = makeRelease("darwin", "universal"); - const commands: string[][] = []; - const wrappers: string[] = []; - const run = (command: string, args: string[]): void => { - commands.push([command, ...args]); - if (command === "ditto") createExecutable(args[1] ?? "", "darwin"); - }; - const smoke = (args: string[]): number => { - wrappers.push(fs.readFileSync(args[1] ?? "", "utf8")); - return 0; - }; - expect( - runDistributableSmoke( - { - arch: "universal", - platform: "darwin", - version: "30.0.3", - releaseDirectory, - }, - { run, smoke } - ) - ).toBe(0); - expect(commands.map((command) => command[0])).toStrictEqual([ - "hdiutil", - "ditto", - "hdiutil", - "codesign", - ]); - expect(commands[0]).toContain("-readonly"); - expect(commands[3]).toContain("--all-architectures"); - expect(wrappers.map((wrapper) => wrapper.split("\n")[1])).toEqual([ - expect.stringContaining("arch -arm64"), - expect.stringContaining("arch -x86_64"), - expect.stringContaining("open -W -n"), - ]); - expect(wrappers[2]).toContain('"FFV_SMOKE_NONCE=$FFV_SMOKE_NONCE"'); - expect( - readSmokeReport(releaseDirectory, "darwin", "universal") - ).toMatchObject({ - artifacts: [ - { - passed: true, - signatureVerified: true, - architectures: ["arm64", "x64"], - }, - ], - }); - }); + it.each([ + { hostArch: "arm64", includeRosetta: false, architectures: ["arm64"] }, + { hostArch: "x64", includeRosetta: false, architectures: ["x64"] }, + { + hostArch: "arm64", + includeRosetta: true, + architectures: ["arm64", "x64"], + }, + ])( + "verifies all signatures and launches the requested Universal slices and native LaunchServices: $hostArch, Rosetta=$includeRosetta", + ({ hostArch, includeRosetta, architectures }) => { + expect.assertions(10); + const releaseDirectory = makeRelease("darwin", "universal"); + const commands: string[][] = []; + const wrappers: string[] = []; + const environments: Record[] = []; + const run = (command: string, args: string[]): void => { + commands.push([command, ...args]); + if (command === "ditto") + createExecutable(args[1] ?? "", "darwin"); + }; + const smoke = ( + args: string[], + environment: Record + ): number => { + wrappers.push(fs.readFileSync(args[1] ?? "", "utf8")); + environments.push(environment); + return 0; + }; + expect( + runDistributableSmoke( + { + arch: "universal", + platform: "darwin", + hostArch, + ...(includeRosetta ? { includeRosetta } : {}), + environment: { FFV_PACKAGED_SMOKE_TIMEOUT_MS: "60000" }, + version: "30.0.3", + releaseDirectory, + }, + { run, smoke } + ) + ).toBe(0); + expect(commands.map((command) => command[0])).toStrictEqual([ + "hdiutil", + "ditto", + "hdiutil", + "codesign", + ]); + expect(commands[0]).toContain("-readonly"); + expect(commands[3]).toContain("--all-architectures"); + expect(wrappers.map((wrapper) => wrapper.split("\n")[1])).toEqual([ + ...architectures.map((architecture) => + expect.stringContaining( + `arch -${architecture === "x64" ? "x86_64" : architecture}` + ) + ), + expect.stringContaining("open -W -n"), + ]); + expect(wrappers.at(-1)).toContain( + '"FFV_SMOKE_NONCE=$FFV_SMOKE_NONCE"' + ); + expect( + environments.map( + (environment) => environment.FFV_SMOKE_EXPECTED_ARCH + ) + ).toStrictEqual([...architectures, hostArch]); + expect( + environments.map( + (environment) => environment.FFV_SMOKE_EXPECTED_VERSION + ) + ).toStrictEqual(architectures.concat(hostArch).map(() => "30.0.3")); + expect( + environments.map( + (environment) => environment.FFV_PACKAGED_SMOKE_TIMEOUT_MS + ) + ).toStrictEqual(architectures.concat(hostArch).map(() => "60000")); + expect( + readSmokeReport(releaseDirectory, "darwin", "universal") + ).toMatchObject({ + artifacts: [ + { + passed: true, + signatureVerified: true, + architectures, + launchServicesVerified: true, + }, + ], + }); + } + ); it("rejects an invalid final signature before launch and preserves failure evidence", () => { expect.assertions(3); @@ -441,6 +583,7 @@ describe("final distributable smoke", () => { { arch: "arm64", platform: "darwin", + hostArch: "arm64", version: "30.0.3", releaseDirectory, }, diff --git a/tests/unit/packaging/runMacosSmokeDiagnostics.test.ts b/tests/unit/packaging/runMacosSmokeDiagnostics.test.ts index 4a63e283e..c84427f2c 100644 --- a/tests/unit/packaging/runMacosSmokeDiagnostics.test.ts +++ b/tests/unit/packaging/runMacosSmokeDiagnostics.test.ts @@ -135,6 +135,31 @@ describe("macOS smoke diagnostics", () => { }); }); + it.each([false, true])( + "forwards Rosetta opt-in %s without changing the harness result", + async (includeRosetta) => { + expect.assertions(2); + const child = Object.assign(new EventEmitter(), { pid: 10 }); + const spawn = vi + .fn<(...args: unknown[]) => typeof child>() + .mockReturnValue(child); + const running = runMacosSmokeDiagnostics( + { + platform: "darwin", + directory: createDirectory(), + includeRosetta, + }, + { spawn, capture: successfulCapture() } + ); + expect(spawn.mock.calls[0]?.[1]).toEqual([ + expect.stringContaining("run-distributable-smoke.mjs"), + ...(includeRosetta ? ["--include-rosetta"] : []), + ]); + child.emit("close", 0, null); + await expect(running).resolves.toBe(0); + } + ); + it("preserves harness spawn errors while collecting system diagnostics", async () => { expect.assertions(2); const directory = createDirectory(); diff --git a/tests/unit/packaging/universalNativeWorkflow.test.ts b/tests/unit/packaging/universalNativeWorkflow.test.ts new file mode 100644 index 000000000..d99d62bee --- /dev/null +++ b/tests/unit/packaging/universalNativeWorkflow.test.ts @@ -0,0 +1,179 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; +import { parse as parseYaml } from "yaml"; + +type Step = { + env?: Record; + if?: string; + name: string; + run?: string; + uses?: string; + with?: Record; +}; + +type Job = { + "continue-on-error"?: boolean; + if?: string; + needs?: string | string[]; + permissions?: Record; + "runs-on"?: string; + steps?: Step[]; + uses?: string; + with?: Record; +}; + +function readWorkflow(name: string): { jobs: Record } { + return parseYaml( + readFileSync( + path.join(process.cwd(), ".github/workflows", name), + "utf8" + ) + ) as { jobs: Record }; +} + +describe("Universal DMG native verification workflows", () => { + it.each([ + { + file: "Build.yml", + producer: "build", + source: "${{ needs.bump-version.outputs.bump_sha }}", + }, + { + file: "release-rehearsal.yml", + producer: "release-rehearsal", + source: "${{ github.sha }}", + }, + ])( + "hands off the exact ARM64-tested DMG separately from release assets in $file", + ({ file, producer, source }) => { + expect.assertions(8); + const { jobs } = readWorkflow(file); + const steps = jobs[producer]?.steps ?? []; + const smokeIndex = steps.findIndex( + (step) => + step.name === "Smoke test installed distributable artifacts" + ); + const uploadIndex = steps.findIndex( + (step) => + step.name === + "Upload Universal DMG for required native Intel verification" + ); + const upload = steps[uploadIndex]; + expect(uploadIndex).toBeGreaterThan(smokeIndex); + expect(upload?.if).toBe( + "runner.os == 'macOS' && matrix.arch == 'universal'" + ); + expect(upload?.with?.name).toBe( + "universal-native-verification-${{ github.run_attempt }}" + ); + expect(upload?.with?.path).toContain( + "release-dist/distributable-smoke-darwin-universal.json" + ); + expect(upload?.with?.path).toContain( + "release-dist/Fit-File-Viewer-dmg-universal-*.dmg" + ); + expect(upload?.with?.path).toContain( + "release-dist/signing-verification-report.json" + ); + expect( + steps.find( + (step) => + step.name === + "Record Universal native verification source" + )?.env?.SOURCE_SHA + ).toBe(source); + expect(steps.map((step) => step.run ?? "").join("\n")).not.toMatch( + /install-rosetta|run-macos-smoke-diagnostics|--include-rosetta/u + ); + } + ); + + it("requires successful native Intel verification before publishing", () => { + expect.assertions(7); + const { jobs } = readWorkflow("Build.yml"); + expect(jobs.release?.needs).toEqual([ + "build", + "bump-version", + "verify-universal-intel", + ]); + expect(jobs.release?.if).toContain( + "needs.verify-universal-intel.result == 'success'" + ); + expect(jobs["verify-universal-intel"]?.needs).toEqual([ + "build", + "bump-version", + ]); + expect(jobs["verify-universal-intel"]?.with).toEqual({ + "expected-version": "${{ needs.bump-version.outputs.new_version }}", + "source-sha": "${{ needs.bump-version.outputs.bump_sha }}", + }); + expect(jobs["verify-universal-intel"]).not.toHaveProperty( + "continue-on-error" + ); + expect( + jobs.release?.steps?.find((step) => + step.uses?.startsWith("actions/download-artifact@") + )?.with?.pattern + ).toBe("dist-*"); + expect(jobs["verify-universal-intel"]?.uses).toBe( + "./.github/workflows/verify-universal-native-intel.yml" + ); + }); + + it("requires native Intel rehearsal evidence even when another matrix job fails", () => { + expect.assertions(5); + const { jobs } = readWorkflow("release-rehearsal.yml"); + const consumer = jobs["verify-universal-intel"]; + expect(consumer?.needs).toBe("release-rehearsal"); + expect(consumer?.if).toBe("always() && !cancelled()"); + expect(consumer?.with?.["source-sha"]).toBe("${{ github.sha }}"); + expect(consumer).not.toHaveProperty("continue-on-error"); + expect(jobs["release-verification"]).not.toHaveProperty("needs"); + }); + + it("validates the current run's source and bytes before native x64 and LaunchServices smoke", () => { + expect.assertions(12); + const consumer = readWorkflow("verify-universal-native-intel.yml").jobs[ + "native-intel" + ]; + const steps = consumer?.steps ?? []; + const verifyIndex = steps.findIndex((step) => + step.run?.includes( + "node scripts/verify-universal-native-source.mjs" + ) + ); + const smokeIndex = steps.findIndex( + (step) => step.run === "node scripts/run-distributable-smoke.mjs" + ); + const download = steps.find((step) => + step.uses?.startsWith("actions/download-artifact@") + ); + expect(consumer?.["runs-on"]).toBe("macos-15-intel"); + expect( + steps.find((step) => step.uses?.startsWith("actions/checkout@")) + ?.with?.ref + ).toBe("${{ inputs.source-sha }}"); + expect(download?.with?.name).toBe( + "universal-native-verification-${{ github.run_attempt }}" + ); + expect(download?.with?.["run-id"]).toBe("${{ github.run_id }}"); + expect(download?.with?.["digest-mismatch"]).toBe("error"); + expect(verifyIndex).toBeGreaterThan(-1); + expect(smokeIndex).toBeGreaterThan(verifyIndex); + expect(steps[verifyIndex]?.env).toEqual({ + EXPECTED_VERSION: "${{ inputs.expected-version }}", + SOURCE_SHA: "${{ inputs.source-sha }}", + }); + expect(steps[smokeIndex]?.env).toEqual({ + FFV_PACKAGED_SMOKE_TIMEOUT_MS: "60000", + MATRIX_ARCH: "universal", + }); + expect(steps[smokeIndex]).not.toHaveProperty("continue-on-error"); + expect(steps.at(-1)?.if).toBe("always()"); + expect(steps.at(-1)?.with?.path).toContain( + "release-dist/smoke-diagnostics/**" + ); + }); +}); diff --git a/tests/unit/packaging/verifyUniversalNativeSource.test.ts b/tests/unit/packaging/verifyUniversalNativeSource.test.ts new file mode 100644 index 000000000..65e030c5e --- /dev/null +++ b/tests/unit/packaging/verifyUniversalNativeSource.test.ts @@ -0,0 +1,236 @@ +// @vitest-environment node + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +type VerificationOptions = { + artifactDirectory: string; + expectedVersion?: string; + runAttempt: string; + runId: string; + sourceSha: string; + version: string; +}; + +type ArtifactReport = { + architectures: string[]; + artifact: string; + launchServicesVerified: boolean; + passed: boolean; + sha256: string; + signatureVerified: boolean; +}; + +type Fixture = { + artifact: ArtifactReport; + options: VerificationOptions; + report: { + arch: string; + artifacts: ArtifactReport[]; + platform: string; + version: string; + }; +}; + +const temporaryDirectories: string[] = []; + +async function verifier(): Promise< + (options: VerificationOptions) => Record +> { + const module = + (await import("../../../scripts/verify-universal-native-source.mjs")) as { + verifyUniversalNativeSource: ( + options: VerificationOptions + ) => Record; + }; + return module.verifyUniversalNativeSource; +} + +function writeJson(directory: string, name: string, value: unknown): void { + fs.writeFileSync(path.join(directory, name), JSON.stringify(value)); +} + +function createFixture(): Fixture { + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), "ffv-native-source-") + ); + temporaryDirectories.push(directory); + const options: VerificationOptions = { + artifactDirectory: directory, + expectedVersion: "30.0.3", + runAttempt: "2", + runId: "37708098988", + sourceSha: "a".repeat(40), + version: "30.0.3", + }; + const bytes = Buffer.from("The exact Universal DMG bytes tested on ARM64"); + const artifact: ArtifactReport = { + architectures: ["arm64"], + artifact: "Fit-File-Viewer-dmg-universal-30.0.3.dmg", + launchServicesVerified: true, + passed: true, + sha256: createHash("sha256").update(bytes).digest("hex"), + signatureVerified: true, + }; + const report = { + arch: "universal", + artifacts: [artifact], + platform: "darwin", + version: options.version, + }; + fs.writeFileSync(path.join(directory, artifact.artifact), bytes); + writeJson(directory, "universal-native-source.json", options); + writeJson(directory, "distributable-smoke-darwin-universal.json", report); + writeJson(directory, "signing-verification-report.json", { + platform: "darwin", + status: "verified", + }); + return { artifact, options, report }; +} + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) { + fs.rmSync(directory, { force: true, recursive: true }); + } +}); + +describe("Universal native artifact handoff", () => { + it("accepts only the source-bound DMG bytes covered by successful ARM64 smoke", async () => { + expect.assertions(1); + const fixture = createFixture(); + const verify = await verifier(); + expect(verify(fixture.options)).toEqual({ + artifact: fixture.artifact.artifact, + runAttempt: "2", + runId: "37708098988", + sha256: fixture.artifact.sha256, + sourceSha: "a".repeat(40), + verifiedArchitectures: ["arm64"], + version: "30.0.3", + }); + }); + + it("rejects changed DMG bytes even when the reports still claim success", async () => { + expect.assertions(1); + const fixture = createFixture(); + fs.appendFileSync( + path.join( + fixture.options.artifactDirectory, + fixture.artifact.artifact + ), + "changed" + ); + const verify = await verifier(); + expect(() => verify(fixture.options)).toThrow("hash differs"); + }); + + it.each([ + { field: "sourceSha", value: "b".repeat(40) }, + { field: "version", value: "30.0.2" }, + { field: "runId", value: "37708098989" }, + { field: "runAttempt", value: "1" }, + ])("rejects a handoff from another $field", async ({ field, value }) => { + expect.assertions(1); + const fixture = createFixture(); + writeJson( + fixture.options.artifactDirectory, + "universal-native-source.json", + { ...fixture.options, [field]: value } + ); + const verify = await verifier(); + expect(() => verify(fixture.options)).toThrow( + "does not match this source revision and workflow run" + ); + }); + + it.each([ + { label: "wrong architecture", override: { architectures: ["x64"] } }, + { label: "missing native coverage", override: { architectures: [] } }, + { label: "failed smoke", override: { passed: false } }, + { label: "failed signature", override: { signatureVerified: false } }, + { + label: "missing LaunchServices", + override: { launchServicesVerified: false }, + }, + { + label: "different filename", + override: { artifact: "../unexpected.dmg" }, + }, + { label: "invalid digest", override: { sha256: "not-a-digest" } }, + ])("rejects $label in the producer report", async ({ override }) => { + expect.assertions(1); + const fixture = createFixture(); + writeJson( + fixture.options.artifactDirectory, + "distributable-smoke-darwin-universal.json", + { + ...fixture.report, + artifacts: [{ ...fixture.artifact, ...override }], + } + ); + const verify = await verifier(); + expect(() => verify(fixture.options)).toThrow( + "lacks successful native ARM64 and LaunchServices evidence" + ); + }); + + it.each([ + { arch: "arm64" }, + { artifacts: [] }, + { platform: "win32" }, + { version: "30.0.2" }, + ])("rejects an incompatible producer report %j", async (override) => { + expect.assertions(1); + const fixture = createFixture(); + writeJson( + fixture.options.artifactDirectory, + "distributable-smoke-darwin-universal.json", + { ...fixture.report, ...override } + ); + const verify = await verifier(); + expect(() => verify(fixture.options)).toThrow( + "unexpected version or artifact set" + ); + }); + + it("rejects a failed signing report", async () => { + expect.assertions(1); + const fixture = createFixture(); + writeJson( + fixture.options.artifactDirectory, + "signing-verification-report.json", + { platform: "darwin", status: "failed" } + ); + const verify = await verifier(); + expect(() => verify(fixture.options)).toThrow( + "signing verification did not pass" + ); + }); + + it.each([ + { sourceSha: "main" }, + { version: "../30.0.3" }, + { runId: "0" }, + { runAttempt: "-1" }, + ])("rejects malformed expected identity %j", async (override) => { + expect.assertions(1); + const fixture = createFixture(); + const verify = await verifier(); + expect(() => verify({ ...fixture.options, ...override })).toThrow( + "Invalid Universal verification" + ); + }); + + it("requires the checked-out package version to equal the bumped release version", async () => { + expect.assertions(1); + const fixture = createFixture(); + const verify = await verifier(); + expect(() => + verify({ ...fixture.options, expectedVersion: "30.0.4" }) + ).toThrow("does not match the release version"); + }); +}); From 502a114fdaf5016544727d71571138d1c442958a Mon Sep 17 00:00:00 2001 From: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com> Date: Wed, 7 Oct 2026 21:28:41 -0400 Subject: [PATCH 07/12] =?UTF-8?q?=F0=9F=A7=AA=20[test]=20Split=20native=20?= =?UTF-8?q?smoke=20assertions=20into=20focused=20suites?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿงช [test] Separate architecture and Rosetta selection cases from platform installation tests, retain complete launch and evidence assertions, and split workflow provenance from required smoke-order checks to satisfy the existing complexity limits. --- .../packaging/runDistributableSmoke.test.ts | 208 ------------- .../runDistributableSmokeArchitecture.test.ts | 275 ++++++++++++++++++ .../packaging/universalNativeWorkflow.test.ts | 28 +- 3 files changed, 293 insertions(+), 218 deletions(-) create mode 100644 tests/unit/packaging/runDistributableSmokeArchitecture.test.ts diff --git a/tests/unit/packaging/runDistributableSmoke.test.ts b/tests/unit/packaging/runDistributableSmoke.test.ts index 062eda43d..7bc6c6c8f 100644 --- a/tests/unit/packaging/runDistributableSmoke.test.ts +++ b/tests/unit/packaging/runDistributableSmoke.test.ts @@ -9,7 +9,6 @@ import { getArchiveExtractionCommand, getDistributableNames, getWindowsInstallRegistrations, - parseDistributableSmokeArguments, runChecked, runDistributableSmoke, } from "../../../scripts/run-distributable-smoke.mjs"; @@ -33,22 +32,6 @@ function makeRelease(platform: string, arch: string): string { return directory; } -function readSmokeReport( - releaseDirectory: string, - platform: string, - arch: string -): unknown { - return JSON.parse( - fs.readFileSync( - path.join( - releaseDirectory, - `distributable-smoke-${platform}-${arch}.json` - ), - "utf8" - ) - ); -} - function createExecutable(destination: string, platform: string): void { const executable = platform === "darwin" @@ -83,105 +66,6 @@ afterEach(() => { }); describe("final distributable smoke", () => { - it("accepts only the explicit Rosetta diagnostic CLI flag", () => { - expect.assertions(5); - expect(parseDistributableSmokeArguments([])).toStrictEqual({ - includeRosetta: false, - }); - expect( - parseDistributableSmokeArguments(["--include-rosetta"]) - ).toStrictEqual({ includeRosetta: true }); - for (const args of [ - ["--include-rosetta=false"], - ["--include-rosetta", "--include-rosetta"], - ["--arch", "x64"], - ]) { - expect(() => parseDistributableSmokeArguments(args)).toThrow( - "Usage:" - ); - } - }); - - it.each([ - [ - "darwin", - "universal", - "x64", - true, - ], - [ - "darwin", - "arm64", - "arm64", - true, - ], - [ - "darwin", - "x64", - "arm64", - true, - ], - [ - "linux", - "x64", - "arm64", - true, - ], - [ - "win32", - "x64", - "arm64", - true, - ], - [ - "darwin", - "universal", - "ia32", - false, - ], - [ - "darwin", - "arm64", - "x64", - false, - ], - [ - "darwin", - "x64", - "arm64", - false, - ], - [ - "darwin", - "universal", - "arm64", - "true", - ], - ])( - "rejects invalid architecture requests %s/%s on %s with includeRosetta=%s before launching", - (platform, arch, hostArch, includeRosetta) => { - expect.assertions(3); - const releaseDirectory = makeRelease(platform, arch); - const run = vi.fn(); - const smoke = vi.fn(); - expect(() => - runDistributableSmoke( - { - platform, - arch, - hostArch, - includeRosetta, - version: "30.0.3", - releaseDirectory, - }, - { run, smoke } - ) - ).toThrow(/requires|Unsupported|boolean/u); - expect(run).not.toHaveBeenCalled(); - expect(smoke).not.toHaveBeenCalled(); - } - ); - it("uses native Windows tar and preserves D drive archive paths under a Git Bash environment", () => { expect.assertions(1); expect( @@ -477,98 +361,6 @@ describe("final distributable smoke", () => { ).toThrow("invalid signature"); }); - it.each([ - { hostArch: "arm64", includeRosetta: false, architectures: ["arm64"] }, - { hostArch: "x64", includeRosetta: false, architectures: ["x64"] }, - { - hostArch: "arm64", - includeRosetta: true, - architectures: ["arm64", "x64"], - }, - ])( - "verifies all signatures and launches the requested Universal slices and native LaunchServices: $hostArch, Rosetta=$includeRosetta", - ({ hostArch, includeRosetta, architectures }) => { - expect.assertions(10); - const releaseDirectory = makeRelease("darwin", "universal"); - const commands: string[][] = []; - const wrappers: string[] = []; - const environments: Record[] = []; - const run = (command: string, args: string[]): void => { - commands.push([command, ...args]); - if (command === "ditto") - createExecutable(args[1] ?? "", "darwin"); - }; - const smoke = ( - args: string[], - environment: Record - ): number => { - wrappers.push(fs.readFileSync(args[1] ?? "", "utf8")); - environments.push(environment); - return 0; - }; - expect( - runDistributableSmoke( - { - arch: "universal", - platform: "darwin", - hostArch, - ...(includeRosetta ? { includeRosetta } : {}), - environment: { FFV_PACKAGED_SMOKE_TIMEOUT_MS: "60000" }, - version: "30.0.3", - releaseDirectory, - }, - { run, smoke } - ) - ).toBe(0); - expect(commands.map((command) => command[0])).toStrictEqual([ - "hdiutil", - "ditto", - "hdiutil", - "codesign", - ]); - expect(commands[0]).toContain("-readonly"); - expect(commands[3]).toContain("--all-architectures"); - expect(wrappers.map((wrapper) => wrapper.split("\n")[1])).toEqual([ - ...architectures.map((architecture) => - expect.stringContaining( - `arch -${architecture === "x64" ? "x86_64" : architecture}` - ) - ), - expect.stringContaining("open -W -n"), - ]); - expect(wrappers.at(-1)).toContain( - '"FFV_SMOKE_NONCE=$FFV_SMOKE_NONCE"' - ); - expect( - environments.map( - (environment) => environment.FFV_SMOKE_EXPECTED_ARCH - ) - ).toStrictEqual([...architectures, hostArch]); - expect( - environments.map( - (environment) => environment.FFV_SMOKE_EXPECTED_VERSION - ) - ).toStrictEqual(architectures.concat(hostArch).map(() => "30.0.3")); - expect( - environments.map( - (environment) => environment.FFV_PACKAGED_SMOKE_TIMEOUT_MS - ) - ).toStrictEqual(architectures.concat(hostArch).map(() => "60000")); - expect( - readSmokeReport(releaseDirectory, "darwin", "universal") - ).toMatchObject({ - artifacts: [ - { - passed: true, - signatureVerified: true, - architectures, - launchServicesVerified: true, - }, - ], - }); - } - ); - it("rejects an invalid final signature before launch and preserves failure evidence", () => { expect.assertions(3); const releaseDirectory = makeRelease("darwin", "arm64"); diff --git a/tests/unit/packaging/runDistributableSmokeArchitecture.test.ts b/tests/unit/packaging/runDistributableSmokeArchitecture.test.ts new file mode 100644 index 000000000..e95e42685 --- /dev/null +++ b/tests/unit/packaging/runDistributableSmokeArchitecture.test.ts @@ -0,0 +1,275 @@ +import fs from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + parseDistributableSmokeArguments, + runDistributableSmoke, +} from "../../../scripts/run-distributable-smoke.mjs"; + +interface UniversalScenario { + architectures: string[]; + hostArch: string; + includeRosetta: boolean; +} + +interface LaunchCapture { + commands: string[][]; + environments: Record[]; + run: (command: string, args: string[]) => void; + smoke: (args: string[], environment: Record) => number; + wrappers: string[]; +} + +const directories: string[] = []; +const invalidArchitectureRequests = [ + [ + "darwin", + "universal", + "x64", + true, + ], + [ + "darwin", + "arm64", + "arm64", + true, + ], + [ + "darwin", + "x64", + "arm64", + true, + ], + [ + "linux", + "x64", + "arm64", + true, + ], + [ + "win32", + "x64", + "arm64", + true, + ], + [ + "darwin", + "universal", + "ia32", + false, + ], + [ + "darwin", + "arm64", + "x64", + false, + ], + [ + "darwin", + "x64", + "arm64", + false, + ], + [ + "darwin", + "universal", + "arm64", + "true", + ], +]; +const universalScenarios: UniversalScenario[] = [ + { hostArch: "arm64", includeRosetta: false, architectures: ["arm64"] }, + { hostArch: "x64", includeRosetta: false, architectures: ["x64"] }, + { + hostArch: "arm64", + includeRosetta: true, + architectures: ["arm64", "x64"], + }, +]; + +function makeUniversalRelease(): string { + const directory = fs.mkdtempSync( + path.join(tmpdir(), "ffv-universal-test-") + ); + directories.push(directory); + fs.writeFileSync( + path.join(directory, "Fit-File-Viewer-dmg-universal-30.0.3.dmg"), + "fixture Universal artifact" + ); + return directory; +} + +function makeLaunchCapture(): LaunchCapture { + const commands: string[][] = []; + const wrappers: string[] = []; + const environments: Record[] = []; + const run = (command: string, args: string[]): void => { + commands.push([command, ...args]); + if (command !== "ditto") return; + const executable = path.join( + args[1] ?? "", + "Contents", + "MacOS", + "Fit File Viewer" + ); + fs.mkdirSync(path.dirname(executable), { recursive: true }); + fs.writeFileSync(executable, "fixture executable"); + }; + const smoke = ( + args: string[], + environment: Record + ): number => { + wrappers.push(fs.readFileSync(args[1] ?? "", "utf8")); + environments.push(environment); + return 0; + }; + return { commands, wrappers, environments, run, smoke }; +} + +function expectVerifiedLaunches( + capture: LaunchCapture, + { architectures, hostArch }: UniversalScenario +): void { + expect(capture.commands.map((command) => command[0])).toStrictEqual([ + "hdiutil", + "ditto", + "hdiutil", + "codesign", + ]); + expect(capture.commands[0]).toContain("-readonly"); + expect(capture.commands[3]).toContain("--all-architectures"); + expect(capture.wrappers.map((wrapper) => wrapper.split("\n")[1])).toEqual([ + ...architectures.map((architecture) => + expect.stringContaining( + `arch -${architecture === "x64" ? "x86_64" : architecture}` + ) + ), + expect.stringContaining("open -W -n"), + ]); + expect(capture.wrappers.at(-1)).toContain( + '"FFV_SMOKE_NONCE=$FFV_SMOKE_NONCE"' + ); + expect( + capture.environments.map( + (environment) => environment.FFV_SMOKE_EXPECTED_ARCH + ) + ).toStrictEqual([...architectures, hostArch]); + expect( + capture.environments.map( + (environment) => environment.FFV_SMOKE_EXPECTED_VERSION + ) + ).toStrictEqual(architectures.concat(hostArch).map(() => "30.0.3")); + expect( + capture.environments.map( + (environment) => environment.FFV_PACKAGED_SMOKE_TIMEOUT_MS + ) + ).toStrictEqual(architectures.concat(hostArch).map(() => "60000")); +} + +function expectNativeEvidence( + releaseDirectory: string, + architectures: string[] +): void { + const report = JSON.parse( + fs.readFileSync( + path.join( + releaseDirectory, + "distributable-smoke-darwin-universal.json" + ), + "utf8" + ) + ); + expect(report).toMatchObject({ + artifacts: [ + { + passed: true, + signatureVerified: true, + architectures, + launchServicesVerified: true, + }, + ], + }); +} + +afterEach(() => { + for (const directory of directories.splice(0)) { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +describe("distributable smoke architecture selection", () => { + it("accepts only the explicit Rosetta diagnostic CLI flag", () => { + expect.assertions(5); + expect(parseDistributableSmokeArguments([])).toStrictEqual({ + includeRosetta: false, + }); + expect( + parseDistributableSmokeArguments(["--include-rosetta"]) + ).toStrictEqual({ + includeRosetta: true, + }); + for (const args of [ + ["--include-rosetta=false"], + ["--include-rosetta", "--include-rosetta"], + ["--arch", "x64"], + ]) { + expect(() => parseDistributableSmokeArguments(args)).toThrow( + "Usage:" + ); + } + }); + + it.each(invalidArchitectureRequests)( + "rejects invalid architecture requests %s/%s on %s with includeRosetta=%s before launching", + (platform, arch, hostArch, includeRosetta) => { + expect.assertions(3); + const run = vi.fn(); + const smoke = vi.fn(); + expect(() => + runDistributableSmoke( + { + platform, + arch, + hostArch, + includeRosetta, + version: "30.0.3", + releaseDirectory: "unused", + }, + { run, smoke } + ) + ).toThrow(/requires|Unsupported|boolean/u); + expect(run).not.toHaveBeenCalled(); + expect(smoke).not.toHaveBeenCalled(); + } + ); + + it.each(universalScenarios)( + "verifies all signatures and launches the requested Universal slices and native LaunchServices: $hostArch, Rosetta=$includeRosetta", + (scenario) => { + expect.assertions(10); + const releaseDirectory = makeUniversalRelease(); + const capture = makeLaunchCapture(); + expect( + runDistributableSmoke( + { + arch: "universal", + platform: "darwin", + hostArch: scenario.hostArch, + ...(scenario.includeRosetta + ? { includeRosetta: true } + : {}), + environment: { FFV_PACKAGED_SMOKE_TIMEOUT_MS: "60000" }, + version: "30.0.3", + releaseDirectory, + }, + capture + ) + ).toBe(0); + expectVerifiedLaunches(capture, scenario); + expectNativeEvidence(releaseDirectory, scenario.architectures); + } + ); +}); diff --git a/tests/unit/packaging/universalNativeWorkflow.test.ts b/tests/unit/packaging/universalNativeWorkflow.test.ts index d99d62bee..cdea6a030 100644 --- a/tests/unit/packaging/universalNativeWorkflow.test.ts +++ b/tests/unit/packaging/universalNativeWorkflow.test.ts @@ -133,20 +133,12 @@ describe("Universal DMG native verification workflows", () => { expect(jobs["release-verification"]).not.toHaveProperty("needs"); }); - it("validates the current run's source and bytes before native x64 and LaunchServices smoke", () => { - expect.assertions(12); + it("downloads the current run's exact source and artifact onto native Intel", () => { + expect.assertions(5); const consumer = readWorkflow("verify-universal-native-intel.yml").jobs[ "native-intel" ]; const steps = consumer?.steps ?? []; - const verifyIndex = steps.findIndex((step) => - step.run?.includes( - "node scripts/verify-universal-native-source.mjs" - ) - ); - const smokeIndex = steps.findIndex( - (step) => step.run === "node scripts/run-distributable-smoke.mjs" - ); const download = steps.find((step) => step.uses?.startsWith("actions/download-artifact@") ); @@ -160,6 +152,22 @@ describe("Universal DMG native verification workflows", () => { ); expect(download?.with?.["run-id"]).toBe("${{ github.run_id }}"); expect(download?.with?.["digest-mismatch"]).toBe("error"); + }); + + it("validates source and bytes before required native x64 and LaunchServices smoke", () => { + expect.assertions(7); + const consumer = readWorkflow("verify-universal-native-intel.yml").jobs[ + "native-intel" + ]; + const steps = consumer?.steps ?? []; + const verifyIndex = steps.findIndex((step) => + step.run?.includes( + "node scripts/verify-universal-native-source.mjs" + ) + ); + const smokeIndex = steps.findIndex( + (step) => step.run === "node scripts/run-distributable-smoke.mjs" + ); expect(verifyIndex).toBeGreaterThan(-1); expect(smokeIndex).toBeGreaterThan(verifyIndex); expect(steps[verifyIndex]?.env).toEqual({ From ff64834f38003cb43acf1afd0bba8593f7910514 Mon Sep 17 00:00:00 2001 From: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com> Date: Wed, 7 Oct 2026 21:31:09 -0400 Subject: [PATCH 08/12] =?UTF-8?q?=F0=9F=91=B7=20[build]=20Align=20workflow?= =?UTF-8?q?=20lint=20with=20native=20verification=20jobs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿ‘ท [build] Keep explicit per-workflow job limits aligned with the required native Intel consumer and provide its compliant workflow title and source-specific run name. --- .github/workflows/verify-universal-native-intel.yml | 3 ++- eslint.config.mjs | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/verify-universal-native-intel.yml b/.github/workflows/verify-universal-native-intel.yml index 294da8ce8..ba81c3843 100644 --- a/.github/workflows/verify-universal-native-intel.yml +++ b/.github/workflows/verify-universal-native-intel.yml @@ -1,4 +1,5 @@ -name: Verify Universal DMG on Native Intel +name: Verify Universal Package +run-name: Verify Universal DMG on Native Intel (${{ inputs.source-sha }}) on: workflow_call: diff --git a/eslint.config.mjs b/eslint.config.mjs index f11def319..ee00fa698 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -632,6 +632,12 @@ const config = [ }, { files: [".github/workflows/Build.yml"], + rules: { + "github-actions/max-jobs-per-action": ["error", 5], + }, + }, + { + files: [".github/workflows/release-rehearsal.yml"], rules: { "github-actions/max-jobs-per-action": ["error", 4], }, From d097494f2552c8f9cf64c37857757b7ea742a5d4 Mon Sep 17 00:00:00 2001 From: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com> Date: Wed, 7 Oct 2026 22:14:02 -0400 Subject: [PATCH 09/12] =?UTF-8?q?=F0=9F=94=92=20[build]=20Scope=20approved?= =?UTF-8?q?=20build-tool=20audit=20exceptions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿ”’ [build] Match the approved braces and sprintf-js advisories to exact assessed lock nodes, versions, integrity values, and development scope while preserving the root moderate and docs high thresholds. Remove the obsolete image-size exceptions. ๐Ÿ”’ [build] Validate raw npm results, grounded advisory graphs, process failures, scalar identities, and dependency scope before accepting any finding. Keep accepted findings and npm exit statuses visible and reject unexpected stderr. ๐Ÿงช [test] Add 41 focused regression cases for approved graphs, scope changes, malformed results, cycles, process errors, and native npm invocation. ๐Ÿ“ [docs] Record the approved exposure assessment, constraints, and removal requirements in the development guides. --- docs/DEVELOPMENT_GUIDE.md | 10 + docusaurus/docs/development/build-release.md | 4 + .../docs/development/dependency-audits.md | 78 ++++ docusaurus/sidebars.ts | 1 + scripts/audit-policy/docs.json | 154 ++++++++ scripts/audit-policy/root.json | 336 ++++++++++++++++++ scripts/lib/audit-evaluation.mjs | 140 ++++++++ scripts/lib/audit-policy.mjs | 116 ++++++ scripts/lib/audit-report.mjs | 181 ++++++++++ scripts/run-audit.mjs | 293 ++++++--------- tests/fixtures/audit-policy/auditFixture.ts | 149 ++++++++ tests/fixtures/audit-policy/docs.audit.json | 105 ++++++ tests/fixtures/audit-policy/docs.lock.json | 39 ++ tests/fixtures/audit-policy/root.audit.json | 158 ++++++++ tests/fixtures/audit-policy/root.lock.json | 77 ++++ tests/unit/packaging/runAudit.test.ts | 243 ++++++++----- tests/unit/packaging/runAuditPolicy.test.ts | 143 ++++++++ .../unit/packaging/runAuditValidation.test.ts | 152 ++++++++ 18 files changed, 2097 insertions(+), 282 deletions(-) create mode 100644 docusaurus/docs/development/dependency-audits.md create mode 100644 scripts/audit-policy/docs.json create mode 100644 scripts/audit-policy/root.json create mode 100644 scripts/lib/audit-evaluation.mjs create mode 100644 scripts/lib/audit-policy.mjs create mode 100644 scripts/lib/audit-report.mjs create mode 100644 tests/fixtures/audit-policy/auditFixture.ts create mode 100644 tests/fixtures/audit-policy/docs.audit.json create mode 100644 tests/fixtures/audit-policy/docs.lock.json create mode 100644 tests/fixtures/audit-policy/root.audit.json create mode 100644 tests/fixtures/audit-policy/root.lock.json create mode 100644 tests/unit/packaging/runAuditPolicy.test.ts create mode 100644 tests/unit/packaging/runAuditValidation.test.ts diff --git a/docs/DEVELOPMENT_GUIDE.md b/docs/DEVELOPMENT_GUIDE.md index eb08d35c8..a1ce3b300 100644 --- a/docs/DEVELOPMENT_GUIDE.md +++ b/docs/DEVELOPMENT_GUIDE.md @@ -502,6 +502,16 @@ verification outcome are visible after the job completes. In GitHub Actions, the verifier also appends the same status, artifact list, and verifier command results to the job summary through `GITHUB_STEP_SUMMARY`. +### Dependency Audits + +The release gate runs `npm run audit` with the existing moderate application +threshold and high documentation threshold. The approved temporary exceptions +cover only assessed `braces@3.0.3` build paths and application development +`sprintf-js@1.1.3` paths. Exact advisory, version, integrity, and dependency-scope +checks prevent these exceptions from accepting new findings or runtime use. +See [Dependency Audits](../docusaurus/docs/development/dependency-audits.md) for +the reachability assessment, constraints, and removal requirements. + ### Release Rehearsal Before tagging a release, run the manual GitHub Actions workflow **Release diff --git a/docusaurus/docs/development/build-release.md b/docusaurus/docs/development/build-release.md index c001a930e..f0a25bb8d 100644 --- a/docusaurus/docs/development/build-release.md +++ b/docusaurus/docs/development/build-release.md @@ -125,6 +125,10 @@ Run `npm run release:verify`, then dispatch **Release Rehearsal** on the candidate branch. Check every platform result and the Windows installer upgrade workflow before publishing. +The audit gate retains moderate application and high documentation thresholds. +Review the exact temporary build-tool exceptions and their removal conditions in +[Dependency Audits](./dependency-audits.md) before each release. + The packaged smoke test requires a fresh completion report after renderer initialization, preload IPC, real FIT decoding, and visible map rendering. Crashes, signals, timeouts, and missing or stale reports fail the test. diff --git a/docusaurus/docs/development/dependency-audits.md b/docusaurus/docs/development/dependency-audits.md new file mode 100644 index 000000000..cec4d4601 --- /dev/null +++ b/docusaurus/docs/development/dependency-audits.md @@ -0,0 +1,78 @@ +--- +id: dependency-audits +title: Dependency Audits +sidebar_label: Dependency Audits +sidebar_position: 6 +description: Dependency audit thresholds and narrowly scoped build-tool exceptions. +--- + +# Dependency Audits + +`npm run audit` checks the application and the separate Docusaurus dependency +graphs. The release gate requires it to pass. The application threshold is +**moderate** and the documentation threshold is **high**. + +## Approved Temporary Exceptions + +The maintainer approved the following exceptions on October 8, 2026 (UTC), after +reviewing their reachability in the current build tools. These exceptions accept +the assessed denial-of-service exposure; they do not fix the dependencies. + +| Dependency | Advisory | Approved scope | +| ------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `braces@3.0.3` | [GHSA-vfj7-8cjw-p6xm](https://github.com/advisories/GHSA-vfj7-8cjw-p6xm) | Assessed application development dependencies and separate documentation build paths | +| `sprintf-js@1.1.3` | [GHSA-hp3w-g68c-fv3c](https://github.com/advisories/GHSA-hp3w-g68c-fv3c) | Assessed application development dependencies only | + +The application production dependency audit reports no vulnerabilities. The +inspected packaged application contains neither dependency. Documentation tools +can be regular dependencies in the Docusaurus package; the documentation +exception is restricted to the assessed static-site build graph and does not +depend on those packages having npm's `dev` flag. + +The `braces` finding requires attacker-controlled nested glob patterns. The +reviewed callers receive repository-controlled include, ignore, or watch +patterns. Activity contents and filenames are not used as glob patterns. The +application's `sprintf-js` path belongs to Electron download/proxy logging; +reviewed callers use fixed format strings and put variable values in structured +log context. New untrusted pattern or format-string inputs require a fresh +assessment. + +## Gate Behavior + +The approved node inventories live in `scripts/audit-policy/root.json` and +`scripts/audit-policy/docs.json`. They are reviewed inputs to the gate and must +not be regenerated automatically from failing audit output. + +Exceptions match the exact advisory ID, package name, severity, vulnerable range, +installed version, lockfile integrity, and assessed dependency-node paths. Every affected +intermediary must remain in the reviewed scope. Application nodes must remain +development-only. Updating a parent package or moving a vulnerable dependency +into the application runtime can therefore invalidate an exception even if its +advisory identifier stays the same. + +An npm finding propagated through several packages is accepted only when all +causes at or above the existing threshold are explicitly approved and remain in +scope. Valid dependency cycles must lead to concrete advisories. Missing +references, cycles without an advisory, malformed reports, audit service errors, +process signals, and contradictory exit codes fail the gate. + +The gate retains npm's known warning that package-level `allowScripts` takes +precedence over `.npmrc` configuration. Only that exact diagnostic is recognized; +other stderr output fails validation. The wrapper does not rewrite user or global +registry, authentication, or lifecycle configuration. + +Below-threshold findings retain the existing threshold behavior. This policy +does not add exceptions for KaTeX, the documentation graph's moderate findings, +or the previously accepted `image-size` advisories. + +## Reassessment and Removal + +Before every release, check for compatible upstream fixes and re-evaluate the +current dependency graph and its inputs. Remove an exception when a compatible +fixed version is available, its dependency is removed, or its advisory no longer +appears in the fresh audit. Do not automatically expand the assessed versions, +integrities, package paths, or advisory list to make a dependency update pass. + +A changed severity, advisory range, package identity, dependency scope, or input +trust boundary requires a new assessment. Retain the negative regression tests +when removing an exception so new findings continue to block release. diff --git a/docusaurus/sidebars.ts b/docusaurus/sidebars.ts index 79762cb16..251e3e98e 100644 --- a/docusaurus/sidebars.ts +++ b/docusaurus/sidebars.ts @@ -109,6 +109,7 @@ const sidebars = { "development/module-development", "development/testing", "development/build-release", + "development/dependency-audits", ], label: "๐Ÿ› ๏ธ Development", link: { diff --git a/scripts/audit-policy/docs.json b/scripts/audit-policy/docs.json new file mode 100644 index 000000000..5ef0026c2 --- /dev/null +++ b/scripts/audit-policy/docs.json @@ -0,0 +1,154 @@ +{ + "advisories": [ + { + "name": "braces", + "range": "<=3.0.3", + "severity": "high", + "url": "https://github.com/advisories/GHSA-vfj7-8cjw-p6xm" + } + ], + "approvedAt": "2026-10-08", + "lockName": "fitfileviewer-docs", + "minimumSeverity": "high", + "nodes": { + "node_modules/@docusaurus/babel": { + "integrity": "sha512-aJ1hpGyvfkte3dDAfNbWM4biW4yWZBVz7TIGLZP+v+tWOBgxX3e0N5ZIXHIvmfNNXTI77pcHUx3KmtOk05Ze3Q==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/bundler": { + "integrity": "sha512-i0ZNcy0f0WhaOlYVgzLsWhIoEXO9kS3HRoKPtgE6vQtZUq7arKZaYdNBudr3mqCmd+TyOkwtwfHgs1ENj07r5g==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/core": { + "integrity": "sha512-EYByj6nk+aD9KeVxV6Hmo2/nAAT79P21Y82ycTBOBtrmqilloIbIEhgL2/8Xpt2Jz/pgNqHAwyusOGwmbKeJmA==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/mdx-loader": { + "integrity": "sha512-9Fd4V/SFjfrVQ0JH5EN0+iPWyFunvTeQE3gfyFeetqPaXMP0OylIjOw16dCuXG4NZJrYdBqwzjh18/h3gRi47w==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/plugin-content-blog": { + "integrity": "sha512-0cbEnNKf0InmLkhj/+nVRmqEnWEoOE8Mh+2x1qOXI0qYpCnphq4RXknVJ8BvybKRXqYVvbmdMfiJSup+k4tm5w==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/plugin-content-docs": { + "integrity": "sha512-Sqwl4FPoZBDrlY8I2VU2H8O0M91CHp9T8ToMSkTZmjvHCif+1laqfXi6sTk8IfyVS/trN5yNjcWd1bFsGB6W5Q==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/plugin-content-pages": { + "integrity": "sha512-h5R12sZ/vV9EPiVjvIl9YFCOwkpwXes7dQMYt3EvP6Pphu4amHxxTqWxf08Fl5DR8h+oZMbWpFTNw5vKEYfvzQ==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/plugin-css-cascade-layers": { + "integrity": "sha512-UkdvQby5OQUKWrw3lLnSTJXQ6VETaUVTuPQX9AABtmFm5h+ifEBx1OQ+LN726Q4byuwBf2ElHkf4qU4hTxdvRg==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/plugin-debug": { + "integrity": "sha512-8vbZNOSCpnsT57EY6CgN7sgRVmx3KTYwO8Uvo2pbxOyb8tbqAwtT9SslqaQ41HbA1v1hpn5RP7u5s2KvRwAFpQ==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/plugin-google-analytics": { + "integrity": "sha512-kMHMBK9j4VAtgd5owwrRLRIi0EjkrpXlX7ePj1+y68XfVZV9I1T4S+koPDm+Hfw2TtnyHvh0uNrDvjz+DjQGVA==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/plugin-google-gtag": { + "integrity": "sha512-Vt90nNFhtAChRe9+it1hcHFgFvETdSnOkL5Bma+p6E/yU2tAYrvvyk+gv+LJGM2ZUkyKuKXLRsZ2Lb0bO7+Vog==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/plugin-google-tag-manager": { + "integrity": "sha512-MLCffCldysi/R0nzJQP7ZWd0xAoGNnSTiVOo6TTR6mKVGFhE+/XArGe67ZcaZv1uytgQXoXs92VJrgVDrz80rQ==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/plugin-sitemap": { + "integrity": "sha512-PODkwg5XetLML3hU/3xpCKJUZ9cqExLaBnD/Fzzwj2VHogLeqnDisLIujae87zuze7T4mCm2A6KEqZkyiz07EQ==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/plugin-svgr": { + "integrity": "sha512-JgfT3jWM0TJ8Uw0cEcqxHpybngQY1vlBYpuuNO+gEh5iPh5Ar+vxq/u9CFrYsWeXy48BN7Db76Pzp2edNXUQ8A==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/preset-classic": { + "integrity": "sha512-a4B3VczmDl99zK0EufDQYomdJ186WDingjmDXxhN2PNPS9Ty/Y2M5CLFX1KQMRKqRTLiRDKfutzG5IY1FC/ceg==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/theme-classic": { + "integrity": "sha512-JqTSLQmqmA9uKWZsD5iwBGJ4JyKB4/yTw6PsSXVPRJG/6GAm/u+add9Iip+hvwP12/AnPNztrdxsI14NJW4KeA==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/theme-common": { + "integrity": "sha512-R9b/vMpK1yye6hNZTA6x/ivRv+at6GhxnXcxkpzCGzO1R1RwiquqiFg2wMFh6aqlJTpWRFKpFD2TzCDQcyOU0A==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/theme-live-codeblock": { + "integrity": "sha512-rBWmjCFaInkWENi4EjHX4lgwN6uBfVurN8SdK0evZ5LwjIiAdVRTRkmnWNPswiud3UfdSeNalaLQl62Ks9d+pA==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/theme-mermaid": { + "integrity": "sha512-Stssh5MYQJ+EdYugUXf+ZcpeJFQPKXf0KCd/SWp10o3CmXNaOoh5IEgVjVqY1e1XhQf3on4+Y4BnrMiD95E2SQ==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/theme-search-algolia": { + "integrity": "sha512-1msxllyhi/5m77JukXtp5UFnUAriwZIC1oJ7MTnpQpCwLTbclJi5BK5n28CTZuSXpQN2ewbbnqRgAhMM6c6ihg==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/utils": { + "integrity": "sha512-xx0W3eav2uW1NRIpuHJWNwLTC15xPNjU4Uxi9NSnd3swYC96BE3vFiT93SD8s24kmAAWNwgZwfZ2fghGZ01Lcw==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/utils-validation": { + "integrity": "sha512-sn8unbDfUL585NtR3cwHefPicOyaHvPaX7VD0aOg/siIxUBoKyKKaGEqzJZDS64mM43TnxurkYDtmB1wsJlZsw==", + "version": "3.10.2" + }, + "node_modules/@easyops-cn/docusaurus-search-local": { + "integrity": "sha512-PlMKmxuonvZ1C+/zJS1hJaF1xaxD1TsUvOMzpP6DdQMtZqmTaYjcLGM12ePzl0m1rp3AgfTBeDbFNHQhwnH/dA==", + "version": "0.55.3" + }, + "node_modules/braces": { + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "version": "3.0.3" + }, + "node_modules/chokidar": { + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "version": "3.6.0" + }, + "node_modules/copy-webpack-plugin": { + "integrity": "sha512-fX2MWpamkW0hZxMEg0+mYnA40LTosOSa5TqZ9GYIBzyJa9C3QUaMPSE2xAi/buNr8u89SfD9wHSQVBzrRa/SOQ==", + "version": "11.0.0" + }, + "node_modules/copy-webpack-plugin/node_modules/globby": { + "integrity": "sha512-Y1zNGV+pzQdh7H39l9zgB4PJqjRNqydvdYCDG4HFXM4XuvSaQQlEc91IU1yALL8gUTDomgBAfz3XJdmUS+oo0w==", + "version": "13.2.2" + }, + "node_modules/docusaurus-plugin-copy-page-button": { + "integrity": "sha512-OBWmUEFIqR3BJ5giae6D518b69ZfZQ5HKrazrY2IPA6tDNX2F3m1ejeyE0oqcVcE7GVkE+K0+vJ5T+kIos8u1w==", + "version": "0.8.4" + }, + "node_modules/docusaurus-plugin-llms": { + "integrity": "sha512-jYlj2HJ5+gu7oJZuJ83Hk8KlB65YlZZ/7UpHXiL7Qr+qpNBkVocmt2Molc6F3HNr5RqcfhWD/98CvgyNztg/ow==", + "version": "0.4.0" + }, + "node_modules/fast-glob": { + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "version": "3.3.3" + }, + "node_modules/globby": { + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "version": "11.1.0" + }, + "node_modules/http-proxy-middleware": { + "integrity": "sha512-RKzRWNPxUZqbuk3BC5mGVJbBnWgr+diEnjJexIOytFbBzDy88Fbh/YvBr3DsNrl1jYAfjWfpATEv0NO35FDuPQ==", + "version": "2.0.10" + }, + "node_modules/micromatch": { + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "version": "4.0.8" + }, + "node_modules/webpack-dev-server": { + "integrity": "sha512-HNLRmamRvVavZQ+avceZifmv8hmdUjg43t6MI4SqJDwFdW7RPQwH5vzGhDRZSX59SgfbeHhLnq3g+uooWo7pVw==", + "version": "5.2.6" + } + }, + "removalCondition": "Remove when a compatible upstream fix is available; reassess before every release and whenever affected graph scope or exposure changes.", + "requireDevOnly": false, + "scope": "docs" +} diff --git a/scripts/audit-policy/root.json b/scripts/audit-policy/root.json new file mode 100644 index 000000000..7094109a8 --- /dev/null +++ b/scripts/audit-policy/root.json @@ -0,0 +1,336 @@ +{ + "advisories": [ + { + "name": "braces", + "range": "<=3.0.3", + "severity": "high", + "url": "https://github.com/advisories/GHSA-vfj7-8cjw-p6xm" + }, + { + "name": "sprintf-js", + "range": "<=1.1.3", + "severity": "moderate", + "url": "https://github.com/advisories/GHSA-hp3w-g68c-fv3c" + } + ], + "approvedAt": "2026-10-08", + "lockName": "fitfileviewer", + "minimumSeverity": "moderate", + "nodes": { + "node_modules/@codecov/bundle-analyzer": { + "integrity": "sha512-SkL0+Ccs6VuHIA9Bxb8/J110CffRXpqtKt7m18FTWC0P6gDKEsoieUerDdcd6K9BFKujj6gaUdTt5i4I/v8GTA==", + "version": "2.0.1" + }, + "node_modules/@csstools/stylelint-formatter-github": { + "integrity": "sha512-LAzHf7W1FmBNi/cA4n7ZqGW063UK+KZgcaoAmtkJZlbAxRlnthA/VEojmO06+eBAczKMMU1yslqsDh6Etvok8g==", + "version": "2.0.0" + }, + "node_modules/@docusaurus/eslint-plugin": { + "integrity": "sha512-dLUOOA4SBR1IawNQxaPBO4+h5swGJIhh39MitDtyKJh4GFl+srLk6xs417YH/+aQCNemm1rv+cRt5RVzQekE8w==", + "version": "3.10.2" + }, + "node_modules/@docusaurus/eslint-plugin/node_modules/@typescript-eslint/typescript-estree": { + "integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==", + "version": "5.62.0" + }, + "node_modules/@docusaurus/eslint-plugin/node_modules/@typescript-eslint/utils": { + "integrity": "sha512-n8oxjeb5aIbPFEtmQxQYOLI0i9n5ySBEY/ZEHHZqKQSFnxio1rv6dthascc9dLuwrL0RC5mPCxB7vnAVGAYWAQ==", + "version": "5.62.0" + }, + "node_modules/@double-great/stylelint-a11y": { + "integrity": "sha512-tzCK6ItlIiUJwGnATxO54ELtSaQwiMtghhIy6G5umOsp6wTPyMfTUKXt9g/TIGO2+APG1NM4V/V3aiG5W6R8Rw==", + "version": "3.5.2" + }, + "node_modules/@next/eslint-plugin-next": { + "integrity": "sha512-szW9y2Aumu4z88YXfTzcFsgUAg2k64uzbtcO5L9f1AKS4w/GUKJcbFllRflROVyNPgJtGOnvNxiyp3v6b+prIA==", + "version": "16.3.4" + }, + "node_modules/@secretlint/secretlint-rule-pattern": { + "integrity": "sha512-O5FasZpXq8WZ6GPcqiPYDxyJTr1Bx+WjXC3lXd3mpbYb1abEuETDLNuu3AWOtp2Bh39TXQVvj40lX+NcWzus6Q==", + "version": "13.0.5" + }, + "node_modules/@stylelint-types/stylelint-order": { + "integrity": "sha512-jc9elOvmn2UoL+wzzWtHmezhAZPOJn6hWQ9Prct+FOxzY9XafssQEOUcs4T4DJ2RA+rxk9GockujWjbGtqj4FA==", + "version": "8.1.1" + }, + "node_modules/@stylelint-types/stylelint-stylistic": { + "integrity": "sha512-0TTMsiD/upUM5339xYovkWlTD7tN9UMHCD4ul8/qtFOeqwCmttfv7/i8gMQrvGVsZ+EqSxzyQKNn17Rroarwmg==", + "version": "5.1.0" + }, + "node_modules/@stylistic/stylelint-plugin": { + "integrity": "sha512-xbyxPeaO9Vns6A8/0MQV6PzZ5nNZCoGV4q1ERaNd5EBAKlWt+YcpaPapNYNUkZaiQg98+xPbikdA58ehquJG3g==", + "version": "5.3.0" + }, + "node_modules/app-builder-lib": { + "integrity": "sha512-wfL7EhujuODDW3uMSD8RPcr/MLzmT0dmpVfWV0wFUWXI0rIdaukzAJ7EFUSyHXOpxuBZqaIGlQt6VeQhtHhetw==", + "version": "26.17.0" + }, + "node_modules/app-builder-lib/node_modules/@electron/get": { + "integrity": "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==", + "version": "3.1.0" + }, + "node_modules/astro-eslint-parser": { + "integrity": "sha512-+QDcgc7e+au6EZ0YjMmRRjNoQo5bDMlaR45aWDoFsuxQTCM9qmCHRoiKJPELgckJ8Wmr7vcfpa9eCDHBFh6G4w==", + "version": "1.4.0" + }, + "node_modules/astro-eslint-parser/node_modules/fast-glob": { + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "version": "3.3.3" + }, + "node_modules/braces": { + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "version": "3.0.3" + }, + "node_modules/chokidar": { + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "version": "3.6.0" + }, + "node_modules/dmg-builder": { + "integrity": "sha512-EAw1f2iGkICmUvAVBOjm7v5mxJdB7/+OZSycHFhKBimiTkCXtvkCC6wBKzHo7ZQYi58C2MmwIleRbgRnROlK2Q==", + "version": "26.17.0" + }, + "node_modules/electron-builder": { + "integrity": "sha512-iYHBRiagS9sDIbZx1ZD113f5rEGQvtpvTvHf70ovHKJ8mRvxwIkWX7JCwfmVQmVS4eX735p7TZmoxHnBPwF3vA==", + "version": "26.17.0" + }, + "node_modules/electron-builder-squirrel-windows": { + "integrity": "sha512-uyh+D+B0m12qCRp9c/7dwBirHTh7JcvAzj5eTEbb4dXPPGAhYPx1nozzbu1fC6AdULfat6ZNqgWhipTFpb82lQ==", + "version": "26.17.0" + }, + "node_modules/eslint-config-nick2bad4u": { + "integrity": "sha512-nV2sUWDHcXTSPJuHgz68JLsGq7i9iRoiT6+KygVLpWFMh6LMpWIjvS+rDYIb1fQmoWUOY0UuB+JnOv0i92aK2w==", + "version": "1.2.7" + }, + "node_modules/eslint-plugin-astro": { + "integrity": "sha512-89xpAn528UKCdmyysbg0AHHqi6sqcK89wXnJIpu4F0mFBN03zATEBNK7pRtMfl6gwtMOm5ECXs+Wz5qDHhwTFw==", + "version": "1.7.0" + }, + "node_modules/eslint-plugin-repo": { + "integrity": "sha512-W6bBrsVvp7+/0K+zUEzzGOQGm2rJdaKw0py6UldUJUiVHXqK5+tUHSXM+srnxNH5XqaGL4NdDqXbDERA4gnC8Q==", + "version": "1.0.12" + }, + "node_modules/eslint-plugin-stylelint-2": { + "integrity": "sha512-zr1uU426sK91vJqpqOYCtr+ujYVmQLWxdWgyQ6/ccgz7DqsrHWQ5PBiLOMvla/EgUraP3I9Sog9gTqPamU8EpQ==", + "version": "1.1.7" + }, + "node_modules/eslint-plugin-undefined-css-classes": { + "integrity": "sha512-Zh+4qZL04e1XjGe0ZJib1ntUbBGdy8VSsGJMVuHJbgxk3MgFK2chB85aQoGNLPkcOoIIB4DwXmj6+CUxuF1zfA==", + "version": "0.1.5" + }, + "node_modules/fast-glob": { + "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==", + "version": "3.3.1" + }, + "node_modules/global-agent": { + "integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==", + "version": "3.0.0" + }, + "node_modules/global-agent/node_modules/roarr": { + "integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==", + "version": "2.15.4" + }, + "node_modules/globby": { + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "version": "11.1.0" + }, + "node_modules/micromatch": { + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "version": "4.0.8" + }, + "node_modules/npm-package-json-lint": { + "integrity": "sha512-KvphpY9PVN8Le6spIXH9LXdSPPiaeG6HBk/PRCmtOn8vY/gsnUpXCfFBZBRUpPMVjv7dsfCU2jOPao4ao3Z2Hg==", + "version": "10.5.1" + }, + "node_modules/npm-package-json-lint-config-nick2bad4u": { + "integrity": "sha512-FIAZB+NaPBJJjt6YCemnigLcdrwlxx6p4E6zmqfk1KA2x1fxthk9OIHRwLdvYhJCD5DBrIKXJjhTKShTSwTwJw==", + "version": "1.0.4" + }, + "node_modules/remark-cli": { + "integrity": "sha512-2NAEOACoTgo+e+YAaCTODqbrWyhMVmlUyjxNCkTrDRHHQvH6+NbrnqVvQaLH/Q8Ket3v90A43dgAJmXv8y5Tkw==", + "version": "12.0.1" + }, + "node_modules/remark-config-nick2bad4u": { + "integrity": "sha512-eIOjqCjFrKXWBUUBH0pFvmetwPGvERoLODhOhpI/8IkUXypnvBfbkTgxeQomQPoskzRLG+XJPzKQpl7b2lc5PA==", + "version": "1.1.4" + }, + "node_modules/secretlint-config-nick2bad4u": { + "integrity": "sha512-SHiHpnu2s29c5F33VnZUkWQpH3jA/V0ZtUB8k9apEJojtIUmkkJI/MfWXgObVKf065ifEG458aWWUE8meNO3Dw==", + "version": "1.1.2" + }, + "node_modules/sprintf-js": { + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", + "version": "1.1.3" + }, + "node_modules/stylelint": { + "integrity": "sha512-xVQwyiuxALUBNB2fBe0tmNemg9KqLtdj3T64mioFDar79B2cU8LIyz+3KL6LdiHs9NkeNfwxpKSaIVOY8f112g==", + "version": "17.14.1" + }, + "node_modules/stylelint-config-alphabetical-order": { + "integrity": "sha512-oI72VCiqyuB8X0JZzDTPDoX1eicWwUCrvtXaWiiLNuz6pSnt9yL+ZE+q08BQSZdwlmtneG6eDo/XRCOaOX5ARg==", + "version": "2.0.0" + }, + "node_modules/stylelint-config-alphabetical-order/node_modules/stylelint-order": { + "integrity": "sha512-GWPei1zBVDDjxM+/BmcSCiOcHNd8rSqW6FUZtqQGlTRpD0Z5nSzspzWD8rtKif5KPdzUG68DApKEV/y/I9VbTw==", + "version": "7.0.1" + }, + "node_modules/stylelint-config-html": { + "integrity": "sha512-Lk1NPEdUxzHkPv3ehktjpiOk4MPaqQ3H8fkvhxdWlQpaZCm9ze0SoMbRQLqkUxEMfPE1G9/x968uxm/+d2njoA==", + "version": "2.0.0" + }, + "node_modules/stylelint-config-idiomatic-order": { + "integrity": "sha512-gJjT1nwhgnHS52+mRn+5Iw6keZIPRN4W+vbzct9Elb+tWOo61jC/CzXzAJHvvOYQZqUYItfs2aQ8fU5hnCvuGg==", + "version": "10.0.0" + }, + "node_modules/stylelint-config-idiomatic-order/node_modules/stylelint-order": { + "integrity": "sha512-0UuKo4+s1hgQ/uAxlYU4h0o0HS4NiQDud0NAUNI0aa8FJdmYHA5ZZTFHiV5FpmE3071e9pZx5j0QpVJW5zOCUA==", + "version": "6.0.4" + }, + "node_modules/stylelint-config-nick2bad4u": { + "integrity": "sha512-gK4+tOo+B7wf8dxAtXoGfHD297EO9JSj/Z7bI1LT29SbkKPsstEIa05wu8cLnAkkkoc95GMoADJkoVl5ecakpQ==", + "version": "1.0.20" + }, + "node_modules/stylelint-config-recess-order": { + "integrity": "sha512-ObYusdkXavm8ulgb5xvmU1l8wgCdveNYG12hOTUEdjS8bNhSRggl4or0mE0JaOnQz+Ve2xZemVpwqERCgJbntg==", + "version": "7.8.0" + }, + "node_modules/stylelint-config-recommended": { + "integrity": "sha512-mxgT2XY6YZ3HWWe3Di8umG6aBmWmHTblTgu/f10rqFXnyWxjKWwNdjSWkgkwCtxIKnqjSJzvFmPT5yabVIRxZg==", + "version": "18.0.0" + }, + "node_modules/stylelint-config-recommended-scss": { + "integrity": "sha512-x5DVehzJudcwF0od3sGpgkln2PLLranFE7twwbp7dqDINCyZvwzFkMc6TLhNOvazRiVBJYATQLouJY0xPGB8WA==", + "version": "17.0.1" + }, + "node_modules/stylelint-config-recommended-vue": { + "integrity": "sha512-lLW7hTIMBiTfjenGuDq2kyHA6fBWd/+Df7MO4/AWOxiFeXP9clbpKgg27kHfwA3H7UNMGC7aeP3mNlZB5LMmEQ==", + "version": "1.6.1" + }, + "node_modules/stylelint-config-sass-guidelines": { + "integrity": "sha512-YJT0X8h0OqyEo7ys3EycV5CGWt2rrkEYE8sHSN6sFnrxbXvHiy4KJFHDOWfyb3eWR6wtYpM+yIyvR2Plc8+pCg==", + "version": "13.0.0" + }, + "node_modules/stylelint-config-standard": { + "integrity": "sha512-EznGJxOUhtWck2r6dJpbgAdPATIzvpLdK9+i5qPd4Lx70es66TkBPljSg4wN3Qnc6c4h2n+WbUrUynQ3fanjHw==", + "version": "40.0.0" + }, + "node_modules/stylelint-config-standard-scss": { + "integrity": "sha512-uLJS6xgOCBw5EMsDW7Ukji8l28qRoMnkRch15s0qwZpskXvWt9oPzMmcYM307m9GN4MxuWLsQh4I6hU9yI53cQ==", + "version": "17.0.0" + }, + "node_modules/stylelint-config-tailwindcss": { + "integrity": "sha512-IeIMivgaB1kxPBgllMzBqyv0g61IwFxxZKo/fDDelfZ/JtPPlSBT04VuOCslk6PIaq5GQvdRnHOP1K3HpxSkeg==", + "version": "1.0.1" + }, + "node_modules/stylelint-declaration-block-no-ignored-properties": { + "integrity": "sha512-3ml4NgSW6nkHQrk+/ounU7Qljfb7e7FayHzU7Mry6rF9X28RXyPLD2bNn4QVOO7t98d5EGCCVkNbHCZSx+bNUQ==", + "version": "3.0.0" + }, + "node_modules/stylelint-declaration-strict-value": { + "integrity": "sha512-KSQTXfWboeebH0tw3bZq5ZPLnkUBHvz9PtzAmIaqU7egLvjN7wU/F0tukFBVyGDKQEfDlLNGDNvhI/O1+6KipQ==", + "version": "1.12.1" + }, + "node_modules/stylelint-define-config": { + "integrity": "sha512-0/A1yQCf1vfeS7j7hoTomYvxcT5GuHIOtaKk9GzVNuCgNotNLqhStwODmjjUHGj4AtfCsUBzNiYiz3CMsOpqrw==", + "version": "17.14.0" + }, + "node_modules/stylelint-find-new-rules": { + "integrity": "sha512-N+bn85Dr+QirtvxluIZusPDONafdTeX43qnE2QnDUzt3oqNpFGLRCPN3cPhKmV2qtZn/RjsA5b6+/vczYi2F9g==", + "version": "6.1.0" + }, + "node_modules/stylelint-formatter-gitlab-code-quality-report": { + "integrity": "sha512-CtSrZ782sS5bfjNA0RoX6WUrX2Tn46Bs9dXBF3IyjMFKwVmeAZJvoj0DAjueJ8WhEoK6UHnz6AyNDJBreppobw==", + "version": "1.1.0" + }, + "node_modules/stylelint-formatter-pretty": { + "integrity": "sha512-39nasPN8QNdMBq2eghI/SwpyVKx8kJGtmE/KJ5oFvCg0ZvZ5qjJbQgEulzC0gT70XZ+iRk7p1W5tE9IBQhFjPw==", + "version": "4.0.1" + }, + "node_modules/stylelint-gamut": { + "integrity": "sha512-tsNmkvzm4LbeUBOcLIn8A6aDGBanWwcg+3AlBoljlxz0rxxAC3ZHq/sHKso9YLbNlNvCDIMzw8KVtchStOSO8w==", + "version": "2.0.1" + }, + "node_modules/stylelint-group-selectors": { + "integrity": "sha512-t0FbKdKZFlbb2VFZ1cfU0+TUHlrPz0ORIuFCse1rVCvfYF0H75k4rRj544b1Lz6GTbdI3o1Yivotk8i8T6TvOA==", + "version": "1.0.10" + }, + "node_modules/stylelint-high-performance-animation": { + "integrity": "sha512-wzxxfxJFyL7UKc91427EHmi6gNRXB0cBdsyCfIuXZFRb6Xv1qw8elNbF61e/tJRoRcavAGsZICivVsHCD3Mhug==", + "version": "2.0.0" + }, + "node_modules/stylelint-media-use-custom-media": { + "integrity": "sha512-KmrROVhMXd217NM+9PciFp9wu4pNQNx9lpPCqYMBLOVJREi3MbziYJRMP9X5FlaCLfQmbk6so5KdGEzG+4Oe5Q==", + "version": "4.1.0" + }, + "node_modules/stylelint-no-browser-hacks": { + "integrity": "sha512-InPHdXdwCUw2K7YPpqkMKyPTPAWaECcbhRQYj7GwKOfCE3ZPF9WKNPb9S6WwsH406jWVhaezksRAYGRIVYz3pQ==", + "version": "2.0.3" + }, + "node_modules/stylelint-no-unsupported-browser-features": { + "integrity": "sha512-sLEe6NUFoWL2vGt6IKKllQEKfKgVxmvTBFs1JVMHKKLWzxtWAXaqSxJvH+j0URM4vLQQqzC/wXc9Kp3XBNKdBw==", + "version": "8.1.1" + }, + "node_modules/stylelint-order": { + "integrity": "sha512-LqsEB6VggJuu5v10RtkrQsBObcdwBE7GuAOlwfc/LR3VL/w8UqKX2BOLIjhyGt0Gne/njo7gRNGiJAKhfmPMNw==", + "version": "8.1.1" + }, + "node_modules/stylelint-plugin-container-query-sanity": { + "integrity": "sha512-3AdoHS3mA0Vv9yRR4QWspE+J/Yq6qaY3yQJJc7YS+ZGkgN35LX46llTc612lxNxPNDgxItak3tt1VMUxAp/8wA==", + "version": "0.1.4" + }, + "node_modules/stylelint-plugin-css-performance-budget": { + "integrity": "sha512-bakOPdkgevTvXeIe3L5wdqAy/fdMtOBcCTOfEcvBz6MutORCmcHtouLr6/w8uYsu/YRXUdbLbHwxqYdmj7Wa9w==", + "version": "2.0.7" + }, + "node_modules/stylelint-plugin-defensive-css": { + "integrity": "sha512-DhZYjUX3AjMCn6UQx3ksxbvhET7lt7jBu+5q1Z7Db5Lc15aDOIZX4usvSAXQQpnk3SMxGCS20abPr2ipU++iGA==", + "version": "2.9.6" + }, + "node_modules/stylelint-plugin-docusaurus": { + "integrity": "sha512-DlsyJqnavFdR+ZMmA6553J+nfvCGVXWU0HvgzD8GDddDIy669++sJsJ7vkBBt2FUV5PE3znNysk3nwkHPv1u4Q==", + "version": "2.0.5" + }, + "node_modules/stylelint-plugin-font": { + "integrity": "sha512-KUXNtgLh3dAhjB7TKQ5N7k4PE5P1EdJG9gAUUwpqALrWiyZQJ8EzQn27CIlG93Z98U4XJ0qcxPre1tX65ZdN6A==", + "version": "1.1.7" + }, + "node_modules/stylelint-plugin-grid": { + "integrity": "sha512-wugtaZ7SAmIJqDBiNVDpQL9RLv+Ar9emeT0HZ2hER2137xPc0IWdqkU0+yNp+rJtc8urIOocGbKlrQgJsmoyKA==", + "version": "1.0.6" + }, + "node_modules/stylelint-plugin-use-baseline": { + "integrity": "sha512-8FyloHsa3YXt0y3wVYToV1frYgX/p7GYOCV7EjV/BjiNFzzGnqJvcKK94vNBfI/BOUi1d8L+VdgBqx5zNMF3uw==", + "version": "1.4.6" + }, + "node_modules/stylelint-prettier": { + "integrity": "sha512-B6V0oa35ekRrKZlf+6+jA+i50C4GXJ7X1PPmoCqSUoXN6BrNF6NhqqhanvkLjqw2qgvrS0wjdpeC+Tn06KN3jw==", + "version": "5.0.3" + }, + "node_modules/stylelint-scss": { + "integrity": "sha512-6E79Bachv0Iz0gqRUZgdqdXCsiq26DWBWIBNHYtjTmAp3wJu6cp/I37VfW7BPntmh2puF3bY09XWl4HZGrLhzw==", + "version": "7.2.0" + }, + "node_modules/stylelint-use-nesting": { + "integrity": "sha512-1YeOfI7pMucTO0GKAiBOz12EaNN5qzbbboAli/jDC47nTfNsOVd9c4WmTshQnnaMDRF8ZZ0ovGzBjw0WUE4tvg==", + "version": "6.0.2" + }, + "node_modules/stylelint-value-no-unknown-custom-properties": { + "integrity": "sha512-eQ1zidKD5t9zMEaskjGUY4W47lH76qMlmsDSmCAPEwtaGzB4Ls7ORTfysC1D6hamp2zFC+vN1vpQ+GFz3Tw3lw==", + "version": "6.1.1" + }, + "node_modules/stylelint/node_modules/fast-glob": { + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "version": "3.3.3" + }, + "node_modules/stylelint/node_modules/globby": { + "integrity": "sha512-c8B/VNLmxRcmqqenRA9t+9IyOjf9+V6lTxPaUJLqOCONdQkWZ0ETYgX0qbtJqPsgCNusT9MZ5Jeidw8Eb9tn2g==", + "version": "16.2.4" + }, + "node_modules/unified-args": { + "integrity": "sha512-WEQghE91+0s3xPVs0YW6a5zUduNLjmANswX7YbBfksHNDGMjHxaWCql4SR7c9q0yov/XiIEdk6r/LqfPjaYGcw==", + "version": "11.0.1" + } + }, + "removalCondition": "Remove when a compatible upstream fix is available; reassess before every release and whenever affected graph scope or exposure changes.", + "requireDevOnly": true, + "scope": "root" +} diff --git a/scripts/lib/audit-evaluation.mjs b/scripts/lib/audit-evaluation.mjs new file mode 100644 index 000000000..1871d6735 --- /dev/null +++ b/scripts/lib/audit-evaluation.mjs @@ -0,0 +1,140 @@ +import { + parseCapturedAudit, + requireAuditCondition, + severityRank, + validateAuditReport, +} from "./audit-report.mjs"; +import { + advisoryScopeMatches, + lockScopeMatches, + validateAuditPolicy, +} from "./audit-policy.mjs"; + +function rememberAdvisory(leaves, via) { + const key = `${via.name}|${via.url}`; + requireAuditCondition( + !leaves.has(key) || + JSON.stringify(leaves.get(key)) === JSON.stringify(via), + `Conflicting advisory metadata: ${key}` + ); + leaves.set(key, via); +} + +export function collectReachableCauses(vulnerabilities, start) { + const visited = new Set(); + const leaves = new Map(); + const pending = [start]; + while (pending.length > 0) { + const name = pending.pop(); + if (visited.has(name)) continue; + visited.add(name); + for (const via of vulnerabilities[name].via) { + if (typeof via === "string") pending.push(via); + else rememberAdvisory(leaves, via); + } + } + return { packages: [...visited], leaves: [...leaves.values()] }; +} + +function getGroundedReachability(vulnerabilities) { + const reachability = new Map(); + for (const [name, item] of Object.entries(vulnerabilities)) { + const causes = collectReachableCauses(vulnerabilities, name); + requireAuditCondition( + causes.leaves.length > 0, + `Ungrounded advisory component: ${name}` + ); + const leafRank = Math.max( + ...causes.leaves.map((leaf) => severityRank[leaf.severity]) + ); + requireAuditCondition( + severityRank[item.severity] === leafRank, + `Audit severity contradicts reachable advisory causes: ${name}` + ); + reachability.set(name, causes); + } + return reachability; +} + +function classifyVulnerability(name, context) { + const { report, lock, policy, threshold, reachability } = context; + const causes = reachability.get(name); + const relevantLeaves = causes.leaves.filter( + (leaf) => severityRank[leaf.severity] >= threshold + ); + const unacceptedLeaf = relevantLeaves.some( + (leaf) => !advisoryScopeMatches(leaf, report, lock, policy) + ); + const relevantPackages = causes.packages.filter((dependency) => + reachability + .get(dependency) + .leaves.some((leaf) => severityRank[leaf.severity] >= threshold) + ); + const outOfScope = relevantPackages.some( + (dependency) => + !lockScopeMatches( + dependency, + report.vulnerabilities[dependency], + lock, + policy + ) + ); + return unacceptedLeaf || outOfScope ? "blocked" : "accepted"; +} + +function classifyReport(report, lock, policy, reachability) { + const threshold = severityRank[policy.minimumSeverity]; + const result = { accepted: [], blocked: [], belowThreshold: [] }; + for (const [name, item] of Object.entries(report.vulnerabilities)) { + const classification = + severityRank[item.severity] < threshold + ? "belowThreshold" + : classifyVulnerability(name, { + report, + lock, + policy, + threshold, + reachability, + }); + result[classification].push(name); + } + for (const names of Object.values(result)) names.sort(); + return result; +} + +function getAcceptedAdvisories(accepted, reachability, threshold) { + const urls = new Set(); + for (const name of accepted) { + for (const leaf of reachability.get(name).leaves) { + if (severityRank[leaf.severity] >= threshold) urls.add(leaf.url); + } + } + return [...urls].sort(); +} + +export function evaluateCapturedAudit(result, lock, policy) { + const report = parseCapturedAudit(result); + validateAuditReport(report, lock); + validateAuditPolicy(policy, lock); + const threshold = severityRank[policy.minimumSeverity]; + const rawWouldBlock = Object.values(report.vulnerabilities).some( + (item) => severityRank[item.severity] >= threshold + ); + requireAuditCondition( + result.status === (rawWouldBlock ? 1 : 0), + "Audit exit code contradicts report threshold" + ); + const reachability = getGroundedReachability(report.vulnerabilities); + const classified = classifyReport(report, lock, policy, reachability); + return { + scope: policy.scope, + minimumSeverity: policy.minimumSeverity, + rawStatus: result.status, + acceptedAdvisories: getAcceptedAdvisories( + classified.accepted, + reachability, + threshold + ), + ...classified, + }; +} diff --git a/scripts/lib/audit-policy.mjs b/scripts/lib/audit-policy.mjs new file mode 100644 index 000000000..f40da9521 --- /dev/null +++ b/scripts/lib/audit-policy.mjs @@ -0,0 +1,116 @@ +import { + isRecord, + isSeverity, + packageNameForNode, + requireAuditCondition, +} from "./audit-report.mjs"; + +const scopes = Object.freeze({ + root: { minimumSeverity: "moderate", lockName: "fitfileviewer" }, + docs: { minimumSeverity: "high", lockName: "fitfileviewer-docs" }, +}); + +function validatePolicyAdvisories(advisories) { + requireAuditCondition( + Array.isArray(advisories), + "Missing policy advisories" + ); + const urls = new Set(); + for (const advisory of advisories) { + requireAuditCondition(isRecord(advisory), "Malformed policy advisory"); + requireAuditCondition( + typeof advisory.name === "string" && + typeof advisory.range === "string", + "Malformed policy advisory identity" + ); + requireAuditCondition( + isSeverity(advisory.severity), + "Malformed policy advisory severity" + ); + requireAuditCondition( + typeof advisory.url === "string" && !urls.has(advisory.url), + "Missing or duplicate policy advisory URL" + ); + urls.add(advisory.url); + } +} + +function validatePolicyNodes(nodes) { + requireAuditCondition( + isRecord(nodes), + "Missing assessed policy lock nodes" + ); + for (const [node, identity] of Object.entries(nodes)) { + packageNameForNode(node); + requireAuditCondition( + isRecord(identity), + `Malformed policy node ${node}` + ); + requireAuditCondition( + typeof identity.version === "string" && identity.version.length > 0, + `Missing assessed version for ${node}` + ); + requireAuditCondition( + typeof identity.integrity === "string" && + identity.integrity.length > 0, + `Missing assessed integrity for ${node}` + ); + } +} + +export function validateAuditPolicy(policy, lock) { + requireAuditCondition(isRecord(policy), "Missing audit policy"); + requireAuditCondition( + policy.scope === "root" || policy.scope === "docs", + "Unknown audit policy scope" + ); + const expected = scopes[policy.scope]; + requireAuditCondition( + policy.minimumSeverity === expected.minimumSeverity, + "Policy changes an existing audit threshold" + ); + requireAuditCondition( + policy.lockName === expected.lockName && + lock.name === expected.lockName, + "Wrong workspace lockfile" + ); + requireAuditCondition( + policy.requireDevOnly === (policy.scope === "root"), + "Root policy must remain dev-only; docs must retain its separate build scope" + ); + validatePolicyAdvisories(policy.advisories); + validatePolicyNodes(policy.nodes); +} + +export function lockScopeMatches(name, item, lock, policy) { + const expectedNodes = Object.keys(policy.nodes).filter( + (node) => packageNameForNode(node) === name + ); + if (expectedNodes.length !== item.nodes.length) return false; + return item.nodes.every((node) => { + if (!Object.hasOwn(policy.nodes, node)) return false; + const assessed = policy.nodes[node]; + const locked = lock.packages[node]; + return ( + locked.version === assessed.version && + locked.integrity === assessed.integrity && + (!policy.requireDevOnly || locked.dev === true) + ); + }); +} + +export function advisoryScopeMatches(leaf, report, lock, policy) { + const approved = policy.advisories.find((entry) => entry.url === leaf.url); + if (!approved) return false; + return ( + approved.name === leaf.name && + approved.severity === leaf.severity && + approved.range === leaf.range && + lockScopeMatches( + leaf.name, + report.vulnerabilities[leaf.name], + lock, + policy + ) + ); +} diff --git a/scripts/lib/audit-report.mjs b/scripts/lib/audit-report.mjs new file mode 100644 index 000000000..a13e1cd7e --- /dev/null +++ b/scripts/lib/audit-report.mjs @@ -0,0 +1,181 @@ +export const severityRank = Object.freeze({ + info: 0, + low: 1, + moderate: 2, + high: 3, + critical: 4, +}); + +export const isRecord = (value) => + value !== null && typeof value === "object" && !Array.isArray(value); + +export const isSeverity = (value) => + typeof value === "string" && Object.hasOwn(severityRank, value); + +export const npmScriptPrecedenceWarning = + "npm warn install-scripts .npmrc allow-scripts setting is being ignored because package.json declares its own allowScripts field"; + +export function requireAuditCondition(condition, message) { + if (!condition) throw new Error(message); +} + +export function packageNameForNode(node) { + requireAuditCondition(typeof node === "string", "Invalid lock node path"); + const segments = node.split("/"); + requireAuditCondition( + node.startsWith("node_modules/") && + !node.includes("\\") && + !segments.some((segment) => + [ + "", + ".", + "..", + ].includes(segment) + ), + `Unsafe lock node ${node}` + ); + return node.slice( + node.lastIndexOf("node_modules/") + "node_modules/".length + ); +} + +function validateAdvisory(via, name) { + requireAuditCondition(isRecord(via), `Malformed advisory for ${name}`); + requireAuditCondition( + via.name === name && via.dependency === name, + `Advisory package identity disagrees for ${name}` + ); + requireAuditCondition( + isSeverity(via.severity) && typeof via.range === "string", + `Malformed advisory severity or range for ${name}` + ); + requireAuditCondition( + typeof via.url === "string" && + /^https:\/\/github\.com\/advisories\/GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/u.test( + via.url + ), + `Unknown advisory URL for ${name}` + ); +} + +function validateCauses(item, vulnerabilities) { + requireAuditCondition( + Array.isArray(item.via) && item.via.length > 0, + `Missing advisory causes for ${item.name}` + ); + for (const via of item.via) { + if (typeof via === "string") { + requireAuditCondition( + Object.hasOwn(vulnerabilities, via), + `Missing advisory reference ${via}` + ); + } else validateAdvisory(via, item.name); + } +} + +function validateNodes(item, lock) { + requireAuditCondition( + Array.isArray(item.nodes) && item.nodes.length > 0, + `Missing lock nodes for ${item.name}` + ); + requireAuditCondition( + new Set(item.nodes).size === item.nodes.length, + `Duplicate lock nodes for ${item.name}` + ); + for (const node of item.nodes) { + requireAuditCondition( + packageNameForNode(node) === item.name, + `Audit package and lock node disagree: ${item.name}/${node}` + ); + requireAuditCondition( + Object.hasOwn(lock.packages, node) && + isRecord(lock.packages[node]) && + typeof lock.packages[node].version === "string", + `Missing lock node ${node}` + ); + } +} + +function validateSummary(report) { + const counts = report.metadata?.vulnerabilities; + requireAuditCondition(isRecord(counts), "Missing audit summary metadata"); + const items = Object.values(report.vulnerabilities); + requireAuditCondition( + counts.total === items.length, + "Audit summary disagrees with vulnerability nodes" + ); + for (const severity of Object.keys(severityRank)) { + requireAuditCondition( + counts[severity] === + items.filter((item) => item.severity === severity).length, + `Audit severity summary disagrees for ${severity}` + ); + } +} + +export function validateAuditReport(report, lock) { + requireAuditCondition(isRecord(report), "Malformed npm audit report"); + requireAuditCondition( + !Object.hasOwn(report, "error"), + "npm audit reported an infrastructure error" + ); + requireAuditCondition( + report.auditReportVersion === 2 && isRecord(report.vulnerabilities), + "Unsupported npm audit schema" + ); + requireAuditCondition( + isRecord(lock) && lock.lockfileVersion === 3 && isRecord(lock.packages), + "Unsupported or missing lockfile packages" + ); + for (const [name, item] of Object.entries(report.vulnerabilities)) { + requireAuditCondition( + isRecord(item), + `Malformed vulnerability ${name}` + ); + requireAuditCondition( + item.name === name, + `Vulnerability identity disagrees: ${name}` + ); + requireAuditCondition( + isSeverity(item.severity), + `Unknown severity for ${name}` + ); + validateCauses(item, report.vulnerabilities); + validateNodes(item, lock); + } + validateSummary(report); +} + +export function parseCapturedAudit(result) { + requireAuditCondition(isRecord(result), "Missing npm audit process result"); + requireAuditCondition( + !result.error && !result.signal, + "Audit process failed or was terminated" + ); + requireAuditCondition( + result.status === 0 || result.status === 1, + "Unexpected npm audit process status" + ); + requireAuditCondition( + result.stderr === undefined || typeof result.stderr === "string", + "Invalid npm audit stderr" + ); + const unexpectedLines = (result.stderr ?? "") + .split(/\r?\n/u) + .filter((line) => line !== "" && line !== npmScriptPrecedenceWarning); + requireAuditCondition( + unexpectedLines.length === 0, + `Unexpected npm audit stderr: ${result.stderr}` + ); + requireAuditCondition( + typeof result.stdout === "string", + "Missing npm audit JSON output" + ); + try { + return JSON.parse(result.stdout); + } catch (error) { + throw new Error("npm audit did not return valid JSON", { + cause: error, + }); + } +} diff --git a/scripts/run-audit.mjs b/scripts/run-audit.mjs index c9b71822c..40671f41d 100644 --- a/scripts/run-audit.mjs +++ b/scripts/run-audit.mjs @@ -1,222 +1,139 @@ import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; import process from "node:process"; import { pathToFileURL } from "node:url"; -const environment = { ...process.env }; -delete environment.npm_config_allow_scripts; -delete environment.NPM_CONFIG_ALLOW_SCRIPTS; +import { evaluateCapturedAudit } from "./lib/audit-evaluation.mjs"; +import { repositoryRoot } from "./lib/workspaces.mjs"; -const npmCliPath = process.env.npm_execpath; -const severityRank = { - critical: 4, - high: 3, - info: 0, - low: 1, - moderate: 2, -}; - -export const allowedDocusaurusAuditAdvisories = new Set([ - "GHSA-5p2g-fcmc-qvqq", - "GHSA-w3rx-r6r6-pgpr", -]); - -export function getBlockingAuditVulnerabilities( - auditReport, - allowedAdvisories, - minimumSeverity = "high" -) { - const vulnerabilities = getAuditVulnerabilities(auditReport); - const minimumRank = severityRank[minimumSeverity] ?? severityRank.high; - - return Object.entries(vulnerabilities) - .filter(([, vulnerability]) => - isBlockingVulnerability( - vulnerability, - vulnerabilities, - allowedAdvisories, - minimumRank - ) - ) - .map(([name]) => name) - .sort(); +export function readAuditJson(file) { + return JSON.parse(fs.readFileSync(file, "utf8")); } -function getAuditVulnerabilities(auditReport) { - if ( - !auditReport || - typeof auditReport !== "object" || - Array.isArray(auditReport) - ) { - throw new TypeError("npm audit returned an invalid report"); - } - - if ("error" in auditReport) { - throw new Error("npm audit reported an error instead of results"); - } - - const vulnerabilities = auditReport.vulnerabilities; - if ( - !vulnerabilities || - typeof vulnerabilities !== "object" || - Array.isArray(vulnerabilities) - ) { - throw new Error("npm audit report is missing vulnerability results"); - } - - return vulnerabilities; +export function getAuditEnvironment(environment) { + const sanitized = { ...environment }; + delete sanitized.npm_config_allow_scripts; + delete sanitized.NPM_CONFIG_ALLOW_SCRIPTS; + return sanitized; } -function isBlockingVulnerability( - vulnerability, - vulnerabilities, - allowedAdvisories, - minimumRank +export function resolveNpmAuditCommand( + args, + environment, + platform = process.platform ) { - const rank = severityRank[vulnerability.severity] ?? 0; - return ( - rank >= minimumRank && - !isAllowedVulnerability( - vulnerability, - vulnerabilities, - allowedAdvisories, - new Set() - ) + const adjacentCli = path.join( + path.dirname(process.execPath), + "node_modules", + "npm", + "bin", + "npm-cli.js" ); -} - -function runNpmAudit(arguments_, options = {}) { - const { command, commandArguments } = resolveNpmCommand(arguments_); - const result = spawnSync(command, commandArguments, { - cwd: process.cwd(), - encoding: options.captureJson ? "utf8" : undefined, - env: environment, - stdio: options.captureJson - ? [ - "ignore", - "pipe", - "pipe", - ] - : "inherit", - }); - - if (result.error) { - throw result.error; - } - - if (result.status === 0) { - return; - } - - if (!options.captureJson) { + const npmCli = + environment.npm_execpath ?? + (fs.existsSync(adjacentCli) ? adjacentCli : undefined); + if (npmCli) return { command: process.execPath, args: [npmCli, ...args] }; + if (platform === "win32") { throw new Error( - `npm audit failed with exit code ${result.status ?? 1}` + "Run npm run audit so the native Node npm CLI path is available" ); } - - handleCapturedAuditFailure(result, options); -} - -function resolveNpmCommand(arguments_) { - if (npmCliPath) { - return { - command: process.execPath, - commandArguments: [npmCliPath, ...arguments_], - }; - } - - return { - command: process.platform === "win32" ? "npm.cmd" : "npm", - commandArguments: arguments_, - }; + return { command: "npm", args }; } -function handleCapturedAuditFailure(result, options) { - const auditReport = parseAuditReport(result.stdout); - const blockingVulnerabilities = getBlockingAuditVulnerabilities( - auditReport, - options.allowedAdvisories, - options.minimumSeverity +function printAuditSummary(result, policy, log) { + log( + `[audit:${result.scope}] npm status ${result.rawStatus}; threshold ${result.minimumSeverity}; accepted ${result.accepted.length}, blocked ${result.blocked.length}, below threshold ${result.belowThreshold.length}.` ); - if (blockingVulnerabilities.length === 0) { - console.warn( - "Docusaurus audit contains only explicitly accepted, unpatched image-size advisories (GHSA-5p2g-fcmc-qvqq and GHSA-w3rx-r6r6-pgpr)." + if (result.accepted.length > 0) { + const advisories = policy.advisories + .filter((advisory) => + result.acceptedAdvisories.includes(advisory.url) + ) + .map( + (advisory) => + `${advisory.name} (${advisory.url.split("/").at(-1)})` + ); + log( + `[audit:${result.scope}] Applied exact assessed lock-node exceptions: ${advisories.join(", ")}.` ); - return; } - - process.stderr.write(result.stderr ?? ""); - process.stdout.write(result.stdout ?? ""); - throw new Error( - `npm audit found blocking vulnerabilities: ${blockingVulnerabilities.join(", ")}` - ); -} - -function isAllowedVulnerability( - vulnerability, - vulnerabilities, - allowedAdvisories, - visited -) { - if (!Array.isArray(vulnerability.via) || vulnerability.via.length === 0) { - return false; + if (result.blocked.length > 0) { + log( + `[audit:${result.scope}] Blocking dependency findings: ${result.blocked.join(", ")}` + ); } +} - return vulnerability.via.every((via) => { - if (typeof via === "string") { - if (visited.has(via) || !vulnerabilities[via]) { - return false; - } - - const nextVisited = new Set(visited); - nextVisited.add(via); - return isAllowedVulnerability( - vulnerabilities[via], - vulnerabilities, - allowedAdvisories, - nextVisited - ); - } - - if (!via || typeof via.url !== "string") { - return false; - } - - const advisoryId = via.url.split("/").at(-1); - return allowedAdvisories.has(advisoryId); +function runAuditScope(scope, dependencies) { + const { readJson, environment, runner, log, root } = dependencies; + const policy = readJson( + path.join(root, "scripts", "audit-policy", `${scope}.json`) + ); + const directory = scope === "root" ? root : path.join(root, "docusaurus"); + const lock = readJson(path.join(directory, "package-lock.json")); + const args = [ + "audit", + `--audit-level=${policy.minimumSeverity}`, + "--json", + ]; + const invocation = resolveNpmAuditCommand(args, environment); + const captured = runner(invocation.command, invocation.args, { + cwd: directory, + encoding: "utf8", + env: environment, + stdio: [ + "ignore", + "pipe", + "pipe", + ], + timeout: 300_000, + maxBuffer: 16 * 1024 * 1024, }); + if (captured.stderr) log(`[audit:${scope}] ${captured.stderr.trimEnd()}`); + const result = evaluateCapturedAudit(captured, lock, policy); + printAuditSummary(result, policy, log); + return result.blocked.length === 0; } -function parseAuditReport(output) { - try { - return JSON.parse(output); - } catch (error) { - throw new Error("npm audit did not return valid JSON", { - cause: error, - }); - } +function resolveAuditDependencies({ + readJson = readAuditJson, + environment = process.env, + runner = spawnSync, + log = console.log, + root = repositoryRoot, + logError = console.error, +} = {}) { + return { + readJson, + environment: getAuditEnvironment(environment), + runner, + log, + root, + logError, + }; } -export function runAudits() { - runNpmAudit(["audit", "--audit-level=moderate"]); - runNpmAudit( - [ - "--prefix", - "docusaurus", - "audit", - "--audit-level=high", - "--json", - ], - { - allowedAdvisories: allowedDocusaurusAuditAdvisories, - captureJson: true, - minimumSeverity: "high", +export function runAudits(options = {}) { + const dependencies = resolveAuditDependencies(options); + let failed = false; + for (const scope of ["root", "docs"]) { + try { + if (!runAuditScope(scope, dependencies)) failed = true; + } catch (error) { + failed = true; + dependencies.logError( + `[audit:${scope}] ${error instanceof Error ? error.message : String(error)}` + ); } - ); + } + return failed ? 1 : 0; } if ( process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href ) { - runAudits(); + process.exitCode = runAudits(); } diff --git a/tests/fixtures/audit-policy/auditFixture.ts b/tests/fixtures/audit-policy/auditFixture.ts new file mode 100644 index 000000000..f11400953 --- /dev/null +++ b/tests/fixtures/audit-policy/auditFixture.ts @@ -0,0 +1,149 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { evaluateCapturedAudit } from "../../../scripts/lib/audit-evaluation.mjs"; +import { repositoryRoot } from "../../../scripts/lib/workspaces.mjs"; + +export interface Advisory { + dependency: string; + name: string; + range: string; + severity: string; + url: string; +} + +export interface Vulnerability { + name: string; + nodes: string[]; + severity: string; + via: (Advisory | string)[]; +} + +export interface AuditFixture { + lock: { + lockfileVersion: number; + name: string; + packages: Record< + string, + { dev?: boolean; integrity: string; version: string } + >; + version: string; + }; + policy: { + advisories: Omit[]; + lockName: string; + minimumSeverity: string; + nodes: Record; + requireDevOnly: boolean; + scope: string; + }; + report: { + auditReportVersion: number; + metadata: { vulnerabilities: Record }; + vulnerabilities: Record; + }; +} + +function readJson(file: string): unknown { + return JSON.parse(fs.readFileSync(file, "utf8")); +} + +export function auditFixture(scope = "root"): AuditFixture { + const fixtureDirectory = path.join( + repositoryRoot, + "tests", + "fixtures", + "audit-policy" + ); + return { + report: readJson(path.join(fixtureDirectory, `${scope}.audit.json`)), + lock: readJson(path.join(fixtureDirectory, `${scope}.lock.json`)), + policy: readJson( + path.join( + repositoryRoot, + "scripts", + "audit-policy", + `${scope}.json` + ) + ), + } as AuditFixture; +} + +export function finding(fixture: AuditFixture, name: string): Vulnerability { + const item = fixture.report.vulnerabilities[name]; + if (!item) throw new Error(`Missing test finding ${name}`); + return item; +} + +export function leaf(fixture: AuditFixture, name = "braces"): Advisory { + const advisory = finding(fixture, name).via.find( + (via) => typeof via !== "string" + ); + if (!advisory) throw new Error(`Missing test advisory ${name}`); + return advisory; +} + +export function recount(fixture: AuditFixture): void { + const counts: Record = { + info: 0, + low: 0, + moderate: 0, + high: 0, + critical: 0, + total: 0, + }; + for (const item of Object.values(fixture.report.vulnerabilities)) { + counts[item.severity] = (counts[item.severity] ?? 0) + 1; + counts.total = (counts.total ?? 0) + 1; + } + fixture.report.metadata.vulnerabilities = counts; +} + +export function captured(fixture: AuditFixture, overrides = {}): object { + return { + stdout: JSON.stringify(fixture.report), + stderr: "", + status: 1, + signal: null, + ...overrides, + }; +} + +export function evaluateFixture( + fixture: AuditFixture, + overrides = {} +): ReturnType { + return evaluateCapturedAudit( + captured(fixture, overrides), + fixture.lock, + fixture.policy + ); +} + +export function addFinding( + fixture: AuditFixture, + name: string, + severity: string +): void { + const node = `node_modules/${name}`; + fixture.lock.packages[node] = { + version: "1.0.0", + integrity: "sha512-fixture", + dev: true, + }; + fixture.report.vulnerabilities[name] = { + name, + severity, + nodes: [node], + via: [ + { + name, + dependency: name, + severity, + range: "*", + url: "https://github.com/advisories/GHSA-aaaa-bbbb-cccc", + }, + ], + }; + recount(fixture); +} diff --git a/tests/fixtures/audit-policy/docs.audit.json b/tests/fixtures/audit-policy/docs.audit.json new file mode 100644 index 000000000..8c67f8826 --- /dev/null +++ b/tests/fixtures/audit-policy/docs.audit.json @@ -0,0 +1,105 @@ +{ + "auditReportVersion": 2, + "metadata": { + "vulnerabilities": { + "critical": 0, + "high": 5, + "info": 0, + "low": 1, + "moderate": 1, + "total": 7 + } + }, + "vulnerabilities": { + "@docusaurus/utils": { + "name": "@docusaurus/utils", + "nodes": [ + "node_modules/@docusaurus/utils" + ], + "severity": "high", + "via": [ + "globby", + "micromatch" + ] + }, + "braces": { + "name": "braces", + "nodes": [ + "node_modules/braces" + ], + "severity": "high", + "via": [ + { + "dependency": "braces", + "name": "braces", + "range": "<=3.0.3", + "severity": "high", + "url": "https://github.com/advisories/GHSA-vfj7-8cjw-p6xm" + } + ] + }, + "fast-glob": { + "name": "fast-glob", + "nodes": [ + "node_modules/fast-glob" + ], + "severity": "high", + "via": [ + "micromatch" + ] + }, + "globby": { + "name": "globby", + "nodes": [ + "node_modules/copy-webpack-plugin/node_modules/globby", + "node_modules/globby" + ], + "severity": "high", + "via": [ + "fast-glob" + ] + }, + "katex": { + "name": "katex", + "nodes": [ + "node_modules/katex" + ], + "severity": "low", + "via": [ + { + "dependency": "katex", + "name": "katex", + "range": ">=0.11.0 <0.18.2", + "severity": "low", + "url": "https://github.com/advisories/GHSA-238p-pmpm-9mq7" + } + ] + }, + "micromatch": { + "name": "micromatch", + "nodes": [ + "node_modules/micromatch" + ], + "severity": "high", + "via": [ + "braces" + ] + }, + "sprintf-js": { + "name": "sprintf-js", + "nodes": [ + "node_modules/sprintf-js" + ], + "severity": "moderate", + "via": [ + { + "dependency": "sprintf-js", + "name": "sprintf-js", + "range": "<=1.1.3", + "severity": "moderate", + "url": "https://github.com/advisories/GHSA-hp3w-g68c-fv3c" + } + ] + } + } +} diff --git a/tests/fixtures/audit-policy/docs.lock.json b/tests/fixtures/audit-policy/docs.lock.json new file mode 100644 index 000000000..7d8cc62fa --- /dev/null +++ b/tests/fixtures/audit-policy/docs.lock.json @@ -0,0 +1,39 @@ +{ + "lockfileVersion": 3, + "name": "fitfileviewer-docs", + "packages": { + "node_modules/@docusaurus/utils": { + "integrity": "sha512-xx0W3eav2uW1NRIpuHJWNwLTC15xPNjU4Uxi9NSnd3swYC96BE3vFiT93SD8s24kmAAWNwgZwfZ2fghGZ01Lcw==", + "version": "3.10.2" + }, + "node_modules/braces": { + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "version": "3.0.3" + }, + "node_modules/copy-webpack-plugin/node_modules/globby": { + "integrity": "sha512-Y1zNGV+pzQdh7H39l9zgB4PJqjRNqydvdYCDG4HFXM4XuvSaQQlEc91IU1yALL8gUTDomgBAfz3XJdmUS+oo0w==", + "version": "13.2.2" + }, + "node_modules/fast-glob": { + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "version": "3.3.3" + }, + "node_modules/globby": { + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "version": "11.1.0" + }, + "node_modules/katex": { + "integrity": "sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==", + "version": "0.16.47" + }, + "node_modules/micromatch": { + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "version": "4.0.8" + }, + "node_modules/sprintf-js": { + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "version": "1.0.3" + } + }, + "version": "1.0.0" +} diff --git a/tests/fixtures/audit-policy/root.audit.json b/tests/fixtures/audit-policy/root.audit.json new file mode 100644 index 000000000..9d7216ead --- /dev/null +++ b/tests/fixtures/audit-policy/root.audit.json @@ -0,0 +1,158 @@ +{ + "auditReportVersion": 2, + "metadata": { + "vulnerabilities": { + "critical": 0, + "high": 4, + "info": 0, + "low": 1, + "moderate": 7, + "total": 12 + } + }, + "vulnerabilities": { + "@electron/get": { + "name": "@electron/get", + "nodes": [ + "node_modules/app-builder-lib/node_modules/@electron/get" + ], + "severity": "moderate", + "via": [ + "global-agent" + ] + }, + "app-builder-lib": { + "name": "app-builder-lib", + "nodes": [ + "node_modules/app-builder-lib" + ], + "severity": "moderate", + "via": [ + "@electron/get", + "dmg-builder", + "electron-builder-squirrel-windows" + ] + }, + "braces": { + "name": "braces", + "nodes": [ + "node_modules/braces" + ], + "severity": "high", + "via": [ + { + "dependency": "braces", + "name": "braces", + "range": "<=3.0.3", + "severity": "high", + "url": "https://github.com/advisories/GHSA-vfj7-8cjw-p6xm" + } + ] + }, + "dmg-builder": { + "name": "dmg-builder", + "nodes": [ + "node_modules/dmg-builder" + ], + "severity": "moderate", + "via": [ + "app-builder-lib" + ] + }, + "electron-builder-squirrel-windows": { + "name": "electron-builder-squirrel-windows", + "nodes": [ + "node_modules/electron-builder-squirrel-windows" + ], + "severity": "moderate", + "via": [ + "app-builder-lib" + ] + }, + "fast-glob": { + "name": "fast-glob", + "nodes": [ + "node_modules/astro-eslint-parser/node_modules/fast-glob", + "node_modules/fast-glob", + "node_modules/stylelint/node_modules/fast-glob" + ], + "severity": "high", + "via": [ + "micromatch" + ] + }, + "global-agent": { + "name": "global-agent", + "nodes": [ + "node_modules/global-agent" + ], + "severity": "moderate", + "via": [ + "roarr" + ] + }, + "katex": { + "name": "katex", + "nodes": [ + "node_modules/katex" + ], + "severity": "low", + "via": [ + { + "dependency": "katex", + "name": "katex", + "range": ">=0.11.0 <0.18.2", + "severity": "low", + "url": "https://github.com/advisories/GHSA-238p-pmpm-9mq7" + } + ] + }, + "micromatch": { + "name": "micromatch", + "nodes": [ + "node_modules/micromatch" + ], + "severity": "high", + "via": [ + "braces" + ] + }, + "roarr": { + "name": "roarr", + "nodes": [ + "node_modules/global-agent/node_modules/roarr" + ], + "severity": "moderate", + "via": [ + "sprintf-js" + ] + }, + "sprintf-js": { + "name": "sprintf-js", + "nodes": [ + "node_modules/sprintf-js" + ], + "severity": "moderate", + "via": [ + { + "dependency": "sprintf-js", + "name": "sprintf-js", + "range": "<=1.1.3", + "severity": "moderate", + "url": "https://github.com/advisories/GHSA-hp3w-g68c-fv3c" + } + ] + }, + "stylelint": { + "name": "stylelint", + "nodes": [ + "node_modules/stylelint" + ], + "severity": "high", + "via": [ + "fast-glob", + "micromatch" + ] + } + } +} diff --git a/tests/fixtures/audit-policy/root.lock.json b/tests/fixtures/audit-policy/root.lock.json new file mode 100644 index 000000000..4adae895d --- /dev/null +++ b/tests/fixtures/audit-policy/root.lock.json @@ -0,0 +1,77 @@ +{ + "lockfileVersion": 3, + "name": "fitfileviewer", + "packages": { + "node_modules/app-builder-lib": { + "dev": true, + "integrity": "sha512-wfL7EhujuODDW3uMSD8RPcr/MLzmT0dmpVfWV0wFUWXI0rIdaukzAJ7EFUSyHXOpxuBZqaIGlQt6VeQhtHhetw==", + "version": "26.17.0" + }, + "node_modules/app-builder-lib/node_modules/@electron/get": { + "dev": true, + "integrity": "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==", + "version": "3.1.0" + }, + "node_modules/astro-eslint-parser/node_modules/fast-glob": { + "dev": true, + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "version": "3.3.3" + }, + "node_modules/braces": { + "dev": true, + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "version": "3.0.3" + }, + "node_modules/dmg-builder": { + "dev": true, + "integrity": "sha512-EAw1f2iGkICmUvAVBOjm7v5mxJdB7/+OZSycHFhKBimiTkCXtvkCC6wBKzHo7ZQYi58C2MmwIleRbgRnROlK2Q==", + "version": "26.17.0" + }, + "node_modules/electron-builder-squirrel-windows": { + "dev": true, + "integrity": "sha512-uyh+D+B0m12qCRp9c/7dwBirHTh7JcvAzj5eTEbb4dXPPGAhYPx1nozzbu1fC6AdULfat6ZNqgWhipTFpb82lQ==", + "version": "26.17.0" + }, + "node_modules/fast-glob": { + "dev": true, + "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==", + "version": "3.3.1" + }, + "node_modules/global-agent": { + "dev": true, + "integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==", + "version": "3.0.0" + }, + "node_modules/global-agent/node_modules/roarr": { + "dev": true, + "integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==", + "version": "2.15.4" + }, + "node_modules/katex": { + "dev": true, + "integrity": "sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==", + "version": "0.16.47" + }, + "node_modules/micromatch": { + "dev": true, + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "version": "4.0.8" + }, + "node_modules/sprintf-js": { + "dev": true, + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", + "version": "1.1.3" + }, + "node_modules/stylelint": { + "dev": true, + "integrity": "sha512-xVQwyiuxALUBNB2fBe0tmNemg9KqLtdj3T64mioFDar79B2cU8LIyz+3KL6LdiHs9NkeNfwxpKSaIVOY8f112g==", + "version": "17.14.1" + }, + "node_modules/stylelint/node_modules/fast-glob": { + "dev": true, + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "version": "3.3.3" + } + }, + "version": "30.0.2" +} diff --git a/tests/unit/packaging/runAudit.test.ts b/tests/unit/packaging/runAudit.test.ts index 4ff12a432..3666aff92 100644 --- a/tests/unit/packaging/runAudit.test.ts +++ b/tests/unit/packaging/runAudit.test.ts @@ -1,110 +1,165 @@ -import { describe, expect, it } from "vitest"; +import path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; import { - allowedDocusaurusAuditAdvisories, - getBlockingAuditVulnerabilities, + getAuditEnvironment, + resolveNpmAuditCommand, + runAudits, } from "../../../scripts/run-audit.mjs"; +import { npmScriptPrecedenceWarning } from "../../../scripts/lib/audit-report.mjs"; +import { + auditFixture, + captured, + leaf, + type AuditFixture, +} from "../../fixtures/audit-policy/auditFixture"; -describe("run-audit script", () => { - it("accepts only the known image-size advisory cascade", () => { - expect.assertions(1); - - const auditReport = { - vulnerabilities: { - "@docusaurus/core": { - severity: "high", - via: ["@docusaurus/mdx-loader"], - }, - "@docusaurus/mdx-loader": { - severity: "high", - via: ["image-size"], - }, - "image-size": { - severity: "high", - via: [ - { - url: "https://github.com/advisories/GHSA-5p2g-fcmc-qvqq", - }, - { - url: "https://github.com/advisories/GHSA-w3rx-r6r6-pgpr", - }, - ], - }, - }, - }; - - expect( - getBlockingAuditVulnerabilities( - auditReport, - allowedDocusaurusAuditAdvisories +function makeAuditRun( + rootFixture = auditFixture(), + docsFixture = auditFixture("docs") +) { + const fixtures: Record = { + root: rootFixture, + docs: docsFixture, + }; + const log = vi.fn(); + const logError = vi.fn(); + const runner = vi.fn( + (_command: string, _args: string[], options: { cwd: string }) => + captured( + options.cwd.endsWith("docusaurus") ? docsFixture : rootFixture ) - ).toStrictEqual([]); - }); + ); + const readJson = (file: string): unknown => { + if (file.includes("audit-policy")) + return fixtures[path.basename(file, ".json")]?.policy; + return file.includes("docusaurus") + ? docsFixture.lock + : rootFixture.lock; + }; + const options = { + runner, + readJson, + log, + logError, + environment: { + npm_execpath: "/fixture/npm-cli.js", + npm_config_allow_scripts: "fixture", + NPM_CONFIG_ALLOW_SCRIPTS: "fixture", + HTTPS_PROXY: "https://proxy.invalid", + }, + root: path.resolve("fixture-root"), + }; + return { options, runner, log, logError }; +} - it("still blocks unrelated high-severity advisories", () => { - expect.assertions(1); +describe("run-audit orchestration", () => { + it("captures both workspace audits as JSON with unchanged thresholds and scoped acceptance", () => { + expect.assertions(8); + const run = makeAuditRun(); + expect(runAudits(run.options)).toBe(0); + expect(run.runner).toHaveBeenCalledTimes(2); + expect(run.runner.mock.calls.map((call) => call[1])).toStrictEqual([ + [ + "/fixture/npm-cli.js", + "audit", + "--audit-level=moderate", + "--json", + ], + [ + "/fixture/npm-cli.js", + "audit", + "--audit-level=high", + "--json", + ], + ]); + expect(run.runner.mock.calls[0]?.[2]).toMatchObject({ + encoding: "utf8", + stdio: [ + "ignore", + "pipe", + "pipe", + ], + timeout: 300_000, + }); + expect(run.runner.mock.calls[1]?.[2].cwd).toBe( + path.resolve("fixture-root", "docusaurus") + ); + expect(run.log).toHaveBeenCalledWith( + expect.stringContaining("npm status 1; threshold moderate") + ); + expect(run.log).toHaveBeenCalledWith( + expect.stringContaining("GHSA-vfj7-8cjw-p6xm") + ); + expect(run.logError).not.toHaveBeenCalled(); + }); - const auditReport = { - vulnerabilities: { - "image-size": { - severity: "high", - via: [ - { - url: "https://github.com/advisories/GHSA-5p2g-fcmc-qvqq", - }, - ], - }, - unsafe: { - severity: "critical", - via: [ - { - url: "https://github.com/advisories/GHSA-xxxx-yyyy-zzzz", - }, - ], - }, - }, - }; + it("returns failure for an unknown advisory but still audits the second graph", () => { + expect.assertions(3); + const root = auditFixture(); + leaf(root).url = "https://github.com/advisories/GHSA-aaaa-bbbb-cccc"; + const run = makeAuditRun(root); + expect(runAudits(run.options)).toBe(1); + expect(run.runner).toHaveBeenCalledTimes(2); + expect(run.log).toHaveBeenCalledWith( + expect.stringContaining("Blocking dependency findings:") + ); + }); - expect( - getBlockingAuditVulnerabilities( - auditReport, - allowedDocusaurusAuditAdvisories - ) - ).toStrictEqual(["unsafe"]); + it("preserves failure for infrastructure errors and still captures the other scope", () => { + expect.assertions(3); + const run = makeAuditRun(); + run.runner.mockImplementationOnce(() => ({ + stdout: "not-json", + stderr: "", + status: 0, + })); + expect(runAudits(run.options)).toBe(1); + expect(run.runner).toHaveBeenCalledTimes(2); + expect(run.logError).toHaveBeenCalledWith( + expect.stringContaining("did not return valid JSON") + ); }); - it("does not let cyclic dependency metadata bypass the gate", () => { - expect.assertions(1); + it("retains the exact recognized npm precedence diagnostic in the output", () => { + expect.assertions(2); + const fixture = auditFixture(); + const run = makeAuditRun(fixture); + run.runner.mockImplementationOnce(() => + captured(fixture, { stderr: `${npmScriptPrecedenceWarning}\n` }) + ); + expect(runAudits(run.options)).toBe(0); + expect(run.log).toHaveBeenCalledWith( + `[audit:root] ${npmScriptPrecedenceWarning}` + ); + }); - const auditReport = { - vulnerabilities: { - first: { severity: "high", via: ["second"] }, - second: { severity: "high", via: ["first"] }, - }, + it("removes only conflicting script config environment keys", () => { + expect.assertions(2); + const environment = { + npm_config_allow_scripts: "fixture", + NPM_CONFIG_ALLOW_SCRIPTS: "fixture", + HTTPS_PROXY: "https://proxy.invalid", }; - - expect( - getBlockingAuditVulnerabilities( - auditReport, - allowedDocusaurusAuditAdvisories - ) - ).toStrictEqual(["first", "second"]); + expect(getAuditEnvironment(environment)).toStrictEqual({ + HTTPS_PROXY: "https://proxy.invalid", + }); + expect(environment.npm_config_allow_scripts).toBe("fixture"); }); - it("fails closed when npm returns an error document", () => { - expect.assertions(1); - - expect(() => - getBlockingAuditVulnerabilities( - { - error: { - code: "EAUDITENDPOINT", - summary: - "The configured registry does not support audit requests", - }, - }, - allowedDocusaurusAuditAdvisories - ) - ).toThrow("npm audit reported an error instead of results"); + it("invokes npm through Node on Windows when npm supplies its native CLI", () => { + expect.assertions(2); + const command = resolveNpmAuditCommand( + ["audit", "--json"], + { npm_execpath: "C:\\npm\\npm-cli.js" }, + "win32" + ); + expect(command.command).not.toMatch(/npm\.cmd$/u); + expect(command.args).toStrictEqual([ + "C:\\npm\\npm-cli.js", + "audit", + "--json", + ]); }); }); diff --git a/tests/unit/packaging/runAuditPolicy.test.ts b/tests/unit/packaging/runAuditPolicy.test.ts new file mode 100644 index 000000000..730ac1c89 --- /dev/null +++ b/tests/unit/packaging/runAuditPolicy.test.ts @@ -0,0 +1,143 @@ +import { describe, expect, it } from "vitest"; + +import { + addFinding, + auditFixture, + evaluateFixture, + finding, + leaf, + recount, +} from "../../fixtures/audit-policy/auditFixture"; + +describe("approved audit exception scope", () => { + it.each(["root", "docs"])( + "accepts the assessed %s graph projection and preserves the severity threshold", + (scope) => { + expect.assertions(4); + const result = evaluateFixture(auditFixture(scope)); + expect(result.blocked).toStrictEqual([]); + expect(result.accepted).toContain("braces"); + expect(result.belowThreshold).toContain("katex"); + expect(result.minimumSeverity).toBe( + scope === "root" ? "moderate" : "high" + ); + } + ); + + it("accepts the real npm builder cycle when it remains grounded in sprintf-js", () => { + expect.assertions(3); + const fixture = auditFixture(); + expect(finding(fixture, "app-builder-lib").via).toContain( + "dmg-builder" + ); + expect(finding(fixture, "dmg-builder").via).toContain( + "app-builder-lib" + ); + expect(evaluateFixture(fixture).accepted).toContain("app-builder-lib"); + }); + + it("allows a root app version-only bump without widening dependency scope", () => { + expect.assertions(1); + const fixture = auditFixture(); + fixture.lock.version = "30.0.3"; + expect(evaluateFixture(fixture).blocked).toStrictEqual([]); + }); + + it.each([ + "version", + "integrity", + "dev", + ])( + "blocks changed root lock %s on the leaf and its affected parents", + (field) => { + expect.assertions(2); + const fixture = auditFixture(); + Object.assign(fixture.lock.packages["node_modules/braces"] ?? {}, { + [field]: field === "dev" ? false : "changed", + }); + const result = evaluateFixture(fixture); + expect(result.blocked).toContain("braces"); + expect(result.blocked).toContain("stylelint"); + } + ); + + it("blocks promotion of an intermediary to production even if the leaf remains dev-only", () => { + expect.assertions(2); + const fixture = auditFixture(); + Object.assign(fixture.lock.packages["node_modules/micromatch"] ?? {}, { + dev: false, + devOptional: true, + }); + const result = evaluateFixture(fixture); + expect(result.blocked).toContain("micromatch"); + expect(result.blocked).toContain("stylelint"); + }); + + it("blocks a newly affected docs lock node and all propagated parents", () => { + expect.assertions(2); + const fixture = auditFixture("docs"); + const node = "node_modules/new-consumer/node_modules/braces"; + finding(fixture, "braces").nodes.push(node); + fixture.lock.packages[node] = { + version: "3.0.3", + integrity: "sha512-new", + }; + const result = evaluateFixture(fixture); + expect(result.blocked).toContain("braces"); + expect(result.blocked).toContain("@docusaurus/utils"); + }); + + it("blocks an unassessed intermediary even when it leads to an accepted advisory", () => { + expect.assertions(1); + const fixture = auditFixture(); + addFinding(fixture, "new-parent", "high"); + finding(fixture, "new-parent").via = ["braces"]; + expect(evaluateFixture(fixture).blocked).toContain("new-parent"); + }); + + it("blocks every mixed cascade containing a new above-threshold cause", () => { + expect.assertions(2); + const fixture = auditFixture(); + finding(fixture, "braces").via.push({ + ...leaf(fixture), + url: "https://github.com/advisories/GHSA-aaaa-bbbb-cccc", + }); + const result = evaluateFixture(fixture); + expect(result.blocked).toContain("braces"); + expect(result.blocked).toContain("stylelint"); + }); + + it.each(["GHSA-5p2g-fcmc-qvqq", "GHSA-w3rx-r6r6-pgpr"])( + "does not retain obsolete image-size exception %s", + (advisory) => { + expect.assertions(1); + const fixture = auditFixture("docs"); + leaf(fixture).url = `https://github.com/advisories/${advisory}`; + expect(evaluateFixture(fixture).blocked).toContain("braces"); + } + ); + + it("preserves below-threshold causes and new below-threshold-only paths without exceptions", () => { + expect.assertions(3); + const fixture = auditFixture("docs"); + addFinding(fixture, "new-moderate-tool", "moderate"); + finding(fixture, "@docusaurus/utils").via.push("new-moderate-tool"); + const result = evaluateFixture(fixture); + expect(result.blocked).toStrictEqual([]); + expect(result.belowThreshold).toContain("new-moderate-tool"); + expect(result.belowThreshold).toContain("sprintf-js"); + }); + + it("accepts status zero with only below-threshold findings while granting no exceptions", () => { + expect.assertions(3); + const fixture = auditFixture("docs"); + fixture.report.vulnerabilities = { + "sprintf-js": finding(fixture, "sprintf-js"), + }; + recount(fixture); + const result = evaluateFixture(fixture, { status: 0 }); + expect(result.accepted).toStrictEqual([]); + expect(result.blocked).toStrictEqual([]); + expect(result.belowThreshold).toStrictEqual(["sprintf-js"]); + }); +}); diff --git a/tests/unit/packaging/runAuditValidation.test.ts b/tests/unit/packaging/runAuditValidation.test.ts new file mode 100644 index 000000000..3ff6e7343 --- /dev/null +++ b/tests/unit/packaging/runAuditValidation.test.ts @@ -0,0 +1,152 @@ +import { describe, expect, it } from "vitest"; + +import { npmScriptPrecedenceWarning } from "../../../scripts/lib/audit-report.mjs"; +import { + addFinding, + auditFixture, + evaluateFixture, + finding, + leaf, + recount, +} from "../../fixtures/audit-policy/auditFixture"; + +const processFailures = [ + { status: null, signal: "SIGSEGV" }, + { status: 0, signal: "SIGTERM" }, + { status: 2 }, + { error: { code: "ETIMEDOUT" } }, + { stderr: "npm error registry unavailable" }, + { status: 0 }, + { stdout: "not-json", status: 0 }, + { + stdout: JSON.stringify({ error: { code: "EAUDITENDPOINT" } }), + status: 0, + }, +]; + +describe("audit report and policy validation", () => { + it.each(processFailures)( + "fails closed on process or infrastructure failure %j", + (result) => { + expect.assertions(1); + expect(() => evaluateFixture(auditFixture(), result)).toThrow( + /Audit|audit/u + ); + } + ); + + it("recognizes only the exact benign npm12 script-precedence warning", () => { + expect.assertions(1); + expect( + evaluateFixture(auditFixture(), { + stderr: `${npmScriptPrecedenceWarning}\r\n`, + }).blocked + ).toStrictEqual([]); + }); + + it.each([ + `${npmScriptPrecedenceWarning}\nnpm error registry unavailable`, + `${npmScriptPrecedenceWarning}\nnpm warn unknown warning`, + `${npmScriptPrecedenceWarning}!`, + ` ${npmScriptPrecedenceWarning}`, + ])("rejects additional or near-match stderr %s", (stderr) => { + expect.assertions(1); + expect(() => evaluateFixture(auditFixture(), { stderr })).toThrow( + "Unexpected npm audit stderr" + ); + }); + + it("rejects an ungrounded cycle even beside an accepted sibling cause", () => { + expect.assertions(1); + const fixture = auditFixture(); + addFinding(fixture, "cycle-a", "high"); + addFinding(fixture, "cycle-b", "high"); + finding(fixture, "cycle-a").via = ["cycle-b"]; + finding(fixture, "cycle-b").via = ["cycle-a"]; + finding(fixture, "stylelint").via.push("cycle-a"); + expect(() => evaluateFixture(fixture)).toThrow( + "Ungrounded advisory component" + ); + }); + + it("rejects missing advisory references", () => { + expect.assertions(1); + const fixture = auditFixture(); + finding(fixture, "braces").via = ["missing"]; + expect(() => evaluateFixture(fixture)).toThrow( + "Missing advisory reference" + ); + }); + + it("rejects missing lock nodes", () => { + expect.assertions(1); + const fixture = auditFixture(); + delete fixture.lock.packages["node_modules/braces"]; + expect(() => evaluateFixture(fixture)).toThrow("Missing lock node"); + }); + + it("rejects summary mismatches and understated propagated severities", () => { + expect.assertions(2); + const fixture = auditFixture(); + fixture.report.metadata.vulnerabilities.total = 0; + expect(() => evaluateFixture(fixture)).toThrow( + "Audit summary disagrees" + ); + finding(fixture, "stylelint").severity = "low"; + recount(fixture); + expect(() => evaluateFixture(fixture)).toThrow( + "Audit severity contradicts" + ); + }); + + it("rejects threshold changes and root dev-only bypass", () => { + expect.assertions(3); + const fixture = auditFixture(); + fixture.policy.minimumSeverity = "high"; + expect(() => evaluateFixture(fixture)).toThrow("threshold"); + fixture.policy.minimumSeverity = "moderate"; + fixture.policy.requireDevOnly = false; + expect(() => evaluateFixture(fixture)).toThrow("dev-only"); + Object.assign(fixture.policy, { scope: ["root"] }); + expect(() => evaluateFixture(fixture)).toThrow( + "Unknown audit policy scope" + ); + }); + + it("rejects coerced severity arrays in nodes, advisory leaves and policy entries", () => { + expect.assertions(3); + const nodeFixture = auditFixture(); + Object.assign(finding(nodeFixture, "braces"), { severity: ["high"] }); + expect(() => evaluateFixture(nodeFixture)).toThrow("Unknown severity"); + const leafFixture = auditFixture(); + Object.assign(leaf(leafFixture), { severity: ["high"] }); + expect(() => evaluateFixture(leafFixture)).toThrow( + "Malformed advisory severity" + ); + const policyFixture = auditFixture(); + Object.assign(policyFixture.policy.advisories[0] ?? {}, { + severity: ["high"], + }); + expect(() => evaluateFixture(policyFixture)).toThrow( + "Malformed policy advisory severity" + ); + }); + + it("rejects duplicate paths, unsafe paths, wrong workspace and contradictory status one", () => { + expect.assertions(4); + const fixture = auditFixture(); + finding(fixture, "braces").nodes.push("node_modules/braces"); + expect(() => evaluateFixture(fixture)).toThrow("Duplicate lock nodes"); + finding(fixture, "braces").nodes = ["node_modules/../braces"]; + expect(() => evaluateFixture(fixture)).toThrow("Unsafe lock node"); + const wrongLock = auditFixture(); + wrongLock.lock.name = "wrong-workspace"; + expect(() => evaluateFixture(wrongLock)).toThrow("Wrong workspace"); + const empty = auditFixture(); + empty.report.vulnerabilities = {}; + recount(empty); + expect(() => evaluateFixture(empty)).toThrow( + "Audit exit code contradicts" + ); + }); +}); From e6f27e088ee87307393f5b7f0f94efe89d74d66f Mon Sep 17 00:00:00 2001 From: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com> Date: Wed, 7 Oct 2026 22:18:56 -0400 Subject: [PATCH 10/12] =?UTF-8?q?=F0=9F=94=A7=20[fix]=20Make=20audit=20met?= =?UTF-8?q?adata=20rejection=20explicit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/lib/audit-report.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/lib/audit-report.mjs b/scripts/lib/audit-report.mjs index a13e1cd7e..a75f3cdba 100644 --- a/scripts/lib/audit-report.mjs +++ b/scripts/lib/audit-report.mjs @@ -98,7 +98,9 @@ function validateNodes(item, lock) { function validateSummary(report) { const counts = report.metadata?.vulnerabilities; - requireAuditCondition(isRecord(counts), "Missing audit summary metadata"); + if (!isRecord(counts)) { + throw new Error("Missing audit summary metadata"); + } const items = Object.values(report.vulnerabilities); requireAuditCondition( counts.total === items.length, From 59892a9feeee24af1c176c16a53213b82f8fd94e Mon Sep 17 00:00:00 2001 From: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com> Date: Wed, 7 Oct 2026 22:33:19 -0400 Subject: [PATCH 11/12] =?UTF-8?q?=F0=9F=A7=AA=20[test]=20Isolate=20empty-f?= =?UTF-8?q?older=20smoke=20fixtures=20and=20recover=20transient=20CDP=20re?= =?UTF-8?q?plies?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/playwright/app-ui.spec.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/tests/playwright/app-ui.spec.ts b/tests/playwright/app-ui.spec.ts index 382357ca3..c39f799f9 100644 --- a/tests/playwright/app-ui.spec.ts +++ b/tests/playwright/app-ui.spec.ts @@ -114,9 +114,13 @@ async function closeElectronApp(app: ElectronApplication): Promise { function isTransientElectronEvaluateError(error: unknown): boolean { const message = error instanceof Error ? error.message : String(error); - return message.includes("Execution context was destroyed"); + return ( + message.includes("Execution context was destroyed") || + message.includes("Resulting promise was garbage collected.") + ); } +// Callbacks must be idempotent: a lost CDP reply can follow completed execution. async function evaluateElectronAppWithRetry( evaluate: () => Promise ): Promise { @@ -1574,11 +1578,8 @@ test.describe("FitFileViewer Electron UI", () => { activeFileName: sampleFitActivityState.activeFileName, }); - const emptyBrowserFolder = path.join( - repositoryRoot, - "tests", - "fixtures" - ); + const emptyBrowserFolder = test.info().outputPath("empty-browser"); + fs.mkdirSync(emptyBrowserFolder, { recursive: true }); await armFitBrowserStatusRecorder(); await mockOpenFileDialog({ canceled: false, From e7fd53c04c8f246bd0fe22fa9bc5e61b3f2a0df8 Mon Sep 17 00:00:00 2001 From: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com> Date: Wed, 7 Oct 2026 22:43:57 -0400 Subject: [PATCH 12/12] =?UTF-8?q?=F0=9F=A7=AA=20[test]=20Configure=20Linux?= =?UTF-8?q?=20CI=20WebGL=20and=20retain=20startup=20diagnostics?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/Build.yml | 12 ++++++++++++ .github/workflows/release-rehearsal.yml | 5 ++++- docs/DEVELOPMENT_GUIDE.md | 7 +++++++ tests/playwright/app-ui.spec.ts | 9 +++++++-- 4 files changed, 30 insertions(+), 3 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 95f530c50..3ffe14b50 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -91,6 +91,18 @@ jobs: done wait "$verify_pid" + - name: Upload failed release verification diagnostics + if: failure() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: release-verification-diagnostics + path: | + release-dist/smoke-diagnostics/** + test-results/** + playwright-report/** + if-no-files-found: ignore + retention-days: 14 + - name: Show git diff for app source (debug) id: git_diff run: node scripts/print-app-diff.mjs diff --git a/.github/workflows/release-rehearsal.yml b/.github/workflows/release-rehearsal.yml index a8b2c2699..f6e156042 100644 --- a/.github/workflows/release-rehearsal.yml +++ b/.github/workflows/release-rehearsal.yml @@ -114,7 +114,10 @@ jobs: uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: release-gate-smoke-diagnostics - path: release-dist/smoke-diagnostics/** + path: | + release-dist/smoke-diagnostics/** + test-results/** + playwright-report/** if-no-files-found: ignore retention-days: 14 diff --git a/docs/DEVELOPMENT_GUIDE.md b/docs/DEVELOPMENT_GUIDE.md index a1ce3b300..5fc633409 100644 --- a/docs/DEVELOPMENT_GUIDE.md +++ b/docs/DEVELOPMENT_GUIDE.md @@ -290,6 +290,13 @@ export class FeatureManager { [ModuleName].performance.test.ts # Performance tests ``` +The offline MapLibre Playwright test selects Chromium's software WebGL driver +with `--use-gl=angle --use-angle=swiftshader` on Linux when `CI=true`, because +hosted runners do not provide a usable hardware WebGL context. This affects +only that test's Electron launch. The test still requires production `file://` +loading, enabled web security, a real blob worker, rendered GeoJSON features, +and successful map recreation. Production launch settings are unchanged. + ### Writing Tests ```typescript diff --git a/tests/playwright/app-ui.spec.ts b/tests/playwright/app-ui.spec.ts index c39f799f9..f8e04aff7 100644 --- a/tests/playwright/app-ui.spec.ts +++ b/tests/playwright/app-ui.spec.ts @@ -592,8 +592,13 @@ test.describe("FitFileViewer renderer environment fallbacks", () => { test("renders offline MapLibre GeoJSON under the production file CSP after map recreation", async () => { const profile = createElectronLaunchProfile(); + // Hosted Linux runners need an explicit WebGL driver for this render test. + const graphicsArgs = + process.platform === "linux" && process.env.CI === "true" + ? ["--use-gl=angle", "--use-angle=swiftshader"] + : []; const app = await electron.launch({ - args: profile.args, + args: [...profile.args, ...graphicsArgs], cwd: repositoryRoot, env: createElectronLaunchEnv(), }); @@ -731,8 +736,8 @@ test("renders offline MapLibre GeoJSON under the production file CSP after map r "offline-worker" ).length ); - } finally { map.remove(); + } finally { container.remove(); } }