diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 68dc9e9..b30f960 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,2490 +1,91 @@ -# Waggle — Release Build Workflow +# Release build for the community edition (P1.3d). # -# Builds desktop apps for Windows (NSIS) and macOS (DMG) on tag push. -# Publishes only the certified Windows installer; macOS outputs remain -# workflow verification artifacts until the deferred macOS release gate lands. +# On each release target the build job stages the sidecar payload, packs the +# server archive for the installer (ADR-0009), builds the desktop installers, +# smoke-tests the installer and the desktop app, and uploads everything as a +# workflow artifact. A pushed v* tag also gets a draft GitHub release with a +# SHA256SUMS file. Pull requests and manual runs build and test only. # -# Trigger: push tag v* (e.g., v1.0.0). Use tauri-build-pr.yml for manual -# unsigned verification builds; production signing is tag-only. +# Nothing is signed or notarized, and the only secret is GITHUB_TOKEN. The +# macOS app gets an ad-hoc signature ("-"), which needs no certificate: without +# one, macOS reports a downloaded Apple Silicon app as damaged. -name: Release Build +name: Release on: push: tags: - 'v*' + pull_request: + branches: + - main + paths: + - 'app/**' + - 'apps/web/**' + - 'packages/**' + - 'scripts/**' + - 'package.json' + - 'package-lock.json' + - '.github/workflows/release.yml' + workflow_dispatch: permissions: contents: read -env: - WINDOWS_SIGNING_TRANSPORT_MAX_ITEMS: 60000 - concurrency: group: release-${{ github.ref }} - cancel-in-progress: false + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + # The embedding model runs on CPU; skip the CUDA download on Linux (ADR-0008). + ONNXRUNTIME_NODE_INSTALL_CUDA: skip jobs: - build-windows-prebuilt: - runs-on: windows-latest - permissions: - contents: read - outputs: - build_receipt_sha256: ${{ steps.handoff.outputs.receipt_sha256 }} - handoff_size_bytes: ${{ steps.handoff.outputs.handoff_size_bytes }} - artifact_id: ${{ steps.upload-prebuilt.outputs.artifact-id }} - artifact_digest: ${{ steps.upload-prebuilt.outputs.artifact-digest }} - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - with: - fetch-depth: 0 - persist-credentials: false - - - name: Validate immutable Windows build boundary - shell: pwsh - run: | - if ($env:GITHUB_REPOSITORY -cne 'marolinik/waggle-os' -or - $env:GITHUB_REF_TYPE -cne 'tag' -or - $env:GITHUB_SHA -cnotmatch '^[0-9a-f]{40}$') { - throw 'Windows release build requires the exact repository, tag, and revision boundary.' - } - $checkedOutRevision = (git rev-parse --verify HEAD).Trim().ToLowerInvariant() - if ($LASTEXITCODE -ne 0 -or $checkedOutRevision -cne $env:GITHUB_SHA) { - throw 'Checked-out Windows release revision differs from GITHUB_SHA.' - } - if (@(git status --porcelain=v1 --untracked-files=all).Count -ne 0) { - throw 'Windows release build checkout must be clean.' - } - $version = [string](Get-Content -Raw -LiteralPath 'app/src-tauri/tauri.conf.json' | ConvertFrom-Json).version - $expectedTag = "v$version" - if ($env:GITHUB_REF -ne "refs/tags/$expectedTag" -or $env:GITHUB_REF_NAME -ne $expectedTag) { - throw "Release tag $env:GITHUB_REF_NAME does not exactly match app version $version" - } - $remoteMainRevision = (git rev-parse --verify refs/remotes/origin/main).Trim().ToLowerInvariant() - if ($LASTEXITCODE -ne 0 -or $remoteMainRevision -cnotmatch '^[0-9a-f]{40}$') { - throw 'Fresh checkout did not provide canonical origin/main for release ancestry validation' - } - git merge-base --is-ancestor $env:GITHUB_SHA refs/remotes/origin/main - if ($LASTEXITCODE -ne 0) { throw 'Release tag commit is not an ancestor of canonical origin/main' } - - - name: Setup Node.js - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 - with: - node-version: 22.23.2 - cache: npm - - - name: Setup Rust - uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 - with: - toolchain: 1.94.0 - - - name: Rust cache - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 - with: - workspaces: app/src-tauri - - - name: Install dependencies - run: npm ci - - - name: Install locked Tauri CLI - run: npm ci --prefix app --ignore-scripts - - - name: Build packages (shared -> core -> agent -> server) - run: npm run build:packages - - - name: Bundle Node.js runtime - run: node scripts/bundle-node.mjs - - - name: Build sidecar - run: node scripts/build-sidecar.mjs - - - name: Bundle native dependencies - run: node scripts/bundle-native-deps.mjs - - - name: Stage sidecar dependencies - run: node scripts/stage-sidecar-deps.mjs - - - name: Build frontend - run: cd apps/web && npx vite build - - - name: Build full unsigned Tauri NSIS package - shell: pwsh - run: | - $override = Get-Content -Raw -LiteralPath 'app/src-tauri/tauri.build-override.conf.json' | ConvertFrom-Json - if ($null -ne $override.bundle.windows -and - $null -ne $override.bundle.windows.PSObject.Properties['signCommand']) { - throw 'The hosted prebuilt job must not carry a Windows signing command.' - } - Push-Location app - try { - & node node_modules/@tauri-apps/cli/tauri.js build ` - --target x86_64-pc-windows-msvc ` - --bundles nsis ` - --config src-tauri/tauri.build-override.conf.json - if ($LASTEXITCODE -ne 0) { throw 'Full unsigned Tauri NSIS package failed.' } - } finally { - Pop-Location - } - - - name: Issue immutable Windows signing handoff - id: handoff - shell: pwsh - run: | - $handoffRoot = Join-Path $env:RUNNER_TEMP 'waggle-windows-signing-handoff' - if (Test-Path -LiteralPath $handoffRoot) { - throw "Windows signing handoff root already exists: $handoffRoot" - } - & ./app/scripts/new-windows-signing-handoff.ps1 ` - -SourceTargetRoot 'app/src-tauri/target' ` - -DestinationRoot $handoffRoot - if ($LASTEXITCODE -ne 0) { throw 'Windows signing handoff failed.' } - $receiptPath = Join-Path $handoffRoot 'build-receipt.json' - $prebuiltRoot = Join-Path $handoffRoot 'prebuilt' - if (-not (Test-Path -LiteralPath $receiptPath -PathType Leaf) -or - -not (Test-Path -LiteralPath $prebuiltRoot -PathType Container)) { - throw 'Windows signing handoff did not publish its canonical receipt and prebuilt root.' - } - $receiptSha256 = (Get-FileHash -LiteralPath $receiptPath -Algorithm SHA256).Hash - if ($receiptSha256 -notmatch '^[0-9A-F]{64}$') { - throw 'Windows signing handoff receipt digest is invalid.' - } - $handoffSizeBytes = [long]( - Get-ChildItem -LiteralPath $handoffRoot -Recurse -Force -File | - Measure-Object -Property Length -Sum - ).Sum - if ($handoffSizeBytes -le 0) { - throw 'Windows signing handoff has an invalid aggregate size.' - } - "receipt_sha256=$receiptSha256" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "handoff_size_bytes=$handoffSizeBytes" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - - - name: Upload immutable Windows signing handoff - id: upload-prebuilt - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - with: - name: waggle-windows-prebuilt-${{ github.sha }} - path: ${{ runner.temp }}\waggle-windows-signing-handoff - if-no-files-found: error - include-hidden-files: true - retention-days: 7 - - prepare-windows-signing: - needs: build-windows-prebuilt - runs-on: windows-latest - permissions: - contents: read - outputs: - release_mode: ${{ steps.release-mode.outputs.mode }} - candidate_version: ${{ steps.release-mode.outputs.candidate_version }} - bootstrap_identity: ${{ steps.release-mode.outputs.bootstrap_identity }} - upgrade_base_tag: ${{ steps.release-mode.outputs.upgrade_base_tag }} - upgrade_base_asset_name: ${{ steps.release-mode.outputs.upgrade_base_asset_name }} - upgrade_base_sha256: ${{ steps.release-mode.outputs.upgrade_base_sha256 }} - upgrade_base_commit: ${{ steps.release-mode.outputs.upgrade_base_commit }} - signer_subject: ${{ steps.signer-identity.outputs.subject }} - preparation_receipt_sha256: ${{ steps.stage-prepared.outputs.receipt_sha256 }} - preparation_size_bytes: ${{ steps.stage-prepared.outputs.size_bytes }} - artifact_id: ${{ steps.upload-prepared.outputs.artifact-id }} - artifact_digest: ${{ steps.upload-prepared.outputs.artifact-digest }} - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - with: - fetch-depth: 0 - persist-credentials: false - - - name: Validate exact hosted signing preparation boundary - shell: pwsh - run: | - $version = [string](Get-Content -Raw -LiteralPath 'app/src-tauri/tauri.conf.json' | ConvertFrom-Json).version - if ($env:GITHUB_ACTIONS -cne 'true' -or - $env:GITHUB_EVENT_NAME -cne 'push' -or - $env:GITHUB_REPOSITORY -cne 'marolinik/waggle-os' -or - $env:GITHUB_REF_TYPE -cne 'tag' -or - $env:GITHUB_REF -cne "refs/tags/v$version" -or - $env:GITHUB_REF_NAME -cne "v$version" -or - $env:GITHUB_WORKFLOW_REF -cne "marolinik/waggle-os/.github/workflows/release.yml@$env:GITHUB_REF" -or - $env:GITHUB_WORKFLOW_SHA -cne $env:GITHUB_SHA -or - $env:RUNNER_ENVIRONMENT -cne 'github-hosted' -or - $env:GITHUB_SHA -cnotmatch '^[0-9a-f]{40}$') { - throw 'Windows signing preparation requires the exact hosted push, repository, tag, workflow, and revision boundary.' - } - $checkedOutRevision = (git rev-parse --verify HEAD).Trim().ToLowerInvariant() - if ($LASTEXITCODE -ne 0 -or $checkedOutRevision -cne $env:GITHUB_SHA -or - @(git status --porcelain=v1 --untracked-files=all).Count -ne 0) { - throw 'Windows signing preparation checkout is not the clean GITHUB_SHA revision.' - } - - - name: Resolve Windows release mode - id: release-mode - shell: pwsh - env: - WINDOWS_BOOTSTRAP_RELEASE_IDENTITY: ${{ vars.WINDOWS_BOOTSTRAP_RELEASE_IDENTITY }} - WINDOWS_UPGRADE_BASE_TAG: ${{ vars.WINDOWS_UPGRADE_BASE_TAG }} - WINDOWS_UPGRADE_BASE_ASSET_NAME: ${{ vars.WINDOWS_UPGRADE_BASE_ASSET_NAME }} - WINDOWS_UPGRADE_BASE_SHA256: ${{ vars.WINDOWS_UPGRADE_BASE_SHA256 }} - WINDOWS_UPGRADE_BASE_COMMIT: ${{ vars.WINDOWS_UPGRADE_BASE_COMMIT }} - run: | - function Resolve-WindowsReleaseMode { - param( - [string]$CandidateVersion, - [string]$CandidateTag, - [string]$CandidateSha, - [string]$BootstrapIdentity, - [string]$BaseTag, - [string]$BaseAssetName, - [string]$BaseSha256, - [string]$BaseCommit - ) - - if ($CandidateVersion -notmatch '^\d+\.\d+\.\d+$' -or - $CandidateTag -cne "v$CandidateVersion" -or - $CandidateSha -cnotmatch '^[0-9a-f]{40}$') { - throw 'Candidate release identity is not a strict tag, version, and commit tuple.' - } - $candidateSemVer = [version]$CandidateVersion - $bootstrapSemVer = [version]'0.2.0' - - $releaseInputs = @( - $BootstrapIdentity, - $BaseTag, - $BaseAssetName, - $BaseSha256, - $BaseCommit - ) - if (@($releaseInputs | Where-Object { $_ -ne $_.Trim() }).Count -gt 0) { - throw 'Windows release-mode inputs must be exact values without surrounding whitespace.' - } - - $baselineInputs = @($BaseTag, $BaseAssetName, $BaseSha256, $BaseCommit) - $configuredBaselineInputs = @( - $baselineInputs | Where-Object { -not [string]::IsNullOrEmpty($_) } - ).Count - - if ($CandidateVersion -ceq '0.2.0') { - if ($CandidateTag -cne 'v0.2.0' -or $configuredBaselineInputs -ne 0) { - throw 'The v0.2.0 bootstrap requires all protected upgrade-baseline inputs to be exactly empty.' - } - $expectedBootstrapIdentity = "v0.2.0@$CandidateSha" - if (-not [string]::Equals( - $BootstrapIdentity, - $expectedBootstrapIdentity, - [System.StringComparison]::Ordinal - )) { - throw 'The v0.2.0 bootstrap authorization does not exactly match the release tag and commit.' - } - return 'bootstrap' - } - - if ($candidateSemVer -le $bootstrapSemVer) { - throw 'Non-bootstrap Windows releases must be newer than v0.2.0.' - } - if (-not [string]::IsNullOrEmpty($BootstrapIdentity)) { - throw 'Bootstrap authorization is valid only for the exact v0.2.0 release.' - } - if ($configuredBaselineInputs -ne 4) { - throw 'Non-bootstrap Windows releases require all four protected upgrade-baseline inputs.' - } - if ($CandidateVersion -ceq '0.2.1' -and $BaseTag -cne 'v0.2.0') { - throw 'The first Windows upgrade must use the signed v0.2.0 bootstrap baseline.' - } - return 'upgrade' - } - - $candidateVersion = [string](Get-Content -Raw -LiteralPath 'app/src-tauri/tauri.conf.json' | ConvertFrom-Json).version - $bootstrapIdentity = [string]$env:WINDOWS_BOOTSTRAP_RELEASE_IDENTITY - $baseTag = [string]$env:WINDOWS_UPGRADE_BASE_TAG - $baseAssetName = [string]$env:WINDOWS_UPGRADE_BASE_ASSET_NAME - $baseSha256 = [string]$env:WINDOWS_UPGRADE_BASE_SHA256 - $baseCommit = [string]$env:WINDOWS_UPGRADE_BASE_COMMIT - $releaseMode = Resolve-WindowsReleaseMode ` - -CandidateVersion $candidateVersion ` - -CandidateTag $env:GITHUB_REF_NAME ` - -CandidateSha $env:GITHUB_SHA ` - -BootstrapIdentity $bootstrapIdentity ` - -BaseTag $baseTag ` - -BaseAssetName $baseAssetName ` - -BaseSha256 $baseSha256 ` - -BaseCommit $baseCommit - "mode=$releaseMode" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "candidate_version=$candidateVersion" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "bootstrap_identity=$bootstrapIdentity" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "upgrade_base_tag=$baseTag" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "upgrade_base_asset_name=$baseAssetName" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "upgrade_base_sha256=$baseSha256" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "upgrade_base_commit=$baseCommit" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - - - name: Validate protected signer subject - id: signer-identity - shell: pwsh - env: - WINDOWS_CODESIGN_APPROVED_SUBJECT: ${{ vars.WINDOWS_CODESIGN_APPROVED_SUBJECT }} - run: | - $expected = 'CN=EGZAKTA DOO BEOGRAD, O=EGZAKTA DOO BEOGRAD, L=Amsterdam, C=NL' - $subject = [string]$env:WINDOWS_CODESIGN_APPROVED_SUBJECT - if ($subject -cne $expected -or $subject -cne $subject.Trim() -or - $subject -match '[\x00-\x1F\x7F]') { - throw 'WINDOWS_CODESIGN_APPROVED_SUBJECT does not exactly match the approved public identity.' - } - "subject=$subject" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - - - name: Validate capacity before duplicate handoff extraction - shell: pwsh - env: - WAGGLE_HANDOFF_SIZE_BYTES: ${{ needs.build-windows-prebuilt.outputs.handoff_size_bytes }} - run: | - $handoffSizeBytes = [long]0 - if (-not [long]::TryParse( - [string]$env:WAGGLE_HANDOFF_SIZE_BYTES, - [Globalization.NumberStyles]::None, - [Globalization.CultureInfo]::InvariantCulture, - [ref]$handoffSizeBytes - ) -or $handoffSizeBytes -le 0 -or $handoffSizeBytes -gt 40GB) { - throw 'Hosted build handoff size output is missing or invalid.' - } - $dependencyAndCertificationOverheadBytes = [long]9GB - if ($handoffSizeBytes -gt - ([long]::MaxValue - $dependencyAndCertificationOverheadBytes) / 2) { - throw 'Hosted build handoff size overflows the capacity calculation.' - } - $requiredBytes = [long]( - $handoffSizeBytes * 2 + $dependencyAndCertificationOverheadBytes - ) - $runnerRoot = [IO.Path]::GetPathRoot([IO.Path]::GetFullPath($env:RUNNER_TEMP)) - $availableBytes = [IO.DriveInfo]::new($runnerRoot).AvailableFreeSpace - if ($availableBytes -lt $requiredBytes) { - throw "Insufficient disk for two isolated handoff extractions: requires=$requiredBytes available=$availableBytes" - } - - - name: Setup Node.js for protected packaging - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 - with: - node-version: '22.23.2' - cache: npm - cache-dependency-path: app/package-lock.json - - - name: Install locked Tauri packaging CLI - run: npm ci --prefix app --ignore-scripts - - - name: Download immutable prebuilt handoff for unsigned verification - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 - with: - artifact-ids: ${{ needs.build-windows-prebuilt.outputs.artifact_id }} - path: ${{ runner.temp }}\waggle-prebuilt-unsigned - merge-multiple: true - - - name: Download immutable prebuilt handoff for signed packaging - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 - with: - artifact-ids: ${{ needs.build-windows-prebuilt.outputs.artifact_id }} - path: ${{ runner.temp }}\waggle-prebuilt-signing - merge-multiple: true - - - name: Verify duplicate handoff roots and bound receipt - id: verify-handoff - shell: pwsh - env: - EXPECTED_BUILD_RECEIPT_SHA256: ${{ needs.build-windows-prebuilt.outputs.build_receipt_sha256 }} - run: | - $expectedSha256 = [string]$env:EXPECTED_BUILD_RECEIPT_SHA256 - if ($expectedSha256 -notmatch '^[0-9A-F]{64}$') { - throw 'Build receipt SHA-256 output is missing or invalid.' - } - $unsignedDownload = [IO.Path]::GetFullPath((Resolve-Path (Join-Path $env:RUNNER_TEMP 'waggle-prebuilt-unsigned')).Path) - $signingDownload = [IO.Path]::GetFullPath((Resolve-Path (Join-Path $env:RUNNER_TEMP 'waggle-prebuilt-signing')).Path) - if ([string]::Equals($unsignedDownload, $signingDownload, [StringComparison]::OrdinalIgnoreCase)) { - throw 'Unsigned and signing handoff downloads must be distinct.' - } - $unsignedReceipt = Join-Path $unsignedDownload 'build-receipt.json' - $signingReceipt = Join-Path $signingDownload 'build-receipt.json' - $unsignedRoot = Join-Path $unsignedDownload 'prebuilt' - $signingRoot = Join-Path $signingDownload 'prebuilt' - $unsignedNsisRoot = Join-Path $unsignedDownload 'nsis-toolchain' - $signingNsisRoot = Join-Path $signingDownload 'nsis-toolchain' - foreach ($path in @($unsignedReceipt, $signingReceipt)) { - if (-not (Test-Path -LiteralPath $path -PathType Leaf) -or - -not [string]::Equals( - (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash, - $expectedSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Downloaded hosted build receipt differs from its immutable handoff digest.' - } - } - $signingReceiptForPackage = Join-Path $signingDownload 'build-receipt.package.json' - [IO.File]::Copy($signingReceipt, $signingReceiptForPackage, $false) - if ((Get-FileHash -LiteralPath $signingReceiptForPackage -Algorithm SHA256).Hash -cne - $expectedSha256) { - throw 'Signing package receipt copy changed before use.' - } - foreach ($path in @($unsignedRoot, $signingRoot)) { - if (-not (Test-Path -LiteralPath $path -PathType Container)) { - throw 'Downloaded prebuilt input root is missing.' - } - } - foreach ($path in @($unsignedNsisRoot, $signingNsisRoot)) { - if (-not (Test-Path -LiteralPath $path -PathType Container)) { - throw 'Downloaded NSIS toolchain root is missing.' - } - } - $receipt = Get-Content -Raw -LiteralPath $unsignedReceipt | ConvertFrom-Json -Depth 32 - $expectedNsisAggregate = '1FC822D1A183552A80ADEA01B0BF456F462B90518256EF1FE9EDFA22D76CD85A' - if (@($receipt.nsisInventory.entries).Count -ne 442 -or - [string]$receipt.nsisInventory.sha256 -cne $expectedNsisAggregate) { - throw 'Hosted build receipt does not bind the pinned 442-file NSIS closure.' - } - . ./app/scripts/sign-windows-artifact.ps1 - $unsignedNsisInventory = New-WagglePrebuiltInventory $unsignedNsisRoot - $signingNsisInventory = New-WagglePrebuiltInventory $signingNsisRoot - foreach ($inventory in @($unsignedNsisInventory, $signingNsisInventory)) { - if (@($inventory.entries).Count -ne 442 -or - [string]$inventory.sha256 -cne $expectedNsisAggregate -or - ($inventory | ConvertTo-Json -Depth 8 -Compress) -cne - ($receipt.nsisInventory | ConvertTo-Json -Depth 8 -Compress)) { - throw 'Downloaded NSIS toolchain does not exactly match its canonical receipt inventory.' - } - } - $installedNsisRoot = Join-Path $env:LOCALAPPDATA 'tauri\NSIS' - if (Test-Path -LiteralPath $installedNsisRoot) { - throw 'Fresh protected signer runner unexpectedly already contains a Tauri NSIS closure.' - } - $installedNsisParent = Split-Path $installedNsisRoot -Parent - New-Item -ItemType Directory -Path $installedNsisParent -Force | Out-Null - $temporaryNsisRoot = Join-Path $installedNsisParent "NSIS.$([Guid]::NewGuid().ToString('N')).tmp" - Copy-Item -LiteralPath $unsignedNsisRoot -Destination $temporaryNsisRoot -Recurse -ErrorAction Stop - [IO.Directory]::Move($temporaryNsisRoot, $installedNsisRoot) - $installedNsisInventory = New-WagglePrebuiltInventory $installedNsisRoot - if (($installedNsisInventory | ConvertTo-Json -Depth 8 -Compress) -cne - ($receipt.nsisInventory | ConvertTo-Json -Depth 8 -Compress)) { - throw 'Installed signer NSIS closure changed during receipt-bound staging.' - } - $resourceEntries = @($receipt.resourcesInventory.entries) - Assert-WaggleCanonicalInventoryEntries $resourceEntries 'Hosted resources inventory' - $sourceResourcesRoot = Get-TrustedPath ` - (Join-Path $unsignedRoot 'resources') 'Hosted source resources' 'Container' - $signingResourcesRoot = Get-TrustedPath ` - (Join-Path $signingRoot 'resources') 'Hosted signing resources' 'Container' - $canonicalResourcesRoot = Get-TrustedPath ` - ([IO.Path]::GetFullPath('app/src-tauri/resources')) ` - 'Canonical repository resources' 'Container' - $canonicalResourcesPrefix = $canonicalResourcesRoot.TrimEnd('\') + '\' - $materializedEntries = [Collections.Generic.List[object]]::new() - foreach ($entry in $resourceEntries) { - $relative = [string]$entry.path - $sourcePath = Get-TrustedPath ` - (Join-Path $sourceResourcesRoot $relative) 'Hosted resource file' -AllowHardLink - $signingPath = Get-TrustedPath ` - (Join-Path $signingResourcesRoot $relative) 'Hosted signing resource file' -AllowHardLink - foreach ($path in @($sourcePath, $signingPath)) { - $item = Get-Item -LiteralPath $path -Force - if ([long]$item.Length -ne [long]$entry.size -or - (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -cne - [string]$entry.sha256) { - throw 'Hosted resource file differs from its canonical build receipt.' - } - } - $destinationPath = [IO.Path]::GetFullPath( - (Join-Path $canonicalResourcesRoot $relative) - ) - if (-not $destinationPath.StartsWith( - $canonicalResourcesPrefix, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Hosted resource destination escaped the canonical repository resources root.' - } - [IO.Directory]::CreateDirectory((Split-Path $destinationPath -Parent)) | Out-Null - if (Test-Path -LiteralPath $destinationPath) { - $existing = Get-TrustedPath ` - $destinationPath 'Existing canonical resource' -AllowHardLink - if ((Get-FileHash -LiteralPath $existing -Algorithm SHA256).Hash -cne - [string]$entry.sha256) { - throw 'Tracked canonical resource differs from the hosted build receipt.' - } - } else { - [IO.File]::Copy($sourcePath, $destinationPath, $false) - } - $materialized = Get-Item -LiteralPath $destinationPath -Force - $materializedEntries.Add([pscustomobject][ordered]@{ - path = $relative - size = [long]$materialized.Length - sha256 = (Get-FileHash -LiteralPath $destinationPath -Algorithm SHA256).Hash - }) - } - if (@(Get-ChildItem -LiteralPath $canonicalResourcesRoot -Recurse -Force -File).Count -ne - $resourceEntries.Count -or - (Get-WaggleInventorySha256 @($materializedEntries)) -cne - [string]$receipt.resourcesInventory.sha256) { - throw 'Materialized canonical repository resources differ from the hosted build receipt.' - } - $canonicalService = Get-TrustedPath ` - (Join-Path $canonicalResourcesRoot 'service.js') ` - 'Canonical source-bound service.js' - "unsigned_root=$unsignedRoot" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "signing_root=$signingRoot" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "receipt_path=$signingReceiptForPackage" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "source_service_path=$canonicalService" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - - - name: Provision pinned Artifact Signing client package - id: artifact-signing-package - shell: pwsh - run: | - $packagePath = Join-Path $env:RUNNER_TEMP 'Microsoft.ArtifactSigning.Client.1.0.128.nupkg' - if (Test-Path -LiteralPath $packagePath) { throw 'Artifact Signing package destination already exists.' } - Invoke-WebRequest ` - -Uri 'https://www.nuget.org/api/v2/package/Microsoft.ArtifactSigning.Client/1.0.128' ` - -OutFile $packagePath ` - -UseBasicParsing - $actualSha256 = (Get-FileHash -LiteralPath $packagePath -Algorithm SHA256).Hash - if ($actualSha256 -cne '74BD7D27E6CE1051409C38D9B46BC8DF0400ECD643D51FFBF2AC00869061E40B') { - throw 'Official Artifact Signing package does not match the repository-pinned SHA-256.' - } - "package_path=$packagePath" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - - - name: Validate protected Azure OIDC bindings - shell: pwsh - env: - AZURE_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }} - AZURE_TENANT_ID: ${{ vars.AZURE_TENANT_ID }} - AZURE_SUBSCRIPTION_ID: ${{ vars.AZURE_SUBSCRIPTION_ID }} - run: | - foreach ($entry in @( - @('AZURE_CLIENT_ID', [string]$env:AZURE_CLIENT_ID), - @('AZURE_TENANT_ID', [string]$env:AZURE_TENANT_ID), - @('AZURE_SUBSCRIPTION_ID', [string]$env:AZURE_SUBSCRIPTION_ID) - )) { - if ([string]$entry[1] -cnotmatch '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$' -or - [string]$entry[1] -cne ([string]$entry[1]).Trim()) { - throw "$([string]$entry[0]) must be one exact GUID in the protected signing environment." - } - } - - - name: Provision pinned portable signing toolchain - id: portable-toolchain - shell: pwsh - run: | - $stageRoot = Join-Path $env:RUNNER_TEMP 'waggle-portable-signing-stage' - $root = Join-Path $stageRoot 'toolchain' - if (Test-Path -LiteralPath $root) { throw 'Portable signing toolchain root already exists.' } - . ./app/scripts/sign-windows-artifact.ps1 - $root = New-PrivateDirectory $root - $downloads = Join-Path $stageRoot 'downloads' - New-Item -ItemType Directory -Path $downloads | Out-Null - $packages = @( - [pscustomobject]@{ - Name = 'node.zip' - Uri = 'https://nodejs.org/dist/v22.22.2/node-v22.22.2-win-x64.zip' - Sha256 = '7C93E9D92BF68C07182B471AA187E35EE6CD08EF0F24AB060DFFF605FCC1C57C' - }, - [pscustomobject]@{ - Name = 'mingit.zip' - Uri = 'https://github.com/git-for-windows/git/releases/download/v2.51.0.windows.1/MinGit-2.51.0-64-bit.zip' - Sha256 = 'C2C955A21FA99889D83F485F24FA5D9A38FFFC2D509D4022385510E11C26B250' - }, - [pscustomobject]@{ - Name = 'sevenzip.exe' - Uri = 'https://www.7-zip.org/a/7z2501-x64.exe' - Sha256 = '78AFA2A1C773CAF3CF7EDF62F857D2A8A5DA55FB0FFF5DA416074C0D28B2B55F' - } - ) - foreach ($package in $packages) { - $path = Join-Path $downloads $package.Name - Invoke-WebRequest -Uri $package.Uri -OutFile $path -UseBasicParsing - if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -cne $package.Sha256) { - throw "Portable signing package has the wrong SHA-256: $($package.Name)" - } - } - $nodeRoot = Join-Path $root 'node' - $gitRoot = Join-Path $root 'git' - $sevenZipRoot = Join-Path $root 'sevenzip' - Expand-Archive -LiteralPath (Join-Path $downloads 'node.zip') -DestinationPath $nodeRoot - Expand-Archive -LiteralPath (Join-Path $downloads 'mingit.zip') -DestinationPath $gitRoot - New-Item -ItemType Directory -Path $sevenZipRoot | Out-Null - & 'C:\Windows\System32\tar.exe' ` - -xf (Join-Path $downloads 'sevenzip.exe') ` - -C $sevenZipRoot - if ($LASTEXITCODE -ne 0) { throw 'Pinned 7-Zip package extraction failed.' } - $nodePath = Join-Path $nodeRoot 'node-v22.22.2-win-x64\node.exe' - $gitPath = Join-Path $gitRoot 'cmd\git.exe' - $gitRuntimePath = Join-Path $gitRoot 'mingw64\bin\git.exe' - $sevenZipPath = Join-Path $sevenZipRoot '7z.exe' - $sevenZipDllPath = Join-Path $sevenZipRoot '7z.dll' - $innerFiles = @( - @($nodePath, 'AE1A50511BE58E987483FDBC12125407443926D2D394669ADE2352776E920DD3'), - @($gitPath, '34A408843194BE320D8A87A3C12CD5C7D2E08D03B24567A41DB32E21D12569D2'), - @($gitRuntimePath, '755D4896D35663D0FF08924F84507F35236B83D240635B512C519BF43CC71A87'), - @($sevenZipPath, '4CD7D776C686427226A151789D2D61F0B2ED2C392148CC4E69C0238362FAFECF'), - @($sevenZipDllPath, '5BD20FB38499D95C39594F41D4781B6181B3304B7F1F4D06B0182F514E7EAA74') - ) - foreach ($binding in $innerFiles) { - $path = [IO.Path]::GetFullPath([string]$binding[0]) - if (-not $path.StartsWith( - [IO.Path]::GetFullPath($root).TrimEnd('\') + '\', - [StringComparison]::OrdinalIgnoreCase - ) -or - -not (Test-Path -LiteralPath $path -PathType Leaf) -or - (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -cne [string]$binding[1]) { - throw 'Portable signing toolchain inner binary does not match its pinned identity.' - } - } - $nodeSignature = Get-AuthenticodeSignature -LiteralPath $nodePath - $gitSignature = Get-AuthenticodeSignature -LiteralPath $gitPath - $gitRuntimeSignature = Get-AuthenticodeSignature -LiteralPath $gitRuntimePath - if ($nodeSignature.Status -ne 'Valid' -or - [string]$nodeSignature.SignerCertificate.Subject -cne - 'CN=OpenJS Foundation, O=OpenJS Foundation, L=San Francisco, S=California, C=US' -or - $gitSignature.Status -ne 'Valid' -or - [string]$gitSignature.SignerCertificate.Subject -cne - 'CN=Johannes Schindelin, O=Johannes Schindelin, S=Nordrhein-Westfalen, C=DE' -or - $gitRuntimeSignature.Status -ne 'Valid' -or - [string]$gitRuntimeSignature.SignerCertificate.Subject -cne - 'CN=Johannes Schindelin, O=Johannes Schindelin, S=Nordrhein-Westfalen, C=DE') { - throw 'Portable Node.js or Git lacks its approved Authenticode publisher evidence.' - } - $allowedFiles = @( - Get-ChildItem -LiteralPath $root -Recurse -Force | - Where-Object { -not $_.PSIsContainer } - ) - foreach ($file in $allowedFiles) { - if (($file.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -or - @(Get-Item -LiteralPath $file.FullName -Stream *).Count -ne 1) { - throw "Portable signing toolchain contains a linked file or alternate data stream: $($file.FullName)" - } - } - $toolchainInventory = New-WagglePrebuiltInventory -Root $root - if (@($toolchainInventory.entries).Count -ne 2495 -or - [string]$toolchainInventory.sha256 -cne - 'D64F897D4E1A7F07FE9BA62D6AF062EF9F0E41C595CDAF2F3C4F73991BBEA0F5') { - throw 'Portable signing toolchain differs from the pinned official extracted closure.' - } - $receiptPath = Join-Path $stageRoot 'portable-toolchain-receipt.json' - if (Test-Path -LiteralPath $receiptPath) { - throw 'Portable signing toolchain receipt destination already exists.' - } - $toolchainReceipt = [ordered]@{ - schemaVersion = 1 - portableToolchainRoot = [IO.Path]::GetFullPath($root) - archives = [ordered]@{ - node = [ordered]@{ - path = [IO.Path]::GetFullPath((Join-Path $downloads 'node.zip')) - sha256 = '7C93E9D92BF68C07182B471AA187E35EE6CD08EF0F24AB060DFFF605FCC1C57C' - } - git = [ordered]@{ - path = [IO.Path]::GetFullPath((Join-Path $downloads 'mingit.zip')) - sha256 = 'C2C955A21FA99889D83F485F24FA5D9A38FFFC2D509D4022385510E11C26B250' - } - sevenZip = [ordered]@{ - path = [IO.Path]::GetFullPath((Join-Path $downloads 'sevenzip.exe')) - sha256 = '78AFA2A1C773CAF3CF7EDF62F857D2A8A5DA55FB0FFF5DA416074C0D28B2B55F' - } - } - inventory = $toolchainInventory - } - Write-WaggleJsonNoBom $receiptPath $toolchainReceipt - $receiptSha256 = (Get-FileHash -LiteralPath $receiptPath -Algorithm SHA256).Hash - if ($receiptSha256 -notmatch '^[0-9A-F]{64}$') { - throw 'Portable signing toolchain receipt digest is invalid.' - } - "root=$root" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "node_path=$nodePath" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "git_path=$gitPath" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "sevenzip_path=$sevenZipPath" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "receipt_path=$receiptPath" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "receipt_sha256=$receiptSha256" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - - - name: Stage fully inventoried Windows signing preparation - id: stage-prepared - shell: pwsh - env: - WAGGLE_RELEASE_MODE: ${{ steps.release-mode.outputs.mode }} - WAGGLE_CANDIDATE_VERSION: ${{ steps.release-mode.outputs.candidate_version }} - WINDOWS_BOOTSTRAP_RELEASE_IDENTITY: ${{ steps.release-mode.outputs.bootstrap_identity }} - WINDOWS_UPGRADE_BASE_TAG: ${{ steps.release-mode.outputs.upgrade_base_tag }} - WINDOWS_UPGRADE_BASE_ASSET_NAME: ${{ steps.release-mode.outputs.upgrade_base_asset_name }} - WINDOWS_UPGRADE_BASE_SHA256: ${{ steps.release-mode.outputs.upgrade_base_sha256 }} - WINDOWS_UPGRADE_BASE_COMMIT: ${{ steps.release-mode.outputs.upgrade_base_commit }} - WINDOWS_CODESIGN_APPROVED_SUBJECT: ${{ steps.signer-identity.outputs.subject }} - AZURE_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }} - AZURE_TENANT_ID: ${{ vars.AZURE_TENANT_ID }} - AZURE_SUBSCRIPTION_ID: ${{ vars.AZURE_SUBSCRIPTION_ID }} - EXPECTED_BUILD_RECEIPT_SHA256: ${{ needs.build-windows-prebuilt.outputs.build_receipt_sha256 }} - EXPECTED_BUILD_ARTIFACT_ID: ${{ needs.build-windows-prebuilt.outputs.artifact_id }} - EXPECTED_BUILD_ARTIFACT_DIGEST: ${{ needs.build-windows-prebuilt.outputs.artifact_digest }} - EXPECTED_BUILD_HANDOFF_SIZE_BYTES: ${{ needs.build-windows-prebuilt.outputs.handoff_size_bytes }} - run: | - function Write-WaggleJsonNoBom { - param([string]$Path, [object]$Value) - [IO.File]::WriteAllText( - $Path, - ($Value | ConvertTo-Json -Depth 32), - [Text.UTF8Encoding]::new($false) - ) - } - - function Copy-WagglePreparedItem { - param([string]$Source, [string]$Destination, [string]$Kind = 'Leaf') - if (-not (Test-Path -LiteralPath $Source -PathType $Kind) -or - (Test-Path -LiteralPath $Destination)) { - throw "Signing preparation source is missing or destination already exists: $Destination" - } - [IO.Directory]::CreateDirectory((Split-Path $Destination -Parent)) | Out-Null - Copy-Item -LiteralPath $Source -Destination $Destination -Recurse -ErrorAction Stop - } - - function Assert-WagglePreparedTree { - param([string]$Root, [string]$Label) - $trustedRoot = [IO.Path]::GetFullPath((Resolve-Path -LiteralPath $Root).Path) - $items = @(Get-ChildItem -LiteralPath $trustedRoot -Recurse -Force) - $maxItems = [int]$env:WINDOWS_SIGNING_TRANSPORT_MAX_ITEMS - if ($items.Count -gt $maxItems) { - throw "$Label exceeds the bounded $maxItems-item transport envelope." - } - foreach ($item in $items) { - $linkProperty = $item.PSObject.Properties['LinkType'] - $linkType = if ($null -eq $linkProperty) { '' } else { [string]$linkProperty.Value } - if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -or - -not [string]::IsNullOrEmpty($linkType)) { - throw "$Label contains a linked or reparse filesystem object." - } - if (-not $item.PSIsContainer -and - @(Get-Item -LiteralPath $item.FullName -Stream *).Count -ne 1) { - throw "$Label contains a file with an alternate data stream." - } - } - } - - foreach ($digest in @( - [string]$env:EXPECTED_BUILD_RECEIPT_SHA256, - [string]$env:EXPECTED_BUILD_ARTIFACT_DIGEST - )) { - if ($digest -cnotmatch '^[0-9A-Fa-f]{64}$') { - throw 'Signing preparation received an invalid upstream digest.' - } - } - if ($env:EXPECTED_BUILD_ARTIFACT_ID -cnotmatch '^[1-9][0-9]*$' -or - $env:EXPECTED_BUILD_HANDOFF_SIZE_BYTES -cnotmatch '^[1-9][0-9]*$') { - throw 'Signing preparation received an invalid upstream artifact identity or size.' - } - - . ./app/scripts/sign-windows-artifact.ps1 - $preparedRoot = Join-Path $env:RUNNER_TEMP 'waggle-windows-signing-preparation' - $payloadRoot = Join-Path $preparedRoot 'payload' - if (Test-Path -LiteralPath $preparedRoot) { - throw 'Windows signing preparation root already exists.' - } - [IO.Directory]::CreateDirectory($payloadRoot) | Out-Null - - foreach ($variant in @('unsigned', 'signing')) { - $sourceRoot = Join-Path $env:RUNNER_TEMP "waggle-prebuilt-$variant" - $destinationRoot = Join-Path $payloadRoot "raw\$variant" - foreach ($relative in @('build-receipt.json', 'prebuilt', 'nsis-toolchain')) { - $kind = if ($relative -eq 'build-receipt.json') { 'Leaf' } else { 'Container' } - Copy-WagglePreparedItem ` - (Join-Path $sourceRoot $relative) (Join-Path $destinationRoot $relative) $kind - } - } - - $artifactSigningDestination = Join-Path $payloadRoot ` - 'artifact-signing\Microsoft.ArtifactSigning.Client.1.0.128.nupkg' - Copy-WagglePreparedItem ` - '${{ steps.artifact-signing-package.outputs.package_path }}' ` - $artifactSigningDestination - if ((Get-FileHash -LiteralPath $artifactSigningDestination -Algorithm SHA256).Hash -cne - '74BD7D27E6CE1051409C38D9B46BC8DF0400ECD643D51FFBF2AC00869061E40B') { - throw 'Staged Artifact Signing package differs from its pinned identity.' - } - - $portableSourceRoot = '${{ steps.portable-toolchain.outputs.root }}' - $portableSourceReceiptPath = '${{ steps.portable-toolchain.outputs.receipt_path }}' - $portableSourceReceipt = Get-Content -Raw -LiteralPath $portableSourceReceiptPath | - ConvertFrom-Json -Depth 32 - if ([int]$portableSourceReceipt.schemaVersion -ne 1 -or - [string]$portableSourceReceipt.portableToolchainRoot -cne - [IO.Path]::GetFullPath($portableSourceRoot) -or - @($portableSourceReceipt.inventory.entries).Count -ne 2495 -or - [string]$portableSourceReceipt.inventory.sha256 -cne - 'D64F897D4E1A7F07FE9BA62D6AF062EF9F0E41C595CDAF2F3C4F73991BBEA0F5') { - throw 'Portable signing toolchain source receipt is not the pinned semantic closure.' - } - Copy-WagglePreparedItem ` - $portableSourceRoot (Join-Path $payloadRoot 'portable\toolchain') 'Container' - $portableDownloadsSource = Join-Path (Split-Path $portableSourceRoot -Parent) 'downloads' - Copy-WagglePreparedItem ` - $portableDownloadsSource (Join-Path $payloadRoot 'portable\downloads') 'Container' - $relativePortableReceipt = [ordered]@{ - schemaVersion = 1 - portableToolchainRoot = 'portable\toolchain' - archives = [ordered]@{ - node = [ordered]@{ - path = 'portable\downloads\node.zip' - sha256 = '7C93E9D92BF68C07182B471AA187E35EE6CD08EF0F24AB060DFFF605FCC1C57C' - } - git = [ordered]@{ - path = 'portable\downloads\mingit.zip' - sha256 = 'C2C955A21FA99889D83F485F24FA5D9A38FFFC2D509D4022385510E11C26B250' - } - sevenZip = [ordered]@{ - path = 'portable\downloads\sevenzip.exe' - sha256 = '78AFA2A1C773CAF3CF7EDF62F857D2A8A5DA55FB0FFF5DA416074C0D28B2B55F' - } - } - inventory = $portableSourceReceipt.inventory - } - Write-WaggleJsonNoBom ` - (Join-Path $payloadRoot 'portable\portable-toolchain-receipt.json') ` - $relativePortableReceipt - - $tauriDestination = Join-Path $payloadRoot 'tauri\node_modules\@tauri-apps' - foreach ($packageName in @('cli', 'cli-win32-x64-msvc')) { - $sourcePackage = Join-Path 'app\node_modules\@tauri-apps' $packageName - $package = Get-Content -Raw -LiteralPath (Join-Path $sourcePackage 'package.json') | - ConvertFrom-Json - if ([string]$package.name -cne "@tauri-apps/$packageName" -or - [string]$package.version -cne '2.10.1') { - throw "Prepared Tauri package is not the locked Windows package: $packageName" - } - Copy-WagglePreparedItem ` - $sourcePackage (Join-Path $tauriDestination $packageName) 'Container' - } - - Assert-WagglePreparedTree $payloadRoot 'Windows signing preparation payload' - $payloadInventory = New-WagglePrebuiltInventory -Root $payloadRoot - $allowedPrefixes = @( - 'raw\unsigned\', - 'raw\signing\', - 'portable\toolchain\', - 'portable\downloads\', - 'tauri\node_modules\@tauri-apps\cli\', - 'tauri\node_modules\@tauri-apps\cli-win32-x64-msvc\' - ) - $allowedExact = @( - 'artifact-signing\Microsoft.ArtifactSigning.Client.1.0.128.nupkg', - 'portable\portable-toolchain-receipt.json' - ) - foreach ($entry in @($payloadInventory.entries)) { - $relative = [string]$entry.path - $allowed = $allowedExact -ccontains $relative - foreach ($prefix in $allowedPrefixes) { - if ($relative.StartsWith($prefix, [StringComparison]::Ordinal)) { - $allowed = $true - break - } - } - if (-not $allowed) { - throw "Windows signing preparation contains a non-allowlisted payload path: $relative" - } - } - - $preparationReceipt = [ordered]@{ - schemaVersion = 1 - repository = 'marolinik/waggle-os' - sourceRevision = $env:GITHUB_SHA - candidateTag = $env:GITHUB_REF_NAME - candidateVersion = $env:WAGGLE_CANDIDATE_VERSION - workflowRef = $env:GITHUB_WORKFLOW_REF - workflowSha = $env:GITHUB_WORKFLOW_SHA - release = [ordered]@{ - mode = $env:WAGGLE_RELEASE_MODE - bootstrapIdentity = $env:WINDOWS_BOOTSTRAP_RELEASE_IDENTITY - upgradeBaseTag = $env:WINDOWS_UPGRADE_BASE_TAG - upgradeBaseAssetName = $env:WINDOWS_UPGRADE_BASE_ASSET_NAME - upgradeBaseSha256 = $env:WINDOWS_UPGRADE_BASE_SHA256 - upgradeBaseCommit = $env:WINDOWS_UPGRADE_BASE_COMMIT - } - signerSubject = $env:WINDOWS_CODESIGN_APPROVED_SUBJECT - build = [ordered]@{ - receiptSha256 = $env:EXPECTED_BUILD_RECEIPT_SHA256.ToUpperInvariant() - artifactId = $env:EXPECTED_BUILD_ARTIFACT_ID - artifactDigest = $env:EXPECTED_BUILD_ARTIFACT_DIGEST.ToUpperInvariant() - handoffSizeBytes = $env:EXPECTED_BUILD_HANDOFF_SIZE_BYTES - } - azure = [ordered]@{ - clientId = $env:AZURE_CLIENT_ID - tenantId = $env:AZURE_TENANT_ID - subscriptionId = $env:AZURE_SUBSCRIPTION_ID - audience = 'api://AzureADTokenExchange' - } - payloadInventory = $payloadInventory - } - $preparationReceiptPath = Join-Path $preparedRoot 'preparation-receipt.json' - Write-WaggleJsonNoBom $preparationReceiptPath $preparationReceipt - Assert-WagglePreparedTree $preparedRoot 'Windows signing preparation artifact' - $receiptSha256 = (Get-FileHash -LiteralPath $preparationReceiptPath -Algorithm SHA256).Hash - $sizeBytes = [long]( - Get-ChildItem -LiteralPath $preparedRoot -Recurse -Force -File | - Measure-Object -Property Length -Sum - ).Sum - if ($receiptSha256 -cnotmatch '^[0-9A-F]{64}$' -or $sizeBytes -le 0) { - throw 'Windows signing preparation receipt or aggregate size is invalid.' - } - "receipt_sha256=$receiptSha256" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "size_bytes=$sizeBytes" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - - - name: Upload immutable prepared Windows signing handoff - id: upload-prepared - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - with: - name: waggle-windows-signing-prepared-${{ github.sha }} - path: ${{ runner.temp }}\waggle-windows-signing-preparation - if-no-files-found: error - include-hidden-files: true - retention-days: 7 - - sign-windows: - needs: [build-windows-prebuilt, prepare-windows-signing] - runs-on: windows-latest - permissions: - contents: read - id-token: write - outputs: - release_mode: ${{ needs.prepare-windows-signing.outputs.release_mode }} - candidate_sha256: ${{ steps.stage-signed.outputs.candidate_sha256 }} - candidate_version: ${{ steps.stage-signed.outputs.candidate_version }} - bootstrap_identity: ${{ needs.prepare-windows-signing.outputs.bootstrap_identity }} - upgrade_base_tag: ${{ needs.prepare-windows-signing.outputs.upgrade_base_tag }} - upgrade_base_asset_name: ${{ needs.prepare-windows-signing.outputs.upgrade_base_asset_name }} - upgrade_base_sha256: ${{ needs.prepare-windows-signing.outputs.upgrade_base_sha256 }} - upgrade_base_commit: ${{ needs.prepare-windows-signing.outputs.upgrade_base_commit }} - signer_subject: ${{ needs.prepare-windows-signing.outputs.signer_subject }} - build_receipt_sha256: ${{ needs.build-windows-prebuilt.outputs.build_receipt_sha256 }} - build_artifact_id: ${{ needs.build-windows-prebuilt.outputs.artifact_id }} - build_artifact_digest: ${{ needs.build-windows-prebuilt.outputs.artifact_digest }} - handoff_receipt_sha256: ${{ steps.stage-signed.outputs.receipt_sha256 }} - artifact_id: ${{ steps.upload-signed.outputs.artifact-id }} - artifact_digest: ${{ steps.upload-signed.outputs.artifact-digest }} - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - with: - fetch-depth: 0 - persist-credentials: false - - - name: Validate exact hosted OIDC release boundary - shell: pwsh - run: | - $version = [string](Get-Content -Raw -LiteralPath 'app/src-tauri/tauri.conf.json' | ConvertFrom-Json).version - if ($env:GITHUB_ACTIONS -cne 'true' -or - $env:GITHUB_EVENT_NAME -cne 'push' -or - $env:GITHUB_REPOSITORY -cne 'marolinik/waggle-os' -or - $env:GITHUB_REF_TYPE -cne 'tag' -or - $env:GITHUB_REF -cne "refs/tags/v$version" -or - $env:GITHUB_REF_NAME -cne "v$version" -or - $env:GITHUB_WORKFLOW_REF -cne "marolinik/waggle-os/.github/workflows/release.yml@$env:GITHUB_REF" -or - $env:GITHUB_WORKFLOW_SHA -cne $env:GITHUB_SHA -or - $env:RUNNER_ENVIRONMENT -cne 'github-hosted' -or - $env:GITHUB_SHA -cnotmatch '^[0-9a-f]{40}$') { - throw 'Windows signing requires the exact hosted push, repository, tag, workflow, and revision boundary.' - } - $checkedOutRevision = (git rev-parse --verify HEAD).Trim().ToLowerInvariant() - if ($LASTEXITCODE -ne 0 -or $checkedOutRevision -cne $env:GITHUB_SHA -or - @(git status --porcelain=v1 --untracked-files=all).Count -ne 0) { - throw 'Windows signing checkout is not the clean GITHUB_SHA revision.' - } - - - name: Validate initial signing revision on fresh origin main - shell: pwsh - run: | - $checkedOutRevision = (git rev-parse --verify HEAD).Trim().ToLowerInvariant() - $remoteMainRevision = (git rev-parse --verify refs/remotes/origin/main).Trim().ToLowerInvariant() - if ($LASTEXITCODE -ne 0 -or - $checkedOutRevision -cne $env:GITHUB_SHA -or - $env:GITHUB_WORKFLOW_SHA -cne $env:GITHUB_SHA -or - $remoteMainRevision -cnotmatch '^[0-9a-f]{40}$' -or - @(git status --porcelain=v1 --untracked-files=all).Count -ne 0) { - throw 'Initial signing checkout, workflow, or origin/main revision evidence is invalid.' - } - git merge-base --is-ancestor $env:GITHUB_SHA refs/remotes/origin/main - if ($LASTEXITCODE -ne 0) { - throw 'The exact signing revision is not contained by initial fresh origin/main.' - } - - - name: Download immutable prepared Windows signing handoff - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 - with: - artifact-ids: ${{ needs.prepare-windows-signing.outputs.artifact_id }} - path: ${{ runner.temp }}\waggle-windows-signing-prepared - merge-multiple: true - - - name: Verify and restore immutable prepared Windows signing handoff - id: verify-prepared - shell: pwsh - env: - EXPECTED_PREPARATION_RECEIPT_SHA256: ${{ needs.prepare-windows-signing.outputs.preparation_receipt_sha256 }} - EXPECTED_PREPARATION_ARTIFACT_ID: ${{ needs.prepare-windows-signing.outputs.artifact_id }} - EXPECTED_PREPARATION_ARTIFACT_DIGEST: ${{ needs.prepare-windows-signing.outputs.artifact_digest }} - EXPECTED_PREPARATION_SIZE_BYTES: ${{ needs.prepare-windows-signing.outputs.preparation_size_bytes }} - EXPECTED_RELEASE_MODE: ${{ needs.prepare-windows-signing.outputs.release_mode }} - EXPECTED_CANDIDATE_VERSION: ${{ needs.prepare-windows-signing.outputs.candidate_version }} - EXPECTED_BOOTSTRAP_IDENTITY: ${{ needs.prepare-windows-signing.outputs.bootstrap_identity }} - EXPECTED_UPGRADE_BASE_TAG: ${{ needs.prepare-windows-signing.outputs.upgrade_base_tag }} - EXPECTED_UPGRADE_BASE_ASSET_NAME: ${{ needs.prepare-windows-signing.outputs.upgrade_base_asset_name }} - EXPECTED_UPGRADE_BASE_SHA256: ${{ needs.prepare-windows-signing.outputs.upgrade_base_sha256 }} - EXPECTED_UPGRADE_BASE_COMMIT: ${{ needs.prepare-windows-signing.outputs.upgrade_base_commit }} - EXPECTED_SIGNER_SUBJECT: ${{ needs.prepare-windows-signing.outputs.signer_subject }} - EXPECTED_BUILD_RECEIPT_SHA256: ${{ needs.build-windows-prebuilt.outputs.build_receipt_sha256 }} - EXPECTED_BUILD_ARTIFACT_ID: ${{ needs.build-windows-prebuilt.outputs.artifact_id }} - EXPECTED_BUILD_ARTIFACT_DIGEST: ${{ needs.build-windows-prebuilt.outputs.artifact_digest }} - EXPECTED_BUILD_HANDOFF_SIZE_BYTES: ${{ needs.build-windows-prebuilt.outputs.handoff_size_bytes }} - AZURE_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }} - AZURE_TENANT_ID: ${{ vars.AZURE_TENANT_ID }} - AZURE_SUBSCRIPTION_ID: ${{ vars.AZURE_SUBSCRIPTION_ID }} - run: | - function Write-WaggleJsonNoBom { - param([string]$Path, [object]$Value) - [IO.File]::WriteAllText( - $Path, - ($Value | ConvertTo-Json -Depth 32), - [Text.UTF8Encoding]::new($false) - ) - } - - function Assert-WaggleTransportTree { - param([string]$Root, [string]$Label) - $items = @(Get-ChildItem -LiteralPath $Root -Recurse -Force) - $maxItems = [int]$env:WINDOWS_SIGNING_TRANSPORT_MAX_ITEMS - if ($items.Count -gt $maxItems) { - throw "$Label exceeds the bounded $maxItems-item transport envelope." - } - foreach ($item in $items) { - $linkProperty = $item.PSObject.Properties['LinkType'] - $linkType = if ($null -eq $linkProperty) { '' } else { [string]$linkProperty.Value } - if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -or - -not [string]::IsNullOrEmpty($linkType)) { - throw "$Label contains a linked or reparse filesystem object." - } - if (-not $item.PSIsContainer -and - @(Get-Item -LiteralPath $item.FullName -Stream *).Count -ne 1) { - throw "$Label contains a file with an alternate data stream." - } - } - } - - function Assert-WaggleExactValue { - param([object]$Actual, [string]$Expected, [string]$Label) - if ([string]$Actual -cne $Expected) { - throw "Prepared Windows signing binding differs: $Label" - } - } - - $preparedRoot = [IO.Path]::GetFullPath( - (Resolve-Path -LiteralPath (Join-Path $env:RUNNER_TEMP 'waggle-windows-signing-prepared')).Path - ) - $payloadRoot = Join-Path $preparedRoot 'payload' - $receiptPath = Join-Path $preparedRoot 'preparation-receipt.json' - foreach ($digest in @( - [string]$env:EXPECTED_PREPARATION_RECEIPT_SHA256, - [string]$env:EXPECTED_PREPARATION_ARTIFACT_DIGEST, - [string]$env:EXPECTED_BUILD_RECEIPT_SHA256, - [string]$env:EXPECTED_BUILD_ARTIFACT_DIGEST - )) { - if ($digest -cnotmatch '^[0-9A-Fa-f]{64}$') { - throw 'Prepared Windows signing digest binding is invalid.' - } - } - if ($env:EXPECTED_PREPARATION_ARTIFACT_ID -cnotmatch '^[1-9][0-9]*$' -or - $env:EXPECTED_BUILD_ARTIFACT_ID -cnotmatch '^[1-9][0-9]*$' -or - $env:EXPECTED_PREPARATION_SIZE_BYTES -cnotmatch '^[1-9][0-9]*$') { - throw 'Prepared Windows signing artifact identity or size binding is invalid.' - } - Assert-WaggleTransportTree $preparedRoot 'Prepared Windows signing artifact' - $actualSizeBytes = [long]( - Get-ChildItem -LiteralPath $preparedRoot -Recurse -Force -File | - Measure-Object -Property Length -Sum - ).Sum - if (-not (Test-Path -LiteralPath $payloadRoot -PathType Container) -or - -not (Test-Path -LiteralPath $receiptPath -PathType Leaf) -or - $actualSizeBytes -ne [long]$env:EXPECTED_PREPARATION_SIZE_BYTES -or - (Get-FileHash -LiteralPath $receiptPath -Algorithm SHA256).Hash -cne - $env:EXPECTED_PREPARATION_RECEIPT_SHA256.ToUpperInvariant()) { - throw 'Prepared Windows signing artifact differs from its immutable receipt or size.' - } - - . ./app/scripts/sign-windows-artifact.ps1 - $receipt = Get-Content -Raw -LiteralPath $receiptPath | ConvertFrom-Json -Depth 32 - if ([int]$receipt.schemaVersion -ne 1) { - throw 'Prepared Windows signing receipt schema is invalid.' - } - Assert-WaggleExactValue $receipt.repository 'marolinik/waggle-os' 'repository' - Assert-WaggleExactValue $receipt.sourceRevision $env:GITHUB_SHA 'sourceRevision' - Assert-WaggleExactValue $receipt.candidateTag $env:GITHUB_REF_NAME 'candidateTag' - Assert-WaggleExactValue $receipt.candidateVersion $env:EXPECTED_CANDIDATE_VERSION 'candidateVersion' - Assert-WaggleExactValue $receipt.workflowRef $env:GITHUB_WORKFLOW_REF 'workflowRef' - Assert-WaggleExactValue $receipt.workflowSha $env:GITHUB_WORKFLOW_SHA 'workflowSha' - Assert-WaggleExactValue $receipt.release.mode $env:EXPECTED_RELEASE_MODE 'release.mode' - Assert-WaggleExactValue $receipt.release.bootstrapIdentity $env:EXPECTED_BOOTSTRAP_IDENTITY 'release.bootstrapIdentity' - Assert-WaggleExactValue $receipt.release.upgradeBaseTag $env:EXPECTED_UPGRADE_BASE_TAG 'release.upgradeBaseTag' - Assert-WaggleExactValue $receipt.release.upgradeBaseAssetName $env:EXPECTED_UPGRADE_BASE_ASSET_NAME 'release.upgradeBaseAssetName' - Assert-WaggleExactValue $receipt.release.upgradeBaseSha256 $env:EXPECTED_UPGRADE_BASE_SHA256 'release.upgradeBaseSha256' - Assert-WaggleExactValue $receipt.release.upgradeBaseCommit $env:EXPECTED_UPGRADE_BASE_COMMIT 'release.upgradeBaseCommit' - Assert-WaggleExactValue $receipt.signerSubject $env:EXPECTED_SIGNER_SUBJECT 'signerSubject' - Assert-WaggleExactValue $receipt.build.receiptSha256 $env:EXPECTED_BUILD_RECEIPT_SHA256.ToUpperInvariant() 'build.receiptSha256' - Assert-WaggleExactValue $receipt.build.artifactId $env:EXPECTED_BUILD_ARTIFACT_ID 'build.artifactId' - Assert-WaggleExactValue $receipt.build.artifactDigest $env:EXPECTED_BUILD_ARTIFACT_DIGEST.ToUpperInvariant() 'build.artifactDigest' - Assert-WaggleExactValue $receipt.build.handoffSizeBytes $env:EXPECTED_BUILD_HANDOFF_SIZE_BYTES 'build.handoffSizeBytes' - Assert-WaggleExactValue $receipt.azure.clientId $env:AZURE_CLIENT_ID 'azure.clientId' - Assert-WaggleExactValue $receipt.azure.tenantId $env:AZURE_TENANT_ID 'azure.tenantId' - Assert-WaggleExactValue $receipt.azure.subscriptionId $env:AZURE_SUBSCRIPTION_ID 'azure.subscriptionId' - Assert-WaggleExactValue $receipt.azure.audience 'api://AzureADTokenExchange' 'azure.audience' - - $actualPayloadInventory = New-WagglePrebuiltInventory -Root $payloadRoot - if (($actualPayloadInventory | ConvertTo-Json -Depth 32 -Compress) -cne - ($receipt.payloadInventory | ConvertTo-Json -Depth 32 -Compress)) { - throw 'Prepared Windows signing payload differs from its canonical inventory.' - } - - $unsignedRoot = Get-TrustedPath ` - (Join-Path $payloadRoot 'raw\unsigned\prebuilt') 'Prepared unsigned root' 'Container' - $signingRoot = Get-TrustedPath ` - (Join-Path $payloadRoot 'raw\signing\prebuilt') 'Prepared signing root' 'Container' - $unsignedReceipt = Get-TrustedPath ` - (Join-Path $payloadRoot 'raw\unsigned\build-receipt.json') 'Prepared unsigned build receipt' - $signingReceipt = Get-TrustedPath ` - (Join-Path $payloadRoot 'raw\signing\build-receipt.json') 'Prepared signing build receipt' - foreach ($buildReceiptPath in @($unsignedReceipt, $signingReceipt)) { - if ((Get-FileHash -LiteralPath $buildReceiptPath -Algorithm SHA256).Hash -cne - $env:EXPECTED_BUILD_RECEIPT_SHA256.ToUpperInvariant()) { - throw 'Prepared raw handoff receipt differs from the immutable build receipt.' - } - } - $buildReceipt = Get-Content -Raw -LiteralPath $unsignedReceipt | ConvertFrom-Json -Depth 32 - foreach ($rawRoot in @($unsignedRoot, $signingRoot)) { - $rawInventory = New-WagglePrebuiltInventory -Root $rawRoot - if (($rawInventory | ConvertTo-Json -Depth 32 -Compress) -cne - ($buildReceipt.targetInventory | ConvertTo-Json -Depth 32 -Compress)) { - throw 'Prepared raw prebuilt root differs from the hosted build receipt.' - } - } - $expectedNsisAggregate = '1FC822D1A183552A80ADEA01B0BF456F462B90518256EF1FE9EDFA22D76CD85A' - foreach ($nsisRoot in @( - (Join-Path $payloadRoot 'raw\unsigned\nsis-toolchain'), - (Join-Path $payloadRoot 'raw\signing\nsis-toolchain') - )) { - $nsisInventory = New-WagglePrebuiltInventory -Root $nsisRoot - if (@($nsisInventory.entries).Count -ne 442 -or - [string]$nsisInventory.sha256 -cne $expectedNsisAggregate -or - ($nsisInventory | ConvertTo-Json -Depth 8 -Compress) -cne - ($buildReceipt.nsisInventory | ConvertTo-Json -Depth 8 -Compress)) { - throw 'Prepared NSIS toolchain differs from the hosted build receipt.' - } - } - - $installedNsisRoot = Join-Path $env:LOCALAPPDATA 'tauri\NSIS' - if (Test-Path -LiteralPath $installedNsisRoot) { - throw 'Fresh OIDC signer unexpectedly already contains a Tauri NSIS closure.' - } - [IO.Directory]::CreateDirectory((Split-Path $installedNsisRoot -Parent)) | Out-Null - Copy-Item -LiteralPath (Join-Path $payloadRoot 'raw\unsigned\nsis-toolchain') ` - -Destination $installedNsisRoot -Recurse -ErrorAction Stop - $installedNsisInventory = New-WagglePrebuiltInventory -Root $installedNsisRoot - if (($installedNsisInventory | ConvertTo-Json -Depth 8 -Compress) -cne - ($buildReceipt.nsisInventory | ConvertTo-Json -Depth 8 -Compress)) { - throw 'Restored signer NSIS closure differs from the hosted build receipt.' - } - - $resourceEntries = @($buildReceipt.resourcesInventory.entries) - Assert-WaggleCanonicalInventoryEntries $resourceEntries 'Prepared resources inventory' - $sourceResourcesRoot = Get-TrustedPath ` - (Join-Path $unsignedRoot 'resources') 'Prepared source resources' 'Container' - $signingResourcesRoot = Get-TrustedPath ` - (Join-Path $signingRoot 'resources') 'Prepared signing resources' 'Container' - $canonicalResourcesRoot = Get-TrustedPath ` - ([IO.Path]::GetFullPath('app/src-tauri/resources')) 'Canonical repository resources' 'Container' - $canonicalPrefix = $canonicalResourcesRoot.TrimEnd('\') + '\' - $materializedEntries = [Collections.Generic.List[object]]::new() - foreach ($entry in $resourceEntries) { - $relative = [string]$entry.path - $sourcePath = Get-TrustedPath ` - (Join-Path $sourceResourcesRoot $relative) 'Prepared resource file' -AllowHardLink - $signingPath = Get-TrustedPath ` - (Join-Path $signingResourcesRoot $relative) 'Prepared signing resource file' -AllowHardLink - foreach ($path in @($sourcePath, $signingPath)) { - $item = Get-Item -LiteralPath $path -Force - if ([long]$item.Length -ne [long]$entry.size -or - (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -cne [string]$entry.sha256) { - throw 'Prepared resource file differs from its hosted receipt.' - } - } - $destination = [IO.Path]::GetFullPath((Join-Path $canonicalResourcesRoot $relative)) - if (-not $destination.StartsWith($canonicalPrefix, [StringComparison]::OrdinalIgnoreCase)) { - throw 'Prepared resource destination escaped the canonical repository root.' - } - [IO.Directory]::CreateDirectory((Split-Path $destination -Parent)) | Out-Null - if (Test-Path -LiteralPath $destination) { - if ((Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash -cne - [string]$entry.sha256) { - throw 'Canonical repository resource differs from the prepared receipt.' - } - } else { - [IO.File]::Copy($sourcePath, $destination, $false) - } - $materialized = Get-Item -LiteralPath $destination -Force - $materializedEntries.Add([pscustomobject][ordered]@{ - path = $relative - size = [long]$materialized.Length - sha256 = (Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash - }) - } - if ((Get-WaggleInventorySha256 @($materializedEntries)) -cne - [string]$buildReceipt.resourcesInventory.sha256) { - throw 'Restored canonical resources differ from the prepared build receipt.' - } - - $tauriSource = Join-Path $payloadRoot 'tauri\node_modules\@tauri-apps' - $tauriDestination = [IO.Path]::GetFullPath('app\node_modules\@tauri-apps') - if (Test-Path -LiteralPath (Split-Path $tauriDestination -Parent)) { - throw 'Fresh OIDC signer unexpectedly already contains app node_modules.' - } - [IO.Directory]::CreateDirectory($tauriDestination) | Out-Null - foreach ($packageName in @('cli', 'cli-win32-x64-msvc')) { - Copy-Item -LiteralPath (Join-Path $tauriSource $packageName) ` - -Destination $tauriDestination -Recurse -ErrorAction Stop - } - $restoredPackages = @( - Get-ChildItem -LiteralPath $tauriDestination -Force -Directory | - ForEach-Object { $_.Name } | Sort-Object - ) - if ([string]::Join("`n", $restoredPackages) -cne - [string]::Join("`n", @('cli', 'cli-win32-x64-msvc'))) { - throw 'OIDC signer restored more than the two approved Tauri CLI packages.' - } - - $portableRelativeReceiptPath = Join-Path $payloadRoot ` - 'portable\portable-toolchain-receipt.json' - $portableRelativeReceipt = Get-Content -Raw -LiteralPath $portableRelativeReceiptPath | - ConvertFrom-Json -Depth 32 - if ([int]$portableRelativeReceipt.schemaVersion -ne 1 -or - [string]$portableRelativeReceipt.portableToolchainRoot -cne 'portable\toolchain' -or - [string]$portableRelativeReceipt.archives.node.path -cne 'portable\downloads\node.zip' -or - [string]$portableRelativeReceipt.archives.git.path -cne 'portable\downloads\mingit.zip' -or - [string]$portableRelativeReceipt.archives.sevenZip.path -cne 'portable\downloads\sevenzip.exe' -or - @($portableRelativeReceipt.inventory.entries).Count -ne 2495 -or - [string]$portableRelativeReceipt.inventory.sha256 -cne - 'D64F897D4E1A7F07FE9BA62D6AF062EF9F0E41C595CDAF2F3C4F73991BBEA0F5') { - throw 'Prepared portable toolchain receipt is not path-relative and repository-pinned.' - } - $portablePayloadRoot = Get-TrustedPath ` - (Join-Path $payloadRoot 'portable\toolchain') 'Prepared portable toolchain' 'Container' - $portableDownloads = Get-TrustedPath ` - (Join-Path $payloadRoot 'portable\downloads') 'Restored portable downloads' 'Container' - $portableActualInventory = New-WagglePrebuiltInventory -Root $portablePayloadRoot - if (($portableActualInventory | ConvertTo-Json -Depth 32 -Compress) -cne - ($portableRelativeReceipt.inventory | ConvertTo-Json -Depth 32 -Compress)) { - throw 'Restored portable toolchain differs from its path-relative receipt.' - } - $relocatedReceiptRoot = Join-Path $env:RUNNER_TEMP 'waggle-portable-signing-restored' - if (Test-Path -LiteralPath $relocatedReceiptRoot) { - throw 'Relocated portable receipt root already exists.' - } - $relocatedReceiptRoot = New-PrivateDirectory $relocatedReceiptRoot - $portableRoot = New-PrivateDirectory (Join-Path $relocatedReceiptRoot 'toolchain') - foreach ($entry in @($portableRelativeReceipt.inventory.entries)) { - $relative = [string]$entry.path - $source = Get-TrustedPath ` - (Join-Path $portablePayloadRoot $relative) 'Prepared portable toolchain file' - $destination = Join-Path $portableRoot $relative - [IO.Directory]::CreateDirectory((Split-Path $destination -Parent)) | Out-Null - [IO.File]::Copy($source, $destination, $false) - } - $restoredPortableInventory = New-WagglePrebuiltInventory -Root $portableRoot - if (($restoredPortableInventory | ConvertTo-Json -Depth 32 -Compress) -cne - ($portableRelativeReceipt.inventory | ConvertTo-Json -Depth 32 -Compress)) { - throw 'Private restored portable toolchain differs from its path-relative receipt.' - } - $relocatedReceiptPath = Join-Path $relocatedReceiptRoot 'portable-toolchain-receipt.json' - $relocatedReceipt = [ordered]@{ - schemaVersion = 1 - portableToolchainRoot = [IO.Path]::GetFullPath($portableRoot) - archives = [ordered]@{ - node = [ordered]@{ - path = [IO.Path]::GetFullPath((Join-Path $portableDownloads 'node.zip')) - sha256 = '7C93E9D92BF68C07182B471AA187E35EE6CD08EF0F24AB060DFFF605FCC1C57C' - } - git = [ordered]@{ - path = [IO.Path]::GetFullPath((Join-Path $portableDownloads 'mingit.zip')) - sha256 = 'C2C955A21FA99889D83F485F24FA5D9A38FFFC2D509D4022385510E11C26B250' - } - sevenZip = [ordered]@{ - path = [IO.Path]::GetFullPath((Join-Path $portableDownloads 'sevenzip.exe')) - sha256 = '78AFA2A1C773CAF3CF7EDF62F857D2A8A5DA55FB0FFF5DA416074C0D28B2B55F' - } - } - inventory = $portableRelativeReceipt.inventory - } - Write-WaggleJsonNoBom $relocatedReceiptPath $relocatedReceipt - $relocatedReceiptSha256 = (Get-FileHash -LiteralPath $relocatedReceiptPath -Algorithm SHA256).Hash - - $artifactSigningPackage = Get-TrustedPath ` - (Join-Path $payloadRoot 'artifact-signing\Microsoft.ArtifactSigning.Client.1.0.128.nupkg') ` - 'Prepared Artifact Signing package' - if ((Get-FileHash -LiteralPath $artifactSigningPackage -Algorithm SHA256).Hash -cne - '74BD7D27E6CE1051409C38D9B46BC8DF0400ECD643D51FFBF2AC00869061E40B') { - throw 'Prepared Artifact Signing package differs from its pinned SHA-256.' - } - "unsigned_root=$unsignedRoot" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "signing_root=$signingRoot" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "build_receipt_path=$signingReceipt" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "artifact_signing_package=$artifactSigningPackage" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "portable_root=$portableRoot" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "portable_node=$([IO.Path]::GetFullPath((Join-Path $portableRoot 'node\node-v22.22.2-win-x64\node.exe')))" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "portable_git=$([IO.Path]::GetFullPath((Join-Path $portableRoot 'git\cmd\git.exe')))" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "portable_sevenzip=$([IO.Path]::GetFullPath((Join-Path $portableRoot 'sevenzip\7z.exe')))" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "portable_receipt_path=$relocatedReceiptPath" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "portable_receipt_sha256=$relocatedReceiptSha256" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - - - name: Refresh exact signing repository refs - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - with: - repository: marolinik/waggle-os - ref: ${{ github.ref }} - fetch-depth: 0 - persist-credentials: false - clean: false - - - name: Revalidate exact signing revision against fresh origin main - shell: pwsh - run: | - $checkedOutRevision = (git rev-parse --verify HEAD).Trim().ToLowerInvariant() - if ($LASTEXITCODE -ne 0) { - throw 'Could not resolve the exact signing checkout after refreshing repository refs.' - } - $remoteMainRevision = (git rev-parse --verify refs/remotes/origin/main).Trim().ToLowerInvariant() - if ($LASTEXITCODE -ne 0 -or - $checkedOutRevision -cne $env:GITHUB_SHA -or - $env:GITHUB_WORKFLOW_SHA -cne $env:GITHUB_SHA -or - $remoteMainRevision -cnotmatch '^[0-9a-f]{40}$' -or - @(git status --porcelain=v1 --untracked-files=all).Count -ne 0) { - throw 'Fresh signing checkout, workflow, or origin/main revision evidence is invalid.' - } - git merge-base --is-ancestor $env:GITHUB_SHA refs/remotes/origin/main - if ($LASTEXITCODE -ne 0) { - throw 'The exact signing revision is not contained by fresh origin/main.' - } - - - name: Authenticate Azure Artifact Signing with OIDC - uses: azure/login@f5d393ae46f8fde4be8b75f32e3fc50e654ad0ca # v3.0.1 - with: - client-id: ${{ vars.AZURE_CLIENT_ID }} - tenant-id: ${{ vars.AZURE_TENANT_ID }} - subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }} - audience: api://AzureADTokenExchange - - - name: Package and sign from immutable prepared inputs - id: sign-windows - shell: pwsh - env: - WINDOWS_CODESIGN_APPROVED_SUBJECT: ${{ needs.prepare-windows-signing.outputs.signer_subject }} - EXPECTED_BUILD_RECEIPT_SHA256: ${{ needs.build-windows-prebuilt.outputs.build_receipt_sha256 }} - run: | - & 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' ` - -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass ` - -File ./app/scripts/sign-windows-artifact.ps1 ` - -Mode Package ` - -UnsignedInputRoot '${{ steps.verify-prepared.outputs.unsigned_root }}' ` - -SigningInputRoot '${{ steps.verify-prepared.outputs.signing_root }}' ` - -BuildReceiptPath '${{ steps.verify-prepared.outputs.build_receipt_path }}' ` - -BuildReceiptSha256 $env:EXPECTED_BUILD_RECEIPT_SHA256 ` - -ArtifactSigningPackageSource '${{ steps.verify-prepared.outputs.artifact_signing_package }}' ` - -PortableToolchainRoot '${{ steps.verify-prepared.outputs.portable_root }}' ` - -PortableToolchainReceiptPath '${{ steps.verify-prepared.outputs.portable_receipt_path }}' ` - -PortableToolchainReceiptSha256 '${{ steps.verify-prepared.outputs.portable_receipt_sha256 }}' ` - -PortableNodePath '${{ steps.verify-prepared.outputs.portable_node }}' ` - -PortableGitPath '${{ steps.verify-prepared.outputs.portable_git }}' ` - -PortableSevenZipPath '${{ steps.verify-prepared.outputs.portable_sevenzip }}' - if ($LASTEXITCODE -ne 0) { throw 'Protected Artifact Signing package failed.' } - $receipts = @(Get-ChildItem -LiteralPath 'app/src-tauri/target/.signing-sessions' -Recurse -Filter 'provenance-receipt.json' -File) - if ($receipts.Count -ne 1) { throw "Expected exactly one sealed signing receipt, found $($receipts.Count)." } - $receipt = Get-Content -Raw -LiteralPath $receipts[0].FullName | ConvertFrom-Json - if ([string]$receipt.status -cne 'sealed' -or - [string]$receipt.sourceRevision -cne $env:GITHUB_SHA -or - [string]$receipt.signerSubject -cne $env:WINDOWS_CODESIGN_APPROVED_SUBJECT -or - [string]$receipt.installerSha256 -notmatch '^[0-9A-F]{64}$') { - throw 'Sealed signing receipt does not bind the approved revision and signer.' - } - $installerPath = [IO.Path]::GetFullPath([string]$receipt.installerPath) - $targetRoot = [IO.Path]::GetFullPath((Resolve-Path 'app/src-tauri/target').Path) - $targetPrefix = $targetRoot.TrimEnd([char[]]@('\', '/')) + [IO.Path]::DirectorySeparatorChar - if (-not $installerPath.StartsWith($targetPrefix, [StringComparison]::OrdinalIgnoreCase) -or - -not (Test-Path -LiteralPath $installerPath -PathType Leaf) -or - -not [string]::Equals( - (Get-FileHash -LiteralPath $installerPath -Algorithm SHA256).Hash, - [string]$receipt.installerSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Sealed installer is missing, escaped the target root, or changed after signing.' - } - if ($env:GITHUB_OUTPUT) { - "candidate_sha256=$([string]$receipt.installerSha256)" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - } - - - name: Stage exact signed handoff - id: stage-signed - shell: pwsh - env: - WAGGLE_RELEASE_MODE: ${{ needs.prepare-windows-signing.outputs.release_mode }} - WINDOWS_BOOTSTRAP_RELEASE_IDENTITY: ${{ needs.prepare-windows-signing.outputs.bootstrap_identity }} - WINDOWS_UPGRADE_BASE_TAG: ${{ needs.prepare-windows-signing.outputs.upgrade_base_tag }} - WINDOWS_UPGRADE_BASE_ASSET_NAME: ${{ needs.prepare-windows-signing.outputs.upgrade_base_asset_name }} - WINDOWS_UPGRADE_BASE_SHA256: ${{ needs.prepare-windows-signing.outputs.upgrade_base_sha256 }} - WINDOWS_UPGRADE_BASE_COMMIT: ${{ needs.prepare-windows-signing.outputs.upgrade_base_commit }} - WINDOWS_CODESIGN_APPROVED_SUBJECT: ${{ needs.prepare-windows-signing.outputs.signer_subject }} - EXPECTED_BUILD_RECEIPT_SHA256: ${{ needs.build-windows-prebuilt.outputs.build_receipt_sha256 }} - EXPECTED_BUILD_ARTIFACT_ID: ${{ needs.build-windows-prebuilt.outputs.artifact_id }} - EXPECTED_BUILD_ARTIFACT_DIGEST: ${{ needs.build-windows-prebuilt.outputs.artifact_digest }} - EXPECTED_PREPARATION_RECEIPT_SHA256: ${{ needs.prepare-windows-signing.outputs.preparation_receipt_sha256 }} - EXPECTED_PREPARATION_ARTIFACT_ID: ${{ needs.prepare-windows-signing.outputs.artifact_id }} - EXPECTED_PREPARATION_ARTIFACT_DIGEST: ${{ needs.prepare-windows-signing.outputs.artifact_digest }} - run: | - $signedRoot = Join-Path $env:RUNNER_TEMP 'waggle-windows-signed' - if (Test-Path -LiteralPath $signedRoot) { throw 'Signed handoff root already exists.' } - $releaseRoot = New-Item -ItemType Directory -Path (Join-Path $signedRoot 'release') - $sourceNsisRoot = New-Item -ItemType Directory -Path (Join-Path $signedRoot 'source\release-nsis') - $sourceResourcesRoot = New-Item -ItemType Directory -Path (Join-Path $signedRoot 'source\resources') - $provenanceRoot = New-Item -ItemType Directory -Path (Join-Path $signedRoot 'provenance') - $receipts = @( - Get-ChildItem -LiteralPath 'app/src-tauri/target/.signing-sessions' ` - -Recurse -Filter 'provenance-receipt.json' -File - ) - if ($receipts.Count -ne 1) { throw 'Signed handoff requires exactly one sealed provenance receipt.' } - $provenance = Get-Content -Raw -LiteralPath $receipts[0].FullName | ConvertFrom-Json -Depth 32 - $installer = Get-Item -LiteralPath ([string]$provenance.installerPath) - $candidateVersion = [string]( - Get-Content -Raw -LiteralPath 'app/src-tauri/tauri.conf.json' | ConvertFrom-Json - ).version - if ([string]$provenance.status -cne 'sealed' -or - [string]$provenance.sourceRevision -cne $env:GITHUB_SHA -or - [string]$provenance.signerSubject -cne $env:WINDOWS_CODESIGN_APPROVED_SUBJECT -or - $candidateVersion -notmatch '^\d+\.\d+\.\d+$' -or - $env:GITHUB_REF_NAME -cne "v$candidateVersion" -or - (Get-FileHash -LiteralPath $installer.FullName -Algorithm SHA256).Hash -cne - [string]$provenance.installerSha256) { - throw 'Signed handoff source no longer matches the protected signing receipt.' - } - $signedReleaseRoot = Split-Path -Parent (Split-Path -Parent $installer.DirectoryName) - $generatedInstallerScripts = @( - Get-ChildItem -LiteralPath (Join-Path $signedReleaseRoot 'nsis') ` - -Recurse -Filter 'installer.nsi' -File - ) - $sourceService = Get-Item -LiteralPath 'app/src-tauri/resources/service.js' - if ($generatedInstallerScripts.Count -ne 1) { - throw 'Signed handoff does not contain exactly one generated installer.nsi.' - } - Copy-Item -LiteralPath $installer.FullName -Destination $releaseRoot.FullName -ErrorAction Stop - Copy-Item -LiteralPath $generatedInstallerScripts[0].FullName ` - -Destination (Join-Path $sourceNsisRoot.FullName 'installer.nsi') -ErrorAction Stop - Copy-Item -LiteralPath $sourceService.FullName ` - -Destination (Join-Path $sourceResourcesRoot.FullName 'service.js') -ErrorAction Stop - Copy-Item -LiteralPath $receipts[0].FullName ` - -Destination (Join-Path $provenanceRoot.FullName 'provenance-receipt.json') -ErrorAction Stop - - . ./app/scripts/sign-windows-artifact.ps1 - $inventory = New-WagglePrebuiltInventory -Root $signedRoot - $expectedPaths = @( - 'provenance\provenance-receipt.json' - "release\$($installer.Name)" - 'source\release-nsis\installer.nsi' - 'source\resources\service.js' - ) - if (@($inventory.entries).Count -ne $expectedPaths.Count -or - [string]::Join("`n", @($inventory.entries | ForEach-Object { [string]$_.path })) -cne - [string]::Join("`n", $expectedPaths)) { - throw 'Signed handoff topology differs from the exact four-file contract.' - } - foreach ($value in @( - $env:EXPECTED_BUILD_RECEIPT_SHA256, - $env:EXPECTED_BUILD_ARTIFACT_DIGEST, - [string]$provenance.installerSha256 - )) { - if ($value -cnotmatch '^[0-9A-Fa-f]{64}$') { throw 'Signed handoff digest binding is invalid.' } - } - if ($env:EXPECTED_BUILD_ARTIFACT_ID -cnotmatch '^[1-9][0-9]*$') { - throw 'Signed handoff build artifact ID is invalid.' - } - if ($env:EXPECTED_PREPARATION_RECEIPT_SHA256 -cnotmatch '^[0-9A-Fa-f]{64}$' -or - $env:EXPECTED_PREPARATION_ARTIFACT_DIGEST -cnotmatch '^[0-9A-Fa-f]{64}$' -or - $env:EXPECTED_PREPARATION_ARTIFACT_ID -cnotmatch '^[1-9][0-9]*$') { - throw 'Signed handoff preparation artifact binding is invalid.' - } - $handoffReceipt = [ordered]@{ - schemaVersion = 1 - sourceRevision = $env:GITHUB_SHA - candidateTag = $env:GITHUB_REF_NAME - candidateVersion = $candidateVersion - releaseMode = $env:WAGGLE_RELEASE_MODE - bootstrapIdentity = $env:WINDOWS_BOOTSTRAP_RELEASE_IDENTITY - upgradeBaseTag = $env:WINDOWS_UPGRADE_BASE_TAG - upgradeBaseAssetName = $env:WINDOWS_UPGRADE_BASE_ASSET_NAME - upgradeBaseSha256 = $env:WINDOWS_UPGRADE_BASE_SHA256 - upgradeBaseCommit = $env:WINDOWS_UPGRADE_BASE_COMMIT - signerSubject = $env:WINDOWS_CODESIGN_APPROVED_SUBJECT - candidateSha256 = ([string]$provenance.installerSha256).ToUpperInvariant() - buildReceiptSha256 = $env:EXPECTED_BUILD_RECEIPT_SHA256.ToUpperInvariant() - buildArtifactId = $env:EXPECTED_BUILD_ARTIFACT_ID - buildArtifactDigest = $env:EXPECTED_BUILD_ARTIFACT_DIGEST.ToUpperInvariant() - preparationReceiptSha256 = $env:EXPECTED_PREPARATION_RECEIPT_SHA256.ToUpperInvariant() - preparationArtifactId = $env:EXPECTED_PREPARATION_ARTIFACT_ID - preparationArtifactDigest = $env:EXPECTED_PREPARATION_ARTIFACT_DIGEST.ToUpperInvariant() - timestampPolicy = 'fresh-certification-monotonic-v1' - inventory = $inventory - } - $receiptPath = Join-Path $signedRoot 'signing-handoff-receipt.json' - Write-WaggleJsonNoBom $receiptPath $handoffReceipt - $receiptSha256 = (Get-FileHash -LiteralPath $receiptPath -Algorithm SHA256).Hash - "receipt_sha256=$receiptSha256" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "candidate_sha256=$([string]$handoffReceipt.candidateSha256)" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "candidate_version=$candidateVersion" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - - - name: Upload immutable signed Windows handoff - id: upload-signed - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - with: - name: waggle-windows-signed-${{ github.sha }} - path: ${{ runner.temp }}\waggle-windows-signed - if-no-files-found: error - include-hidden-files: true - retention-days: 7 - - certify-windows: - needs: sign-windows - runs-on: windows-latest - permissions: - contents: read - outputs: - release_mode: ${{ steps.verify-signed.outputs.release_mode }} - candidate_sha256: ${{ steps.certify-windows.outputs.candidate_sha256 }} - candidate_version: ${{ steps.certify-windows.outputs.candidate_version }} - bootstrap_identity: ${{ steps.verify-signed.outputs.bootstrap_identity }} - upgrade_base_tag: ${{ steps.verify-signed.outputs.upgrade_base_tag }} - upgrade_base_asset_name: ${{ steps.verify-signed.outputs.upgrade_base_asset_name }} - upgrade_base_sha256: ${{ steps.verify-signed.outputs.upgrade_base_sha256 }} - upgrade_base_commit: ${{ steps.verify-signed.outputs.upgrade_base_commit }} - signer_subject: ${{ steps.verify-signed.outputs.signer_subject }} - sealed_receipt_sha256: ${{ steps.stage-sealed.outputs.receipt_sha256 }} - artifact_id: ${{ steps.upload-sealed.outputs.artifact-id }} - artifact_digest: ${{ steps.upload-sealed.outputs.artifact-digest }} - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - with: - fetch-depth: 0 - persist-credentials: false - - - name: Validate credential-free certification boundary - shell: pwsh - run: | - $version = [string](Get-Content -Raw -LiteralPath 'app/src-tauri/tauri.conf.json' | ConvertFrom-Json).version - $checkedOutRevision = (git rev-parse --verify HEAD).Trim().ToLowerInvariant() - if ($env:GITHUB_REPOSITORY -cne 'marolinik/waggle-os' -or - $env:GITHUB_REF_TYPE -cne 'tag' -or - $env:RUNNER_ENVIRONMENT -cne 'github-hosted' -or - $env:GITHUB_REF_NAME -cne "v$version" -or - $checkedOutRevision -cne $env:GITHUB_SHA -or - @(git status --porcelain=v1 --untracked-files=all).Count -ne 0) { - throw 'Windows certification requires a clean fresh runner at the exact release revision.' - } - - - name: Setup Node.js for source-bound certification - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 - with: - node-version: '22.23.2' - cache: npm - - - name: Install locked certification dependencies - run: npm ci - - - name: Download immutable signed Windows handoff - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 - with: - artifact-ids: ${{ needs.sign-windows.outputs.artifact_id }} - path: ${{ runner.temp }}\waggle-windows-signed - merge-multiple: true - - - name: Validate exact signed handoff before candidate execution - id: verify-signed - shell: pwsh - env: - EXPECTED_HANDOFF_RECEIPT_SHA256: ${{ needs.sign-windows.outputs.handoff_receipt_sha256 }} - EXPECTED_SIGNED_ARTIFACT_ID: ${{ needs.sign-windows.outputs.artifact_id }} - EXPECTED_SIGNED_ARTIFACT_DIGEST: ${{ needs.sign-windows.outputs.artifact_digest }} - EXPECTED_BUILD_RECEIPT_SHA256: ${{ needs.sign-windows.outputs.build_receipt_sha256 }} - EXPECTED_BUILD_ARTIFACT_ID: ${{ needs.sign-windows.outputs.build_artifact_id }} - EXPECTED_BUILD_ARTIFACT_DIGEST: ${{ needs.sign-windows.outputs.build_artifact_digest }} - EXPECTED_RELEASE_MODE: ${{ needs.sign-windows.outputs.release_mode }} - EXPECTED_CANDIDATE_SHA256: ${{ needs.sign-windows.outputs.candidate_sha256 }} - EXPECTED_CANDIDATE_VERSION: ${{ needs.sign-windows.outputs.candidate_version }} - EXPECTED_BOOTSTRAP_IDENTITY: ${{ needs.sign-windows.outputs.bootstrap_identity }} - EXPECTED_UPGRADE_BASE_TAG: ${{ needs.sign-windows.outputs.upgrade_base_tag }} - EXPECTED_UPGRADE_BASE_ASSET_NAME: ${{ needs.sign-windows.outputs.upgrade_base_asset_name }} - EXPECTED_UPGRADE_BASE_SHA256: ${{ needs.sign-windows.outputs.upgrade_base_sha256 }} - EXPECTED_UPGRADE_BASE_COMMIT: ${{ needs.sign-windows.outputs.upgrade_base_commit }} - EXPECTED_SIGNER_SUBJECT: ${{ needs.sign-windows.outputs.signer_subject }} - run: | - $signedRoot = [IO.Path]::GetFullPath( - (Resolve-Path (Join-Path $env:RUNNER_TEMP 'waggle-windows-signed')).Path - ) - $receiptPath = Join-Path $signedRoot 'signing-handoff-receipt.json' - foreach ($digest in @( - $env:EXPECTED_HANDOFF_RECEIPT_SHA256, - $env:EXPECTED_SIGNED_ARTIFACT_DIGEST, - $env:EXPECTED_BUILD_RECEIPT_SHA256, - $env:EXPECTED_CANDIDATE_SHA256 - )) { - if ($digest -cnotmatch '^[0-9A-Fa-f]{64}$') { throw 'Signed handoff expected digest is invalid.' } - } - if ($env:EXPECTED_SIGNED_ARTIFACT_ID -cnotmatch '^[1-9][0-9]*$' -or - -not (Test-Path -LiteralPath $receiptPath -PathType Leaf) -or - (Get-FileHash -LiteralPath $receiptPath -Algorithm SHA256).Hash -cne - $env:EXPECTED_HANDOFF_RECEIPT_SHA256.ToUpperInvariant()) { - throw 'Signed handoff immutable artifact or receipt binding is invalid.' - } - $receipt = Get-Content -Raw -LiteralPath $receiptPath | ConvertFrom-Json -Depth 32 - $expectedBindings = [ordered]@{ - sourceRevision = $env:GITHUB_SHA - candidateTag = $env:GITHUB_REF_NAME - candidateVersion = $env:EXPECTED_CANDIDATE_VERSION - releaseMode = $env:EXPECTED_RELEASE_MODE - bootstrapIdentity = $env:EXPECTED_BOOTSTRAP_IDENTITY - upgradeBaseTag = $env:EXPECTED_UPGRADE_BASE_TAG - upgradeBaseAssetName = $env:EXPECTED_UPGRADE_BASE_ASSET_NAME - upgradeBaseSha256 = $env:EXPECTED_UPGRADE_BASE_SHA256 - upgradeBaseCommit = $env:EXPECTED_UPGRADE_BASE_COMMIT - signerSubject = $env:EXPECTED_SIGNER_SUBJECT - candidateSha256 = $env:EXPECTED_CANDIDATE_SHA256 - buildReceiptSha256 = $env:EXPECTED_BUILD_RECEIPT_SHA256 - buildArtifactId = $env:EXPECTED_BUILD_ARTIFACT_ID - buildArtifactDigest = $env:EXPECTED_BUILD_ARTIFACT_DIGEST.ToUpperInvariant() - timestampPolicy = 'fresh-certification-monotonic-v1' - } - if ($receipt.schemaVersion -is [string] -or [int]$receipt.schemaVersion -ne 1 -or - $env:EXPECTED_BUILD_ARTIFACT_ID -cnotmatch '^[1-9][0-9]*$' -or - $env:EXPECTED_BUILD_ARTIFACT_DIGEST -cnotmatch '^[0-9A-Fa-f]{64}$') { - throw 'Signed handoff receipt schema or upstream artifact binding is invalid.' - } - foreach ($property in $expectedBindings.Keys) { - if (-not [string]::Equals( - [string]$receipt.$property, - [string]$expectedBindings[$property], - [StringComparison]::Ordinal - )) { - throw "Signed handoff protected binding differs: $property" - } - } - . ./app/scripts/sign-windows-artifact.ps1 - $entries = @($receipt.inventory.entries) - Assert-WaggleCanonicalInventoryEntries $entries 'Signed handoff inventory' - if ($entries.Count -ne 4 -or - (Get-WaggleInventorySha256 $entries) -cne [string]$receipt.inventory.sha256) { - throw 'Signed handoff inventory aggregate is invalid.' - } - $actualPaths = @( - Get-ChildItem -LiteralPath $signedRoot -Recurse -Force -File | - ForEach-Object { [IO.Path]::GetRelativePath($signedRoot, $_.FullName).Replace('/', '\') } | - Sort-Object -CaseSensitive - ) - $expectedPaths = @($entries | ForEach-Object { [string]$_.path }) + - @('signing-handoff-receipt.json') - $expectedPaths = @($expectedPaths | Sort-Object -CaseSensitive) - if ([string]::Join("`n", $actualPaths) -cne [string]::Join("`n", $expectedPaths)) { - throw 'Signed handoff extracted topology is not exact.' - } - foreach ($entry in $entries) { - $path = Get-TrustedPath (Join-Path $signedRoot ([string]$entry.path)) 'Signed handoff file' - $item = Get-Item -LiteralPath $path - if ([long]$item.Length -ne [long]$entry.size -or - (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -cne - ([string]$entry.sha256).ToUpperInvariant()) { - throw 'Signed handoff file differs from its exact receipt.' - } - } - $installerEntries = @($entries | Where-Object { [string]$_.path -match '^release\\[^\\]+-setup\.exe$' }) - if ($installerEntries.Count -ne 1) { throw 'Signed handoff has an ambiguous installer identity.' } - $installerSource = Get-TrustedPath ` - (Join-Path $signedRoot ([string]$installerEntries[0].path)) 'Signed candidate installer' - $signature = Get-AuthenticodeSignature -LiteralPath $installerSource - if ($signature.Status -ne 'Valid' -or - [string]$signature.SignerCertificate.Subject -cne $env:EXPECTED_SIGNER_SUBJECT -or - $null -eq $signature.TimeStamperCertificate) { - throw 'Signed candidate lacks the approved signer and timestamp before execution.' - } - $targetReleaseRoot = [IO.Path]::GetFullPath( - 'app/src-tauri/target/x86_64-pc-windows-msvc/release' - ) - if (Test-Path -LiteralPath $targetReleaseRoot) { throw 'Certification target unexpectedly exists.' } - $bundleRoot = New-Item -ItemType Directory -Path (Join-Path $targetReleaseRoot 'bundle\nsis') - $nsisRoot = New-Item -ItemType Directory -Path (Join-Path $targetReleaseRoot 'nsis') - $installerTarget = Join-Path $bundleRoot.FullName (Split-Path $installerSource -Leaf) - [IO.File]::Copy($installerSource, $installerTarget, $false) - [IO.File]::Copy( - (Join-Path $signedRoot 'source\release-nsis\installer.nsi'), - (Join-Path $nsisRoot.FullName 'installer.nsi'), - $false - ) - $canonicalServicePath = [IO.Path]::GetFullPath('app/src-tauri/resources/service.js') - if (Test-Path -LiteralPath $canonicalServicePath) { - throw 'Fresh certification checkout unexpectedly contains generated service.js.' - } - [IO.File]::Copy( - (Join-Path $signedRoot 'source\resources\service.js'), - $canonicalServicePath, - $false - ) - $hookTime = (Get-Item -LiteralPath 'app/src-tauri/nsis/installer.nsi').LastWriteTimeUtc - (Get-Item -LiteralPath (Join-Path $nsisRoot.FullName 'installer.nsi')).LastWriteTimeUtc = - $hookTime.AddSeconds(1) - (Get-Item -LiteralPath $installerTarget).LastWriteTimeUtc = $hookTime.AddSeconds(2) - "release_mode=$([string]$receipt.releaseMode)" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "bootstrap_identity=$([string]$receipt.bootstrapIdentity)" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "upgrade_base_tag=$([string]$receipt.upgradeBaseTag)" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "upgrade_base_asset_name=$([string]$receipt.upgradeBaseAssetName)" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "upgrade_base_sha256=$([string]$receipt.upgradeBaseSha256)" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "upgrade_base_commit=$([string]$receipt.upgradeBaseCommit)" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "signer_subject=$([string]$receipt.signerSubject)" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - - - name: Reclaim Windows build intermediates for managed-model certification - shell: pwsh - run: | - $installers = @( - Get-ChildItem -LiteralPath 'app/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis' ` - -Filter '*-setup.exe' -File - ) - if ($installers.Count -ne 1) { throw 'Certification target installer identity is ambiguous.' } - $installer = $installers[0] - $targetRoot = [IO.Path]::GetFullPath((Resolve-Path 'app/src-tauri/target').Path) - $targetPrefix = $targetRoot.TrimEnd([char[]]@('\', '/')) + [IO.Path]::DirectorySeparatorChar - $targetProfileRoot = [IO.Path]::GetFullPath((Split-Path -Parent (Split-Path -Parent $installer.DirectoryName))) - if (-not $targetProfileRoot.StartsWith($targetPrefix, [StringComparison]::OrdinalIgnoreCase)) { - throw "Refusing to prune outside the Tauri target: $targetProfileRoot" - } - foreach ($directoryName in @('deps', 'incremental', 'build', '.fingerprint')) { - $directory = Join-Path $targetProfileRoot $directoryName - if (Test-Path -LiteralPath $directory -PathType Container) { - Remove-Item -LiteralPath $directory -Recurse -Force -ErrorAction Stop - } - } - $driveRoot = [IO.Path]::GetPathRoot($targetRoot) - if ($driveRoot -notmatch '^[A-Za-z]:\\$') { throw "Unexpected Tauri target drive: $driveRoot" } - $drive = Get-PSDrive -Name $driveRoot.Substring(0, 1) -PSProvider FileSystem - if ([int64]$drive.Free -lt 8GB) { - throw "Managed-model certification requires at least 8 GiB free after pruning; available=$($drive.Free)" - } - - - name: Download signed Windows upgrade baseline - if: steps.verify-signed.outputs.release_mode == 'upgrade' - shell: pwsh - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - WINDOWS_UPGRADE_BASE_TAG: ${{ steps.verify-signed.outputs.upgrade_base_tag }} - WINDOWS_UPGRADE_BASE_ASSET_NAME: ${{ steps.verify-signed.outputs.upgrade_base_asset_name }} - WINDOWS_UPGRADE_BASE_SHA256: ${{ steps.verify-signed.outputs.upgrade_base_sha256 }} - WINDOWS_UPGRADE_BASE_COMMIT: ${{ steps.verify-signed.outputs.upgrade_base_commit }} - run: | - $baseTag = [string]$env:WINDOWS_UPGRADE_BASE_TAG - $assetName = [string]$env:WINDOWS_UPGRADE_BASE_ASSET_NAME - $expectedSha256 = ([string]$env:WINDOWS_UPGRADE_BASE_SHA256).Trim().ToUpperInvariant() - $expectedBaseCommit = ([string]$env:WINDOWS_UPGRADE_BASE_COMMIT).Trim().ToLowerInvariant() - if ($baseTag -notmatch '^v(?\d+\.\d+\.\d+)$') { - throw 'WINDOWS_UPGRADE_BASE_TAG must use exact vX.Y.Z format' - } - $baseVersion = $Matches['version'] - if ($assetName -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]*-setup\.exe$') { - throw 'WINDOWS_UPGRADE_BASE_ASSET_NAME must be one exact NSIS setup filename' - } - if ($expectedSha256 -notmatch '^[0-9A-F]{64}$') { - throw 'WINDOWS_UPGRADE_BASE_SHA256 must be exactly 64 hexadecimal characters' - } - if ($expectedBaseCommit -notmatch '^[0-9a-f]{40}$') { - throw 'WINDOWS_UPGRADE_BASE_COMMIT must be exactly 40 hexadecimal characters' - } - $candidateVersion = [string](Get-Content -Raw -LiteralPath 'app/src-tauri/tauri.conf.json' | ConvertFrom-Json).version - if ($candidateVersion -notmatch '^\d+\.\d+\.\d+$' -or $env:GITHUB_REF_NAME -ne "v$candidateVersion") { - throw 'Candidate installer version no longer matches the release tag' - } - if ([version]$baseVersion -ge [version]$candidateVersion) { - throw 'The protected Windows upgrade baseline must be older than the candidate' - } - - $baseCommit = (git rev-parse --verify "refs/tags/$baseTag^{}").Trim().ToLowerInvariant() - if ($LASTEXITCODE -ne 0 -or $baseCommit -notmatch '^[0-9a-f]{40}$') { - throw "Fresh checkout could not resolve protected upgrade baseline tag $baseTag" - } - if (-not [string]::Equals($baseCommit, $expectedBaseCommit, [System.StringComparison]::Ordinal)) { - throw 'Protected Windows upgrade baseline tag does not resolve to WINDOWS_UPGRADE_BASE_COMMIT' - } - git merge-base --is-ancestor $baseCommit $env:GITHUB_SHA - if ($LASTEXITCODE -ne 0) { - throw 'The protected Windows upgrade baseline is not an ancestor of the candidate release' - } - $releaseJson = gh release view $baseTag --json isDraft,isPrerelease,tagName,assets - if ($LASTEXITCODE -ne 0) { throw "Could not inspect protected upgrade baseline $baseTag" } - $releaseData = $releaseJson | ConvertFrom-Json - if ($releaseData.tagName -ne $baseTag -or $releaseData.isDraft -or $releaseData.isPrerelease) { - throw 'Windows upgrade baseline must be an exact published, non-prerelease release' - } - $matchingAssets = @($releaseData.assets | Where-Object { $_.name -eq $assetName }) - if ($matchingAssets.Count -ne 1) { - throw "Expected exactly one protected upgrade baseline asset named $assetName" - } - - $downloadRoot = Join-Path $env:RUNNER_TEMP 'waggle-windows-upgrade-baseline' - if (Test-Path -LiteralPath $downloadRoot) { - throw "Upgrade baseline directory already exists: $downloadRoot" - } - New-Item -ItemType Directory -Path $downloadRoot | Out-Null - gh release download $baseTag --pattern $assetName --dir $downloadRoot - if ($LASTEXITCODE -ne 0) { throw 'Could not download the protected Windows upgrade baseline' } - $downloadedFiles = @(Get-ChildItem -LiteralPath $downloadRoot -File) - if ($downloadedFiles.Count -ne 1 -or $downloadedFiles[0].Name -ne $assetName) { - throw 'Downloaded Windows upgrade baseline identity is ambiguous' - } - $baseInstaller = $downloadedFiles[0] - $actualSha256 = (Get-FileHash -LiteralPath $baseInstaller.FullName -Algorithm SHA256).Hash - if (-not [string]::Equals($actualSha256, $expectedSha256, [System.StringComparison]::OrdinalIgnoreCase)) { - throw 'Downloaded Windows upgrade baseline does not match the protected SHA-256' - } - - - name: Certify Windows Solo installer lifecycle - id: certify-windows - shell: pwsh - env: - WAGGLE_RELEASE_MODE: ${{ steps.verify-signed.outputs.release_mode }} - WINDOWS_CODESIGN_APPROVED_SUBJECT: ${{ steps.verify-signed.outputs.signer_subject }} - WINDOWS_UPGRADE_BASE_TAG: ${{ steps.verify-signed.outputs.upgrade_base_tag }} - WINDOWS_UPGRADE_BASE_ASSET_NAME: ${{ steps.verify-signed.outputs.upgrade_base_asset_name }} - WINDOWS_UPGRADE_BASE_SHA256: ${{ steps.verify-signed.outputs.upgrade_base_sha256 }} - WAGGLE_UPGRADE_BASE_COMMIT: ${{ steps.verify-signed.outputs.upgrade_base_commit }} - run: | - if ($env:WAGGLE_RELEASE_MODE -notin @('bootstrap', 'upgrade')) { - throw 'Windows release mode is missing or invalid during certification' - } - $installers = @( - Get-ChildItem -LiteralPath 'app/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis' ` - -Filter '*-setup.exe' -File - ) - if ($installers.Count -ne 1) { throw 'Certification target installer identity is ambiguous.' } - $installer = $installers[0] - if ($installer.Name -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]*-setup\.exe$' -or - $installer.DirectoryName -notmatch '[\\/]bundle[\\/]nsis$') { - throw 'Sealed signing receipt did not identify one canonical NSIS setup executable.' - } - $candidateVersion = [string](Get-Content -Raw -LiteralPath 'app/src-tauri/tauri.conf.json' | ConvertFrom-Json).version - if ($candidateVersion -notmatch '^\d+\.\d+\.\d+$' -or $env:GITHUB_REF_NAME -ne "v$candidateVersion") { - throw 'Candidate installer version no longer matches the release tag' - } - $candidateSha256 = (Get-FileHash -LiteralPath $installer.FullName -Algorithm SHA256).Hash - if ($candidateSha256 -cne '${{ needs.sign-windows.outputs.candidate_sha256 }}') { - throw 'Materialized candidate differs from the protected signed-handoff digest.' - } - $cleanReceiptPath = Join-Path $installer.DirectoryName 'windows-installer-certificate.json' - $upgradeReceiptPath = Join-Path $installer.DirectoryName 'windows-installer-upgrade-certificate.json' - if ((Test-Path -LiteralPath $cleanReceiptPath) -or - (Test-Path -LiteralPath $upgradeReceiptPath)) { - throw 'Refusing to overwrite a pre-existing Windows certification receipt' - } - - & ./scripts/certify-windows-installer.ps1 ` - -InstallerPath $installer.FullName ` - -ReceiptPath $cleanReceiptPath ` - -RequireAuthenticodeSignature ` - -ExpectedSignerSubject $env:WINDOWS_CODESIGN_APPROVED_SUBJECT ` - -ExpectedSourceRevision $env:GITHUB_SHA ` - -VerifyManagedModel - - if ($env:WAGGLE_RELEASE_MODE -eq 'upgrade') { - if ($env:WINDOWS_UPGRADE_BASE_TAG -notmatch '^v(?\d+\.\d+\.\d+)$') { - throw 'Protected upgrade base tag is invalid during certification.' - } - $baseVersion = $Matches['version'] - $baseInstallerPath = Join-Path ` - (Join-Path $env:RUNNER_TEMP 'waggle-windows-upgrade-baseline') ` - $env:WINDOWS_UPGRADE_BASE_ASSET_NAME - & ./scripts/certify-windows-installer.ps1 ` - -InstallerPath $installer.FullName ` - -ReceiptPath $upgradeReceiptPath ` - -RequireAuthenticodeSignature ` - -ExpectedSignerSubject $env:WINDOWS_CODESIGN_APPROVED_SUBJECT ` - -ExpectedSourceRevision $env:GITHUB_SHA ` - -RequireVersionToVersionUpgrade ` - -PreviousInstallerPath $baseInstallerPath ` - -ExpectedPreviousInstallerSha256 $env:WINDOWS_UPGRADE_BASE_SHA256 ` - -ExpectedPreviousVersion $baseVersion ` - -ExpectedPreviousSourceRevision $env:WAGGLE_UPGRADE_BASE_COMMIT ` - -ExpectedCandidateInstallerSha256 $candidateSha256 ` - -ExpectedCandidateVersion $candidateVersion ` - -VerifyManagedModel - } elseif (Test-Path -LiteralPath $upgradeReceiptPath) { - throw 'Bootstrap certification unexpectedly produced an upgrade receipt' - } - - $postCertificationSha256 = (Get-FileHash -LiteralPath $installer.FullName -Algorithm SHA256).Hash - if (-not [string]::Equals($postCertificationSha256, $candidateSha256, [System.StringComparison]::OrdinalIgnoreCase)) { - throw 'Candidate installer changed during Windows lifecycle certification' - } - "candidate_sha256=$candidateSha256" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - "candidate_version=$candidateVersion" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - - - name: Stage sealed Windows release outputs - id: stage-sealed - shell: pwsh - env: - WAGGLE_RELEASE_MODE: ${{ steps.verify-signed.outputs.release_mode }} - WINDOWS_BOOTSTRAP_RELEASE_IDENTITY: ${{ steps.verify-signed.outputs.bootstrap_identity }} - WINDOWS_UPGRADE_BASE_TAG: ${{ steps.verify-signed.outputs.upgrade_base_tag }} - WINDOWS_UPGRADE_BASE_ASSET_NAME: ${{ steps.verify-signed.outputs.upgrade_base_asset_name }} - WINDOWS_UPGRADE_BASE_SHA256: ${{ steps.verify-signed.outputs.upgrade_base_sha256 }} - WINDOWS_UPGRADE_BASE_COMMIT: ${{ steps.verify-signed.outputs.upgrade_base_commit }} - WINDOWS_CODESIGN_APPROVED_SUBJECT: ${{ steps.verify-signed.outputs.signer_subject }} - EXPECTED_CANDIDATE_SHA256: ${{ steps.certify-windows.outputs.candidate_sha256 }} - EXPECTED_CANDIDATE_VERSION: ${{ steps.certify-windows.outputs.candidate_version }} - SIGNED_HANDOFF_RECEIPT_SHA256: ${{ needs.sign-windows.outputs.handoff_receipt_sha256 }} - SIGNED_HANDOFF_ARTIFACT_ID: ${{ needs.sign-windows.outputs.artifact_id }} - SIGNED_HANDOFF_ARTIFACT_DIGEST: ${{ needs.sign-windows.outputs.artifact_digest }} - run: | - $sealedRoot = Join-Path $env:RUNNER_TEMP 'waggle-windows-sealed' - if (Test-Path -LiteralPath $sealedRoot) { throw 'Sealed Windows output root already exists.' } - $releaseRoot = New-Item -ItemType Directory -Path (Join-Path $sealedRoot 'release') - $sourceNsisRoot = New-Item -ItemType Directory -Path (Join-Path $sealedRoot 'source\release-nsis') - $sourceResourcesRoot = New-Item -ItemType Directory -Path (Join-Path $sealedRoot 'source\resources') - $provenanceRoot = New-Item -ItemType Directory -Path (Join-Path $sealedRoot 'provenance') - $installers = @( - Get-ChildItem -LiteralPath 'app/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis' ` - -Filter '*-setup.exe' -File - ) - if ($installers.Count -ne 1) { throw 'Sealed release installer identity is ambiguous.' } - $installer = $installers[0] - $cleanReceipt = Get-Item -LiteralPath (Join-Path $installer.DirectoryName 'windows-installer-certificate.json') - $upgradeReceiptPath = Join-Path $installer.DirectoryName 'windows-installer-upgrade-certificate.json' - $provenanceReceipt = Get-Item -LiteralPath ( - Join-Path $env:RUNNER_TEMP 'waggle-windows-signed\provenance\provenance-receipt.json' - ) - foreach ($file in @($installer, $cleanReceipt)) { - Copy-Item -LiteralPath $file.FullName -Destination $releaseRoot.FullName -ErrorAction Stop - } - Copy-Item -LiteralPath $provenanceReceipt.FullName ` - -Destination $provenanceRoot.FullName -ErrorAction Stop - $cleanReceiptData = Get-Content -Raw -LiteralPath $cleanReceipt.FullName | ConvertFrom-Json -Depth 32 - $signedReleaseRoot = Split-Path -Parent (Split-Path -Parent $installer.DirectoryName) - $generatedInstallerScripts = @( - Get-ChildItem -LiteralPath (Join-Path $signedReleaseRoot 'nsis') ` - -Recurse -Filter 'installer.nsi' -File - ) - $sourceService = Get-Item -LiteralPath 'app/src-tauri/resources/service.js' - if ($generatedInstallerScripts.Count -ne 1 -or - (Get-FileHash -LiteralPath $generatedInstallerScripts[0].FullName -Algorithm SHA256).Hash -cne - [string]$cleanReceiptData.evidence.generatedInstallerScriptSha256 -or - (Get-FileHash -LiteralPath $sourceService.FullName -Algorithm SHA256).Hash -cne - [string]$cleanReceiptData.evidence.sidecarBundleSha256) { - throw 'Certified source inputs no longer match the clean-install receipt.' - } - Copy-Item -LiteralPath $generatedInstallerScripts[0].FullName ` - -Destination (Join-Path $sourceNsisRoot.FullName 'installer.nsi') -ErrorAction Stop - Copy-Item -LiteralPath $sourceService.FullName ` - -Destination (Join-Path $sourceResourcesRoot.FullName 'service.js') -ErrorAction Stop - if ($env:WAGGLE_RELEASE_MODE -ceq 'upgrade') { - $upgradeReceipt = Get-Item -LiteralPath $upgradeReceiptPath - Copy-Item -LiteralPath $upgradeReceipt.FullName -Destination $releaseRoot.FullName -ErrorAction Stop - $baselineRoot = New-Item -ItemType Directory -Path (Join-Path $sealedRoot 'baseline') - $baseInstaller = Get-Item -LiteralPath ( - Join-Path ` - (Join-Path $env:RUNNER_TEMP 'waggle-windows-upgrade-baseline') ` - $env:WINDOWS_UPGRADE_BASE_ASSET_NAME - ) - Copy-Item -LiteralPath $baseInstaller.FullName -Destination $baselineRoot.FullName -ErrorAction Stop - } elseif (Test-Path -LiteralPath $upgradeReceiptPath) { - throw 'Bootstrap sealed outputs contain an unexpected upgrade receipt.' - } - $stagedInstaller = Get-Item -LiteralPath (Join-Path $releaseRoot.FullName $installer.Name) - if (-not [string]::Equals( - (Get-FileHash -LiteralPath $stagedInstaller.FullName -Algorithm SHA256).Hash, - $env:EXPECTED_CANDIDATE_SHA256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Staged sealed installer differs from its certified digest.' - } - if (@(Get-ChildItem -LiteralPath $provenanceRoot.FullName -File).Count -ne 1 -or - @(Get-ChildItem -LiteralPath (Join-Path $sealedRoot 'source') -Recurse -File).Count -ne 2) { - throw 'Sealed provenance and source inputs do not have the exact approved topology.' - } - . ./app/scripts/sign-windows-artifact.ps1 - $sealedInventory = New-WagglePrebuiltInventory -Root $sealedRoot - $expectedInventoryCount = if ($env:WAGGLE_RELEASE_MODE -ceq 'upgrade') { 7 } else { 5 } - if (@($sealedInventory.entries).Count -ne $expectedInventoryCount) { - throw 'Sealed release topology differs from the exact mode-specific contract.' - } - foreach ($digest in @( - $env:EXPECTED_CANDIDATE_SHA256, - $env:SIGNED_HANDOFF_RECEIPT_SHA256, - $env:SIGNED_HANDOFF_ARTIFACT_DIGEST - )) { - if ($digest -cnotmatch '^[0-9A-Fa-f]{64}$') { throw 'Sealed release digest binding is invalid.' } - } - if ($env:SIGNED_HANDOFF_ARTIFACT_ID -cnotmatch '^[1-9][0-9]*$') { - throw 'Sealed release signed-handoff artifact ID is invalid.' - } - $sealedReceipt = [ordered]@{ - schemaVersion = 1 - sourceRevision = $env:GITHUB_SHA - candidateTag = $env:GITHUB_REF_NAME - candidateVersion = $env:EXPECTED_CANDIDATE_VERSION - releaseMode = $env:WAGGLE_RELEASE_MODE - bootstrapIdentity = $env:WINDOWS_BOOTSTRAP_RELEASE_IDENTITY - upgradeBaseTag = $env:WINDOWS_UPGRADE_BASE_TAG - upgradeBaseAssetName = $env:WINDOWS_UPGRADE_BASE_ASSET_NAME - upgradeBaseSha256 = $env:WINDOWS_UPGRADE_BASE_SHA256 - upgradeBaseCommit = $env:WINDOWS_UPGRADE_BASE_COMMIT - signerSubject = $env:WINDOWS_CODESIGN_APPROVED_SUBJECT - candidateSha256 = $env:EXPECTED_CANDIDATE_SHA256.ToUpperInvariant() - signedHandoffReceiptSha256 = $env:SIGNED_HANDOFF_RECEIPT_SHA256.ToUpperInvariant() - signedHandoffArtifactId = $env:SIGNED_HANDOFF_ARTIFACT_ID - signedHandoffArtifactDigest = $env:SIGNED_HANDOFF_ARTIFACT_DIGEST.ToUpperInvariant() - inventory = $sealedInventory - } - $sealedReceiptPath = Join-Path $sealedRoot 'sealed-release-receipt.json' - Write-WaggleJsonNoBom $sealedReceiptPath $sealedReceipt - $sealedReceiptSha256 = (Get-FileHash -LiteralPath $sealedReceiptPath -Algorithm SHA256).Hash - "receipt_sha256=$sealedReceiptSha256" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append - - - name: Upload sealed Windows release outputs - id: upload-sealed - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - with: - name: waggle-windows-sealed-${{ github.sha }} - path: ${{ runner.temp }}\waggle-windows-sealed - if-no-files-found: error - include-hidden-files: true - retention-days: 30 - - attest-windows: - needs: certify-windows - if: github.event.repository.private == false - environment: production - runs-on: ubuntu-latest - permissions: - contents: read - attestations: write - id-token: write - steps: - - name: Download certified Windows release by immutable artifact ID - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 - with: - artifact-ids: ${{ needs.certify-windows.outputs.artifact_id }} - path: ${{ runner.temp }}/waggle-windows-sealed - merge-multiple: true - - - name: Validate certified artifact receipt and topology without execution - shell: pwsh - env: - EXPECTED_SEALED_RECEIPT_SHA256: ${{ needs.certify-windows.outputs.sealed_receipt_sha256 }} - EXPECTED_SEALED_ARTIFACT_ID: ${{ needs.certify-windows.outputs.artifact_id }} - EXPECTED_SEALED_ARTIFACT_DIGEST: ${{ needs.certify-windows.outputs.artifact_digest }} - EXPECTED_RELEASE_MODE: ${{ needs.certify-windows.outputs.release_mode }} - EXPECTED_CANDIDATE_SHA256: ${{ needs.certify-windows.outputs.candidate_sha256 }} - EXPECTED_CANDIDATE_VERSION: ${{ needs.certify-windows.outputs.candidate_version }} - EXPECTED_BOOTSTRAP_IDENTITY: ${{ needs.certify-windows.outputs.bootstrap_identity }} - EXPECTED_UPGRADE_BASE_TAG: ${{ needs.certify-windows.outputs.upgrade_base_tag }} - EXPECTED_UPGRADE_BASE_ASSET_NAME: ${{ needs.certify-windows.outputs.upgrade_base_asset_name }} - EXPECTED_UPGRADE_BASE_SHA256: ${{ needs.certify-windows.outputs.upgrade_base_sha256 }} - EXPECTED_UPGRADE_BASE_COMMIT: ${{ needs.certify-windows.outputs.upgrade_base_commit }} - EXPECTED_SIGNER_SUBJECT: ${{ needs.certify-windows.outputs.signer_subject }} - run: | - $sealedRoot = [IO.Path]::GetFullPath( - (Resolve-Path (Join-Path $env:RUNNER_TEMP 'waggle-windows-sealed')).Path - ) - $receiptPath = Join-Path $sealedRoot 'sealed-release-receipt.json' - foreach ($digest in @( - $env:EXPECTED_SEALED_RECEIPT_SHA256, - $env:EXPECTED_SEALED_ARTIFACT_DIGEST, - $env:EXPECTED_CANDIDATE_SHA256 - )) { - if ($digest -cnotmatch '^[0-9A-Fa-f]{64}$') { throw 'Attestation input digest is invalid.' } - } - if ($env:EXPECTED_SEALED_ARTIFACT_ID -cnotmatch '^[1-9][0-9]*$' -or - -not (Test-Path -LiteralPath $receiptPath -PathType Leaf) -or - (Get-FileHash -LiteralPath $receiptPath -Algorithm SHA256).Hash -cne - $env:EXPECTED_SEALED_RECEIPT_SHA256.ToUpperInvariant()) { - throw 'Attestation input immutable artifact or receipt binding is invalid.' - } - $receipt = Get-Content -Raw -LiteralPath $receiptPath | ConvertFrom-Json -Depth 32 - $expectedBindings = [ordered]@{ - sourceRevision = $env:GITHUB_SHA - candidateTag = $env:GITHUB_REF_NAME - candidateVersion = $env:EXPECTED_CANDIDATE_VERSION - releaseMode = $env:EXPECTED_RELEASE_MODE - bootstrapIdentity = $env:EXPECTED_BOOTSTRAP_IDENTITY - upgradeBaseTag = $env:EXPECTED_UPGRADE_BASE_TAG - upgradeBaseAssetName = $env:EXPECTED_UPGRADE_BASE_ASSET_NAME - upgradeBaseSha256 = $env:EXPECTED_UPGRADE_BASE_SHA256 - upgradeBaseCommit = $env:EXPECTED_UPGRADE_BASE_COMMIT - signerSubject = $env:EXPECTED_SIGNER_SUBJECT - candidateSha256 = $env:EXPECTED_CANDIDATE_SHA256 - } - if ([int]$receipt.schemaVersion -ne 1) { throw 'Sealed release receipt schema is invalid.' } - foreach ($property in $expectedBindings.Keys) { - if (-not [string]::Equals( - [string]$receipt.$property, - [string]$expectedBindings[$property], - [StringComparison]::OrdinalIgnoreCase - )) { - throw "Sealed release protected binding differs before attestation: $property" - } - } - $entries = @($receipt.inventory.entries) - $expectedCount = if ($env:EXPECTED_RELEASE_MODE -ceq 'upgrade') { 7 } else { 5 } - if ($entries.Count -ne $expectedCount) { throw 'Sealed release receipt inventory count is invalid.' } - $seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) - $orderedPaths = [Collections.Generic.List[string]]::new() - foreach ($entry in $entries) { - $relative = [string]$entry.path - if ($relative -match '(^|[\\/])\.\.?(?:[\\/]|$)' -or - $relative.Contains('/') -or $relative.Contains(':') -or - -not $seen.Add($relative) -or [string]$entry.sha256 -cnotmatch '^[0-9A-Fa-f]{64}$' -or - [long]$entry.size -lt 0) { - throw 'Sealed release receipt contains an unsafe inventory entry.' - } - $orderedPaths.Add($relative) - $platformRelative = $relative.Replace('\', [IO.Path]::DirectorySeparatorChar) - $path = [IO.Path]::GetFullPath((Join-Path $sealedRoot $platformRelative)) - $prefix = $sealedRoot.TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar - if (-not $path.StartsWith($prefix, [StringComparison]::Ordinal) -or - -not (Test-Path -LiteralPath $path -PathType Leaf) -or - (Get-Item -LiteralPath $path).Length -ne [long]$entry.size -or - (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -cne - ([string]$entry.sha256).ToUpperInvariant()) { - throw 'Sealed release artifact differs from its exact receipt.' - } - } - $sortedPaths = @($orderedPaths | Sort-Object -CaseSensitive) - if ([string]::Join("`n", $orderedPaths) -cne [string]::Join("`n", $sortedPaths)) { - throw 'Sealed release receipt paths are not canonically ordered.' - } - $canonical = @($entries | ForEach-Object { - [ordered]@{ - path = [string]$_.path - size = [long]$_.size - sha256 = ([string]$_.sha256).ToUpperInvariant() - } - }) | ConvertTo-Json -Depth 8 -Compress - $inventorySha256 = [Convert]::ToHexString( - [Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($canonical)) - ) - if ($inventorySha256 -cne [string]$receipt.inventory.sha256) { - throw 'Sealed release receipt inventory aggregate is invalid.' - } - $actualPaths = @( - Get-ChildItem -LiteralPath $sealedRoot -Recurse -Force -File | - ForEach-Object { [IO.Path]::GetRelativePath($sealedRoot, $_.FullName).Replace('/', '\') } | - Sort-Object -CaseSensitive - ) - $expectedPaths = @($orderedPaths) + @('sealed-release-receipt.json') - $expectedPaths = @($expectedPaths | Sort-Object -CaseSensitive) - if ([string]::Join("`n", $actualPaths) -cne [string]::Join("`n", $expectedPaths)) { - throw 'Sealed release extracted topology is not exact before attestation.' - } - - - name: Attest bootstrap Windows artifacts - if: needs.certify-windows.outputs.release_mode == 'bootstrap' - uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3 - with: - subject-path: | - ${{ runner.temp }}/waggle-windows-sealed/release/*-setup.exe - ${{ runner.temp }}/waggle-windows-sealed/release/windows-installer-certificate.json - ${{ runner.temp }}/waggle-windows-sealed/source/release-nsis/installer.nsi - ${{ runner.temp }}/waggle-windows-sealed/source/resources/service.js - ${{ runner.temp }}/waggle-windows-sealed/provenance/provenance-receipt.json - ${{ runner.temp }}/waggle-windows-sealed/sealed-release-receipt.json - - - name: Attest upgrade Windows artifacts - if: needs.certify-windows.outputs.release_mode == 'upgrade' - uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3 - with: - subject-path: | - ${{ runner.temp }}/waggle-windows-sealed/release/*-setup.exe - ${{ runner.temp }}/waggle-windows-sealed/release/windows-installer-certificate.json - ${{ runner.temp }}/waggle-windows-sealed/release/windows-installer-upgrade-certificate.json - ${{ runner.temp }}/waggle-windows-sealed/source/release-nsis/installer.nsi - ${{ runner.temp }}/waggle-windows-sealed/source/resources/service.js - ${{ runner.temp }}/waggle-windows-sealed/provenance/provenance-receipt.json - ${{ runner.temp }}/waggle-windows-sealed/sealed-release-receipt.json - - publish-windows: - needs: [certify-windows, attest-windows] - if: >- - vars.WINDOWS_PUBLIC_RELEASE_AUTHORIZED == 'true' && - github.event.repository.private == false && - startsWith(github.ref, 'refs/tags/v') - runs-on: windows-latest - permissions: - contents: write - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - with: - fetch-depth: 0 - persist-credentials: false - - - name: Validate immutable publication boundary - shell: pwsh - run: | - $version = [string](Get-Content -Raw -LiteralPath 'app/src-tauri/tauri.conf.json' | ConvertFrom-Json).version - $checkedOutRevision = (git rev-parse --verify HEAD).Trim().ToLowerInvariant() - if ($env:GITHUB_REPOSITORY -cne 'marolinik/waggle-os' -or - $env:GITHUB_REF_TYPE -cne 'tag' -or - $env:GITHUB_REF_NAME -cne "v$version" -or - $checkedOutRevision -cne $env:GITHUB_SHA -or - @(git status --porcelain=v1 --untracked-files=all).Count -ne 0) { - throw 'Windows publication requires the clean exact repository, tag, revision, and version boundary.' - } - - - name: Download sealed Windows release outputs - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 - with: - artifact-ids: ${{ needs.certify-windows.outputs.artifact_id }} - path: ${{ runner.temp }}\waggle-windows-sealed - merge-multiple: true - - - name: Stage exact publication inputs - id: publication-inputs - shell: pwsh - env: - WAGGLE_RELEASE_MODE: ${{ needs.certify-windows.outputs.release_mode }} - EXPECTED_CANDIDATE_SHA256: ${{ needs.certify-windows.outputs.candidate_sha256 }} - EXPECTED_CANDIDATE_VERSION: ${{ needs.certify-windows.outputs.candidate_version }} - EXPECTED_BOOTSTRAP_IDENTITY: ${{ needs.certify-windows.outputs.bootstrap_identity }} - EXPECTED_BASE_TAG: ${{ needs.certify-windows.outputs.upgrade_base_tag }} - EXPECTED_BASE_ASSET_NAME: ${{ needs.certify-windows.outputs.upgrade_base_asset_name }} - EXPECTED_BASE_SHA256: ${{ needs.certify-windows.outputs.upgrade_base_sha256 }} - EXPECTED_BASE_COMMIT: ${{ needs.certify-windows.outputs.upgrade_base_commit }} - EXPECTED_SIGNER_SUBJECT: ${{ needs.certify-windows.outputs.signer_subject }} - EXPECTED_SEALED_RECEIPT_SHA256: ${{ needs.certify-windows.outputs.sealed_receipt_sha256 }} - EXPECTED_SEALED_ARTIFACT_ID: ${{ needs.certify-windows.outputs.artifact_id }} - EXPECTED_SEALED_ARTIFACT_DIGEST: ${{ needs.certify-windows.outputs.artifact_digest }} - run: | - $sealedRoot = Join-Path $env:RUNNER_TEMP 'waggle-windows-sealed' - $sealedReceiptPath = Join-Path $sealedRoot 'sealed-release-receipt.json' - foreach ($digest in @( - $env:EXPECTED_SEALED_RECEIPT_SHA256, - $env:EXPECTED_SEALED_ARTIFACT_DIGEST, - $env:EXPECTED_CANDIDATE_SHA256 - )) { - if ($digest -cnotmatch '^[0-9A-Fa-f]{64}$') { throw 'Publication artifact digest is invalid.' } - } - if ($env:EXPECTED_SEALED_ARTIFACT_ID -cnotmatch '^[1-9][0-9]*$' -or - -not (Test-Path -LiteralPath $sealedReceiptPath -PathType Leaf) -or - (Get-FileHash -LiteralPath $sealedReceiptPath -Algorithm SHA256).Hash -cne - $env:EXPECTED_SEALED_RECEIPT_SHA256.ToUpperInvariant()) { - throw 'Publication immutable artifact or sealed receipt binding is invalid.' - } - $sealedReceipt = Get-Content -Raw -LiteralPath $sealedReceiptPath | - ConvertFrom-Json -Depth 32 - $expectedBindings = [ordered]@{ - sourceRevision = $env:GITHUB_SHA - candidateTag = $env:GITHUB_REF_NAME - candidateVersion = $env:EXPECTED_CANDIDATE_VERSION - releaseMode = $env:WAGGLE_RELEASE_MODE - bootstrapIdentity = $env:EXPECTED_BOOTSTRAP_IDENTITY - upgradeBaseTag = $env:EXPECTED_BASE_TAG - upgradeBaseAssetName = $env:EXPECTED_BASE_ASSET_NAME - upgradeBaseSha256 = $env:EXPECTED_BASE_SHA256 - upgradeBaseCommit = $env:EXPECTED_BASE_COMMIT - signerSubject = $env:EXPECTED_SIGNER_SUBJECT - candidateSha256 = $env:EXPECTED_CANDIDATE_SHA256 - } - if ($sealedReceipt.schemaVersion -is [string] -or [int]$sealedReceipt.schemaVersion -ne 1) { - throw 'Publication sealed receipt schema is invalid.' - } - foreach ($property in $expectedBindings.Keys) { - if (-not [string]::Equals( - [string]$sealedReceipt.$property, - [string]$expectedBindings[$property], - [StringComparison]::Ordinal - )) { - throw "Publication sealed receipt binding differs: $property" - } - } - $entries = @($sealedReceipt.inventory.entries) - $expectedEntryCount = if ($env:WAGGLE_RELEASE_MODE -ceq 'upgrade') { 7 } else { 5 } - if ($entries.Count -ne $expectedEntryCount) { - throw 'Publication sealed receipt inventory count is invalid.' - } - $seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) - $orderedPaths = [Collections.Generic.List[string]]::new() - foreach ($entry in $entries) { - $relative = [string]$entry.path - if ($relative -match '(^|[\\/])\.\.?(?:[\\/]|$)' -or - $relative.Contains('/') -or $relative.Contains(':') -or - -not $seen.Add($relative) -or [string]$entry.sha256 -cnotmatch '^[0-9A-Fa-f]{64}$' -or - [long]$entry.size -lt 0) { - throw 'Publication sealed receipt contains an unsafe inventory entry.' - } - $orderedPaths.Add($relative) - $path = [IO.Path]::GetFullPath((Join-Path $sealedRoot $relative)) - $prefix = [IO.Path]::GetFullPath($sealedRoot).TrimEnd('\') + '\' - if (-not $path.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase) -or - -not (Test-Path -LiteralPath $path -PathType Leaf) -or - (Get-Item -LiteralPath $path).Length -ne [long]$entry.size -or - (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -cne - ([string]$entry.sha256).ToUpperInvariant()) { - throw 'Publication artifact file differs from its sealed receipt.' - } - } - $sortedPaths = @($orderedPaths | Sort-Object -CaseSensitive) - if ([string]::Join("`n", $orderedPaths) -cne [string]::Join("`n", $sortedPaths)) { - throw 'Publication sealed receipt paths are not canonically ordered.' - } - $canonical = @($entries | ForEach-Object { - [ordered]@{ - path = [string]$_.path - size = [long]$_.size - sha256 = ([string]$_.sha256).ToUpperInvariant() - } - }) | ConvertTo-Json -Depth 8 -Compress - $inventorySha256 = [Convert]::ToHexString( - [Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($canonical)) - ) - if ($inventorySha256 -cne [string]$sealedReceipt.inventory.sha256) { - throw 'Publication sealed receipt inventory aggregate is invalid.' - } - $actualPaths = @( - Get-ChildItem -LiteralPath $sealedRoot -Recurse -Force -File | - ForEach-Object { [IO.Path]::GetRelativePath($sealedRoot, $_.FullName).Replace('/', '\') } | - Sort-Object -CaseSensitive - ) - $expectedPaths = @($orderedPaths) + @('sealed-release-receipt.json') - $expectedPaths = @($expectedPaths | Sort-Object -CaseSensitive) - if ([string]::Join("`n", $actualPaths) -cne [string]::Join("`n", $expectedPaths)) { - throw 'Sealed publication artifact topology is not exact.' - } - $sourceReleaseRoot = Join-Path $sealedRoot 'release' - $sealedSourceRoot = Join-Path $sealedRoot 'source' - $sealedProvenanceRoot = Join-Path $sealedRoot 'provenance' - $installers = @(Get-ChildItem -LiteralPath $sourceReleaseRoot -Filter '*-setup.exe' -File) - if ($installers.Count -ne 1 -or - -not [string]::Equals( - (Get-FileHash -LiteralPath $installers[0].FullName -Algorithm SHA256).Hash, - [string]$env:EXPECTED_CANDIDATE_SHA256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Sealed publication artifact does not contain exactly the certified candidate installer.' - } - $cleanReceipt = Get-Item -LiteralPath ( - Join-Path $sourceReleaseRoot 'windows-installer-certificate.json' - ) - $upgradeReceiptPath = Join-Path ` - $sourceReleaseRoot 'windows-installer-upgrade-certificate.json' - $expectedReleaseFileCount = if ($env:WAGGLE_RELEASE_MODE -ceq 'upgrade') { 3 } else { 2 } - if (@(Get-ChildItem -LiteralPath $sourceReleaseRoot -File).Count -ne - $expectedReleaseFileCount -or - ($env:WAGGLE_RELEASE_MODE -ceq 'upgrade') -ne - (Test-Path -LiteralPath $upgradeReceiptPath -PathType Leaf)) { - throw 'Sealed release directory does not contain exactly the installer and required certificate receipt(s).' - } - $sealedGeneratedInstaller = Get-Item -LiteralPath ( - Join-Path $sealedSourceRoot 'release-nsis\installer.nsi' - ) - $sealedService = Get-Item -LiteralPath ( - Join-Path $sealedSourceRoot 'resources\service.js' - ) - $sealedProvenance = @(Get-ChildItem -LiteralPath $sealedProvenanceRoot -File) - if (@(Get-ChildItem -LiteralPath $sealedSourceRoot -Recurse -File).Count -ne 2 -or - $sealedProvenance.Count -ne 1 -or - $sealedProvenance[0].Name -cne 'provenance-receipt.json') { - throw 'Sealed publication source and provenance topology is not exact.' - } - $cleanReceiptData = Get-Content -Raw -LiteralPath $cleanReceipt.FullName | - ConvertFrom-Json -Depth 32 - if ((Get-FileHash -LiteralPath $sealedGeneratedInstaller.FullName -Algorithm SHA256).Hash -cne - [string]$cleanReceiptData.evidence.generatedInstallerScriptSha256 -or - (Get-FileHash -LiteralPath $sealedService.FullName -Algorithm SHA256).Hash -cne - [string]$cleanReceiptData.evidence.sidecarBundleSha256) { - throw 'Sealed publication source inputs differ from their certified hashes.' - } - $targetReleaseRoot = 'app/src-tauri/target/x86_64-pc-windows-msvc/release' - if (Test-Path -LiteralPath $targetReleaseRoot) { throw 'Publication target already exists.' } - $publicationRoot = New-Item -ItemType Directory -Path (Join-Path $targetReleaseRoot 'bundle\nsis') - $generatedNsisRoot = New-Item -ItemType Directory -Path (Join-Path $targetReleaseRoot 'nsis') - Copy-Item -LiteralPath $installers[0].FullName ` - -Destination $publicationRoot.FullName -ErrorAction Stop - Copy-Item -LiteralPath $cleanReceipt.FullName ` - -Destination $publicationRoot.FullName -ErrorAction Stop - if ($env:WAGGLE_RELEASE_MODE -ceq 'upgrade') { - Copy-Item -LiteralPath $upgradeReceiptPath ` - -Destination $publicationRoot.FullName -ErrorAction Stop - } - Copy-Item -LiteralPath $sealedGeneratedInstaller.FullName ` - -Destination (Join-Path $generatedNsisRoot.FullName 'installer.nsi') -ErrorAction Stop - $canonicalServicePath = [IO.Path]::GetFullPath('app/src-tauri/resources/service.js') - if (Test-Path -LiteralPath $canonicalServicePath) { - throw 'Fresh publication checkout unexpectedly already contains generated service.js.' - } - [IO.File]::Copy($sealedService.FullName, $canonicalServicePath, $false) - if (@(Get-ChildItem -LiteralPath $publicationRoot.FullName -File).Count -ne - $expectedReleaseFileCount) { - throw 'Publication bundle contains an unexpected asset; provenance must remain separate.' - } - $baseInstallerPath = '' - if ($env:WAGGLE_RELEASE_MODE -ceq 'upgrade') { - $baselineRoot = Join-Path $sealedRoot 'baseline' - $baseInstallers = @(Get-ChildItem -LiteralPath $baselineRoot -File) - if ($baseInstallers.Count -ne 1 -or - $baseInstallers[0].Name -cne $env:EXPECTED_BASE_ASSET_NAME -or - -not [string]::Equals( - (Get-FileHash -LiteralPath $baseInstallers[0].FullName -Algorithm SHA256).Hash, - [string]$env:EXPECTED_BASE_SHA256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Sealed publication artifact does not contain the exact protected upgrade baseline.' - } - $baseInstallerPath = $baseInstallers[0].FullName - } elseif (Test-Path -LiteralPath (Join-Path $sealedRoot 'baseline')) { - throw 'Bootstrap sealed publication artifact contains an unexpected upgrade baseline.' - } - "WAGGLE_UPGRADE_BASE_INSTALLER_PATH=$baseInstallerPath" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append - - - name: Publish certified Windows release - if: success() && startsWith(github.ref, 'refs/tags/v') - shell: pwsh - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - WINDOWS_BOOTSTRAP_RELEASE_IDENTITY: ${{ needs.certify-windows.outputs.bootstrap_identity }} - WINDOWS_UPGRADE_BASE_TAG: ${{ needs.certify-windows.outputs.upgrade_base_tag }} - WINDOWS_UPGRADE_BASE_ASSET_NAME: ${{ needs.certify-windows.outputs.upgrade_base_asset_name }} - WINDOWS_UPGRADE_BASE_SHA256: ${{ needs.certify-windows.outputs.upgrade_base_sha256 }} - WINDOWS_UPGRADE_BASE_COMMIT: ${{ needs.certify-windows.outputs.upgrade_base_commit }} - WINDOWS_CODESIGN_APPROVED_SUBJECT: ${{ needs.certify-windows.outputs.signer_subject }} - WAGGLE_RELEASE_MODE: ${{ needs.certify-windows.outputs.release_mode }} - WAGGLE_UPGRADE_BASE_COMMIT: ${{ needs.certify-windows.outputs.upgrade_base_commit }} - WAGGLE_CERTIFIED_CANDIDATE_SHA256: ${{ needs.certify-windows.outputs.candidate_sha256 }} - WAGGLE_CERTIFIED_CANDIDATE_VERSION: ${{ needs.certify-windows.outputs.candidate_version }} - run: | - if ($env:WAGGLE_RELEASE_MODE -notin @('bootstrap', 'upgrade')) { - throw 'Protected signer did not authorize a publication mode.' - } - $baseVersion = '' - if ($env:WAGGLE_RELEASE_MODE -ceq 'upgrade') { - if ($env:WINDOWS_UPGRADE_BASE_TAG -notmatch '^v(?\d+\.\d+\.\d+)$') { - throw 'Protected upgrade base tag is invalid during publication.' - } - $baseVersion = $Matches['version'] - } - $env:WAGGLE_UPGRADE_BASE_VERSION = $baseVersion - ./scripts/publish-windows-release.ps1 -Mode $env:WAGGLE_RELEASE_MODE - - build-macos: + build: + name: Build (${{ matrix.release_target }}) strategy: + fail-fast: false matrix: include: - - target: aarch64-apple-darwin - arch: arm64 - runner: macos-15 - - target: x86_64-apple-darwin + - runner: windows-latest + rust_target: x86_64-pc-windows-msvc + release_target: windows-x64 arch: x64 - runner: macos-15-intel + bundles: nsis,msi + - runner: macos-15 + rust_target: aarch64-apple-darwin + release_target: macos-arm64 + arch: arm64 + bundles: app,dmg + - runner: macos-15-intel + rust_target: x86_64-apple-darwin + release_target: macos-x64 + arch: x64 + bundles: app,dmg + - runner: ubuntu-22.04 + rust_target: x86_64-unknown-linux-gnu + release_target: linux-x64 + arch: x64 + bundles: deb,appimage runs-on: ${{ matrix.runner }} + timeout-minutes: 120 env: + # The staging scripts take the Node runtime and native modules for this architecture. TARGET_ARCH: ${{ matrix.arch }} steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 with: persist-credentials: false + # The Node version the installer and the desktop app ship (ADR-0008). - name: Setup Node.js uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: 22.23.2 cache: npm + cache-dependency-path: | + package-lock.json + app/package-lock.json - name: Verify runner architecture run: node -e "if (process.arch !== process.env.TARGET_ARCH) { console.error('Expected ' + process.env.TARGET_ARCH + ' runner, got ' + process.arch); process.exit(1); }" @@ -2493,12 +94,21 @@ jobs: uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 with: toolchain: 1.94.0 - targets: ${{ matrix.target }} + targets: ${{ matrix.rust_target }} - name: Rust cache uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 with: workspaces: app/src-tauri + key: ${{ matrix.rust_target }} + + # Tauri 2 build dependencies, plus Xvfb and D-Bus for the desktop smoke test. + - name: Install Linux system packages + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev \ + libxdo-dev libssl-dev patchelf file xdg-utils xvfb dbus - name: Install dependencies run: npm ci @@ -2506,9 +116,15 @@ jobs: - name: Install locked Tauri CLI run: npm ci --prefix app --ignore-scripts - - name: Build packages (shared -> core -> agent -> server) + # The staged sidecar carries the dist/ builds of the workspace packages. + - name: Build packages run: npm run build:packages + - name: Build installer + run: npm run build --workspace @waggle-ai/waggle + + # On Windows these steps run in PowerShell, the default shell, where tar + # is the system bsdtar that bundle-node and build-server-archive expect. - name: Bundle Node.js runtime run: node scripts/bundle-node.mjs @@ -2521,37 +137,117 @@ jobs: - name: Stage sidecar dependencies run: node scripts/stage-sidecar-deps.mjs - - name: Build frontend + - name: Check sidecar resources + run: node scripts/check-sidecar-resources.mjs + + - name: Build web UI run: cd apps/web && npx vite build - - name: Build Tauri (macOS) - run: cd app && node node_modules/@tauri-apps/cli/tauri.js build --target ${{ matrix.target }} + - name: Build server archive + run: node scripts/build-server-archive.mjs + + # Install, doctor, run on a free port with a temporary data directory, + # wait for /health, stop, uninstall. + - name: Installer smoke test + timeout-minutes: 15 + run: node scripts/release-smoke.mjs installer + + - name: Build desktop app + if: runner.os != 'macOS' + run: cd app && node node_modules/@tauri-apps/cli/tauri.js build --target ${{ matrix.rust_target }} --bundles "${{ matrix.bundles }}" + + - name: Build desktop app (macOS, ad-hoc signature) + if: runner.os == 'macOS' + run: cd app && node node_modules/@tauri-apps/cli/tauri.js build --target ${{ matrix.rust_target }} --bundles "${{ matrix.bundles }}" --config '{"bundle":{"macOS":{"signingIdentity":"-"}}}' + + # Each desktop smoke test starts the packaged app, waits until its sidecar + # answers /health on 127.0.0.1:3333, then stops the app and the sidecar. + - name: Desktop smoke test (Windows) + if: runner.os == 'Windows' + timeout-minutes: 15 + run: | + $setup = Get-ChildItem app/src-tauri/target/${{ matrix.rust_target }}/release/bundle/nsis/*-setup.exe | Select-Object -First 1 + $installDir = Join-Path $env:RUNNER_TEMP 'waggle-desktop' + # A silent per-user install into a temporary directory. + $installer = Start-Process -FilePath $setup.FullName -ArgumentList '/S', "/D=$installDir" -Wait -PassThru + if ($installer.ExitCode -ne 0) { throw "The NSIS installer exited with code $($installer.ExitCode)" } + $app = Get-ChildItem -LiteralPath $installDir -Filter *.exe | Where-Object { $_.Name -notlike 'uninstall*' } | Select-Object -First 1 + if (-not $app) { throw "No app executable in $installDir" } + node scripts/release-smoke.mjs desktop --app $app.FullName + + - name: Desktop smoke test (macOS) + if: runner.os == 'macOS' + timeout-minutes: 15 + run: node scripts/release-smoke.mjs desktop --app app/src-tauri/target/${{ matrix.rust_target }}/release/bundle/macos/Waggle.app + + - name: Desktop smoke test (Linux) + if: runner.os == 'Linux' + timeout-minutes: 15 env: - TAURI_PRIVATE_KEY: '' - TAURI_KEY_PASSWORD: '' + # WebKitGTK has no GPU compositing under Xvfb. + WEBKIT_DISABLE_COMPOSITING_MODE: '1' + run: | + deb=$(ls app/src-tauri/target/${{ matrix.rust_target }}/release/bundle/deb/*.deb) + sudo apt-get install -y "$PWD/$deb" + app=$(dpkg-deb --contents "$deb" | awk '$1 ~ /^-/ && $6 ~ /^\.\/usr\/bin\// { print substr($6, 2); exit }') + xvfb-run --auto-servernum dbus-run-session -- node scripts/release-smoke.mjs desktop --app "$app" - - name: Upload macOS DMG verification artifact + - name: Collect installers + shell: bash + run: | + bundle=app/src-tauri/target/${{ matrix.rust_target }}/release/bundle + case "$RUNNER_OS" in + Windows) cp "$bundle"/nsis/*-setup.exe "$bundle"/msi/*.msi artifacts/ ;; + macOS) cp "$bundle"/dmg/*.dmg artifacts/ ;; + Linux) cp "$bundle"/deb/*.deb "$bundle"/appimage/*.AppImage artifacts/ ;; + esac + ls -l artifacts + + - name: Upload build outputs uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: - name: waggle-macos-dmg-verification-${{ matrix.target }}-${{ github.sha }} - path: app/src-tauri/target/${{ matrix.target }}/release/bundle/dmg/*.dmg + name: waggle-${{ matrix.release_target }} + path: artifacts/ if-no-files-found: error - retention-days: 7 + retention-days: 14 - - name: Upload macOS app verification artifact - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + publish: + name: Draft GitHub release + needs: build + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') + runs-on: ubuntu-22.04 + timeout-minutes: 30 + permissions: + contents: write + steps: + - name: Download build outputs + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: - name: waggle-macos-app-verification-${{ matrix.target }}-${{ github.sha }} - path: app/src-tauri/target/${{ matrix.target }}/release/bundle/macos/*.app - if-no-files-found: error - retention-days: 7 + pattern: waggle-* + path: release + merge-multiple: true - # NOTE: the Tauri auto-updater is disabled for v1 (plugins.updater removed from - # tauri.conf.json — see BUILD P0-2 / P1-8). The former `update-manifest` job - # published a latest.json with EMPTY signatures, which every client rejected at - # signature verification. Re-enabling the updater requires: - # 1. Provision a TAURI_SIGNING_PRIVATE_KEY (+ password) repo secret. - # 2. Restore `plugins.updater` (endpoints + pubkey) in tauri.conf.json and - # set bundle.createUpdaterArtifacts so tauri-action emits signed .sig files. - # 3. Restore a latest.json generator that reads the real signatures from the - # build artifacts (tauri-action can publish the manifest directly). + # The installer downloads release v, and the desktop + # installers carry the app version. Warn when the tag differs from either. + - name: Check versions + env: + TAG: ${{ github.ref_name }} + run: | + version="${TAG#v}" + compgen -G "release/waggle-server-$version-*.tar.gz" > /dev/null \ + || echo "::warning::No server archive for $TAG: packages/launcher/package.json has another version." + compgen -G "release/Waggle_${version}_*" > /dev/null \ + || echo "::warning::No desktop installer for $TAG: app/src-tauri/tauri.conf.json has another version." + + - name: Write SHA256SUMS + working-directory: release + run: | + find . -maxdepth 1 -type f ! -name '*.sha256' -printf '%f\n' | LC_ALL=C sort | xargs -d '\n' sha256sum > SHA256SUMS + cat SHA256SUMS + + - name: Create draft release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + TAG: ${{ github.ref_name }} + run: gh release create "$TAG" release/* --draft --verify-tag --title "Waggle $TAG" --generate-notes diff --git a/.github/workflows/tauri-build-pr.yml b/.github/workflows/tauri-build-pr.yml deleted file mode 100644 index ee8a4ba..0000000 --- a/.github/workflows/tauri-build-pr.yml +++ /dev/null @@ -1,281 +0,0 @@ -# Waggle — Tauri Build Verification (per-PR + main pushes) -# -# CC Sesija A §2.4 Task A13 (PM-reframed scope). Verifies the desktop app -# builds cleanly on Win + macOS for every PR + main push, so a regression -# can't sneak in unnoticed between releases. Distinct from release.yml -# which only triggers on `v*` tags + uploads to GitHub Releases (this -# workflow only uploads to the workflow run as artifacts for download -# verification, no release publishing). -# -# Exit signal: green CI here means tag-push to release.yml is safe to -# pull the trigger on. Red CI here = same investigation flow as release.yml -# (Rust compile / Vite build / sidecar bundle / native dep failure). - -name: Tauri Build Verification - -on: - pull_request: - branches: - - main - paths: - - 'app/**' - - 'apps/web/**' - - 'packages/**' - - 'scripts/**' - - 'package.json' - - 'package-lock.json' - - '.github/workflows/release.yml' - - '.github/workflows/tauri-build-pr.yml' - push: - branches: - - main - paths: - - 'app/**' - - 'apps/web/**' - - 'packages/**' - - 'scripts/**' - - 'package.json' - - 'package-lock.json' - - '.github/workflows/release.yml' - - '.github/workflows/tauri-build-pr.yml' - workflow_dispatch: - -permissions: - contents: read - -jobs: - verify-windows: - runs-on: windows-latest - timeout-minutes: 45 - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - with: - persist-credentials: false - - - name: Setup Node.js - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 - with: - node-version: 22.23.2 - cache: npm - - - name: Setup Rust - uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 - with: - toolchain: 1.94.0 - - - name: Rust cache - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 - with: - workspaces: app/src-tauri - - - name: Install dependencies - run: npm ci - - - name: Verify Windows skill-audit and vault regressions - shell: pwsh - run: node node_modules/vitest/vitest.mjs run --root . --config vitest.config.ts packages/agent/tests/skill-audit-store.test.ts packages/core/tests/vault.test.ts --maxWorkers=1 --no-file-parallelism - - - name: Verify Windows release-mode and publication guards - shell: pwsh - env: - WAGGLE_REQUIRE_PWSH7: '1' - run: node node_modules/vitest/vitest.mjs run --root . --config vitest.config.ts packages/server/tests/tauri-config.test.ts -t "CI/CD Configuration" - - - name: Install locked Tauri CLI - run: npm ci --prefix app --ignore-scripts - - - name: Build packages (shared → core → agent → server) - run: npm run build:packages - - - name: Bundle Node.js runtime - run: node scripts/bundle-node.mjs - - - name: Build sidecar - run: node scripts/build-sidecar.mjs - - - name: Bundle native dependencies - run: node scripts/bundle-native-deps.mjs - - - name: Stage sidecar dependencies - run: node scripts/stage-sidecar-deps.mjs - - - name: Build frontend - run: cd apps/web && npx vite build - - - name: Verify repository cleanliness before Tauri build - shell: pwsh - run: | - $sourceStatus = @(& git status --porcelain=v1 --untracked-files=all) - if ($LASTEXITCODE -ne 0) { throw 'Could not inspect repository source state before Tauri build.' } - if ($sourceStatus.Count -ne 0) { - $sourceDetails = $sourceStatus -join [Environment]::NewLine - throw "Repository must be clean before Windows Tauri build.$([Environment]::NewLine)$sourceDetails" - } - - - name: Build Tauri (Windows) - id: tauri-build-windows - # app/package-lock.json pins the CLI and platform binary. Invoke that - # local copy so verification builds cannot drift to a newer 2.x release. - run: cd app && node node_modules/@tauri-apps/cli/tauri.js build --bundles nsis - env: - # Skip code signing for PR verification — release.yml handles signing - # only on tag push. - TAURI_PRIVATE_KEY: '' - TAURI_KEY_PASSWORD: '' - - - name: Report repository changes after Tauri build - if: ${{ always() && steps.tauri-build-windows.outcome != 'skipped' }} - shell: pwsh - run: | - $sourceStatus = @(& git status --porcelain=v1 --untracked-files=all) - if ($LASTEXITCODE -ne 0) { throw 'Could not inspect repository source state after Tauri build.' } - if ($sourceStatus.Count -ne 0) { - $trackedPaths = @(& git diff --name-only --diff-filter=ACDMRTUXB) - if ($LASTEXITCODE -ne 0) { throw 'Could not enumerate tracked Tauri build mutations.' } - foreach ($trackedPath in $trackedPaths) { - Write-Host "::group::Tracked mutation: $trackedPath" - $headBlob = @(& git rev-parse "HEAD:$trackedPath" 2>&1) -join '' - $headBlobExit = $LASTEXITCODE - $indexBlob = @(& git rev-parse ":$trackedPath" 2>&1) -join '' - $indexBlobExit = $LASTEXITCODE - if (Test-Path -LiteralPath $trackedPath -PathType Leaf) { - $worktreeHash = (Get-FileHash -LiteralPath $trackedPath -Algorithm SHA256).Hash.ToLowerInvariant() - $filteredBlob = @(& git hash-object "--path=$trackedPath" -- $trackedPath 2>&1) -join '' - $filteredBlobExit = $LASTEXITCODE - $resolvedPath = (Resolve-Path -LiteralPath $trackedPath).Path - $bytes = [IO.File]::ReadAllBytes($resolvedPath) - $crlfCount = 0 - $lfOnlyCount = 0 - for ($index = 0; $index -lt $bytes.Length; $index += 1) { - if ($bytes[$index] -ne 10) { continue } - if ($index -gt 0 -and $bytes[$index - 1] -eq 13) { $crlfCount += 1 } - else { $lfOnlyCount += 1 } - } - } else { - $worktreeHash = '' - $filteredBlob = '' - $filteredBlobExit = 0 - $crlfCount = 0 - $lfOnlyCount = 0 - } - Write-Host "HEAD blob (exit $headBlobExit): $headBlob" - Write-Host "Index blob (exit $indexBlobExit): $indexBlob" - Write-Host "Git-filtered worktree blob (exit $filteredBlobExit): $filteredBlob" - Write-Host "Raw worktree SHA256: $worktreeHash; CRLF=$crlfCount; LF-only=$lfOnlyCount" - $changeSummary = @(& git diff --numstat -- $trackedPath) - $changeSummaryExit = $LASTEXITCODE - if ($changeSummaryExit -ne 0) { - Write-Host "Could not render numeric diff summary (exit $changeSummaryExit)." - } else { - Write-Host "Numeric diff summary: $($changeSummary -join '; ')" - } - Write-Host '::endgroup::' - } - $sourceDetails = $sourceStatus -join [Environment]::NewLine - throw "Windows Tauri build mutated repository worktree.$([Environment]::NewLine)$sourceDetails" - } - - - name: Certify Windows Solo installer lifecycle - shell: pwsh - run: | - $installers = @(Get-ChildItem -LiteralPath 'app/src-tauri/target' -Recurse -Filter '*-setup.exe' -File | Where-Object { $_.DirectoryName -match '[\\/]bundle[\\/]nsis$' }) - if ($installers.Count -ne 1) { throw "Expected exactly one NSIS setup executable, found $($installers.Count)" } - $installer = $installers[0] - & ./scripts/certify-windows-installer.ps1 -InstallerPath $installer.FullName -ExpectedSourceRevision $env:GITHUB_SHA - - - name: Upload Windows artifacts - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - with: - name: waggle-windows-${{ github.sha }} - path: | - app/src-tauri/target/**/bundle/nsis/*.exe - app/src-tauri/target/**/bundle/nsis/windows-installer-certificate.json - if-no-files-found: error - retention-days: 7 - - verify-macos: - timeout-minutes: 60 - strategy: - # Per-arch, matching release.yml. Universal builds are rejected by the - # bundle scripts (sqlite-vec / onnxruntime / node ship per-arch binaries), - # so each arch is staged and built separately. - matrix: - include: - - target: aarch64-apple-darwin - arch: arm64 - runner: macos-15 - bundles: dmg - artifact_path: app/src-tauri/target/aarch64-apple-darwin/release/bundle/dmg/*.dmg - - target: x86_64-apple-darwin - arch: x64 - runner: macos-15-intel - bundles: app - artifact_path: app/src-tauri/target/x86_64-apple-darwin/release/bundle/macos/*.app - runs-on: ${{ matrix.runner }} - env: - TARGET_ARCH: ${{ matrix.arch }} - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - with: - persist-credentials: false - - - name: Setup Node.js - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 - with: - node-version: 22.23.2 - cache: npm - - - name: Verify runner architecture - run: node -e "if (process.arch !== process.env.TARGET_ARCH) { console.error('Expected ' + process.env.TARGET_ARCH + ' runner, got ' + process.arch); process.exit(1); }" - - - name: Setup Rust - uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 - with: - toolchain: 1.94.0 - targets: ${{ matrix.target }} - - - name: Rust cache - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 - with: - workspaces: app/src-tauri - - - name: Install dependencies - run: npm ci - - - name: Install locked Tauri CLI - run: npm ci --prefix app --ignore-scripts - - - name: Build packages (shared → core → agent → server) - run: npm run build:packages - - - name: Bundle Node.js runtime - run: node scripts/bundle-node.mjs - - - name: Build sidecar - run: node scripts/build-sidecar.mjs - - - name: Bundle native dependencies - run: node scripts/bundle-native-deps.mjs - - - name: Stage sidecar dependencies - run: node scripts/stage-sidecar-deps.mjs - - - name: Build frontend - run: cd apps/web && npx vite build - - - name: Build Tauri (macOS ${{ matrix.target }}) - # See verify-windows note: use the app-local lockfile-pinned CLI. - # Built per-arch — universal is rejected by the bundle scripts - # (per-arch native modules), matching release.yml. - run: cd app && node node_modules/@tauri-apps/cli/tauri.js build --target ${{ matrix.target }} --bundles ${{ matrix.bundles }} - env: - TAURI_PRIVATE_KEY: '' - TAURI_KEY_PASSWORD: '' - - - name: Upload macOS artifacts - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - with: - name: waggle-macos-${{ matrix.target }}-${{ github.sha }} - path: ${{ matrix.artifact_path }} - if-no-files-found: error - retention-days: 7 diff --git a/app/package.json b/app/package.json index 52a2f04..72eb7e4 100644 --- a/app/package.json +++ b/app/package.json @@ -13,15 +13,11 @@ "tauri:build": "node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && node ../scripts/bundle-native-deps.mjs && node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build", "tauri:build:local": "node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && node ../scripts/bundle-native-deps.mjs && node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --debug", "tauri:build:win": "node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && node ../scripts/bundle-native-deps.mjs && node ../scripts/stage-sidecar-deps.mjs && node ../scripts/check-sidecar-resources.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --target x86_64-pc-windows-msvc", - "tauri:build:win:pilot-signed": "npm run tauri:sign:pilot:win:apply && npm run tauri:build:win -- --config src-tauri/tauri.build-override.conf.json", "tauri:build:mac": "npm run tauri:build:mac:arm64 && npm run tauri:build:mac:x64", "tauri:build:mac:arm64": "TARGET_ARCH=arm64 node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && TARGET_ARCH=arm64 node ../scripts/bundle-native-deps.mjs && TARGET_ARCH=arm64 node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --target aarch64-apple-darwin", "tauri:build:mac:x64": "TARGET_ARCH=x64 node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && TARGET_ARCH=x64 node ../scripts/bundle-native-deps.mjs && TARGET_ARCH=x64 node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --target x86_64-apple-darwin", - "tauri:dev": "npx tauri dev", - "tauri:sign:pilot:win:setup": "powershell -ExecutionPolicy Bypass -File scripts/sign-windows-pilot.ps1 -Mode Setup", - "tauri:sign:pilot:win:apply": "node scripts/apply-signing-config.mjs", - "tauri:sign:pilot:win:sign": "powershell -ExecutionPolicy Bypass -File scripts/sign-windows-pilot.ps1 -Mode Sign -ArtifactPath", - "tauri:sign:pilot:mac:adhoc": "bash scripts/sign-macos-adhoc.sh" + "tauri:build:linux": "node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && node ../scripts/bundle-native-deps.mjs && node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --target x86_64-unknown-linux-gnu", + "tauri:dev": "npx tauri dev" }, "dependencies": { "@base-ui/react": "^1.3.0", diff --git a/app/scripts/apply-signing-config.mjs b/app/scripts/apply-signing-config.mjs deleted file mode 100644 index b421a6e..0000000 --- a/app/scripts/apply-signing-config.mjs +++ /dev/null @@ -1,145 +0,0 @@ -#!/usr/bin/env node -/** - * apply-signing-config.mjs — write the captured Windows code-signing thumbprint - * into app/src-tauri/tauri.build-override.conf.json. - * - * Read by `npm run tauri:sign:pilot:win:apply`. Idempotent: re-running with the - * same thumbprint produces an identical file. Updating the cert (rotation) is - * handled by re-running the upstream cert-gen script + this CLI. - * - * Pure logic lives in `signing-config.ts`; this is the thin file-I/O wrapper. - * - * Reference: docs/code-signing-pilot-and-launch.md §1.1 - */ - -import { readFileSync, writeFileSync, existsSync } from 'node:fs'; -import { resolve, dirname } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -// The pure helpers below mirror the certificate-store helpers in -// app/scripts/signing-config.ts so this pilot CLI has zero TS-loader dependency -// at runtime. Keep parseThumbprintString and addWindowsSigningToOverride in -// lockstep with the canonical TypeScript implementation. - -const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)); -const APP_DIR = resolve(SCRIPT_DIR, '..'); -const REPO_ROOT = resolve(APP_DIR, '..'); - -const OVERRIDE_PATH = resolve( - APP_DIR, - 'src-tauri', - 'tauri.build-override.conf.json', -); -const THUMBPRINT_PATH = resolve(APP_DIR, 'src-tauri', '.thumbprint.txt'); -const DEFAULT_DIGEST_ALGORITHM = 'sha256'; -const DEFAULT_TIMESTAMP_URL = 'http://timestamp.digicert.com'; -const THUMBPRINT_LENGTH = 40; -const HEX_PATTERN = /^[0-9A-F]+$/; -const WINDOWS_SIGNING_MODE = - process.env.WAGGLE_WINDOWS_SIGNING_MODE ?? 'certificate-store'; - -function parseThumbprintString(raw) { - if (!raw || raw.trim().length === 0) { - throw new Error('Thumbprint is empty — cert generation may have failed.'); - } - const compact = raw.replace(/\s+/g, '').toUpperCase(); - if (compact.length !== THUMBPRINT_LENGTH || !HEX_PATTERN.test(compact)) { - throw new Error( - `Thumbprint must be 40 hex characters; got ${compact.length} chars (sample: "${compact.slice(0, 16)}...").`, - ); - } - return compact; -} - -function addWindowsSigningToOverride(config, thumbprint, options = {}) { - const normalisedThumbprint = parseThumbprintString(thumbprint); - const digestAlgorithm = options.digestAlgorithm ?? DEFAULT_DIGEST_ALGORITHM; - const timestampUrl = options.timestampUrl ?? DEFAULT_TIMESTAMP_URL; - - const existingBundle = config.bundle ?? {}; - const existingWindows = existingBundle.windows ?? {}; - const nonCustomCommandWindows = { ...existingWindows }; - delete nonCustomCommandWindows.signCommand; - - return { - ...config, - bundle: { - ...existingBundle, - windows: { - ...nonCustomCommandWindows, - certificateThumbprint: normalisedThumbprint, - digestAlgorithm, - timestampUrl, - }, - }, - }; -} - -// ─── Main ─────────────────────────────────────────────────────────────────── - -function main() { - if (!['certificate-store', 'artifact-signing'].includes(WINDOWS_SIGNING_MODE)) { - console.error( - `[apply-signing-config] unsupported WAGGLE_WINDOWS_SIGNING_MODE: ${WINDOWS_SIGNING_MODE}`, - ); - process.exit(1); - } - if (WINDOWS_SIGNING_MODE === 'artifact-signing') { - console.error( - '[apply-signing-config] Azure Artifact Signing is hosted-only. ' - + 'Run the protected GitHub-hosted release workflow; this local helper cannot issue ' - + 'the immutable build receipt, protected OIDC identity, session manifest, or callback ledger.', - ); - process.exit(1); - } - if (!existsSync(THUMBPRINT_PATH)) { - console.error( - `[apply-signing-config] thumbprint file missing: ${THUMBPRINT_PATH}`, - ); - console.error( - '[apply-signing-config] Run `npm run tauri:sign:pilot:win:setup` (or app/scripts/sign-windows-pilot.ps1 -Mode Setup) first.', - ); - process.exit(1); - } - if (!existsSync(OVERRIDE_PATH)) { - console.error( - `[apply-signing-config] override config missing: ${OVERRIDE_PATH}`, - ); - process.exit(1); - } - - const overrideRaw = readFileSync(OVERRIDE_PATH, 'utf8'); - - let override; - try { - override = JSON.parse(overrideRaw); - } catch (err) { - console.error( - `[apply-signing-config] failed to parse ${OVERRIDE_PATH}: ${err instanceof Error ? err.message : String(err)}`, - ); - process.exit(1); - } - - let updated; - try { - const rawThumbprint = readFileSync(THUMBPRINT_PATH, 'utf8'); - updated = addWindowsSigningToOverride(override, rawThumbprint); - } catch (err) { - console.error( - `[apply-signing-config] failed: ${err instanceof Error ? err.message : String(err)}`, - ); - process.exit(1); - } - - // Format with 2-space indent + trailing newline (matches existing JSON files - // in the repo). Idempotent: same input → same output bytes. - const serialised = JSON.stringify(updated, null, 2) + '\n'; - writeFileSync(OVERRIDE_PATH, serialised, 'utf8'); - - const relativePath = OVERRIDE_PATH.replace(REPO_ROOT, '').replace(/^\\/, ''); - const signingDescription = - `thumbprint ${updated.bundle.windows.certificateThumbprint.slice(0, 8)}...`; - console.log(`[apply-signing-config] wrote ${signingDescription} to ${relativePath}`); -} - -main(); diff --git a/app/scripts/new-windows-signing-handoff.ps1 b/app/scripts/new-windows-signing-handoff.ps1 deleted file mode 100644 index 5e32a45..0000000 --- a/app/scripts/new-windows-signing-handoff.ps1 +++ /dev/null @@ -1,1059 +0,0 @@ -[CmdletBinding()] -param( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$SourceTargetRoot, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$DestinationRoot, - - [string]$GitPath = 'C:\Program Files\Git\cmd\git.exe', - - [string]$NodePath = '' -) - -Set-StrictMode -Version Latest -$ErrorActionPreference = 'Stop' - -$ApprovedRepository = 'marolinik/waggle-os' -$TargetTriple = 'x86_64-pc-windows-msvc' -$ExpectedNodeVersion = 'v22.23.2' -$ExpectedNsisFileCount = 442 -$ExpectedNsisInventorySha256 = '1FC822D1A183552A80ADEA01B0BF456F462B90518256EF1FE9EDFA22D76CD85A' -$OpenJsPublisher = 'CN=OpenJS Foundation, O=OpenJS Foundation, L=San Francisco, S=California, C=US' -$GitPublisher = 'CN=Johannes Schindelin, O=Johannes Schindelin, S=Nordrhein-Westfalen, C=DE' -$CodeSigningOid = '1.3.6.1.5.5.7.3.3' -$MaxTargetFileCount = 18000 -$MaxTargetBytes = 768MB -$MaxResourceFileCount = 17500 -$MaxResourceBytes = 600MB - -function Get-HandoffHex { - param([Parameter(Mandatory = $true)] [byte[]]$Bytes) - - return ([BitConverter]::ToString($Bytes) -replace '-', '') -} - -function Get-HandoffBytesSha256 { - param([Parameter(Mandatory = $true)] [byte[]]$Bytes) - - $algorithm = [Security.Cryptography.SHA256]::Create() - try { - return Get-HandoffHex ($algorithm.ComputeHash($Bytes)) - } finally { - $algorithm.Dispose() - } -} - -function Get-HandoffNormalizedGitBlobSha1 { - param([Parameter(Mandatory = $true)] [string]$Path) - - $strictUtf8 = [Text.UTF8Encoding]::new($false, $true) - try { - $text = $strictUtf8.GetString([IO.File]::ReadAllBytes($Path)) - } catch { - throw 'Tracked handoff input is not canonical UTF-8 text.' - } - if ($text.Length -gt 0 -and $text[0] -eq [char]0xFEFF) { - throw 'Tracked handoff input contains a UTF-8 BOM.' - } - $normalized = $text.Replace("`r`n", "`n") - if ($normalized.Contains("`r")) { - throw 'Tracked handoff input contains a non-canonical carriage return.' - } - $contentBytes = [Text.UTF8Encoding]::new($false).GetBytes($normalized) - $headerBytes = [Text.Encoding]::ASCII.GetBytes("blob $($contentBytes.Length)`0") - $algorithm = [Security.Cryptography.SHA1]::Create() - try { - return Get-HandoffHex ($algorithm.ComputeHash([byte[]]($headerBytes + $contentBytes))) - } finally { - $algorithm.Dispose() - } -} - -function Get-HandoffFileSha256 { - param([Parameter(Mandatory = $true)] [string]$Path) - - $stream = [IO.File]::Open( - $Path, - [IO.FileMode]::Open, - [IO.FileAccess]::Read, - [IO.FileShare]::Read - ) - $algorithm = [Security.Cryptography.SHA256]::Create() - try { - return Get-HandoffHex ($algorithm.ComputeHash($stream)) - } finally { - $algorithm.Dispose() - $stream.Dispose() - } -} - -function Assert-HandoffSignedExecutable { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$ExpectedPublisher, - [Parameter(Mandatory = $true)] [string]$Label - ) - - $signature = Get-AuthenticodeSignature -LiteralPath $Path - if ($signature.Status -ne [Management.Automation.SignatureStatus]::Valid -or - [string]$signature.SignatureType -cne 'Authenticode' -or - $null -eq $signature.SignerCertificate -or - -not [string]::Equals( - [string]$signature.SignerCertificate.Subject, - $ExpectedPublisher, - [StringComparison]::Ordinal - )) { - throw "$Label does not have the approved Authenticode publisher." - } - $hasCodeSigningEku = @( - $signature.SignerCertificate.Extensions | - Where-Object { - $_ -is [Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension] - } | - ForEach-Object { $_.EnhancedKeyUsages } | - Where-Object { $_.Value -eq $CodeSigningOid } - ).Count -gt 0 - if (-not $hasCodeSigningEku) { throw "$Label lacks the Code Signing EKU." } -} - -function Get-HandoffTrustedPath { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$Label, - [ValidateSet('Leaf', 'Container')] [string]$PathType = 'Leaf', - [switch]$AllowHardLink - ) - - if ([string]::IsNullOrWhiteSpace($Path) -or - $Path -match '[\x00-\x1F\x7F]' -or - $Path -notmatch '^[A-Za-z]:[\\/]' -or - $Path -match '^[\\/]{2}' -or - $Path.Substring(2) -match ':' -or - $Path -match '(^|[\\/])\.\.?(?:[\\/]|$)' -or - @($Path -split '[\\/]' | Where-Object { $_ -match '[. ]$' }).Count -ne 0) { - throw "$Label must use a safe, fully qualified local Windows path." - } - - $fullPath = [IO.Path]::GetFullPath($Path) - $testPathType = if ($PathType -ceq 'Leaf') { 'Leaf' } else { 'Container' } - if (-not (Test-Path -LiteralPath $fullPath -PathType $testPathType)) { - throw "$Label does not exist as a $($PathType.ToLowerInvariant()): $fullPath" - } - - $root = [IO.Path]::GetPathRoot($fullPath) - $relative = $fullPath.Substring($root.Length) - $current = $root - foreach ($component in @($relative -split '[\\/]' | Where-Object { $_ })) { - $current = Join-Path $current $component - $item = Get-Item -LiteralPath $current -Force - if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { - throw "$Label traverses a reparse point: $current" - } - $linkTypeProperty = $item.PSObject.Properties['LinkType'] - if ($null -eq $linkTypeProperty) { - throw "$Label filesystem provider does not expose link topology." - } - $linkType = [string]$linkTypeProperty.Value - if (-not [string]::IsNullOrEmpty($linkType) -and - -not ($AllowHardLink -and $linkType -ceq 'HardLink')) { - throw "$Label traverses an unsupported linked filesystem object: $current" - } - } - - $resolved = (Resolve-Path -LiteralPath $fullPath).ProviderPath - if (-not [string]::Equals( - [IO.Path]::GetFullPath($resolved), - $fullPath, - [StringComparison]::OrdinalIgnoreCase - )) { - throw "$Label resolves to an unexpected path." - } - return $fullPath -} - -function Get-HandoffContainedRelativePath { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$Root - ) - - $fullPath = [IO.Path]::GetFullPath($Path) - $fullRoot = [IO.Path]::GetFullPath($Root).TrimEnd('\') - $prefix = "$fullRoot\" - if (-not $fullPath.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { - return $null - } - return $fullPath.Substring($prefix.Length).Replace('/', '\') -} - -function Assert-HandoffCanonicalRelativePath { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$Label - ) - - if ([string]::IsNullOrWhiteSpace($Path) -or - $Path -match '[\x00-\x1F\x7F]' -or - $Path -match '(^|[\\/])\.\.?(?:[\\/]|$)' -or - [IO.Path]::IsPathRooted($Path) -or - $Path.Contains('/') -or - $Path.Contains(':') -or - @($Path -split '\\' | Where-Object { $_ -match '[. ]$' }).Count -ne 0) { - throw "$Label contains an unsafe or non-canonical relative path." - } -} - -function Get-HandoffTreeFiles { - param( - [Parameter(Mandatory = $true)] [string]$Root, - [Parameter(Mandatory = $true)] [string]$Label, - [switch]$AllowCargoHardLinkPair, - [string]$CargoReleaseRoot = '', - [int]$MaxFileCount = [int]::MaxValue, - [long]$MaxBytes = [long]::MaxValue, - [int]$MaxDirectoryCount = [int]::MaxValue - ) - - if ($MaxFileCount -lt 1 -or $MaxBytes -lt 1 -or $MaxDirectoryCount -lt 1) { - throw "$Label inventory bound is invalid." - } - $trustedRoot = Get-HandoffTrustedPath $Root $Label 'Container' - $pending = [Collections.Generic.Queue[string]]::new() - $files = [Collections.Generic.List[object]]::new() - $exactPaths = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) - $foldedPaths = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) - $totalBytes = [long]0 - $directoryCount = 1 - $pending.Enqueue($trustedRoot) - while ($pending.Count -gt 0) { - $directory = $pending.Dequeue() - $enumerator = [IO.Directory]::EnumerateFileSystemEntries($directory).GetEnumerator() - try { - while ($enumerator.MoveNext()) { - $item = Get-Item -LiteralPath ([string]$enumerator.Current) -Force - if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { - throw "$Label contains a reparse point: $($item.FullName)" - } - $linkTypeProperty = $item.PSObject.Properties['LinkType'] - if ($null -eq $linkTypeProperty) { - throw "$Label filesystem provider does not expose link topology." - } - $linkType = [string]$linkTypeProperty.Value - if ($item.PSIsContainer) { - if (-not [string]::IsNullOrEmpty($linkType)) { - throw "$Label contains a linked directory." - } - $childDirectory = [IO.Path]::GetFullPath($item.FullName) - if ($null -eq (Get-HandoffContainedRelativePath $childDirectory $trustedRoot)) { - throw "$Label directory escaped its root." - } - $directoryCount++ - $directoryRelative = Get-HandoffContainedRelativePath $childDirectory $trustedRoot - if ($directoryCount -gt $MaxDirectoryCount -or - @($directoryRelative -split '\\').Count -gt 32) { - throw "$Label exceeds its deterministic directory-count or depth bound." - } - $pending.Enqueue($childDirectory) - continue - } - - $path = [IO.Path]::GetFullPath($item.FullName) - $relative = Get-HandoffContainedRelativePath $path $trustedRoot - if ($null -eq $relative) { throw "$Label file escaped its root." } - Assert-HandoffCanonicalRelativePath $relative $Label - if (-not $exactPaths.Add($relative) -or -not $foldedPaths.Add($relative)) { - throw "$Label contains a duplicate path or case-insensitive collision." - } - $streams = @(Get-Item -LiteralPath $path -Stream * -ErrorAction Stop) - if ($streams.Count -ne 1 -or [string]$streams[0].Stream -cne ':$DATA') { - throw "$Label contains an alternate data stream." - } - - if (-not [string]::IsNullOrEmpty($linkType)) { - if (-not $AllowCargoHardLinkPair -or $linkType -cne 'HardLink') { - throw "$Label contains an unsupported hard link." - } - $releaseRoot = [IO.Path]::GetFullPath($CargoReleaseRoot) - $main = [IO.Path]::GetFullPath((Join-Path $releaseRoot 'waggle.exe')) - $dependency = [IO.Path]::GetFullPath((Join-Path $releaseRoot 'deps\waggle.exe')) - if (-not [string]::Equals($path, $main, [StringComparison]::OrdinalIgnoreCase) -and - -not [string]::Equals($path, $dependency, [StringComparison]::OrdinalIgnoreCase)) { - throw "$Label permits only the exact Cargo executable hard-link pair." - } - } - $fileSize = [long]$item.Length - if ($files.Count -ge $MaxFileCount -or $fileSize -lt 0 -or - $totalBytes -gt $MaxBytes - $fileSize) { - throw "$Label exceeds its deterministic file-count or byte bound." - } - $totalBytes += $fileSize - $files.Add([pscustomobject]@{ FullName = $path; RelativePath = $relative }) - } - } finally { - if ($enumerator -is [IDisposable]) { $enumerator.Dispose() } - } - } - return @($files) -} - -function Assert-HandoffMappingBounds { - param( - [Parameter(Mandatory = $true)] [object[]]$Mappings, - [Parameter(Mandatory = $true)] [int]$MaxFileCount, - [Parameter(Mandatory = $true)] [long]$MaxBytes, - [Parameter(Mandatory = $true)] [string]$Label - ) - - if ($MaxFileCount -lt 1 -or $MaxBytes -lt 1 -or $Mappings.Count -gt $MaxFileCount) { - throw "$Label exceeds its deterministic file-count or byte bound." - } - $totalBytes = [long]0 - foreach ($mapping in $Mappings) { - $size = [long](Get-Item -LiteralPath ([string]$mapping.Source) -Force).Length - if ($size -lt 0 -or $totalBytes -gt $MaxBytes - $size) { - throw "$Label exceeds its deterministic file-count or byte bound." - } - $totalBytes += $size - } - return $totalBytes -} - -function Assert-HandoffDefaultIndexFlags { - param( - [Parameter(Mandatory = $true)] [string]$Git, - [Parameter(Mandatory = $true)] [string]$RepoRoot - ) - - foreach ($flag in @('-v', '-f')) { - $entries = @(& $Git -C $RepoRoot ls-files $flag --full-name) - if ($LASTEXITCODE -ne 0 -or $entries.Count -lt 100 -or - @($entries | Where-Object { [string]$_ -notmatch '^H [^\x00-\x1F\x7F]+$' }).Count -ne 0) { - throw 'Repository index contains assume-unchanged, skip-worktree, fsmonitor-valid, or non-default tracked state.' - } - } - $fsmonitor = @(& $Git -C $RepoRoot config --get-all core.fsmonitor) - $fsmonitorExitCode = $LASTEXITCODE - if (($fsmonitorExitCode -ne 0 -and $fsmonitorExitCode -ne 1) -or - $fsmonitor.Count -ne 0) { - throw 'Repository must not enable core.fsmonitor for the signing handoff.' - } -} - -function Assert-HandoffRepositoryState { - param( - [Parameter(Mandatory = $true)] [string]$Git, - [Parameter(Mandatory = $true)] [string]$RepoRoot, - [Parameter(Mandatory = $true)] [string]$Revision, - [Parameter(Mandatory = $true)] [string]$AppVersion, - [Parameter(Mandatory = $true)] [string[]]$TrackedPaths - ) - - $actualRoot = [string](& $Git -C $RepoRoot rev-parse --show-toplevel) - $head = [string](& $Git -C $RepoRoot rev-parse --verify HEAD) - $tagCommit = [string](& $Git -C $RepoRoot rev-parse --verify "refs/tags/v$AppVersion`^{commit}") - $status = @(& $Git -C $RepoRoot status --porcelain=v1 --untracked-files=all) - if ($LASTEXITCODE -ne 0 -or - -not [string]::Equals( - [IO.Path]::GetFullPath($actualRoot), - [IO.Path]::GetFullPath($RepoRoot), - [StringComparison]::OrdinalIgnoreCase - ) -or $head -cne $Revision -or $tagCommit -cne $Revision -or - $status.Count -ne 0) { - throw 'Windows signing handoff requires the clean exact tagged GITHUB_SHA.' - } - Assert-HandoffDefaultIndexFlags $Git $RepoRoot - foreach ($trackedPath in $TrackedPaths) { - & $Git -C $RepoRoot ls-files --error-unmatch -- $trackedPath | Out-Null - if ($LASTEXITCODE -ne 0) { - throw "Windows signing handoff input is not tracked: $trackedPath" - } - $expectedBlob = [string](& $Git -C $RepoRoot rev-parse --verify "HEAD:$trackedPath") - $actualBlob = Get-HandoffNormalizedGitBlobSha1 (Join-Path $RepoRoot $trackedPath) - if ($LASTEXITCODE -ne 0 -or $expectedBlob -notmatch '^[0-9a-f]{40}$' -or - -not [string]::Equals( - $expectedBlob, - $actualBlob, - [StringComparison]::OrdinalIgnoreCase - )) { - throw "Tracked handoff input differs from its exact HEAD blob: $trackedPath" - } - } -} - -function Get-HandoffHardLinkPaths { - param([Parameter(Mandatory = $true)] [string]$Path) - - $fsutil = Get-HandoffTrustedPath 'C:\Windows\System32\fsutil.exe' 'fsutil' -AllowHardLink - $raw = @(& $fsutil hardlink list $Path) - if ($LASTEXITCODE -ne 0 -or $raw.Count -ne 2) { - throw 'Cargo executable must have exactly two hard-link paths.' - } - $volumeRoot = [IO.Path]::GetPathRoot($Path).TrimEnd('\') - return @($raw | ForEach-Object { - if ([string]$_ -notmatch '^\\[^\\]') { - throw 'fsutil returned a non-canonical hard-link path.' - } - [IO.Path]::GetFullPath($volumeRoot + [string]$_) - }) -} - -function Assert-HandoffCargoPair { - param( - [Parameter(Mandatory = $true)] [string]$ReleaseRoot, - [Parameter(Mandatory = $true)] [string]$Label - ) - - $release = Get-HandoffTrustedPath $ReleaseRoot "$Label release root" 'Container' - $main = Get-HandoffTrustedPath (Join-Path $release 'waggle.exe') "$Label main" -AllowHardLink - $dependency = Get-HandoffTrustedPath ` - (Join-Path $release 'deps\waggle.exe') "$Label dependency" -AllowHardLink - $links = @(Get-HandoffHardLinkPaths $main) - $set = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) - foreach ($link in $links) { [void]$set.Add($link) } - if ($set.Count -ne 2 -or -not $set.Contains($main) -or -not $set.Contains($dependency) -or - (Get-HandoffFileSha256 $main) -cne (Get-HandoffFileSha256 $dependency)) { - throw "$Label does not have the exact equal-byte release\waggle.exe and release\deps\waggle.exe hard-link pair." - } -} - -function New-HandoffInventory { - param( - [Parameter(Mandatory = $true)] [object[]]$Mappings, - [Parameter(Mandatory = $true)] [string]$Label - ) - - $entries = [Collections.Generic.List[object]]::new() - $exactPaths = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) - $foldedPaths = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) - foreach ($mapping in $Mappings) { - $relative = [string]$mapping.Path - Assert-HandoffCanonicalRelativePath $relative $Label - if (-not $exactPaths.Add($relative) -or -not $foldedPaths.Add($relative)) { - throw "$Label contains a duplicate path or case-insensitive collision." - } - $source = [IO.Path]::GetFullPath([string]$mapping.Source) - if (-not (Test-Path -LiteralPath $source -PathType Leaf)) { - throw "$Label source file is missing." - } - $item = Get-Item -LiteralPath $source -Force - if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { - throw "$Label source file became a reparse point." - } - $linkTypeProperty = $item.PSObject.Properties['LinkType'] - if ($null -eq $linkTypeProperty -or - -not ([string]::IsNullOrEmpty([string]$linkTypeProperty.Value) -or - [string]$linkTypeProperty.Value -ceq 'HardLink')) { - throw "$Label source file has an unsupported link topology." - } - $streams = @(Get-Item -LiteralPath $source -Stream * -ErrorAction Stop) - if ($streams.Count -ne 1 -or [string]$streams[0].Stream -cne ':$DATA') { - throw "$Label source file contains an alternate data stream." - } - $lock = [IO.File]::Open( - $source, - [IO.FileMode]::Open, - [IO.FileAccess]::Read, - [IO.FileShare]::Read - ) - try { - $entries.Add([pscustomobject][ordered]@{ - path = $relative - size = [long]$item.Length - sha256 = Get-HandoffFileSha256 $source - }) - } finally { - $lock.Dispose() - } - } - $sorted = @($entries) - [Array]::Sort($sorted, [Comparison[object]]{ - param($left, $right) - return [StringComparer]::Ordinal.Compare([string]$left.path, [string]$right.path) - }) - $canonical = @($sorted | ForEach-Object { - [ordered]@{ - path = [string]$_.path - size = [long]$_.size - sha256 = ([string]$_.sha256).ToUpperInvariant() - } - }) | ConvertTo-Json -Depth 8 -Compress - return [pscustomobject][ordered]@{ - entries = $sorted - sha256 = Get-HandoffBytesSha256 ([Text.Encoding]::UTF8.GetBytes($canonical)) - } -} - -function Assert-HandoffInventoriesEqual { - param( - [Parameter(Mandatory = $true)] [object]$Expected, - [Parameter(Mandatory = $true)] [object]$Actual, - [Parameter(Mandatory = $true)] [string]$Label - ) - - if (-not [string]::Equals( - [string]$Expected.sha256, - [string]$Actual.sha256, - [StringComparison]::OrdinalIgnoreCase - ) -or @($Expected.entries).Count -ne @($Actual.entries).Count) { - throw "$Label inventory changed during handoff staging." - } - for ($index = 0; $index -lt @($Expected.entries).Count; $index++) { - $left = @($Expected.entries)[$index] - $right = @($Actual.entries)[$index] - if ([string]$left.path -cne [string]$right.path -or - [long]$left.size -ne [long]$right.size -or - -not [string]::Equals( - [string]$left.sha256, - [string]$right.sha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw "$Label inventory changed during handoff staging." - } - } -} - -function Copy-HandoffMappings { - param( - [Parameter(Mandatory = $true)] [object[]]$Mappings, - [Parameter(Mandatory = $true)] [string]$Root, - [string]$SkipRelativePath = '' - ) - - foreach ($mapping in $Mappings) { - $relative = [string]$mapping.Path - if (-not [string]::IsNullOrEmpty($SkipRelativePath) -and - $relative -ceq $SkipRelativePath) { - continue - } - $destination = Join-Path $Root $relative - [IO.Directory]::CreateDirectory((Split-Path $destination -Parent)) | Out-Null - if (Test-Path -LiteralPath $destination) { - throw 'Handoff destination contains an unexpected file or directory collision.' - } - [IO.File]::Copy([string]$mapping.Source, $destination, $false) - } -} - -function Get-HandoffMappings { - param( - [Parameter(Mandatory = $true)] [string]$ReleaseRoot, - [Parameter(Mandatory = $true)] [string]$ResourcesRoot - ) - - $mappings = [Collections.Generic.List[object]]::new() - foreach ($relative in @('waggle.exe', 'deps\waggle.exe')) { - $mappings.Add([pscustomobject]@{ - Source = Join-Path $ReleaseRoot $relative - Path = "$TargetTriple\release\$relative" - }) - } - foreach ($treeSpec in @( - [pscustomobject]@{ - Root = Join-Path $ReleaseRoot 'nsis' - Prefix = "$TargetTriple\release\nsis" - }, - [pscustomobject]@{ - Root = Join-Path $ReleaseRoot 'bundle\nsis' - Prefix = "$TargetTriple\release\bundle\nsis" - } - )) { - $treeMaxCount = if ([string]$treeSpec.Prefix -like '*\bundle\nsis') { 1 } else { 128 } - $treeMaxBytes = if ([string]$treeSpec.Prefix -like '*\bundle\nsis') { 256MB } else { 64MB } - foreach ($file in @(Get-HandoffTreeFiles ` - ([string]$treeSpec.Root) 'Unsigned NSIS output' ` - -MaxFileCount $treeMaxCount -MaxBytes $treeMaxBytes ` - -MaxDirectoryCount 16)) { - $mappings.Add([pscustomobject]@{ - Source = [string]$file.FullName - Path = "$([string]$treeSpec.Prefix)\$([string]$file.RelativePath)" - }) - } - } - foreach ($file in @(Get-HandoffTreeFiles ` - $ResourcesRoot 'Tauri sidecar resources' ` - -MaxFileCount $MaxResourceFileCount -MaxBytes $MaxResourceBytes ` - -MaxDirectoryCount 2400)) { - $mappings.Add([pscustomobject]@{ - Source = [string]$file.FullName - Path = "resources\$([string]$file.RelativePath)" - }) - } - return @($mappings) -} - -function Get-HandoffResourceMappings { - param([Parameter(Mandatory = $true)] [object[]]$TargetMappings) - - return @($TargetMappings | Where-Object { - ([string]$_.Path).StartsWith('resources\', [StringComparison]::Ordinal) - } | ForEach-Object { - [pscustomobject]@{ - Source = [string]$_.Source - Path = ([string]$_.Path).Substring('resources\'.Length) - } - }) -} - -function Get-HandoffTreeMappings { - param( - [Parameter(Mandatory = $true)] [string]$Root, - [Parameter(Mandatory = $true)] [string]$Label, - [switch]$AllowCargoHardLinkPair, - [string]$CargoReleaseRoot = '', - [int]$MaxFileCount = [int]::MaxValue, - [long]$MaxBytes = [long]::MaxValue, - [int]$MaxDirectoryCount = [int]::MaxValue - ) - - return @(Get-HandoffTreeFiles ` - $Root $Label ` - -AllowCargoHardLinkPair:$AllowCargoHardLinkPair ` - -CargoReleaseRoot $CargoReleaseRoot ` - -MaxFileCount $MaxFileCount -MaxBytes $MaxBytes ` - -MaxDirectoryCount $MaxDirectoryCount | ForEach-Object { - [pscustomobject]@{ Source = [string]$_.FullName; Path = [string]$_.RelativePath } - }) -} - -function Write-HandoffJsonNoBom { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [object]$Value - ) - - [IO.File]::WriteAllText( - $Path, - ($Value | ConvertTo-Json -Depth 32), - [Text.UTF8Encoding]::new($false) - ) -} - -function Write-HandoffOutput { - param( - [Parameter(Mandatory = $true)] [string]$Name, - [Parameter(Mandatory = $true)] [string]$Value - ) - - if ($Name -notmatch '^[a-z_]+$' -or $Value -match '[\r\n\x00]') { - throw 'GitHub output contains an unsafe name or value.' - } - $line = "$Name=$Value" - Write-Host $line - $outputPath = [Environment]::GetEnvironmentVariable('GITHUB_OUTPUT') - if (-not [string]::IsNullOrWhiteSpace($outputPath)) { - $trustedOutput = Get-HandoffTrustedPath $outputPath 'GITHUB_OUTPUT' - [IO.File]::AppendAllText( - $trustedOutput, - $line + [Environment]::NewLine, - [Text.UTF8Encoding]::new($false) - ) - } -} - -function New-HandoffBuildReceipt { - param( - [Parameter(Mandatory = $true)] [string]$SourceRevision, - [Parameter(Mandatory = $true)] [object]$TargetInventory, - [Parameter(Mandatory = $true)] [object]$ResourcesInventory, - [Parameter(Mandatory = $true)] [object]$NsisInventory, - [Parameter(Mandatory = $true)] [string]$CheckerSha256 - ) - - if ($SourceRevision -notmatch '^[0-9a-f]{40}$' -or - $CheckerSha256 -notmatch '^[0-9A-F]{64}$') { - throw 'Handoff receipt requires an exact source revision and checker SHA-256.' - } - return [ordered]@{ - schemaVersion = 1 - repository = $ApprovedRepository - sourceRevision = $SourceRevision - targetTriple = $TargetTriple - targetInventory = $TargetInventory - resourcesInventory = $ResourcesInventory - nsisInventory = $NsisInventory - checker = [ordered]@{ - exitCode = 0 - sha256 = $CheckerSha256 - } - } -} - -function Invoke-HandoffDestinationTransaction { - param( - [Parameter(Mandatory = $true)] [string]$DestinationRoot, - [Parameter(Mandatory = $true)] [string]$DestinationParentRoot, - [Parameter(Mandatory = $true)] [object[]]$TargetMappings, - [Parameter(Mandatory = $true)] [object[]]$ResourceMappings, - [Parameter(Mandatory = $true)] [object[]]$NsisMappings, - [Parameter(Mandatory = $true)] [object]$ExpectedTargetInventory, - [Parameter(Mandatory = $true)] [object]$ExpectedResourcesInventory, - [Parameter(Mandatory = $true)] [object]$ExpectedNsisInventory, - [Parameter(Mandatory = $true)] [string]$SourceRevision, - [Parameter(Mandatory = $true)] [string]$CheckerSha256, - [scriptblock]$FinalSourceAssertion = {}, - [int]$TargetFileCountLimit = $MaxTargetFileCount, - [long]$TargetByteLimit = $MaxTargetBytes, - [int]$ResourceFileCountLimit = $MaxResourceFileCount, - [long]$ResourceByteLimit = $MaxResourceBytes, - [int]$NsisFileCountLimit = $ExpectedNsisFileCount, - [long]$NsisByteLimit = 16MB - ) - - $destinationParent = Get-HandoffTrustedPath ` - $DestinationParentRoot 'Handoff destination parent' 'Container' - if ([string]::IsNullOrWhiteSpace($DestinationRoot) -or - -not [IO.Path]::IsPathRooted($DestinationRoot) -or - $DestinationRoot -match '[\x00-\x1F\x7F]' -or - $DestinationRoot -match '(^|[\\/])\.\.?(?:[\\/]|$)') { - throw 'DestinationRoot must be a safe, fully qualified local Windows path.' - } - $destination = [IO.Path]::GetFullPath($DestinationRoot).TrimEnd('\') - if (-not [string]::Equals( - (Split-Path $destination -Parent), - $destinationParent.TrimEnd('\'), - [StringComparison]::OrdinalIgnoreCase - ) -or (Split-Path $destination -Leaf) -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]*$' -or - (Test-Path -LiteralPath $destination)) { - throw 'DestinationRoot must be an absent direct child of its trusted parent.' - } - - [void](Assert-HandoffMappingBounds ` - $TargetMappings $TargetFileCountLimit $TargetByteLimit 'Hosted target inventory') - [void](Assert-HandoffMappingBounds ` - $ResourceMappings $ResourceFileCountLimit $ResourceByteLimit ` - 'Hosted resources inventory') - [void](Assert-HandoffMappingBounds ` - $NsisMappings $NsisFileCountLimit $NsisByteLimit 'Hosted NSIS inventory') - - $prebuiltRoot = Join-Path $destination 'prebuilt' - $stagedNsisRoot = Join-Path $destination 'nsis-toolchain' - $receiptPath = Join-Path $destination 'build-receipt.json' - try { - [IO.Directory]::CreateDirectory($prebuiltRoot) | Out-Null - [IO.Directory]::CreateDirectory($stagedNsisRoot) | Out-Null - $mainRelative = "$TargetTriple\release\waggle.exe" - Copy-HandoffMappings $TargetMappings $prebuiltRoot $mainRelative - $stagedDependency = Join-Path ` - $prebuiltRoot "$TargetTriple\release\deps\waggle.exe" - $stagedMain = Join-Path $prebuiltRoot $mainRelative - New-Item -ItemType HardLink -Path $stagedMain -Target $stagedDependency | Out-Null - Copy-HandoffMappings $NsisMappings $stagedNsisRoot - - Assert-HandoffCargoPair ` - (Join-Path $prebuiltRoot "$TargetTriple\release") 'Staged Cargo output' - $stagedTargetMappings = @(Get-HandoffTreeMappings ` - $prebuiltRoot 'Staged prebuilt tree' -AllowCargoHardLinkPair ` - -CargoReleaseRoot (Join-Path $prebuiltRoot "$TargetTriple\release") ` - -MaxFileCount $TargetFileCountLimit -MaxBytes $TargetByteLimit ` - -MaxDirectoryCount 2500) - $stagedResourceMappings = @(Get-HandoffTreeMappings ` - (Join-Path $prebuiltRoot 'resources') 'Staged sidecar resources' ` - -MaxFileCount $ResourceFileCountLimit -MaxBytes $ResourceByteLimit ` - -MaxDirectoryCount 2400) - $stagedNsisMappings = @(Get-HandoffTreeMappings ` - $stagedNsisRoot 'Staged NSIS toolchain' ` - -MaxFileCount $NsisFileCountLimit -MaxBytes $NsisByteLimit ` - -MaxDirectoryCount 128) - & $FinalSourceAssertion $prebuiltRoot $stagedNsisRoot - $targetInventory = New-HandoffInventory $stagedTargetMappings 'Staged target inventory' - $resourcesInventory = New-HandoffInventory ` - $stagedResourceMappings 'Staged resources inventory' - $nsisInventory = New-HandoffInventory $stagedNsisMappings 'Staged NSIS inventory' - Assert-HandoffInventoriesEqual ` - $ExpectedTargetInventory $targetInventory 'Hosted target' - Assert-HandoffInventoriesEqual ` - $ExpectedResourcesInventory $resourcesInventory 'Hosted resources' - Assert-HandoffInventoriesEqual ` - $ExpectedNsisInventory $nsisInventory 'Hosted NSIS toolchain' - - & $FinalSourceAssertion $prebuiltRoot $stagedNsisRoot - $receipt = New-HandoffBuildReceipt ` - $SourceRevision $targetInventory $resourcesInventory $nsisInventory $CheckerSha256 - Write-HandoffJsonNoBom $receiptPath $receipt - $receiptSha256 = Get-HandoffFileSha256 $receiptPath - return [pscustomobject][ordered]@{ - ArtifactRoot = $destination - PrebuiltRoot = $prebuiltRoot - NsisToolchainRoot = $stagedNsisRoot - ReceiptPath = $receiptPath - ReceiptSha256 = $receiptSha256 - Receipt = $receipt - } - } catch { - if (Test-Path -LiteralPath $destination -PathType Container) { - [IO.Directory]::Delete($destination, $true) - } - throw - } -} - -function Invoke-WindowsSigningHandoff { - if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT -or - -not [Environment]::Is64BitProcess) { - throw 'Windows signing handoff requires 64-bit Windows.' - } - - $repoRoot = Get-HandoffTrustedPath ` - (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) ` - 'Repository root' 'Container' - $expectedBoundary = [ordered]@{ - GITHUB_ACTIONS = 'true' - RUNNER_ENVIRONMENT = 'github-hosted' - RUNNER_OS = 'Windows' - GITHUB_REPOSITORY = $ApprovedRepository - GITHUB_REF_TYPE = 'tag' - } - foreach ($entry in $expectedBoundary.GetEnumerator()) { - if ([Environment]::GetEnvironmentVariable([string]$entry.Key) -cne [string]$entry.Value) { - throw "Windows signing handoff requires exact $($entry.Key) boundary evidence." - } - } - $workspace = Get-HandoffTrustedPath ` - ([Environment]::GetEnvironmentVariable('GITHUB_WORKSPACE')) ` - 'GITHUB_WORKSPACE' 'Container' - if (-not [string]::Equals($workspace, $repoRoot, [StringComparison]::OrdinalIgnoreCase)) { - throw 'Windows signing handoff must run from the exact GitHub workspace.' - } - - $revision = [Environment]::GetEnvironmentVariable('GITHUB_SHA') - if ($revision -notmatch '^[0-9a-f]{40}$') { - throw 'GITHUB_SHA must be one exact lowercase commit revision.' - } - $expectedGitPath = 'C:\Program Files\Git\cmd\git.exe' - if (-not [string]::Equals( - [IO.Path]::GetFullPath($GitPath), - $expectedGitPath, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Git executable must use the canonical Git for Windows path.' - } - $git = Get-HandoffTrustedPath $expectedGitPath 'Git executable' -AllowHardLink - $runnerToolCache = Get-HandoffTrustedPath ` - ([Environment]::GetEnvironmentVariable('RUNNER_TOOL_CACHE')) ` - 'RUNNER_TOOL_CACHE' 'Container' - $expectedNodePath = Join-Path $runnerToolCache 'node\22.23.2\x64\node.exe' - if ([string]::IsNullOrWhiteSpace($NodePath)) { - $NodePath = $expectedNodePath - } elseif (-not [string]::Equals( - [IO.Path]::GetFullPath($NodePath), - [IO.Path]::GetFullPath($expectedNodePath), - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Node.js runtime must use the exact setup-node tool-cache path.' - } - $node = Get-HandoffTrustedPath $NodePath 'Node.js runtime' -AllowHardLink - $configPath = Get-HandoffTrustedPath ` - (Join-Path $repoRoot 'app\src-tauri\tauri.conf.json') 'Tauri config' - $checkerPath = Get-HandoffTrustedPath ` - (Join-Path $repoRoot 'scripts\check-sidecar-resources.mjs') ` - 'Sidecar resource checker' - - $toolLocks = [Collections.Generic.List[IDisposable]]::new() - try { - foreach ($toolPath in @($git, $node, $configPath, $checkerPath)) { - $toolLocks.Add([IO.File]::Open( - $toolPath, - [IO.FileMode]::Open, - [IO.FileAccess]::Read, - [IO.FileShare]::Read - )) - } - Assert-HandoffSignedExecutable $git $GitPublisher 'Git executable' - Assert-HandoffSignedExecutable $node $OpenJsPublisher 'Node.js runtime' - $nodeVersion = [string](& $node --version) - if ($LASTEXITCODE -ne 0 -or $nodeVersion -cne $ExpectedNodeVersion) { - throw "Node.js runtime must be exactly $ExpectedNodeVersion." - } - $appVersion = [string]( - Get-Content -Raw -LiteralPath $configPath | ConvertFrom-Json - ).version - if ($appVersion -notmatch '^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$' -or - [Environment]::GetEnvironmentVariable('GITHUB_REF_NAME') -cne "v$appVersion") { - throw 'Windows signing handoff requires the exact app-version release tag.' - } - - $trackedHandoffPaths = @( - 'app/scripts/new-windows-signing-handoff.ps1', - 'scripts/check-sidecar-resources.mjs', - 'app/src-tauri/tauri.conf.json' - ) - Assert-HandoffRepositoryState ` - $git $repoRoot $revision $appVersion $trackedHandoffPaths - - $expectedSourceTarget = [IO.Path]::GetFullPath( - (Join-Path $repoRoot 'app\src-tauri\target') - ) - $sourceTargetCandidate = if ([IO.Path]::IsPathRooted($SourceTargetRoot)) { - $SourceTargetRoot - } else { - Join-Path $repoRoot $SourceTargetRoot - } - $sourceTarget = Get-HandoffTrustedPath ` - $sourceTargetCandidate 'Unsigned Cargo target root' 'Container' - if (-not [string]::Equals( - $sourceTarget, - $expectedSourceTarget, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Unsigned Cargo target root must be the canonical repository target root.' - } - $sourceRelease = Get-HandoffTrustedPath ` - (Join-Path $sourceTarget "$TargetTriple\release") ` - 'Unsigned Cargo release root' 'Container' - Assert-HandoffCargoPair $sourceRelease 'Unsigned Cargo output' - $sourceNsis = Get-HandoffTrustedPath ` - (Join-Path $sourceRelease 'nsis') 'Generated NSIS input root' 'Container' - $sourceBundleNsis = Get-HandoffTrustedPath ` - (Join-Path $sourceRelease 'bundle\nsis') 'Generated NSIS bundle root' 'Container' - if (@(Get-HandoffTreeFiles ` - $sourceNsis 'Generated NSIS input root' ` - -MaxFileCount 128 -MaxBytes 64MB -MaxDirectoryCount 16).Count -eq 0 -or - @(Get-HandoffTreeFiles ` - $sourceBundleNsis 'Generated NSIS bundle root' ` - -MaxFileCount 1 -MaxBytes 256MB -MaxDirectoryCount 1).Count -eq 0) { - throw 'A completed full unsigned NSIS build is required before handoff.' - } - $expectedInstaller = Get-HandoffTrustedPath ` - (Join-Path $sourceBundleNsis "Waggle_${appVersion}_x64-setup.exe") ` - 'Unsigned NSIS installer' - $bundleFiles = @(Get-HandoffTreeFiles ` - $sourceBundleNsis 'Generated NSIS bundle root' ` - -MaxFileCount 1 -MaxBytes 256MB -MaxDirectoryCount 1) - if ($bundleFiles.Count -ne 1 -or - -not [string]::Equals( - [string]$bundleFiles[0].FullName, - $expectedInstaller, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Generated NSIS bundle root must contain only the exact versioned installer.' - } - foreach ($unsignedPath in @( - (Join-Path $sourceRelease 'waggle.exe'), - (Join-Path $sourceRelease 'deps\waggle.exe'), - $expectedInstaller - )) { - $signature = Get-AuthenticodeSignature -LiteralPath $unsignedPath - if ($signature.Status -ne [Management.Automation.SignatureStatus]::NotSigned -or - [string]$signature.SignatureType -cne 'None') { - throw 'Windows signing handoff accepts only an unsigned executable and NSIS installer.' - } - } - - $resourcesRoot = Get-HandoffTrustedPath ` - (Join-Path $repoRoot 'app\src-tauri\resources') ` - 'Tauri sidecar resources' 'Container' - $localAppData = [Environment]::GetFolderPath('LocalApplicationData') - $nsisToolchainRoot = Get-HandoffTrustedPath ` - (Join-Path $localAppData 'tauri\NSIS') 'Tauri NSIS toolchain' 'Container' - $checkerSha256 = Get-HandoffFileSha256 $checkerPath - - $targetMappings = @(Get-HandoffMappings $sourceRelease $resourcesRoot) - $resourceMappings = @(Get-HandoffResourceMappings $targetMappings) - $targetBytes = [long](Assert-HandoffMappingBounds ` - $targetMappings $MaxTargetFileCount $MaxTargetBytes 'Hosted target inventory') - [void](Assert-HandoffMappingBounds ` - $resourceMappings $MaxResourceFileCount $MaxResourceBytes 'Hosted resources inventory') - $nsisMappings = @(Get-HandoffTreeMappings ` - $nsisToolchainRoot 'Tauri NSIS toolchain' ` - -MaxFileCount $ExpectedNsisFileCount -MaxBytes 16MB -MaxDirectoryCount 128) - $nsisBytes = [long](Assert-HandoffMappingBounds ` - $nsisMappings $ExpectedNsisFileCount 16MB 'Hosted NSIS inventory') - $expectedTargetInventory = New-HandoffInventory $targetMappings 'Hosted target inventory' - $expectedResourcesInventory = New-HandoffInventory ` - $resourceMappings 'Hosted resources inventory' - $expectedNsisInventory = New-HandoffInventory $nsisMappings 'Hosted NSIS inventory' - if (@($expectedNsisInventory.entries).Count -ne $ExpectedNsisFileCount -or - [string]$expectedNsisInventory.sha256 -cne $ExpectedNsisInventorySha256) { - throw 'Tauri NSIS toolchain does not match the pinned 442-file closure.' - } - - $savedTargetArch = [Environment]::GetEnvironmentVariable('TARGET_ARCH') - $savedNodeOptions = [Environment]::GetEnvironmentVariable('NODE_OPTIONS') - $savedNodePath = [Environment]::GetEnvironmentVariable('NODE_PATH') - try { - [Environment]::SetEnvironmentVariable('TARGET_ARCH', 'x64') - [Environment]::SetEnvironmentVariable('NODE_OPTIONS', $null) - [Environment]::SetEnvironmentVariable('NODE_PATH', $null) - Push-Location $repoRoot - try { - & $node $checkerPath --expected-source-revision $revision - if ($LASTEXITCODE -ne 0) { - throw "Sidecar resource checker failed with exit code $LASTEXITCODE." - } - } finally { - Pop-Location - } - } finally { - [Environment]::SetEnvironmentVariable('TARGET_ARCH', $savedTargetArch) - [Environment]::SetEnvironmentVariable('NODE_OPTIONS', $savedNodeOptions) - [Environment]::SetEnvironmentVariable('NODE_PATH', $savedNodePath) - } - if ((Get-HandoffFileSha256 $checkerPath) -cne $checkerSha256) { - throw 'Sidecar resource checker changed while it was executing.' - } - - $runnerTemp = Get-HandoffTrustedPath ` - ([Environment]::GetEnvironmentVariable('RUNNER_TEMP')) 'RUNNER_TEMP' 'Container' - if ([string]::IsNullOrWhiteSpace($DestinationRoot) -or - -not [IO.Path]::IsPathRooted($DestinationRoot) -or - $DestinationRoot -match '[\x00-\x1F\x7F]' -or - $DestinationRoot -match '(^|[\\/])\.\.?(?:[\\/]|$)') { - throw 'DestinationRoot must be a safe, fully qualified local Windows path.' - } - $destination = [IO.Path]::GetFullPath($DestinationRoot).TrimEnd('\') - if (-not [string]::Equals( - (Split-Path $destination -Parent), - $runnerTemp.TrimEnd('\'), - [StringComparison]::OrdinalIgnoreCase - ) -or (Split-Path $destination -Leaf) -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]*$' -or - (Test-Path -LiteralPath $destination)) { - throw 'DestinationRoot must be an absent direct child of RUNNER_TEMP.' - } - if ($targetBytes -gt [long]::MaxValue - $nsisBytes -or - $targetBytes + $nsisBytes -gt [long]::MaxValue - 1GB) { - throw 'Handoff disk-capacity calculation overflowed.' - } - $requiredFreeBytes = $targetBytes + $nsisBytes + 1GB - $availableFreeBytes = [IO.DriveInfo]::new( - [IO.Path]::GetPathRoot($destination) - ).AvailableFreeSpace - if ($availableFreeBytes -lt $requiredFreeBytes) { - throw "RUNNER_TEMP has insufficient free space for the bounded handoff: requires $requiredFreeBytes bytes." - } - - $finalSourceAssertion = { - $lockedHead = [string](& $git -C $repoRoot rev-parse --verify HEAD) - $lockedStatus = @(& $git -C $repoRoot status --porcelain=v1 --untracked-files=all) - if ($LASTEXITCODE -ne 0 -or $lockedHead -cne $revision -or $lockedStatus.Count -ne 0 -or - (Get-HandoffFileSha256 $checkerPath) -cne $checkerSha256) { - throw 'Repository or checker changed while the handoff was being assembled.' - } - Assert-HandoffDefaultIndexFlags $git $repoRoot - }.GetNewClosure() - $handoff = Invoke-HandoffDestinationTransaction ` - -DestinationRoot $destination -DestinationParentRoot $runnerTemp ` - -TargetMappings $targetMappings -ResourceMappings $resourceMappings ` - -NsisMappings $nsisMappings ` - -ExpectedTargetInventory $expectedTargetInventory ` - -ExpectedResourcesInventory $expectedResourcesInventory ` - -ExpectedNsisInventory $expectedNsisInventory ` - -SourceRevision $revision -CheckerSha256 $checkerSha256 ` - -FinalSourceAssertion $finalSourceAssertion - - Write-HandoffOutput 'artifact_root' $handoff.ArtifactRoot - Write-HandoffOutput 'prebuilt_root' $handoff.PrebuiltRoot - Write-HandoffOutput 'nsis_toolchain_root' $handoff.NsisToolchainRoot - Write-HandoffOutput 'receipt_path' $handoff.ReceiptPath - Write-HandoffOutput 'receipt_sha256' $handoff.ReceiptSha256 - Write-HandoffOutput 'source_revision' $revision - } finally { - foreach ($toolLock in $toolLocks) { $toolLock.Dispose() } - } -} - -if ($MyInvocation.InvocationName -ne '.') { - Invoke-WindowsSigningHandoff -} diff --git a/app/scripts/sign-macos-adhoc.sh b/app/scripts/sign-macos-adhoc.sh deleted file mode 100644 index 58d3dc9..0000000 --- a/app/scripts/sign-macos-adhoc.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env bash -# sign-macos-adhoc.sh — re-sign + verify a Tauri-built .app bundle for the -# Wave-1 Egzakta-internal pilot using ad-hoc signing. -# -# Implements docs/code-signing-pilot-and-launch.md §1.2 (macOS ad-hoc). -# -# Usage: -# ./sign-macos-adhoc.sh -# -# Ordinary `npm run tauri:build:mac` does not load the optional build override. -# Treat the input as unsigned until this script signs and verifies it. This script: -# -# 1. Signs or re-signs the bundle with --force --deep to catch nested helpers -# (sidecar binary, native deps) that Tauri's pass missed. -# 2. Verifies the signature with --verify --deep --strict. -# -# Distribute the result wrapped in .zip (NOT .dmg — Gatekeeper enforces -# notarization more aggressively on disk images since macOS 10.15). -# -# NOT for public Day-0 — that requires Apple Developer ID + notarization -# per docs/code-signing-pilot-and-launch.md §2.2. - -set -euo pipefail - -APP_PATH="${1:-}" - -if [[ -z "$APP_PATH" ]]; then - echo "usage: $0 " >&2 - exit 64 # EX_USAGE -fi - -if [[ ! -d "$APP_PATH" ]]; then - echo "[sign-macos-adhoc] not a directory: $APP_PATH" >&2 - exit 66 # EX_NOINPUT -fi - -if [[ ! "$APP_PATH" =~ \.app$ ]]; then - echo "[sign-macos-adhoc] path must end in .app: $APP_PATH" >&2 - exit 64 -fi - -if ! command -v codesign >/dev/null 2>&1; then - echo "[sign-macos-adhoc] codesign not found — Xcode command-line tools required." >&2 - exit 69 # EX_UNAVAILABLE -fi - -echo "[sign-macos-adhoc] re-signing: $APP_PATH" -codesign --force --deep --sign - "$APP_PATH" - -echo "[sign-macos-adhoc] verifying signature" -codesign --verify --deep --strict "$APP_PATH" - -echo "[sign-macos-adhoc] OK" -echo "" -echo "Next:" -echo " ditto -c -k --keepParent \"$APP_PATH\" \"${APP_PATH%.app}.zip\"" -echo " # Distribute the .zip, NOT a .dmg, for the pilot." diff --git a/app/scripts/sign-windows-artifact.ps1 b/app/scripts/sign-windows-artifact.ps1 deleted file mode 100644 index 8df2750..0000000 --- a/app/scripts/sign-windows-artifact.ps1 +++ /dev/null @@ -1,4704 +0,0 @@ -[CmdletBinding()] -param( - [ValidateSet('Callback', 'Package')] - [string]$Mode = 'Callback', - - [AllowEmptyString()] - [string]$ArtifactPath = '', - - [AllowEmptyString()] - [string]$ArtifactSigningPackageSource = '', - - [AllowEmptyString()] - [string]$UnsignedInputRoot = '', - - [AllowEmptyString()] - [string]$SigningInputRoot = '', - - [AllowEmptyString()] - [string]$BuildReceiptPath = '', - - [AllowEmptyString()] - [string]$BuildReceiptSha256 = '', - - [AllowEmptyString()] - [string]$PortableToolchainRoot = '', - - [AllowEmptyString()] - [string]$PortableNodePath = '', - - [AllowEmptyString()] - [string]$PortableGitPath = '', - - [AllowEmptyString()] - [string]$PortableSevenZipPath = '', - - [AllowEmptyString()] - [string]$PortableToolchainReceiptPath = '', - - [AllowEmptyString()] - [string]$PortableToolchainReceiptSha256 = '', - - [switch]$TrustedPowerShellHost -) - -$trustedModuleRoot = [IO.Path]::GetFullPath([IO.Path]::Combine($PSHOME, 'Modules')) -[Environment]::SetEnvironmentVariable('PSModulePath', $trustedModuleRoot, 'Process') -$global:PSModuleAutoLoadingPreference = 'None' -foreach ($moduleName in @( - 'Microsoft.PowerShell.Security', - 'Microsoft.PowerShell.Management', - 'Microsoft.PowerShell.Utility' - )) { - $moduleManifest = [IO.Path]::Combine( - $trustedModuleRoot, $moduleName, "$moduleName.psd1" - ) - if (-not [IO.File]::Exists($moduleManifest)) { - throw "Trusted PowerShell module is missing: $moduleManifest" - } - Microsoft.PowerShell.Core\Import-Module ` - $moduleManifest -Force -Scope Global -ErrorAction Stop -} -if ($PSVersionTable.PSEdition -ceq 'Desktop') { - $appxManifest = [IO.Path]::Combine($trustedModuleRoot, 'Appx', 'Appx.psd1') - if ([IO.File]::Exists($appxManifest)) { - Microsoft.PowerShell.Core\Import-Module ` - $appxManifest -Force -Scope Global -ErrorAction Stop - } -} - -$trustedCommandModules = [ordered]@{ - 'Get-AuthenticodeSignature' = 'Microsoft.PowerShell.Security' - 'Get-Acl' = 'Microsoft.PowerShell.Security' - 'Set-Acl' = 'Microsoft.PowerShell.Security' - 'Get-FileHash' = 'Microsoft.PowerShell.Utility' -} -foreach ($entry in $trustedCommandModules.GetEnumerator()) { - $command = $ExecutionContext.SessionState.InvokeCommand.GetCommand( - [string]$entry.Key, - [Management.Automation.CommandTypes]::All - ) - $expectedModulePath = [IO.Path]::Combine( - $trustedModuleRoot, [string]$entry.Value, "$([string]$entry.Value).psd1" - ) - if ($null -eq $command -or - -not [string]::Equals( - [IO.Path]::GetFullPath([string]$command.Module.Path), - [IO.Path]::GetFullPath($expectedModulePath), - [StringComparison]::OrdinalIgnoreCase - )) { - throw "PowerShell command '$($entry.Key)' did not resolve from the trusted module root." - } -} - -Set-StrictMode -Version Latest -$ErrorActionPreference = 'Stop' - -$MicrosoftPublisher = 'CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US' -$MicrosoftWindowsPublisher = 'CN=Microsoft Windows, O=Microsoft Corporation, L=Redmond, S=Washington, C=US' -$DotNetPublisher = 'CN=.NET, O=Microsoft Corporation, L=Redmond, S=Washington, C=US' -$NodePublisher = 'CN=OpenJS Foundation, O=OpenJS Foundation, L=San Francisco, S=California, C=US' -$GitPublisher = 'CN=Johannes Schindelin, O=Johannes Schindelin, S=Nordrhein-Westfalen, C=DE' -$ArtifactSigningEndpoint = 'https://weu.codesigning.azure.net/' -$ArtifactSigningAccount = 'waggleos-egzakta-signing' -$ArtifactSigningProfile = 'waggleos-public-trust' -$ArtifactSigningClientVersion = '1.0.128.0' -$ArtifactSigningDlibSha256 = '2D4C1BBC87467B3AC25BBC49DF58CC8B36A0F92B3E21AA98BBBAD08A4D7C98BA' -$ArtifactSigningPackageSha256 = '74BD7D27E6CE1051409C38D9B46BC8DF0400ECD643D51FFBF2AC00869061E40B' -$ArtifactSigningX64ManifestSha256 = '7B78EF94C8B5939281F7AA364EA6406716F844D893DAA89AF601933D0BA1DB6E' -$SignToolSha256 = '431EE314C83988CACDA86606356FD321B75AE0093481B97E3B738E99C412F2A0' -$TauriCliVersion = '2.10.1' -$TauriCliSha256 = '0DD6EC63C7C63A993FDE20955E291D833C03F3760E63E0EE21E83482F6C0B43A' -$TauriCliPackageSha256 = '15A3A9383E8EDF7AD3D5117DBD8B9A6D75EE36654D3F71D2D0AD48E294EBAB98' -$TauriCliMainSha256 = '49DF414A16784E3711D5582D55C5C9E537ACEB1108C5ECFC6A17CDC2F5259B4D' -$TauriCliIndexSha256 = 'F6A7556765D3ED2DD40F9FCF609CEB7D3646FCCBB7FA01EEB9B7931F8BC8BB4F' -$TauriNativePackageSha256 = '6CB1DD193C36BAA11679ED9403FC564AA1E06A2BFAA066A146555D93BD07A783' -$TauriNativeBinarySha256 = 'F7289148FDF4CE6CE527D34C63A0055C87DE4FFE0A98475F3998D527225B1443' -$MakensisSha256 = '42850802704ECB11163F7E0329D35EE54BD288953200D4966E226D572848CFC5' -$NsisClosureSha256 = '1FC822D1A183552A80ADEA01B0BF456F462B90518256EF1FE9EDFA22D76CD85A' -$GitSha256 = '34A408843194BE320D8A87A3C12CD5C7D2E08D03B24567A41DB32E21D12569D2' -$GitRuntimeSha256 = '755D4896D35663D0FF08924F84507F35236B83D240635B512C519BF43CC71A87' -$NodePath = 'C:\Program Files\nodejs\node.exe' -$NodeSha256 = 'AE1A50511BE58E987483FDBC12125407443926D2D394669ADE2352776E920DD3' -$SevenZipPath = 'C:\Program Files\7-Zip\7z.exe' -$SevenZipSha256 = '4CD7D776C686427226A151789D2D61F0B2ED2C392148CC4E69C0238362FAFECF' -$SevenZipDllSha256 = '5BD20FB38499D95C39594F41D4781B6181B3304B7F1F4D06B0182F514E7EAA74' -$NodeArchiveSha256 = '7C93E9D92BF68C07182B471AA187E35EE6CD08EF0F24AB060DFFF605FCC1C57C' -$GitArchiveSha256 = 'C2C955A21FA99889D83F485F24FA5D9A38FFFC2D509D4022385510E11C26B250' -$SevenZipArchiveSha256 = '78AFA2A1C773CAF3CF7EDF62F857D2A8A5DA55FB0FFF5DA416074C0D28B2B55F' -$PortableToolchainFileCount = 2495 -$PortableToolchainInventorySha256 = 'D64F897D4E1A7F07FE9BA62D6AF062EF9F0E41C595CDAF2F3C4F73991BBEA0F5' -$ApprovedPublisher = 'CN=EGZAKTA DOO BEOGRAD, O=EGZAKTA DOO BEOGRAD, L=Amsterdam, C=NL' -$CodeSigningOid = '1.3.6.1.5.5.7.3.3' -$SystemPowerShellPath = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' -$SignToolPath = 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\signtool.exe' -$GitPath = 'C:\Program Files\Git\cmd\git.exe' -$NsisUninstallerPattern = '^nst[0-9A-F]{4}\.tmp$' - -function Get-TrustedPath { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$Label, - [ValidateSet('Leaf', 'Container')] [string]$PathType = 'Leaf', - [switch]$AllowHardLink - ) - - if ([string]::IsNullOrWhiteSpace($Path) -or - $Path -match '[\x00-\x1F\x7F]' -or - $Path -notmatch '^[A-Za-z]:[\\/]' -or - $Path -match '^[\\/]{2}' -or - $Path -match '^[\\/]{2}[?.][\\/]' -or - $Path -match '(^|[\\/])\.\.?(?:[\\/]|$)' -or - $Path.Substring(2) -match ':' -or - @($Path -split '[\\/]' | Where-Object { $_ -match '[. ]$' }).Count -gt 0) { - throw "$Label must use a safe, fully qualified local Windows path." - } - - $fullPath = [IO.Path]::GetFullPath($Path) - $testPathType = if ($PathType -eq 'Leaf') { 'Leaf' } else { 'Container' } - if (-not (Test-Path -LiteralPath $fullPath -PathType $testPathType)) { - throw "$Label does not exist as a $($PathType.ToLowerInvariant()): $fullPath" - } - - $root = [IO.Path]::GetPathRoot($fullPath) - $relative = $fullPath.Substring($root.Length) - $current = $root - foreach ($component in @($relative -split '[\\/]' | Where-Object { $_ })) { - $current = Join-Path $current $component - $item = Get-Item -LiteralPath $current -Force - if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { - throw "$Label traverses a reparse point: $current" - } - $linkTypeProperty = $item.PSObject.Properties['LinkType'] - $linkType = if ($null -eq $linkTypeProperty) { '' } else { [string]$linkTypeProperty.Value } - if (-not [string]::IsNullOrEmpty($linkType) -and - -not ($AllowHardLink -and $linkType -ceq 'HardLink')) { - throw "$Label traverses a linked filesystem object: $current" - } - } - - $resolved = (Resolve-Path -LiteralPath $fullPath).ProviderPath - if (-not [string]::Equals( - [IO.Path]::GetFullPath($resolved), - $fullPath, - [StringComparison]::OrdinalIgnoreCase - )) { - throw "$Label resolves to an unexpected path." - } - return $fullPath -} - -function Get-ContainedRelativePath { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$Root - ) - - $relative = [IO.Path]::GetRelativePath($Root, $Path) - if ([IO.Path]::IsPathRooted($relative) -or - $relative -eq '..' -or - $relative.StartsWith("..$([IO.Path]::DirectorySeparatorChar)", [StringComparison]::Ordinal)) { - return $null - } - return $relative.Replace('/', '\') -} - -function Get-ArtifactPolicyKind { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$ReleaseRoot, - [Parameter(Mandatory = $true)] [string]$ResourcesRoot, - [AllowNull()] [string]$NsisTempRoot, - [Parameter(Mandatory = $true)] [string]$Version - ) - - $releaseRelative = Get-ContainedRelativePath $Path $ReleaseRoot - if ($null -ne $releaseRelative) { - $allowedPeFiles = @( - 'waggle.exe', - 'nsis\x64\Plugins\x86-unicode\NSISdl.dll', - 'nsis\x64\Plugins\x86-unicode\StartMenu.dll', - 'nsis\x64\Plugins\x86-unicode\System.dll', - 'nsis\x64\Plugins\x86-unicode\nsDialogs.dll', - 'nsis\x64\Plugins\x86-unicode\additional\nsis_tauri_utils.dll', - "bundle\nsis\Waggle_${Version}_x64-setup.exe" - ) - if ($allowedPeFiles -contains $releaseRelative) { - return 'PE' - } - throw "Artifact is not in the approved Tauri release manifest: $releaseRelative" - } - - $resourceRelative = Get-ContainedRelativePath $Path $ResourcesRoot - if ($null -ne $resourceRelative) { - $allowedResourceFiles = @( - 'native\vec0.dll', - 'native\onnxruntime\onnxruntime.dll', - 'node_modules\@img\sharp-win32-x64\lib\libvips-42.dll', - 'node_modules\@img\sharp-win32-x64\lib\libvips-cpp-8.18.3.dll', - 'node_modules\onnxruntime-node\bin\napi-v3\win32\x64\onnxruntime.dll', - 'node_modules\sqlite-vec-windows-x64\vec0.dll' - ) - if ($allowedResourceFiles -contains $resourceRelative) { - return 'PE' - } - throw "Artifact is not in the approved Tauri resource manifest: $resourceRelative" - } - - if ($null -ne $NsisTempRoot) { - $tempRelative = Get-ContainedRelativePath $Path $NsisTempRoot - if ($null -ne $tempRelative -and - $tempRelative -notmatch '[\\/]' -and - $tempRelative -cmatch '^nst[0-9A-F]{4}\.tmp$') { - return 'PE' - } - } - - throw 'Artifact is outside every approved Waggle signing root.' -} - -function Assert-PeFile { - param([Parameter(Mandatory = $true)] [string]$Path) - - $stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read) - try { - if ($stream.Length -lt 64) { throw 'PE file is too short.' } - $reader = [IO.BinaryReader]::new($stream) - if ($reader.ReadUInt16() -ne 0x5A4D) { throw 'Artifact lacks the PE MZ header.' } - $stream.Position = 0x3C - $peOffset = $reader.ReadUInt32() - if ($peOffset -lt 64 -or $peOffset -gt 4MB -or $peOffset + 4 -gt $stream.Length) { - throw 'Artifact has an invalid PE header offset.' - } - $stream.Position = $peOffset - if ($reader.ReadUInt32() -ne 0x00004550) { throw 'Artifact lacks the PE signature.' } - } finally { - $stream.Dispose() - } -} - -function Assert-MsiFile { - param([Parameter(Mandatory = $true)] [string]$Path) - - $expected = [byte[]](0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1) - $stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read) - try { - if ($stream.Length -lt $expected.Length) { throw 'MSI file is too short.' } - $actual = [byte[]]::new($expected.Length) - if ($stream.Read($actual, 0, $actual.Length) -ne $actual.Length) { - throw 'Could not read the MSI header.' - } - if (-not [Linq.Enumerable]::SequenceEqual($actual, $expected)) { - throw 'Artifact lacks the MSI compound-file header.' - } - } finally { - $stream.Dispose() - } -} - -function Assert-ApprovedAuthenticodeFile { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$Label, - [AllowNull()] [string]$ExpectedSha256, - [Parameter(Mandatory = $true)] [string]$ExpectedPublisher, - [switch]$AllowCatalog - ) - - $signature = Get-AuthenticodeSignature -LiteralPath $Path - $signatureType = [string]$signature.SignatureType - $approvedSignatureType = $signatureType -ceq 'Authenticode' -or - ($AllowCatalog -and $signatureType -ceq 'Catalog') - if ($signature.Status -ne [Management.Automation.SignatureStatus]::Valid -or - -not $approvedSignatureType -or - $null -eq $signature.SignerCertificate -or - -not [string]::Equals( - [string]$signature.SignerCertificate.Subject, - $ExpectedPublisher, - [StringComparison]::Ordinal - )) { - throw "$Label is not validly Authenticode-signed by the approved publisher." - } - - $hasCodeSigningEku = @( - $signature.SignerCertificate.Extensions | - Where-Object { $_ -is [Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension] } | - ForEach-Object { $_.EnhancedKeyUsages } | - Where-Object { $_.Value -eq $CodeSigningOid } - ).Count -gt 0 - if (-not $hasCodeSigningEku) { throw "$Label lacks the Code Signing EKU." } - - if (-not [string]::IsNullOrEmpty($ExpectedSha256)) { - $actualHash = (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash - if (-not [string]::Equals($actualHash, $ExpectedSha256, [StringComparison]::OrdinalIgnoreCase)) { - throw "$Label does not match the pinned SHA-256 digest." - } - } -} - -function Assert-MicrosoftAuthenticodeFile { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$Label, - [AllowNull()] [string]$ExpectedSha256, - [string]$ExpectedPublisher = $MicrosoftPublisher, - [switch]$AllowCatalog - ) - - Assert-ApprovedAuthenticodeFile ` - $Path $Label $ExpectedSha256 $ExpectedPublisher -AllowCatalog:$AllowCatalog -} - -function Assert-ApprovedPowerShell7Path { - param([Parameter(Mandatory = $true)] [string]$Path) - - $programFiles = [Environment]::GetFolderPath( - [Environment+SpecialFolder]::ProgramFiles - ) - $standardPath = [IO.Path]::GetFullPath((Join-Path $programFiles 'PowerShell\7\pwsh.exe')) - $windowsAppsPattern = '^[A-Za-z]:\\Program Files\\WindowsApps\\Microsoft\.PowerShell_\d+\.\d+\.\d+\.\d+_x64__8wekyb3d8bbwe\\pwsh\.exe$' - if (-not [string]::Equals($Path, $standardPath, [StringComparison]::OrdinalIgnoreCase) -and - $Path -notmatch $windowsAppsPattern) { - throw 'PowerShell 7 must come from the canonical Microsoft installation path.' - } - if ([Version](Get-Item -LiteralPath $Path).VersionInfo.FileVersion -lt [Version]'7.5.0') { - throw 'Artifact Signing requires PowerShell 7.5 or newer for non-coercing JSON validation.' - } - Assert-MicrosoftAuthenticodeFile $Path 'PowerShell 7 host' $null -} - -function Get-ApprovedPowerShell7Path { - $programFiles = [Environment]::GetFolderPath( - [Environment+SpecialFolder]::ProgramFiles - ) - $candidates = @() - $standardPath = Join-Path $programFiles 'PowerShell\7\pwsh.exe' - if (Test-Path -LiteralPath $standardPath -PathType Leaf) { - $candidates += $standardPath - } - if ($PSVersionTable.PSEdition -ceq 'Core') { - $currentHost = (Get-Process -Id $PID).Path - if (-not [string]::IsNullOrWhiteSpace($currentHost)) { - $candidates += $currentHost - } - } - - if ($PSVersionTable.PSEdition -ceq 'Desktop') { - $windowsAppsRoot = Join-Path $programFiles 'WindowsApps' - $candidates += @( - Microsoft.PowerShell.Core\Get-Module Appx | - ForEach-Object { Appx\Get-AppxPackage -Name Microsoft.PowerShell -ErrorAction SilentlyContinue } | - Where-Object { - [string]$_.Architecture -ceq 'X64' -and - $_.InstallLocation -like "$windowsAppsRoot\Microsoft.PowerShell_*" - } | - Sort-Object Version -Descending | - ForEach-Object { Join-Path $_.InstallLocation 'pwsh.exe' } | - Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } - ) - } - - foreach ($candidate in $candidates) { - try { - $trustedCandidate = Get-TrustedPath $candidate 'PowerShell 7 host' -AllowHardLink - Assert-ApprovedPowerShell7Path $trustedCandidate - return $trustedCandidate - } catch { - continue - } - } - throw 'No approved, Microsoft-signed 64-bit PowerShell 7 host is installed.' -} - -function Invoke-TrustedPowerShellRelaunch { - param( - [Parameter(Mandatory = $true)] [ValidateSet('Callback', 'Package')] [string]$LaunchMode, - [string]$Path = '', - [string]$PackageSource = '', - [string]$ToolchainRoot = '', - [string]$Node = '', - [string]$Git = '', - [string]$SevenZip = '', - [string]$ToolchainReceipt = '', - [string]$ToolchainReceiptSha256 = '' - ) - - $systemHost = Get-TrustedPath $SystemPowerShellPath 'Windows PowerShell bootstrap' -AllowHardLink - $actualHost = Get-TrustedPath (Get-Process -Id $PID).Path 'Current bootstrap host' -AllowHardLink - if (-not [string]::Equals($actualHost, $systemHost, [StringComparison]::OrdinalIgnoreCase)) { - throw 'Artifact Signing bootstrap must run under canonical Windows PowerShell.' - } - Assert-MicrosoftAuthenticodeFile ` - $systemHost 'Windows PowerShell bootstrap' $null $MicrosoftWindowsPublisher -AllowCatalog - - $powerShell7 = Get-ApprovedPowerShell7Path - $arguments = @( - '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', - '-File', $PSCommandPath, '-Mode', $LaunchMode, '-TrustedPowerShellHost' - ) - if ($LaunchMode -ceq 'Callback') { - if ([string]::IsNullOrWhiteSpace($Path)) { - throw 'Signing callback requires an artifact path.' - } - $arguments += @('-ArtifactPath', $Path) - } else { - foreach ($pair in @( - @('-UnsignedInputRoot', $UnsignedInputRoot), - @('-SigningInputRoot', $SigningInputRoot), - @('-BuildReceiptPath', $BuildReceiptPath), - @('-BuildReceiptSha256', $BuildReceiptSha256), - @('-ArtifactSigningPackageSource', $PackageSource), - @('-PortableToolchainRoot', $ToolchainRoot), - @('-PortableNodePath', $Node), - @('-PortableGitPath', $Git), - @('-PortableSevenZipPath', $SevenZip), - @('-PortableToolchainReceiptPath', $ToolchainReceipt), - @('-PortableToolchainReceiptSha256', $ToolchainReceiptSha256) - )) { - if (-not [string]::IsNullOrWhiteSpace([string]$pair[1])) { - $arguments += @([string]$pair[0], [string]$pair[1]) - } - } - } - & $powerShell7 @arguments - if ($LASTEXITCODE -ne 0) { - throw "Trusted PowerShell 7 signing process failed with exit code $LASTEXITCODE." - } -} - -function New-PrivateDirectory { - param([Parameter(Mandatory = $true)] [string]$Path) - - [IO.Directory]::CreateDirectory($Path) | Out-Null - $inheritance = [Security.AccessControl.InheritanceFlags]::ContainerInherit -bor - [Security.AccessControl.InheritanceFlags]::ObjectInherit - $propagation = [Security.AccessControl.PropagationFlags]::None - $allow = [Security.AccessControl.AccessControlType]::Allow - $fullControl = [Security.AccessControl.FileSystemRights]::FullControl - $identities = @( - [Security.Principal.WindowsIdentity]::GetCurrent().User, - [Security.Principal.SecurityIdentifier]::new('S-1-5-18'), - [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') - ) - $approvedSids = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) - foreach ($identity in $identities) { [void]$approvedSids.Add($identity.Value) } - $isApprovedAcl = { - param([Security.AccessControl.DirectorySecurity]$Acl) - - if (-not $Acl.AreAccessRulesProtected -or - -not $approvedSids.Contains( - $Acl.GetOwner([Security.Principal.SecurityIdentifier]).Value - )) { - return $false - } - $rules = @($Acl.GetAccessRules( - $true, - $true, - [Security.Principal.SecurityIdentifier] - )) - if ($rules.Count -ne $approvedSids.Count) { return $false } - foreach ($rule in $rules) { - if ($rule.IsInherited -or - $rule.AccessControlType -ne $allow -or - -not $approvedSids.Contains($rule.IdentityReference.Value) -or - ($rule.FileSystemRights -band $fullControl) -ne $fullControl) { - return $false - } - } - return $true - } - - $existing = Get-Acl -LiteralPath $Path - if (-not (& $isApprovedAcl $existing)) { - $security = $existing - $security.SetAccessRuleProtection($true, $false) - $security.SetOwner([Security.Principal.WindowsIdentity]::GetCurrent().User) - $existingRules = @($security.GetAccessRules( - $true, - $true, - [Security.Principal.SecurityIdentifier] - )) - foreach ($existingRule in $existingRules) { - $security.RemoveAccessRuleSpecific($existingRule) - } - foreach ($identity in $identities) { - $rule = [Security.AccessControl.FileSystemAccessRule]::new( - $identity, - $fullControl, - $inheritance, - $propagation, - $allow - ) - [void]$security.AddAccessRule($rule) - } - Set-Acl -LiteralPath $Path -AclObject $security - } - - $trustedPath = Get-TrustedPath $Path 'Private signing directory' 'Container' - $applied = Get-Acl -LiteralPath $trustedPath - if (-not (& $isApprovedAcl $applied)) { - throw 'Private signing directory permissions do not match the approved principals.' - } - return $trustedPath -} - -function Open-ReadLock { - param([Parameter(Mandatory = $true)] [string]$Path) - - return [IO.File]::Open( - $Path, - [IO.FileMode]::Open, - [IO.FileAccess]::Read, - [IO.FileShare]::Read - ) -} - -function Get-WagglePrebuiltFiles { - param( - [Parameter(Mandatory = $true)] [string]$Root, - [Parameter(Mandatory = $true)] [string]$Label - ) - - $trustedRoot = Get-TrustedPath $Root $Label 'Container' - $pending = [Collections.Generic.Queue[string]]::new() - $files = [Collections.Generic.List[string]]::new() - $pending.Enqueue($trustedRoot) - while ($pending.Count -gt 0) { - $directory = $pending.Dequeue() - foreach ($item in @(Get-ChildItem -LiteralPath $directory -Force)) { - if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { - throw "$Label contains a reparse point or linked filesystem object: $($item.FullName)" - } - if ($item.PSIsContainer) { - $pending.Enqueue((Get-TrustedPath $item.FullName $Label 'Container')) - } else { - $files.Add((Get-TrustedPath $item.FullName $Label -AllowHardLink)) - } - } - } - return [pscustomobject]@{ Root = $trustedRoot; Files = @($files) } -} - -function Get-WaggleInventorySha256 { - param([Parameter(Mandatory = $true)] [object[]]$Entries) - - $canonical = @($Entries | ForEach-Object { - [ordered]@{ - path = [string]$_.path - size = [long]$_.size - sha256 = ([string]$_.sha256).ToUpperInvariant() - } - }) | ConvertTo-Json -Depth 8 -Compress - return [Convert]::ToHexString( - [Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($canonical)) - ) -} - -function Assert-WaggleCanonicalInventoryEntries { - param( - [Parameter(Mandatory = $true)] [object[]]$Entries, - [Parameter(Mandatory = $true)] [string]$Label - ) - - $exactPaths = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) - $foldedPaths = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) - $orderedPaths = [Collections.Generic.List[string]]::new() - foreach ($entry in $Entries) { - $relativePath = [string](Get-RequiredPropertyValue $entry 'path' "$Label entry") - $sha256 = [string](Get-RequiredPropertyValue $entry 'sha256' "$Label entry") - $size = [long](Get-RequiredPropertyValue $entry 'size' "$Label entry") - if ([string]::IsNullOrWhiteSpace($relativePath) -or - $relativePath -match '[\x00-\x1F\x7F]' -or - $relativePath -match '(^|[\\/])\.\.?(?:[\\/]|$)' -or - [IO.Path]::IsPathRooted($relativePath) -or - $relativePath.Contains('/') -or - $relativePath.Contains(':') -or - @($relativePath -split '\\' | Where-Object { $_ -match '[. ]$' }).Count -ne 0) { - throw "$Label contains an unsafe or non-canonical relative path." - } - if (-not $exactPaths.Add($relativePath) -or -not $foldedPaths.Add($relativePath)) { - throw "$Label contains a duplicate canonical path or case-insensitive case collision." - } - if ($sha256 -notmatch '^[0-9A-Fa-f]{64}$' -or $size -lt 0) { - throw "$Label contains an invalid SHA-256 digest or file size." - } - $orderedPaths.Add($relativePath) - } - $sortedPaths = [Collections.Generic.List[string]]::new() - foreach ($path in $orderedPaths) { $sortedPaths.Add($path) } - $sortedPaths.Sort([StringComparer]::Ordinal) - if ([string]::Join("`n", $orderedPaths) -cne [string]::Join("`n", $sortedPaths)) { - throw "$Label entries must be sorted by ordinal canonical path." - } -} - -function New-WagglePrebuiltInventory { - param( - [Parameter(Mandatory = $true)] [string]$Root, - [string]$CargoReleaseRelativePath = 'release' - ) - - $tree = Get-WagglePrebuiltFiles $Root 'Prebuilt input tree' - $entries = [Collections.Generic.List[object]]::new() - foreach ($path in $tree.Files) { - $streams = @(Get-Item -LiteralPath $path -Stream * -ErrorAction Stop) - if ($streams.Count -ne 1 -or [string]$streams[0].Stream -cne ':$DATA') { - throw 'Prebuilt input tree contains an alternate data stream (ADS).' - } - $relative = (Get-ContainedRelativePath $path $tree.Root).Replace('/', '\') - if ($null -eq $relative) { throw 'Prebuilt input tree path escaped its root.' } - $item = Get-Item -LiteralPath $path -Force - $linkTypeProperty = $item.PSObject.Properties['LinkType'] - $linkType = if ($null -eq $linkTypeProperty) { '' } else { [string]$linkTypeProperty.Value } - if (-not [string]::IsNullOrEmpty($linkType)) { - if ($linkType -cne 'HardLink') { - throw 'Prebuilt input tree contains an unsupported linked filesystem object.' - } - Assert-ApprovedHardLinkTopology ` - $path (Join-Path $tree.Root $CargoReleaseRelativePath) - } - $lock = Open-ReadLock $path - try { - $entries.Add([pscustomobject][ordered]@{ - path = $relative - size = [long]$item.Length - sha256 = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash - }) - } finally { - $lock.Dispose() - } - } - $sortedEntries = @($entries) - [Array]::Sort($sortedEntries, [Comparison[object]]{ - param($left, $right) - return [StringComparer]::Ordinal.Compare([string]$left.path, [string]$right.path) - }) - Assert-WaggleCanonicalInventoryEntries $sortedEntries 'Prebuilt input inventory' - return [pscustomobject][ordered]@{ - entries = $sortedEntries - sha256 = Get-WaggleInventorySha256 $sortedEntries - } -} - -function Test-WagglePathsOverlap { - param( - [Parameter(Mandatory = $true)] [string]$Left, - [Parameter(Mandatory = $true)] [string]$Right - ) - $leftPath = [IO.Path]::GetFullPath($Left).TrimEnd('\') - $rightPath = [IO.Path]::GetFullPath($Right).TrimEnd('\') - return [string]::Equals($leftPath, $rightPath, [StringComparison]::OrdinalIgnoreCase) -or - $leftPath.StartsWith("$rightPath\", [StringComparison]::OrdinalIgnoreCase) -or - $rightPath.StartsWith("$leftPath\", [StringComparison]::OrdinalIgnoreCase) -} - -function New-WagglePrebuiltWorkCopy { - param( - [Parameter(Mandatory = $true)] [string]$SourceRoot, - [Parameter(Mandatory = $true)] [string]$DestinationRoot, - [Parameter(Mandatory = $true)] [object]$Inventory, - [Parameter(Mandatory = $true)] [string]$Label, - [string]$CargoReleaseRelativePath = 'x86_64-pc-windows-msvc\release' - ) - - $source = Get-TrustedPath $SourceRoot "$Label source" 'Container' - $destination = [IO.Path]::GetFullPath($DestinationRoot) - if ((Test-WagglePathsOverlap $source $destination) -or - (Test-Path -LiteralPath $destination)) { - throw "$Label destination must be absent and distinct from its source." - } - $root = New-PrivateDirectory $destination - $entries = @((Get-RequiredPropertyValue $Inventory 'entries' "$Label inventory")) - Assert-WaggleCanonicalInventoryEntries $entries "$Label inventory" - $releaseRelative = $CargoReleaseRelativePath - $mainRelative = "$releaseRelative\waggle.exe" - $dependencyRelative = "$releaseRelative\deps\waggle.exe" - $mainEntry = @($entries | Where-Object { [string]$_.path -ceq $mainRelative }) - $dependencyEntry = @($entries | Where-Object { [string]$_.path -ceq $dependencyRelative }) - if ($mainEntry.Count -ne 1 -or $dependencyEntry.Count -ne 1 -or - [long]$mainEntry[0].size -ne [long]$dependencyEntry[0].size -or - -not [string]::Equals( - [string]$mainEntry[0].sha256, - [string]$dependencyEntry[0].sha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw "$Label inventory lacks the exact equal-byte Cargo executable pair." - } - try { - foreach ($entry in $entries) { - $relative = [string]$entry.path - if ($relative -ceq $mainRelative) { continue } - $sourcePath = Get-TrustedPath ` - (Join-Path $source $relative) "$Label source file" -AllowHardLink - $destinationPath = Join-Path $root $relative - [IO.Directory]::CreateDirectory((Split-Path $destinationPath -Parent)) | Out-Null - [IO.File]::Copy($sourcePath, $destinationPath, $false) - } - $dependencyPath = Join-Path $root $dependencyRelative - $mainPath = Join-Path $root $mainRelative - New-Item -ItemType HardLink -Path $mainPath -Target $dependencyPath | Out-Null - $copyInventory = New-WagglePrebuiltInventory ` - -Root $root -CargoReleaseRelativePath $CargoReleaseRelativePath - if (-not [string]::Equals( - [string]$copyInventory.sha256, - [string](Get-RequiredPropertyValue $Inventory 'sha256' "$Label inventory"), - [StringComparison]::OrdinalIgnoreCase - )) { - throw "$Label work copy does not match the receipt-bound inventory." - } - Assert-ApprovedHardLinkTopology ` - $mainPath (Join-Path $root $releaseRelative) - return $root - } catch { - if (Test-Path -LiteralPath $root) { - Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue - } - throw - } -} - -function Assert-WaggleHostedDiskCapacity { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [object]$Inventory, - [long]$AvailableBytes = -1 - ) - $entries = @((Get-RequiredPropertyValue $Inventory 'entries' 'Hosted build target inventory')) - $inventoryBytes = [long]0 - foreach ($entry in $entries) { - $size = [long](Get-RequiredPropertyValue $entry 'size' 'Hosted build inventory entry') - if ($size -lt 0 -or $inventoryBytes -gt [long]::MaxValue - $size) { - throw 'Hosted build target inventory has an invalid aggregate size.' - } - $inventoryBytes += $size - } - $safetyBytes = [Math]::Max(2GB, [long][Math]::Ceiling($inventoryBytes / 2.0)) - $requiredBytes = $inventoryBytes + $safetyBytes - if ($AvailableBytes -lt 0) { - $root = [IO.Path]::GetPathRoot([IO.Path]::GetFullPath($Path)) - $AvailableBytes = [IO.DriveInfo]::new($root).AvailableFreeSpace - } - if ($AvailableBytes -lt $requiredBytes) { - throw "Hosted signing has insufficient free disk space: requires $requiredBytes bytes, available $AvailableBytes bytes." - } - return $requiredBytes -} - -function New-WagglePreflightEvidenceCopy { - param( - [Parameter(Mandatory = $true)] [object]$Context, - [Parameter(Mandatory = $true)] [string]$DestinationRoot - ) - $root = New-PrivateDirectory $DestinationRoot - try { - $fixedPaths = @(Get-ExpectedNsisFixedPaths $Context '0.0.0') - $mainSource = Get-TrustedPath $fixedPaths[0] 'Unsigned preflight main' -AllowHardLink - $mainRelative = Get-ContainedRelativePath $mainSource $Context.TargetRoot - if ($null -eq $mainRelative) { - throw 'Unsigned preflight main escaped its target root.' - } - $mainDestination = Join-Path $root $mainRelative - $dependencyDestination = Join-Path ` - (Split-Path $mainDestination -Parent) 'deps\waggle.exe' - [IO.Directory]::CreateDirectory((Split-Path $dependencyDestination -Parent)) | Out-Null - [IO.File]::Copy($mainSource, $dependencyDestination, $false) - New-Item -ItemType HardLink -Path $mainDestination -Target $dependencyDestination | Out-Null - Assert-ApprovedHardLinkTopology ` - $mainDestination (Split-Path $mainDestination -Parent) - - foreach ($sourcePathValue in @($fixedPaths | Select-Object -Skip 1)) { - $sourcePath = Get-TrustedPath ` - $sourcePathValue 'Unsigned preflight evidence source' -AllowHardLink - $relative = Get-ContainedRelativePath $sourcePath $Context.TargetRoot - if ($null -eq $relative) { - throw 'Unsigned preflight evidence escaped its target root.' - } - $destination = Join-Path $root $relative - [IO.Directory]::CreateDirectory((Split-Path $destination -Parent)) | Out-Null - [IO.File]::Copy($sourcePath, $destination, $false) - if ((Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash -cne - (Get-FileHash -LiteralPath $sourcePath -Algorithm SHA256).Hash) { - throw 'Unsigned preflight evidence copy failed digest verification.' - } - } - return $root - } catch { - if (Test-Path -LiteralPath $root) { - Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue - } - throw - } -} - -function Open-WaggleValidatedPrebuiltTree { - param( - [Parameter(Mandatory = $true)] [string]$Root, - [Parameter(Mandatory = $true)] [object]$ExpectedInventory, - [Parameter(Mandatory = $true)] [string]$Label, - [string[]]$DisallowedRoots = @(), - [string[]]$MutablePaths = @(), - [string[]]$RegeneratedRoots = @(), - [string]$CargoReleaseRelativePath = 'release' - ) - - $trustedRoot = Get-TrustedPath $Root $Label 'Container' - foreach ($disallowedRoot in $DisallowedRoots) { - $overlaps = if ([string]::IsNullOrWhiteSpace($disallowedRoot)) { - $false - } else { - Test-WagglePathsOverlap $trustedRoot ([IO.Path]::GetFullPath($disallowedRoot)) - } - if (-not [string]::IsNullOrWhiteSpace($disallowedRoot) -and - $overlaps) { - throw "$Label must be distinct from every disallowed root; root overlap is forbidden." - } - } - $expectedEntries = @((Get-RequiredPropertyValue $ExpectedInventory 'entries' "$Label inventory")) - $expectedSha256 = [string](Get-RequiredPropertyValue ` - $ExpectedInventory 'sha256' "$Label inventory") - Assert-WaggleCanonicalInventoryEntries $expectedEntries "$Label inventory" - if ($expectedSha256 -notmatch '^[0-9A-Fa-f]{64}$' -or - -not [string]::Equals( - (Get-WaggleInventorySha256 $expectedEntries), - $expectedSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw "$Label inventory aggregate SHA-256 digest is invalid." - } - - $tree = Get-WagglePrebuiltFiles $trustedRoot $Label - $actualPaths = [Collections.Generic.List[string]]::new() - foreach ($path in $tree.Files) { - $relative = Get-ContainedRelativePath $path $trustedRoot - if ($null -eq $relative) { throw "$Label path escaped its root." } - $actualPaths.Add($relative.Replace('/', '\')) - } - $actualPaths.Sort([StringComparer]::Ordinal) - $expectedPaths = @($expectedEntries | ForEach-Object { [string]$_.path }) - if ($actualPaths.Count -ne $expectedPaths.Count -or - [string]::Join("`n", $actualPaths) -cne [string]::Join("`n", $expectedPaths)) { - throw "$Label contains missing, extra, or unexpected files relative to its inventory." - } - - $mutableSet = [Collections.Generic.HashSet[string]]::new( - [StringComparer]::OrdinalIgnoreCase - ) - foreach ($mutablePathValue in @($MutablePaths)) { - $mutablePath = Get-TrustedPath ` - $mutablePathValue "$Label mutable file" -AllowHardLink - if ($null -eq (Get-ContainedRelativePath $mutablePath $trustedRoot) -or - -not $mutableSet.Add($mutablePath)) { - throw "$Label mutable-file roster contains an escaped or duplicate path." - } - } - $regeneratedRootList = [Collections.Generic.List[string]]::new() - foreach ($regeneratedRootValue in @($RegeneratedRoots)) { - $regeneratedRoot = Get-TrustedPath ` - $regeneratedRootValue "$Label regenerated root" 'Container' - $relativeRoot = Get-ContainedRelativePath $regeneratedRoot $trustedRoot - if ($null -eq $relativeRoot -or $relativeRoot -ceq '.') { - throw "$Label regenerated-root roster contains an escaped or unsafe root." - } - foreach ($existingRoot in $regeneratedRootList) { - if (Test-WagglePathsOverlap $regeneratedRoot $existingRoot) { - throw "$Label regenerated-root roster contains duplicate or overlapping roots." - } - } - $regeneratedRootList.Add($regeneratedRoot) - } - $matchedMutableSet = [Collections.Generic.HashSet[string]]::new( - [StringComparer]::OrdinalIgnoreCase - ) - $matchedRegeneratedRoots = [Collections.Generic.HashSet[string]]::new( - [StringComparer]::OrdinalIgnoreCase - ) - - $locks = [Collections.Generic.List[IDisposable]]::new() - try { - for ($index = 0; $index -lt $expectedEntries.Count; $index++) { - $entry = $expectedEntries[$index] - $path = Get-TrustedPath (Join-Path $trustedRoot ([string]$entry.path)) $Label -AllowHardLink - $streams = @(Get-Item -LiteralPath $path -Stream * -ErrorAction Stop) - if ($streams.Count -ne 1 -or [string]$streams[0].Stream -cne ':$DATA') { - throw "$Label contains an alternate data stream (ADS)." - } - $item = Get-Item -LiteralPath $path -Force - $linkTypeProperty = $item.PSObject.Properties['LinkType'] - $linkType = if ($null -eq $linkTypeProperty) { '' } else { [string]$linkTypeProperty.Value } - if (-not [string]::IsNullOrEmpty($linkType)) { - if ($linkType -cne 'HardLink') { throw "$Label contains an unsupported link." } - Assert-ApprovedHardLinkTopology ` - $path (Join-Path $trustedRoot $CargoReleaseRelativePath) - } - $lock = Open-ReadLock $path - try { - if ([long]$item.Length -ne [long]$entry.size -or - -not [string]::Equals( - (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash, - [string]$entry.sha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw "$Label file does not match its inventory SHA-256 digest and size." - } - if ($mutableSet.Contains($path)) { - [void]$matchedMutableSet.Add($path) - } - $isRegeneratedOutput = $false - foreach ($regeneratedRoot in $regeneratedRootList) { - if ($null -ne (Get-ContainedRelativePath $path $regeneratedRoot)) { - $isRegeneratedOutput = $true - [void]$matchedRegeneratedRoots.Add($regeneratedRoot) - break - } - } - if (-not $mutableSet.Contains($path) -and -not $isRegeneratedOutput) { - $locks.Add($lock) - $lock = $null - } - } finally { - if ($null -ne $lock) { $lock.Dispose() } - } - } - if ($matchedMutableSet.Count -ne $mutableSet.Count) { - throw "$Label mutable-file roster does not match its exact inventory." - } - if ($matchedRegeneratedRoots.Count -ne $regeneratedRootList.Count) { - throw "$Label regenerated-root roster does not match its exact inventory." - } - return [pscustomobject]@{ - Root = $trustedRoot - Inventory = $ExpectedInventory - Locks = $locks - MutablePaths = @($mutableSet) - RegeneratedRoots = @($regeneratedRootList) - } - } catch { - foreach ($lock in $locks) { $lock.Dispose() } - throw - } -} - -function Clear-WaggleRegeneratedRoots { - param([Parameter(Mandatory = $true)] [object]$Lease) - - $leaseRoot = Get-TrustedPath $Lease.Root 'Validated prebuilt work root' 'Container' - foreach ($rootValue in @($Lease.RegeneratedRoots)) { - $trustedRoot = Get-TrustedPath ` - ([string]$rootValue) 'Validated Tauri-generated output root' 'Container' - $relativeRoot = Get-ContainedRelativePath $trustedRoot $leaseRoot - if ($null -eq $relativeRoot -or $relativeRoot -ceq '.') { - throw 'Tauri-generated output root escaped its validated private work root.' - } - [IO.Directory]::Delete($trustedRoot, $true) - if (Test-Path -LiteralPath $trustedRoot) { - throw 'Tauri-generated output root could not be cleared before packaging.' - } - } -} - -function Get-NsisPatchedMainSha256 { - param([Parameter(Mandatory = $true)] [string]$Path) - - $trustedPath = Get-TrustedPath $Path 'Tauri main executable' -AllowHardLink - $lock = Open-ReadLock $trustedPath - try { - $bytes = [IO.File]::ReadAllBytes($trustedPath) - $unknownToken = [Text.Encoding]::ASCII.GetBytes('__TAURI_BUNDLE_TYPE_VAR_UNK') - $nsisToken = [Text.Encoding]::ASCII.GetBytes('__TAURI_BUNDLE_TYPE_VAR_NSS') - $msiToken = [Text.Encoding]::ASCII.GetBytes('__TAURI_BUNDLE_TYPE_VAR_MSI') - $findOffsets = { - param([byte[]]$Needle) - $offsets = [Collections.Generic.List[int]]::new() - for ($offset = 0; $offset -le $bytes.Length - $Needle.Length; $offset++) { - $matches = $true - for ($index = 0; $index -lt $Needle.Length; $index++) { - if ($bytes[$offset + $index] -ne $Needle[$index]) { - $matches = $false - break - } - } - if ($matches) { $offsets.Add($offset) } - } - return @($offsets) - } - $unknownOffsets = @(& $findOffsets $unknownToken) - if ($unknownOffsets.Count -ne 1 -or - @(& $findOffsets $nsisToken).Count -ne 0 -or - @(& $findOffsets $msiToken).Count -ne 0) { - throw 'Tauri main executable must contain exactly one unpatched bundle-type token.' - } - $patched = [byte[]]$bytes.Clone() - [Array]::Copy($nsisToken, 0, $patched, $unknownOffsets[0], $nsisToken.Length) - return [Convert]::ToHexString( - [Security.Cryptography.SHA256]::HashData($patched) - ) - } finally { - $lock.Dispose() - } -} - -function Get-RequiredPropertyValue { - param( - [Parameter(Mandatory = $true)] [object]$InputObject, - [Parameter(Mandatory = $true)] [string]$Name, - [Parameter(Mandatory = $true)] [string]$Label - ) - - $property = $InputObject.PSObject.Properties[$Name] - if ($null -eq $property -or $null -eq $property.Value) { - throw "$Label is missing required property '$Name'." - } - return $property.Value -} - -function Assert-ExactCanonicalPathValue { - param( - [Parameter(Mandatory = $true)] [string]$Actual, - [Parameter(Mandatory = $true)] [string]$Expected, - [Parameter(Mandatory = $true)] [string]$Label - ) - - if ([string]::IsNullOrWhiteSpace($Actual) -or - $Actual -match '[\x00-\x1F\x7F]' -or - $Actual -notmatch '^[A-Za-z]:[\\/]' -or - $Actual -match '^[\\/]{2}' -or - $Actual -match '(^|[\\/])\.\.?(?:[\\/]|$)' -or - $Actual.Substring(2) -match ':' -or - @($Actual -split '[\\/]' | Where-Object { $_ -match '[. ]$' }).Count -gt 0) { - throw "$Label must be a safe, fully qualified local Windows path." - } - if (-not [string]::Equals( - [IO.Path]::GetFullPath($Actual), - [IO.Path]::GetFullPath($Expected), - [StringComparison]::OrdinalIgnoreCase - )) { - throw "$Label does not match the signing session." - } -} - -function Get-WaggleSigningSlotPhase { - param([Parameter(Mandatory = $true)] [int]$Order) - if ($Order -eq 1) { return 1 } - if ($Order -ge 2 -and $Order -le 7) { return 2 } - if ($Order -ge 8 -and $Order -le 12) { return 3 } - if ($Order -eq 13) { return 4 } - if ($Order -eq 14) { return 5 } - throw 'Signing callback slot order is outside the exact NSIS phase roster.' -} - -function Assert-PrivateDirectoryAcl { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$Label - ) - - $directory = Get-TrustedPath $Path $Label 'Container' - $acl = Get-Acl -LiteralPath $directory - $allow = [Security.AccessControl.AccessControlType]::Allow - $fullControl = [Security.AccessControl.FileSystemRights]::FullControl - $approvedSids = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) - foreach ($identity in @( - [Security.Principal.WindowsIdentity]::GetCurrent().User, - [Security.Principal.SecurityIdentifier]::new('S-1-5-18'), - [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') - )) { - [void]$approvedSids.Add($identity.Value) - } - - if (-not $acl.AreAccessRulesProtected -or - -not $approvedSids.Contains( - $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value - )) { - throw "$Label must have protected private signing permissions." - } - $rules = @($acl.GetAccessRules( - $true, - $true, - [Security.Principal.SecurityIdentifier] - )) - if ($rules.Count -ne $approvedSids.Count) { - throw "$Label contains an unexpected access rule." - } - foreach ($rule in $rules) { - if ($rule.IsInherited -or - $rule.AccessControlType -ne $allow -or - -not $approvedSids.Contains($rule.IdentityReference.Value) -or - ($rule.FileSystemRights -band $fullControl) -ne $fullControl) { - throw "$Label contains an unapproved access rule." - } - } - return $directory -} - -function Assert-WagglePinnedToolFile { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$Label, - [Parameter(Mandatory = $true)] [string]$ExpectedSha256, - [AllowNull()] [string]$ExpectedPublisher, - [switch]$AllowCatalog, - [switch]$AllowHardLink - ) - - $trustedPath = Get-TrustedPath $Path $Label -AllowHardLink:$AllowHardLink - if ([string]::IsNullOrEmpty($ExpectedPublisher)) { - if ((Get-FileHash -LiteralPath $trustedPath -Algorithm SHA256).Hash -cne - $ExpectedSha256) { - throw "$Label does not match the pinned SHA-256 digest." - } - } else { - Assert-ApprovedAuthenticodeFile ` - $trustedPath $Label $ExpectedSha256 $ExpectedPublisher ` - -AllowCatalog:$AllowCatalog - } - return $trustedPath -} - -function Open-WagglePortableToolchainReceipt { - param( - [Parameter(Mandatory = $true)] [string]$Root, - [Parameter(Mandatory = $true)] [string]$ReceiptPath, - [Parameter(Mandatory = $true)] [string]$ReceiptSha256, - [string[]]$DisallowedRoots = @() - ) - - if ($ReceiptSha256 -notmatch '^[0-9A-Fa-f]{64}$') { - throw 'Portable signing toolchain receipt SHA-256 is invalid.' - } - $trustedRoot = Assert-PrivateDirectoryAcl $Root 'Portable signing toolchain root' - $trustedReceipt = Get-TrustedPath $ReceiptPath 'Portable signing toolchain receipt' - if (Test-WagglePathsOverlap $trustedRoot $trustedReceipt) { - throw 'Portable signing toolchain receipt must be outside its toolchain root.' - } - foreach ($disallowedRoot in @($DisallowedRoots | Where-Object { - -not [string]::IsNullOrWhiteSpace([string]$_) - })) { - if (Test-WagglePathsOverlap $trustedReceipt ([string]$disallowedRoot)) { - throw 'Portable signing toolchain receipt overlaps a protected signing boundary.' - } - } - $locks = [Collections.Generic.List[IDisposable]]::new() - try { - $receiptLock = Open-ReadLock $trustedReceipt - $locks.Add($receiptLock) - if (-not [string]::Equals( - (Get-FileHash -LiteralPath $trustedReceipt -Algorithm SHA256).Hash, - $ReceiptSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Portable signing toolchain receipt does not match its handoff SHA-256.' - } - try { - $receipt = Get-Content -Raw -LiteralPath $trustedReceipt | - ConvertFrom-Json -Depth 32 -DateKind String - } catch { - throw 'Portable signing toolchain receipt is not valid JSON.' - } - if ([int](Get-RequiredPropertyValue ` - $receipt 'schemaVersion' 'Portable signing toolchain receipt') -ne 1) { - throw 'Portable signing toolchain receipt schemaVersion must be 1.' - } - Assert-ExactCanonicalPathValue ` - ([string](Get-RequiredPropertyValue ` - $receipt 'portableToolchainRoot' 'Portable signing toolchain receipt')) ` - $trustedRoot 'Portable signing toolchain receipt root' - - $archives = Get-RequiredPropertyValue ` - $receipt 'archives' 'Portable signing toolchain receipt' - $archiveBindings = @( - @('node', $NodeArchiveSha256), - @('git', $GitArchiveSha256), - @('sevenZip', $SevenZipArchiveSha256) - ) - $archivePaths = [Collections.Generic.HashSet[string]]::new( - [StringComparer]::OrdinalIgnoreCase - ) - foreach ($binding in $archiveBindings) { - $archive = Get-RequiredPropertyValue ` - $archives ([string]$binding[0]) 'Portable toolchain archives' - $archivePath = Get-TrustedPath ` - ([string](Get-RequiredPropertyValue ` - $archive 'path' 'Portable toolchain vendor archive')) ` - 'Portable toolchain vendor archive' - $archiveHash = [string](Get-RequiredPropertyValue ` - $archive 'sha256' 'Portable toolchain vendor archive') - if ($archiveHash -cne [string]$binding[1] -or - -not $archivePaths.Add($archivePath) -or - (Test-WagglePathsOverlap $trustedRoot $archivePath) -or - [string]::Equals( - $trustedReceipt, $archivePath, [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Portable toolchain vendor archives are not the exact distinct repository-pinned handoff.' - } - foreach ($disallowedRoot in @($DisallowedRoots | Where-Object { - -not [string]::IsNullOrWhiteSpace([string]$_) - })) { - if (Test-WagglePathsOverlap $archivePath ([string]$disallowedRoot)) { - throw 'Portable toolchain vendor archive overlaps a protected signing boundary.' - } - } - $archiveLock = Open-ReadLock $archivePath - if ((Get-FileHash -LiteralPath $archivePath -Algorithm SHA256).Hash -cne - $archiveHash) { - $archiveLock.Dispose() - throw 'Portable toolchain vendor archive does not match its pinned SHA-256.' - } - $locks.Add($archiveLock) - } - - $inventory = Get-RequiredPropertyValue ` - $receipt 'inventory' 'Portable signing toolchain receipt' - $inventoryEntries = @((Get-RequiredPropertyValue ` - $inventory 'entries' 'Portable signing toolchain inventory')) - $inventoryHash = [string](Get-RequiredPropertyValue ` - $inventory 'sha256' 'Portable signing toolchain inventory') - if ($inventoryEntries.Count -ne $PortableToolchainFileCount -or - $inventoryHash -cne $PortableToolchainInventorySha256) { - throw 'Portable signing toolchain inventory does not match the repository-pinned full closure.' - } - $treeLease = Open-WaggleValidatedPrebuiltTree ` - $trustedRoot $inventory 'Portable signing toolchain full closure' ` - ($DisallowedRoots + @($trustedReceipt) + @($archivePaths)) - foreach ($treeLock in $treeLease.Locks) { $locks.Add($treeLock) } - $treeLease.Locks.Clear() - return [pscustomobject]@{ - Receipt = $receipt - ReceiptPath = $trustedReceipt - ReceiptSha256 = $ReceiptSha256.ToUpperInvariant() - Inventory = $inventory - InventorySha256 = $inventoryHash - Locks = $locks - } - } catch { - foreach ($lock in $locks) { $lock.Dispose() } - throw - } -} - -function Get-WagglePortableToolchain { - param( - [Parameter(Mandatory = $true)] [string]$Root, - [Parameter(Mandatory = $true)] [string]$Node, - [Parameter(Mandatory = $true)] [string]$Git, - [Parameter(Mandatory = $true)] [string]$SevenZip, - [Parameter(Mandatory = $true)] [string]$ReceiptPath, - [Parameter(Mandatory = $true)] [string]$ReceiptSha256, - [string[]]$DisallowedRoots = @() - ) - - $trustedRoot = Assert-PrivateDirectoryAcl $Root 'Portable signing toolchain root' - foreach ($disallowedRoot in @($DisallowedRoots | Where-Object { - -not [string]::IsNullOrWhiteSpace([string]$_) - })) { - if (Test-WagglePathsOverlap $trustedRoot ([string]$disallowedRoot)) { - throw 'Portable signing toolchain root overlaps a repository, prebuilt, receipt, or signing-temp boundary.' - } - } - - $receiptLease = Open-WagglePortableToolchainReceipt ` - $trustedRoot $ReceiptPath $ReceiptSha256 -DisallowedRoots $DisallowedRoots - $receiptLeaseTransferred = $false - try { - $rootItems = @(Get-ChildItem -LiteralPath $trustedRoot -Force -Recurse) - $rootFiles = @($rootItems | Where-Object { -not $_.PSIsContainer }) - $rootBytes = [long](($rootFiles | Measure-Object -Property Length -Sum).Sum) - if ($rootItems.Count -gt 20000 -or $rootBytes -gt 1GB) { - throw 'Portable signing toolchain root exceeds the bounded 20,000-item or 1-GiB trust envelope.' - } - foreach ($item in $rootItems) { - $linkProperty = $item.PSObject.Properties['LinkType'] - $linkType = if ($null -eq $linkProperty) { '' } else { [string]$linkProperty.Value } - if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -or - -not [string]::IsNullOrEmpty($linkType)) { - throw 'Portable signing toolchain root contains a linked or reparse filesystem object.' - } - } - - $requestedTools = [ordered]@{ - Node = @($Node, 'Portable Node.js runtime') - Git = @($Git, 'Portable Git executable') - SevenZip = @($SevenZip, 'Portable 7-Zip inventory tool') - } - $trustedTools = @{} - $uniquePaths = [Collections.Generic.HashSet[string]]::new( - [StringComparer]::OrdinalIgnoreCase - ) - foreach ($entry in $requestedTools.GetEnumerator()) { - $trustedPath = Get-TrustedPath ([string]$entry.Value[0]) ([string]$entry.Value[1]) - $relativePath = Get-ContainedRelativePath $trustedPath $trustedRoot - if ([string]::IsNullOrEmpty($relativePath)) { - throw "$($entry.Value[1]) must be a regular non-reparse file contained by the private portable toolchain root." - } - if (-not $uniquePaths.Add($trustedPath)) { - throw 'Portable signing tool paths must be distinct regular files.' - } - $trustedTools[[string]$entry.Key] = $trustedPath - } - - $sevenZipDll = Get-TrustedPath ` - (Join-Path (Split-Path $trustedTools.SevenZip -Parent) '7z.dll') ` - 'Portable 7-Zip runtime library' - $sevenZipDllRelative = Get-ContainedRelativePath $sevenZipDll $trustedRoot - if ([string]::IsNullOrEmpty($sevenZipDllRelative) -or - -not $uniquePaths.Add($sevenZipDll)) { - throw 'Portable 7-Zip runtime library must be a distinct regular file contained by the private portable toolchain root.' - } - $gitRuntime = Get-TrustedPath ` - (Join-Path (Split-Path (Split-Path $trustedTools.Git -Parent) -Parent) ` - 'mingw64\bin\git.exe') ` - 'Portable Git runtime' - $gitRuntimeRelative = Get-ContainedRelativePath $gitRuntime $trustedRoot - if ([string]::IsNullOrEmpty($gitRuntimeRelative) -or - -not $uniquePaths.Add($gitRuntime)) { - throw 'Portable Git runtime must be a distinct regular file contained by the private portable toolchain root.' - } - - $trustedTools.Node = Assert-WagglePinnedToolFile ` - $trustedTools.Node 'Portable Node.js runtime' $NodeSha256 $NodePublisher - $trustedTools.Git = Assert-WagglePinnedToolFile ` - $trustedTools.Git 'Portable Git executable' $GitSha256 $GitPublisher - $gitRuntime = Assert-WagglePinnedToolFile ` - $gitRuntime 'Portable Git runtime' $GitRuntimeSha256 $GitPublisher - $trustedTools.SevenZip = Assert-WagglePinnedToolFile ` - $trustedTools.SevenZip 'Portable 7-Zip inventory tool' $SevenZipSha256 $null - $sevenZipDll = Assert-WagglePinnedToolFile ` - $sevenZipDll 'Portable 7-Zip runtime library' $SevenZipDllSha256 $null - - $result = [pscustomobject]@{ - PortableToolchainRoot = $trustedRoot - NodePath = $trustedTools.Node - GitPath = $trustedTools.Git - GitRuntimePath = $gitRuntime - SevenZipPath = $trustedTools.SevenZip - SevenZipDllPath = $sevenZipDll - ReceiptPath = $receiptLease.ReceiptPath - ReceiptSha256 = $receiptLease.ReceiptSha256 - InventorySha256 = $receiptLease.InventorySha256 - Locks = $receiptLease.Locks - } - $receiptLeaseTransferred = $true - return $result - } finally { - if (-not $receiptLeaseTransferred) { - foreach ($lock in $receiptLease.Locks) { $lock.Dispose() } - } - } -} - -function Get-WaggleSigningToolchain { - param( - [string[]]$DisallowedRoots = @(), - [switch]$AllowPortableBeforeManifest - ) - - $portableValues = [ordered]@{ - Root = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_TOOLCHAIN_ROOT') - Node = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_NODE_PATH') - Git = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_GIT_PATH') - SevenZip = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_SEVEN_ZIP_PATH') - Receipt = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_RECEIPT_PATH') - ReceiptSha256 = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_RECEIPT_SHA256') - } - $providedCount = @($portableValues.Values | Where-Object { - -not [string]::IsNullOrWhiteSpace([string]$_) - }).Count - if ($providedCount -ne 0) { - if ($providedCount -ne $portableValues.Count) { - throw 'Portable signing toolchain environment must provide the exact root, Node, Git, 7-Zip, receipt path, and receipt SHA-256.' - } - if (-not $AllowPortableBeforeManifest -and - ([Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_PATH') -notmatch - '^[A-Za-z]:[\\/]' -or - [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_SHA256') -notmatch - '^[0-9A-Fa-f]{64}$')) { - throw 'Portable signing tools are valid only inside an active receipt-bound signing session.' - } - return Get-WagglePortableToolchain ` - $portableValues.Root $portableValues.Node $portableValues.Git ` - $portableValues.SevenZip $portableValues.Receipt ` - $portableValues.ReceiptSha256 -DisallowedRoots $DisallowedRoots - } - - $systemNode = Assert-WagglePinnedToolFile ` - $NodePath 'Node.js runtime' $NodeSha256 $NodePublisher -AllowHardLink - $systemGit = Assert-WagglePinnedToolFile ` - $GitPath 'Git executable' $GitSha256 $GitPublisher -AllowHardLink - $systemGitRuntime = Assert-WagglePinnedToolFile ` - (Join-Path (Split-Path (Split-Path $systemGit -Parent) -Parent) ` - 'mingw64\bin\git.exe') ` - 'Git runtime' $GitRuntimeSha256 $GitPublisher -AllowHardLink - $systemSevenZip = Assert-WagglePinnedToolFile ` - $SevenZipPath '7-Zip inventory tool' $SevenZipSha256 $null - $systemSevenZipDll = Assert-WagglePinnedToolFile ` - (Join-Path (Split-Path $systemSevenZip -Parent) '7z.dll') ` - '7-Zip runtime library' $SevenZipDllSha256 $null - return [pscustomobject]@{ - PortableToolchainRoot = $null - NodePath = $systemNode - GitPath = $systemGit - GitRuntimePath = $systemGitRuntime - SevenZipPath = $systemSevenZip - SevenZipDllPath = $systemSevenZipDll - ReceiptPath = $null - ReceiptSha256 = $null - InventorySha256 = $null - Locks = [Collections.Generic.List[IDisposable]]::new() - } -} - -function Assert-WagglePortableToolchainEnvironment { - param([Parameter(Mandatory = $true)] [object]$Context) - - if ($null -eq $Context.PortableToolchainRoot) { return } - foreach ($binding in @( - @('WAGGLE_SIGNING_PORTABLE_TOOLCHAIN_ROOT', $Context.PortableToolchainRoot), - @('WAGGLE_SIGNING_PORTABLE_NODE_PATH', $Context.NodePath), - @('WAGGLE_SIGNING_PORTABLE_GIT_PATH', $Context.GitPath), - @('WAGGLE_SIGNING_PORTABLE_SEVEN_ZIP_PATH', $Context.SevenZipPath), - @('WAGGLE_SIGNING_PORTABLE_RECEIPT_PATH', $Context.PortableToolchainReceiptPath) - )) { - Assert-ExactCanonicalPathValue ` - ([Environment]::GetEnvironmentVariable([string]$binding[0])) ` - ([string]$binding[1]) ([string]$binding[0]) - } - if ([Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_RECEIPT_SHA256') -cne - $Context.PortableToolchainReceiptSha256) { - throw 'WAGGLE_SIGNING_PORTABLE_RECEIPT_SHA256 does not match the signing session.' - } -} - -function Assert-WagglePortableSessionBootstrap { - param( - [Parameter(Mandatory = $true)] [object]$Toolchain, - [Parameter(Mandatory = $true)] [string]$RepoRoot, - [Parameter(Mandatory = $true)] [string]$TauriRoot - ) - - if ($null -eq $Toolchain.PortableToolchainRoot) { return } - $sessionId = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_SESSION_ID') - $manifestPathValue = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_PATH') - $manifestSha256 = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_SHA256') - if ($sessionId -notmatch '^[0-9a-f]{32}$' -or - $manifestSha256 -notmatch '^[0-9A-Fa-f]{64}$') { - throw 'Portable signing callback is not inside an active receipt-bound signing session.' - } - $sessionDirectory = Assert-PrivateDirectoryAcl ` - (Join-Path $TauriRoot "target\.signing-sessions\run-$sessionId") ` - 'Portable signing callback session directory' - $expectedManifestPath = Join-Path $sessionDirectory 'manifest.json' - Assert-ExactCanonicalPathValue ` - $manifestPathValue $expectedManifestPath 'Portable signing callback manifest path' - $manifestPath = Get-TrustedPath $manifestPathValue 'Portable signing callback manifest' - $lock = Open-ReadLock $manifestPath - try { - if ((Get-FileHash -LiteralPath $manifestPath -Algorithm SHA256).Hash -cne - $manifestSha256.ToUpperInvariant()) { - throw 'Portable signing callback manifest does not match its session digest.' - } - try { - $manifest = Get-Content -Raw -LiteralPath $manifestPath | - ConvertFrom-Json -Depth 32 -DateKind String - } catch { - throw 'Portable signing callback manifest is not valid JSON.' - } - if ([int](Get-RequiredPropertyValue $manifest 'schemaVersion' 'Signing manifest') -ne 1 -or - [string](Get-RequiredPropertyValue $manifest 'mode' 'Signing manifest') -cne 'nsis' -or - [string](Get-RequiredPropertyValue $manifest 'sessionId' 'Signing manifest') -cne $sessionId) { - throw 'Portable signing callback manifest does not bind the active NSIS session.' - } - Assert-ExactCanonicalPathValue ` - ([string](Get-RequiredPropertyValue $manifest 'repoRoot' 'Signing manifest')) ` - $RepoRoot 'Portable signing callback repository root' - $sourceRevision = [string](Get-RequiredPropertyValue ` - $manifest 'sourceRevision' 'Signing manifest') - $receipt = Get-RequiredPropertyValue ` - $manifest 'buildReceipt' 'Receipt-bound signing manifest' - if ($sourceRevision -notmatch '^[0-9a-f]{40}$' -or - [int](Get-RequiredPropertyValue $receipt 'schemaVersion' 'Hosted build receipt') -ne 1 -or - [string](Get-RequiredPropertyValue $receipt 'repository' 'Hosted build receipt') -cne - 'marolinik/waggle-os' -or - [string](Get-RequiredPropertyValue $receipt 'sourceRevision' 'Hosted build receipt') -cne - $sourceRevision -or - [string](Get-RequiredPropertyValue $receipt 'targetTriple' 'Hosted build receipt') -cne - 'x86_64-pc-windows-msvc') { - throw 'Portable signing callback manifest is not bound to the approved hosted receipt.' - } - $manifestToolchain = Get-RequiredPropertyValue $manifest 'toolchain' 'Signing manifest' - foreach ($binding in @( - @('portableToolchainRoot', $Toolchain.PortableToolchainRoot), - @('nodePath', $Toolchain.NodePath), - @('gitPath', $Toolchain.GitPath), - @('gitRuntimePath', $Toolchain.GitRuntimePath), - @('sevenZipPath', $Toolchain.SevenZipPath), - @('sevenZipDllPath', $Toolchain.SevenZipDllPath), - @('portableToolchainReceiptPath', $Toolchain.ReceiptPath) - )) { - Assert-ExactCanonicalPathValue ` - ([string](Get-RequiredPropertyValue ` - $manifestToolchain ([string]$binding[0]) 'Signing manifest toolchain')) ` - ([string]$binding[1]) "Portable signing callback $($binding[0])" - } - foreach ($binding in @( - @('nodeSha256', $NodeSha256), - @('gitSha256', $GitSha256), - @('gitRuntimeSha256', $GitRuntimeSha256), - @('sevenZipSha256', $SevenZipSha256), - @('sevenZipDllSha256', $SevenZipDllSha256), - @('portableToolchainReceiptSha256', $Toolchain.ReceiptSha256), - @('portableToolchainInventorySha256', $PortableToolchainInventorySha256) - )) { - if ([string](Get-RequiredPropertyValue ` - $manifestToolchain ([string]$binding[0]) 'Signing manifest toolchain') -cne - [string]$binding[1]) { - throw "Portable signing callback $($binding[0]) is not repository-pinned." - } - } - if ([int](Get-RequiredPropertyValue ` - $manifestToolchain 'portableToolchainFileCount' 'Signing manifest toolchain') -ne - $PortableToolchainFileCount) { - throw 'Portable signing callback full closure file count is not repository-pinned.' - } - } finally { - $lock.Dispose() - } -} - -function Get-WaggleSigningContext { - param([switch]$AllowPortableBeforeManifest) - - $sessionId = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_SESSION_ID') - if ($sessionId -notmatch '^[0-9a-f]{32}$') { - throw 'WAGGLE_SIGNING_SESSION_ID must be one lowercase 128-bit session id.' - } - $scriptPath = Get-TrustedPath $PSCommandPath 'Signing wrapper' - $appRoot = Split-Path (Split-Path $scriptPath -Parent) -Parent - $repoRoot = Get-TrustedPath (Split-Path $appRoot -Parent) 'Repository root' 'Container' - $tauriRoot = Get-TrustedPath (Join-Path $appRoot 'src-tauri') 'Tauri root' 'Container' - $resourcesRootValue = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_RESOURCES_ROOT') - if ([string]::IsNullOrWhiteSpace($resourcesRootValue)) { - throw 'WAGGLE_SIGNING_RESOURCES_ROOT must identify the receipt-bound resource tree.' - } - $resourcesRoot = Get-TrustedPath $resourcesRootValue 'Tauri resources root' 'Container' - $cargoTargetRoot = [Environment]::GetEnvironmentVariable('CARGO_TARGET_DIR') - if ([string]::IsNullOrWhiteSpace($cargoTargetRoot)) { - throw 'CARGO_TARGET_DIR must identify the isolated signing package root.' - } - $targetRoot = Assert-PrivateDirectoryAcl $cargoTargetRoot 'Signing package target root' - $releaseRoot = Get-TrustedPath ` - (Join-Path $targetRoot 'x86_64-pc-windows-msvc\release') ` - 'Tauri release root' 'Container' - $configPath = Get-TrustedPath (Join-Path $tauriRoot 'tauri.conf.json') 'Tauri config' - $sessionDirectory = Join-Path ` - (Join-Path $tauriRoot 'target\.signing-sessions') ` - "run-$sessionId" - $overrideConfigPath = Get-TrustedPath ` - (Join-Path $sessionDirectory 'tauri.signing-override.json') ` - 'Tauri signing override config' - $tauriCliPath = Get-TrustedPath ` - (Join-Path $appRoot 'node_modules\@tauri-apps\cli\tauri.js') ` - 'Tauri CLI' - $tauriCliPackagePath = Get-TrustedPath ` - (Join-Path $appRoot 'node_modules\@tauri-apps\cli\package.json') ` - 'Tauri CLI package manifest' - $tauriCliMainPath = Get-TrustedPath ` - (Join-Path $appRoot 'node_modules\@tauri-apps\cli\main.js') ` - 'Tauri CLI main module' - $tauriCliIndexPath = Get-TrustedPath ` - (Join-Path $appRoot 'node_modules\@tauri-apps\cli\index.js') ` - 'Tauri CLI native loader' - $tauriNativePackagePath = Get-TrustedPath ` - (Join-Path $appRoot 'node_modules\@tauri-apps\cli-win32-x64-msvc\package.json') ` - 'Tauri native package manifest' - $tauriNativeBinaryPath = Get-TrustedPath ` - (Join-Path $appRoot 'node_modules\@tauri-apps\cli-win32-x64-msvc\cli.win32-x64-msvc.node') ` - 'Tauri native CLI binary' - $tauriVersion = [string]( - Get-Content -Raw -LiteralPath $tauriCliPackagePath | ConvertFrom-Json - ).version - if ($tauriVersion -cne $TauriCliVersion) { - throw "Tauri CLI must be the pinned version $TauriCliVersion." - } - $tauriNativeVersion = [string]( - Get-Content -Raw -LiteralPath $tauriNativePackagePath | ConvertFrom-Json - ).version - if ($tauriNativeVersion -cne $TauriCliVersion) { - throw "Tauri native CLI must be the pinned version $TauriCliVersion." - } - $makensisPath = Get-TrustedPath ` - (Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'tauri\NSIS\Bin\makensis.exe') ` - 'makensis' - $nsisRoot = Get-TrustedPath ` - (Split-Path (Split-Path $makensisPath -Parent) -Parent) ` - 'NSIS compiler root' 'Container' - $toolchain = Get-WaggleSigningToolchain ` - -DisallowedRoots @( - $repoRoot, $targetRoot, $resourcesRoot, - [Environment]::GetEnvironmentVariable('TEMP'), - [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_PATH') - ) ` - -AllowPortableBeforeManifest:$AllowPortableBeforeManifest - if (-not $AllowPortableBeforeManifest) { - Assert-WagglePortableSessionBootstrap $toolchain $repoRoot $tauriRoot - } - $git = $toolchain.GitPath - $gitLock = Open-ReadLock $git - try { - if ((Get-FileHash -LiteralPath $git -Algorithm SHA256).Hash -cne $GitSha256) { - throw 'Git executable does not match the pinned SHA-256 digest.' - } - $sourceRevision = [string](& $git -C $repoRoot rev-parse --verify HEAD) - if ($LASTEXITCODE -ne 0 -or $sourceRevision -notmatch '^[0-9a-f]{40}$') { - throw 'Could not resolve the exact repository source revision.' - } - $status = @(& $git -C $repoRoot status --porcelain=v1 --untracked-files=all) - if ($LASTEXITCODE -ne 0 -or $status.Count -ne 0) { - throw 'Signing requires a clean exact repository revision.' - } - } finally { - $gitLock.Dispose() - } - - return [pscustomobject]@{ - RepoRoot = $repoRoot - AppRoot = $appRoot - TauriRoot = $tauriRoot - ResourcesRoot = $resourcesRoot - TargetRoot = $targetRoot - ReleaseRoot = $releaseRoot - ConfigPath = $configPath - OverrideConfigPath = $overrideConfigPath - WrapperPath = $scriptPath - TauriCliPath = $tauriCliPath - TauriCliPackagePath = $tauriCliPackagePath - TauriCliMainPath = $tauriCliMainPath - TauriCliIndexPath = $tauriCliIndexPath - TauriNativePackagePath = $tauriNativePackagePath - TauriNativeBinaryPath = $tauriNativeBinaryPath - MakensisPath = $makensisPath - NsisRoot = $nsisRoot - GitPath = $git - GitRuntimePath = $toolchain.GitRuntimePath - PortableToolchainRoot = $toolchain.PortableToolchainRoot - PortableToolchainReceiptPath = $toolchain.ReceiptPath - PortableToolchainReceiptSha256 = $toolchain.ReceiptSha256 - PortableToolchainInventorySha256 = $toolchain.InventorySha256 - PortableToolchainLocks = $toolchain.Locks - SignToolPath = Get-TrustedPath $SignToolPath 'SignTool' -AllowHardLink - ArtifactSigningPackagePath = Get-TrustedPath ` - (Join-Path $tauriRoot 'target\.artifact-signing-tools\Microsoft.ArtifactSigning.Client.1.0.128.nupkg') ` - 'Artifact Signing package' - NodePath = $toolchain.NodePath - SevenZipPath = $toolchain.SevenZipPath - SevenZipDllPath = $toolchain.SevenZipDllPath - SourceRevision = $sourceRevision - TauriCliVersion = $TauriCliVersion - TauriCliSha256 = $TauriCliSha256 - TauriCliPackageSha256 = $TauriCliPackageSha256 - TauriCliMainSha256 = $TauriCliMainSha256 - TauriCliIndexSha256 = $TauriCliIndexSha256 - TauriNativePackageSha256 = $TauriNativePackageSha256 - TauriNativeBinarySha256 = $TauriNativeBinarySha256 - MakensisSha256 = $MakensisSha256 - NsisClosureSha256 = $NsisClosureSha256 - GitSha256 = $GitSha256 - GitRuntimeSha256 = $GitRuntimeSha256 - NodeSha256 = $NodeSha256 - SevenZipSha256 = $SevenZipSha256 - SevenZipDllSha256 = $SevenZipDllSha256 - SignToolSha256 = $SignToolSha256 - ArtifactSigningPackageSha256 = $ArtifactSigningPackageSha256 - ArtifactSigningX64ManifestSha256 = $ArtifactSigningX64ManifestSha256 - } -} - -function Get-ExpectedNsisFixedPaths { - param( - [Parameter(Mandatory = $true)] [object]$Context, - [Parameter(Mandatory = $true)] [string]$Version - ) - - return @( - Join-Path $Context.ReleaseRoot 'waggle.exe' - Join-Path $Context.ResourcesRoot 'native\vec0.dll' - Join-Path $Context.ResourcesRoot 'native\onnxruntime\onnxruntime.dll' - Join-Path $Context.ResourcesRoot 'node_modules\@img\sharp-win32-x64\lib\libvips-42.dll' - Join-Path $Context.ResourcesRoot 'node_modules\@img\sharp-win32-x64\lib\libvips-cpp-8.18.3.dll' - Join-Path $Context.ResourcesRoot 'node_modules\onnxruntime-node\bin\napi-v3\win32\x64\onnxruntime.dll' - Join-Path $Context.ResourcesRoot 'node_modules\sqlite-vec-windows-x64\vec0.dll' - Join-Path $Context.ReleaseRoot 'nsis\x64\Plugins\x86-unicode\NSISdl.dll' - Join-Path $Context.ReleaseRoot 'nsis\x64\Plugins\x86-unicode\StartMenu.dll' - Join-Path $Context.ReleaseRoot 'nsis\x64\Plugins\x86-unicode\System.dll' - Join-Path $Context.ReleaseRoot 'nsis\x64\Plugins\x86-unicode\nsDialogs.dll' - Join-Path $Context.ReleaseRoot 'nsis\x64\Plugins\x86-unicode\additional\nsis_tauri_utils.dll' - ) | ForEach-Object { [IO.Path]::GetFullPath($_) } -} - -function Get-ExpectedNsisPackagedPaths { - return @( - 'waggle.exe' - 'resources\native\vec0.dll' - 'resources\native\onnxruntime\onnxruntime.dll' - 'resources\node_modules\@img\sharp-win32-x64\lib\libvips-42.dll' - 'resources\node_modules\@img\sharp-win32-x64\lib\libvips-cpp-8.18.3.dll' - 'resources\node_modules\onnxruntime-node\bin\napi-v3\win32\x64\onnxruntime.dll' - 'resources\node_modules\sqlite-vec-windows-x64\vec0.dll' - '$PLUGINSDIR\NSISdl.dll' - '$PLUGINSDIR\StartMenu.dll' - '$PLUGINSDIR\System.dll' - '$PLUGINSDIR\nsDialogs.dll' - '$PLUGINSDIR\nsis_tauri_utils.dll' - ) -} - -function Add-ValidatedSessionFileLock { - param( - [Parameter(Mandatory = $true)] [Collections.Generic.List[IDisposable]]$Locks, - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$ExpectedSha256, - [Parameter(Mandatory = $true)] [string]$Label, - [switch]$AllowHardLink - ) - - if ($ExpectedSha256 -notmatch '^[0-9A-Fa-f]{64}$') { - throw "$Label manifest SHA-256 is invalid." - } - $trustedPath = Get-TrustedPath $Path $Label -AllowHardLink:$AllowHardLink - $lock = Open-ReadLock $trustedPath - try { - if (-not [string]::Equals( - (Get-FileHash -LiteralPath $trustedPath -Algorithm SHA256).Hash, - $ExpectedSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw "$Label does not match the signing manifest SHA-256 digest." - } - $Locks.Add($lock) - $lock = $null - } finally { - if ($null -ne $lock) { $lock.Dispose() } - } - return $trustedPath -} - -function Assert-WaggleSigningOverrideContract { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$WrapperPath, - [AllowNull()] [string]$ResourcesRoot = $null, - [switch]$Unsigned - ) - try { - $override = Get-Content -Raw -LiteralPath $Path | ConvertFrom-Json -Depth 16 - } catch { - throw 'Tauri signing override is not valid JSON.' - } - $targets = @((Get-RequiredPropertyValue ` - (Get-RequiredPropertyValue $override 'bundle' 'Tauri signing override') ` - 'targets' 'Tauri signing override bundle')) - $bundle = $override.bundle - $windows = Get-RequiredPropertyValue $bundle 'windows' 'Tauri signing override bundle' - $signCommand = $windows.PSObject.Properties['signCommand'] - $expectedArgs = @( - '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', - '-File', $WrapperPath, '-ArtifactPath', '%1' - ) - if ([bool](Get-RequiredPropertyValue $bundle 'active' 'Tauri signing override bundle') -ne $true -or - $targets.Count -ne 1 -or [string]$targets[0] -cne 'nsis' -or - [string](Get-RequiredPropertyValue ` - (Get-RequiredPropertyValue $override 'build' 'Tauri signing override') ` - 'beforeBuildCommand' 'Tauri signing override build') -cne '' -or - [string](Get-RequiredPropertyValue ` - (Get-RequiredPropertyValue $override 'build' 'Tauri signing override') ` - 'beforeBundleCommand' 'Tauri signing override build') -cne '' -or - $null -ne $windows.PSObject.Properties['certificateThumbprint'] -or - $null -ne $windows.PSObject.Properties['timestampUrl']) { - throw 'Tauri signing override must be the exact fail-closed NSIS-only callback contract.' - } - if (-not [string]::IsNullOrWhiteSpace($ResourcesRoot)) { - $resourceMap = Get-RequiredPropertyValue ` - $bundle 'resources' 'Tauri signing override bundle' - $resourceEntries = @($resourceMap.PSObject.Properties) - $trustedResourcesRoot = Get-TrustedPath ` - $ResourcesRoot 'Tauri signing override resource root' 'Container' - if ($resourceEntries.Count -ne 1 -or - -not [string]::Equals( - [IO.Path]::GetFullPath([string]$resourceEntries[0].Name), - $trustedResourcesRoot, - [StringComparison]::OrdinalIgnoreCase - ) -or - [string]$resourceEntries[0].Value -cne 'resources') { - throw 'Tauri signing override must map the exact receipt-bound resource tree.' - } - } elseif ($null -ne $bundle.PSObject.Properties['resources']) { - throw 'Tauri signing override unexpectedly contains an unbound resource map.' - } - if ($Unsigned) { - if ($null -ne $signCommand) { - throw 'Unsigned Tauri override cannot contain a signing callback.' - } - return - } - if ($null -eq $signCommand) { - throw 'Signed Tauri override must contain the signing callback.' - } - $actualCommand = $signCommand.Value - $actualArgs = @((Get-RequiredPropertyValue ` - $actualCommand 'args' 'Tauri signing override signCommand')) - if ([string](Get-RequiredPropertyValue ` - $actualCommand 'cmd' 'Tauri signing override signCommand') -cne - $SystemPowerShellPath -or - $actualArgs.Count -ne $expectedArgs.Count -or - [string]::Join("`n", $actualArgs) -cne [string]::Join("`n", $expectedArgs)) { - throw 'Tauri signing override must be the exact fail-closed NSIS-only callback contract.' - } -} - -function Get-WaggleSigningSession { - param([Parameter(Mandatory = $true)] [object]$Context) - - Assert-WagglePortableToolchainEnvironment $Context - $manifestPathValue = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_PATH') - $manifestSha256 = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_SHA256') - $sessionId = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_SESSION_ID') - if ([string]::IsNullOrWhiteSpace($manifestPathValue)) { - throw 'WAGGLE_SIGNING_MANIFEST_PATH is required for production signing.' - } - if ($manifestSha256 -notmatch '^[0-9A-Fa-f]{64}$') { - throw 'WAGGLE_SIGNING_MANIFEST_SHA256 must be one exact SHA-256 digest.' - } - if ($sessionId -notmatch '^[0-9a-f]{32}$') { - throw 'WAGGLE_SIGNING_SESSION_ID must be one lowercase 128-bit session id.' - } - - $sessionDirectory = Join-Path ` - (Join-Path $Context.TauriRoot 'target\.signing-sessions') ` - "run-$sessionId" - $expectedManifestPath = Join-Path $sessionDirectory 'manifest.json' - Assert-ExactCanonicalPathValue ` - $manifestPathValue $expectedManifestPath 'Signing manifest path' - $sessionDirectory = Assert-PrivateDirectoryAcl $sessionDirectory 'Signing session directory' - $manifestPath = Get-TrustedPath $manifestPathValue 'Signing manifest' - - $locks = [Collections.Generic.List[IDisposable]]::new() - $portableLocksProperty = $Context.PSObject.Properties['PortableToolchainLocks'] - if ($null -ne $portableLocksProperty -and $null -ne $portableLocksProperty.Value) { - foreach ($portableLock in @($portableLocksProperty.Value)) { - $locks.Add($portableLock) - } - $portableLocksProperty.Value.Clear() - } - try { - $manifestLock = Open-ReadLock $manifestPath - $locks.Add($manifestLock) - if (-not [string]::Equals( - (Get-FileHash -LiteralPath $manifestPath -Algorithm SHA256).Hash, - $manifestSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Signing manifest does not match WAGGLE_SIGNING_MANIFEST_SHA256.' - } - try { - $manifest = Get-Content -Raw -LiteralPath $manifestPath | - ConvertFrom-Json -Depth 32 -DateKind String - } catch { - throw 'Signing manifest is not valid JSON.' - } - - if ([int](Get-RequiredPropertyValue $manifest 'schemaVersion' 'Signing manifest') -ne 1) { - throw 'Signing manifest schemaVersion must be 1.' - } - if ([string](Get-RequiredPropertyValue $manifest 'mode' 'Signing manifest') -cne 'nsis') { - throw 'Production signing is NSIS-only.' - } - if ([string](Get-RequiredPropertyValue $manifest 'sessionId' 'Signing manifest') -cne $sessionId) { - throw 'Signing manifest session id does not match WAGGLE_SIGNING_SESSION_ID.' - } - if ([string](Get-RequiredPropertyValue $manifest 'sourceRevision' 'Signing manifest') -cne - [string]$Context.SourceRevision) { - throw 'Signing manifest source revision does not match the clean repository HEAD.' - } - if ($null -ne $Context.PortableToolchainRoot) { - $buildReceipt = Get-RequiredPropertyValue ` - $manifest 'buildReceipt' 'Receipt-bound signing manifest' - if ([int](Get-RequiredPropertyValue $buildReceipt 'schemaVersion' 'Hosted build receipt') -ne 1 -or - [string](Get-RequiredPropertyValue $buildReceipt 'repository' 'Hosted build receipt') -cne - 'marolinik/waggle-os' -or - [string](Get-RequiredPropertyValue $buildReceipt 'sourceRevision' 'Hosted build receipt') -cne - [string]$Context.SourceRevision -or - [string](Get-RequiredPropertyValue $buildReceipt 'targetTriple' 'Hosted build receipt') -cne - 'x86_64-pc-windows-msvc') { - throw 'Portable signing callback is not bound to the approved hosted build receipt.' - } - } - - $createdAt = [DateTimeOffset]::MinValue - $expiresAt = [DateTimeOffset]::MinValue - if (-not [DateTimeOffset]::TryParseExact( - [string](Get-RequiredPropertyValue $manifest 'createdAtUtc' 'Signing manifest'), - 'O', - [Globalization.CultureInfo]::InvariantCulture, - [Globalization.DateTimeStyles]::AssumeUniversal, - [ref]$createdAt - ) -or - -not [DateTimeOffset]::TryParseExact( - [string](Get-RequiredPropertyValue $manifest 'expiresAtUtc' 'Signing manifest'), - 'O', - [Globalization.CultureInfo]::InvariantCulture, - [Globalization.DateTimeStyles]::AssumeUniversal, - [ref]$expiresAt - )) { - throw 'Signing manifest timestamps must use the round-trip UTC format.' - } - $now = [DateTimeOffset]::UtcNow - if ($createdAt -gt $now.AddMinutes(5) -or - $expiresAt -le $now -or - $expiresAt -le $createdAt -or - $expiresAt -gt $createdAt.AddHours(4)) { - throw 'Signing manifest is expired or outside the four-hour signing window.' - } - - Assert-ExactCanonicalPathValue ` - ([string](Get-RequiredPropertyValue $manifest 'repoRoot' 'Signing manifest')) ` - $Context.RepoRoot 'Signing manifest repository root' - Assert-ExactCanonicalPathValue ` - ([string](Get-RequiredPropertyValue $manifest 'tauriRoot' 'Signing manifest')) ` - $Context.TauriRoot 'Signing manifest Tauri root' - Assert-ExactCanonicalPathValue ` - ([string](Get-RequiredPropertyValue $manifest 'releaseRoot' 'Signing manifest')) ` - $Context.ReleaseRoot 'Signing manifest release root' - Assert-ExactCanonicalPathValue ` - ([string](Get-RequiredPropertyValue $manifest 'resourcesRoot' 'Signing manifest')) ` - $Context.ResourcesRoot 'Signing manifest resources root' - Assert-ExactCanonicalPathValue ` - ([string](Get-RequiredPropertyValue $manifest 'targetRoot' 'Signing manifest')) ` - $Context.TargetRoot 'Signing manifest target root' - - $expectedTempRoot = Join-Path ` - (Join-Path $Context.TauriRoot 'target\.signing-temp') ` - "run-$sessionId" - $tempRootValue = [string](Get-RequiredPropertyValue $manifest 'tempRoot' 'Signing manifest') - Assert-ExactCanonicalPathValue $tempRootValue $expectedTempRoot 'Signing manifest session temp root' - $tempRoot = Assert-PrivateDirectoryAcl $tempRootValue 'Signing session temp root' - foreach ($name in @('TEMP', 'TMP', 'WAGGLE_NSIS_SIGNING_TEMP_ROOT')) { - $environmentPath = [Environment]::GetEnvironmentVariable($name) - if ([string]::IsNullOrWhiteSpace($environmentPath)) { - throw "$name must identify the signing session temp root." - } - Assert-ExactCanonicalPathValue $environmentPath $tempRoot "$name path" - } - - $expectedLedgerPath = Join-Path $sessionDirectory 'callback-ledger.json' - $ledgerPathValue = [string](Get-RequiredPropertyValue $manifest 'ledgerPath' 'Signing manifest') - Assert-ExactCanonicalPathValue $ledgerPathValue $expectedLedgerPath 'Signing callback ledger path' - $ledgerPath = Get-TrustedPath $ledgerPathValue 'Signing callback ledger' - - $config = Get-Content -Raw -LiteralPath $Context.ConfigPath | ConvertFrom-Json - $version = [string]$config.version - if ($version -notmatch '^\d+\.\d+\.\d+$' -or - [string](Get-RequiredPropertyValue $manifest 'appVersion' 'Signing manifest') -cne $version) { - throw 'Signing manifest app version does not match tauri.conf.json.' - } - - $toolchain = Get-RequiredPropertyValue $manifest 'toolchain' 'Signing manifest' - $toolBindings = @( - @('wrapperPath', 'wrapperSha256', $Context.WrapperPath, $null, 'Signing wrapper', $false), - @('tauriConfigPath', 'tauriConfigSha256', $Context.ConfigPath, $null, 'Tauri config', $false), - @('tauriOverrideConfigPath', 'tauriOverrideConfigSha256', $Context.OverrideConfigPath, $null, 'Tauri signing override config', $false), - @('tauriCliPath', 'tauriCliSha256', $Context.TauriCliPath, $Context.TauriCliSha256, 'Tauri CLI', $false), - @('tauriCliPackagePath', 'tauriCliPackageSha256', $Context.TauriCliPackagePath, $Context.TauriCliPackageSha256, 'Tauri CLI package manifest', $false), - @('tauriCliMainPath', 'tauriCliMainSha256', $Context.TauriCliMainPath, $Context.TauriCliMainSha256, 'Tauri CLI main module', $false), - @('tauriCliIndexPath', 'tauriCliIndexSha256', $Context.TauriCliIndexPath, $Context.TauriCliIndexSha256, 'Tauri CLI native loader', $false), - @('tauriNativePackagePath', 'tauriNativePackageSha256', $Context.TauriNativePackagePath, $Context.TauriNativePackageSha256, 'Tauri native package manifest', $false), - @('tauriNativeBinaryPath', 'tauriNativeBinarySha256', $Context.TauriNativeBinaryPath, $Context.TauriNativeBinarySha256, 'Tauri native CLI binary', $false), - @('makensisPath', 'makensisSha256', $Context.MakensisPath, $Context.MakensisSha256, 'makensis', $false), - @('gitPath', 'gitSha256', $Context.GitPath, $Context.GitSha256, 'Git executable', $true), - @('gitRuntimePath', 'gitRuntimeSha256', $Context.GitRuntimePath, $Context.GitRuntimeSha256, 'Git runtime', $true), - @('nodePath', 'nodeSha256', $Context.NodePath, $Context.NodeSha256, 'Node.js runtime', $true), - @('sevenZipPath', 'sevenZipSha256', $Context.SevenZipPath, $Context.SevenZipSha256, '7-Zip inventory tool', $false), - @('signToolPath', 'signToolSha256', $Context.SignToolPath, $Context.SignToolSha256, 'SignTool', $true), - @('artifactSigningPackagePath', 'artifactSigningPackageSha256', $Context.ArtifactSigningPackagePath, $Context.ArtifactSigningPackageSha256, 'Artifact Signing package', $false) - ) - foreach ($binding in $toolBindings) { - $manifestToolPath = [string](Get-RequiredPropertyValue $toolchain $binding[0] 'Signing manifest toolchain') - $manifestToolHash = [string](Get-RequiredPropertyValue $toolchain $binding[1] 'Signing manifest toolchain') - Assert-ExactCanonicalPathValue $manifestToolPath ([string]$binding[2]) "$($binding[4]) path" - if ($null -ne $binding[3] -and $manifestToolHash -cne [string]$binding[3]) { - throw "$($binding[4]) manifest SHA-256 is not the repository-pinned digest." - } - Add-ValidatedSessionFileLock ` - $locks ([string]$binding[2]) $manifestToolHash ([string]$binding[4]) ` - -AllowHardLink:([bool]$binding[5]) | Out-Null - } - if ($null -ne $Context.PortableToolchainRoot) { - Assert-ExactCanonicalPathValue ` - ([string](Get-RequiredPropertyValue ` - $toolchain 'portableToolchainRoot' 'Signing manifest toolchain')) ` - $Context.PortableToolchainRoot 'Portable signing toolchain root' - $sevenZipDllPath = [string](Get-RequiredPropertyValue ` - $toolchain 'sevenZipDllPath' 'Signing manifest toolchain') - $sevenZipDllHash = [string](Get-RequiredPropertyValue ` - $toolchain 'sevenZipDllSha256' 'Signing manifest toolchain') - Assert-ExactCanonicalPathValue ` - $sevenZipDllPath $Context.SevenZipDllPath '7-Zip runtime library path' - if ($sevenZipDllHash -cne $Context.SevenZipDllSha256) { - throw '7-Zip runtime library manifest SHA-256 is not the repository-pinned digest.' - } - Add-ValidatedSessionFileLock ` - $locks $Context.SevenZipDllPath $sevenZipDllHash ` - '7-Zip runtime library' | Out-Null - Assert-ExactCanonicalPathValue ` - ([string](Get-RequiredPropertyValue ` - $toolchain 'portableToolchainReceiptPath' 'Signing manifest toolchain')) ` - $Context.PortableToolchainReceiptPath ` - 'Portable signing toolchain receipt path' - if ([string](Get-RequiredPropertyValue ` - $toolchain 'portableToolchainReceiptSha256' 'Signing manifest toolchain') -cne - $Context.PortableToolchainReceiptSha256 -or - [string](Get-RequiredPropertyValue ` - $toolchain 'portableToolchainInventorySha256' 'Signing manifest toolchain') -cne - $PortableToolchainInventorySha256 -or - [int](Get-RequiredPropertyValue ` - $toolchain 'portableToolchainFileCount' 'Signing manifest toolchain') -ne - $PortableToolchainFileCount) { - throw 'Portable signing toolchain manifest does not bind the repository-pinned full closure.' - } - } - if ([string](Get-RequiredPropertyValue $toolchain 'tauriCliVersion' 'Signing manifest toolchain') -cne - [string]$Context.TauriCliVersion) { - throw 'Signing manifest Tauri CLI version is not the repository-pinned version.' - } - if ([string](Get-RequiredPropertyValue $toolchain 'artifactSigningX64ManifestSha256' 'Signing manifest toolchain') -cne - [string]$Context.ArtifactSigningX64ManifestSha256) { - throw 'Signing manifest Artifact Signing x64 closure digest is not repository-pinned.' - } - Assert-WaggleSigningOverrideContract ` - $Context.OverrideConfigPath $Context.WrapperPath $Context.ResourcesRoot - - $payloads = @((Get-RequiredPropertyValue $manifest 'payloads' 'Signing manifest')) - $uniquePayloadPaths = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) - foreach ($payload in $payloads) { - $payloadPath = [string](Get-RequiredPropertyValue $payload 'path' 'Signing manifest payload') - $payloadHash = [string](Get-RequiredPropertyValue $payload 'sha256' 'Signing manifest payload') - $payloadSize = [long](Get-RequiredPropertyValue $payload 'size' 'Signing manifest payload') - if ([string]::IsNullOrWhiteSpace($payloadPath) -or - -not $uniquePayloadPaths.Add($payloadPath) -or - $payloadHash -notmatch '^[0-9A-Fa-f]{64}$' -or $payloadSize -lt 0) { - throw 'Signing manifest NSIS payload digest inventory is invalid.' - } - } - if ($payloads.Count -lt 10 -or -not $uniquePayloadPaths.Contains('waggle.exe')) { - throw 'Signing manifest NSIS payload inventory is invalid or incomplete.' - } - - $expectedFixedPaths = @(Get-ExpectedNsisFixedPaths $Context $version) - $expectedPackagedPaths = @(Get-ExpectedNsisPackagedPaths) - $expectedFixedSet = [Collections.Generic.HashSet[string]]::new( - [StringComparer]::OrdinalIgnoreCase - ) - foreach ($expectedPath in $expectedFixedPaths) { [void]$expectedFixedSet.Add($expectedPath) } - $seenFixedSet = [Collections.Generic.HashSet[string]]::new( - [StringComparer]::OrdinalIgnoreCase - ) - $seenIds = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) - $seenOrders = [Collections.Generic.HashSet[int]]::new() - $slots = @((Get-RequiredPropertyValue $manifest 'slots' 'Signing manifest')) - if ($slots.Count -ne 14) { - throw 'NSIS-only signing manifest must contain exactly 14 callback slots.' - } - $uninstallerSlots = 0 - $installerSlots = 0 - foreach ($slot in $slots) { - $slotId = [string](Get-RequiredPropertyValue $slot 'id' 'Signing manifest slot') - $slotKind = [string](Get-RequiredPropertyValue $slot 'kind' 'Signing manifest slot') - $slotOrder = [int](Get-RequiredPropertyValue $slot 'order' 'Signing manifest slot') - $maxUses = [int](Get-RequiredPropertyValue $slot 'maxUses' 'Signing manifest slot') - if ($slotId -notmatch '^[a-z0-9][a-z0-9-]{2,63}$' -or - -not $seenIds.Add($slotId) -or - -not $seenOrders.Add($slotOrder) -or - $slotOrder -lt 1 -or - $slotOrder -gt $slots.Count -or - $maxUses -ne 1) { - throw 'Signing manifest callback slots must have unique ids, consecutive orders, and maxUses 1.' - } - switch ($slotKind) { - 'fixed' { - $slotPath = [string](Get-RequiredPropertyValue $slot 'path' 'Fixed signing slot') - $slotHash = [string](Get-RequiredPropertyValue $slot 'preSignSha256' 'Fixed signing slot') - $packagedPath = [string](Get-RequiredPropertyValue $slot 'packagedPath' 'Fixed signing slot') - if ($slotHash -notmatch '^[0-9A-Fa-f]{64}$' -or - -not $expectedFixedSet.Contains([IO.Path]::GetFullPath($slotPath)) -or - -not $seenFixedSet.Add([IO.Path]::GetFullPath($slotPath)) -or - $slotOrder -gt $expectedPackagedPaths.Count -or - $packagedPath -cne $expectedPackagedPaths[$slotOrder - 1]) { - throw 'Fixed signing slot is outside the exact NSIS-only callback manifest.' - } - } - 'generated-nsis-uninstaller' { - $uninstallerSlots++ - $expectedEvidencePath = Join-Path $sessionDirectory 'signed-evidence\13-nsis-uninstaller.exe' - if ([string](Get-RequiredPropertyValue $slot 'pathPattern' 'NSIS uninstaller slot') -cne - $NsisUninstallerPattern -or $slotOrder -ne ($slots.Count - 1)) { - throw 'NSIS uninstaller slot must be the one-time penultimate session lease.' - } - Assert-ExactCanonicalPathValue ` - ([string](Get-RequiredPropertyValue $slot 'evidencePath' 'NSIS uninstaller slot')) ` - $expectedEvidencePath 'NSIS uninstaller evidence path' - } - 'generated-nsis-installer' { - $installerSlots++ - $expectedInstaller = Join-Path ` - $Context.ReleaseRoot ` - "bundle\nsis\Waggle_${version}_x64-setup.exe" - Assert-ExactCanonicalPathValue ` - ([string](Get-RequiredPropertyValue $slot 'path' 'NSIS installer slot')) ` - $expectedInstaller 'NSIS installer slot path' - if ($slotOrder -ne $slots.Count) { - throw 'NSIS installer slot must be the final callback lease.' - } - } - default { throw 'Production signing manifest contains a non-NSIS callback slot.' } - } - } - if ($seenFixedSet.Count -ne $expectedFixedSet.Count -or - $uninstallerSlots -ne 1 -or $installerSlots -ne 1 -or - [int](@($slots | Where-Object { $_.order -eq 1 })[0].order) -ne 1 -or - -not [string]::Equals( - [string](@($slots | Where-Object { $_.order -eq 1 })[0].path), - [string]$expectedFixedPaths[0], - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Signing manifest does not cover the exact ordered NSIS callback surface.' - } - - $session = [pscustomobject]@{ - Id = $sessionId - Manifest = $manifest - ManifestSha256 = $manifestSha256.ToUpperInvariant() - ManifestPath = $manifestPath - SessionDirectory = $sessionDirectory - TempRoot = $tempRoot - LedgerPath = $ledgerPath - Context = $Context - Locks = $locks - } - $ledger = Get-Content -Raw -LiteralPath $ledgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-WaggleSigningLedgerState $session $ledger - return $session - } catch { - foreach ($lock in $locks) { $lock.Dispose() } - throw - } -} - -function Assert-WaggleSigningLedgerState { - param( - [Parameter(Mandatory = $true)] [object]$Session, - [Parameter(Mandatory = $true)] [object]$Ledger - ) - - if ([int](Get-RequiredPropertyValue $Ledger 'schemaVersion' 'Signing callback ledger') -ne 3 -or - [string](Get-RequiredPropertyValue $Ledger 'sessionId' 'Signing callback ledger') -cne - [string]$Session.Id -or - -not [string]::Equals( - [string](Get-RequiredPropertyValue $Ledger 'manifestSha256' 'Signing callback ledger'), - [string]$Session.ManifestSha256, - [StringComparison]::OrdinalIgnoreCase - ) -or - [string](Get-RequiredPropertyValue $Ledger 'state' 'Signing callback ledger') -notin - @('open', 'failed', 'sealed')) { - throw 'Signing callback ledger does not belong to the active manifest session.' - } - foreach ($field in @('terminalAtUtc', 'terminalReceiptSha256')) { - if ($null -eq $Ledger.PSObject.Properties[$field]) { - throw "Signing callback ledger is missing required property '$field'." - } - } - $ledgerState = [string]$Ledger.state - if ($ledgerState -ceq 'open') { - if ($null -ne $Ledger.terminalAtUtc -or $null -ne $Ledger.terminalReceiptSha256) { - throw 'An open signing callback ledger cannot contain terminal metadata.' - } - } else { - $terminalAt = [DateTimeOffset]::MinValue - if (-not [DateTimeOffset]::TryParseExact( - [string]$Ledger.terminalAtUtc, - 'O', - [Globalization.CultureInfo]::InvariantCulture, - [Globalization.DateTimeStyles]::AssumeUniversal, - [ref]$terminalAt - ) -or [string]$Ledger.terminalReceiptSha256 -notmatch '^[0-9A-Fa-f]{64}$') { - throw 'Terminal signing callback ledger metadata is invalid.' - } - } - - $manifestSlots = @($Session.Manifest.slots) - $entries = @((Get-RequiredPropertyValue $Ledger 'entries' 'Signing callback ledger')) - if ($entries.Count -ne $manifestSlots.Count -or $entries.Count -ne 14) { - throw 'Signing callback ledger must predeclare the exact 14-slot manifest roster.' - } - - $reservedCount = 0 - $failedCount = 0 - for ($index = 0; $index -lt $manifestSlots.Count; $index++) { - $slot = $manifestSlots[$index] - $entry = $entries[$index] - $slotId = [string](Get-RequiredPropertyValue $slot 'id' 'Signing manifest slot') - $slotKind = [string](Get-RequiredPropertyValue $slot 'kind' 'Signing manifest slot') - $slotOrder = [int](Get-RequiredPropertyValue $slot 'order' 'Signing manifest slot') - if ([string](Get-RequiredPropertyValue $entry 'slotId' 'Signing callback ledger entry') -cne - $slotId -or - [string](Get-RequiredPropertyValue $entry 'kind' 'Signing callback ledger entry') -cne - $slotKind -or - [int](Get-RequiredPropertyValue $entry 'order' 'Signing callback ledger entry') -ne - $slotOrder -or $slotOrder -ne ($index + 1)) { - throw 'Signing callback ledger roster does not exactly match the ordered manifest slots.' - } - - foreach ($field in @( - 'reservationId', 'path', 'preSignSha256', 'reservedAtUtc', - 'completedAtUtc', 'postSignSha256', 'signerSubject' - )) { - if ($null -eq $entry.PSObject.Properties[$field]) { - throw "Signing callback ledger entry is missing required property '$field'." - } - } - $status = [string](Get-RequiredPropertyValue $entry 'status' 'Signing callback ledger entry') - $attempts = [int](Get-RequiredPropertyValue $entry 'attempts' 'Signing callback ledger entry') - - if ($status -ceq 'pending') { - if ($attempts -ne 0 -or @( - 'reservationId', 'path', 'preSignSha256', 'reservedAtUtc', - 'completedAtUtc', 'postSignSha256', 'signerSubject' | - Where-Object { $null -ne $entry.PSObject.Properties[$_].Value } - ).Count -ne 0) { - throw 'Pending signing callback ledger entries must be pristine and unused.' - } - continue - } - - if ($status -notin @('reserved', 'completed', 'failed') -or $attempts -ne 1 -or - [string]$entry.reservationId -notmatch '^[0-9a-f]{32}$' -or - [string]$entry.preSignSha256 -notmatch '^[0-9A-Fa-f]{64}$' -or - [string]::IsNullOrWhiteSpace([string]$entry.path)) { - throw 'Consumed signing callback ledger entry has invalid reservation metadata.' - } - $entryPath = [IO.Path]::GetFullPath([string]$entry.path) - if ($slotKind -ceq 'generated-nsis-uninstaller') { - $relative = Get-ContainedRelativePath $entryPath $Session.TempRoot - if ($null -eq $relative -or $relative -match '[\\/]' -or - $relative -cnotmatch $NsisUninstallerPattern) { - throw 'Signing callback ledger contains an invalid NSIS uninstaller path.' - } - } else { - Assert-ExactCanonicalPathValue ` - $entryPath ([string](Get-RequiredPropertyValue $slot 'path' 'Signing manifest slot')) ` - 'Signing callback ledger artifact path' - } - if ($slotKind -ceq 'fixed' -and -not [string]::Equals( - [string]$entry.preSignSha256, - [string](Get-RequiredPropertyValue $slot 'preSignSha256' 'Fixed signing slot'), - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Signing callback ledger fixed artifact hash does not match the manifest.' - } - - $reservedAt = [DateTimeOffset]::MinValue - if (-not [DateTimeOffset]::TryParseExact( - [string]$entry.reservedAtUtc, - 'O', - [Globalization.CultureInfo]::InvariantCulture, - [Globalization.DateTimeStyles]::AssumeUniversal, - [ref]$reservedAt - )) { - throw 'Signing callback reservation timestamp is invalid.' - } - - if ($status -ceq 'reserved') { - if ($ledgerState -cne 'open') { - throw 'Only an open signing callback ledger may contain a reservation.' - } - $reservedCount++ - if ($reservedCount -ne 1 -or @( - 'completedAtUtc', 'postSignSha256', 'signerSubject' | - Where-Object { $null -ne $entry.PSObject.Properties[$_].Value } - ).Count -ne 0) { - throw 'Reserved signing callback ledger entry has invalid completion metadata.' - } - continue - } - - if ($status -ceq 'failed') { - if ($ledgerState -cne 'failed') { - throw 'Only a failed signing callback ledger may contain a failed entry.' - } - $failedCount++ - if ($failedCount -ne 1 -or @( - 'completedAtUtc', 'postSignSha256', 'signerSubject' | - Where-Object { $null -ne $entry.PSObject.Properties[$_].Value } - ).Count -ne 0) { - throw 'Failed signing callback ledger entry has invalid completion metadata.' - } - continue - } - - $completedAt = [DateTimeOffset]::MinValue - if (-not [DateTimeOffset]::TryParseExact( - [string]$entry.completedAtUtc, - 'O', - [Globalization.CultureInfo]::InvariantCulture, - [Globalization.DateTimeStyles]::AssumeUniversal, - [ref]$completedAt - ) -or $completedAt -lt $reservedAt -or - [string]$entry.postSignSha256 -notmatch '^[0-9A-Fa-f]{64}$' -or - [string]::IsNullOrWhiteSpace([string]$entry.signerSubject)) { - throw 'Completed signing callback ledger entry has invalid completion metadata.' - } - } - if ($ledgerState -ceq 'open' -and $failedCount -ne 0) { - throw 'An open signing callback ledger cannot contain a failed entry.' - } - if ($ledgerState -ceq 'failed' -and $reservedCount -ne 0) { - throw 'A failed signing callback ledger cannot retain a reservation.' - } - if ($ledgerState -ceq 'sealed' -and - @($entries | Where-Object { [string]$_.status -cne 'completed' }).Count -ne 0) { - throw 'A sealed signing callback ledger must contain only completed entries.' - } - if ($reservedCount -gt 1) { - throw 'Signing callback ledger contains multiple reservations.' - } - if ($ledgerState -ceq 'open') { - $incompletePhases = @($entries | Where-Object { - [string]$_.status -cne 'completed' - } | ForEach-Object { Get-WaggleSigningSlotPhase ([int]$_.order) }) - $firstIncompletePhase = if ($incompletePhases.Count -eq 0) { - 6 - } else { - ($incompletePhases | Measure-Object -Minimum).Minimum - } - if (@($entries | Where-Object { - (Get-WaggleSigningSlotPhase ([int]$_.order)) -gt $firstIncompletePhase -and - [string]$_.status -ne 'pending' - }).Count -ne 0) { - throw 'Signing callback ledger crossed an incomplete NSIS signing phase.' - } - } -} - -function Write-WaggleLedgerAtomicNoLock { - param( - [Parameter(Mandatory = $true)] [object]$Session, - [Parameter(Mandatory = $true)] [object]$Ledger - ) - - $tempLedgerPath = $null - $backupLedgerPath = $null - try { - $ledgerPath = Get-TrustedPath $Session.LedgerPath 'Signing callback ledger' - Assert-ExactCanonicalPathValue ` - $ledgerPath (Join-Path $Session.SessionDirectory 'callback-ledger.json') ` - 'Signing callback ledger path' - Assert-WaggleSigningLedgerState $Session $ledger - $json = $ledger | ConvertTo-Json -Depth 32 -Compress - $tempLedgerPath = Join-Path ` - $Session.SessionDirectory ` - "callback-ledger.$([Guid]::NewGuid().ToString('N')).tmp" - $backupLedgerPath = Join-Path ` - $Session.SessionDirectory ` - "callback-ledger.$([Guid]::NewGuid().ToString('N')).bak" - $bytes = [Text.UTF8Encoding]::new($false).GetBytes($json) - $stream = [IO.FileStream]::new( - $tempLedgerPath, - [IO.FileMode]::CreateNew, - [IO.FileAccess]::Write, - [IO.FileShare]::None, - 4096, - [IO.FileOptions]::WriteThrough - ) - try { - $stream.Write($bytes, 0, $bytes.Length) - $stream.Flush($true) - } finally { - $stream.Dispose() - } - [IO.File]::Replace($tempLedgerPath, $ledgerPath, $backupLedgerPath, $true) - $tempLedgerPath = $null - try { [IO.File]::Delete($backupLedgerPath) } catch { } - $backupLedgerPath = $null - } finally { - if ($null -ne $tempLedgerPath -and (Test-Path -LiteralPath $tempLedgerPath -PathType Leaf)) { - try { [IO.File]::Delete($tempLedgerPath) } catch { } - } - if ($null -ne $backupLedgerPath -and (Test-Path -LiteralPath $backupLedgerPath -PathType Leaf)) { - try { [IO.File]::Delete($backupLedgerPath) } catch { } - } - } -} - -function Invoke-WaggleLedgerMutation { - param( - [Parameter(Mandatory = $true)] [object]$Session, - [Parameter(Mandatory = $true)] [scriptblock]$Mutation, - [switch]$AllowTerminalReceipt - ) - - $mutex = [Threading.Mutex]::new($false, "Local\WaggleSigning-$($Session.Id)") - $hasMutex = $false - try { - try { - $hasMutex = $mutex.WaitOne([TimeSpan]::FromSeconds(30)) - } catch [Threading.AbandonedMutexException] { - $hasMutex = $true - } - if (-not $hasMutex) { throw 'Timed out waiting for the signing callback ledger.' } - - $ledgerPath = Get-TrustedPath $Session.LedgerPath 'Signing callback ledger' - try { - $ledger = Get-Content -Raw -LiteralPath $ledgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - } catch { - throw 'Signing callback ledger is not valid JSON.' - } - Assert-WaggleSigningLedgerState $Session $ledger - if ([string]$ledger.state -cne 'open') { - throw 'Signing callback ledger is already terminal.' - } - if (-not $AllowTerminalReceipt -and @( - @('terminal-intent.json', 'provenance-receipt.json', 'failure-receipt.json') | - Where-Object { Test-Path -LiteralPath (Join-Path $Session.SessionDirectory $_) } - ).Count -ne 0) { - throw 'Signing callback ledger has a pending terminal receipt.' - } - - $mutationResult = & $Mutation $ledger - Write-WaggleLedgerAtomicNoLock $Session $ledger - return $mutationResult - } finally { - if ($hasMutex) { $mutex.ReleaseMutex() } - $mutex.Dispose() - } -} - -function Reserve-WaggleSigningCallback { - param( - [Parameter(Mandatory = $true)] [object]$Session, - [Parameter(Mandatory = $true)] [string]$ArtifactPath - ) - - $artifact = Get-TrustedPath $ArtifactPath 'Signing callback artifact' -AllowHardLink - $matches = @($Session.Manifest.slots | Where-Object { - if ([string]$_.kind -ceq 'generated-nsis-uninstaller') { - $relative = Get-ContainedRelativePath $artifact $Session.TempRoot - return $null -ne $relative -and - $relative -notmatch '[\\/]' -and $relative -cmatch $NsisUninstallerPattern - } - $pathProperty = $_.PSObject.Properties['path'] - return $null -ne $pathProperty -and [string]::Equals( - [IO.Path]::GetFullPath([string]$pathProperty.Value), - $artifact, - [StringComparison]::OrdinalIgnoreCase - ) - }) - if ($matches.Count -ne 1) { - throw 'Signing callback artifact does not match exactly one manifest slot.' - } - $slot = $matches[0] - $preSignHash = (Get-FileHash -LiteralPath $artifact -Algorithm SHA256).Hash - if ([string]$slot.kind -ceq 'fixed' -and - -not [string]::Equals( - $preSignHash, - [string]$slot.preSignSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Signing callback artifact does not match the manifest pre-sign SHA-256 digest.' - } - - if (@(@('terminal-intent.json', 'provenance-receipt.json', 'failure-receipt.json') | Where-Object { - Test-Path -LiteralPath (Join-Path $Session.SessionDirectory $_) - }).Count -ne 0) { - throw 'Signing provenance receipt already exists.' - } - Invoke-WaggleLedgerMutation $Session { - param($ledger) - - $entries = @($ledger.entries) - $entry = $entries[[int]$slot.order - 1] - if ([string]$entry.status -cne 'pending' -or [int]$entry.attempts -ne 0) { - throw 'Signing callback slot was already consumed.' - } - $slotPhase = Get-WaggleSigningSlotPhase ([int]$slot.order) - if (@($entries | Where-Object { [string]$_.status -ceq 'reserved' }).Count -ne 0 -or - @($entries | Where-Object { - (Get-WaggleSigningSlotPhase ([int]$_.order)) -lt $slotPhase -and - [string]$_.status -cne 'completed' - }).Count -ne 0) { - throw 'Signing callback phase does not match the manifest ledger.' - } - $entry.status = 'reserved' - $entry.attempts = 1 - $entry.reservationId = [Guid]::NewGuid().ToString('N') - $entry.path = $artifact - $entry.preSignSha256 = $preSignHash - $entry.reservedAtUtc = [DateTimeOffset]::UtcNow.ToString('O') - return [pscustomobject][ordered]@{ - reservationId = [string]$entry.reservationId - slotId = [string]$entry.slotId - order = [int]$entry.order - kind = [string]$entry.kind - path = [string]$entry.path - preSignSha256 = [string]$entry.preSignSha256 - } - } -} - -function Complete-WaggleSigningCallback { - param( - [Parameter(Mandatory = $true)] [object]$Session, - [Parameter(Mandatory = $true)] [object]$Reservation, - [Parameter(Mandatory = $true)] [string]$SignedArtifactPath - ) - - $artifact = Get-TrustedPath $SignedArtifactPath 'Signed callback artifact' - $postSignHash = (Get-FileHash -LiteralPath $artifact -Algorithm SHA256).Hash - $signature = Get-AuthenticodeSignature -LiteralPath $artifact - $signerSubject = if ($null -eq $signature.SignerCertificate) { - $null - } else { - [string]$signature.SignerCertificate.Subject - } - Invoke-WaggleLedgerMutation $Session { - param($ledger) - - $entries = @($ledger.entries) - $matchingEntries = @($entries | Where-Object { - [string]$_.slotId -ceq [string]$Reservation.slotId - }) - if ($matchingEntries.Count -ne 1 -or - [string]$matchingEntries[0].status -cne 'reserved' -or - [string]$matchingEntries[0].reservationId -cne [string]$Reservation.reservationId -or - [int]$matchingEntries[0].order -ne [int]$Reservation.order -or - [string]$matchingEntries[0].kind -cne [string]$Reservation.kind -or - -not [string]::Equals( - [string]$matchingEntries[0].path, - [string]$Reservation.path, - [StringComparison]::OrdinalIgnoreCase - ) -or - -not [string]::Equals( - [IO.Path]::GetFullPath([string]$matchingEntries[0].path), - $artifact, - [StringComparison]::OrdinalIgnoreCase - ) -or - -not [string]::Equals( - [string]$matchingEntries[0].preSignSha256, - [string]$Reservation.preSignSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Signing callback reservation is missing or already completed.' - } - $matchingEntries[0].status = 'completed' - $matchingEntries[0].completedAtUtc = [DateTimeOffset]::UtcNow.ToString('O') - $matchingEntries[0].postSignSha256 = $postSignHash - $matchingEntries[0].signerSubject = $signerSubject - return $matchingEntries[0] - } -} - -function Write-WaggleDurableJsonNew { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [object]$Value - ) - $bytes = [Text.UTF8Encoding]::new($false).GetBytes( - ($Value | ConvertTo-Json -Depth 32 -Compress) - ) - $stream = [IO.FileStream]::new( - $Path, - [IO.FileMode]::CreateNew, - [IO.FileAccess]::Write, - [IO.FileShare]::None, - 4096, - [IO.FileOptions]::WriteThrough - ) - try { - $stream.Write($bytes, 0, $bytes.Length) - $stream.Flush($true) - } finally { - $stream.Dispose() - } -} - -function Assert-WaggleTerminalReceipt { - param( - [Parameter(Mandatory = $true)] [object]$Session, - [Parameter(Mandatory = $true)] [ValidateSet('failed', 'sealed')] [string]$State, - [Parameter(Mandatory = $true)] [object]$Receipt - ) - - if ([int](Get-RequiredPropertyValue $Receipt 'schemaVersion' 'Signing terminal receipt') -ne 1 -or - [string](Get-RequiredPropertyValue $Receipt 'status' 'Signing terminal receipt') -cne $State -or - [string](Get-RequiredPropertyValue $Receipt 'sessionId' 'Signing terminal receipt') -cne - [string]$Session.Id -or - -not [string]::Equals( - [string](Get-RequiredPropertyValue $Receipt 'manifestSha256' 'Signing terminal receipt'), - [string]$Session.ManifestSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Signing terminal receipt does not belong to the active session.' - } - $terminalAtUtc = [string](Get-RequiredPropertyValue ` - $Receipt 'terminalAtUtc' 'Signing terminal receipt') - $terminalAt = [DateTimeOffset]::MinValue - if (-not [DateTimeOffset]::TryParseExact( - $terminalAtUtc, - 'O', - [Globalization.CultureInfo]::InvariantCulture, - [Globalization.DateTimeStyles]::AssumeUniversal, - [ref]$terminalAt - )) { - throw 'Signing terminal receipt has an invalid terminal timestamp.' - } - $sourceRevision = [string](Get-RequiredPropertyValue ` - $Receipt 'sourceRevision' 'Signing terminal receipt') - if ($sourceRevision -cne [string]$Session.Context.SourceRevision) { - throw 'Signing terminal receipt does not match the active source revision.' - } - if ($State -ceq 'failed') { - foreach ($name in @('failureCode', 'failureMessage', 'rollbackOutcome')) { - if ([string]::IsNullOrWhiteSpace([string](Get-RequiredPropertyValue ` - $Receipt $name 'Signing failure receipt'))) { - throw 'Signing failure receipt has incomplete failure provenance.' - } - } - if ($null -eq $Receipt.PSObject.Properties['failedSlotId']) { - throw 'Signing failure receipt is missing its failed-slot provenance.' - } - } else { - foreach ($name in @( - 'manifestPath', 'callbackLedgerPath', 'installerPath', - 'installerSha256', 'signerSubject', 'payloadManifestSha256', 'artifactBindings' - )) { - [void](Get-RequiredPropertyValue $Receipt $name 'Signing provenance receipt') - } - Assert-ExactCanonicalPathValue ` - ([string]$Receipt.manifestPath) ([string]$Session.ManifestPath) ` - 'Signing provenance manifest path' - Assert-ExactCanonicalPathValue ` - ([string]$Receipt.callbackLedgerPath) ([string]$Session.LedgerPath) ` - 'Signing provenance callback ledger path' - $installerSlots = @($Session.Manifest.slots | Where-Object { - [string]$_.kind -ceq 'generated-nsis-installer' - }) - if ($installerSlots.Count -ne 1) { - throw 'Signing provenance session lacks one exact installer slot.' - } - Assert-ExactCanonicalPathValue ` - ([string]$Receipt.installerPath) ([string]$installerSlots[0].path) ` - 'Signing provenance installer path' - if ([string]$Receipt.installerSha256 -notmatch '^[0-9A-Fa-f]{64}$' -or - [string]$Receipt.payloadManifestSha256 -notmatch '^[0-9A-Fa-f]{64}$' -or - [string]::IsNullOrWhiteSpace([string]$Receipt.signerSubject) -or - @($Receipt.artifactBindings).Count -lt 2) { - throw 'Signing provenance receipt has invalid artifact provenance.' - } - } - return $terminalAtUtc -} - -function Get-WaggleTerminalIntentPath { - param([Parameter(Mandatory = $true)] [object]$Session) - return Join-Path $Session.SessionDirectory 'terminal-intent.json' -} - -function Assert-WaggleTerminalIntent { - param( - [Parameter(Mandatory = $true)] [object]$Session, - [Parameter(Mandatory = $true)] [ValidateSet('failed', 'sealed')] [string]$State, - [Parameter(Mandatory = $true)] [object]$Intent - ) - if ([int](Get-RequiredPropertyValue $Intent 'schemaVersion' 'Signing terminal intent') -ne 1 -or - [string](Get-RequiredPropertyValue $Intent 'state' 'Signing terminal intent') -cne $State -or - [string](Get-RequiredPropertyValue $Intent 'sessionId' 'Signing terminal intent') -cne - [string]$Session.Id -or - -not [string]::Equals( - [string](Get-RequiredPropertyValue $Intent 'manifestSha256' 'Signing terminal intent'), - [string]$Session.ManifestSha256, - [StringComparison]::OrdinalIgnoreCase - ) -or - [string](Get-RequiredPropertyValue ` - $Intent 'receiptSha256' 'Signing terminal intent') -notmatch '^[0-9A-Fa-f]{64}$') { - throw 'Signing terminal intent does not belong to the active session.' - } - $terminalAtUtc = [string](Get-RequiredPropertyValue ` - $Intent 'terminalAtUtc' 'Signing terminal intent') - $terminalAt = [DateTimeOffset]::MinValue - if (-not [DateTimeOffset]::TryParseExact( - $terminalAtUtc, - 'O', - [Globalization.CultureInfo]::InvariantCulture, - [Globalization.DateTimeStyles]::AssumeUniversal, - [ref]$terminalAt - )) { - throw 'Signing terminal intent has an invalid terminal timestamp.' - } - return $terminalAtUtc -} - -function Set-WaggleSigningTerminalState { - param( - [Parameter(Mandatory = $true)] [object]$Session, - [Parameter(Mandatory = $true)] [ValidateSet('failed', 'sealed')] [string]$State, - [Parameter(Mandatory = $true)] [object]$Receipt, - [Parameter(Mandatory = $true)] [scriptblock]$LedgerMutation - ) - - $mutex = [Threading.Mutex]::new($false, "Local\WaggleSigning-$($Session.Id)") - $hasMutex = $false - $temporaryReceipt = $null - $temporaryIntent = $null - $receiptLock = $null - $intentLock = $null - try { - try { - $hasMutex = $mutex.WaitOne([TimeSpan]::FromSeconds(30)) - } catch [Threading.AbandonedMutexException] { - $hasMutex = $true - } - if (-not $hasMutex) { - throw 'Timed out waiting to terminalize the signing session.' - } - - $fileName = if ($State -ceq 'sealed') { - 'provenance-receipt.json' - } else { - 'failure-receipt.json' - } - $receiptPath = Join-Path $Session.SessionDirectory $fileName - $oppositeFileName = if ($State -ceq 'sealed') { - 'failure-receipt.json' - } else { - 'provenance-receipt.json' - } - $oppositePath = Join-Path $Session.SessionDirectory $oppositeFileName - if (Test-Path -LiteralPath $oppositePath) { - throw 'Signing session already contains the opposite terminal receipt.' - } - $intentPath = Get-WaggleTerminalIntentPath $Session - - $ledgerPath = Get-TrustedPath $Session.LedgerPath 'Signing callback ledger' - try { - $currentLedger = Get-Content -Raw -LiteralPath $ledgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - } catch { - throw 'Signing callback ledger is not valid JSON.' - } - Assert-WaggleSigningLedgerState $Session $currentLedger - if ([string]$currentLedger.state -notin @('open', $State)) { - throw 'Signing session is already in a different terminal state.' - } - - if ([string]$currentLedger.state -ceq 'open') { - & $LedgerMutation $currentLedger - } - - if (Test-Path -LiteralPath $receiptPath) { - $trustedReceiptPath = Get-TrustedPath $receiptPath 'Signing terminal receipt' - $receiptLock = Open-ReadLock $trustedReceiptPath - try { - $persistedReceipt = Get-Content -Raw -LiteralPath $trustedReceiptPath | - ConvertFrom-Json -Depth 32 -DateKind String - } catch { - throw 'Signing terminal receipt is not valid JSON.' - } - $terminalAtUtc = Assert-WaggleTerminalReceipt ` - $Session $State $persistedReceipt - [void](Assert-WaggleTerminalReceipt $Session $State $Receipt) - $candidateReceipt = $Receipt | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $candidateReceipt.terminalAtUtc = $terminalAtUtc - if (($candidateReceipt | ConvertTo-Json -Depth 32 -Compress) -cne - ($persistedReceipt | ConvertTo-Json -Depth 32 -Compress)) { - throw 'Signing terminal receipt does not match the current terminalization candidate.' - } - $receiptHash = (Get-FileHash -LiteralPath $trustedReceiptPath -Algorithm SHA256).Hash - if (-not (Test-Path -LiteralPath $intentPath -PathType Leaf)) { - throw 'Signing terminal receipt exists without its durable terminal intent.' - } - $trustedIntentPath = Get-TrustedPath $intentPath 'Signing terminal intent' - $intentLock = Open-ReadLock $trustedIntentPath - try { - $intent = Get-Content -Raw -LiteralPath $trustedIntentPath | - ConvertFrom-Json -Depth 16 -DateKind String - } catch { - throw 'Signing terminal intent is not valid JSON.' - } - $intentTerminalAtUtc = Assert-WaggleTerminalIntent $Session $State $intent - if ($intentTerminalAtUtc -cne $terminalAtUtc -or - -not [string]::Equals( - [string]$intent.receiptSha256, - $receiptHash, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Signing terminal receipt does not match its durable terminal intent.' - } - } else { - $terminalAtUtc = Assert-WaggleTerminalReceipt $Session $State $Receipt - $candidateReceipt = $Receipt | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - if (Test-Path -LiteralPath $intentPath) { - $trustedIntentPath = Get-TrustedPath $intentPath 'Signing terminal intent' - $intentLock = Open-ReadLock $trustedIntentPath - try { - $intent = Get-Content -Raw -LiteralPath $trustedIntentPath | - ConvertFrom-Json -Depth 16 -DateKind String - } catch { - throw 'Signing terminal intent is not valid JSON.' - } - $terminalAtUtc = Assert-WaggleTerminalIntent $Session $State $intent - $candidateReceipt.terminalAtUtc = $terminalAtUtc - } - $temporaryReceipt = Join-Path ` - $Session.SessionDirectory "$fileName.$([Guid]::NewGuid().ToString('N')).tmp" - Write-WaggleDurableJsonNew $temporaryReceipt $candidateReceipt - $trustedTemporaryReceipt = Get-TrustedPath ` - $temporaryReceipt 'Staged signing terminal receipt' - $persistedReceipt = Get-Content -Raw -LiteralPath $trustedTemporaryReceipt | - ConvertFrom-Json -Depth 32 -DateKind String - $terminalAtUtc = Assert-WaggleTerminalReceipt ` - $Session $State $persistedReceipt - $receiptHash = (Get-FileHash -LiteralPath $trustedTemporaryReceipt -Algorithm SHA256).Hash - if ($null -ne $intentLock) { - if (-not [string]::Equals( - [string]$intent.receiptSha256, - $receiptHash, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Signing terminalization candidate does not match its durable terminal intent.' - } - } else { - $intent = [pscustomobject][ordered]@{ - schemaVersion = 1 - state = $State - sessionId = $Session.Id - manifestSha256 = $Session.ManifestSha256 - terminalAtUtc = $terminalAtUtc - receiptSha256 = $receiptHash - } - $temporaryIntent = Join-Path ` - $Session.SessionDirectory "terminal-intent.$([Guid]::NewGuid().ToString('N')).tmp" - Write-WaggleDurableJsonNew $temporaryIntent $intent - [void](Assert-WaggleTerminalIntent $Session $State ( - Get-Content -Raw -LiteralPath $temporaryIntent | - ConvertFrom-Json -Depth 16 -DateKind String - )) - [IO.File]::Move($temporaryIntent, $intentPath) - $temporaryIntent = $null - $trustedIntentPath = Get-TrustedPath $intentPath 'Signing terminal intent' - $intentLock = Open-ReadLock $trustedIntentPath - try { - $persistedIntent = Get-Content -Raw -LiteralPath $trustedIntentPath | - ConvertFrom-Json -Depth 16 -DateKind String - } catch { - throw 'Signing terminal intent is not valid JSON.' - } - $persistedIntentTerminalAtUtc = Assert-WaggleTerminalIntent ` - $Session $State $persistedIntent - if ($persistedIntentTerminalAtUtc -cne $terminalAtUtc -or - -not [string]::Equals( - [string]$persistedIntent.receiptSha256, - $receiptHash, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Published signing terminal intent does not match its staged receipt.' - } - } - } - - if ([string]$currentLedger.state -ceq $State) { - if (-not [string]::Equals( - [string]$currentLedger.terminalReceiptSha256, - $receiptHash, - [StringComparison]::OrdinalIgnoreCase - ) -or [string]$currentLedger.terminalAtUtc -cne $terminalAtUtc) { - throw 'Terminal ledger does not match its durable receipt.' - } - return $receiptPath - } - - $currentLedger.state = $State - $currentLedger.terminalAtUtc = $terminalAtUtc - $currentLedger.terminalReceiptSha256 = $receiptHash - Assert-WaggleSigningLedgerState $Session $currentLedger - if ($null -ne $temporaryReceipt) { - [IO.File]::Move($temporaryReceipt, $receiptPath) - $temporaryReceipt = $null - $trustedReceiptPath = Get-TrustedPath $receiptPath 'Signing terminal receipt' - $receiptLock = Open-ReadLock $trustedReceiptPath - if (-not [string]::Equals( - (Get-FileHash -LiteralPath $trustedReceiptPath -Algorithm SHA256).Hash, - $receiptHash, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Published signing terminal receipt does not match its durable terminal intent.' - } - } - Write-WaggleLedgerAtomicNoLock $Session $currentLedger - return Get-TrustedPath $receiptPath 'Signing terminal receipt' - } finally { - if ($null -ne $temporaryReceipt -and - (Test-Path -LiteralPath $temporaryReceipt -PathType Leaf)) { - try { [IO.File]::Delete($temporaryReceipt) } catch { } - } - if ($null -ne $temporaryIntent -and - (Test-Path -LiteralPath $temporaryIntent -PathType Leaf)) { - try { [IO.File]::Delete($temporaryIntent) } catch { } - } - if ($null -ne $receiptLock) { $receiptLock.Dispose() } - if ($null -ne $intentLock) { $intentLock.Dispose() } - if ($hasMutex) { $mutex.ReleaseMutex() } - $mutex.Dispose() - } -} - -function Publish-WaggleTerminalReceipt { - param( - [Parameter(Mandatory = $true)] [object]$Session, - [Parameter(Mandatory = $true)] [ValidateSet('failed', 'sealed')] [string]$State, - [Parameter(Mandatory = $true)] [object]$Receipt, - [Parameter(Mandatory = $true)] [scriptblock]$LedgerMutation - ) - - return Set-WaggleSigningTerminalState ` - -Session $Session -State $State -Receipt $Receipt ` - -LedgerMutation $LedgerMutation -} - -function Fail-WaggleSigningSession { - param( - [Parameter(Mandatory = $true)] [object]$Session, - [AllowNull()] [object]$Reservation, - [Parameter(Mandatory = $true)] [string]$FailureCode, - [Parameter(Mandatory = $true)] [string]$FailureMessage, - [string]$RollbackOutcome = 'not-required' - ) - - $ledger = Get-Content -Raw -LiteralPath $Session.LedgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-WaggleSigningLedgerState $Session $ledger - if ([string]$ledger.state -ceq 'failed') { - $persistedReceiptPath = Join-Path $Session.SessionDirectory 'failure-receipt.json' - try { - $persistedReceipt = Get-Content -Raw -LiteralPath $persistedReceiptPath | - ConvertFrom-Json -Depth 32 -DateKind String - } catch { - throw 'Signing failure receipt is not valid JSON.' - } - return Publish-WaggleTerminalReceipt $Session 'failed' $persistedReceipt { param($_) } - } - if ([string]$ledger.state -cne 'open') { - throw 'A sealed signing session cannot be marked failed.' - } - $reserved = @($ledger.entries | Where-Object { [string]$_.status -ceq 'reserved' }) - if ($reserved.Count -gt 1) { throw 'Signing ledger contains multiple reservations.' } - $failedSlot = $null - if ($null -ne $Reservation) { - $reserved = @($reserved | Where-Object { - [string]$_.reservationId -ceq [string]$Reservation.reservationId - }) - if ($reserved.Count -ne 1) { - throw 'Signing failure does not match the active reservation.' - } - $failedSlot = [string]$reserved[0].slotId - } elseif ($reserved.Count -eq 1) { - $failedSlot = [string]$reserved[0].slotId - } - $terminalAt = [DateTimeOffset]::UtcNow.ToString('O') - $receipt = [pscustomobject][ordered]@{ - schemaVersion = 1 - status = 'failed' - sessionId = $Session.Id - sourceRevision = $Session.Context.SourceRevision - manifestPath = $Session.ManifestPath - manifestSha256 = $Session.ManifestSha256 - failureCode = $FailureCode - failureMessage = $FailureMessage - failedSlotId = $failedSlot - rollbackOutcome = $RollbackOutcome - terminalAtUtc = $terminalAt - } - return Publish-WaggleTerminalReceipt $Session 'failed' $receipt { - param($activeLedger) - $activeReserved = @($activeLedger.entries | Where-Object { [string]$_.status -ceq 'reserved' }) - if ($null -ne $failedSlot) { - $activeReserved = @($activeReserved | Where-Object { [string]$_.slotId -ceq $failedSlot }) - if ($activeReserved.Count -ne 1) { - throw 'Signing failure reservation changed before terminalization.' - } - $activeReserved[0].status = 'failed' - } elseif ($activeReserved.Count -ne 0) { - throw 'Signing failure receipt omitted an active reservation.' - } - } -} - -function Expand-PinnedArtifactSigningPackage { - param( - [Parameter(Mandatory = $true)] [string]$PackagePath, - [Parameter(Mandatory = $true)] [string]$StagingRoot - ) - - $package = Get-TrustedPath $PackagePath 'Artifact Signing package' - $packageLock = Open-ReadLock $package - try { - if ((Get-FileHash -LiteralPath $package -Algorithm SHA256).Hash -cne - $ArtifactSigningPackageSha256) { - throw 'Artifact Signing package does not match the pinned SHA-256 digest.' - } - $stagedPackage = Join-Path $StagingRoot 'Microsoft.ArtifactSigning.Client.1.0.128.nupkg' - [IO.File]::Copy($package, $stagedPackage, $false) - if ((Get-FileHash -LiteralPath $stagedPackage -Algorithm SHA256).Hash -cne - $ArtifactSigningPackageSha256) { - throw 'Staged Artifact Signing package differs from the pinned package.' - } - } finally { - $packageLock.Dispose() - } - - $toolRoot = New-PrivateDirectory (Join-Path $StagingRoot 'artifact-signing-client') - Add-Type -AssemblyName System.IO.Compression.FileSystem - [IO.Compression.ZipFile]::ExtractToDirectory($stagedPackage, $toolRoot) - $x64Root = Get-TrustedPath (Join-Path $toolRoot 'bin\x64') 'Artifact Signing x64 root' 'Container' - $toolFiles = @(Get-ChildItem -LiteralPath $x64Root -Force) - if ($toolFiles.Count -ne 41 -or @($toolFiles | Where-Object { -not $_.PSIsContainer }).Count -ne 41) { - throw 'Artifact Signing x64 toolset does not match the pinned 41-file closure.' - } - $manifestLines = @( - $toolFiles | - Sort-Object Name | - ForEach-Object { - "{0} {1}" -f (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash, $_.Name - } - ) - $manifestBytes = [Text.Encoding]::UTF8.GetBytes(($manifestLines -join "`n") + "`n") - $manifestHash = [Convert]::ToHexString( - [Security.Cryptography.SHA256]::HashData($manifestBytes) - ) - if ($manifestHash -cne $ArtifactSigningX64ManifestSha256) { - throw 'Artifact Signing x64 dependency manifest does not match the pinned digest.' - } - - $dlib = Get-TrustedPath ` - (Join-Path $x64Root 'Azure.CodeSigning.Dlib.dll') ` - 'Azure Artifact Signing dlib' - if ([string](Get-Item -LiteralPath $dlib).VersionInfo.FileVersion -cne $ArtifactSigningClientVersion) { - throw "Azure Artifact Signing dlib must be version $ArtifactSigningClientVersion x64." - } - Assert-MicrosoftAuthenticodeFile $dlib 'Azure Artifact Signing dlib' $ArtifactSigningDlibSha256 - - $locks = [Collections.Generic.List[IDisposable]]::new() - try { - foreach ($toolFile in $toolFiles) { - $trustedToolFile = Get-TrustedPath $toolFile.FullName 'Artifact Signing dependency' - $locks.Add((Open-ReadLock $trustedToolFile)) - } - } catch { - foreach ($lock in $locks) { $lock.Dispose() } - throw - } - return [pscustomobject]@{ - Dlib = $dlib - Locks = $locks - } -} - -function Assert-DotNet8X64Runtime { - $dotnet = Get-TrustedPath 'C:\Program Files\dotnet\dotnet.exe' '.NET host' -AllowHardLink - Assert-MicrosoftAuthenticodeFile $dotnet '.NET host' $null $DotNetPublisher - $dotnetLock = Open-ReadLock $dotnet - try { - $runtimes = @(& $dotnet --list-runtimes) - if ($LASTEXITCODE -ne 0 -or - -not ($runtimes -match '^Microsoft\.NETCore\.App 8\.\d+\.\d+ \[')) { - throw 'Artifact Signing requires an installed x64 .NET 8 runtime.' - } - } finally { - $dotnetLock.Dispose() - } -} - -function Get-SystemFsutilPath { - return Get-TrustedPath ` - 'C:\Windows\System32\fsutil.exe' 'fsutil' -AllowHardLink -} - -function Get-HardLinkPaths { - param([Parameter(Mandatory = $true)] [string]$Path) - - $fsutil = Get-SystemFsutilPath - $fsutilLock = Open-ReadLock $fsutil - try { - Assert-MicrosoftAuthenticodeFile ` - $fsutil 'fsutil' $null $MicrosoftWindowsPublisher -AllowCatalog - $rawLinks = @(& $fsutil hardlink list $Path) - if ($LASTEXITCODE -ne 0 -or $rawLinks.Count -lt 2) { - throw 'Could not enumerate the complete hard-link set for the signing artifact.' - } - } finally { - $fsutilLock.Dispose() - } - - $volumeRoot = [IO.Path]::GetPathRoot($Path) - $links = foreach ($rawLink in $rawLinks) { - $volumeRelative = [string]$rawLink - if ($volumeRelative -notmatch '^\\[^\\]') { - throw 'fsutil returned an invalid hard-link path.' - } - $absolutePath = $volumeRoot.TrimEnd('\') + $volumeRelative - Get-TrustedPath $absolutePath 'Hard-link sibling' -AllowHardLink - } - return @($links | Sort-Object -Unique) -} - -function Assert-ApprovedHardLinkTopology { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$ReleaseRoot, - [switch]$AllowDetachedMain - ) - - $expectedMain = [IO.Path]::GetFullPath((Join-Path $ReleaseRoot 'waggle.exe')) - $expectedDependency = [IO.Path]::GetFullPath((Join-Path $ReleaseRoot 'deps\waggle.exe')) - $isMain = [string]::Equals($Path, $expectedMain, [StringComparison]::OrdinalIgnoreCase) - $isDependency = [string]::Equals( - $Path, - $expectedDependency, - [StringComparison]::OrdinalIgnoreCase - ) - $item = Get-Item -LiteralPath $Path -Force - $linkTypeProperty = $item.PSObject.Properties['LinkType'] - $linkType = if ($null -eq $linkTypeProperty) { '' } else { [string]$linkTypeProperty.Value } - if ([string]::IsNullOrEmpty($linkType)) { - if ($isMain -and -not $AllowDetachedMain) { - throw 'Cargo main executable must have the exact release\waggle.exe <-> release\deps\waggle.exe hard-link topology.' - } - return - } - if ($linkType -cne 'HardLink') { - throw 'Only the exact Cargo main-executable hard-link topology is allowed.' - } - - if (-not $isMain -and -not $isDependency) { - throw 'Only the exact Cargo executable pair may be hard-linked.' - } - - $actualLinks = @(Get-HardLinkPaths $Path) - $actualSet = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) - foreach ($actualLink in $actualLinks) { [void]$actualSet.Add($actualLink) } - if ($actualSet.Count -ne 2 -or - -not $actualSet.Contains($expectedMain) -or - -not $actualSet.Contains($expectedDependency)) { - throw 'Cargo main executable has an unexpected hard-link sibling.' - } -} - -function Restore-WaggleReplacedArtifact { - param( - [Parameter(Mandatory = $true)] [string]$ArtifactPath, - [Parameter(Mandatory = $true)] [string]$BackupPath, - [Parameter(Mandatory = $true)] [string]$ExpectedOriginalSha256, - [Parameter(Mandatory = $true)] [string[]]$ExpectedHardLinkPaths - ) - - if ($ExpectedOriginalSha256 -notmatch '^[0-9A-Fa-f]{64}$') { - throw 'Rollback expected-original SHA-256 is invalid.' - } - - $backup = Get-TrustedPath $BackupPath 'Rollback backup' -AllowHardLink - if ((Get-FileHash -LiteralPath $backup -Algorithm SHA256).Hash -cne - $ExpectedOriginalSha256.ToUpperInvariant()) { - throw 'Rollback backup SHA-256 does not match expected original digest.' - } - - $artifact = Get-TrustedPath $ArtifactPath 'Rollback artifact' -AllowHardLink - $expectedSet = [Collections.Generic.HashSet[string]]::new( - [StringComparer]::OrdinalIgnoreCase - ) - foreach ($expectedPath in @($ExpectedHardLinkPaths)) { - if ([string]::IsNullOrWhiteSpace($expectedPath)) { - throw 'Rollback hard-link inventory contains an empty path.' - } - [void]$expectedSet.Add([IO.Path]::GetFullPath($expectedPath)) - } - $isCargoPair = $expectedSet.Count -eq 2 - $releaseRoot = $null - if ($isCargoPair) { - $releaseRoot = Split-Path $artifact -Parent - $expectedMain = [IO.Path]::GetFullPath((Join-Path $releaseRoot 'waggle.exe')) - $expectedDependency = [IO.Path]::GetFullPath((Join-Path $releaseRoot 'deps\waggle.exe')) - if (-not [string]::Equals( - $artifact, - $expectedMain, - [StringComparison]::OrdinalIgnoreCase - ) -or -not $expectedSet.Contains($expectedMain) -or - -not $expectedSet.Contains($expectedDependency)) { - throw 'Rollback hard-link inventory does not match the exact Cargo executable pair.' - } - $dependency = Get-TrustedPath ` - $expectedDependency 'Rollback Cargo dependency' -AllowHardLink - if ((Get-FileHash -LiteralPath $dependency -Algorithm SHA256).Hash -cne - $ExpectedOriginalSha256.ToUpperInvariant()) { - throw 'Rollback Cargo dependency no longer matches the expected original digest.' - } - $backupLinks = @(Get-HardLinkPaths $backup) - $backupSet = [Collections.Generic.HashSet[string]]::new( - [StringComparer]::OrdinalIgnoreCase - ) - foreach ($backupLink in $backupLinks) { [void]$backupSet.Add($backupLink) } - if ($backupSet.Count -ne 2 -or - -not $backupSet.Contains($backup) -or - -not $backupSet.Contains($expectedDependency)) { - throw 'Rollback backup has unexpected hard-link topology.' - } - } elseif ($expectedSet.Count -ne 1 -or -not $expectedSet.Contains($artifact)) { - throw 'Rollback regular-file inventory must contain only the exact artifact path.' - } else { - $backupItem = Get-Item -LiteralPath $backup -Force - $backupLinkType = $backupItem.PSObject.Properties['LinkType'] - if ($null -ne $backupLinkType -and - -not [string]::IsNullOrEmpty([string]$backupLinkType.Value)) { - throw 'Rollback regular-file backup unexpectedly has linked-file topology.' - } - } - - $failedReplacement = Join-Path ` - (Split-Path $backup -Parent) ` - "failed-replacement-$([Guid]::NewGuid().ToString('N')).bin" - [IO.File]::Replace($backup, $artifact, $failedReplacement, $true) - try { - if ((Get-FileHash -LiteralPath $artifact -Algorithm SHA256).Hash -cne - $ExpectedOriginalSha256.ToUpperInvariant()) { - throw 'Rollback did not restore the exact original artifact bytes.' - } - if ($isCargoPair) { - Assert-ApprovedHardLinkTopology $artifact $releaseRoot - } else { - $restoredItem = Get-Item -LiteralPath $artifact -Force - $restoredLinkType = $restoredItem.PSObject.Properties['LinkType'] - if ($null -ne $restoredLinkType -and - -not [string]::IsNullOrEmpty([string]$restoredLinkType.Value)) { - throw 'Rollback restored regular artifact with unexpected linked-file topology.' - } - } - } finally { - if (Test-Path -LiteralPath $failedReplacement -PathType Leaf) { - [IO.File]::Delete($failedReplacement) - } - } -} - -function Get-ApprovedArtifact { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [object]$SigningSession, - [switch]$AllowDetachedMain - ) - - $context = $SigningSession.Context - $tauriRoot = $context.TauriRoot - $resourcesRoot = $context.ResourcesRoot - $releaseRoot = $context.ReleaseRoot - $artifact = Get-TrustedPath $Path 'Signing artifact' -AllowHardLink - $tempRoot = $SigningSession.TempRoot - $version = [string](Get-Content -Raw -LiteralPath $context.ConfigPath | ConvertFrom-Json).version - if ($version -notmatch '^\d+\.\d+\.\d+$') { throw 'Tauri version is not strict semantic version.' } - - $kind = Get-ArtifactPolicyKind $artifact $releaseRoot $resourcesRoot $tempRoot $version - Assert-ApprovedHardLinkTopology $artifact $releaseRoot -AllowDetachedMain:$AllowDetachedMain - if ($kind -eq 'MSI') { Assert-MsiFile $artifact } else { Assert-PeFile $artifact } - return $artifact -} - -function Assert-WaggleSignedArtifact { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$SignTool - ) - - & $SignTool verify /pa /all /v $Path - if ($LASTEXITCODE -ne 0) { - throw "Signed artifact verification failed with SignTool exit code $LASTEXITCODE." - } - - $signature = Get-AuthenticodeSignature -LiteralPath $Path - if ($signature.Status -ne [Management.Automation.SignatureStatus]::Valid -or - [string]$signature.SignatureType -cne 'Authenticode' -or - $null -eq $signature.SignerCertificate -or - $null -eq $signature.TimeStamperCertificate) { - throw 'Signed artifact lacks a valid, timestamped Authenticode signature.' - } - if (-not [string]::Equals( - [string]$signature.SignerCertificate.Subject, - $ApprovedPublisher, - [StringComparison]::Ordinal - )) { - throw 'Signed artifact publisher does not match the repository-approved identity.' - } - $hasCodeSigningEku = @( - $signature.SignerCertificate.Extensions | - Where-Object { $_ -is [Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension] } | - ForEach-Object { $_.EnhancedKeyUsages } | - Where-Object { $_.Value -eq $CodeSigningOid } - ).Count -gt 0 - if (-not $hasCodeSigningEku) { - throw 'Signed artifact certificate lacks the Code Signing EKU.' - } -} - -function Write-WaggleJsonNoBom { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [object]$Value - ) - [IO.File]::WriteAllText( - $Path, - ($Value | ConvertTo-Json -Depth 32), - [Text.UTF8Encoding]::new($false) - ) -} - -function Write-WaggleSigningOverride { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$WrapperPath, - [AllowNull()] [string]$ResourcesRoot = $null, - [switch]$EnableSigning - ) - $windows = [ordered]@{} - if ($EnableSigning) { - $windows.signCommand = [ordered]@{ - cmd = $SystemPowerShellPath - args = @( - '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', - '-File', $WrapperPath, '-ArtifactPath', '%1' - ) - } - } - $bundle = [ordered]@{ - active = $true - targets = @('nsis') - windows = $windows - } - if (-not [string]::IsNullOrWhiteSpace($ResourcesRoot)) { - $trustedResourcesRoot = Get-TrustedPath ` - $ResourcesRoot 'Signing override resource root' 'Container' - $resourceMap = [ordered]@{} - $resourceMap[$trustedResourcesRoot] = 'resources' - $bundle.resources = $resourceMap - } - Write-WaggleJsonNoBom $Path ([ordered]@{ - build = [ordered]@{ beforeBuildCommand = ''; beforeBundleCommand = '' } - bundle = $bundle - }) - return Get-TrustedPath $Path 'Tauri signing override config' -} - -function Get-NsisPayloadInventory { - param( - [Parameter(Mandatory = $true)] [string]$InstallerPath, - [Parameter(Mandatory = $true)] [string]$InventoryTool - ) - $installer = Get-TrustedPath $InstallerPath 'NSIS installer inventory artifact' -AllowHardLink - $output = @(& $InventoryTool l -slt -- $installer) - if ($LASTEXITCODE -ne 0) { - throw "NSIS payload inventory failed with 7-Zip exit code $LASTEXITCODE." - } - $afterDelimiter = $false - $paths = [Collections.Generic.List[string]]::new() - $uniquePaths = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) - foreach ($line in $output) { - if ([string]$line -ceq '----------') { - $afterDelimiter = $true - continue - } - if ($afterDelimiter -and [string]$line -cmatch '^Path = (.+)$' -and - $Matches[1] -cne '[0]') { - $path = [string]$Matches[1] - if ($path -match '[\x00-\x1F\x7F]' -or [IO.Path]::IsPathRooted($path) -or - $path -match '(^|[\\/])\.\.?(?:[\\/]|$)' -or $path -match ':' -or - -not $uniquePaths.Add($path)) { - throw 'NSIS payload inventory contains an unsafe, duplicate, or case-colliding path.' - } - $paths.Add($path) - } - } - $paths.Sort([StringComparer]::Ordinal) - $inventory = @($paths) - if ($inventory.Count -lt 10 -or $inventory -notcontains 'waggle.exe') { - throw 'NSIS payload inventory is incomplete or missing waggle.exe.' - } - return $inventory -} - -function Expand-NsisPayloadManifest { - param( - [Parameter(Mandatory = $true)] [string]$InstallerPath, - [Parameter(Mandatory = $true)] [string]$InventoryTool, - [Parameter(Mandatory = $true)] [string]$ExtractionRoot - ) - $installer = Get-TrustedPath $InstallerPath 'NSIS payload artifact' -AllowHardLink - $expectedPaths = @(Get-NsisPayloadInventory $installer $InventoryTool) - $root = New-PrivateDirectory $ExtractionRoot - if (@(Get-ChildItem -LiteralPath $root -Force).Count -ne 0) { - throw 'NSIS payload extraction root must be empty.' - } - & $InventoryTool x -y "-o$root" -- $installer | Out-Null - if ($LASTEXITCODE -ne 0) { - throw "NSIS payload extraction failed with 7-Zip exit code $LASTEXITCODE." - } - $entries = [Collections.Generic.List[object]]::new() - $actualPaths = [Collections.Generic.List[string]]::new() - foreach ($file in @(Get-ChildItem -LiteralPath $root -Recurse -File -Force)) { - $trustedFile = Get-TrustedPath $file.FullName 'Extracted NSIS payload' - $relative = (Get-ContainedRelativePath $trustedFile $root).Replace('/', '\') - $actualPaths.Add($relative) - $entries.Add([pscustomobject][ordered]@{ - path = $relative - sha256 = (Get-FileHash -LiteralPath $trustedFile -Algorithm SHA256).Hash - size = [long]$file.Length - extractedPath = $trustedFile - }) - } - $actualPaths.Sort([StringComparer]::Ordinal) - if ($actualPaths.Count -ne $expectedPaths.Count -or - [string]::Join("`n", $actualPaths) -cne [string]::Join("`n", $expectedPaths)) { - throw 'Extracted NSIS payload roster differs from the exact archive inventory.' - } - return @($entries | Sort-Object { [string]$_.path }) -} - -function Get-WagglePayloadManifestSha256 { - param([Parameter(Mandatory = $true)] [object[]]$Payloads) - $canonical = @($Payloads | Sort-Object { [string]$_.path } | ForEach-Object { - [ordered]@{ path = [string]$_.path; sha256 = [string]$_.sha256; size = [long]$_.size } - }) | ConvertTo-Json -Depth 8 -Compress - return [Convert]::ToHexString( - [Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($canonical)) - ) -} - -function Assert-WaggleUnsignedPayloadResourceProjection { - param( - [Parameter(Mandatory = $true)] [object[]]$Payloads, - [Parameter(Mandatory = $true)] [object]$ResourcesInventory - ) - - $payloadResources = @( - @($Payloads) | - Where-Object { ([string]$_.path).StartsWith('resources\', [StringComparison]::Ordinal) } | - ForEach-Object { - [pscustomobject][ordered]@{ - path = ([string]$_.path).Substring('resources\'.Length) - size = [long]$_.size - sha256 = [string]$_.sha256 - } - } - ) - $expectedResources = @((Get-RequiredPropertyValue ` - $ResourcesInventory 'entries' 'Hosted build resourcesInventory')) - Assert-WaggleCanonicalInventoryEntries ` - $payloadResources 'Unsigned NSIS payload resource projection' - Assert-WaggleCanonicalInventoryEntries ` - $expectedResources 'Hosted build resourcesInventory' - if ($payloadResources.Count -ne $expectedResources.Count) { - throw 'Unsigned NSIS payload resource projection does not match build receipt.' - } - for ($index = 0; $index -lt $payloadResources.Count; $index++) { - if ([string]$payloadResources[$index].path -cne [string]$expectedResources[$index].path -or - [long]$payloadResources[$index].size -ne [long]$expectedResources[$index].size -or - -not [string]::Equals( - [string]$payloadResources[$index].sha256, - [string]$expectedResources[$index].sha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Unsigned NSIS payload resource projection does not match build receipt.' - } - } -} - -function New-WagglePendingLedger { - param( - [Parameter(Mandatory = $true)] [string]$SessionId, - [Parameter(Mandatory = $true)] [string]$ManifestSha256, - [Parameter(Mandatory = $true)] [object[]]$Slots - ) - return [pscustomobject][ordered]@{ - schemaVersion = 3 - sessionId = $SessionId - manifestSha256 = $ManifestSha256 - state = 'open' - terminalAtUtc = $null - terminalReceiptSha256 = $null - entries = @($Slots | ForEach-Object { - [pscustomobject][ordered]@{ - slotId = [string]$_.id - order = [int]$_.order - kind = [string]$_.kind - status = 'pending' - attempts = 0 - reservationId = $null - path = $null - preSignSha256 = $null - reservedAtUtc = $null - completedAtUtc = $null - postSignSha256 = $null - signerSubject = $null - } - }) - } -} - -function Resolve-WagglePreflightFixedPath { - param( - [Parameter(Mandatory = $true)] [string]$SigningPath, - [Parameter(Mandatory = $true)] [string]$SigningTargetRoot, - [Parameter(Mandatory = $true)] [string]$PreflightTargetRoot - ) - - $relativePath = Get-ContainedRelativePath ` - ([IO.Path]::GetFullPath($SigningPath)) ` - ([IO.Path]::GetFullPath($SigningTargetRoot)) - if ($null -eq $relativePath) { - throw 'Preflight signing path escaped the signing target root.' - } - return Get-TrustedPath ` - (Join-Path $PreflightTargetRoot $relativePath) ` - 'Preflight signing artifact' -AllowHardLink -} - -function New-WaggleSigningManifest { - param( - [Parameter(Mandatory = $true)] [object]$Context, - [Parameter(Mandatory = $true)] [object[]]$Payloads, - [Parameter(Mandatory = $true)] [string]$PreflightTargetRoot, - [AllowNull()] [object]$BuildReceipt = $null - ) - $sessionId = [Environment]::GetEnvironmentVariable('WAGGLE_SIGNING_SESSION_ID') - $sessionDirectory = Assert-PrivateDirectoryAcl ` - (Join-Path (Join-Path $Context.TauriRoot 'target\.signing-sessions') "run-$sessionId") ` - 'Signing session directory' - $manifestPath = Join-Path $sessionDirectory 'manifest.json' - $ledgerPath = Join-Path $sessionDirectory 'callback-ledger.json' - if (Test-Path -LiteralPath $manifestPath -or Test-Path -LiteralPath $ledgerPath) { - throw 'Signing session manifest or ledger already exists.' - } - - $version = [string](Get-Content -Raw -LiteralPath $Context.ConfigPath | ConvertFrom-Json).version - $fixedPaths = @(Get-ExpectedNsisFixedPaths $Context $version) - $packagedPaths = @(Get-ExpectedNsisPackagedPaths) - $trustedPreflightTargetRoot = Get-TrustedPath ` - $PreflightTargetRoot 'Preflight signing target root' 'Container' - $preflightReleaseRoot = Get-TrustedPath ` - (Join-Path $trustedPreflightTargetRoot 'x86_64-pc-windows-msvc\release') ` - 'Preflight signing release root' 'Container' - $slots = [Collections.Generic.List[object]]::new() - for ($index = 0; $index -lt $fixedPaths.Count; $index++) { - $fixedPath = [IO.Path]::GetFullPath($fixedPaths[$index]) - $preflightPath = Resolve-WagglePreflightFixedPath ` - $fixedPath $Context.TargetRoot $trustedPreflightTargetRoot - Assert-PeFile $preflightPath - Assert-ApprovedHardLinkTopology ` - $preflightPath $preflightReleaseRoot - if ((Get-AuthenticodeSignature -LiteralPath $preflightPath).Status -ne - [Management.Automation.SignatureStatus]::NotSigned) { - throw 'Unsigned NSIS preflight contains an already signed or invalid callback artifact.' - } - $slots.Add([pscustomobject][ordered]@{ - id = 'fixed-{0:d2}' -f ($index + 1) - order = $index + 1 - kind = 'fixed' - maxUses = 1 - path = $fixedPath - packagedPath = $packagedPaths[$index] - preSignSha256 = if ($index -eq 0) { - Get-NsisPatchedMainSha256 $preflightPath - } else { - (Get-FileHash -LiteralPath $preflightPath -Algorithm SHA256).Hash - } - }) - } - $slots.Add([pscustomobject][ordered]@{ - id = 'nsis-uninstaller' - order = 13 - kind = 'generated-nsis-uninstaller' - maxUses = 1 - pathPattern = $NsisUninstallerPattern - evidencePath = Join-Path $sessionDirectory 'signed-evidence\13-nsis-uninstaller.exe' - }) - $installerPath = Join-Path ` - $Context.ReleaseRoot "bundle\nsis\Waggle_${version}_x64-setup.exe" - $slots.Add([pscustomobject][ordered]@{ - id = 'nsis-installer' - order = 14 - kind = 'generated-nsis-installer' - maxUses = 1 - path = $installerPath - }) - - $toolchain = [ordered]@{ - wrapperPath = $Context.WrapperPath - wrapperSha256 = (Get-FileHash -LiteralPath $Context.WrapperPath -Algorithm SHA256).Hash - tauriConfigPath = $Context.ConfigPath - tauriConfigSha256 = (Get-FileHash -LiteralPath $Context.ConfigPath -Algorithm SHA256).Hash - tauriOverrideConfigPath = $Context.OverrideConfigPath - tauriOverrideConfigSha256 = (Get-FileHash -LiteralPath $Context.OverrideConfigPath -Algorithm SHA256).Hash - tauriCliPath = $Context.TauriCliPath - tauriCliSha256 = $Context.TauriCliSha256 - tauriCliPackagePath = $Context.TauriCliPackagePath - tauriCliPackageSha256 = $Context.TauriCliPackageSha256 - tauriCliMainPath = $Context.TauriCliMainPath - tauriCliMainSha256 = $Context.TauriCliMainSha256 - tauriCliIndexPath = $Context.TauriCliIndexPath - tauriCliIndexSha256 = $Context.TauriCliIndexSha256 - tauriNativePackagePath = $Context.TauriNativePackagePath - tauriNativePackageSha256 = $Context.TauriNativePackageSha256 - tauriNativeBinaryPath = $Context.TauriNativeBinaryPath - tauriNativeBinarySha256 = $Context.TauriNativeBinarySha256 - tauriCliVersion = $Context.TauriCliVersion - nsisRoot = $Context.NsisRoot - nsisClosureSha256 = $Context.NsisClosureSha256 - makensisPath = $Context.MakensisPath - makensisSha256 = $Context.MakensisSha256 - gitPath = $Context.GitPath - gitSha256 = $Context.GitSha256 - gitRuntimePath = $Context.GitRuntimePath - gitRuntimeSha256 = $Context.GitRuntimeSha256 - nodePath = $Context.NodePath - nodeSha256 = $Context.NodeSha256 - sevenZipPath = $Context.SevenZipPath - sevenZipSha256 = $Context.SevenZipSha256 - signToolPath = $Context.SignToolPath - signToolSha256 = $Context.SignToolSha256 - artifactSigningPackagePath = $Context.ArtifactSigningPackagePath - artifactSigningPackageSha256 = $Context.ArtifactSigningPackageSha256 - artifactSigningX64ManifestSha256 = $Context.ArtifactSigningX64ManifestSha256 - } - if ($null -ne $Context.PortableToolchainRoot) { - $toolchain.portableToolchainRoot = $Context.PortableToolchainRoot - $toolchain.sevenZipDllPath = $Context.SevenZipDllPath - $toolchain.sevenZipDllSha256 = $Context.SevenZipDllSha256 - $toolchain.portableToolchainReceiptPath = $Context.PortableToolchainReceiptPath - $toolchain.portableToolchainReceiptSha256 = $Context.PortableToolchainReceiptSha256 - $toolchain.portableToolchainInventorySha256 = $PortableToolchainInventorySha256 - $toolchain.portableToolchainFileCount = $PortableToolchainFileCount - } - $now = [DateTimeOffset]::UtcNow - $manifest = [pscustomobject][ordered]@{ - schemaVersion = 1 - mode = 'nsis' - sessionId = $sessionId - sourceRevision = $Context.SourceRevision - buildReceipt = $BuildReceipt - createdAtUtc = $now.ToString('O') - expiresAtUtc = $now.AddHours(4).ToString('O') - repoRoot = $Context.RepoRoot - tauriRoot = $Context.TauriRoot - targetRoot = $Context.TargetRoot - releaseRoot = $Context.ReleaseRoot - resourcesRoot = $Context.ResourcesRoot - tempRoot = [Environment]::GetEnvironmentVariable('WAGGLE_NSIS_SIGNING_TEMP_ROOT') - ledgerPath = $ledgerPath - appVersion = $version - payloads = @($Payloads | Sort-Object { [string]$_.path } | ForEach-Object { - [pscustomobject][ordered]@{ - path = [string]$_.path - sha256 = [string]$_.sha256 - size = [long]$_.size - } - }) - toolchain = $toolchain - slots = @($slots) - } - Write-WaggleJsonNoBom $manifestPath $manifest - $manifestSha256 = (Get-FileHash -LiteralPath $manifestPath -Algorithm SHA256).Hash - Write-WaggleJsonNoBom ` - $ledgerPath (New-WagglePendingLedger $sessionId $manifestSha256 @($slots)) - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_PATH', $manifestPath) - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_SHA256', $manifestSha256) - return Get-WaggleSigningSession $Context -} - -function Get-CompletedWaggleSigningLedger { - param([Parameter(Mandatory = $true)] [object]$Session) - $ledger = Get-Content -Raw -LiteralPath $Session.LedgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-WaggleSigningLedgerState $Session $ledger - if ([string]$ledger.state -cne 'open' -or - @($ledger.entries | Where-Object { [string]$_.status -cne 'completed' }).Count -ne 0) { - throw 'Signing callback ledger is incomplete after the NSIS package.' - } - return $ledger -} - -function Assert-WaggleFinalPayloadBindings { - param( - [Parameter(Mandatory = $true)] [object]$Session, - [Parameter(Mandatory = $true)] [object]$Ledger, - [Parameter(Mandatory = $true)] [object[]]$ActualPayloads, - [Parameter(Mandatory = $true)] [scriptblock]$SignatureVerifier - ) - $expectedPayloads = @($Session.Manifest.payloads | Sort-Object { [string]$_.path }) - $actualPayloadsSorted = @($ActualPayloads | Sort-Object { [string]$_.path }) - if ($expectedPayloads.Count -ne $actualPayloadsSorted.Count -or - [string]::Join("`n", @($expectedPayloads | ForEach-Object { [string]$_.path })) -cne - [string]::Join("`n", @($actualPayloadsSorted | ForEach-Object { [string]$_.path }))) { - throw 'Final signed NSIS payload inventory differs from the unsigned preflight inventory.' - } - $fixedSlots = @($Session.Manifest.slots | Where-Object { [string]$_.kind -ceq 'fixed' }) - $bindings = [Collections.Generic.List[object]]::new() - for ($index = 0; $index -lt $expectedPayloads.Count; $index++) { - $expected = $expectedPayloads[$index] - $actual = $actualPayloadsSorted[$index] - $slot = @($fixedSlots | Where-Object { - [string]$_.packagedPath -ceq [string]$expected.path - }) - $expectedHash = [string]$expected.sha256 - $slotOrder = $null - if ($slot.Count -eq 1) { - $slotOrder = [int]$slot[0].order - $expectedHash = [string]$Ledger.entries[$slotOrder - 1].postSignSha256 - } elseif ($slot.Count -gt 1) { - throw 'Multiple signing slots map to one packaged NSIS payload.' - } - if (-not [string]::Equals( - [string]$actual.sha256, - $expectedHash, - [StringComparison]::OrdinalIgnoreCase - )) { - throw "Final NSIS payload bytes differ for '$([string]$expected.path)'." - } - if ($null -ne $slotOrder) { - & $SignatureVerifier ([string]$actual.extractedPath) $Session.Context.SignToolPath - $bindings.Add([pscustomobject][ordered]@{ - order = $slotOrder - kind = 'packaged-signed-payload' - packagedPath = [string]$expected.path - sha256 = $expectedHash - }) - } - } - return @($bindings | Sort-Object order) -} - -function Assert-WaggleSigningPackageComplete { - param( - [Parameter(Mandatory = $true)] [object]$Session, - [AllowNull()] [object[]]$ActualPayloads, - [AllowNull()] [scriptblock]$SignatureVerifier - ) - - $ledger = Get-CompletedWaggleSigningLedger $Session - if ($null -eq $SignatureVerifier) { - $SignatureVerifier = { param($Path, $SignTool) Assert-WaggleSignedArtifact $Path $SignTool } - } - $installerEntry = @($ledger.entries | Where-Object { [int]$_.order -eq 14 }) - if ($installerEntry.Count -ne 1) { - throw 'Signing callback ledger lacks the final NSIS installer entry.' - } - $installer = Get-TrustedPath ([string]$installerEntry[0].path) 'Final NSIS installer' - if (-not [string]::Equals( - (Get-FileHash -LiteralPath $installer -Algorithm SHA256).Hash, - [string]$installerEntry[0].postSignSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Final NSIS installer hash does not match the completed callback ledger.' - } - $installerLock = Open-ReadLock $installer - $uninstallerLock = $null - $extractionRoot = $null - $validationSucceeded = $false - try { - & $SignatureVerifier $installer $Session.Context.SignToolPath - if ($null -eq $ActualPayloads) { - $extractionRoot = Join-Path $Session.SessionDirectory 'final-payload-extraction' - $ActualPayloads = @(Expand-NsisPayloadManifest ` - $installer $Session.Context.SevenZipPath $extractionRoot) - } - $artifactBindings = [Collections.Generic.List[object]]::new() - foreach ($binding in @(Assert-WaggleFinalPayloadBindings ` - $Session $ledger $ActualPayloads $SignatureVerifier)) { - $artifactBindings.Add($binding) - } - $uninstallerSlot = @($Session.Manifest.slots | Where-Object { - [string]$_.kind -ceq 'generated-nsis-uninstaller' - }) - if ($uninstallerSlot.Count -ne 1) { - throw 'Signing manifest lacks the generated NSIS uninstaller evidence slot.' - } - $uninstallerEvidence = Get-TrustedPath ` - ([string]$uninstallerSlot[0].evidencePath) 'Signed NSIS uninstaller evidence' - $uninstallerLock = Open-ReadLock $uninstallerEvidence - $uninstallerEntry = $ledger.entries[[int]$uninstallerSlot[0].order - 1] - if (-not [string]::Equals( - (Get-FileHash -LiteralPath $uninstallerEvidence -Algorithm SHA256).Hash, - [string]$uninstallerEntry.postSignSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Signed NSIS uninstaller evidence differs from the callback ledger.' - } - & $SignatureVerifier $uninstallerEvidence $Session.Context.SignToolPath - $artifactBindings.Add([pscustomobject][ordered]@{ - order = [int]$uninstallerEntry.order - kind = 'generated-nsis-uninstaller-evidence' - evidencePath = $uninstallerEvidence - sha256 = [string]$uninstallerEntry.postSignSha256 - }) - $artifactBindings.Add([pscustomobject][ordered]@{ - order = [int]$installerEntry[0].order - kind = 'generated-nsis-installer' - path = $installer - sha256 = [string]$installerEntry[0].postSignSha256 - }) - $validationSucceeded = $true - } finally { - if ($null -ne $extractionRoot -and (Test-Path -LiteralPath $extractionRoot)) { - Remove-Item -LiteralPath $extractionRoot -Recurse -Force -ErrorAction SilentlyContinue - } - if (-not $validationSucceeded) { - if ($null -ne $uninstallerLock) { $uninstallerLock.Dispose() } - $installerLock.Dispose() - } - } - - try { - if (-not [string]::Equals( - (Get-FileHash -LiteralPath $installer -Algorithm SHA256).Hash, - [string]$installerEntry[0].postSignSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Final NSIS installer changed before provenance publication.' - } - $terminalAt = [DateTimeOffset]::UtcNow.ToString('O') - $receipt = [pscustomobject][ordered]@{ - schemaVersion = 1 - status = 'sealed' - sessionId = $Session.Id - sourceRevision = $Session.Context.SourceRevision - manifestPath = $Session.ManifestPath - manifestSha256 = $Session.ManifestSha256 - callbackLedgerPath = $Session.LedgerPath - installerPath = $installer - installerSha256 = [string]$installerEntry[0].postSignSha256 - signerSubject = [string]$installerEntry[0].signerSubject - payloadManifestSha256 = Get-WagglePayloadManifestSha256 $ActualPayloads - artifactBindings = @($artifactBindings | Sort-Object order) - terminalAtUtc = $terminalAt - } - $receiptPath = Publish-WaggleTerminalReceipt $Session 'sealed' $receipt { - param($activeLedger) - if (@($activeLedger.entries | Where-Object { [string]$_.status -cne 'completed' }).Count -ne 0) { - throw 'Signing callback ledger changed before final sealing.' - } - } - return [pscustomobject]@{ - InstallerPath = $installer - ReceiptPath = $receiptPath - } - } finally { - if ($null -ne $uninstallerLock) { $uninstallerLock.Dispose() } - $installerLock.Dispose() - } -} - -function Install-WaggleArtifactSigningPackage { - param( - [Parameter(Mandatory = $true)] [string]$TauriRoot, - [string]$SourcePath = '' - ) - $destinationDirectoryPath = Join-Path $TauriRoot 'target\.artifact-signing-tools' - $destinationPath = Join-Path ` - $destinationDirectoryPath 'Microsoft.ArtifactSigning.Client.1.0.128.nupkg' - if (Test-Path -LiteralPath $destinationPath -PathType Leaf) { - $destination = Get-TrustedPath $destinationPath 'Artifact Signing package' - if ((Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash -cne - $ArtifactSigningPackageSha256) { - throw 'Existing production Artifact Signing package has the wrong SHA-256 digest.' - } - return $destination - } - if ([string]::IsNullOrWhiteSpace($SourcePath)) { - throw 'Production Artifact Signing package is not provisioned by the protected hosted signing workflow.' - } - $source = Get-TrustedPath $SourcePath 'Artifact Signing package source' - $sourceLock = Open-ReadLock $source - $temporaryPath = $null - try { - if ((Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash -cne - $ArtifactSigningPackageSha256) { - throw 'Artifact Signing package source does not match the pinned SHA-256 digest.' - } - $destinationDirectory = New-PrivateDirectory $destinationDirectoryPath - $temporaryPath = Join-Path ` - $destinationDirectory "artifact-signing.$([Guid]::NewGuid().ToString('N')).tmp" - [IO.File]::Copy($source, $temporaryPath, $false) - if ((Get-FileHash -LiteralPath $temporaryPath -Algorithm SHA256).Hash -cne - $ArtifactSigningPackageSha256) { - throw 'Provisioned Artifact Signing package copy failed digest verification.' - } - [IO.File]::Move($temporaryPath, $destinationPath) - $temporaryPath = $null - return Get-TrustedPath $destinationPath 'Artifact Signing package' - } finally { - $sourceLock.Dispose() - if ($null -ne $temporaryPath -and (Test-Path -LiteralPath $temporaryPath -PathType Leaf)) { - try { [IO.File]::Delete($temporaryPath) } catch { } - } - } -} - -function Open-WagglePackageToolchainLocks { - param([Parameter(Mandatory = $true)] [object]$Context) - $bindings = @( - @($Context.WrapperPath, (Get-FileHash -LiteralPath $Context.WrapperPath -Algorithm SHA256).Hash, 'Signing wrapper'), - @($Context.NodePath, $Context.NodeSha256, 'Node.js runtime'), - @($Context.SevenZipPath, $Context.SevenZipSha256, '7-Zip'), - @($Context.SevenZipDllPath, $Context.SevenZipDllSha256, '7-Zip runtime library'), - @($Context.TauriCliPath, $Context.TauriCliSha256, 'Tauri CLI'), - @($Context.TauriCliPackagePath, $Context.TauriCliPackageSha256, 'Tauri CLI package'), - @($Context.TauriCliMainPath, $Context.TauriCliMainSha256, 'Tauri CLI main module'), - @($Context.TauriCliIndexPath, $Context.TauriCliIndexSha256, 'Tauri CLI native loader'), - @($Context.TauriNativePackagePath, $Context.TauriNativePackageSha256, 'Tauri native package'), - @($Context.TauriNativeBinaryPath, $Context.TauriNativeBinarySha256, 'Tauri native binary'), - @($Context.MakensisPath, $Context.MakensisSha256, 'makensis'), - @($Context.GitPath, $Context.GitSha256, 'Git executable'), - @($Context.GitRuntimePath, $Context.GitRuntimeSha256, 'Git runtime'), - @($Context.SignToolPath, $Context.SignToolSha256, 'SignTool'), - @($Context.ArtifactSigningPackagePath, $Context.ArtifactSigningPackageSha256, 'Artifact Signing package') - ) - $locks = [Collections.Generic.List[IDisposable]]::new() - try { - foreach ($portableLock in @($Context.PortableToolchainLocks)) { - $locks.Add($portableLock) - } - $Context.PortableToolchainLocks.Clear() - $trackedBundleInputs = @( - 'app/src-tauri/tauri.conf.json', - 'app/src-tauri/Cargo.toml', - 'app/src-tauri/Cargo.lock', - 'app/src-tauri/build.rs', - 'app/src-tauri/nsis/installer.nsi', - 'app/src-tauri/icons/32x32.png', - 'app/src-tauri/icons/128x128.png', - 'app/src-tauri/icons/128x128@2x.png', - 'app/src-tauri/icons/icon.icns', - 'app/src-tauri/icons/icon.ico', - 'app/src-tauri/icons/icon.png' - ) - foreach ($relativePath in $trackedBundleInputs) { - $trackedPath = Get-TrustedPath ` - (Join-Path $Context.RepoRoot $relativePath) ` - 'Tracked Tauri packaging input' -AllowHardLink - $locks.Add((Open-ReadLock $trackedPath)) - } - $nsisInventory = New-WagglePrebuiltInventory -Root $Context.NsisRoot - if (@($nsisInventory.entries).Count -ne 442 -or - -not [string]::Equals( - [string]$nsisInventory.sha256, - [string]$Context.NsisClosureSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'NSIS compiler closure does not match the pinned 442-file inventory.' - } - $nsisLease = Open-WaggleValidatedPrebuiltTree ` - $Context.NsisRoot $nsisInventory 'NSIS compiler closure' - foreach ($nsisLock in $nsisLease.Locks) { $locks.Add($nsisLock) } - $nsisLease.Locks.Clear() - foreach ($binding in $bindings) { - $path = Get-TrustedPath ([string]$binding[0]) ([string]$binding[2]) -AllowHardLink - $lock = Open-ReadLock $path - if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -cne [string]$binding[1]) { - $lock.Dispose() - throw "$($binding[2]) does not match the pinned production-build digest." - } - $locks.Add($lock) - } - $lockedRevision = [string](& $Context.GitPath -C $Context.RepoRoot rev-parse --verify HEAD) - $lockedStatus = @(& $Context.GitPath -C $Context.RepoRoot status --porcelain=v1 --untracked-files=all) - if ($LASTEXITCODE -ne 0 -or - $lockedRevision -cne [string]$Context.SourceRevision -or - $lockedStatus.Count -ne 0) { - throw 'Exact repository revision changed before packaging inputs were locked.' - } - Assert-WaggleHostedSigningBoundary $lockedRevision ([string]( - Get-Content -Raw -LiteralPath $Context.ConfigPath | ConvertFrom-Json - ).version) - return $locks - } catch { - foreach ($lock in $locks) { $lock.Dispose() } - throw - } -} - -function Invoke-WagglePinnedNodeScript { - param( - [Parameter(Mandatory = $true)] [object]$Context, - [Parameter(Mandatory = $true)] [string]$ScriptPath, - [Parameter(Mandatory = $true)] [string]$WorkingDirectory, - [string[]]$Arguments = @(), - [string]$Label = 'Node build step' - ) - Push-Location $WorkingDirectory - try { - & $Context.NodePath $ScriptPath @Arguments - if ($LASTEXITCODE -ne 0) { - throw "$Label failed with exit code $LASTEXITCODE." - } - } finally { - Pop-Location - } -} - -function Assert-WaggleHostedResourceInventoryProjection { - param( - [Parameter(Mandatory = $true)] [object]$TargetInventory, - [Parameter(Mandatory = $true)] [object]$ResourcesInventory - ) - - $projection = @( - @((Get-RequiredPropertyValue ` - $TargetInventory 'entries' 'Hosted build targetInventory')) | - Where-Object { ([string]$_.path).StartsWith('resources\', [StringComparison]::Ordinal) } | - ForEach-Object { - [pscustomobject][ordered]@{ - path = ([string]$_.path).Substring('resources\'.Length) - size = [long]$_.size - sha256 = [string]$_.sha256 - } - } - ) - $resourceEntries = @((Get-RequiredPropertyValue ` - $ResourcesInventory 'entries' 'Hosted build resourcesInventory')) - Assert-WaggleCanonicalInventoryEntries ` - $projection 'Hosted build target resource projection' - Assert-WaggleCanonicalInventoryEntries ` - $resourceEntries 'Hosted build resourcesInventory' - if ($projection.Count -ne $resourceEntries.Count) { - throw 'Hosted build target resource projection does not match resourcesInventory.' - } - for ($index = 0; $index -lt $projection.Count; $index++) { - if ([string]$projection[$index].path -cne [string]$resourceEntries[$index].path -or - [long]$projection[$index].size -ne [long]$resourceEntries[$index].size -or - -not [string]::Equals( - [string]$projection[$index].sha256, - [string]$resourceEntries[$index].sha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Hosted build target resource projection does not match resourcesInventory.' - } - } - if (-not [string]::Equals( - (Get-WaggleInventorySha256 $projection), - [string](Get-RequiredPropertyValue ` - $ResourcesInventory 'sha256' 'Hosted build resourcesInventory'), - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Hosted build target resource projection does not match resourcesInventory.' - } -} - -function Get-WaggleHostedBuildReceipt { - param( - [Parameter(Mandatory = $true)] [string]$Path, - [Parameter(Mandatory = $true)] [string]$ExpectedSha256, - [Parameter(Mandatory = $true)] [string]$ExpectedSourceRevision - ) - - if ($ExpectedSha256 -notmatch '^[0-9A-Fa-f]{64}$') { - throw 'Build receipt SHA-256 must be one exact digest.' - } - $receiptPath = Get-TrustedPath $Path 'Hosted build receipt' - $lock = Open-ReadLock $receiptPath - try { - if (-not [string]::Equals( - (Get-FileHash -LiteralPath $receiptPath -Algorithm SHA256).Hash, - $ExpectedSha256, - [StringComparison]::OrdinalIgnoreCase - )) { - throw 'Hosted build receipt does not match its SHA-256 handoff.' - } - try { - $receipt = Get-Content -Raw -LiteralPath $receiptPath | - ConvertFrom-Json -Depth 32 -DateKind String - } catch { - throw 'Hosted build receipt is not valid JSON.' - } - if ([int](Get-RequiredPropertyValue $receipt 'schemaVersion' 'Hosted build receipt') -ne 1 -or - [string](Get-RequiredPropertyValue $receipt 'repository' 'Hosted build receipt') -cne - 'marolinik/waggle-os' -or - [string](Get-RequiredPropertyValue $receipt 'sourceRevision' 'Hosted build receipt') -cne - $ExpectedSourceRevision -or - [string](Get-RequiredPropertyValue $receipt 'targetTriple' 'Hosted build receipt') -cne - 'x86_64-pc-windows-msvc') { - throw 'Hosted build receipt does not bind the approved repository, revision, and target.' - } - foreach ($name in @('targetInventory', 'resourcesInventory')) { - $inventory = Get-RequiredPropertyValue $receipt $name 'Hosted build receipt' - $entries = @((Get-RequiredPropertyValue $inventory 'entries' "Hosted build $name")) - Assert-WaggleCanonicalInventoryEntries $entries "Hosted build $name" - if (-not [string]::Equals( - (Get-WaggleInventorySha256 $entries), - [string](Get-RequiredPropertyValue $inventory 'sha256' "Hosted build $name"), - [StringComparison]::OrdinalIgnoreCase - )) { - throw "Hosted build $name aggregate digest is invalid." - } - } - Assert-WaggleHostedResourceInventoryProjection ` - $receipt.targetInventory $receipt.resourcesInventory - $checker = Get-RequiredPropertyValue $receipt 'checker' 'Hosted build receipt' - if ([int](Get-RequiredPropertyValue $checker 'exitCode' 'Hosted build checker') -ne 0 -or - [string](Get-RequiredPropertyValue $checker 'sha256' 'Hosted build checker') -notmatch - '^[0-9A-Fa-f]{64}$') { - throw 'Hosted build sidecar/resource checker did not succeed with a bound digest.' - } - return [pscustomobject]@{ Receipt = $receipt; Path = $receiptPath; Lock = $lock } - } catch { - $lock.Dispose() - throw - } -} - -function Assert-WaggleHostedSigningBoundary { - param( - [Parameter(Mandatory = $true)] [string]$ExpectedRevision, - [Parameter(Mandatory = $true)] [string]$ExpectedVersion - ) - - if ($ExpectedRevision -notmatch '^[0-9a-f]{40}$' -or - $ExpectedVersion -notmatch '^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$') { - throw 'Hosted Package mode requires exact revision and app-version inputs.' - } - $expectedTag = "v$ExpectedVersion" - $expectedRef = "refs/tags/$expectedTag" - $expectedWorkflowRef = "marolinik/waggle-os/.github/workflows/release.yml@$expectedRef" - - $expected = [ordered]@{ - GITHUB_ACTIONS = 'true' - GITHUB_EVENT_NAME = 'push' - RUNNER_ENVIRONMENT = 'github-hosted' - GITHUB_REPOSITORY = 'marolinik/waggle-os' - GITHUB_SHA = $ExpectedRevision - GITHUB_REF = $expectedRef - GITHUB_REF_TYPE = 'tag' - GITHUB_REF_NAME = $expectedTag - GITHUB_WORKFLOW_REF = $expectedWorkflowRef - GITHUB_WORKFLOW_SHA = $ExpectedRevision - } - foreach ($entry in $expected.GetEnumerator()) { - if ([Environment]::GetEnvironmentVariable([string]$entry.Key) -cne [string]$entry.Value) { - throw "Hosted Package mode requires exact $($entry.Key) boundary evidence." - } - } -} - -function Invoke-WaggleSigningPackage { - if (-not $IsWindows -or -not [Environment]::Is64BitProcess -or - $PSVersionTable.PSEdition -cne 'Core' -or - $PSVersionTable.PSVersion -lt [Version]'7.5.0') { - throw 'Production signing Package mode requires approved 64-bit PowerShell 7.5+ on Windows.' - } - $actualHost = Get-TrustedPath (Get-Process -Id $PID).Path 'Current PowerShell 7 host' -AllowHardLink - Assert-ApprovedPowerShell7Path $actualHost - - $scriptPath = Get-TrustedPath $PSCommandPath 'Signing wrapper' - $appRoot = Split-Path (Split-Path $scriptPath -Parent) -Parent - $repoRoot = Get-TrustedPath (Split-Path $appRoot -Parent) 'Repository root' 'Container' - $tauriRoot = Get-TrustedPath (Join-Path $appRoot 'src-tauri') 'Tauri root' 'Container' - if (@( - $UnsignedInputRoot, $SigningInputRoot, $BuildReceiptPath, $BuildReceiptSha256, - $PortableToolchainRoot, $PortableNodePath, $PortableGitPath, - $PortableSevenZipPath, $PortableToolchainReceiptPath, - $PortableToolchainReceiptSha256 | - Where-Object { [string]::IsNullOrWhiteSpace([string]$_) } - ).Count -ne 0) { - throw 'Hosted Package mode requires both prebuilt roots, the exact build receipt, and the complete portable toolchain handoff.' - } - $unsignedSourceRoot = Get-TrustedPath ` - $UnsignedInputRoot 'Unsigned prebuilt input root' 'Container' - $signingSourceRoot = Get-TrustedPath ` - $SigningInputRoot 'Signing prebuilt input root' 'Container' - $portableToolchain = Get-WagglePortableToolchain ` - $PortableToolchainRoot $PortableNodePath $PortableGitPath ` - $PortableSevenZipPath $PortableToolchainReceiptPath ` - $PortableToolchainReceiptSha256 ` - -DisallowedRoots @( - $repoRoot, $unsignedSourceRoot, $signingSourceRoot, - $BuildReceiptPath, $ArtifactSigningPackageSource - ) - $portableBootstrapLocks = $portableToolchain.Locks - try { - $gitLock = Open-ReadLock $portableToolchain.GitPath - try { - $sourceRevision = [string](& $portableToolchain.GitPath ` - -C $repoRoot rev-parse --verify HEAD) - if ($LASTEXITCODE -ne 0 -or $sourceRevision -notmatch '^[0-9a-f]{40}$') { - throw 'Could not resolve the exact repository source revision.' - } - } finally { - $gitLock.Dispose() - } - $appVersion = [string]( - Get-Content -Raw -LiteralPath (Join-Path $tauriRoot 'tauri.conf.json') | - ConvertFrom-Json - ).version - Assert-WaggleHostedSigningBoundary $sourceRevision $appVersion - foreach ($pair in @( - @($unsignedSourceRoot, $signingSourceRoot), - @($unsignedSourceRoot, $BuildReceiptPath), - @($signingSourceRoot, $BuildReceiptPath), - @($unsignedSourceRoot, $tauriRoot), - @($signingSourceRoot, $tauriRoot) - )) { - if (Test-WagglePathsOverlap ([string]$pair[0]) ([string]$pair[1])) { - throw 'Hosted Package input, receipt, repository, and output roots must be distinct.' - } - } - $receiptLease = Get-WaggleHostedBuildReceipt ` - $BuildReceiptPath $BuildReceiptSha256 $sourceRevision - $receipt = $receiptLease.Receipt - } catch { - foreach ($lock in $portableBootstrapLocks) { $lock.Dispose() } - throw - } - $sessionId = [Guid]::NewGuid().ToString('N') - $sessionDirectory = New-PrivateDirectory ` - (Join-Path $tauriRoot "target\.signing-sessions\run-$sessionId") - $tempRoot = New-PrivateDirectory ` - (Join-Path $tauriRoot "target\.signing-temp\run-$sessionId") - $overridePath = Join-Path $sessionDirectory 'tauri.signing-override.json' - - $environmentNames = @( - 'WAGGLE_SIGNING_SESSION_ID', 'WAGGLE_SIGNING_MANIFEST_PATH', - 'WAGGLE_SIGNING_MANIFEST_SHA256', 'CARGO_TARGET_DIR', 'TEMP', 'TMP', - 'WAGGLE_NSIS_SIGNING_TEMP_ROOT', 'WAGGLE_SIGNING_RESOURCES_ROOT', - 'WAGGLE_SIGNING_PORTABLE_TOOLCHAIN_ROOT', - 'WAGGLE_SIGNING_PORTABLE_NODE_PATH', - 'WAGGLE_SIGNING_PORTABLE_GIT_PATH', - 'WAGGLE_SIGNING_PORTABLE_SEVEN_ZIP_PATH', - 'WAGGLE_SIGNING_PORTABLE_RECEIPT_PATH', - 'WAGGLE_SIGNING_PORTABLE_RECEIPT_SHA256', - 'NODE_OPTIONS', 'NODE_PATH', - 'NAPI_RS_NATIVE_LIBRARY_PATH', 'NAPI_RS_FORCE_WASI', - 'npm_config_node_options', 'TARGET_ARCH' - ) - $savedEnvironment = @{} - foreach ($name in $environmentNames) { - $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name) - } - $session = $null - $packageLocks = $null - $unsignedSourceLease = $null - $signingSourceLease = $null - $unsignedWorkLease = $null - $signingWorkLease = $null - $unsignedWorkRoot = $null - $signingWorkRoot = $null - $preflightEvidenceRoot = $null - $unsignedExtractionRoot = $null - $unsignedOverrideLock = $null - $packageSucceeded = $false - try { - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_SESSION_ID', $sessionId) - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_PATH', $null) - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_SHA256', $null) - [Environment]::SetEnvironmentVariable( - 'WAGGLE_SIGNING_PORTABLE_TOOLCHAIN_ROOT', $portableToolchain.PortableToolchainRoot - ) - [Environment]::SetEnvironmentVariable( - 'WAGGLE_SIGNING_PORTABLE_NODE_PATH', $portableToolchain.NodePath - ) - [Environment]::SetEnvironmentVariable( - 'WAGGLE_SIGNING_PORTABLE_GIT_PATH', $portableToolchain.GitPath - ) - [Environment]::SetEnvironmentVariable( - 'WAGGLE_SIGNING_PORTABLE_SEVEN_ZIP_PATH', $portableToolchain.SevenZipPath - ) - [Environment]::SetEnvironmentVariable( - 'WAGGLE_SIGNING_PORTABLE_RECEIPT_PATH', $portableToolchain.ReceiptPath - ) - [Environment]::SetEnvironmentVariable( - 'WAGGLE_SIGNING_PORTABLE_RECEIPT_SHA256', $portableToolchain.ReceiptSha256 - ) - [Environment]::SetEnvironmentVariable('TEMP', $tempRoot) - [Environment]::SetEnvironmentVariable('TMP', $tempRoot) - [Environment]::SetEnvironmentVariable('WAGGLE_NSIS_SIGNING_TEMP_ROOT', $tempRoot) - [Environment]::SetEnvironmentVariable('NODE_OPTIONS', $null) - [Environment]::SetEnvironmentVariable('NODE_PATH', $null) - [Environment]::SetEnvironmentVariable('NAPI_RS_NATIVE_LIBRARY_PATH', $null) - [Environment]::SetEnvironmentVariable('NAPI_RS_FORCE_WASI', $null) - [Environment]::SetEnvironmentVariable('npm_config_node_options', $null) - [Environment]::SetEnvironmentVariable('TARGET_ARCH', 'x64') - - $cargoReleaseRelative = 'x86_64-pc-windows-msvc\release' - $sourceDisallowedRoots = @( - $sessionDirectory, $tempRoot, $tauriRoot, $BuildReceiptPath - ) - $unsignedSourceLease = Open-WaggleValidatedPrebuiltTree ` - $unsignedSourceRoot $receipt.targetInventory ` - 'Unsigned receipt-bound prebuilt input tree' ` - ($sourceDisallowedRoots + @($signingSourceRoot)) ` - -CargoReleaseRelativePath $cargoReleaseRelative - $signingSourceLease = Open-WaggleValidatedPrebuiltTree ` - $signingSourceRoot $receipt.targetInventory ` - 'Signing receipt-bound prebuilt input tree' ` - ($sourceDisallowedRoots + @($unsignedSourceRoot)) ` - -CargoReleaseRelativePath $cargoReleaseRelative - - $workRoot = Join-Path $sessionDirectory 'work' - $unsignedWorkRoot = Join-Path $workRoot 'unsigned' - $signingWorkRoot = Join-Path $workRoot 'signing' - [void](Assert-WaggleHostedDiskCapacity $sessionDirectory $receipt.targetInventory) - New-WagglePrebuiltWorkCopy ` - $unsignedSourceRoot $unsignedWorkRoot $receipt.targetInventory ` - 'Unsigned hosted prebuilt input' $cargoReleaseRelative | Out-Null - - $unsignedReleaseRoot = Join-Path $unsignedWorkRoot $cargoReleaseRelative - $unsignedResourcesRoot = Join-Path $unsignedWorkRoot 'resources' - $unsignedMutablePaths = @( - (Join-Path $unsignedReleaseRoot 'waggle.exe'), - (Join-Path $unsignedReleaseRoot 'deps\waggle.exe') - ) - $unsignedRegeneratedRoots = @( - (Join-Path $unsignedReleaseRoot 'nsis'), - (Join-Path $unsignedReleaseRoot 'bundle\nsis') - ) - $unsignedWorkLease = Open-WaggleValidatedPrebuiltTree ` - $unsignedWorkRoot $receipt.targetInventory 'Unsigned private work tree' ` - @($unsignedSourceRoot, $signingSourceRoot, $signingWorkRoot, $tempRoot) ` - -MutablePaths $unsignedMutablePaths ` - -RegeneratedRoots $unsignedRegeneratedRoots ` - -CargoReleaseRelativePath $cargoReleaseRelative - Clear-WaggleRegeneratedRoots $unsignedWorkLease - Write-WaggleSigningOverride ` - $overridePath $scriptPath $unsignedResourcesRoot | Out-Null - Assert-WaggleSigningOverrideContract ` - $overridePath $scriptPath $unsignedResourcesRoot -Unsigned - Install-WaggleArtifactSigningPackage ` - $tauriRoot $ArtifactSigningPackageSource | Out-Null - - [Environment]::SetEnvironmentVariable('CARGO_TARGET_DIR', $unsignedWorkRoot) - [Environment]::SetEnvironmentVariable( - 'WAGGLE_SIGNING_RESOURCES_ROOT', $unsignedResourcesRoot - ) - $context = Get-WaggleSigningContext -AllowPortableBeforeManifest - $packageLocks = Open-WagglePackageToolchainLocks $context - - $unsignedOverrideLock = Open-ReadLock $overridePath - try { - Assert-WaggleSigningOverrideContract ` - $overridePath $scriptPath $unsignedResourcesRoot -Unsigned - Invoke-WagglePinnedNodeScript ` - $context $context.TauriCliPath $context.AppRoot @( - 'bundle', '--target', 'x86_64-pc-windows-msvc', '--no-sign', - '--bundles', 'nsis', '--config', $overridePath, '--ci' - ) 'Unsigned immutable NSIS preflight package' - } finally { - $unsignedOverrideLock.Dispose() - $unsignedOverrideLock = $null - } - - $version = [string](Get-Content -Raw -LiteralPath $context.ConfigPath | ConvertFrom-Json).version - $installerPath = Join-Path ` - $context.ReleaseRoot "bundle\nsis\Waggle_${version}_x64-setup.exe" - $unsignedExtractionRoot = Join-Path $sessionDirectory 'unsigned-payload-extraction' - $payloads = @(Expand-NsisPayloadManifest ` - $installerPath $context.SevenZipPath $unsignedExtractionRoot) - Assert-WaggleUnsignedPayloadResourceProjection ` - $payloads $receipt.resourcesInventory - $preflightEvidenceRoot = New-WagglePreflightEvidenceCopy ` - $context (Join-Path $sessionDirectory 'preflight-evidence') - Remove-Item -LiteralPath $unsignedExtractionRoot -Recurse -Force - $unsignedExtractionRoot = $null - Remove-Item -LiteralPath $installerPath -Force - foreach ($lock in $unsignedWorkLease.Locks) { $lock.Dispose() } - $unsignedWorkLease = $null - Remove-Item -LiteralPath $unsignedWorkRoot -Recurse -Force - $unsignedWorkRoot = $null - - [void](Assert-WaggleHostedDiskCapacity $sessionDirectory $receipt.targetInventory) - New-WagglePrebuiltWorkCopy ` - $signingSourceRoot $signingWorkRoot $receipt.targetInventory ` - 'Signing hosted prebuilt input' $cargoReleaseRelative | Out-Null - $signingReleaseRoot = Join-Path $signingWorkRoot $cargoReleaseRelative - $signingResourcesRoot = Join-Path $signingWorkRoot 'resources' - $signingMutablePaths = @( - Get-ExpectedNsisFixedPaths ` - ([pscustomobject]@{ - ReleaseRoot = $signingReleaseRoot - ResourcesRoot = $signingResourcesRoot - }) ` - '0.0.0' - ) + @((Join-Path $signingReleaseRoot 'deps\waggle.exe')) - $signingRegeneratedRoots = @( - (Join-Path $signingReleaseRoot 'nsis'), - (Join-Path $signingReleaseRoot 'bundle\nsis') - ) - $signingWorkLease = Open-WaggleValidatedPrebuiltTree ` - $signingWorkRoot $receipt.targetInventory 'Signing private work tree' ` - @($unsignedSourceRoot, $signingSourceRoot, $tempRoot) ` - -MutablePaths $signingMutablePaths ` - -RegeneratedRoots $signingRegeneratedRoots ` - -CargoReleaseRelativePath $cargoReleaseRelative - Clear-WaggleRegeneratedRoots $signingWorkLease - - Write-WaggleSigningOverride ` - $overridePath $scriptPath $signingResourcesRoot -EnableSigning | Out-Null - Assert-WaggleSigningOverrideContract ` - $overridePath $scriptPath $signingResourcesRoot - [Environment]::SetEnvironmentVariable('CARGO_TARGET_DIR', $signingWorkRoot) - [Environment]::SetEnvironmentVariable( - 'WAGGLE_SIGNING_RESOURCES_ROOT', $signingResourcesRoot - ) - $context = Get-WaggleSigningContext -AllowPortableBeforeManifest - $session = New-WaggleSigningManifest ` - $context $payloads $preflightEvidenceRoot $receipt - Remove-Item -LiteralPath $preflightEvidenceRoot -Recurse -Force - $preflightEvidenceRoot = $null - Assert-DotNet8X64Runtime - - Invoke-WagglePinnedNodeScript ` - $context $context.TauriCliPath $context.AppRoot @( - 'bundle', '--target', 'x86_64-pc-windows-msvc', '--bundles', 'nsis', - '--config', $overridePath, '--ci' - ) 'Signed NSIS bundle' - - $result = Assert-WaggleSigningPackageComplete $session - $packageSucceeded = $true - Write-Host "Public Artifact Signing package sealed: $($result.InstallerPath)" - Write-Host "Provenance receipt: $($result.ReceiptPath)" - } catch { - $packageFailure = $_ - if ($null -ne $session) { - try { - Fail-WaggleSigningSession ` - $session $null 'package_or_finalization_failure' ` - $packageFailure.Exception.Message | Out-Null - } catch { - throw "Signing package failed: $($packageFailure.Exception.Message) Terminalization also failed: $($_.Exception.Message)" - } - } - throw $packageFailure - } finally { - if ($null -ne $unsignedExtractionRoot -and (Test-Path -LiteralPath $unsignedExtractionRoot)) { - Remove-Item -LiteralPath $unsignedExtractionRoot -Recurse -Force -ErrorAction SilentlyContinue - } - if ($null -ne $preflightEvidenceRoot -and (Test-Path -LiteralPath $preflightEvidenceRoot)) { - Remove-Item -LiteralPath $preflightEvidenceRoot -Recurse -Force -ErrorAction SilentlyContinue - } - if ($null -ne $unsignedOverrideLock) { $unsignedOverrideLock.Dispose() } - if ($null -ne $session) { - foreach ($sessionLock in $session.Locks) { $sessionLock.Dispose() } - } - if ($null -ne $packageLocks) { foreach ($lock in $packageLocks) { $lock.Dispose() } } - foreach ($lock in $portableBootstrapLocks) { $lock.Dispose() } - foreach ($lease in @( - $unsignedWorkLease, $signingWorkLease, - $unsignedSourceLease, $signingSourceLease - )) { - if ($null -ne $lease) { foreach ($lock in $lease.Locks) { $lock.Dispose() } } - } - if ($null -ne $unsignedWorkRoot -and (Test-Path -LiteralPath $unsignedWorkRoot)) { - Remove-Item -LiteralPath $unsignedWorkRoot -Recurse -Force -ErrorAction SilentlyContinue - } - if (-not $packageSucceeded -and $null -ne $signingWorkRoot -and - (Test-Path -LiteralPath $signingWorkRoot)) { - Remove-Item -LiteralPath $signingWorkRoot -Recurse -Force -ErrorAction SilentlyContinue - } - $receiptLease.Lock.Dispose() - foreach ($name in $environmentNames) { - [Environment]::SetEnvironmentVariable($name, $savedEnvironment[$name]) - } - } -} - -function Invoke-WaggleArtifactSigning { - param([Parameter(Mandatory = $true)] [string]$Path) - - if (-not $IsWindows -or -not [Environment]::Is64BitProcess -or - $PSVersionTable.PSEdition -cne 'Core' -or - $PSVersionTable.PSVersion -lt [Version]'7.5.0') { - throw 'Azure Artifact Signing requires approved 64-bit PowerShell 7.5+ on Windows.' - } - - $actualHost = Get-TrustedPath (Get-Process -Id $PID).Path 'Current PowerShell 7 host' -AllowHardLink - Assert-ApprovedPowerShell7Path $actualHost - $context = Get-WaggleSigningContext - $session = Get-WaggleSigningSession $context - $artifact = $null - $reservation = $null - $stagingRoot = $null - $signToolLock = $null - $toolsetLocks = $null - $signedArtifactLock = $null - $replaced = $false - $expectedRollbackPaths = $null - try { - $artifact = Get-ApprovedArtifact $Path $session - $reservation = Reserve-WaggleSigningCallback $session $artifact - $sourceHash = [string]$reservation.preSignSha256 - try { - Assert-DotNet8X64Runtime - $signTool = $context.SignToolPath - $packagePath = $context.ArtifactSigningPackagePath - $stagingParent = New-PrivateDirectory ` - (Join-Path $context.TauriRoot 'target\.signing-staging') - $stagingRoot = New-PrivateDirectory ` - (Join-Path $stagingParent ([Guid]::NewGuid().ToString('N'))) - $stagedArtifact = Join-Path $stagingRoot ([IO.Path]::GetFileName($artifact)) - $backupPath = Join-Path $stagingRoot 'original.backup' - $metadataPath = Join-Path $stagingRoot 'artifact-signing.json' - $metadata = [ordered]@{ - Endpoint = $ArtifactSigningEndpoint - CodeSigningAccountName = $ArtifactSigningAccount - CertificateProfileName = $ArtifactSigningProfile - } - [IO.File]::Copy($artifact, $stagedArtifact, $false) - $stagedArtifact = Get-TrustedPath $stagedArtifact 'Staged signing artifact' - Assert-PeFile $stagedArtifact - if ((Get-FileHash -LiteralPath $stagedArtifact -Algorithm SHA256).Hash -cne $sourceHash) { - throw 'Staged artifact bytes differ from the validated source artifact.' - } - [IO.File]::WriteAllText( - $metadataPath, - ($metadata | ConvertTo-Json -Compress), - [Text.UTF8Encoding]::new($false) - ) - - $signToolLock = Open-ReadLock $signTool - Assert-MicrosoftAuthenticodeFile $signTool 'SignTool' $SignToolSha256 - $toolset = Expand-PinnedArtifactSigningPackage $packagePath $stagingRoot - $dlib = $toolset.Dlib - $toolsetLocks = $toolset.Locks - - & $signTool sign ` - /v /debug ` - /fd SHA256 ` - /tr 'http://timestamp.acs.microsoft.com' ` - /td SHA256 ` - /dlib $dlib ` - /dmdf $metadataPath ` - $stagedArtifact - if ($LASTEXITCODE -ne 0) { - throw "Azure Artifact Signing failed with SignTool exit code $LASTEXITCODE." - } - Assert-WaggleSignedArtifact $stagedArtifact $signTool - - $artifact = Get-ApprovedArtifact $artifact $session - if ((Get-FileHash -LiteralPath $artifact -Algorithm SHA256).Hash -cne $sourceHash) { - throw 'Source artifact changed while its validated staging copy was being signed.' - } - $sourceItem = Get-Item -LiteralPath $artifact -Force - $sourceLinkTypeProperty = $sourceItem.PSObject.Properties['LinkType'] - $sourceLinkType = if ($null -eq $sourceLinkTypeProperty) { - '' - } else { - [string]$sourceLinkTypeProperty.Value - } - $expectedRollbackPaths = if ($sourceLinkType -ceq 'HardLink') { - @(Get-HardLinkPaths $artifact) - } else { - @($artifact) - } - [IO.File]::Replace($stagedArtifact, $artifact, $backupPath, $true) - $replaced = $true - $artifact = Get-ApprovedArtifact $artifact $session -AllowDetachedMain - $signedArtifactLock = Open-ReadLock $artifact - Assert-WaggleSignedArtifact $artifact $signTool - if ([string]$reservation.kind -ceq 'generated-nsis-uninstaller') { - $uninstallerSlot = $session.Manifest.slots[[int]$reservation.order - 1] - $evidencePath = [string]$uninstallerSlot.evidencePath - $evidenceDirectory = New-PrivateDirectory (Split-Path $evidencePath -Parent) - Assert-ExactCanonicalPathValue ` - $evidenceDirectory (Join-Path $session.SessionDirectory 'signed-evidence') ` - 'Signed evidence directory' - if (Test-Path -LiteralPath $evidencePath) { - throw 'Signed NSIS uninstaller evidence was already published.' - } - $temporaryEvidence = Join-Path ` - $evidenceDirectory "uninstaller.$([Guid]::NewGuid().ToString('N')).tmp" - [IO.File]::Copy($artifact, $temporaryEvidence, $false) - if ((Get-FileHash -LiteralPath $temporaryEvidence -Algorithm SHA256).Hash -cne - (Get-FileHash -LiteralPath $artifact -Algorithm SHA256).Hash) { - throw 'Signed NSIS uninstaller evidence copy failed digest verification.' - } - [IO.File]::Move($temporaryEvidence, $evidencePath) - } - Complete-WaggleSigningCallback $session $reservation $artifact | Out-Null - $replaced = $false - Remove-Item -LiteralPath $backupPath -Force -ErrorAction SilentlyContinue - } catch { - $signingFailure = $_ - $rollbackOutcome = 'not-required' - if ($null -ne $signedArtifactLock) { - $signedArtifactLock.Dispose() - $signedArtifactLock = $null - } - if ($replaced) { - if (-not (Test-Path -LiteralPath $backupPath -PathType Leaf)) { - $rollbackOutcome = 'rollback-failed: Rollback backup is missing.' - } else { - try { - Restore-WaggleReplacedArtifact ` - -ArtifactPath $artifact -BackupPath $backupPath ` - -ExpectedOriginalSha256 $sourceHash ` - -ExpectedHardLinkPaths $expectedRollbackPaths - $rollbackOutcome = 'restored-original' - } catch { - $rollbackOutcome = "rollback-failed: $($_.Exception.Message)" - } - } - } - try { - Fail-WaggleSigningSession ` - $session $reservation 'callback_failure' ` - $signingFailure.Exception.Message $rollbackOutcome | Out-Null - } catch { - throw "Signing callback failed: $($signingFailure.Exception.Message) Terminalization also failed: $($_.Exception.Message)" - } - throw $signingFailure - } finally { - if ($null -ne $toolsetLocks) { - foreach ($toolsetLock in $toolsetLocks) { $toolsetLock.Dispose() } - } - if ($null -ne $signedArtifactLock) { $signedArtifactLock.Dispose() } - if ($null -ne $signToolLock) { $signToolLock.Dispose() } - if ($null -ne $stagingRoot) { - Remove-Item -LiteralPath $stagingRoot -Recurse -Force -ErrorAction SilentlyContinue - } - } - } finally { - foreach ($sessionLock in $session.Locks) { $sessionLock.Dispose() } - } - - Write-Host "Azure Artifact Signing verified: $artifact" -} - -if ($MyInvocation.InvocationName -ne '.') { - if ($TrustedPowerShellHost) { - if ($Mode -ceq 'Package') { - Invoke-WaggleSigningPackage - } else { - if ([string]::IsNullOrWhiteSpace($ArtifactPath)) { - throw 'Signing callback requires an artifact path.' - } - Invoke-WaggleArtifactSigning -Path $ArtifactPath - } - } else { - Invoke-TrustedPowerShellRelaunch ` - -LaunchMode $Mode -Path $ArtifactPath ` - -PackageSource $ArtifactSigningPackageSource ` - -ToolchainRoot $PortableToolchainRoot ` - -Node $PortableNodePath -Git $PortableGitPath -SevenZip $PortableSevenZipPath ` - -ToolchainReceipt $PortableToolchainReceiptPath ` - -ToolchainReceiptSha256 $PortableToolchainReceiptSha256 - } -} diff --git a/app/scripts/sign-windows-artifact.test.ps1 b/app/scripts/sign-windows-artifact.test.ps1 deleted file mode 100644 index 0717706..0000000 --- a/app/scripts/sign-windows-artifact.test.ps1 +++ /dev/null @@ -1,2772 +0,0 @@ -#Requires -Version 7.0 - -Set-StrictMode -Version Latest -$ErrorActionPreference = 'Stop' - -$wrapperPath = Join-Path $PSScriptRoot 'sign-windows-artifact.ps1' -. $wrapperPath -ArtifactPath 'C:\unused.exe' - -$passed = 0 - -function Assert-Equal { - param($Actual, $Expected, [string]$Label) - if ($Actual -cne $Expected) { throw "$Label expected '$Expected', got '$Actual'." } - $script:passed++ -} - -function Assert-Throws { - param([scriptblock]$Action, [string]$Pattern, [string]$Label) - try { - & $Action - } catch { - if ($_.Exception.Message -notmatch $Pattern) { - throw "$Label threw the wrong error: $($_.Exception.Message)" - } - $script:passed++ - return - } - throw "$Label did not throw." -} - -function Write-JsonNoBom { - param([string]$Path, [object]$Value) - [IO.File]::WriteAllText( - $Path, - ($Value | ConvertTo-Json -Depth 32 -Compress), - [Text.UTF8Encoding]::new($false) - ) -} - -function New-SyntheticPe { - param([string]$Path, [byte]$Marker = 0) - [IO.Directory]::CreateDirectory((Split-Path $Path -Parent)) | Out-Null - $bytes = [byte[]]::new(128) - $bytes[0] = 0x4D - $bytes[1] = 0x5A - [BitConverter]::GetBytes([uint32]0x40).CopyTo($bytes, 0x3C) - $bytes[0x40] = 0x50 - $bytes[0x41] = 0x45 - $bytes[0x42] = 0 - $bytes[0x43] = 0 - $bytes[127] = $Marker - [IO.File]::WriteAllBytes($Path, $bytes) -} - -function New-SyntheticPatchablePe { - param([string]$Path) - [IO.Directory]::CreateDirectory((Split-Path $Path -Parent)) | Out-Null - $bytes = [byte[]]::new(256) - $bytes[0] = 0x4D - $bytes[1] = 0x5A - [BitConverter]::GetBytes([uint32]0x40).CopyTo($bytes, 0x3C) - $bytes[0x40] = 0x50 - $bytes[0x41] = 0x45 - $token = [Text.Encoding]::ASCII.GetBytes('__TAURI_BUNDLE_TYPE_VAR_UNK') - [Array]::Copy($token, 0, $bytes, 160, $token.Length) - [IO.File]::WriteAllBytes($Path, $bytes) -} - -function Get-Sha256 { - param([string]$Path) - return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash -} - -function Get-RealSha256 { - param([string]$Path) - $stream = [IO.File]::Open( - $Path, - [IO.FileMode]::Open, - [IO.FileAccess]::Read, - [IO.FileShare]::Read - ) - $algorithm = [Security.Cryptography.SHA256]::Create() - try { - return ([BitConverter]::ToString($algorithm.ComputeHash($stream)) -replace '-', '') - } finally { - $algorithm.Dispose() - $stream.Dispose() - } -} - -function New-PendingLedger { - param([string]$SessionId, [string]$ManifestSha256, [object[]]$Slots) - return [pscustomobject][ordered]@{ - schemaVersion = 3 - sessionId = $SessionId - manifestSha256 = $ManifestSha256 - state = 'open' - terminalAtUtc = $null - terminalReceiptSha256 = $null - entries = @($Slots | ForEach-Object { - [pscustomobject][ordered]@{ - slotId = [string]$_.id - order = [int]$_.order - kind = [string]$_.kind - status = 'pending' - attempts = 0 - reservationId = $null - path = $null - preSignSha256 = $null - reservedAtUtc = $null - completedAtUtc = $null - postSignSha256 = $null - signerSubject = $null - } - }) - } -} - -function Close-PrebuiltTreeLease { - param([AllowNull()] [object]$Lease) - if ($null -eq $Lease) { return } - $locksProperty = $Lease.PSObject.Properties['Locks'] - $locks = if ($null -eq $locksProperty) { @($Lease) } else { @($locksProperty.Value) } - foreach ($lock in $locks) { - if ($null -ne $lock) { $lock.Dispose() } - } -} - -function Assert-FreshProcessModuleIsolation { - param( - [Parameter(Mandatory = $true)] [string]$HostPath, - [Parameter(Mandatory = $true)] [string]$Label, - [Parameter(Mandatory = $true)] [string]$Root - ) - - $hostRoot = Join-Path $Root ([IO.Path]::GetFileNameWithoutExtension($HostPath)) - $hostileModuleRoot = Join-Path $hostRoot 'hostile-modules' - $markerPath = Join-Path $hostRoot 'hostile-module-loaded.txt' - $childPath = Join-Path $hostRoot 'module-isolation-child.ps1' - [IO.Directory]::CreateDirectory($hostileModuleRoot) | Out-Null - foreach ($moduleName in @( - 'Microsoft.PowerShell.Security', - 'Microsoft.PowerShell.Management', - 'Microsoft.PowerShell.Utility' - )) { - $moduleRoot = Join-Path $hostileModuleRoot $moduleName - [IO.Directory]::CreateDirectory($moduleRoot) | Out-Null - $modulePath = Join-Path $moduleRoot "$moduleName.psm1" - $manifestPath = Join-Path $moduleRoot "$moduleName.psd1" - [IO.File]::WriteAllText( - $modulePath, - "[IO.File]::AppendAllText('$($markerPath.Replace("'", "''"))', '$moduleName')`n" + - "function Get-AuthenticodeSignature { throw 'hostile command' }`n" + - "function Get-Acl { throw 'hostile command' }`n" + - "function Set-Acl { throw 'hostile command' }`n" + - "function Get-FileHash { throw 'hostile command' }`n" + - 'Export-ModuleMember -Function *', - [Text.UTF8Encoding]::new($false) - ) - New-ModuleManifest -Path $manifestPath -RootModule "$moduleName.psm1" ` - -ModuleVersion '99.0.0' -FunctionsToExport '*' | Out-Null - } - $childSource = @' -param([string]$WrapperPath, [string]$HostileModuleRoot, [string]$MarkerPath) -$ErrorActionPreference = 'Stop' -[Environment]::SetEnvironmentVariable('PSModulePath', $HostileModuleRoot, 'Process') -$global:PSModuleAutoLoadingPreference = 'All' -. $WrapperPath -ArtifactPath 'C:\unused.exe' -$trustedRoot = [IO.Path]::GetFullPath([IO.Path]::Combine($PSHOME, 'Modules')) -$expected = @{ - 'Get-AuthenticodeSignature' = 'Microsoft.PowerShell.Security' - 'Get-Acl' = 'Microsoft.PowerShell.Security' - 'Set-Acl' = 'Microsoft.PowerShell.Security' -} -if ($PSVersionTable.PSEdition -ceq 'Core') { - $expected['Get-FileHash'] = 'Microsoft.PowerShell.Utility' -} -foreach ($entry in $expected.GetEnumerator()) { - $command = Get-Command $entry.Key -CommandType Cmdlet -ErrorAction Stop - $expectedPath = [IO.Path]::Combine($trustedRoot, $entry.Value, "$($entry.Value).psd1") - if (-not [string]::Equals( - [IO.Path]::GetFullPath([string]$command.Module.Path), - [IO.Path]::GetFullPath($expectedPath), - [StringComparison]::OrdinalIgnoreCase - )) { - throw "Command '$($entry.Key)' resolved outside the trusted module root." - } -} -if ([IO.File]::Exists($MarkerPath)) { throw 'A hostile PowerShell module was loaded.' } -'module-isolation-ok' -'@ - [IO.File]::WriteAllText($childPath, $childSource, [Text.UTF8Encoding]::new($false)) - $output = & $HostPath -NoLogo -NoProfile -NonInteractive ` - -ExecutionPolicy Bypass -File $childPath ` - -WrapperPath $wrapperPath -HostileModuleRoot $hostileModuleRoot ` - -MarkerPath $markerPath 2>&1 - if ($LASTEXITCODE -ne 0 -or @($output | Where-Object { $_ -ceq 'module-isolation-ok' }).Count -ne 1) { - throw "$Label hostile PSModulePath isolation failed: $($output -join ' | ')" - } - if (Test-Path -LiteralPath $markerPath) { - throw "$Label imported a hostile PowerShell module." - } - $script:passed++ -} - -function Start-SynchronizedChild { - param( - [Parameter(Mandatory = $true)] [string]$PowerShellPath, - [Parameter(Mandatory = $true)] [string]$ScriptPath, - [Parameter(Mandatory = $true)] [hashtable]$Arguments - ) - $argumentList = [Collections.Generic.List[string]]::new() - foreach ($argument in @( - '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', - '-File', ('"' + $ScriptPath + '"') - )) { - $argumentList.Add($argument) - } - foreach ($entry in $Arguments.GetEnumerator()) { - $argumentList.Add("-$($entry.Key)") - $argumentList.Add('"' + ([string]$entry.Value).Replace('"', '\"') + '"') - } - return Start-Process -FilePath $PowerShellPath -ArgumentList @($argumentList) ` - -WindowStyle Hidden -PassThru -} - -function Wait-ForChildBarriers { - param([string[]]$Paths, [string]$Label) - $deadline = [DateTimeOffset]::UtcNow.AddSeconds(30) - while (@($Paths | Where-Object { -not (Test-Path -LiteralPath $_ -PathType Leaf) }).Count -ne 0) { - if ([DateTimeOffset]::UtcNow -gt $deadline) { - throw "Timed out waiting for $Label child barriers." - } - Start-Sleep -Milliseconds 20 - } -} - -$releaseRoot = 'D:\repo\app\src-tauri\target\x86_64-pc-windows-msvc\release' -$resourcesRoot = 'D:\repo\app\src-tauri\resources' -$tempRoot = 'D:\repo\app\src-tauri\target\.signing-temp\run-123456' -$version = '0.2.0' - -$installedTauriRoot = Join-Path ` - (Split-Path $PSScriptRoot -Parent) 'node_modules\@tauri-apps\cli' -$installedNativeRoot = Join-Path ` - (Split-Path $PSScriptRoot -Parent) 'node_modules\@tauri-apps\cli-win32-x64-msvc' -foreach ($binding in @( - @((Join-Path $installedTauriRoot 'tauri.js'), $TauriCliSha256, 'installed Tauri entry'), - @((Join-Path $installedTauriRoot 'main.js'), $TauriCliMainSha256, 'installed Tauri main'), - @((Join-Path $installedTauriRoot 'index.js'), $TauriCliIndexSha256, 'installed Tauri loader'), - @((Join-Path $installedNativeRoot 'package.json'), $TauriNativePackageSha256, 'installed Tauri native package'), - @((Join-Path $installedNativeRoot 'cli.win32-x64-msvc.node'), $TauriNativeBinarySha256, 'installed Tauri native binary') - )) { - Assert-Equal (Get-Sha256 $binding[0]) $binding[1] $binding[2] -} -$wrapperSource = Get-Content -Raw -LiteralPath $wrapperPath -if ($wrapperSource -match "ValidateSet\('Callback',\s*'Build'\)" -or - $wrapperSource -match 'function\s+Invoke-WaggleSigningBuild' -or - $wrapperSource -match 'function\s+Assert-WaggleSigningBuildComplete' -or - $wrapperSource -match "Mode\s+-ceq\s+'Build'") { - throw 'Production Artifact Signing still exposes the rejected local Build issuer.' -} -if ($wrapperSource -notmatch "ValidateSet\('Callback',\s*'Package'\)" -or - $wrapperSource -notmatch 'function\s+Invoke-WaggleSigningPackage' -or - $wrapperSource -notmatch 'function\s+Assert-WaggleSigningPackageComplete') { - throw 'Production Artifact Signing lacks the hosted-only Package issuer.' -} -foreach ($portableParameter in @( - 'PortableToolchainRoot', 'PortableNodePath', - 'PortableGitPath', 'PortableSevenZipPath' - )) { - if ($wrapperSource -notmatch "\[string\]\`$$portableParameter") { - throw "Hosted Package mode lacks the explicit $portableParameter input." - } - $passed++ -} -$portableEnvironmentNames = @( - 'WAGGLE_SIGNING_PORTABLE_TOOLCHAIN_ROOT', - 'WAGGLE_SIGNING_PORTABLE_NODE_PATH', - 'WAGGLE_SIGNING_PORTABLE_GIT_PATH', - 'WAGGLE_SIGNING_PORTABLE_SEVEN_ZIP_PATH' -) -foreach ($portableEnvironmentName in $portableEnvironmentNames) { - if ($wrapperSource -notmatch [Regex]::Escape($portableEnvironmentName)) { - throw "Signing callbacks do not receive $portableEnvironmentName." - } - $passed++ -} -if ($wrapperSource -notmatch 'function\s+Get-WagglePortableToolchain' -or - $wrapperSource -notmatch 'portableToolchainRoot' -or - $wrapperSource -notmatch 'sevenZipDllPath' -or - $wrapperSource -notmatch 'sevenZipDllSha256') { - throw 'Portable signing tools are not path-, manifest-, and closure-bound.' -} -$passed++ -if ($wrapperSource -notmatch [Regex]::Escape( - 'CN=.NET, O=Microsoft Corporation, L=Redmond, S=Washington, C=US' - ) -or - $wrapperSource -notmatch - 'Assert-MicrosoftAuthenticodeFile\s+\$dotnet\s+''\.NET host''\s+\$null\s+\$DotNetPublisher') { - throw '.NET 8 validation is not bound to the exact repository-pinned .NET signer.' -} -$passed++ -if ($wrapperSource -notmatch 'Restore-WaggleReplacedArtifact\s+`?\s*-ArtifactPath') { - throw 'Production signing callback does not use the verified rollback path.' -} -$passed++ -foreach ($hostBoundaryName in @( - 'GITHUB_ACTIONS', 'GITHUB_EVENT_NAME', 'RUNNER_ENVIRONMENT', - 'GITHUB_REPOSITORY', 'GITHUB_SHA', 'GITHUB_REF', - 'GITHUB_REF_TYPE', 'GITHUB_REF_NAME', 'GITHUB_WORKFLOW_REF', - 'GITHUB_WORKFLOW_SHA' - )) { - if ($wrapperSource -notmatch [Regex]::Escape($hostBoundaryName)) { - throw "Hosted Package mode does not bind $hostBoundaryName." - } - $passed++ -} -foreach ($hostBoundaryPattern in @( - "GITHUB_EVENT_NAME\s*=\s*'push'", - 'GITHUB_REF\s*=\s*\$expectedRef', - 'GITHUB_WORKFLOW_REF\s*=\s*\$expectedWorkflowRef', - 'GITHUB_WORKFLOW_SHA\s*=\s*\$ExpectedRevision' - )) { - if ($wrapperSource -notmatch $hostBoundaryPattern) { - throw "Hosted Package mode lacks exact boundary binding: $hostBoundaryPattern" - } - $passed++ -} -$validBoundaryRevision = '0123456789abcdef0123456789abcdef01234567' -$validBoundaryVersion = '0.2.0' -$validHostedBoundary = [ordered]@{ - GITHUB_ACTIONS = 'true' - GITHUB_EVENT_NAME = 'push' - RUNNER_ENVIRONMENT = 'github-hosted' - GITHUB_REPOSITORY = 'marolinik/waggle-os' - GITHUB_SHA = $validBoundaryRevision - GITHUB_REF = 'refs/tags/v0.2.0' - GITHUB_REF_TYPE = 'tag' - GITHUB_REF_NAME = 'v0.2.0' - GITHUB_WORKFLOW_REF = 'marolinik/waggle-os/.github/workflows/release.yml@refs/tags/v0.2.0' - GITHUB_WORKFLOW_SHA = $validBoundaryRevision -} -$savedHostedBoundary = @{} -foreach ($name in $validHostedBoundary.Keys) { - $savedHostedBoundary[$name] = [Environment]::GetEnvironmentVariable($name) -} -try { - foreach ($name in $validHostedBoundary.Keys) { - [Environment]::SetEnvironmentVariable($name, $validHostedBoundary[$name]) - } - Assert-WaggleHostedSigningBoundary ` - -ExpectedRevision $validBoundaryRevision ` - -ExpectedVersion $validBoundaryVersion - $passed++ - foreach ($name in $validHostedBoundary.Keys) { - [Environment]::SetEnvironmentVariable($name, "invalid-$name") - Assert-Throws { - Assert-WaggleHostedSigningBoundary ` - -ExpectedRevision $validBoundaryRevision ` - -ExpectedVersion $validBoundaryVersion - } "exact $([Regex]::Escape($name)) boundary evidence" ` - "hosted signing rejects mutated $name" - [Environment]::SetEnvironmentVariable($name, $validHostedBoundary[$name]) - } -} finally { - foreach ($name in $validHostedBoundary.Keys) { - [Environment]::SetEnvironmentVariable($name, $savedHostedBoundary[$name]) - } -} -$wrapperTokens = $null -$wrapperParseErrors = $null -$wrapperAst = [Management.Automation.Language.Parser]::ParseFile( - $wrapperPath, [ref]$wrapperTokens, [ref]$wrapperParseErrors -) -if (@($wrapperParseErrors).Count -ne 0) { - throw "Signing wrapper does not parse: $($wrapperParseErrors[0].Message)" -} -$packageFunctions = @($wrapperAst.FindAll({ - param($node) - $node -is [Management.Automation.Language.FunctionDefinitionAst] -and - $node.Name -ceq 'Invoke-WaggleSigningPackage' -}, $true)) -if ($packageFunctions.Count -ne 1 -or - $packageFunctions[0].Extent.Text -match - 'BuildScriptPaths|ViteCliPath|bundleNode|buildSidecar|bundleNativeDeps|stageSidecarDeps|tauri:build') { - throw 'Hosted Package mode still contains the rejected local source-build closure.' -} -$passed++ -$packageSource = $packageFunctions[0].Extent.Text -if ([regex]::Matches($packageSource, 'New-WagglePrebuiltWorkCopy').Count -ne 2 -or - [regex]::Matches($packageSource, 'Clear-WaggleRegeneratedRoots').Count -ne 2 -or - $packageSource -notmatch "SetEnvironmentVariable\('CARGO_TARGET_DIR',\s*\`$unsignedWorkRoot\)" -or - $packageSource -notmatch "SetEnvironmentVariable\('CARGO_TARGET_DIR',\s*\`$signingWorkRoot\)" -or - $packageSource -match "SetEnvironmentVariable\('CARGO_TARGET_DIR',\s*\`$(?:unsigned|signing)SourceRoot\)" -or - $packageSource -notmatch '(?s)New-WaggleSigningManifest.*?\$preflightEvidenceRoot.*?\$receipt' -or - $packageSource -notmatch '(?s)Unsigned hosted prebuilt input.*?Remove-Item\s+-LiteralPath\s+\$unsignedWorkRoot.*?Signing hosted prebuilt input' -or - $packageSource -notmatch '(?s)Unsigned private work tree.*?Clear-WaggleRegeneratedRoots.*?Unsigned immutable NSIS preflight package' -or - $packageSource -notmatch '(?s)Signing private work tree.*?Clear-WaggleRegeneratedRoots.*?Signed NSIS bundle' -or - [regex]::Matches($packageSource, 'Assert-WaggleHostedDiskCapacity').Count -ne 2) { - throw 'Hosted Package mode does not isolate immutable receipt inputs in private work copies.' -} -$passed++ -if ($packageSource -notmatch '(?s)Open-ReadLock\s+\$overridePath.*?Unsigned immutable NSIS preflight package' -or - $wrapperSource -notmatch '(?s)function\s+Open-WagglePackageToolchainLocks.*?app/src-tauri/icons/icon\.ico.*?status\s+--porcelain=v1.*?Assert-WaggleHostedSigningBoundary') { - throw 'Hosted Package mode does not lock exact-HEAD packaging inputs and its unsigned override.' -} -$passed++ -if ($wrapperSource -notmatch "(?s)if\s*\(\`$replaced\)\s*\{.*?Rollback backup is missing") { - throw 'Signing callback does not report a missing required rollback backup as a rollback failure.' -} -$passed++ -if ($wrapperSource -notmatch "PSModuleAutoLoadingPreference\s*=\s*'None'" -or - $wrapperSource -notmatch "SetEnvironmentVariable\(\s*'PSModulePath'") { - throw 'Production Artifact Signing does not harden PowerShell module resolution before trust checks.' -} -$passed++ -if ($wrapperSource -match 'NpmCliPath\s+run|npm\s+run\s+tauri:build') { - throw 'Production signing build still invokes the PATH-dependent npm build script.' -} -$passed++ -foreach ($environmentName in @( - 'NODE_OPTIONS', 'NODE_PATH', 'NAPI_RS_NATIVE_LIBRARY_PATH', - 'NAPI_RS_FORCE_WASI', 'npm_config_node_options' - )) { - if ($wrapperSource -notmatch "SetEnvironmentVariable\('$environmentName', \`$null\)") { - throw "Production signing build does not sanitize $environmentName." - } - $passed++ -} -if ($packageSource -notmatch '(?s)foreach\s*\(\$name\s+in\s+\$environmentNames\).*?\$savedEnvironment\[\$name\].*?finally\s*\{.*?SetEnvironmentVariable\(\$name,\s*\$savedEnvironment\[\$name\]\)' -or - $wrapperSource -notmatch "@\('-PortableToolchainRoot',\s*\`$ToolchainRoot\)" -or - $wrapperSource -notmatch "@\('-PortableNodePath',\s*\`$Node\)" -or - $wrapperSource -notmatch "@\('-PortableGitPath',\s*\`$Git\)" -or - $wrapperSource -notmatch "@\('-PortableSevenZipPath',\s*\`$SevenZip\)") { - throw 'Portable toolchain inputs are not forwarded and transactionally restored.' -} -$passed++ - -& { - $handoffPath = Join-Path $PSScriptRoot 'new-windows-signing-handoff.ps1' - . $handoffPath -SourceTargetRoot 'C:\unused' -DestinationRoot 'C:\unused' - - Assert-Equal $MaxTargetFileCount 18000 'handoff target file-count production bound' - Assert-Equal $MaxTargetBytes ([long]768MB) 'handoff target byte production bound' - Assert-Equal $MaxResourceFileCount 17500 'handoff resource file-count production bound' - Assert-Equal $MaxResourceBytes ([long]600MB) 'handoff resource byte production bound' - - $handoffFixtureRoot = Join-Path ` - ([IO.Path]::GetTempPath()) ` - "waggle-handoff-test-$([Guid]::NewGuid().ToString('N'))" - [IO.Directory]::CreateDirectory($handoffFixtureRoot) | Out-Null - $handoffReparsePath = $null - try { - $sourceRoot = Join-Path $handoffFixtureRoot 'source' - $sourceDependency = Join-Path $sourceRoot 'release\deps\waggle.exe' - $sourceMain = Join-Path $sourceRoot 'release\waggle.exe' - $sourceResource = Join-Path $sourceRoot 'resources\service.js' - $sourceResourceTwo = Join-Path $sourceRoot 'resources\model.json' - $sourceNsis = Join-Path $sourceRoot 'nsis\makensis.exe' - $sourceNsisDll = Join-Path $sourceRoot 'nsis\plugin.dll' - [IO.Directory]::CreateDirectory((Split-Path $sourceDependency -Parent)) | Out-Null - [IO.Directory]::CreateDirectory((Split-Path $sourceResource -Parent)) | Out-Null - [IO.Directory]::CreateDirectory((Split-Path $sourceNsis -Parent)) | Out-Null - New-SyntheticPe $sourceDependency 211 - New-Item -ItemType HardLink -Path $sourceMain -Target $sourceDependency | Out-Null - [IO.File]::WriteAllText($sourceResource, 'receipt-bound-service') - [IO.File]::WriteAllText($sourceResourceTwo, '{"model":"fixture"}') - [IO.File]::WriteAllText($sourceNsis, 'fixture-makensis') - [IO.File]::WriteAllText($sourceNsisDll, 'fixture-plugin') - - $targetMappings = @( - [pscustomobject]@{ - Source = $sourceMain - Path = "$TargetTriple\release\waggle.exe" - }, - [pscustomobject]@{ - Source = $sourceDependency - Path = "$TargetTriple\release\deps\waggle.exe" - }, - [pscustomobject]@{ Source = $sourceResource; Path = 'resources\service.js' }, - [pscustomobject]@{ Source = $sourceResourceTwo; Path = 'resources\model.json' } - ) - $resourceMappings = @( - [pscustomobject]@{ Source = $sourceResource; Path = 'service.js' }, - [pscustomobject]@{ Source = $sourceResourceTwo; Path = 'model.json' } - ) - $nsisMappings = @( - [pscustomobject]@{ Source = $sourceNsis; Path = 'makensis.exe' }, - [pscustomobject]@{ Source = $sourceNsisDll; Path = 'plugins\plugin.dll' } - ) - $expectedTarget = New-HandoffInventory $targetMappings 'Fixture target' - $expectedResources = New-HandoffInventory $resourceMappings 'Fixture resources' - $expectedNsis = New-HandoffInventory $nsisMappings 'Fixture NSIS' - $sourceRevision = 'a' * 40 - $checkerSha256 = 'B' * 64 - $transactionArguments = @{ - DestinationParentRoot = $handoffFixtureRoot - TargetMappings = $targetMappings - ResourceMappings = $resourceMappings - NsisMappings = $nsisMappings - ExpectedTargetInventory = $expectedTarget - ExpectedResourcesInventory = $expectedResources - ExpectedNsisInventory = $expectedNsis - SourceRevision = $sourceRevision - CheckerSha256 = $checkerSha256 - TargetFileCountLimit = 8 - TargetByteLimit = 1MB - ResourceFileCountLimit = 4 - ResourceByteLimit = 1MB - NsisFileCountLimit = 4 - NsisByteLimit = 1MB - } - - $acceptedDestination = Join-Path $handoffFixtureRoot 'accepted' - $accepted = Invoke-HandoffDestinationTransaction ` - -DestinationRoot $acceptedDestination @transactionArguments - Assert-Equal ` - (Test-Path -LiteralPath $accepted.ReceiptPath -PathType Leaf) $true ` - 'handoff transaction publishes a receipt' - Assert-Equal ` - (Get-HandoffFileSha256 $accepted.ReceiptPath) $accepted.ReceiptSha256 ` - 'handoff receipt digest binds exact bytes' - $acceptedReceipt = Get-Content -Raw -LiteralPath $accepted.ReceiptPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-Equal $acceptedReceipt.schemaVersion 1 'handoff receipt schema' - Assert-Equal $acceptedReceipt.repository $ApprovedRepository 'handoff receipt repository' - Assert-Equal $acceptedReceipt.sourceRevision $sourceRevision ` - 'handoff receipt source revision' - Assert-Equal $acceptedReceipt.targetInventory.sha256 $expectedTarget.sha256 ` - 'handoff receipt target inventory' - Assert-Equal $acceptedReceipt.resourcesInventory.sha256 $expectedResources.sha256 ` - 'handoff receipt resource inventory' - Assert-Equal $acceptedReceipt.nsisInventory.sha256 $expectedNsis.sha256 ` - 'handoff receipt NSIS inventory' - $acceptedRelease = Join-Path ` - $accepted.PrebuiltRoot "$TargetTriple\release" - Assert-HandoffCargoPair $acceptedRelease 'Accepted staged Cargo output' - $passed++ - - foreach ($boundProbe in @( - [pscustomobject]@{ Name = 'target-count'; Overrides = @{ TargetFileCountLimit = 3 } }, - [pscustomobject]@{ - Name = 'target-bytes' - Overrides = @{ - TargetByteLimit = ([long](Assert-HandoffMappingBounds ` - $targetMappings 8 1MB 'Fixture target bytes')) - 1 - } - }, - [pscustomobject]@{ Name = 'resource-count'; Overrides = @{ ResourceFileCountLimit = 1 } }, - [pscustomobject]@{ Name = 'nsis-count'; Overrides = @{ NsisFileCountLimit = 1 } } - )) { - $probeDestination = Join-Path $handoffFixtureRoot ([string]$boundProbe.Name) - $probeArguments = @{} + $transactionArguments - foreach ($override in $boundProbe.Overrides.GetEnumerator()) { - $probeArguments[$override.Key] = $override.Value - } - Assert-Throws { - Invoke-HandoffDestinationTransaction ` - -DestinationRoot $probeDestination @probeArguments | Out-Null - } 'deterministic file-count or byte bound' ` - "handoff $($boundProbe.Name) rejection" - Assert-Equal (Test-Path -LiteralPath $probeDestination) $false ` - "handoff $($boundProbe.Name) leaves no destination" - } - - $tamperedDestination = Join-Path $handoffFixtureRoot 'tampered-stage' - Assert-Throws { - Invoke-HandoffDestinationTransaction ` - -DestinationRoot $tamperedDestination @transactionArguments ` - -FinalSourceAssertion { - param([string]$StagedRoot) - [IO.File]::WriteAllText( - (Join-Path $StagedRoot 'resources\service.js'), - 'tampered-after-copy' - ) - } | Out-Null - } 'inventory changed during handoff staging' ` - 'handoff tampered staged inventory rejection' - Assert-Equal (Test-Path -LiteralPath $tamperedDestination) $false ` - 'handoff tamper rollback removes the entire destination' - - $collisionMappings = @($resourceMappings) + @( - [pscustomobject]@{ Source = $sourceResource; Path = 'SERVICE.JS' } - ) - Assert-Throws { - New-HandoffInventory $collisionMappings 'Fixture collision' | Out-Null - } 'duplicate path or case-insensitive collision' ` - 'handoff case-insensitive collision rejection' - Assert-Throws { - Invoke-HandoffDestinationTransaction ` - -DestinationRoot (Join-Path $handoffFixtureRoot '..\escape') ` - @transactionArguments | Out-Null - } 'safe, fully qualified local Windows path|absent direct child' ` - 'handoff unsafe destination rejection' - - $adsRoot = Join-Path $handoffFixtureRoot 'ads-tree' - [IO.Directory]::CreateDirectory($adsRoot) | Out-Null - $adsFile = Join-Path $adsRoot 'payload.bin' - [IO.File]::WriteAllText($adsFile, 'visible') - [IO.File]::WriteAllText("${adsFile}:hidden", 'hidden') - Assert-Throws { - Get-HandoffTreeFiles $adsRoot 'Fixture ADS tree' | Out-Null - } 'alternate data stream' 'handoff ADS rejection' - - $reparseTarget = Join-Path $handoffFixtureRoot 'reparse-target' - $reparseRoot = Join-Path $handoffFixtureRoot 'reparse-tree' - [IO.Directory]::CreateDirectory($reparseTarget) | Out-Null - [IO.Directory]::CreateDirectory($reparseRoot) | Out-Null - [IO.File]::WriteAllText((Join-Path $reparseTarget 'payload.bin'), 'outside') - $handoffReparsePath = Join-Path $reparseRoot 'linked' - New-Item -ItemType Junction -Path $handoffReparsePath ` - -Target $reparseTarget | Out-Null - Assert-Throws { - Get-HandoffTreeFiles $reparseRoot 'Fixture reparse tree' | Out-Null - } 'reparse point|linked directory' 'handoff reparse rejection' - - $git = [string]( - Get-Command git.exe -CommandType Application -ErrorAction Stop | - Select-Object -First 1 -ExpandProperty Source - ) - $repoFixture = Join-Path $handoffFixtureRoot 'repo' - [IO.Directory]::CreateDirectory($repoFixture) | Out-Null - & $git -C $repoFixture init --quiet - & $git -C $repoFixture config user.email 'handoff-test@invalid.example' - & $git -C $repoFixture config user.name 'Waggle Handoff Test' - for ($index = 0; $index -lt 101; $index++) { - [IO.File]::WriteAllText( - (Join-Path $repoFixture ("input-{0:D3}.txt" -f $index)), - "canonical-$index", - [Text.UTF8Encoding]::new($false) - ) - } - & $git -C $repoFixture add -- . - & $git -C $repoFixture commit --quiet -m 'fixture' - & $git -C $repoFixture tag v1.0.0 - $fixtureRevision = [string](& $git -C $repoFixture rev-parse HEAD) - $trackedFixture = @('input-000.txt') - Assert-HandoffRepositoryState ` - $git $repoFixture $fixtureRevision '1.0.0' $trackedFixture - $passed++ - [IO.File]::AppendAllText((Join-Path $repoFixture 'input-000.txt'), 'dirty') - Assert-Throws { - Assert-HandoffRepositoryState ` - $git $repoFixture $fixtureRevision '1.0.0' $trackedFixture - } 'clean exact tagged' 'handoff dirty repository rejection' - & $git -C $repoFixture checkout --quiet -- input-000.txt - & $git -C $repoFixture tag -d v1.0.0 | Out-Null - Assert-Throws { - Assert-HandoffRepositoryState ` - $git $repoFixture $fixtureRevision '1.0.0' $trackedFixture 2>$null - } 'clean exact tagged' 'handoff missing release tag rejection' - & $git -C $repoFixture tag v1.0.0 - & $git -C $repoFixture update-index --skip-worktree input-000.txt - Assert-Throws { - Assert-HandoffRepositoryState ` - $git $repoFixture $fixtureRevision '1.0.0' $trackedFixture - } 'non-default tracked state' 'handoff skip-worktree index rejection' - & $git -C $repoFixture update-index --no-skip-worktree input-000.txt - } finally { - if ($null -ne $handoffReparsePath -and - (Test-Path -LiteralPath $handoffReparsePath)) { - [IO.Directory]::Delete($handoffReparsePath) - } - if (Test-Path -LiteralPath $handoffFixtureRoot) { - foreach ($fixtureItem in @(Get-ChildItem ` - -LiteralPath $handoffFixtureRoot -Force -Recurse)) { - if (($fixtureItem.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq 0) { - $fixtureItem.Attributes = [IO.FileAttributes]::Normal - } - } - [IO.Directory]::Delete($handoffFixtureRoot, $true) - } - } -} - -& { - $portableFixtureParent = Join-Path ` - ([IO.Path]::GetTempPath()) ` - "waggle-portable-tools-$([Guid]::NewGuid().ToString('N'))" - [IO.Directory]::CreateDirectory($portableFixtureParent) | Out-Null - $portableRoot = New-PrivateDirectory (Join-Path $portableFixtureParent 'private') - $node = Join-Path $portableRoot 'node\node.exe' - $git = Join-Path $portableRoot 'git\cmd\git.exe' - $gitRuntime = Join-Path $portableRoot 'git\mingw64\bin\git.exe' - $gitDependency = Join-Path $portableRoot 'git\mingw64\bin\libcrypto-3-x64.dll' - $sevenZip = Join-Path $portableRoot 'sevenzip\7z.exe' - $sevenZipDll = Join-Path $portableRoot 'sevenzip\7z.dll' - $outsideNode = Join-Path $portableFixtureParent 'outside-node.exe' - foreach ($path in @( - $node, $git, $gitRuntime, $gitDependency, - $sevenZip, $sevenZipDll, $outsideNode - )) { - [IO.Directory]::CreateDirectory((Split-Path $path -Parent)) | Out-Null - [IO.File]::WriteAllText($path, "fixture:$([IO.Path]::GetFileName($path))") - } - - function Get-FileHash { - param([string]$LiteralPath, [string]$Algorithm) - if ($null -ne (Get-Variable receiptPath -ErrorAction SilentlyContinue) -and - [string]::Equals( - [IO.Path]::GetFullPath($LiteralPath), - [IO.Path]::GetFullPath($receiptPath), - [StringComparison]::OrdinalIgnoreCase - )) { - return [pscustomobject]@{ Hash = Get-RealSha256 $LiteralPath } - } - $content = [IO.File]::ReadAllText($LiteralPath) - $hash = if ($content -match 'tampered') { - '0' * 64 - } else { - switch ([IO.Path]::GetFileName($LiteralPath)) { - 'node.exe' { $NodeSha256 } - 'git.exe' { - if ($LiteralPath -match 'mingw64') { $GitRuntimeSha256 } else { $GitSha256 } - } - '7z.exe' { $SevenZipSha256 } - '7z.dll' { $SevenZipDllSha256 } - 'node.zip' { $NodeArchiveSha256 } - 'mingit.zip' { $GitArchiveSha256 } - 'sevenzip.exe' { $SevenZipArchiveSha256 } - default { 'F' * 64 } - } - } - return [pscustomobject]@{ Hash = $hash } - } - - $archiveRoot = Join-Path $portableFixtureParent 'downloads' - [IO.Directory]::CreateDirectory($archiveRoot) | Out-Null - $nodeArchive = Join-Path $archiveRoot 'node.zip' - $gitArchive = Join-Path $archiveRoot 'mingit.zip' - $sevenZipArchive = Join-Path $archiveRoot 'sevenzip.exe' - foreach ($archive in @($nodeArchive, $gitArchive, $sevenZipArchive)) { - [IO.File]::WriteAllText($archive, 'fixture:vendor-archive') - } - $portableInventory = New-WagglePrebuiltInventory -Root $portableRoot - $receiptPath = Join-Path $portableFixtureParent 'portable-receipt.json' - Write-WaggleJsonNoBom $receiptPath ([ordered]@{ - schemaVersion = 1 - portableToolchainRoot = $portableRoot - archives = [ordered]@{ - node = [ordered]@{ path = $nodeArchive; sha256 = $NodeArchiveSha256 } - git = [ordered]@{ path = $gitArchive; sha256 = $GitArchiveSha256 } - sevenZip = [ordered]@{ path = $sevenZipArchive; sha256 = $SevenZipArchiveSha256 } - } - inventory = $portableInventory - }) - $portableReceiptJson = [IO.File]::ReadAllText($receiptPath) - $receiptSha256 = Get-RealSha256 $receiptPath - $savedPortableFileCount = $PortableToolchainFileCount - $savedPortableInventorySha256 = $PortableToolchainInventorySha256 - $PortableToolchainFileCount = @($portableInventory.entries).Count - $PortableToolchainInventorySha256 = $portableInventory.sha256 - - function Get-AuthenticodeSignature { - param([string]$LiteralPath) - $content = [IO.File]::ReadAllText($LiteralPath) - $subject = switch ([IO.Path]::GetFileName($LiteralPath)) { - 'node.exe' { $NodePublisher } - 'git.exe' { - if ($content -match 'wrong-publisher') { $MicrosoftPublisher } else { $GitPublisher } - } - 'dotnet.exe' { - if ($content -match 'wrong-publisher') { $MicrosoftPublisher } else { $DotNetPublisher } - } - default { $MicrosoftPublisher } - } - $oids = [Security.Cryptography.OidCollection]::new() - [void]$oids.Add([Security.Cryptography.Oid]::new($CodeSigningOid)) - $eku = [Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension]::new( - $oids, - $false - ) - return [pscustomobject]@{ - Status = [Management.Automation.SignatureStatus]::Valid - SignatureType = 'Authenticode' - SignerCertificate = [pscustomobject]@{ - Subject = $subject - Extensions = @($eku) - } - } - } - - $portableEnvironmentNames = @( - 'WAGGLE_SIGNING_PORTABLE_TOOLCHAIN_ROOT', - 'WAGGLE_SIGNING_PORTABLE_NODE_PATH', - 'WAGGLE_SIGNING_PORTABLE_GIT_PATH', - 'WAGGLE_SIGNING_PORTABLE_SEVEN_ZIP_PATH', - 'WAGGLE_SIGNING_PORTABLE_RECEIPT_PATH', - 'WAGGLE_SIGNING_PORTABLE_RECEIPT_SHA256', - 'WAGGLE_SIGNING_MANIFEST_PATH', - 'WAGGLE_SIGNING_MANIFEST_SHA256' - ) - $savedPortableEnvironment = @{} - foreach ($name in $portableEnvironmentNames) { - $savedPortableEnvironment[$name] = [Environment]::GetEnvironmentVariable($name) - } - try { - $portable = Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath $receiptSha256 - Assert-Equal $portable.NodePath $node 'portable Node path validation' - Assert-Equal $portable.GitPath $git 'portable Git path validation' - Assert-Equal $portable.GitRuntimePath $gitRuntime ` - 'portable Git runtime closure validation' - Assert-Equal $portable.SevenZipDllPath $sevenZipDll ` - 'portable 7-Zip closure validation' - foreach ($lock in $portable.Locks) { $lock.Dispose() } - - [IO.File]::AppendAllText( - $receiptPath, ' ', [Text.UTF8Encoding]::new($false) - ) - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath $receiptSha256 - } 'does not match its handoff SHA-256' ` - 'portable raw receipt byte tamper with stale digest rejection' - [IO.File]::WriteAllText( - $receiptPath, $portableReceiptJson, [Text.UTF8Encoding]::new($false) - ) - - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath ('E' * 64) - } 'does not match its handoff SHA-256' 'portable receipt handoff digest rejection' - - $mutatedReceipt = $portableReceiptJson | ConvertFrom-Json -Depth 32 - $mutatedReceipt.schemaVersion = 2 - Write-WaggleJsonNoBom $receiptPath $mutatedReceipt - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath ` - (Get-RealSha256 $receiptPath) - } 'schemaVersion must be 1' 'portable receipt schema rejection' - [IO.File]::WriteAllText( - $receiptPath, $portableReceiptJson, [Text.UTF8Encoding]::new($false) - ) - - $mutatedReceipt = $portableReceiptJson | ConvertFrom-Json -Depth 32 - $mutatedReceipt.portableToolchainRoot = $portableFixtureParent - Write-WaggleJsonNoBom $receiptPath $mutatedReceipt - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath ` - (Get-RealSha256 $receiptPath) - } 'receipt root' 'portable receipt root substitution rejection' - [IO.File]::WriteAllText( - $receiptPath, $portableReceiptJson, [Text.UTF8Encoding]::new($false) - ) - - $mutatedReceipt = $portableReceiptJson | ConvertFrom-Json -Depth 32 - $mutatedReceipt.archives.node.sha256 = '0' * 64 - Write-WaggleJsonNoBom $receiptPath $mutatedReceipt - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath ` - (Get-RealSha256 $receiptPath) - } 'exact distinct repository-pinned handoff' ` - 'portable receipt recomputed archive hash rejection' - [IO.File]::WriteAllText( - $receiptPath, $portableReceiptJson, [Text.UTF8Encoding]::new($false) - ) - - $mutatedReceipt = $portableReceiptJson | ConvertFrom-Json -Depth 32 - $mutatedReceipt.archives.node.path = $gitArchive - Write-WaggleJsonNoBom $receiptPath $mutatedReceipt - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath ` - (Get-RealSha256 $receiptPath) - } 'exact distinct repository-pinned handoff|does not match its pinned SHA-256' ` - 'portable receipt recomputed archive path rejection' - [IO.File]::WriteAllText( - $receiptPath, $portableReceiptJson, [Text.UTF8Encoding]::new($false) - ) - - $mutatedReceipt = $portableReceiptJson | ConvertFrom-Json -Depth 32 - $mutatedReceipt.inventory.sha256 = '0' * 64 - Write-WaggleJsonNoBom $receiptPath $mutatedReceipt - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath ` - (Get-RealSha256 $receiptPath) - } 'repository-pinned full closure' ` - 'portable receipt recomputed inventory aggregate rejection' - [IO.File]::WriteAllText( - $receiptPath, $portableReceiptJson, [Text.UTF8Encoding]::new($false) - ) - - $mutatedReceipt = $portableReceiptJson | ConvertFrom-Json -Depth 32 - $mutatedReceipt.inventory.entries[0].sha256 = '0' * 64 - Write-WaggleJsonNoBom $receiptPath $mutatedReceipt - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath ` - (Get-RealSha256 $receiptPath) - } 'inventory aggregate SHA-256 digest is invalid' ` - 'portable receipt recomputed inventory entry rejection' - [IO.File]::WriteAllText( - $receiptPath, $portableReceiptJson, [Text.UTF8Encoding]::new($false) - ) - - $mutatedReceipt = $portableReceiptJson | ConvertFrom-Json -Depth 32 - $mutatedReceipt.inventory.entries = @($mutatedReceipt.inventory.entries)[1..( - @($mutatedReceipt.inventory.entries).Count - 1 - )] - Write-WaggleJsonNoBom $receiptPath $mutatedReceipt - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath ` - (Get-RealSha256 $receiptPath) - } 'repository-pinned full closure' ` - 'portable receipt recomputed inventory full-count rejection' - [IO.File]::WriteAllText( - $receiptPath, $portableReceiptJson, [Text.UTF8Encoding]::new($false) - ) - - $unexpectedDependency = Join-Path $portableRoot 'git\mingw64\bin\injected.dll' - [IO.File]::WriteAllText($unexpectedDependency, 'unexpected') - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath $receiptSha256 - } 'missing, extra, or unexpected files' ` - 'portable unexpected adjacent dependency rejection' - [IO.File]::Delete($unexpectedDependency) - - [IO.File]::WriteAllText($gitDependency, 'tampered adjacent dependency') - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath $receiptSha256 - } 'inventory SHA-256 digest and size' ` - 'portable mutated adjacent dependency rejection' - [IO.File]::WriteAllText($gitDependency, 'fixture:libcrypto-3-x64.dll') - - [IO.File]::Delete($gitDependency) - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath $receiptSha256 - } 'missing, extra, or unexpected files' ` - 'portable missing adjacent dependency rejection' - [IO.File]::WriteAllText($gitDependency, 'fixture:libcrypto-3-x64.dll') - - [IO.File]::WriteAllText($node, 'tampered') - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath $receiptSha256 - } 'inventory SHA-256 digest and size' 'portable Node tamper rejection' - [IO.File]::WriteAllText($node, 'fixture:node.exe') - - [IO.File]::WriteAllText($git, 'wrong-publisher') - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath $receiptSha256 - } 'Git executable.*approved publisher' 'portable Git publisher rejection' - [IO.File]::WriteAllText($git, 'fixture:git.exe') - - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $outsideNode $git $sevenZip $receiptPath $receiptSha256 - } 'contained by the private portable toolchain root' ` - 'portable tool path containment rejection' - Assert-Throws { - Get-WagglePortableToolchain ` - $portableRoot $node $git $sevenZip $receiptPath $receiptSha256 ` - -DisallowedRoots @($portableFixtureParent) - } 'overlaps.*boundary' 'portable root overlap rejection' - - [Environment]::SetEnvironmentVariable( - 'WAGGLE_SIGNING_PORTABLE_TOOLCHAIN_ROOT', $portableRoot - ) - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_NODE_PATH', $node) - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_GIT_PATH', $git) - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_SEVEN_ZIP_PATH', $sevenZip) - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_RECEIPT_PATH', $receiptPath) - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_RECEIPT_SHA256', $receiptSha256) - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_PATH', $null) - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_MANIFEST_SHA256', $null) - Assert-Throws { - Get-WaggleSigningToolchain - } 'active receipt-bound signing session' ` - 'portable callback outside receipt-bound session rejection' - $resolvedPortable = Get-WaggleSigningToolchain -AllowPortableBeforeManifest - Assert-Equal $resolvedPortable.PortableToolchainRoot $portableRoot ` - 'Package setup resolves exact portable root' - foreach ($lock in $resolvedPortable.Locks) { $lock.Dispose() } - [Environment]::SetEnvironmentVariable('WAGGLE_SIGNING_PORTABLE_NODE_PATH', $null) - Assert-Throws { - Get-WaggleSigningToolchain -AllowPortableBeforeManifest - } 'must provide the exact root, Node, Git, 7-Zip, receipt path, and receipt SHA-256' ` - 'partial portable environment rejection' - - $dotnetFixture = Join-Path $portableRoot 'dotnet.exe' - [IO.File]::WriteAllText($dotnetFixture, 'wrong-publisher') - Assert-Throws { - Assert-MicrosoftAuthenticodeFile ` - $dotnetFixture '.NET host' $null $DotNetPublisher - } 'approved publisher' 'generic Microsoft signer rejected for .NET host' - [IO.File]::WriteAllText($dotnetFixture, 'exact-dotnet-publisher') - Assert-MicrosoftAuthenticodeFile ` - $dotnetFixture '.NET host' $null $DotNetPublisher - $script:passed++ - } finally { - $PortableToolchainFileCount = $savedPortableFileCount - $PortableToolchainInventorySha256 = $savedPortableInventorySha256 - foreach ($name in $portableEnvironmentNames) { - [Environment]::SetEnvironmentVariable($name, $savedPortableEnvironment[$name]) - } - [IO.Directory]::Delete($portableFixtureParent, $true) - } -} - -Assert-Equal ` - (Get-ArtifactPolicyKind 'D:\repo\app\src-tauri\target\x86_64-pc-windows-msvc\release\waggle.exe' $releaseRoot $resourcesRoot $tempRoot $version) ` - 'PE' 'main executable policy' -Assert-Equal ` - (Get-ArtifactPolicyKind 'D:\repo\app\src-tauri\target\x86_64-pc-windows-msvc\release\bundle\nsis\Waggle_0.2.0_x64-setup.exe' $releaseRoot $resourcesRoot $tempRoot $version) ` - 'PE' 'NSIS installer policy' -Assert-Throws { - Get-ArtifactPolicyKind 'D:\repo\app\src-tauri\target\x86_64-pc-windows-msvc\release\bundle\msi\Waggle_0.2.0_x64_en-US.msi' $releaseRoot $resourcesRoot $tempRoot $version -} 'approved Tauri release manifest' 'MSI rejection for NSIS-only production signing' -Assert-Throws { - Get-ArtifactPolicyKind 'D:\repo\app\src-tauri\target\x86_64-pc-windows-msvc\release\wix\x64\wix\WixUIExtension.dll' $releaseRoot $resourcesRoot $tempRoot $version -} 'approved Tauri release manifest' 'WiX rejection for NSIS-only production signing' -Assert-Equal ` - (Get-ArtifactPolicyKind 'D:\repo\app\src-tauri\resources\native\vec0.dll' $releaseRoot $resourcesRoot $tempRoot $version) ` - 'PE' 'resource policy' -Assert-Equal ` - (Get-ArtifactPolicyKind 'D:\repo\app\src-tauri\target\.signing-temp\run-123456\nst9DA7.tmp' $releaseRoot $resourcesRoot $tempRoot $version) ` - 'PE' 'NSIS uninstaller policy' - -Assert-Throws { - Get-ArtifactPolicyKind 'D:\outside\malware.exe' $releaseRoot $resourcesRoot $tempRoot $version -} 'outside every approved' 'outside-root rejection' -Assert-Throws { - Get-ArtifactPolicyKind 'D:\repo\app\src-tauri\target\x86_64-pc-windows-msvc\release-evil\waggle.exe' $releaseRoot $resourcesRoot $tempRoot $version -} 'outside every approved' 'prefix-collision rejection' -Assert-Throws { - Get-ArtifactPolicyKind 'D:\repo\app\src-tauri\target\.signing-temp\run-123456\evil.tmp' $releaseRoot $resourcesRoot $tempRoot $version -} 'outside every approved' 'wrong temp name rejection' -Assert-Throws { - Get-ArtifactPolicyKind 'D:\repo\app\src-tauri\resources\node.exe' $releaseRoot $resourcesRoot $tempRoot $version -} 'resource manifest' 'vendor binary rejection' -Assert-Throws { - Get-TrustedPath 'D:\safe\..\outside.exe' 'Traversal probe' -} 'safe, fully qualified' 'traversal rejection' -Assert-Throws { - Get-TrustedPath '\\server\share\outside.exe' 'UNC probe' -} 'safe, fully qualified' 'UNC rejection' -Assert-Throws { - Get-TrustedPath '\\?\C:\outside.exe' 'Device probe' -} 'safe, fully qualified' 'device path rejection' -Assert-Throws { - Get-TrustedPath 'D:\outside.exe:stream' 'ADS probe' -} 'safe, fully qualified' 'ADS rejection' - -$probeRoot = Join-Path ([IO.Path]::GetTempPath()) "waggle-signing-policy-$([Guid]::NewGuid().ToString('N'))" -$targetDirectory = Join-Path $probeRoot 'target' -$junctionPath = Join-Path $probeRoot 'junction' -$fakeToolDirectory = Join-Path $probeRoot 'x64' -$hardLinkReleaseRoot = Join-Path $probeRoot 'release' -try { - [IO.Directory]::CreateDirectory($targetDirectory) | Out-Null - [IO.File]::WriteAllText((Join-Path $targetDirectory 'payload.exe'), 'not a PE') - New-Item -ItemType Junction -Path $junctionPath -Target $targetDirectory | Out-Null - Assert-Throws { - Get-TrustedPath (Join-Path $junctionPath 'payload.exe') 'Junction probe' - } 'reparse point|linked filesystem' 'junction rejection' - - [IO.Directory]::CreateDirectory($fakeToolDirectory) | Out-Null - $patchableMain = Join-Path $probeRoot 'patchable-waggle.exe' - New-SyntheticPatchablePe $patchableMain - $expectedPatchedBytes = [IO.File]::ReadAllBytes($patchableMain) - $expectedToken = [Text.Encoding]::ASCII.GetBytes('__TAURI_BUNDLE_TYPE_VAR_NSS') - [Array]::Copy($expectedToken, 0, $expectedPatchedBytes, 160, $expectedToken.Length) - $expectedPatchedHash = [Convert]::ToHexString( - [Security.Cryptography.SHA256]::HashData($expectedPatchedBytes) - ) - Assert-Equal ` - (Get-NsisPatchedMainSha256 $patchableMain) ` - $expectedPatchedHash ` - 'Tauri NSIS main patch pre-authorization hash' - $missingPatchToken = Join-Path $probeRoot 'missing-patch-token.exe' - New-SyntheticPe $missingPatchToken - Assert-Throws { - Get-NsisPatchedMainSha256 $missingPatchToken - } 'exactly one unpatched' 'missing Tauri bundle token rejection' - $duplicatePatchToken = Join-Path $probeRoot 'duplicate-patch-token.exe' - $duplicateBytes = [byte[]]::new(320) - $sourceBytes = [IO.File]::ReadAllBytes($patchableMain) - [Array]::Copy($sourceBytes, $duplicateBytes, $sourceBytes.Length) - $unknownToken = [Text.Encoding]::ASCII.GetBytes('__TAURI_BUNDLE_TYPE_VAR_UNK') - [Array]::Copy($unknownToken, 0, $duplicateBytes, 270, $unknownToken.Length) - [IO.File]::WriteAllBytes($duplicatePatchToken, $duplicateBytes) - Assert-Throws { - Get-NsisPatchedMainSha256 $duplicatePatchToken - } 'exactly one unpatched' 'duplicate Tauri bundle token rejection' - $fakeSignTool = Join-Path $fakeToolDirectory 'signtool.exe' - $fakeDlib = Join-Path $fakeToolDirectory 'Azure.CodeSigning.Dlib.dll' - [IO.File]::WriteAllText($fakeSignTool, 'impostor') - [IO.File]::WriteAllText($fakeDlib, 'impostor') - Assert-Throws { - Assert-MicrosoftAuthenticodeFile ` - (Get-TrustedPath $fakeSignTool 'Fake SignTool') 'Fake SignTool' $null - } 'not validly Authenticode-signed by the approved publisher' 'fake SignTool rejection' - Assert-Throws { - Assert-MicrosoftAuthenticodeFile ` - (Get-TrustedPath $fakeDlib 'Fake dlib') 'Fake dlib' $ArtifactSigningDlibSha256 - } 'not validly Authenticode-signed by the approved publisher' 'fake dlib rejection' - - $currentPowerShell = Get-TrustedPath (Get-Process -Id $PID).Path 'Current PowerShell' - Assert-MicrosoftAuthenticodeFile $currentPowerShell 'Current PowerShell' $null - $passed++ - $approvedPowerShell = Get-ApprovedPowerShell7Path - Assert-ApprovedPowerShell7Path $approvedPowerShell - $passed++ - Assert-FreshProcessModuleIsolation ` - $approvedPowerShell 'PowerShell 7' $probeRoot - if (Test-Path -LiteralPath $SystemPowerShellPath -PathType Leaf) { - Assert-FreshProcessModuleIsolation ` - $SystemPowerShellPath 'Windows PowerShell' $probeRoot - } - - $privateDirectory = New-PrivateDirectory (Join-Path $probeRoot 'private') - if (-not (Get-Acl -LiteralPath $privateDirectory).AreAccessRulesProtected) { - throw 'Private signing directory test still inherits permissions.' - } - $passed++ - if ((New-PrivateDirectory $privateDirectory) -cne $privateDirectory) { - throw 'Private signing directory hardening is not idempotent.' - } - $passed++ - - $readLock = Open-ReadLock $fakeSignTool - try { - Assert-Throws { - $writeProbe = [IO.File]::Open( - $fakeSignTool, - [IO.FileMode]::Open, - [IO.FileAccess]::Write, - [IO.FileShare]::None - ) - $writeProbe.Dispose() - } 'used by another process|cannot access' 'read-lock write rejection' - } finally { - $readLock.Dispose() - } - - $hardLinkDeps = Join-Path $hardLinkReleaseRoot 'deps' - [IO.Directory]::CreateDirectory($hardLinkDeps) | Out-Null - $hardLinkDependency = Join-Path $hardLinkDeps 'waggle.exe' - $hardLinkMain = Join-Path $hardLinkReleaseRoot 'waggle.exe' - [IO.File]::WriteAllText($hardLinkDependency, 'cargo executable probe') - New-Item -ItemType HardLink -Path $hardLinkMain -Target $hardLinkDependency | Out-Null - $originalSystemRoot = $env:SystemRoot - try { - $env:SystemRoot = $probeRoot - Assert-Equal ` - (Get-SystemFsutilPath) ` - 'C:\Windows\System32\fsutil.exe' ` - 'fixed fsutil path ignores environment' - } finally { - $env:SystemRoot = $originalSystemRoot - } - Assert-ApprovedHardLinkTopology $hardLinkMain $hardLinkReleaseRoot - $passed++ - $detachedReleaseRoot = Join-Path $probeRoot 'detached-release' - [IO.Directory]::CreateDirectory($detachedReleaseRoot) | Out-Null - $detachedMain = Join-Path $detachedReleaseRoot 'waggle.exe' - [IO.File]::WriteAllText($detachedMain, 'detached executable probe') - Assert-Throws { - Assert-ApprovedHardLinkTopology $detachedMain $detachedReleaseRoot - } 'must have.*hard-link topology' 'detached Cargo main rejection' - Assert-ApprovedHardLinkTopology $detachedMain $detachedReleaseRoot -AllowDetachedMain - $passed++ - $rogueHardLink = Join-Path $probeRoot 'rogue.exe' - New-Item -ItemType HardLink -Path $rogueHardLink -Target $hardLinkDependency | Out-Null - Assert-Throws { - Assert-ApprovedHardLinkTopology $hardLinkMain $hardLinkReleaseRoot - } 'unexpected hard-link sibling' 'rogue hard-link rejection' -} finally { - if (Test-Path -LiteralPath $junctionPath) { [IO.Directory]::Delete($junctionPath) } - if (Test-Path -LiteralPath $probeRoot) { [IO.Directory]::Delete($probeRoot, $true) } -} - -$prebuiltFixtureRoot = Join-Path ` - ([IO.Path]::GetTempPath()) ` - "waggle-prebuilt-tree-$([Guid]::NewGuid().ToString('N'))" -$reparseDirectory = $null -try { - $seedRoot = Join-Path $prebuiltFixtureRoot 'seed' - [IO.Directory]::CreateDirectory((Join-Path $seedRoot 'Bin')) | Out-Null - [IO.Directory]::CreateDirectory((Join-Path $seedRoot 'resources')) | Out-Null - [IO.File]::WriteAllBytes( - (Join-Path $seedRoot 'Bin\Payload.bin'), - [Text.Encoding]::UTF8.GetBytes('immutable-payload-one') - ) - [IO.File]::WriteAllBytes( - (Join-Path $seedRoot 'resources\data.bin'), - [Text.Encoding]::UTF8.GetBytes('immutable-payload-two') - ) - $expectedInventory = New-WagglePrebuiltInventory -Root $seedRoot - if (@($expectedInventory.entries).Count -ne 2 -or - [string]$expectedInventory.sha256 -notmatch '^[0-9A-Fa-f]{64}$') { - throw 'Prebuilt inventory lacks its exact canonical entries and aggregate digest.' - } - $passed++ - - $treeLease = Open-WaggleValidatedPrebuiltTree ` - -Root $seedRoot -ExpectedInventory $expectedInventory -Label 'Pristine prebuilt tree' - try { - foreach ($entry in @($expectedInventory.entries)) { - $lockedPath = Join-Path $seedRoot ([string]$entry.path) - Assert-Throws { - $writeProbe = [IO.File]::Open( - $lockedPath, - [IO.FileMode]::Open, - [IO.FileAccess]::Write, - [IO.FileShare]::None - ) - $writeProbe.Dispose() - } 'used by another process|cannot access' 'validated prebuilt tree holds every file read-locked' - } - } finally { - Close-PrebuiltTreeLease $treeLease - } - - $mutablePath = Join-Path $seedRoot 'Bin\Payload.bin' - $immutablePath = Join-Path $seedRoot 'resources\data.bin' - $mutableLease = Open-WaggleValidatedPrebuiltTree ` - -Root $seedRoot -ExpectedInventory $expectedInventory ` - -Label 'Signing-mutable prebuilt tree' -MutablePaths @($mutablePath) - try { - $mutableWriteProbe = [IO.File]::Open( - $mutablePath, - [IO.FileMode]::Open, - [IO.FileAccess]::Write, - [IO.FileShare]::None - ) - $mutableWriteProbe.Dispose() - $passed++ - Assert-Throws { - $immutableWriteProbe = [IO.File]::Open( - $immutablePath, - [IO.FileMode]::Open, - [IO.FileAccess]::Write, - [IO.FileShare]::None - ) - $immutableWriteProbe.Dispose() - } 'used by another process|cannot access' 'mutable tree keeps immutable files read-locked' - } finally { - Close-PrebuiltTreeLease $mutableLease - } - - foreach ($passName in @('unsigned-generated-roots', 'signing-generated-roots')) { - $generatedTreeRoot = Join-Path $prebuiltFixtureRoot $passName - $generatedReleaseRoot = Join-Path ` - $generatedTreeRoot 'x86_64-pc-windows-msvc\release' - $generatedNsisRoot = Join-Path $generatedReleaseRoot 'nsis' - $generatedBundleNsisRoot = Join-Path $generatedReleaseRoot 'bundle\nsis' - $generatedNsisSiblingRoot = Join-Path $generatedReleaseRoot 'nsis-evil' - $generatedBundleSiblingRoot = Join-Path $generatedReleaseRoot 'bundle\nsis-old' - $generatedResourceRoot = Join-Path $generatedTreeRoot 'resources' - foreach ($directory in @( - $generatedNsisRoot, $generatedBundleNsisRoot, - $generatedNsisSiblingRoot, $generatedBundleSiblingRoot, - $generatedResourceRoot - )) { - [IO.Directory]::CreateDirectory($directory) | Out-Null - } - $generatedFiles = @( - [pscustomobject]@{ - Path = Join-Path $generatedNsisRoot 'x64\Plugins\fixture.dll' - Content = 'tauri-nsis-output' - } - [pscustomobject]@{ - Path = Join-Path $generatedBundleNsisRoot 'Waggle_fixture_x64-setup.exe' - Content = 'tauri-installer-output' - } - [pscustomobject]@{ - Path = Join-Path $generatedNsisSiblingRoot 'sibling.dll' - Content = 'locked-nsis-sibling' - } - [pscustomobject]@{ - Path = Join-Path $generatedBundleSiblingRoot 'sibling.exe' - Content = 'locked-bundle-sibling' - } - [pscustomobject]@{ - Path = Join-Path $generatedResourceRoot 'data.bin' - Content = 'locked-resource' - } - ) - foreach ($file in $generatedFiles) { - [IO.Directory]::CreateDirectory((Split-Path ([string]$file.Path) -Parent)) | Out-Null - [IO.File]::WriteAllBytes( - [string]$file.Path, [Text.Encoding]::UTF8.GetBytes([string]$file.Content) - ) - } - $generatedInventory = New-WagglePrebuiltInventory -Root $generatedTreeRoot - $generatedLease = Open-WaggleValidatedPrebuiltTree ` - -Root $generatedTreeRoot -ExpectedInventory $generatedInventory ` - -Label "$passName private work tree" ` - -RegeneratedRoots @($generatedNsisRoot, $generatedBundleNsisRoot) ` - -CargoReleaseRelativePath 'x86_64-pc-windows-msvc\release' - try { - Clear-WaggleRegeneratedRoots $generatedLease - Assert-Equal ` - (Test-Path -LiteralPath $generatedNsisRoot) $false ` - "$passName clears the exact Tauri NSIS work root" - Assert-Equal ` - (Test-Path -LiteralPath $generatedBundleNsisRoot) $false ` - "$passName clears the exact Tauri installer output root" - Assert-Equal ` - (Test-Path -LiteralPath $generatedNsisSiblingRoot -PathType Container) $true ` - "$passName preserves the nsis-evil sibling root" - Assert-Equal ` - (Test-Path -LiteralPath $generatedBundleSiblingRoot -PathType Container) $true ` - "$passName preserves the bundle nsis-old sibling root" - foreach ($lockedFile in @( - (Join-Path $generatedNsisSiblingRoot 'sibling.dll'), - (Join-Path $generatedBundleSiblingRoot 'sibling.exe'), - (Join-Path $generatedResourceRoot 'data.bin') - )) { - Assert-Throws { - $writeProbe = [IO.File]::Open( - $lockedFile, - [IO.FileMode]::Open, - [IO.FileAccess]::Write, - [IO.FileShare]::None - ) - $writeProbe.Dispose() - } 'used by another process|cannot access' ` - "$passName retains the non-generated work-tree lock for $lockedFile" - } - } finally { - Close-PrebuiltTreeLease $generatedLease - } - } - - $copySeed = { - param([string]$Name) - $destination = Join-Path $prebuiltFixtureRoot $Name - [IO.Directory]::CreateDirectory($destination) | Out-Null - Copy-Item -Path (Join-Path $seedRoot '*') -Destination $destination -Recurse - return $destination - } - - $extraRoot = & $copySeed 'extra' - [IO.File]::WriteAllText((Join-Path $extraRoot 'unexpected.bin'), 'unexpected') - Assert-Throws { - Open-WaggleValidatedPrebuiltTree ` - -Root $extraRoot -ExpectedInventory $expectedInventory -Label 'Extra-file tree' - } 'extra|unexpected|inventory' 'prebuilt tree extra-file rejection' - - $missingRoot = & $copySeed 'missing' - [IO.File]::Delete((Join-Path $missingRoot 'resources\data.bin')) - Assert-Throws { - Open-WaggleValidatedPrebuiltTree ` - -Root $missingRoot -ExpectedInventory $expectedInventory -Label 'Missing-file tree' - } 'missing|inventory' 'prebuilt tree missing-file rejection' - - $mutatedRoot = & $copySeed 'same-size-mutation' - $mutatedPath = Join-Path $mutatedRoot 'Bin\Payload.bin' - $originalLength = (Get-Item -LiteralPath $mutatedPath).Length - [IO.File]::WriteAllBytes( - $mutatedPath, - [Text.Encoding]::UTF8.GetBytes('tampered-payload-one!') - ) - Assert-Equal ` - (Get-Item -LiteralPath $mutatedPath).Length ` - $originalLength ` - 'same-size prebuilt mutation fixture' - Assert-Throws { - Open-WaggleValidatedPrebuiltTree ` - -Root $mutatedRoot -ExpectedInventory $expectedInventory -Label 'Mutated tree' - } 'SHA-256|digest|inventory' 'prebuilt tree same-size mutation rejection' - - $collisionInventory = $expectedInventory | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $collisionEntry = $collisionInventory.entries[0] | ConvertTo-Json -Depth 8 | - ConvertFrom-Json -Depth 8 -DateKind String - $collisionEntry.path = ([string]$collisionEntry.path).ToUpperInvariant() - $collisionInventory.entries = @($collisionInventory.entries) + @($collisionEntry) - Assert-Throws { - Open-WaggleValidatedPrebuiltTree ` - -Root $seedRoot -ExpectedInventory $collisionInventory -Label 'Case-collision inventory' - } 'case-insensitive|case collision|duplicate canonical' 'prebuilt inventory case-collision rejection' - - $traversalInventory = $expectedInventory | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $traversalInventory.entries[0].path = '..\outside.bin' - Assert-Throws { - Open-WaggleValidatedPrebuiltTree ` - -Root $seedRoot -ExpectedInventory $traversalInventory -Label 'Traversal inventory' - } 'relative|traversal|canonical|unsafe' 'prebuilt inventory traversal rejection' - - $adsRoot = & $copySeed 'alternate-data-stream' - $adsCarrier = Join-Path $adsRoot 'Bin\Payload.bin' - [IO.File]::WriteAllText("${adsCarrier}:waggle-probe", 'hidden-content') - Assert-Throws { - Open-WaggleValidatedPrebuiltTree ` - -Root $adsRoot -ExpectedInventory $expectedInventory -Label 'ADS tree' - } 'alternate data stream|ADS|named stream' 'prebuilt tree ADS rejection' - - $reparseRoot = & $copySeed 'reparse' - $reparseDirectory = Join-Path $reparseRoot 'resources' - $reparseTarget = Join-Path $prebuiltFixtureRoot 'reparse-target' - Move-Item -LiteralPath $reparseDirectory -Destination $reparseTarget - New-Item -ItemType Junction -Path $reparseDirectory -Target $reparseTarget | Out-Null - Assert-Throws { - Open-WaggleValidatedPrebuiltTree ` - -Root $reparseRoot -ExpectedInventory $expectedInventory -Label 'Reparse tree' - } 'reparse point|linked filesystem|junction' 'prebuilt tree reparse rejection' - - $unapprovedLinkRoot = & $copySeed 'unapproved-hardlink' - $unapprovedLink = Join-Path $unapprovedLinkRoot 'rogue-link.bin' - Copy-Item -LiteralPath (Join-Path $unapprovedLinkRoot 'resources\data.bin') ` - -Destination $unapprovedLink - $unapprovedLinkInventory = New-WagglePrebuiltInventory -Root $unapprovedLinkRoot - [IO.File]::Delete($unapprovedLink) - New-Item -ItemType HardLink -Path $unapprovedLink ` - -Target (Join-Path $unapprovedLinkRoot 'resources\data.bin') | Out-Null - Assert-Throws { - Open-WaggleValidatedPrebuiltTree ` - -Root $unapprovedLinkRoot -ExpectedInventory $unapprovedLinkInventory ` - -Label 'Unapproved hard-link tree' - } 'hard-link|hardlink|link topology' 'prebuilt tree unapproved hard-link rejection' - - $approvedLinkRoot = Join-Path $prebuiltFixtureRoot 'approved-hardlink' - $approvedDependency = Join-Path $approvedLinkRoot 'release\deps\waggle.exe' - $approvedMain = Join-Path $approvedLinkRoot 'release\waggle.exe' - [IO.Directory]::CreateDirectory((Split-Path $approvedDependency -Parent)) | Out-Null - New-SyntheticPe $approvedDependency 91 - New-Item -ItemType HardLink -Path $approvedMain -Target $approvedDependency | Out-Null - $approvedLinkInventory = New-WagglePrebuiltInventory -Root $approvedLinkRoot - $approvedLinkLease = Open-WaggleValidatedPrebuiltTree ` - -Root $approvedLinkRoot -ExpectedInventory $approvedLinkInventory ` - -Label 'Approved Cargo hard-link tree' - try { - Assert-ApprovedHardLinkTopology ` - $approvedMain (Join-Path $approvedLinkRoot 'release') - $passed++ - } finally { - Close-PrebuiltTreeLease $approvedLinkLease - } - - $combinedSourceRoot = Join-Path $prebuiltFixtureRoot 'combined-source' - $combinedReleaseRelative = 'x86_64-pc-windows-msvc\release' - $combinedDependency = Join-Path ` - $combinedSourceRoot "$combinedReleaseRelative\deps\waggle.exe" - $combinedMain = Join-Path $combinedSourceRoot "$combinedReleaseRelative\waggle.exe" - $combinedResource = Join-Path $combinedSourceRoot 'resources\service.js' - [IO.Directory]::CreateDirectory((Split-Path $combinedDependency -Parent)) | Out-Null - [IO.Directory]::CreateDirectory((Split-Path $combinedResource -Parent)) | Out-Null - New-SyntheticPe $combinedDependency 92 - New-Item -ItemType HardLink -Path $combinedMain -Target $combinedDependency | Out-Null - [IO.File]::WriteAllText($combinedResource, 'receipt-bound-sidecar') - $combinedInventory = New-WagglePrebuiltInventory ` - -Root $combinedSourceRoot -CargoReleaseRelativePath $combinedReleaseRelative - $requiredDiskBytes = Assert-WaggleHostedDiskCapacity ` - -Path $combinedSourceRoot -Inventory $combinedInventory -AvailableBytes ([long]::MaxValue) - Assert-Throws { - Assert-WaggleHostedDiskCapacity ` - -Path $combinedSourceRoot -Inventory $combinedInventory ` - -AvailableBytes ($requiredDiskBytes - 1) - } 'insufficient free disk space' 'hosted signing disk-capacity fail-fast' - $passed++ - $combinedSourceLease = Open-WaggleValidatedPrebuiltTree ` - -Root $combinedSourceRoot -ExpectedInventory $combinedInventory ` - -Label 'Combined hosted input tree' ` - -CargoReleaseRelativePath $combinedReleaseRelative - $combinedWorkRoot = Join-Path $prebuiltFixtureRoot 'combined-work' - try { - $sourceHashBeforeCopy = Get-Sha256 $combinedMain - New-WagglePrebuiltWorkCopy ` - -SourceRoot $combinedSourceRoot -DestinationRoot $combinedWorkRoot ` - -Inventory $combinedInventory -Label 'Combined hosted input tree' ` - -CargoReleaseRelativePath $combinedReleaseRelative | Out-Null - Assert-Equal (Get-Sha256 $combinedMain) $sourceHashBeforeCopy ` - 'work-copy creation leaves receipt source unchanged' - $workMain = Join-Path $combinedWorkRoot "$combinedReleaseRelative\waggle.exe" - $workDependency = Join-Path ` - $combinedWorkRoot "$combinedReleaseRelative\deps\waggle.exe" - Assert-ApprovedHardLinkTopology ` - $workMain (Join-Path $combinedWorkRoot $combinedReleaseRelative) - $workLinks = @(Get-HardLinkPaths $workMain) - if ($workLinks.Count -ne 2 -or $workLinks -notcontains $workMain -or - $workLinks -notcontains $workDependency -or - $workLinks -contains $combinedMain -or $workLinks -contains $combinedDependency) { - throw 'Work copy did not create a destination-local Cargo hard-link pair.' - } - $passed++ - $combinedWorkLease = Open-WaggleValidatedPrebuiltTree ` - -Root $combinedWorkRoot -ExpectedInventory $combinedInventory ` - -Label 'Combined mutable private work tree' ` - -MutablePaths @($workMain, $workDependency) ` - -CargoReleaseRelativePath $combinedReleaseRelative - try { - $writeProbe = [IO.File]::Open( - $workMain, - [IO.FileMode]::Open, - [IO.FileAccess]::Write, - [IO.FileShare]::None - ) - $writeProbe.Dispose() - Assert-Throws { - $writeProbe = [IO.File]::Open( - (Join-Path $combinedWorkRoot 'resources\service.js'), - [IO.FileMode]::Open, - [IO.FileAccess]::Write, - [IO.FileShare]::None - ) - $writeProbe.Dispose() - } 'used by another process|cannot access|being used|denied' ` - 'private work tree locks immutable resources while Cargo pair stays mutable' - } finally { - Close-PrebuiltTreeLease $combinedWorkLease - } - } finally { - Close-PrebuiltTreeLease $combinedSourceLease - if (Test-Path -LiteralPath $combinedWorkRoot) { - [IO.Directory]::Delete($combinedWorkRoot, $true) - } - } - - $resourcesInventory = New-WagglePrebuiltInventory ` - -Root (Join-Path $seedRoot 'resources') - $hostedReceiptPath = Join-Path $prebuiltFixtureRoot 'build-receipt.json' - $hostedReceipt = [pscustomobject][ordered]@{ - schemaVersion = 1 - repository = 'marolinik/waggle-os' - sourceRevision = 'a' * 40 - targetTriple = 'x86_64-pc-windows-msvc' - targetInventory = $expectedInventory - resourcesInventory = $resourcesInventory - checker = [pscustomobject]@{ exitCode = 0; sha256 = 'A' * 64 } - } - Write-JsonNoBom $hostedReceiptPath $hostedReceipt - $hostedReceiptLease = Get-WaggleHostedBuildReceipt ` - $hostedReceiptPath (Get-Sha256 $hostedReceiptPath) ('a' * 40) - $hostedReceiptLease.Lock.Dispose() - $passed++ - $mismatchedReceipt = $hostedReceipt | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $mismatchedReceipt.resourcesInventory.entries[0].sha256 = 'B' * 64 - $mismatchedReceipt.resourcesInventory.sha256 = Get-WaggleInventorySha256 ` - @($mismatchedReceipt.resourcesInventory.entries) - Write-JsonNoBom $hostedReceiptPath $mismatchedReceipt - Assert-Throws { - Get-WaggleHostedBuildReceipt ` - $hostedReceiptPath (Get-Sha256 $hostedReceiptPath) ('a' * 40) - } 'resource projection.*does not match' ` - 'hosted receipt rejects independently valid mismatched resource inventory' - - $payloadProjection = @( - [pscustomobject]@{ path = 'waggle.exe'; size = 128; sha256 = 'C' * 64 }, - [pscustomobject]@{ - path = 'resources\data.bin' - size = [long]$resourcesInventory.entries[0].size - sha256 = [string]$resourcesInventory.entries[0].sha256 - } - ) - Assert-WaggleUnsignedPayloadResourceProjection ` - $payloadProjection $resourcesInventory - $passed++ - $tamperedPayloadProjection = $payloadProjection | ConvertTo-Json -Depth 8 | - ConvertFrom-Json -Depth 8 -DateKind String - $tamperedPayloadProjection[1].sha256 = 'D' * 64 - Assert-Throws { - Assert-WaggleUnsignedPayloadResourceProjection ` - $tamperedPayloadProjection $resourcesInventory - } 'resource projection.*does not match' ` - 'unsigned payload rejects resource digest mismatch against build receipt' - - $preflightSigningRoot = Join-Path $prebuiltFixtureRoot 'preflight-signing' - $preflightUnsignedRoot = Join-Path $prebuiltFixtureRoot 'preflight-unsigned' - $preflightRelative = 'resources\service.js' - $preflightSigningPath = Join-Path $preflightSigningRoot $preflightRelative - $preflightUnsignedPath = Join-Path $preflightUnsignedRoot $preflightRelative - [IO.Directory]::CreateDirectory((Split-Path $preflightSigningPath -Parent)) | Out-Null - [IO.Directory]::CreateDirectory((Split-Path $preflightUnsignedPath -Parent)) | Out-Null - [IO.File]::WriteAllText($preflightSigningPath, 'signing-copy') - [IO.File]::WriteAllText($preflightUnsignedPath, 'unsigned-copy') - Assert-Equal ` - (Resolve-WagglePreflightFixedPath ` - $preflightSigningPath $preflightSigningRoot $preflightUnsignedRoot) ` - ([IO.Path]::GetFullPath($preflightUnsignedPath)) ` - 'manifest preflight resolves same relative path from unsigned work tree' - Assert-Throws { - Resolve-WagglePreflightFixedPath ` - (Join-Path $prebuiltFixtureRoot 'outside.bin') ` - $preflightSigningRoot $preflightUnsignedRoot - } 'escaped.*signing target root' 'manifest preflight rejects signing-root escape' - - $rollbackRoot = Join-Path $prebuiltFixtureRoot 'rollback' - $rollbackDependency = Join-Path $rollbackRoot 'release\deps\waggle.exe' - $rollbackMain = Join-Path $rollbackRoot 'release\waggle.exe' - [IO.Directory]::CreateDirectory((Split-Path $rollbackDependency -Parent)) | Out-Null - New-SyntheticPe $rollbackDependency 101 - New-Item -ItemType HardLink -Path $rollbackMain -Target $rollbackDependency | Out-Null - $expectedOriginalSha256 = Get-Sha256 $rollbackMain - $expectedHardLinkPaths = @(Get-HardLinkPaths $rollbackMain) - $replacement = Join-Path $rollbackRoot 'signed-replacement.exe' - $backup = Join-Path $rollbackRoot 'original.backup' - New-SyntheticPe $replacement 102 - [IO.File]::Replace($replacement, $rollbackMain, $backup, $true) - if ((Get-Sha256 $rollbackMain) -ceq $expectedOriginalSha256) { - throw 'Rollback test fixture did not replace the original artifact.' - } - $passed++ - Restore-WaggleReplacedArtifact ` - -ArtifactPath $rollbackMain -BackupPath $backup ` - -ExpectedOriginalSha256 $expectedOriginalSha256 ` - -ExpectedHardLinkPaths $expectedHardLinkPaths - Assert-Equal (Get-Sha256 $rollbackMain) $expectedOriginalSha256 'rollback restores exact main bytes' - Assert-Equal (Get-Sha256 $rollbackDependency) $expectedOriginalSha256 'rollback preserves exact dependency bytes' - Assert-ApprovedHardLinkTopology ` - $rollbackMain (Join-Path $rollbackRoot 'release') - $passed++ - - $regularRollbackArtifact = Join-Path $rollbackRoot 'regular-artifact.dll' - $regularRollbackReplacement = Join-Path $rollbackRoot 'regular-replacement.dll' - $regularRollbackBackup = Join-Path $rollbackRoot 'regular.backup' - New-SyntheticPe $regularRollbackArtifact 106 - New-SyntheticPe $regularRollbackReplacement 107 - $regularOriginalHash = Get-Sha256 $regularRollbackArtifact - [IO.File]::Replace( - $regularRollbackReplacement, - $regularRollbackArtifact, - $regularRollbackBackup, - $true - ) - Restore-WaggleReplacedArtifact ` - -ArtifactPath $regularRollbackArtifact -BackupPath $regularRollbackBackup ` - -ExpectedOriginalSha256 $regularOriginalHash ` - -ExpectedHardLinkPaths @($regularRollbackArtifact) - Assert-Equal ` - (Get-Sha256 $regularRollbackArtifact) $regularOriginalHash ` - 'rollback restores exact regular-artifact bytes' - - $missingBackupArtifact = Join-Path $rollbackRoot 'missing-backup-artifact.exe' - $missingBackup = Join-Path $rollbackRoot 'missing.backup' - New-SyntheticPe $missingBackupArtifact 103 - $missingArtifactHash = Get-Sha256 $missingBackupArtifact - Assert-Throws { - Restore-WaggleReplacedArtifact ` - -ArtifactPath $missingBackupArtifact -BackupPath $missingBackup ` - -ExpectedOriginalSha256 ('0' * 64) ` - -ExpectedHardLinkPaths @($missingBackupArtifact) - } 'backup.*missing|does not exist' 'rollback missing-backup rejection' - Assert-Equal ` - (Get-Sha256 $missingBackupArtifact) $missingArtifactHash ` - 'missing rollback backup leaves replacement unchanged' - - $corruptBackupArtifact = Join-Path $rollbackRoot 'corrupt-backup-artifact.exe' - $corruptBackup = Join-Path $rollbackRoot 'corrupt.backup' - New-SyntheticPe $corruptBackupArtifact 104 - New-SyntheticPe $corruptBackup 105 - $corruptArtifactHash = Get-Sha256 $corruptBackupArtifact - Assert-Throws { - Restore-WaggleReplacedArtifact ` - -ArtifactPath $corruptBackupArtifact -BackupPath $corruptBackup ` - -ExpectedOriginalSha256 ('0' * 64) ` - -ExpectedHardLinkPaths @($corruptBackupArtifact) - } 'backup.*SHA-256|backup.*digest|original.*digest' 'rollback corrupt-backup rejection' - Assert-Equal ` - (Get-Sha256 $corruptBackupArtifact) $corruptArtifactHash ` - 'corrupt rollback backup leaves replacement unchanged' - - Assert-Throws { - Open-WaggleValidatedPrebuiltTree ` - -Root $seedRoot -ExpectedInventory $expectedInventory ` - -Label 'Overlapping prebuilt tree' -DisallowedRoots @($prebuiltFixtureRoot) - } 'overlap|disallowed root|must be distinct' 'prebuilt tree root-overlap rejection' -} finally { - if ($null -ne $reparseDirectory -and (Test-Path -LiteralPath $reparseDirectory)) { - [IO.Directory]::Delete($reparseDirectory) - } - if (Test-Path -LiteralPath $prebuiltFixtureRoot) { - [IO.Directory]::Delete($prebuiltFixtureRoot, $true) - } -} - -$sessionFixtureRoot = Join-Path ` - ([IO.Path]::GetTempPath()) ` - "waggle-signing-session-$([Guid]::NewGuid().ToString('N'))" -$environmentNames = @( - 'WAGGLE_SIGNING_MANIFEST_PATH', 'WAGGLE_SIGNING_MANIFEST_SHA256', - 'WAGGLE_SIGNING_SESSION_ID', 'CARGO_TARGET_DIR', 'TEMP', 'TMP', - 'WAGGLE_NSIS_SIGNING_TEMP_ROOT', 'NODE_OPTIONS', 'NODE_PATH', - 'WAGGLE_SIGNING_PORTABLE_TOOLCHAIN_ROOT', - 'WAGGLE_SIGNING_PORTABLE_NODE_PATH', - 'WAGGLE_SIGNING_PORTABLE_GIT_PATH', - 'WAGGLE_SIGNING_PORTABLE_SEVEN_ZIP_PATH', - 'NAPI_RS_NATIVE_LIBRARY_PATH', 'NAPI_RS_FORCE_WASI', - 'npm_config_node_options', 'TARGET_ARCH' -) -$savedEnvironment = @{} -foreach ($name in $environmentNames) { - $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name) -} -try { - $sessionId = '0123456789abcdef0123456789abcdef' - $tauriRoot = Join-Path $sessionFixtureRoot 'app\src-tauri' - $resourcesRoot = Join-Path $tauriRoot 'resources' - $targetRoot = New-PrivateDirectory ` - (Join-Path $tauriRoot "target\.signing-builds\run-$sessionId") - $releaseRoot = Join-Path $targetRoot 'x86_64-pc-windows-msvc\release' - [IO.Directory]::CreateDirectory($resourcesRoot) | Out-Null - [IO.File]::WriteAllText((Join-Path $resourcesRoot 'service.js'), 'sidecar') - [IO.Directory]::CreateDirectory($releaseRoot) | Out-Null - $sessionDirectory = New-PrivateDirectory ` - (Join-Path $tauriRoot "target\.signing-sessions\run-$sessionId") - $tempRoot = New-PrivateDirectory ` - (Join-Path $tauriRoot "target\.signing-temp\run-$sessionId") - $configPath = Join-Path $tauriRoot 'tauri.conf.json' - $overridePath = Join-Path $sessionDirectory 'tauri.signing-override.json' - Write-JsonNoBom $configPath ([ordered]@{ version = '0.2.0' }) - Write-WaggleSigningOverride ` - $overridePath $wrapperPath $resourcesRoot | Out-Null - $unsignedOverride = Get-Content -Raw $overridePath | ConvertFrom-Json -Depth 16 - Assert-Equal $unsignedOverride.bundle.targets[0] 'nsis' 'unsigned preflight targets NSIS only' - Assert-Equal $unsignedOverride.build.beforeBuildCommand '' 'unsigned preflight disables nested build' - Assert-Equal $unsignedOverride.build.beforeBundleCommand '' 'unsigned preflight disables nested bundle hook' - $unsignedResourceMap = @($unsignedOverride.bundle.resources.PSObject.Properties) - Assert-Equal $unsignedResourceMap.Count 1 'unsigned override maps one complete resource tree' - Assert-Equal ` - ([IO.Path]::GetFullPath([string]$unsignedResourceMap[0].Name)) ` - ([IO.Path]::GetFullPath($resourcesRoot)) ` - 'unsigned override resource source' - Assert-Equal ([string]$unsignedResourceMap[0].Value) 'resources' ` - 'unsigned override resource destination' - if ($null -ne $unsignedOverride.bundle.windows.PSObject.Properties['signCommand']) { - throw 'Unsigned preflight override unexpectedly contains a signing command.' - } - $passed++ - Write-WaggleSigningOverride ` - $overridePath $wrapperPath $resourcesRoot -EnableSigning | Out-Null - $signedOverride = Get-Content -Raw $overridePath | ConvertFrom-Json -Depth 16 - Assert-Equal $signedOverride.bundle.windows.signCommand.cmd ` - $SystemPowerShellPath 'signed override uses canonical bootstrap host' - Assert-Equal ` - (@($signedOverride.bundle.windows.signCommand.args | Where-Object { $_ -ceq '%1' }).Count) ` - 1 'signed override contains one artifact placeholder' - Assert-Equal $signedOverride.build.beforeBundleCommand '' 'signed override disables nested bundle hook' - $invalidOverride = $signedOverride | ConvertTo-Json -Depth 16 | - ConvertFrom-Json -Depth 16 - $invalidOverride.bundle.resources = [ordered]@{ - (Join-Path $resourcesRoot 'native') = 'resources' - } - Write-JsonNoBom $overridePath $invalidOverride - Assert-Throws { - Assert-WaggleSigningOverrideContract ` - $overridePath $wrapperPath $resourcesRoot - } 'exact receipt-bound resource tree' ` - 'signed override rejects receipt resource subroot substitution' - Write-WaggleSigningOverride ` - $overridePath $wrapperPath $resourcesRoot -EnableSigning | Out-Null - - $toolDirectory = Join-Path $sessionFixtureRoot 'tools' - [IO.Directory]::CreateDirectory($toolDirectory) | Out-Null - $toolNames = @( - 'wrapper.ps1', 'tauri.js', 'tauri-main.js', 'tauri-index.js', - 'tauri-package.json', 'tauri-native-package.json', 'tauri-native.node', - 'vite.js', 'vite-package.json', 'bundle-node.mjs', 'build-sidecar.mjs', - 'bundle-native-deps.mjs', 'stage-sidecar-deps.mjs', 'makensis.exe', - 'git.exe', 'git-runtime.exe', 'node.exe', 'npm-cli.js', '7z.exe', 'signtool.exe', - 'artifact-signing.nupkg' - ) - $toolPaths = @{} - foreach ($toolName in $toolNames) { - $toolPath = Join-Path $toolDirectory $toolName - [IO.File]::WriteAllText($toolPath, "fixture:$toolName") - $toolPaths[$toolName] = $toolPath - } - - $context = [pscustomobject]@{ - RepoRoot = $sessionFixtureRoot - AppRoot = Join-Path $sessionFixtureRoot 'app' - TauriRoot = $tauriRoot - ResourcesRoot = $resourcesRoot - TargetRoot = $targetRoot - ReleaseRoot = $releaseRoot - ConfigPath = $configPath - OverrideConfigPath = $overridePath - WrapperPath = $wrapperPath - TauriCliPath = $toolPaths['tauri.js'] - TauriCliPackagePath = $toolPaths['tauri-package.json'] - TauriCliMainPath = $toolPaths['tauri-main.js'] - TauriCliIndexPath = $toolPaths['tauri-index.js'] - TauriNativePackagePath = $toolPaths['tauri-native-package.json'] - TauriNativeBinaryPath = $toolPaths['tauri-native.node'] - ViteCliPath = $toolPaths['vite.js'] - VitePackagePath = $toolPaths['vite-package.json'] - WebRoot = Join-Path $sessionFixtureRoot 'apps\web' - BuildScriptPaths = [ordered]@{ - bundleNode = $toolPaths['bundle-node.mjs'] - buildSidecar = $toolPaths['build-sidecar.mjs'] - bundleNativeDeps = $toolPaths['bundle-native-deps.mjs'] - stageSidecarDeps = $toolPaths['stage-sidecar-deps.mjs'] - } - MakensisPath = $toolPaths['makensis.exe'] - GitPath = $toolPaths['git.exe'] - GitRuntimePath = $toolPaths['git-runtime.exe'] - PortableToolchainRoot = $null - NodePath = $toolPaths['node.exe'] - NpmCliPath = $toolPaths['npm-cli.js'] - SevenZipPath = $toolPaths['7z.exe'] - SevenZipDllPath = $toolPaths['7z.exe'] - SignToolPath = $toolPaths['signtool.exe'] - ArtifactSigningPackagePath = $toolPaths['artifact-signing.nupkg'] - SourceRevision = 'a' * 40 - TauriCliVersion = '2.10.1' - TauriCliSha256 = Get-Sha256 $toolPaths['tauri.js'] - TauriCliPackageSha256 = Get-Sha256 $toolPaths['tauri-package.json'] - TauriCliMainSha256 = Get-Sha256 $toolPaths['tauri-main.js'] - TauriCliIndexSha256 = Get-Sha256 $toolPaths['tauri-index.js'] - TauriNativePackageSha256 = Get-Sha256 $toolPaths['tauri-native-package.json'] - TauriNativeBinarySha256 = Get-Sha256 $toolPaths['tauri-native.node'] - ViteCliSha256 = Get-Sha256 $toolPaths['vite.js'] - VitePackageSha256 = Get-Sha256 $toolPaths['vite-package.json'] - ViteVersion = '6.4.3' - BuildScriptHashes = [ordered]@{ - bundleNode = Get-Sha256 $toolPaths['bundle-node.mjs'] - buildSidecar = Get-Sha256 $toolPaths['build-sidecar.mjs'] - bundleNativeDeps = Get-Sha256 $toolPaths['bundle-native-deps.mjs'] - stageSidecarDeps = Get-Sha256 $toolPaths['stage-sidecar-deps.mjs'] - } - MakensisSha256 = Get-Sha256 $toolPaths['makensis.exe'] - GitSha256 = Get-Sha256 $toolPaths['git.exe'] - GitRuntimeSha256 = Get-Sha256 $toolPaths['git-runtime.exe'] - NodeSha256 = Get-Sha256 $toolPaths['node.exe'] - NpmCliSha256 = Get-Sha256 $toolPaths['npm-cli.js'] - SevenZipSha256 = Get-Sha256 $toolPaths['7z.exe'] - SevenZipDllSha256 = Get-Sha256 $toolPaths['7z.exe'] - SignToolSha256 = Get-Sha256 $toolPaths['signtool.exe'] - ArtifactSigningPackageSha256 = Get-Sha256 $toolPaths['artifact-signing.nupkg'] - ArtifactSigningX64ManifestSha256 = 'B' * 64 - } - $fixedPaths = @(Get-ExpectedNsisFixedPaths $context '0.2.0') - $packagedPaths = @(Get-ExpectedNsisPackagedPaths) - $slots = [Collections.Generic.List[object]]::new() - for ($index = 0; $index -lt $fixedPaths.Count; $index++) { - New-SyntheticPe $fixedPaths[$index] ([byte]($index + 1)) - $slots.Add([pscustomobject][ordered]@{ - id = 'fixed-{0:d2}' -f ($index + 1) - order = $index + 1 - kind = 'fixed' - maxUses = 1 - path = $fixedPaths[$index] - packagedPath = $packagedPaths[$index] - preSignSha256 = Get-Sha256 $fixedPaths[$index] - }) - } - $slots.Add([pscustomobject][ordered]@{ - id = 'nsis-uninstaller' - order = 13 - kind = 'generated-nsis-uninstaller' - maxUses = 1 - pathPattern = $NsisUninstallerPattern - evidencePath = Join-Path $sessionDirectory 'signed-evidence\13-nsis-uninstaller.exe' - }) - $slots.Add([pscustomobject][ordered]@{ - id = 'nsis-installer' - order = 14 - kind = 'generated-nsis-installer' - maxUses = 1 - path = Join-Path $releaseRoot 'bundle\nsis\Waggle_0.2.0_x64-setup.exe' - }) - - $manifestPath = Join-Path $sessionDirectory 'manifest.json' - $ledgerPath = Join-Path $sessionDirectory 'callback-ledger.json' - $baseManifest = [pscustomobject][ordered]@{ - schemaVersion = 1 - mode = 'nsis' - sessionId = $sessionId - sourceRevision = $context.SourceRevision - createdAtUtc = [DateTimeOffset]::UtcNow.AddMinutes(-1).ToString('O') - expiresAtUtc = [DateTimeOffset]::UtcNow.AddHours(1).ToString('O') - repoRoot = $context.RepoRoot - tauriRoot = $tauriRoot - targetRoot = $targetRoot - releaseRoot = $releaseRoot - resourcesRoot = $resourcesRoot - tempRoot = $tempRoot - ledgerPath = $ledgerPath - appVersion = '0.2.0' - payloads = @( - [pscustomobject]@{ path = 'waggle.exe'; sha256 = '1' * 64; size = 128 } - ) + @(1..9 | ForEach-Object { - [pscustomobject]@{ path = "resources\fixture-$_.bin"; sha256 = '2' * 64; size = $_ } - }) - toolchain = [pscustomobject][ordered]@{ - wrapperPath = $context.WrapperPath - wrapperSha256 = Get-Sha256 $context.WrapperPath - tauriConfigPath = $configPath - tauriConfigSha256 = Get-Sha256 $configPath - tauriOverrideConfigPath = $overridePath - tauriOverrideConfigSha256 = Get-Sha256 $overridePath - tauriCliPath = $context.TauriCliPath - tauriCliSha256 = $context.TauriCliSha256 - tauriCliPackagePath = $context.TauriCliPackagePath - tauriCliPackageSha256 = $context.TauriCliPackageSha256 - tauriCliMainPath = $context.TauriCliMainPath - tauriCliMainSha256 = $context.TauriCliMainSha256 - tauriCliIndexPath = $context.TauriCliIndexPath - tauriCliIndexSha256 = $context.TauriCliIndexSha256 - tauriNativePackagePath = $context.TauriNativePackagePath - tauriNativePackageSha256 = $context.TauriNativePackageSha256 - tauriNativeBinaryPath = $context.TauriNativeBinaryPath - tauriNativeBinarySha256 = $context.TauriNativeBinarySha256 - tauriCliVersion = $context.TauriCliVersion - viteCliPath = $context.ViteCliPath - viteCliSha256 = $context.ViteCliSha256 - vitePackagePath = $context.VitePackagePath - vitePackageSha256 = $context.VitePackageSha256 - viteVersion = $context.ViteVersion - buildScripts = [pscustomobject][ordered]@{ - bundleNode = [pscustomobject]@{ path = $context.BuildScriptPaths.bundleNode; sha256 = $context.BuildScriptHashes.bundleNode } - buildSidecar = [pscustomobject]@{ path = $context.BuildScriptPaths.buildSidecar; sha256 = $context.BuildScriptHashes.buildSidecar } - bundleNativeDeps = [pscustomobject]@{ path = $context.BuildScriptPaths.bundleNativeDeps; sha256 = $context.BuildScriptHashes.bundleNativeDeps } - stageSidecarDeps = [pscustomobject]@{ path = $context.BuildScriptPaths.stageSidecarDeps; sha256 = $context.BuildScriptHashes.stageSidecarDeps } - } - makensisPath = $context.MakensisPath - makensisSha256 = $context.MakensisSha256 - gitPath = $context.GitPath - gitSha256 = $context.GitSha256 - gitRuntimePath = $context.GitRuntimePath - gitRuntimeSha256 = $context.GitRuntimeSha256 - nodePath = $context.NodePath - nodeSha256 = $context.NodeSha256 - npmCliPath = $context.NpmCliPath - npmCliSha256 = $context.NpmCliSha256 - sevenZipPath = $context.SevenZipPath - sevenZipSha256 = $context.SevenZipSha256 - signToolPath = $context.SignToolPath - signToolSha256 = $context.SignToolSha256 - artifactSigningPackagePath = $context.ArtifactSigningPackagePath - artifactSigningPackageSha256 = $context.ArtifactSigningPackageSha256 - artifactSigningX64ManifestSha256 = $context.ArtifactSigningX64ManifestSha256 - } - slots = @($slots) - } - $writeSessionFixture = { - param([object]$Manifest) - Write-JsonNoBom $manifestPath $Manifest - $manifestHash = Get-Sha256 $manifestPath - Write-JsonNoBom $ledgerPath (New-PendingLedger $sessionId $manifestHash $Manifest.slots) - $env:WAGGLE_SIGNING_MANIFEST_SHA256 = $manifestHash - return $manifestHash - } - - $env:WAGGLE_SIGNING_MANIFEST_PATH = $manifestPath - $env:WAGGLE_SIGNING_SESSION_ID = $sessionId - $env:CARGO_TARGET_DIR = $targetRoot - $env:TEMP = $tempRoot - $env:TMP = $tempRoot - $env:WAGGLE_NSIS_SIGNING_TEMP_ROOT = $tempRoot - [void](& $writeSessionFixture $baseManifest) - - $loadedSession = Get-WaggleSigningSession $context - try { - Assert-Equal $loadedSession.Id $sessionId 'valid manifest session load' - foreach ($lockedPath in @( - $context.TauriCliMainPath, - $context.TauriCliIndexPath, - $context.TauriNativeBinaryPath - )) { - Assert-Throws { - $writeProbe = [IO.File]::Open( - $lockedPath, - [IO.FileMode]::Open, - [IO.FileAccess]::Write, - [IO.FileShare]::None - ) - $writeProbe.Dispose() - } 'used by another process|cannot access' 'loaded session locks complete Tauri runtime closure' - } - } finally { - foreach ($lock in $loadedSession.Locks) { $lock.Dispose() } - } - - $portableContext = $context | Select-Object * - $portableContext.PortableToolchainRoot = $toolDirectory - $portableContext | Add-Member ` - -NotePropertyName PortableToolchainReceiptPath ` - -NotePropertyValue $toolPaths['artifact-signing.nupkg'] - $portableContext | Add-Member ` - -NotePropertyName PortableToolchainReceiptSha256 ` - -NotePropertyValue (Get-Sha256 $toolPaths['artifact-signing.nupkg']) - $portableContext | Add-Member ` - -NotePropertyName PortableToolchainInventorySha256 ` - -NotePropertyValue $PortableToolchainInventorySha256 - $portableContext | Add-Member ` - -NotePropertyName PortableToolchainLocks ` - -NotePropertyValue ([Collections.Generic.List[IDisposable]]::new()) - $portableContext.SevenZipDllPath = $toolPaths['7z.exe'] - $portableContext.SevenZipDllSha256 = Get-Sha256 $toolPaths['7z.exe'] - $portableManifest = $baseManifest | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $portableManifest | Add-Member -NotePropertyName buildReceipt -NotePropertyValue ( - [pscustomobject]@{ - schemaVersion = 1 - repository = 'marolinik/waggle-os' - sourceRevision = $context.SourceRevision - targetTriple = 'x86_64-pc-windows-msvc' - } - ) - $portableManifest.toolchain | Add-Member ` - -NotePropertyName portableToolchainRoot -NotePropertyValue $toolDirectory - $portableManifest.toolchain | Add-Member ` - -NotePropertyName sevenZipDllPath -NotePropertyValue $portableContext.SevenZipDllPath - $portableManifest.toolchain | Add-Member ` - -NotePropertyName sevenZipDllSha256 -NotePropertyValue $portableContext.SevenZipDllSha256 - $portableManifest.toolchain | Add-Member ` - -NotePropertyName portableToolchainReceiptPath ` - -NotePropertyValue $portableContext.PortableToolchainReceiptPath - $portableManifest.toolchain | Add-Member ` - -NotePropertyName portableToolchainReceiptSha256 ` - -NotePropertyValue $portableContext.PortableToolchainReceiptSha256 - $portableManifest.toolchain | Add-Member ` - -NotePropertyName portableToolchainInventorySha256 ` - -NotePropertyValue $PortableToolchainInventorySha256 - $portableManifest.toolchain | Add-Member ` - -NotePropertyName portableToolchainFileCount ` - -NotePropertyValue $PortableToolchainFileCount - $env:WAGGLE_SIGNING_PORTABLE_TOOLCHAIN_ROOT = $toolDirectory - $env:WAGGLE_SIGNING_PORTABLE_NODE_PATH = $context.NodePath - $env:WAGGLE_SIGNING_PORTABLE_GIT_PATH = $context.GitPath - $env:WAGGLE_SIGNING_PORTABLE_SEVEN_ZIP_PATH = $context.SevenZipPath - $env:WAGGLE_SIGNING_PORTABLE_RECEIPT_PATH = ` - $portableContext.PortableToolchainReceiptPath - $env:WAGGLE_SIGNING_PORTABLE_RECEIPT_SHA256 = ` - $portableContext.PortableToolchainReceiptSha256 - [void](& $writeSessionFixture $portableManifest) - $portableSession = Get-WaggleSigningSession $portableContext - try { - Assert-Equal $portableSession.Id $sessionId ` - 'receipt-bound portable manifest session load' - } finally { - foreach ($lock in $portableSession.Locks) { $lock.Dispose() } - } - - $wrongPortableRootManifest = $portableManifest | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $wrongPortableRootManifest.toolchain.portableToolchainRoot = ` - Join-Path $sessionFixtureRoot 'substituted-tools' - [void](& $writeSessionFixture $wrongPortableRootManifest) - Assert-Throws { - Get-WaggleSigningSession $portableContext - } 'Portable signing toolchain root does not match' ` - 'portable manifest root substitution rejection' - - $wrongPortableHashManifest = $portableManifest | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $wrongPortableHashManifest.toolchain.sevenZipDllSha256 = '0' * 64 - [void](& $writeSessionFixture $wrongPortableHashManifest) - Assert-Throws { - Get-WaggleSigningSession $portableContext - } '7-Zip runtime library manifest SHA-256' ` - 'portable manifest closure digest substitution rejection' - - [void](& $writeSessionFixture $portableManifest) - $env:WAGGLE_SIGNING_PORTABLE_NODE_PATH = $context.GitPath - Assert-Throws { - Get-WaggleSigningSession $portableContext - } 'WAGGLE_SIGNING_PORTABLE_NODE_PATH does not match' ` - 'portable callback environment substitution rejection' - $env:WAGGLE_SIGNING_PORTABLE_NODE_PATH = $context.NodePath - - $unboundPortableManifest = $portableManifest | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $unboundPortableManifest.PSObject.Properties.Remove('buildReceipt') - [void](& $writeSessionFixture $unboundPortableManifest) - Assert-Throws { - Get-WaggleSigningSession $portableContext - } 'missing required property.*buildReceipt' ` - 'portable callback without hosted receipt rejection' - - foreach ($portableEnvironmentName in @( - 'WAGGLE_SIGNING_PORTABLE_TOOLCHAIN_ROOT', - 'WAGGLE_SIGNING_PORTABLE_NODE_PATH', - 'WAGGLE_SIGNING_PORTABLE_GIT_PATH', - 'WAGGLE_SIGNING_PORTABLE_SEVEN_ZIP_PATH', - 'WAGGLE_SIGNING_PORTABLE_RECEIPT_PATH', - 'WAGGLE_SIGNING_PORTABLE_RECEIPT_SHA256' - )) { - [Environment]::SetEnvironmentVariable($portableEnvironmentName, $null) - } - [void](& $writeSessionFixture $baseManifest) - - $validManifestHash = $env:WAGGLE_SIGNING_MANIFEST_SHA256 - $env:WAGGLE_SIGNING_MANIFEST_SHA256 = '0' * 64 - Assert-Throws { - Get-WaggleSigningSession $context - } 'manifest does not match.*SHA256|manifest.*WAGGLE_SIGNING_MANIFEST_SHA256' 'wrong manifest digest rejection' - $env:WAGGLE_SIGNING_MANIFEST_SHA256 = $validManifestHash - - $unsupportedManifest = $baseManifest | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $unsupportedManifest.mode = 'msi' - [void](& $writeSessionFixture $unsupportedManifest) - Assert-Throws { - Get-WaggleSigningSession $context - } 'NSIS-only' 'unsupported manifest mode rejection' - - $expiredManifest = $baseManifest | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $expiredManifest.createdAtUtc = [DateTimeOffset]::UtcNow.AddHours(-2).ToString('O') - $expiredManifest.expiresAtUtc = [DateTimeOffset]::UtcNow.AddHours(-1).ToString('O') - [void](& $writeSessionFixture $expiredManifest) - Assert-Throws { - Get-WaggleSigningSession $context - } 'expired|four-hour' 'expired manifest rejection' - - $wrongToolManifest = $baseManifest | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $wrongToolManifest.toolchain.wrapperSha256 = '0' * 64 - [void](& $writeSessionFixture $wrongToolManifest) - Assert-Throws { - Get-WaggleSigningSession $context - } 'wrapper.*SHA-256' 'wrong wrapper digest rejection' - - $wrongNativeManifest = $baseManifest | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $wrongNativeManifest.toolchain.tauriNativeBinarySha256 = '0' * 64 - [void](& $writeSessionFixture $wrongNativeManifest) - Assert-Throws { - Get-WaggleSigningSession $context - } 'native CLI binary.*SHA-256|native CLI binary.*digest' 'wrong Tauri native digest rejection' - - Write-JsonNoBom $overridePath ([ordered]@{ - build = @{ beforeBuildCommand = '' } - bundle = @{ active = $true; targets = @('msi'); windows = @{ - signCommand = @{ cmd = $SystemPowerShellPath; args = @( - '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', - '-File', $wrapperPath, '-ArtifactPath', '%1' - ) } - } } - }) - $wrongOverrideManifest = $baseManifest | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $wrongOverrideManifest.toolchain.tauriOverrideConfigSha256 = Get-Sha256 $overridePath - [void](& $writeSessionFixture $wrongOverrideManifest) - Assert-Throws { - Get-WaggleSigningSession $context - } 'NSIS-only callback contract' 'MSI signing override rejection' - Write-WaggleSigningOverride $overridePath $wrapperPath -EnableSigning | Out-Null - - [void](& $writeSessionFixture $baseManifest) - $env:TEMP = Join-Path $sessionFixtureRoot 'wrong-temp' - Assert-Throws { - Get-WaggleSigningSession $context - } 'TEMP path does not match' 'cross-session TEMP rejection' - $env:TEMP = $tempRoot - - [void](& $writeSessionFixture $baseManifest) - $legacyLedger = [pscustomobject]@{ - schemaVersion = 1 - sessionId = $sessionId - manifestSha256 = $env:WAGGLE_SIGNING_MANIFEST_SHA256 - nextOrder = 1 - entries = @() - } - Assert-Throws { - Assert-WaggleSigningLedgerState ` - ([pscustomobject]@{ - Id = $sessionId - ManifestSha256 = $env:WAGGLE_SIGNING_MANIFEST_SHA256 - Manifest = $baseManifest - TempRoot = $tempRoot - }) ` - $legacyLedger - } 'active manifest session|schemaVersion' 'legacy empty ledger rejection' - - $lifecycleDirectory = New-PrivateDirectory (Join-Path $sessionFixtureRoot 'lifecycle') - $lifecycleTemp = New-PrivateDirectory (Join-Path $lifecycleDirectory 'temp') - $lifecycleSlots = [Collections.Generic.List[object]]::new() - $signedHost = Get-TrustedPath (Get-Process -Id $PID).Path 'Signed lifecycle host' -AllowHardLink - for ($index = 0; $index -lt 14; $index++) { - $path = if ($index -eq 0) { - $signedHost - } else { - $candidate = Join-Path $lifecycleDirectory "slot-$($index + 1).exe" - New-SyntheticPe $candidate ([byte]($index + 20)) - $candidate - } - $lifecycleSlots.Add([pscustomobject][ordered]@{ - id = 'lifecycle-{0:d2}' -f ($index + 1) - order = $index + 1 - kind = 'fixed' - maxUses = 1 - path = $path - preSignSha256 = Get-Sha256 $path - }) - } - $lifecycleLedgerPath = Join-Path $lifecycleDirectory 'callback-ledger.json' - $lifecycleSession = [pscustomobject]@{ - Id = 'abcdef0123456789abcdef0123456789' - ManifestSha256 = 'C' * 64 - Manifest = [pscustomobject]@{ slots = @($lifecycleSlots) } - TempRoot = $lifecycleTemp - SessionDirectory = $lifecycleDirectory - LedgerPath = $lifecycleLedgerPath - ManifestPath = Join-Path $lifecycleDirectory 'manifest.json' - Context = [pscustomobject]@{ SourceRevision = 'a' * 40 } - } - Write-JsonNoBom $lifecycleLedgerPath ` - (New-PendingLedger $lifecycleSession.Id $lifecycleSession.ManifestSha256 $lifecycleSlots) - $lifecycleLedger = Get-Content -Raw $lifecycleLedgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-WaggleSigningLedgerState $lifecycleSession $lifecycleLedger - $passed++ - - Assert-Throws { - Reserve-WaggleSigningCallback $lifecycleSession $lifecycleSlots[1].path - } 'callback phase' 'cross-phase callback rejection' - - $ledgerBeforeInvalidMutation = Get-Content -Raw -LiteralPath $lifecycleLedgerPath - Assert-Throws { - Invoke-WaggleLedgerMutation $lifecycleSession { - param($ledger) - $ledger.entries[0].attempts = 99 - } - } 'pristine|reservation metadata' 'invalid ledger mutation rejection' - Assert-Equal ` - (Get-Content -Raw -LiteralPath $lifecycleLedgerPath) ` - $ledgerBeforeInvalidMutation ` - 'invalid mutation leaves ledger unchanged' - - $reservation = Reserve-WaggleSigningCallback $lifecycleSession $lifecycleSlots[0].path - Assert-Throws { - Reserve-WaggleSigningCallback $lifecycleSession $lifecycleSlots[0].path - } 'already consumed|state must be' 'duplicate callback rejection' - Assert-Throws { - Reserve-WaggleSigningCallback $lifecycleSession $lifecycleSlots[1].path - } 'callback phase|state must be' 'reserved callback blocks later slot' - Complete-WaggleSigningCallback $lifecycleSession $reservation $lifecycleSlots[0].path | Out-Null - $completedLedger = Get-Content -Raw -LiteralPath $lifecycleLedgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-Equal $completedLedger.entries[0].status 'completed' 'callback completion state' - [IO.File]::Copy($signedHost, $lifecycleSlots[2].path, $true) - $lifecycleSlots[2].preSignSha256 = Get-Sha256 $lifecycleSlots[2].path - $phaseReservation = Reserve-WaggleSigningCallback ` - $lifecycleSession $lifecycleSlots[2].path - Assert-Equal $phaseReservation.order 3 'resource callback may arrive out of manifest order' - Complete-WaggleSigningCallback ` - $lifecycleSession $phaseReservation $lifecycleSlots[2].path | Out-Null - $secondReservation = Reserve-WaggleSigningCallback $lifecycleSession $lifecycleSlots[1].path - Assert-Equal $secondReservation.order 2 'next ordered callback reservation' - $failureReceiptPath = Fail-WaggleSigningSession ` - $lifecycleSession $secondReservation 'fixture_failure' 'fixture error' 'restored-original' - Assert-Equal ` - (Test-Path -LiteralPath $failureReceiptPath -PathType Leaf) ` - $true ` - 'failed callback publishes durable failure receipt' - $failedLedger = Get-Content -Raw -LiteralPath $lifecycleLedgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-Equal $failedLedger.state 'failed' 'callback failure terminal ledger state' - Assert-Equal $failedLedger.entries[1].status 'failed' 'reserved callback becomes failed' - $failedLedgerBeforeRetry = Get-Content -Raw -LiteralPath $lifecycleLedgerPath - Assert-Throws { - Reserve-WaggleSigningCallback $lifecycleSession $lifecycleSlots[2].path - } 'receipt already exists|terminal' 'failed session callback retry rejection' - Assert-Equal ` - (Get-Content -Raw -LiteralPath $lifecycleLedgerPath) ` - $failedLedgerBeforeRetry ` - 'failed session retry leaves ledger unchanged' - - $completeDirectory = New-PrivateDirectory (Join-Path $sessionFixtureRoot 'complete-ledger') - $completeTemp = New-PrivateDirectory (Join-Path $completeDirectory 'temp') - $completeSlots = [Collections.Generic.List[object]]::new() - $completePayloads = [Collections.Generic.List[object]]::new() - for ($index = 0; $index -lt 12; $index++) { - $completePath = Join-Path $completeDirectory "complete-$($index + 1).exe" - New-SyntheticPe $completePath ([byte]($index + 40)) - $completeSlots.Add([pscustomobject][ordered]@{ - id = 'complete-{0:d2}' -f ($index + 1) - order = $index + 1 - kind = 'fixed' - maxUses = 1 - path = $completePath - packagedPath = $packagedPaths[$index] - preSignSha256 = Get-Sha256 $completePath - }) - $completePayloads.Add([pscustomobject][ordered]@{ - path = $packagedPaths[$index] - sha256 = Get-Sha256 $completePath - size = [long](Get-Item -LiteralPath $completePath).Length - extractedPath = $completePath - }) - } - $completeUninstallerPath = Join-Path $completeTemp 'nstABCD.tmp' - New-SyntheticPe $completeUninstallerPath 80 - $completeEvidencePath = Join-Path $completeDirectory 'signed-evidence\13-nsis-uninstaller.exe' - New-SyntheticPe $completeEvidencePath 81 - $completeSlots.Add([pscustomobject][ordered]@{ - id = 'complete-13'; order = 13; kind = 'generated-nsis-uninstaller'; maxUses = 1 - pathPattern = $NsisUninstallerPattern; evidencePath = $completeEvidencePath - }) - $completeInstallerPath = Join-Path $completeDirectory 'Waggle_0.2.0_x64-setup.exe' - New-SyntheticPe $completeInstallerPath 82 - $completeSlots.Add([pscustomobject][ordered]@{ - id = 'complete-14'; order = 14; kind = 'generated-nsis-installer'; maxUses = 1 - path = $completeInstallerPath - }) - $completeLedgerPath = Join-Path $completeDirectory 'callback-ledger.json' - $completeSession = [pscustomobject]@{ - Id = 'fedcba9876543210fedcba9876543210' - ManifestSha256 = 'D' * 64 - Manifest = [pscustomobject]@{ - slots = @($completeSlots) - payloads = @($completePayloads | ForEach-Object { - [pscustomobject]@{ path = $_.path; sha256 = $_.sha256; size = $_.size } - }) - } - TempRoot = $completeTemp - SessionDirectory = $completeDirectory - LedgerPath = $completeLedgerPath - ManifestPath = Join-Path $completeDirectory 'manifest.json' - Context = [pscustomobject]@{ - SourceRevision = 'b' * 40 - SignToolPath = $toolPaths['signtool.exe'] - SevenZipPath = $toolPaths['7z.exe'] - } - } - $completeLedger = New-PendingLedger ` - $completeSession.Id $completeSession.ManifestSha256 @($completeSlots) - $reservedAt = [DateTimeOffset]::UtcNow.AddMinutes(-2).ToString('O') - $completedAt = [DateTimeOffset]::UtcNow.AddMinutes(-1).ToString('O') - foreach ($entry in $completeLedger.entries) { - $slot = $completeSlots[[int]$entry.order - 1] - $entryPath = if ([int]$entry.order -eq 13) { - $completeUninstallerPath - } else { - [string]$slot.path - } - $entry.status = 'completed' - $entry.attempts = 1 - $entry.reservationId = [Guid]::NewGuid().ToString('N') - $entry.path = $entryPath - $entry.preSignSha256 = Get-Sha256 $entryPath - $entry.reservedAtUtc = $reservedAt - $entry.completedAtUtc = $completedAt - $entry.postSignSha256 = if ([int]$entry.order -eq 13) { - Get-Sha256 $completeEvidencePath - } else { - Get-Sha256 $entryPath - } - $entry.signerSubject = 'CN=Fixture signer' - } - Write-JsonNoBom $completeLedgerPath $completeLedger - $loadedCompleteLedger = Get-CompletedWaggleSigningLedger $completeSession - Assert-Equal $loadedCompleteLedger.entries.Count 14 'complete finalizer accepts exact 14-slot ledger' - $changedPayloads = @($completePayloads | ForEach-Object { - [pscustomobject]@{ - path = $_.path; sha256 = $_.sha256; size = $_.size; extractedPath = $_.extractedPath - } - }) - $changedPayloads[0].sha256 = '0' * 64 - Assert-Throws { - Assert-WaggleFinalPayloadBindings ` - $completeSession $loadedCompleteLedger $changedPayloads { param($Path, $SignTool) } - } 'payload bytes differ' 'same-name changed packaged payload rejection' - $completeLedger.entries[13].status = 'pending' - $completeLedger.entries[13].attempts = 0 - foreach ($field in @( - 'reservationId', 'path', 'preSignSha256', 'reservedAtUtc', - 'completedAtUtc', 'postSignSha256', 'signerSubject' - )) { - $completeLedger.entries[13].$field = $null - } - Write-JsonNoBom $completeLedgerPath $completeLedger - Assert-Throws { - Get-CompletedWaggleSigningLedger $completeSession - } 'incomplete' 'finalizer rejects incomplete callback ledger' - Write-JsonNoBom $completeLedgerPath $loadedCompleteLedger - $finalResult = Assert-WaggleSigningPackageComplete ` - $completeSession @($completePayloads) { param($Path, $SignTool) } - Assert-Equal ` - (Test-Path -LiteralPath $finalResult.ReceiptPath -PathType Leaf) ` - $true ` - 'finalizer publishes regular provenance receipt' - $sealedLedger = Get-Content -Raw -LiteralPath $completeLedgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-Equal $sealedLedger.state 'sealed' 'finalizer seals only after receipt publication' - Assert-Equal ` - $sealedLedger.terminalReceiptSha256 ` - (Get-Sha256 $finalResult.ReceiptPath) ` - 'sealed ledger binds exact provenance receipt digest' - - $receiptFailureDirectory = New-PrivateDirectory ` - (Join-Path $sessionFixtureRoot 'receipt-ledger-recovery') - $receiptFailureLedgerPath = Join-Path $receiptFailureDirectory 'callback-ledger.json' - $receiptFailureSession = [pscustomobject]@{ - Id = '11111111111111111111111111111111' - ManifestSha256 = 'F' * 64 - Manifest = [pscustomobject]@{ slots = @($completeSlots) } - TempRoot = $completeTemp - SessionDirectory = $receiptFailureDirectory - LedgerPath = $receiptFailureLedgerPath - ManifestPath = Join-Path $receiptFailureDirectory 'manifest.json' - Context = [pscustomobject]@{ SourceRevision = 'b' * 40 } - } - Write-JsonNoBom $receiptFailureLedgerPath ` - (New-PendingLedger $receiptFailureSession.Id $receiptFailureSession.ManifestSha256 @($completeSlots)) - $ledgerBlocker = [IO.FileStream]::new( - $receiptFailureLedgerPath, - [IO.FileMode]::Open, - [IO.FileAccess]::Read, - [IO.FileShare]::Read - ) - try { - Assert-Throws { - Fail-WaggleSigningSession ` - $receiptFailureSession $null 'forced-ledger-failure' ` - 'forced receipt-before-ledger recovery fixture' - } 'replace|access|being used|used by another process' ` - 'ledger replace failure occurs after durable receipt publication' - } finally { - $ledgerBlocker.Dispose() - } - $pendingReceiptPath = Join-Path $receiptFailureDirectory 'failure-receipt.json' - $terminalIntentPath = Join-Path $receiptFailureDirectory 'terminal-intent.json' - Assert-Equal ` - (Test-Path -LiteralPath $pendingReceiptPath -PathType Leaf) $true ` - 'ledger failure leaves a durable pending terminal receipt' - Assert-Equal ` - (Test-Path -LiteralPath $terminalIntentPath -PathType Leaf) $true ` - 'ledger failure leaves a durable terminal intent' - $receiptFailureLedger = Get-Content -Raw -LiteralPath $receiptFailureLedgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-Equal $receiptFailureLedger.state 'open' 'receipt failure leaves ledger open' - Assert-Throws { - Invoke-WaggleLedgerMutation $receiptFailureSession { param($ledger) } - } 'pending terminal receipt' 'pending terminal intent blocks ordinary ledger mutation' - $pendingReceiptBytes = [IO.File]::ReadAllBytes($pendingReceiptPath) - $pendingReceipt = Get-Content -Raw -LiteralPath $pendingReceiptPath | - ConvertFrom-Json -Depth 32 -DateKind String - $pendingReceiptSha256 = Get-Sha256 $pendingReceiptPath - [IO.File]::WriteAllText( - $pendingReceiptPath, - '{"schemaVersion":1,"status":"failed","tampered":true}', - [Text.UTF8Encoding]::new($false) - ) - Assert-Throws { - Fail-WaggleSigningSession ` - $receiptFailureSession $null 'forced-ledger-failure' ` - 'forced receipt-before-ledger recovery fixture' - } 'intent|digest|receipt' 'tampered pending terminal receipt is rejected' - [IO.File]::WriteAllBytes($pendingReceiptPath, $pendingReceiptBytes) - $recoveredReceiptPath = Fail-WaggleSigningSession ` - $receiptFailureSession $null 'forced-ledger-failure' ` - 'forced receipt-before-ledger recovery fixture' - $recoveredLedger = Get-Content -Raw -LiteralPath $receiptFailureLedgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-Equal $recoveredLedger.state 'failed' 'pending terminal receipt recovers ledger state' - Assert-Equal ` - $recoveredLedger.terminalAtUtc $pendingReceipt.terminalAtUtc ` - 'recovery reuses the original durable terminal timestamp' - Assert-Equal ` - $recoveredLedger.terminalReceiptSha256 $pendingReceiptSha256 ` - 'recovery reuses the original durable terminal receipt digest' - $recoveredBytes = [IO.File]::ReadAllBytes($recoveredReceiptPath) - [IO.File]::WriteAllText($recoveredReceiptPath, '{}', [Text.UTF8Encoding]::new($false)) - Assert-Throws { - Fail-WaggleSigningSession ` - $receiptFailureSession $null 'forced-ledger-failure' ` - 'forced receipt-before-ledger recovery fixture' - } 'intent|digest|receipt' 'post-commit terminal receipt tampering is rejected' - [IO.File]::WriteAllBytes($recoveredReceiptPath, $recoveredBytes) - - $intentOnlyDirectory = New-PrivateDirectory ` - (Join-Path $sessionFixtureRoot 'intent-only-recovery') - $intentOnlyLedgerPath = Join-Path $intentOnlyDirectory 'callback-ledger.json' - $intentOnlySession = [pscustomobject]@{ - Id = '12121212121212121212121212121212' - ManifestSha256 = '1' * 64 - Manifest = [pscustomobject]@{ slots = @($completeSlots) } - TempRoot = $completeTemp - SessionDirectory = $intentOnlyDirectory - LedgerPath = $intentOnlyLedgerPath - ManifestPath = Join-Path $intentOnlyDirectory 'manifest.json' - Context = [pscustomobject]@{ SourceRevision = 'b' * 40 } - } - Write-JsonNoBom $intentOnlyLedgerPath ` - (New-PendingLedger $intentOnlySession.Id $intentOnlySession.ManifestSha256 @($completeSlots)) - $intentOnlyTerminalAt = [DateTimeOffset]::UtcNow.AddMinutes(-3).ToString('O') - $intentOnlyReceipt = [pscustomobject][ordered]@{ - schemaVersion = 1 - status = 'failed' - sessionId = $intentOnlySession.Id - sourceRevision = $intentOnlySession.Context.SourceRevision - manifestPath = $intentOnlySession.ManifestPath - manifestSha256 = $intentOnlySession.ManifestSha256 - failureCode = 'intent-only-failure' - failureMessage = 'recover the receipt from the durable terminal intent' - failedSlotId = $null - rollbackOutcome = 'not-required' - terminalAtUtc = $intentOnlyTerminalAt - } - $intentOnlyStagedReceiptPath = Join-Path $intentOnlyDirectory 'staged-receipt.tmp' - Write-WaggleDurableJsonNew $intentOnlyStagedReceiptPath $intentOnlyReceipt - $intentOnlyReceiptSha256 = Get-Sha256 $intentOnlyStagedReceiptPath - [IO.File]::Delete($intentOnlyStagedReceiptPath) - Write-WaggleDurableJsonNew ` - (Join-Path $intentOnlyDirectory 'terminal-intent.json') ` - ([pscustomobject][ordered]@{ - schemaVersion = 1 - state = 'failed' - sessionId = $intentOnlySession.Id - manifestSha256 = $intentOnlySession.ManifestSha256 - terminalAtUtc = $intentOnlyTerminalAt - receiptSha256 = $intentOnlyReceiptSha256 - }) - Assert-Throws { - Fail-WaggleSigningSession ` - $intentOnlySession $null 'intent-only-failure' 'tampered recovery candidate' - } 'intent|candidate' 'intent-only recovery rejects a changed terminal candidate' - Assert-Equal ` - (Test-Path -LiteralPath (Join-Path $intentOnlyDirectory 'failure-receipt.json')) ` - $false ` - 'intent-only candidate mismatch does not publish a receipt' - $intentOnlyOpenLedger = Get-Content -Raw -LiteralPath $intentOnlyLedgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-Equal $intentOnlyOpenLedger.state 'open' 'intent-only candidate mismatch leaves ledger open' - $intentOnlyRecoveredReceiptPath = Fail-WaggleSigningSession ` - $intentOnlySession $null 'intent-only-failure' ` - 'recover the receipt from the durable terminal intent' - $intentOnlyRecoveredLedger = Get-Content -Raw -LiteralPath $intentOnlyLedgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-Equal $intentOnlyRecoveredLedger.state 'failed' 'intent-only retry terminalizes the ledger' - Assert-Equal ` - $intentOnlyRecoveredLedger.terminalAtUtc $intentOnlyTerminalAt ` - 'intent-only retry reuses the durable terminal timestamp' - Assert-Equal ` - (Get-Sha256 $intentOnlyRecoveredReceiptPath) $intentOnlyReceiptSha256 ` - 'intent-only retry publishes the exact intent-bound receipt bytes' - - $concurrencyRoot = New-PrivateDirectory ` - (Join-Path $sessionFixtureRoot 'concurrent-reservation') - $concurrencyLedgerPath = Join-Path $concurrencyRoot 'callback-ledger.json' - $concurrencySessionPath = Join-Path $concurrencyRoot 'session.json' - $concurrencySession = [pscustomobject]@{ - Id = '22222222222222222222222222222222' - ManifestSha256 = '2' * 64 - Manifest = [pscustomobject]@{ slots = @($lifecycleSlots) } - TempRoot = $lifecycleTemp - SessionDirectory = $concurrencyRoot - LedgerPath = $concurrencyLedgerPath - ManifestPath = Join-Path $concurrencyRoot 'manifest.json' - Context = [pscustomobject]@{ SourceRevision = 'a' * 40 } - } - Write-JsonNoBom $concurrencyLedgerPath ` - (New-PendingLedger ` - $concurrencySession.Id $concurrencySession.ManifestSha256 @($lifecycleSlots)) - Write-JsonNoBom $concurrencySessionPath $concurrencySession - $reservationChildPath = Join-Path $concurrencyRoot 'reserve-child.ps1' - $reservationChildSource = @' -param( - [string]$WrapperPath, [string]$SessionPath, [string]$CallbackArtifactPath, - [string]$ReadyPath, [string]$GoPath, [string]$ResultPath -) -$ErrorActionPreference = 'Stop' -. $WrapperPath -ArtifactPath 'C:\unused.exe' -$session = Get-Content -Raw -LiteralPath $SessionPath | - ConvertFrom-Json -Depth 32 -DateKind String -[IO.File]::WriteAllText($ReadyPath, 'ready') -while (-not [IO.File]::Exists($GoPath)) { Start-Sleep -Milliseconds 10 } -try { - $reservation = Reserve-WaggleSigningCallback $session $CallbackArtifactPath - [IO.File]::WriteAllText($ResultPath, "reserved:$($reservation.reservationId)") -} catch { - [IO.File]::WriteAllText($ResultPath, "error:$($_.Exception.Message)") -} -'@ - [IO.File]::WriteAllText( - $reservationChildPath, $reservationChildSource, [Text.UTF8Encoding]::new($false) - ) - $reservationGoPath = Join-Path $concurrencyRoot 'go' - $reservationReadyPaths = @( - (Join-Path $concurrencyRoot 'ready-1'), - (Join-Path $concurrencyRoot 'ready-2') - ) - $reservationResultPaths = @( - (Join-Path $concurrencyRoot 'result-1'), - (Join-Path $concurrencyRoot 'result-2') - ) - $reservationProcesses = @() - for ($index = 0; $index -lt 2; $index++) { - $reservationProcesses += Start-SynchronizedChild ` - -PowerShellPath $approvedPowerShell -ScriptPath $reservationChildPath ` - -Arguments @{ - WrapperPath = $wrapperPath - SessionPath = $concurrencySessionPath - CallbackArtifactPath = [string]$lifecycleSlots[0].path - ReadyPath = $reservationReadyPaths[$index] - GoPath = $reservationGoPath - ResultPath = $reservationResultPaths[$index] - } - } - Wait-ForChildBarriers $reservationReadyPaths 'reservation race' - [IO.File]::WriteAllText($reservationGoPath, 'go') - foreach ($process in $reservationProcesses) { - if (-not $process.WaitForExit(30000)) { - $process.Kill() - throw 'Timed out waiting for the duplicate reservation race.' - } - Assert-Equal $process.ExitCode 0 'reservation race child exit code' - } - $reservationResults = @($reservationResultPaths | ForEach-Object { - [IO.File]::ReadAllText($_) - }) - Assert-Equal ` - @($reservationResults | Where-Object { $_ -cmatch '^reserved:[0-9a-f]{32}$' }).Count ` - 1 ` - "concurrent duplicate reservation has exactly one winner [$($reservationResults -join ' | ')]" - Assert-Equal ` - @($reservationResults | Where-Object { - $_ -cmatch '^error:.*(already consumed|state must be|reservation)' - }).Count ` - 1 ` - 'concurrent duplicate reservation has exactly one rejected loser' - $concurrencyLedger = Get-Content -Raw -LiteralPath $concurrencyLedgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-WaggleSigningLedgerState $concurrencySession $concurrencyLedger - Assert-Equal $concurrencyLedger.entries[0].status 'reserved' 'reservation race persists one reservation' - Assert-Equal $concurrencyLedger.entries[0].attempts 1 'reservation race consumes one attempt' - - $terminalRoot = New-PrivateDirectory ` - (Join-Path $sessionFixtureRoot 'concurrent-terminal') - $terminalLedgerPath = Join-Path $terminalRoot 'callback-ledger.json' - $terminalSessionPath = Join-Path $terminalRoot 'session.json' - $terminalSession = [pscustomobject]@{ - Id = '33333333333333333333333333333333' - ManifestSha256 = '3' * 64 - Manifest = [pscustomobject]@{ slots = @($completeSlots) } - TempRoot = $completeTemp - SessionDirectory = $terminalRoot - LedgerPath = $terminalLedgerPath - ManifestPath = Join-Path $terminalRoot 'manifest.json' - Context = [pscustomobject]@{ SourceRevision = 'b' * 40 } - } - $terminalLedger = $loadedCompleteLedger | ConvertTo-Json -Depth 32 | - ConvertFrom-Json -Depth 32 -DateKind String - $terminalLedger.sessionId = $terminalSession.Id - $terminalLedger.manifestSha256 = $terminalSession.ManifestSha256 - $terminalLedger.state = 'open' - $terminalLedger.terminalAtUtc = $null - $terminalLedger.terminalReceiptSha256 = $null - Write-JsonNoBom $terminalLedgerPath $terminalLedger - Write-JsonNoBom $terminalSessionPath $terminalSession - $terminalChildPath = Join-Path $terminalRoot 'terminal-child.ps1' - $terminalChildSource = @' -param( - [string]$WrapperPath, [string]$SessionPath, [string]$State, - [string]$ReadyPath, [string]$GoPath, [string]$ResultPath -) -$ErrorActionPreference = 'Stop' -. $WrapperPath -ArtifactPath 'C:\unused.exe' -$session = Get-Content -Raw -LiteralPath $SessionPath | - ConvertFrom-Json -Depth 32 -DateKind String -[IO.File]::WriteAllText($ReadyPath, 'ready') -while (-not [IO.File]::Exists($GoPath)) { Start-Sleep -Milliseconds 10 } -$receipt = [pscustomobject][ordered]@{ - schemaVersion = 1 - status = $State - sessionId = $session.Id - sourceRevision = $session.Context.SourceRevision - manifestSha256 = $session.ManifestSha256 - terminalAtUtc = [DateTimeOffset]::UtcNow.ToString('O') - failureCode = if ($State -ceq 'failed') { 'race-fixture' } else { $null } - failureMessage = if ($State -ceq 'failed') { 'race fixture failure' } else { $null } - failedSlotId = $null - rollbackOutcome = if ($State -ceq 'failed') { 'not-required' } else { $null } - manifestPath = if ($State -ceq 'sealed') { $session.ManifestPath } else { $null } - callbackLedgerPath = if ($State -ceq 'sealed') { $session.LedgerPath } else { $null } - installerPath = if ($State -ceq 'sealed') { [string]$session.Manifest.slots[13].path } else { $null } - installerSha256 = if ($State -ceq 'sealed') { 'A' * 64 } else { $null } - signerSubject = if ($State -ceq 'sealed') { 'CN=Race Fixture' } else { $null } - payloadManifestSha256 = if ($State -ceq 'sealed') { 'B' * 64 } else { $null } - artifactBindings = if ($State -ceq 'sealed') { @( - [pscustomobject]@{ kind = 'fixture'; sha256 = 'C' * 64 }, - [pscustomobject]@{ kind = 'fixture'; sha256 = 'D' * 64 } - ) } else { $null } -} -try { - $path = Set-WaggleSigningTerminalState ` - -Session $session -State $State -Receipt $receipt ` - -LedgerMutation { param($ledger) } - [IO.File]::WriteAllText($ResultPath, "terminal:${State}:$path") -} catch { - [IO.File]::WriteAllText($ResultPath, "error:$($_.Exception.Message)") -} -'@ - [IO.File]::WriteAllText( - $terminalChildPath, $terminalChildSource, [Text.UTF8Encoding]::new($false) - ) - $terminalGoPath = Join-Path $terminalRoot 'go' - $terminalReadyPaths = @( - (Join-Path $terminalRoot 'ready-failed'), - (Join-Path $terminalRoot 'ready-sealed') - ) - $terminalResultPaths = @( - (Join-Path $terminalRoot 'result-failed'), - (Join-Path $terminalRoot 'result-sealed') - ) - $terminalStates = @('failed', 'sealed') - $terminalProcesses = @() - for ($index = 0; $index -lt 2; $index++) { - $terminalProcesses += Start-SynchronizedChild ` - -PowerShellPath $approvedPowerShell -ScriptPath $terminalChildPath ` - -Arguments @{ - WrapperPath = $wrapperPath - SessionPath = $terminalSessionPath - State = $terminalStates[$index] - ReadyPath = $terminalReadyPaths[$index] - GoPath = $terminalGoPath - ResultPath = $terminalResultPaths[$index] - } - } - Wait-ForChildBarriers $terminalReadyPaths 'terminal fail-vs-seal race' - [IO.File]::WriteAllText($terminalGoPath, 'go') - foreach ($process in $terminalProcesses) { - if (-not $process.WaitForExit(30000)) { - $process.Kill() - throw 'Timed out waiting for the terminal fail-vs-seal race.' - } - Assert-Equal $process.ExitCode 0 'terminal race child exit code' - } - $terminalResults = @($terminalResultPaths | ForEach-Object { - [IO.File]::ReadAllText($_) - }) - Assert-Equal ` - @($terminalResults | Where-Object { $_ -cmatch '^terminal:(failed|sealed):' }).Count ` - 1 ` - 'terminal fail-vs-seal race has exactly one winner' - Assert-Equal ` - @($terminalResults | Where-Object { - $_ -cmatch '^error:.*(terminal|opposite|different)' - }).Count ` - 1 ` - 'terminal fail-vs-seal race has exactly one rejected loser' - $terminalReceiptPaths = @( - (Join-Path $terminalRoot 'failure-receipt.json'), - (Join-Path $terminalRoot 'provenance-receipt.json') - ) - $publishedTerminalReceipts = @($terminalReceiptPaths | Where-Object { - Test-Path -LiteralPath $_ -PathType Leaf - }) - Assert-Equal $publishedTerminalReceipts.Count 1 'terminal race publishes one receipt' - $terminalLedgerAfterRace = Get-Content -Raw -LiteralPath $terminalLedgerPath | - ConvertFrom-Json -Depth 32 -DateKind String - Assert-WaggleSigningLedgerState $terminalSession $terminalLedgerAfterRace - $expectedTerminalState = if ( - [IO.Path]::GetFileName($publishedTerminalReceipts[0]) -ceq 'failure-receipt.json' - ) { 'failed' } else { 'sealed' } - Assert-Equal ` - $terminalLedgerAfterRace.state $expectedTerminalState ` - 'terminal race ledger matches its sole receipt' - Assert-Equal ` - $terminalLedgerAfterRace.terminalReceiptSha256 ` - (Get-Sha256 $publishedTerminalReceipts[0]) ` - 'terminal race ledger binds its sole receipt digest' -} finally { - foreach ($name in $environmentNames) { - [Environment]::SetEnvironmentVariable($name, $savedEnvironment[$name]) - } - if (Test-Path -LiteralPath $sessionFixtureRoot) { - [IO.Directory]::Delete($sessionFixtureRoot, $true) - } -} - -Write-Host "Artifact Signing policy tests passed: $passed" diff --git a/app/scripts/sign-windows-pilot.ps1 b/app/scripts/sign-windows-pilot.ps1 deleted file mode 100644 index c1057c4..0000000 --- a/app/scripts/sign-windows-pilot.ps1 +++ /dev/null @@ -1,202 +0,0 @@ -<# -.SYNOPSIS - Self-sign cert generation + signtool wrapper for the Wave-1 Egzakta-internal pilot build. - -.DESCRIPTION - Implements docs/code-signing-pilot-and-launch.md §1.1 (Windows self-sign). - Two modes: - - -Mode Setup Generate self-signed cert (idempotent — reuses existing cert - by subject if it exists), export to .pfx, write thumbprint - to app/src-tauri/.thumbprint.txt. - -Mode Sign Sign the artefact at -ArtifactPath using the cert produced - by Setup. Wraps signtool.exe. - - Password resolution order (Setup): env WAGGLE_PILOT_PFX_PASSWORD; otherwise - Read-Host -AsSecureString prompt. Setup writes the .pfx to %USERPROFILE% - so it never lands inside the repo working tree. - - NOT for public Day-0 signing — that uses a real EV Authenticode cert per §2. - -.PARAMETER Mode - Setup or Sign. Setup is idempotent — safe to re-run. - -.PARAMETER ArtifactPath - Required when -Mode Sign. Path to the .msi or .exe to sign. - -.PARAMETER Subject - Cert subject. Default: "CN=Egzakta Internal Pilot, O=Egzakta Group, C=RS". - Override only if rotating cert identity. - -.PARAMETER PfxPath - Where to write the exported .pfx. Default: - $env:USERPROFILE\waggle-pilot-codesign.pfx - -.PARAMETER ThumbprintFile - Where to write the captured thumbprint for downstream consumption by - apply-signing-config.mjs. Default: app/src-tauri/.thumbprint.txt - (relative to repo root, resolved via this script's location). - -.PARAMETER TimestampUrl - RFC3161 timestamp server. Default: http://timestamp.digicert.com. - -.EXAMPLE - PS> $env:WAGGLE_PILOT_PFX_PASSWORD = "your-strong-pw" - PS> .\sign-windows-pilot.ps1 -Mode Setup - Generates cert (or reuses existing), writes thumbprint to .thumbprint.txt. - -.EXAMPLE - PS> .\sign-windows-pilot.ps1 -Mode Sign -ArtifactPath .\target\release\bundle\msi\Waggle_0.2.0_x64_en-US.msi - Signs the MSI using the cert from Setup. - -.NOTES - Last updated: LAUNCH-06 (Phase 2 Step 4). -#> - -[CmdletBinding()] -param( - [Parameter(Mandatory = $true)] - [ValidateSet('Setup', 'Sign')] - [string]$Mode, - - [Parameter()] - [string]$ArtifactPath, - - [Parameter()] - [string]$Subject = 'CN=Egzakta Internal Pilot, O=Egzakta Group, C=RS', - - [Parameter()] - [string]$PfxPath = (Join-Path $env:USERPROFILE 'waggle-pilot-codesign.pfx'), - - [Parameter()] - [string]$ThumbprintFile, - - [Parameter()] - [string]$TimestampUrl = 'http://timestamp.digicert.com' -) - -$ErrorActionPreference = 'Stop' - -# ─── Resolve repo-root paths ──────────────────────────────────────────────── - -$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path -$AppDir = Split-Path -Parent $ScriptDir # ...\waggle-os\app -$RepoRoot = Split-Path -Parent $AppDir # ...\waggle-os - -if (-not $ThumbprintFile) { - $ThumbprintFile = Join-Path $AppDir 'src-tauri\.thumbprint.txt' -} - -# ─── Helpers ──────────────────────────────────────────────────────────────── - -function Resolve-Password { - if ($env:WAGGLE_PILOT_PFX_PASSWORD) { - return ConvertTo-SecureString -String $env:WAGGLE_PILOT_PFX_PASSWORD -Force -AsPlainText - } - Write-Host 'WAGGLE_PILOT_PFX_PASSWORD not set in env — prompting.' -ForegroundColor Yellow - return Read-Host -Prompt 'Enter password to protect the .pfx export' -AsSecureString -} - -function Find-Signtool { - # Prefer signtool from latest installed Windows SDK; fall back to PATH. - $candidates = @( - 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.22621.0\x64\signtool.exe', - 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.22000.0\x64\signtool.exe', - 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.19041.0\x64\signtool.exe' - ) - foreach ($candidate in $candidates) { - if (Test-Path $candidate) { return $candidate } - } - $fromPath = Get-Command signtool.exe -ErrorAction SilentlyContinue - if ($fromPath) { return $fromPath.Source } - throw 'signtool.exe not found. Install Windows 10 SDK or add signtool to PATH.' -} - -# ─── Mode: Setup ──────────────────────────────────────────────────────────── - -if ($Mode -eq 'Setup') { - Write-Host "[setup] subject: $Subject" - Write-Host "[setup] pfx path: $PfxPath" - Write-Host "[setup] thumbprint out: $ThumbprintFile" - - # Reuse existing cert by subject if present (idempotency). - $existing = Get-ChildItem 'Cert:\CurrentUser\My' | - Where-Object { $_.Subject -eq $Subject -and $_.HasPrivateKey } | - Sort-Object NotAfter -Descending | - Select-Object -First 1 - - if ($existing -and $existing.NotAfter -gt (Get-Date)) { - Write-Host "[setup] reusing existing cert (NotAfter $($existing.NotAfter))" -ForegroundColor Green - $cert = $existing - } else { - Write-Host '[setup] generating new self-signed code-signing cert' -ForegroundColor Cyan - $cert = New-SelfSignedCertificate ` - -Type CodeSigningCert ` - -Subject $Subject ` - -KeyUsage DigitalSignature ` - -KeySpec Signature ` - -KeyAlgorithm RSA -KeyLength 2048 ` - -NotAfter (Get-Date).AddYears(2) ` - -CertStoreLocation 'Cert:\CurrentUser\My' ` - -TextExtension @('2.5.29.37={text}1.3.6.1.5.5.7.3.3', '2.5.29.19={text}') - } - - # Export .pfx (always — re-export is harmless and refreshes the file). - $pwd = Resolve-Password - Export-PfxCertificate -Cert $cert -FilePath $PfxPath -Password $pwd | Out-Null - Write-Host "[setup] exported .pfx -> $PfxPath" -ForegroundColor Green - - # Write thumbprint where apply-signing-config.mjs expects it. - $thumbprintDir = Split-Path -Parent $ThumbprintFile - if (-not (Test-Path $thumbprintDir)) { - New-Item -ItemType Directory -Force -Path $thumbprintDir | Out-Null - } - Set-Content -Path $ThumbprintFile -Value $cert.Thumbprint -Encoding ascii -NoNewline - Write-Host "[setup] thumbprint -> $ThumbprintFile" -ForegroundColor Green - Write-Host '' - Write-Host 'Next:' -ForegroundColor Cyan - Write-Host ' 1. npm run tauri:build:win:pilot-signed' - Write-Host ' 2. .\scripts\sign-windows-pilot.ps1 -Mode Sign -ArtifactPath # optional' - return -} - -# ─── Mode: Sign ───────────────────────────────────────────────────────────── - -if ($Mode -eq 'Sign') { - if (-not $ArtifactPath) { - throw '-ArtifactPath required when -Mode Sign' - } - if (-not (Test-Path $ArtifactPath)) { - throw "Artifact not found: $ArtifactPath" - } - if (-not (Test-Path $PfxPath)) { - throw "PFX not found at $PfxPath. Run -Mode Setup first." - } - - $signtool = Find-Signtool - $pwd = Resolve-Password - $plainPwd = [System.Net.NetworkCredential]::new('', $pwd).Password - - Write-Host "[sign] signtool: $signtool" - Write-Host "[sign] artifact: $ArtifactPath" - - & $signtool sign ` - /f $PfxPath ` - /p $plainPwd ` - /tr $TimestampUrl ` - /td sha256 /fd sha256 ` - $ArtifactPath - - if ($LASTEXITCODE -ne 0) { - throw "signtool failed with exit code $LASTEXITCODE" - } - - Write-Host '[sign] verifying signature' -ForegroundColor Cyan - & $signtool verify /pa /v $ArtifactPath - if ($LASTEXITCODE -ne 0) { - throw "signtool verify failed with exit code $LASTEXITCODE" - } - - Write-Host '[sign] OK' -ForegroundColor Green - return -} diff --git a/app/scripts/signing-config.test.ts b/app/scripts/signing-config.test.ts deleted file mode 100644 index e01369f..0000000 --- a/app/scripts/signing-config.test.ts +++ /dev/null @@ -1,346 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { spawnSync } from 'node:child_process'; -import { dirname, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { - parseThumbprintString, - addWindowsArtifactSigningToOverride, - addWindowsSigningToOverride, - addMacosAdhocToOverride, - type TauriOverrideConfig, -} from './signing-config.js'; - -// ─── parseThumbprintString ────────────────────────────────────────────────── - -describe('parseThumbprintString', () => { - it('returns the uppercased thumbprint when given valid 40-hex input', () => { - const raw = 'abcdef0123456789abcdef0123456789abcdef01'; - expect(parseThumbprintString(raw)).toBe( - 'ABCDEF0123456789ABCDEF0123456789ABCDEF01', - ); - }); - - it('strips surrounding whitespace and trailing newline (PowerShell output shape)', () => { - const raw = ' ABCDEF0123456789ABCDEF0123456789ABCDEF01\r\n'; - expect(parseThumbprintString(raw)).toBe( - 'ABCDEF0123456789ABCDEF0123456789ABCDEF01', - ); - }); - - it('removes embedded whitespace inside the thumbprint (some clipboards introduce spaces)', () => { - const raw = 'AB CD EF 01 23 45 67 89 AB CD EF 01 23 45 67 89 AB CD EF 01'; - expect(parseThumbprintString(raw)).toBe( - 'ABCDEF0123456789ABCDEF0123456789ABCDEF01', - ); - }); - - it('throws when the thumbprint is shorter than 40 chars', () => { - expect(() => parseThumbprintString('ABCDEF')).toThrow( - /must be 40 hex characters/i, - ); - }); - - it('throws when the thumbprint contains non-hex characters', () => { - const raw = 'ZZCDEF0123456789ABCDEF0123456789ABCDEF01'; - expect(() => parseThumbprintString(raw)).toThrow(/must be 40 hex characters/i); - }); - - it('throws on empty input', () => { - expect(() => parseThumbprintString('')).toThrow(/empty/i); - expect(() => parseThumbprintString(' ')).toThrow(/empty/i); - }); -}); - -// ─── addWindowsSigningToOverride ──────────────────────────────────────────── - -describe('addWindowsSigningToOverride', () => { - const VALID_THUMBPRINT = 'ABCDEF0123456789ABCDEF0123456789ABCDEF01'; - - it('writes certificateThumbprint + sensible defaults when no options given', () => { - const input: TauriOverrideConfig = { build: { beforeBuildCommand: '' } }; - const out = addWindowsSigningToOverride(input, VALID_THUMBPRINT); - - expect(out.bundle?.windows?.certificateThumbprint).toBe(VALID_THUMBPRINT); - expect(out.bundle?.windows?.digestAlgorithm).toBe('sha256'); - expect(out.bundle?.windows?.timestampUrl).toBe( - 'http://timestamp.digicert.com', - ); - }); - - it('preserves existing top-level fields (build, app, etc.)', () => { - const input: TauriOverrideConfig = { - build: { beforeBuildCommand: 'echo hello' }, - app: { security: { csp: 'default-src self' } }, - }; - const out = addWindowsSigningToOverride(input, VALID_THUMBPRINT); - - expect(out.build).toEqual({ beforeBuildCommand: 'echo hello' }); - expect(out.app).toEqual({ security: { csp: 'default-src self' } }); - }); - - it('preserves existing bundle.windows fields not related to signing', () => { - const input: TauriOverrideConfig = { - bundle: { - windows: { nsis: { installMode: 'currentUser' } }, - }, - }; - const out = addWindowsSigningToOverride(input, VALID_THUMBPRINT); - - expect(out.bundle?.windows?.nsis).toEqual({ installMode: 'currentUser' }); - expect(out.bundle?.windows?.certificateThumbprint).toBe(VALID_THUMBPRINT); - }); - - it('removes an Azure signCommand when returning to certificate-store signing', () => { - const azure: TauriOverrideConfig = addWindowsArtifactSigningToOverride( - { - bundle: { - windows: { nsis: { installMode: 'currentUser' } }, - }, - }, - String.raw`D:\a\waggle-os\app\scripts\sign-windows-artifact.ps1`, - ); - - const out = addWindowsSigningToOverride(azure, VALID_THUMBPRINT); - - expect(out.bundle?.windows?.signCommand).toBeUndefined(); - expect(out.bundle?.windows?.certificateThumbprint).toBe(VALID_THUMBPRINT); - expect(out.bundle?.windows?.nsis).toEqual({ installMode: 'currentUser' }); - }); - - it('overrides custom digestAlgorithm and timestampUrl when options provided', () => { - const out = addWindowsSigningToOverride({}, VALID_THUMBPRINT, { - digestAlgorithm: 'sha384', - timestampUrl: 'http://timestamp.sectigo.com', - }); - - expect(out.bundle?.windows?.digestAlgorithm).toBe('sha384'); - expect(out.bundle?.windows?.timestampUrl).toBe( - 'http://timestamp.sectigo.com', - ); - }); - - it('does not mutate the input config (immutability invariant)', () => { - const input: TauriOverrideConfig = { build: { beforeBuildCommand: '' } }; - const inputSnapshot = JSON.parse(JSON.stringify(input)); - addWindowsSigningToOverride(input, VALID_THUMBPRINT); - expect(input).toEqual(inputSnapshot); - }); - - it('is idempotent — applying twice with the same thumbprint yields equal output', () => { - const input: TauriOverrideConfig = {}; - const once = addWindowsSigningToOverride(input, VALID_THUMBPRINT); - const twice = addWindowsSigningToOverride(once, VALID_THUMBPRINT); - expect(twice).toEqual(once); - }); - - it('replaces an old thumbprint when called with a new one (cert rotation)', () => { - const input: TauriOverrideConfig = {}; - const v1 = addWindowsSigningToOverride(input, VALID_THUMBPRINT); - const newThumb = '1234567890ABCDEF1234567890ABCDEF12345678'; - const v2 = addWindowsSigningToOverride(v1, newThumb); - expect(v2.bundle?.windows?.certificateThumbprint).toBe(newThumb); - }); - - it('rejects an invalid thumbprint up front', () => { - expect(() => - addWindowsSigningToOverride({}, 'too-short'), - ).toThrow(/must be 40 hex characters/i); - }); -}); - -// ─── addWindowsArtifactSigningToOverride ─────────────────────────────────── - -describe('addWindowsArtifactSigningToOverride', () => { - const WRAPPER_PATH = String.raw`D:\a\waggle-os\app\scripts\sign-windows-artifact.ps1`; - const SYSTEM_POWERSHELL_PATH = - String.raw`C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`; - - it('configures an object-form Tauri signCommand with one artifact placeholder', () => { - const out = addWindowsArtifactSigningToOverride( - {}, - WRAPPER_PATH, - ); - - expect(out.bundle?.windows?.signCommand).toEqual({ - cmd: SYSTEM_POWERSHELL_PATH, - args: [ - '-NoLogo', - '-NoProfile', - '-NonInteractive', - '-ExecutionPolicy', - 'Bypass', - '-File', - WRAPPER_PATH, - '-ArtifactPath', - '%1', - ], - }); - }); - - it('removes mutually exclusive certificate-store signing fields', () => { - const input: TauriOverrideConfig = { - bundle: { - windows: { - certificateThumbprint: 'AB'.repeat(20), - digestAlgorithm: 'sha256', - timestampUrl: 'http://timestamp.digicert.com', - tsp: true, - nsis: { installMode: 'currentUser' }, - }, - }, - }; - - const out = addWindowsArtifactSigningToOverride( - input, - WRAPPER_PATH, - ); - expect(out.bundle?.windows?.certificateThumbprint).toBeUndefined(); - expect(out.bundle?.windows?.digestAlgorithm).toBeUndefined(); - expect(out.bundle?.windows?.timestampUrl).toBeUndefined(); - expect(out.bundle?.windows?.tsp).toBeUndefined(); - expect(out.bundle?.windows?.nsis).toEqual({ installMode: 'currentUser' }); - }); - - it('is immutable and idempotent', () => { - const input: TauriOverrideConfig = { - build: { - beforeBuildCommand: 'npm run build', - beforeBundleCommand: 'node mutate-bundle.mjs', - }, - bundle: { - active: false, - targets: ['msi'], - windows: { nsis: { installMode: 'currentUser' } }, - }, - }; - const snapshot = JSON.parse(JSON.stringify(input)); - const once = addWindowsArtifactSigningToOverride( - input, - WRAPPER_PATH, - ); - const twice = addWindowsArtifactSigningToOverride( - once, - WRAPPER_PATH, - ); - - expect(input).toEqual(snapshot); - expect(twice).toEqual(once); - expect(once.build).toEqual({ - beforeBuildCommand: '', - beforeBundleCommand: '', - }); - expect(once.bundle?.active).toBe(true); - expect(once.bundle?.targets).toEqual(['nsis']); - expect(once.bundle?.windows?.nsis).toEqual({ installMode: 'currentUser' }); - }); - - it('rejects non-absolute, placeholder-bearing, or control-character wrapper paths', () => { - expect(() => - addWindowsArtifactSigningToOverride( - {}, - 'scripts/sign.ps1', - ), - ).toThrow(/absolute Windows path/i); - expect(() => - addWindowsArtifactSigningToOverride( - {}, - String.raw`D:\a\%1\sign-windows-artifact.ps1`, - ), - ).toThrow(/placeholder/i); - expect(() => - addWindowsArtifactSigningToOverride( - {}, - 'D:\\safe\nmalicious.ps1', - ), - ).toThrow(/control characters/i); - expect(() => - addWindowsArtifactSigningToOverride( - {}, - String.raw`D:\safe\..\malicious.ps1`, - ), - ).toThrow(/canonical local Windows/i); - expect(() => - addWindowsArtifactSigningToOverride( - {}, - String.raw`D:\safe\sign.ps1:payload`, - ), - ).toThrow(/canonical local Windows/i); - }); - - it('contains exactly one artifact placeholder across the complete command', () => { - const out = addWindowsArtifactSigningToOverride({}, WRAPPER_PATH); - const command = out.bundle?.windows?.signCommand; - const placeholderCount = [command?.cmd, ...(command?.args ?? [])] - .flatMap((part) => part?.match(/%1/g) ?? []) - .length; - expect(placeholderCount).toBe(1); - }); -}); - -describe('apply-signing-config Artifact Signing boundary', () => { - it('fails closed toward the protected hosted release workflow, never local Build mode', () => { - const scriptDir = dirname(fileURLToPath(import.meta.url)); - const result = spawnSync( - process.execPath, - [resolve(scriptDir, 'apply-signing-config.mjs')], - { - cwd: resolve(scriptDir, '..'), - env: { ...process.env, WAGGLE_WINDOWS_SIGNING_MODE: 'artifact-signing' }, - encoding: 'utf8', - }, - ); - const output = `${result.stdout}\n${result.stderr}`; - expect(result.status).not.toBe(0); - expect(output).toMatch(/protected GitHub-hosted release workflow/i); - expect(output).not.toMatch(/-Mode Build/i); - }); -}); - -// ─── addMacosAdhocToOverride ──────────────────────────────────────────────── - -describe('addMacosAdhocToOverride', () => { - it('sets bundle.macOS.signingIdentity to "-" (ad-hoc sign sentinel)', () => { - const out = addMacosAdhocToOverride({}); - expect(out.bundle?.macOS?.signingIdentity).toBe('-'); - }); - - it('preserves existing top-level and bundle fields', () => { - const input: TauriOverrideConfig = { - build: { beforeBuildCommand: 'echo' }, - bundle: { - windows: { certificateThumbprint: 'AB'.repeat(20) }, - }, - }; - const out = addMacosAdhocToOverride(input); - - expect(out.build).toEqual({ beforeBuildCommand: 'echo' }); - expect(out.bundle?.windows?.certificateThumbprint).toBe('AB'.repeat(20)); - expect(out.bundle?.macOS?.signingIdentity).toBe('-'); - }); - - it('does not mutate the input config', () => { - const input: TauriOverrideConfig = { bundle: { macOS: {} } }; - const snapshot = JSON.parse(JSON.stringify(input)); - addMacosAdhocToOverride(input); - expect(input).toEqual(snapshot); - }); - - it('is idempotent', () => { - const once = addMacosAdhocToOverride({}); - const twice = addMacosAdhocToOverride(once); - expect(twice).toEqual(once); - }); - - it('preserves additional macOS fields (entitlements, providerShortName)', () => { - const input: TauriOverrideConfig = { - bundle: { - macOS: { entitlements: './ent.plist', providerShortName: 'TEAM' }, - }, - }; - const out = addMacosAdhocToOverride(input); - - expect(out.bundle?.macOS?.entitlements).toBe('./ent.plist'); - expect(out.bundle?.macOS?.providerShortName).toBe('TEAM'); - expect(out.bundle?.macOS?.signingIdentity).toBe('-'); - }); -}); diff --git a/app/scripts/signing-config.ts b/app/scripts/signing-config.ts deleted file mode 100644 index 011d148..0000000 --- a/app/scripts/signing-config.ts +++ /dev/null @@ -1,257 +0,0 @@ -/** - * signing-config.ts — Pure utilities for managing code-signing fields in - * Tauri's `tauri.build-override.conf.json`. - * - * Used by: - * - `apply-signing-config.mjs` (LAUNCH-06 pilot wiring) - * - `tauri:sign:pilot:win:apply` npm script - * - * No filesystem side effects — safe to import in tests. The thin CLI wrapper - * does the file I/O. - * - * Reference: docs/code-signing-pilot-and-launch.md §1.1 (Windows self-sign) - * docs/code-signing-pilot-and-launch.md §1.2 (macOS ad-hoc) - */ - -// ─── Types ────────────────────────────────────────────────────────────────── - -export interface TauriBundleWindows { - certificateThumbprint?: string; - digestAlgorithm?: string; - signCommand?: TauriSignCommand; - timestampUrl?: string; - tsp?: boolean; - [key: string]: unknown; -} - -export interface TauriSignCommand { - cmd: string; - args: string[]; -} - -export interface TauriBundleMacOS { - signingIdentity?: string; - [key: string]: unknown; -} - -export interface TauriBundle { - windows?: TauriBundleWindows; - macOS?: TauriBundleMacOS; - [key: string]: unknown; -} - -export interface TauriOverrideConfig { - build?: Record; - bundle?: TauriBundle; - [key: string]: unknown; -} - -export interface WindowsSigningOptions { - digestAlgorithm?: string; - timestampUrl?: string; -} - -// ─── Defaults ─────────────────────────────────────────────────────────────── - -const DEFAULT_DIGEST_ALGORITHM = 'sha256'; -const DEFAULT_TIMESTAMP_URL = 'http://timestamp.digicert.com'; -const MACOS_ADHOC_IDENTITY = '-'; -const THUMBPRINT_LENGTH = 40; -const HEX_PATTERN = /^[0-9A-F]+$/; -const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/; -const WINDOWS_POWERSHELL_PATH = - String.raw`C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`; - -function containsControlCharacter(value: string): boolean { - return [...value].some((character) => { - const codePoint = character.codePointAt(0) ?? 0; - return codePoint <= 31 || codePoint === 127; - }); -} - -function assertCanonicalWindowsFilePath(value: string): void { - if (containsControlCharacter(value)) { - throw new Error('Artifact Signing wrapper path contains control characters.'); - } - if (!WINDOWS_ABSOLUTE_PATH_PATTERN.test(value)) { - throw new Error('Artifact Signing wrapper must use an absolute Windows path.'); - } - const pathTail = value.slice(3); - const segments = pathTail.split(/[\\/]/); - if ( - pathTail.length === 0 - || value.slice(2).includes(':') - || segments.some( - (segment) => segment.length === 0 - || segment === '.' - || segment === '..' - || /[. ]$/.test(segment), - ) - ) { - throw new Error('Artifact Signing wrapper must use a canonical local Windows file path.'); - } -} - -// ─── parseThumbprintString ────────────────────────────────────────────────── - -/** - * Normalise a raw thumbprint string into the canonical 40-char uppercase form. - * - * Accepts whitespace anywhere (tab, space, newline) since PowerShell's - * `$cert.Thumbprint` plus clipboard round-tripping can introduce arbitrary - * spacing. Throws when the result is not exactly 40 hex characters. - */ -export function parseThumbprintString(raw: string): string { - if (!raw || raw.trim().length === 0) { - throw new Error('Thumbprint is empty — cert generation may have failed.'); - } - - const compact = raw.replace(/\s+/g, '').toUpperCase(); - - if (compact.length !== THUMBPRINT_LENGTH || !HEX_PATTERN.test(compact)) { - throw new Error( - `Thumbprint must be 40 hex characters; got ${compact.length} chars (sample: "${compact.slice(0, 16)}...").`, - ); - } - - return compact; -} - -// ─── addWindowsSigningToOverride ──────────────────────────────────────────── - -/** - * Return a new override config with Windows code-signing fields applied. - * - * Preserves all existing top-level and bundle fields; replaces only the - * signing-specific keys under `bundle.windows`. Idempotent — calling - * twice with the same thumbprint yields an equal result. - */ -export function addWindowsSigningToOverride( - config: Readonly, - thumbprint: string, - options?: WindowsSigningOptions, -): T { - const normalisedThumbprint = parseThumbprintString(thumbprint); - const digestAlgorithm = options?.digestAlgorithm ?? DEFAULT_DIGEST_ALGORITHM; - const timestampUrl = options?.timestampUrl ?? DEFAULT_TIMESTAMP_URL; - - const existingBundle: TauriBundle = config.bundle ?? {}; - const existingWindows: TauriBundleWindows = existingBundle.windows ?? {}; - const nonCustomCommandWindows: TauriBundleWindows = { ...existingWindows }; - delete nonCustomCommandWindows.signCommand; - - const nextWindows: TauriBundleWindows = { - ...nonCustomCommandWindows, - certificateThumbprint: normalisedThumbprint, - digestAlgorithm, - timestampUrl, - }; - - const nextBundle: TauriBundle = { - ...existingBundle, - windows: nextWindows, - }; - - return { - ...config, - bundle: nextBundle, - }; -} - -// ─── addWindowsArtifactSigningToOverride ─────────────────────────────────── - -/** - * Return a new override config that delegates every Tauri Windows signing - * target to the fail-closed Azure Artifact Signing wrapper. - * - * Tauri replaces `%1` with each binary path. Object form keeps the absolute - * wrapper path intact when the checkout contains spaces. Certificate-store - * fields are removed because Tauri must not combine them with `signCommand`. - */ -export function addWindowsArtifactSigningToOverride< - T extends TauriOverrideConfig, ->(config: Readonly, wrapperPath: string): T { - assertCanonicalWindowsFilePath(wrapperPath); - if (wrapperPath.includes('%1')) { - throw new Error('Artifact Signing wrapper path cannot contain the %1 placeholder.'); - } - const existingBuild = config.build ?? {}; - const existingBundle: TauriBundle = config.bundle ?? {}; - const existingWindows: TauriBundleWindows = existingBundle.windows ?? {}; - const nonSigningWindows: TauriBundleWindows = { ...existingWindows }; - delete nonSigningWindows.certificateThumbprint; - delete nonSigningWindows.digestAlgorithm; - delete nonSigningWindows.timestampUrl; - delete nonSigningWindows.tsp; - - const nextWindows: TauriBundleWindows = { - ...nonSigningWindows, - signCommand: { - cmd: WINDOWS_POWERSHELL_PATH, - args: [ - '-NoLogo', - '-NoProfile', - '-NonInteractive', - '-ExecutionPolicy', - 'Bypass', - '-File', - wrapperPath, - '-ArtifactPath', - '%1', - ], - }, - }; - const placeholderCount = [ - nextWindows.signCommand?.cmd, - ...(nextWindows.signCommand?.args ?? []), - ].flatMap((part) => part?.match(/%1/g) ?? []).length; - if (placeholderCount !== 1) { - throw new Error('Artifact Signing command must contain exactly one %1 placeholder.'); - } - - return { - ...config, - build: { - ...existingBuild, - beforeBuildCommand: '', - beforeBundleCommand: '', - }, - bundle: { - ...existingBundle, - active: true, - targets: ['nsis'], - windows: nextWindows, - }, - }; -} - -// ─── addMacosAdhocToOverride ──────────────────────────────────────────────── - -/** - * Return a new override config with macOS ad-hoc signing applied. - * - * Sets `bundle.macOS.signingIdentity` to "-" (Tauri / codesign sentinel for - * ad-hoc sign). Preserves all other fields. Used during pilot before a real - * Apple Developer ID cert is procured. - */ -export function addMacosAdhocToOverride( - config: Readonly, -): T { - const existingBundle: TauriBundle = config.bundle ?? {}; - const existingMacOS: TauriBundleMacOS = existingBundle.macOS ?? {}; - - const nextMacOS: TauriBundleMacOS = { - ...existingMacOS, - signingIdentity: MACOS_ADHOC_IDENTITY, - }; - - const nextBundle: TauriBundle = { - ...existingBundle, - macOS: nextMacOS, - }; - - return { - ...config, - bundle: nextBundle, - }; -} diff --git a/app/src-tauri/src/lib.rs b/app/src-tauri/src/lib.rs index 5489384..29dd040 100644 --- a/app/src-tauri/src/lib.rs +++ b/app/src-tauri/src/lib.rs @@ -55,9 +55,8 @@ pub fn run() { commands::onboarding::reset_first_launch, ]) .setup(|app| { - // Create the configured window here so the Windows certifier can - // opt into a loopback-only WebView CDP port without shipping - // remote debugging enabled for normal launches. + // The main window is configured with `create: false` and built + // here, before the tray, the shortcut and the sidecar start. let main_window_config = app .config() .app @@ -71,35 +70,7 @@ pub fn run() { "configured main window is missing", ) })?; - let mut main_window = tauri::WebviewWindowBuilder::from_config( - app.handle(), - &main_window_config, - )?; - #[cfg(windows)] - if let Some(raw_port) = std::env::var_os("WAGGLE_CERTIFIER_WEBVIEW_DEBUG_PORT") { - let raw_port = raw_port.to_string_lossy(); - let port = raw_port.parse::().map_err(|_| { - std::io::Error::new( - std::io::ErrorKind::InvalidInput, - "WAGGLE_CERTIFIER_WEBVIEW_DEBUG_PORT must be an integer", - ) - })?; - if port < 1024 { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - "WAGGLE_CERTIFIER_WEBVIEW_DEBUG_PORT must be >= 1024", - ) - .into()); - } - let browser_args = format!( - "--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --remote-debugging-port={port}" - ); - main_window = main_window.additional_browser_args(&browser_args); - eprintln!( - "[waggle] WebView certifier debug endpoint enabled on 127.0.0.1:{port}" - ); - } - main_window.build()?; + tauri::WebviewWindowBuilder::from_config(app.handle(), &main_window_config)?.build()?; tray::setup_tray(app.handle())?; diff --git a/app/src-tauri/tauri.build-override.conf.json b/app/src-tauri/tauri.build-override.conf.json deleted file mode 100644 index b0d025d..0000000 --- a/app/src-tauri/tauri.build-override.conf.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "build": { - "beforeBuildCommand": "" - }, - "bundle": { - "macOS": { - "signingIdentity": "-" - } - } -} diff --git a/app/tests/auto-update.test.ts b/app/tests/auto-update.test.ts index 2e1d8dd..de21f08 100644 --- a/app/tests/auto-update.test.ts +++ b/app/tests/auto-update.test.ts @@ -8,8 +8,9 @@ * * Release flow: * git tag v1.0.1 && git push --tags - * This triggers release.yml which builds + signs + publishes to GitHub Releases. - * Tauri updater fetches latest.json from the release assets. + * This triggers release.yml, which builds and smoke-tests unsigned installers + * for Windows, macOS and Linux and creates a draft GitHub release. There is + * no update manifest while the updater is disabled. */ import { describe, it, expect } from 'vitest'; @@ -101,6 +102,10 @@ describe('auto-update configuration', () => { expect(workflow).toContain('x86_64-apple-darwin'); }); + it('builds for Linux', () => { + expect(workflow).toContain('x86_64-unknown-linux-gnu'); + }); + it('uses the app-lockfile-pinned Tauri CLI for builds', () => { expect(workflow).toContain('node node_modules/@tauri-apps/cli/tauri.js build'); expect(workflow).not.toMatch(/^\s*uses:\s+tauri-apps\/tauri-action/m); diff --git a/docs/oss/build-windows.md b/docs/oss/build-windows.md index 69728f1..f74a25c 100644 --- a/docs/oss/build-windows.md +++ b/docs/oss/build-windows.md @@ -5,8 +5,10 @@ branch. The build has to run on Windows: the packaging scripts take the bundled runtime and the native modules (better-sqlite3, onnxruntime) from the machine they run on, so a build made on macOS would ship macOS binaries. -The community edition has not been built on Windows yet. The first build is part of the -week 3 acceptance; record what fails in `docs/oss/upstream-fixes.md` or `docs/oss/baseline.md`. +The release workflow (`.github/workflows/release.yml`) runs the same build on GitHub's +`windows-latest` runner for every `v*` tag and for pull requests that touch the desktop app. +It has not run yet; the first build is part of the week 3 acceptance. Record what fails in +`docs/oss/upstream-fixes.md` or `docs/oss/baseline.md`. ## 1. Prepare the machine @@ -74,8 +76,8 @@ copies the native modules, builds the web UI and then the Tauri shell. The first the Rust shell from scratch and takes much longer than later runs. `--bundles nsis` builds only the NSIS installer, the one the app is configured for (a -per-user install without administrator rights); CI builds the same. Without the flag Tauri -also builds an MSI, for which it downloads WiX. +per-user install without administrator rights). Without the flag Tauri also builds an MSI, +for which it downloads WiX; the release workflow builds both (`--bundles nsis,msi`). The installer: @@ -83,6 +85,27 @@ The installer: app\src-tauri\target\x86_64-pc-windows-msvc\release\bundle\nsis\Waggle_0.2.0_x64-setup.exe ``` +The same staged files make the server archive that the installer tool +(`packages/launcher`) installs. To build it and run the release workflow's smoke tests: + +```powershell +cd C:\w\waggle-os +npm run build --workspace @waggle-ai/waggle +node scripts/build-server-archive.mjs +node scripts/release-smoke.mjs installer +``` + +The archive is `artifacts\waggle-server--windows-x64.tar.gz`. The installer test +installs it into a temporary folder, runs `doctor`, starts the server on a free port and +uninstalls it. + +After installing the app (section 4), the desktop test starts it, waits until its sidecar +answers on port 3333, then stops both. Close Waggle first so the port is free: + +```powershell +node scripts/release-smoke.mjs desktop --app "$env:LOCALAPPDATA\Waggle\waggle.exe" +``` + ## 4. Check the result 1. Run the installer. It is not signed, so SmartScreen shows "Windows protected your PC": diff --git a/packages/server/tests/tauri-config.test.ts b/packages/server/tests/tauri-config.test.ts index 6937f8b..51031ae 100644 --- a/packages/server/tests/tauri-config.test.ts +++ b/packages/server/tests/tauri-config.test.ts @@ -7,7 +7,6 @@ import { beforeEach, describe, it, expect } from 'vitest'; import fs from 'node:fs'; import { createHash } from 'node:crypto'; -import http from 'node:http'; import os from 'node:os'; import path from 'node:path'; import { execFile, spawnSync } from 'node:child_process'; @@ -227,9 +226,10 @@ describe('Tauri Production Configuration', () => { expect(win.minHeight).toBe(600); expect(win.resizable).toBe(true); + // The shipped app never opens a WebView debugging port. const lib = fs.readFileSync(path.join(TAURI_DIR, 'src', 'lib.rs'), 'utf-8'); - expect(lib).toContain('WAGGLE_CERTIFIER_WEBVIEW_DEBUG_PORT'); - expect(lib).toContain('additional_browser_args'); + expect(lib).toContain('WebviewWindowBuilder::from_config'); + expect(lib).not.toContain('remote-debugging-port'); }); it('tauri.conf.json has the auto-updater intentionally disabled for v1', () => { @@ -249,12 +249,6 @@ describe('Tauri Production Configuration', () => { const tray = fs.readFileSync(path.join(TAURI_DIR, 'src', 'tray.rs'), 'utf-8'); expect(tray).toContain('TrayIconBuilder::new()'); expect(tray).toContain('.menu(&menu)'); - - const certifier = fs.readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf-8', - ); - expect(certifier).toContain('status --porcelain=v1 --untracked-files=all'); }); it('tray menu exposes only implemented desktop actions', () => { @@ -278,30 +272,12 @@ describe('Tauri Production Configuration', () => { it('packaged Windows sidecar stays hidden and writes bounded diagnostics', () => { const service = fs.readFileSync(path.join(TAURI_DIR, 'src', 'service.rs'), 'utf-8'); - const certifier = fs.readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf-8', - ); expect(service).toContain('const CREATE_NO_WINDOW: u32 = 0x08000000'); expect(service).toContain('command.creation_flags(CREATE_NO_WINDOW)'); expect(service).toContain('service.log'); expect(service).toContain('MAX_SERVICE_LOG_BYTES'); expect(service).toContain('rotate_service_log'); - expect(certifier).toContain('function Assert-NoVisibleConsoleDescendant'); - const consoleCheck = certifier.slice( - certifier.indexOf('function Assert-NoVisibleConsoleDescendant'), - certifier.indexOf('function Wait-ForInstalledRuntimeStop'), - ); - expect(consoleCheck).not.toHaveLength(0); - expect(consoleCheck).toContain('MainWindowHandle'); - expect(consoleCheck).toContain('[IntPtr]::Zero'); - expect(consoleCheck).toContain('[WaggleInstallerWindowProbe]::IsWindowVisible'); - expect(consoleCheck).toMatch( - /catch \{[\s\S]*Get-Process -Id \$consoleProcessId[\s\S]*throw/, - ); - expect(certifier).toContain("$receipt.checks['firstBootHiddenService']"); - expect(certifier).toContain("$receipt.checks['repairHiddenService']"); }); it('preserves detached user sessions while IPC-supervising owned service runtimes', () => { @@ -363,48 +339,6 @@ describe('Tauri Production Configuration', () => { expect(csp).not.toContain('https://fonts.googleapis.com'); }); - it('installer certification fails closed on a blank desktop WebView', () => { - const helperPath = path.join(ROOT, 'scripts', 'read-tauri-bootstrap-token.mjs'); - const result = spawnSync(process.execPath, [helperPath, '--self-test'], { - cwd: ROOT, - encoding: 'utf-8', - timeout: 30_000, - windowsHide: true, - }); - expect(result.status, result.stderr || result.stdout).toBe(0); - expect(JSON.parse(result.stdout)).toEqual({ pass: true, cases: 9 }); - - const certifier = fs.readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf-8', - ); - expect(certifier).toContain("$tokenPayload.PSObject.Properties['uiReady']"); - expect(certifier).toContain('Installed Waggle WebView did not render its application shell.'); - expect(certifier).toContain("$receipt.checks['firstBootUi']"); - expect(certifier).toContain("$receipt.checks['repairUi']"); - }); - - it('keeps candidate-only desktop gates compatible with the protected previous release', () => { - const helper = fs.readFileSync( - path.join(ROOT, 'scripts', 'read-tauri-bootstrap-token.mjs'), - 'utf-8', - ); - const certifier = fs.readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf-8', - ); - const previousReleaseBlock = certifier.slice( - certifier.indexOf('$previousProcess = Start-InstalledApp'), - certifier.indexOf('$previousTier = Invoke-JsonRequest'), - ); - - expect(helper).toContain("argument === '--allow-legacy-ui'"); - expect(certifier).toContain('[switch]$AllowLegacyUi'); - expect(previousReleaseBlock).toContain('-AllowLegacyUi'); - expect(previousReleaseBlock).not.toContain('Assert-NoVisibleConsoleDescendant'); - expect(previousReleaseBlock).not.toContain("$receipt.checks['previousHiddenService']"); - }); - it('Cargo.toml has no updater plugin while the updater is disabled', () => { const cargo = fs.readFileSync(path.join(TAURI_DIR, 'Cargo.toml'), 'utf-8'); expect(cargo).not.toContain('tauri-plugin-updater'); @@ -456,33 +390,6 @@ describe('Tauri Production Configuration', () => { expect(nsis).not.toMatch(/\bExec\s+['"]/); }); - it('pilot-signed Windows build consumes the generated Tauri override', () => { - const manifest = JSON.parse( - fs.readFileSync(path.join(ROOT, 'app', 'package.json'), 'utf-8'), - ); - const signedBuild = manifest.scripts?.['tauri:build:win:pilot-signed']; - const windowsBuild = manifest.scripts?.['tauri:build:win']; - const override = JSON.parse( - fs.readFileSync( - path.join(TAURI_DIR, 'tauri.build-override.conf.json'), - 'utf-8', - ), - ); - - expect(signedBuild).toContain('npm run tauri:sign:pilot:win:apply'); - expect(signedBuild).toContain( - 'npm run tauri:build:win -- --config src-tauri/tauri.build-override.conf.json', - ); - expect(override.build.beforeBuildCommand).toBe(''); - - const stageIndex = windowsBuild.indexOf('stage-sidecar-deps.mjs'); - const preflightIndex = windowsBuild.indexOf('check-sidecar-resources.mjs'); - const tauriIndex = windowsBuild.indexOf('npx tauri build'); - expect(stageIndex).toBeGreaterThanOrEqual(0); - expect(preflightIndex).toBeGreaterThan(stageIndex); - expect(tauriIndex).toBeGreaterThan(preflightIndex); - }); - it('icon.ico exists', () => { expect(fs.existsSync(path.join(TAURI_DIR, 'icons', 'icon.ico'))).toBe(true); }); @@ -719,28 +626,12 @@ describe('Tauri Production Configuration', () => { expect(script).toContain('Hardened bundled npm with ip-address'); expect(script).not.toContain('process.versions.node;'); - for (const workflowPath of [ - '.github/workflows/release.yml', - '.github/workflows/tauri-build-pr.yml', - ]) { - const workflow = fs.readFileSync(path.join(ROOT, workflowPath), 'utf-8'); - expect(workflow.match(/node-version: 22\.23\.2/g), workflowPath).toHaveLength(2); - expect(workflow, workflowPath).not.toMatch(/node-version: 20(?:\s|$)/); - const runtimeSteps = [...workflow.matchAll(/run: node scripts\/bundle-node\.mjs/g)]; - const sidecarSteps = [...workflow.matchAll(/run: node scripts\/build-sidecar\.mjs/g)]; - const nativeSteps = [...workflow.matchAll(/run: node scripts\/bundle-native-deps\.mjs/g)]; - expect(runtimeSteps, workflowPath).toHaveLength(2); - expect(sidecarSteps, workflowPath).toHaveLength(2); - expect(nativeSteps, workflowPath).toHaveLength(2); - for (let index = 0; index < runtimeSteps.length; index++) { - expect(runtimeSteps[index].index, `${workflowPath} job ${index + 1}`).toBeLessThan( - sidecarSteps[index].index, - ); - expect(runtimeSteps[index].index, `${workflowPath} job ${index + 1}`).toBeLessThan( - nativeSteps[index].index, - ); - } - } + const workflow = fs.readFileSync( + path.join(ROOT, '.github', 'workflows', 'release.yml'), + 'utf-8', + ); + expect(workflow.match(/node-version: 22\.23\.2/g)).toHaveLength(1); + expect(workflow).not.toMatch(/node-version: 20(?:\s|$)/); }); it('desktop builds verify the selected Node ABI before staging native resources', () => { @@ -753,6 +644,7 @@ describe('Tauri Production Configuration', () => { 'tauri:build:win', 'tauri:build:mac:arm64', 'tauri:build:mac:x64', + 'tauri:build:linux', ]) { const command = manifest.scripts?.[scriptName] ?? ''; expect(command.indexOf('bundle-node.mjs'), scriptName).toBeGreaterThanOrEqual(0); @@ -1986,95 +1878,6 @@ describe('CI/CD Configuration', () => { expect(run).not.toMatch(/--fileParallelism(?:=|\s+)false\b/); }); - it('keeps Intel macOS PR verification app-only while retaining DMG release coverage', () => { - type MacJob = { - strategy?: { - matrix?: { - include?: Array<{ - target?: string; - arch?: string; - runner?: string; - bundles?: string; - artifact_path?: string; - }>; - }; - }; - steps?: Array<{ - name?: string; - run?: string; - with?: { path?: string; 'if-no-files-found'?: string }; - }>; - }; - const prWorkflow = parseYaml( - fs.readFileSync(path.join(ROOT, '.github', 'workflows', 'tauri-build-pr.yml'), 'utf-8'), - ) as { jobs?: { 'verify-macos'?: MacJob } }; - const prJob = prWorkflow.jobs?.['verify-macos']; - const matrix = prJob?.strategy?.matrix?.include ?? []; - expect(matrix).toEqual([ - { - target: 'aarch64-apple-darwin', - arch: 'arm64', - runner: 'macos-15', - bundles: 'dmg', - artifact_path: 'app/src-tauri/target/aarch64-apple-darwin/release/bundle/dmg/*.dmg', - }, - { - target: 'x86_64-apple-darwin', - arch: 'x64', - runner: 'macos-15-intel', - bundles: 'app', - artifact_path: 'app/src-tauri/target/x86_64-apple-darwin/release/bundle/macos/*.app', - }, - ]); - const prBuild = prJob?.steps?.find( - (step) => step.name === 'Build Tauri (macOS ${{ matrix.target }})', - ); - expect(prBuild?.run).toBe( - 'cd app && node node_modules/@tauri-apps/cli/tauri.js build --target ${{ matrix.target }} --bundles ${{ matrix.bundles }}', - ); - const prUpload = prJob?.steps?.find((step) => step.name === 'Upload macOS artifacts'); - expect(prUpload?.with?.path).toBe('${{ matrix.artifact_path }}'); - expect(prUpload?.with?.['if-no-files-found']).toBe('error'); - - const releaseWorkflow = parseYaml( - fs.readFileSync(path.join(ROOT, '.github', 'workflows', 'release.yml'), 'utf-8'), - ) as { jobs?: { 'build-macos'?: MacJob } }; - const releaseJob = releaseWorkflow.jobs?.['build-macos']; - const releaseMatrix = releaseJob?.strategy?.matrix?.include ?? []; - expect(releaseMatrix).toEqual([ - { - target: 'aarch64-apple-darwin', - arch: 'arm64', - runner: 'macos-15', - }, - { - target: 'x86_64-apple-darwin', - arch: 'x64', - runner: 'macos-15-intel', - }, - ]); - const releaseBuild = releaseJob?.steps?.find( - (step) => step.name === 'Build Tauri (macOS)', - ); - expect(releaseBuild?.run).toBe( - 'cd app && node node_modules/@tauri-apps/cli/tauri.js build --target ${{ matrix.target }}', - ); - const releaseDmgUpload = releaseJob?.steps?.find( - (step) => step.name === 'Upload macOS DMG verification artifact', - ); - expect(releaseDmgUpload?.with?.path).toBe( - 'app/src-tauri/target/${{ matrix.target }}/release/bundle/dmg/*.dmg', - ); - expect(releaseDmgUpload?.with?.['if-no-files-found']).toBe('error'); - const releaseAppUpload = releaseJob?.steps?.find( - (step) => step.name === 'Upload macOS app verification artifact', - ); - expect(releaseAppUpload?.with?.path).toBe( - 'app/src-tauri/target/${{ matrix.target }}/release/bundle/macos/*.app', - ); - expect(releaseAppUpload?.with?.['if-no-files-found']).toBe('error'); - }); - it('clean-checkout CI resolves vendored PPTX and uses the locked dependency graph', () => { const rootPackage = JSON.parse( fs.readFileSync(path.join(ROOT, 'package.json'), 'utf-8'), @@ -2145,23 +1948,6 @@ describe('CI/CD Configuration', () => { expect(vaultTests).not.toContain("'--script'"); }); - it('release workflow exists for Windows + macOS builds', () => { - const workflow = path.join(ROOT, '.github', 'workflows', 'release.yml'); - expect(fs.existsSync(workflow)).toBe(true); - const content = fs.readFileSync(workflow, 'utf-8'); - expect(content).toContain('build-windows'); - expect(content).toContain('build-macos'); - expect(content).not.toMatch(/uses:\s+tauri-apps\/tauri-action/); - expect(content).toContain('Upload macOS DMG verification artifact'); - expect(content).toContain('Upload macOS app verification artifact'); - expect(content).toContain('aarch64-apple-darwin'); - expect(content).toContain('x86_64-apple-darwin'); - expect(content).toContain('runner: macos-15'); - expect(content).toContain('runner: macos-15-intel'); - expect(content).toContain('runs-on: ${{ matrix.runner }}'); - expect(content).toContain('TARGET_ARCH: ${{ matrix.arch }}'); - }); - it.runIf(process.platform === 'win32')( 'PowerShell 7 workflow override rejects Windows PowerShell 5.1', () => { @@ -2188,2958 +1974,6 @@ describe('CI/CD Configuration', () => { }, ); - it.runIf(process.platform === 'win32')( - 'release mode resolver permits only the exact v0.2.0 bootstrap identity', - () => { - const workflow = fs - .readFileSync(path.join(ROOT, '.github', 'workflows', 'release.yml'), 'utf-8') - .replace(/\r\n/g, '\n'); - const resolverStart = workflow.indexOf( - ' function Resolve-WindowsReleaseMode {', - ); - const resolverEnd = workflow.indexOf( - '\n $releaseMode = Resolve-WindowsReleaseMode', - resolverStart, - ); - expect(resolverStart).toBeGreaterThanOrEqual(0); - expect(resolverEnd).toBeGreaterThan(resolverStart); - - const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-release-mode-')); - const probePath = path.join(probeRoot, 'probe.ps1'); - const helperSource = workflow - .slice(resolverStart, resolverEnd) - .replace(/^ {10}/gm, ''); - const fixtureSource = String.raw` -function Expect-Mode { - param([scriptblock]$Action, [string]$ExpectedMode) - $actualMode = & $Action - if ($actualMode -ne $ExpectedMode) { - throw "Expected mode $ExpectedMode, got $actualMode" - } -} - -function Expect-Rejection { - param([scriptblock]$Action, [string]$Label) - $rejected = $false - try { - & $Action | Out-Null - } catch { - $rejected = $true - } - if (-not $rejected) { - throw "Expected release-mode rejection: $Label" - } -} - -$candidateSha = 'a' * 40 -$baseSha256 = 'B' * 64 -$baseCommit = 'c' * 40 - -Expect-Mode { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.0' -CandidateTag 'v0.2.0' -CandidateSha $candidateSha -BootstrapIdentity "v0.2.0@$candidateSha" -BaseTag '' -BaseAssetName '' -BaseSha256 '' -BaseCommit '' -} 'bootstrap' - -Expect-Mode { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.1' -CandidateTag 'v0.2.1' -CandidateSha $candidateSha -BootstrapIdentity '' -BaseTag 'v0.2.0' -BaseAssetName 'Waggle_0.2.0_x64-setup.exe' -BaseSha256 $baseSha256 -BaseCommit $baseCommit -} 'upgrade' - -Expect-Mode { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.2' -CandidateTag 'v0.2.2' -CandidateSha $candidateSha -BootstrapIdentity '' -BaseTag 'v0.2.1' -BaseAssetName 'Waggle_0.2.1_x64-setup.exe' -BaseSha256 $baseSha256 -BaseCommit $baseCommit -} 'upgrade' - -Expect-Rejection { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.0' -CandidateTag 'v0.2.0' -CandidateSha $candidateSha -BootstrapIdentity "v0.2.0@$baseCommit" -BaseTag '' -BaseAssetName '' -BaseSha256 '' -BaseCommit '' -} 'wrong bootstrap commit' - -Expect-Rejection { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.0' -CandidateTag 'v0.2.0' -CandidateSha $candidateSha -BootstrapIdentity "v0.2.0@$candidateSha" -BaseTag 'v0.1.9' -BaseAssetName '' -BaseSha256 '' -BaseCommit '' -} 'bootstrap with partial baseline' - -Expect-Rejection { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.1' -CandidateTag 'v0.2.1' -CandidateSha $candidateSha -BootstrapIdentity '' -BaseTag '' -BaseAssetName '' -BaseSha256 '' -BaseCommit '' -} 'later release without baseline' - -Expect-Rejection { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.1' -CandidateTag 'v0.2.1' -CandidateSha $candidateSha -BootstrapIdentity "v0.2.1@$candidateSha" -BaseTag 'v0.2.0' -BaseAssetName 'Waggle_0.2.0_x64-setup.exe' -BaseSha256 $baseSha256 -BaseCommit $baseCommit -} 'bootstrap authorization on later release' - -Expect-Rejection { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.1' -CandidateTag 'v0.2.1' -CandidateSha $candidateSha -BootstrapIdentity '' -BaseTag ' ' -BaseAssetName 'Waggle_0.2.0_x64-setup.exe' -BaseSha256 $baseSha256 -BaseCommit $baseCommit -} 'whitespace baseline' - -Expect-Rejection { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.1' -CandidateTag 'v0.2.2' -CandidateSha $candidateSha -BootstrapIdentity '' -BaseTag 'v0.2.0' -BaseAssetName 'Waggle_0.2.0_x64-setup.exe' -BaseSha256 $baseSha256 -BaseCommit $baseCommit -} 'candidate tag mismatch' - -Expect-Rejection { - Resolve-WindowsReleaseMode -CandidateVersion '0.2' -CandidateTag 'v0.2' -CandidateSha $candidateSha -BootstrapIdentity '' -BaseTag 'v0.2.0' -BaseAssetName 'Waggle_0.2.0_x64-setup.exe' -BaseSha256 $baseSha256 -BaseCommit $baseCommit -} 'malformed candidate version' - -Expect-Rejection { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.1' -CandidateTag 'v0.2.1' -CandidateSha ('A' * 40) -BootstrapIdentity '' -BaseTag 'v0.2.0' -BaseAssetName 'Waggle_0.2.0_x64-setup.exe' -BaseSha256 $baseSha256 -BaseCommit $baseCommit -} 'uppercase candidate commit' - -Expect-Rejection { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.1' -CandidateTag 'v0.2.1' -CandidateSha ('a' * 39) -BootstrapIdentity '' -BaseTag 'v0.2.0' -BaseAssetName 'Waggle_0.2.0_x64-setup.exe' -BaseSha256 $baseSha256 -BaseCommit $baseCommit -} 'short candidate commit' - -Expect-Rejection { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.1' -CandidateTag 'v0.2.1' -CandidateSha $candidateSha -BootstrapIdentity '' -BaseTag 'v0.2.0' -BaseAssetName 'Waggle_0.2.0_x64-setup.exe' -BaseSha256 $baseSha256 -BaseCommit '' -} 'upgrade with only three baseline inputs' - -Expect-Rejection { - Resolve-WindowsReleaseMode -CandidateVersion '0.1.9' -CandidateTag 'v0.1.9' -CandidateSha $candidateSha -BootstrapIdentity '' -BaseTag 'v0.1.8' -BaseAssetName 'Waggle_0.1.8_x64-setup.exe' -BaseSha256 $baseSha256 -BaseCommit $baseCommit -} 'release older than bootstrap' - -Expect-Rejection { - Resolve-WindowsReleaseMode -CandidateVersion '0.2.1' -CandidateTag 'v0.2.1' -CandidateSha $candidateSha -BootstrapIdentity '' -BaseTag 'v0.1.9' -BaseAssetName 'Waggle_0.1.9_x64-setup.exe' -BaseSha256 $baseSha256 -BaseCommit $baseCommit -} 'first upgrade without v0.2.0 baseline' -`; - - try { - fs.writeFileSync(probePath, `${helperSource}\n${fixtureSource}`, 'utf-8'); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath], - { encoding: 'utf-8', timeout: 30_000, windowsHide: true }, - ); - if (result.status !== 0) { - throw new Error( - `Release-mode probe failed: ${result.stderr || result.stdout}`, - ); - } - } finally { - fs.rmSync(probeRoot, { recursive: true, force: true }); - } - }, - ); - - it('release workflow isolates unsigned build, protected signing, and publication authority', () => { - const workflow = fs.readFileSync( - path.join(ROOT, '.github', 'workflows', 'release.yml'), - 'utf-8', - ).replace(/\r\n/g, '\n'); - const publisherPath = path.join(ROOT, 'scripts', 'publish-windows-release.ps1'); - expect(fs.existsSync(publisherPath)).toBe(true); - const publisher = fs.readFileSync(publisherPath, 'utf-8'); - const parsedWorkflow = parseYaml(workflow) as { - jobs?: Record< - string, - { - environment?: unknown; - if?: unknown; - steps?: Array<{ - name?: string; - uses?: string; - with?: Record; - if?: unknown; - 'continue-on-error'?: unknown; - }>; - } - >; - }; - const job = (name: string, nextName: string) => { - const marker = ` ${name}:`; - const nextMarker = `\n ${nextName}:`; - const start = workflow.indexOf(marker); - const end = workflow.indexOf(nextMarker, start); - expect(start).toBeGreaterThanOrEqual(0); - expect(workflow.lastIndexOf(marker)).toBe(start); - expect(end).toBeGreaterThan(start); - return workflow.slice(start, end); - }; - const step = (jobSource: string, name: string) => { - const marker = ` - name: ${name}`; - const start = jobSource.indexOf(marker); - expect(start).toBeGreaterThanOrEqual(0); - expect(jobSource.lastIndexOf(marker)).toBe(start); - const end = jobSource.indexOf('\n - name:', start + 1); - return jobSource.slice(start, end >= 0 ? end : undefined); - }; - const buildJob = job('build-windows-prebuilt', 'prepare-windows-signing'); - const preparationJob = job('prepare-windows-signing', 'sign-windows'); - const signingJob = job('sign-windows', 'certify-windows'); - const certificationJob = job('certify-windows', 'attest-windows'); - const attestationJob = job('attest-windows', 'publish-windows'); - const publicationJob = job('publish-windows', 'build-macos'); - const parsedSigningJob = parsedWorkflow.jobs?.['sign-windows']; - const parsedAttestationJob = parsedWorkflow.jobs?.['attest-windows']; - const parsedPublicationJob = parsedWorkflow.jobs?.['publish-windows']; - - expect(parsedSigningJob).toBeDefined(); - expect(parsedSigningJob).not.toHaveProperty('environment'); - expect(parsedPublicationJob?.if).toBe( - "vars.WINDOWS_PUBLIC_RELEASE_AUTHORIZED == 'true' && github.event.repository.private == false && startsWith(github.ref, 'refs/tags/v')", - ); - expect(workflow).toContain('WINDOWS_SIGNING_TRANSPORT_MAX_ITEMS: 60000'); - expect([ - ...workflow.matchAll( - /\$maxItems = \[int\]\$env:WINDOWS_SIGNING_TRANSPORT_MAX_ITEMS/g, - ), - ]).toHaveLength(2); - expect([...workflow.matchAll(/\$items\.Count -gt \$maxItems/g)]).toHaveLength(2); - expect(workflow).not.toMatch(/\bgit\s+(?:fetch|ls-remote)\b/); - expect(workflow).toContain( - '$baseCommit = (git rev-parse --verify "refs/tags/$baseTag^{}").Trim().ToLowerInvariant()', - ); - - expect(buildJob).toContain('permissions:\n contents: read'); - expect(buildJob).not.toMatch(/^ {4}environment:/m); - expect(buildJob).not.toContain('id-token: write'); - expect(buildJob).not.toContain('attestations: write'); - expect(buildJob).not.toContain('contents: write'); - expect(buildJob).not.toContain('azure/login@'); - expect(buildJob).not.toContain('GH_TOKEN:'); - - expect(preparationJob).toContain('needs: build-windows-prebuilt'); - expect(preparationJob).toContain('permissions:\n contents: read'); - expect(preparationJob).not.toContain('id-token: write'); - expect(preparationJob).not.toContain('azure/login@'); - expect(signingJob).toContain( - 'needs: [build-windows-prebuilt, prepare-windows-signing]', - ); - expect(signingJob).not.toMatch(/^ {4}environment:/m); - expect(signingJob).toContain('permissions:\n contents: read'); - expect(signingJob).not.toContain('attestations: write'); - expect(signingJob).toContain('id-token: write'); - expect(signingJob).not.toContain('contents: write'); - expect([...certificationJob.matchAll(/GH_TOKEN: \$\{\{ secrets\.GITHUB_TOKEN \}\}/g)]) - .toHaveLength(1); - - expect(certificationJob).toContain('needs: sign-windows'); - expect(certificationJob).not.toMatch(/^ {4}environment:/m); - expect(certificationJob).not.toContain('id-token: write'); - expect(certificationJob).not.toContain('azure/login@'); - expect(attestationJob).toContain('needs: certify-windows'); - expect(parsedAttestationJob?.if).toBe('github.event.repository.private == false'); - expect(parsedAttestationJob?.environment).toBe('production'); - expect(attestationJob).toContain('runs-on: ubuntu-latest'); - expect(attestationJob).toContain('attestations: write'); - expect(attestationJob).toContain('id-token: write'); - expect(attestationJob).not.toContain('azure/login@'); - - expect(publicationJob).toContain('needs: [certify-windows, attest-windows]'); - expect(publicationJob).toContain('permissions:\n contents: write'); - expect(publicationJob).not.toMatch(/^ {4}environment:/m); - expect(publicationJob).not.toContain('id-token: write'); - expect(publicationJob).not.toContain('attestations: write'); - expect(publicationJob).not.toContain('azure/login@'); - expect(publicationJob).not.toContain('sign-windows-artifact.ps1'); - expect(publicationJob).not.toContain('certify-windows-installer.ps1'); - - for (const forbidden of [ - 'WINDOWS_CODESIGN_PFX_BASE64', - 'WINDOWS_CODESIGN_PFX_PASSWORD', - 'Import-PfxCertificate', - 'Cert:\\', - 'WAGGLE_IMPORTED_CERT_THUMBPRINTS', - 'WINDOWS_CODESIGN_APPROVED_THUMBPRINT', - 'client-secret:', - 'creds:', - ]) { - expect(workflow).not.toContain(forbidden); - } - expect(signingJob).toContain( - 'azure/login@f5d393ae46f8fde4be8b75f32e3fc50e654ad0ca', - ); - expect(signingJob).toContain('client-id: ${{ vars.AZURE_CLIENT_ID }}'); - expect(signingJob).toContain('tenant-id: ${{ vars.AZURE_TENANT_ID }}'); - expect(signingJob).toContain('subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}'); - expect(signingJob).toContain('audience: api://AzureADTokenExchange'); - expect(workflow).not.toContain('[checked]'); - - const boundaryStep = step(signingJob, 'Validate exact hosted OIDC release boundary'); - expect(boundaryStep).toContain("$env:GITHUB_EVENT_NAME -cne 'push'"); - expect(boundaryStep).toContain("$env:GITHUB_REPOSITORY -cne 'marolinik/waggle-os'"); - expect(boundaryStep).toContain("$env:GITHUB_REF_TYPE -cne 'tag'"); - expect(boundaryStep).toContain('$env:GITHUB_REF -cne "refs/tags/v$version"'); - expect(boundaryStep).toContain('$env:GITHUB_REF_NAME -cne "v$version"'); - expect(boundaryStep).toContain( - '$env:GITHUB_WORKFLOW_REF -cne "marolinik/waggle-os/.github/workflows/release.yml@$env:GITHUB_REF"', - ); - expect(boundaryStep).toContain('$env:GITHUB_WORKFLOW_SHA -cne $env:GITHUB_SHA'); - - const refreshStep = step(signingJob, 'Refresh exact signing repository refs'); - expect(refreshStep).toContain( - 'actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5', - ); - expect(refreshStep).toContain('ref: ${{ github.ref }}'); - expect(refreshStep).toContain('fetch-depth: 0'); - expect(refreshStep).toContain('persist-credentials: false'); - expect(refreshStep).toContain('clean: false'); - - const parsedSigningSteps = parsedSigningJob?.steps ?? []; - const parsedRefreshIndex = parsedSigningSteps.findIndex( - ({ name }) => name === 'Refresh exact signing repository refs', - ); - const parsedRevalidationIndex = parsedSigningSteps.findIndex( - ({ name }) => name === 'Revalidate exact signing revision against fresh origin main', - ); - const parsedAzureIndex = parsedSigningSteps.findIndex( - ({ name }) => name === 'Authenticate Azure Artifact Signing with OIDC', - ); - expect(parsedRefreshIndex).toBeGreaterThanOrEqual(0); - expect(parsedRevalidationIndex).toBe(parsedRefreshIndex + 1); - expect(parsedAzureIndex).toBe(parsedRevalidationIndex + 1); - expect(parsedSigningSteps[parsedRefreshIndex]).toMatchObject({ - uses: 'actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5', - with: { - repository: 'marolinik/waggle-os', - ref: '${{ github.ref }}', - 'fetch-depth': 0, - 'persist-credentials': false, - clean: false, - }, - }); - expect(parsedSigningSteps[parsedAzureIndex]?.uses).toBe( - 'azure/login@f5d393ae46f8fde4be8b75f32e3fc50e654ad0ca', - ); - for (const index of [parsedRefreshIndex, parsedRevalidationIndex, parsedAzureIndex]) { - expect(parsedSigningSteps[index]).not.toHaveProperty('if'); - expect(parsedSigningSteps[index]).not.toHaveProperty('continue-on-error'); - } - - const revalidationStep = step( - signingJob, - 'Revalidate exact signing revision against fresh origin main', - ); - expect(revalidationStep).toContain( - 'git merge-base --is-ancestor $env:GITHUB_SHA refs/remotes/origin/main', - ); - expect(revalidationStep).toContain('$checkedOutRevision -cne $env:GITHUB_SHA'); - expect(revalidationStep).toContain('$env:GITHUB_WORKFLOW_SHA -cne $env:GITHUB_SHA'); - expect(signingJob.indexOf('Refresh exact signing repository refs')) - .toBeLessThan(signingJob.indexOf('Revalidate exact signing revision against fresh origin main')); - expect(signingJob.indexOf('Revalidate exact signing revision against fresh origin main')) - .toBeLessThan(signingJob.indexOf('Authenticate Azure Artifact Signing with OIDC')); - - expect(publicationJob).toContain( - "vars.WINDOWS_PUBLIC_RELEASE_AUTHORIZED == 'true'", - ); - expect(publicationJob).toContain('github.event.repository.private == false'); - - const capacityIndex = preparationJob.indexOf( - 'Validate capacity before duplicate handoff extraction', - ); - const setupNodeIndex = preparationJob.indexOf( - 'Setup Node.js for protected packaging', - ); - const rootDependenciesIndex = certificationJob.indexOf( - 'Install locked certification dependencies', - ); - const certificationSetupNodeIndex = certificationJob.indexOf( - 'Setup Node.js for source-bound certification', - ); - const appDependenciesIndex = preparationJob.indexOf( - 'Install locked Tauri packaging CLI', - ); - const certificationIndex = certificationJob.indexOf( - 'Certify Windows Solo installer lifecycle', - ); - expect(capacityIndex).toBeGreaterThanOrEqual(0); - expect(setupNodeIndex).toBeGreaterThan(capacityIndex); - expect(appDependenciesIndex).toBeGreaterThan(setupNodeIndex); - expect(certificationSetupNodeIndex).toBeGreaterThanOrEqual(0); - expect(rootDependenciesIndex).toBeGreaterThan(certificationSetupNodeIndex); - expect(rootDependenciesIndex).toBeGreaterThanOrEqual(0); - expect(certificationIndex).toBeGreaterThan(rootDependenciesIndex); - - const resolverStep = step(preparationJob, 'Resolve Windows release mode'); - expect(resolverStep).toContain('id: release-mode'); - expect(resolverStep).toContain( - '-CandidateVersion $candidateVersion `', - ); - expect(resolverStep).toContain('-CandidateTag $env:GITHUB_REF_NAME `'); - expect(resolverStep).toContain('-CandidateSha $env:GITHUB_SHA `'); - expect(resolverStep).toContain( - '"mode=$releaseMode" | Out-File -FilePath $env:GITHUB_OUTPUT', - ); - - const baselineStep = step(certificationJob, 'Download signed Windows upgrade baseline'); - expect(baselineStep).toContain( - "if: steps.verify-signed.outputs.release_mode == 'upgrade'", - ); - expect(baselineStep).toContain('GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}'); - - const certificateStep = step(certificationJob, 'Certify Windows Solo installer lifecycle'); - expect(certificateStep).toContain( - 'WAGGLE_RELEASE_MODE: ${{ steps.verify-signed.outputs.release_mode }}', - ); - expect(certificateStep).toContain( - "if ($env:WAGGLE_RELEASE_MODE -eq 'upgrade') {", - ); - expect(certificateStep).toContain( - 'Bootstrap certification unexpectedly produced an upgrade receipt', - ); - - const bootstrapAttestation = step(attestationJob, 'Attest bootstrap Windows artifacts'); - expect(bootstrapAttestation).toContain( - "if: needs.certify-windows.outputs.release_mode == 'bootstrap'", - ); - expect(bootstrapAttestation).toContain('windows-installer-certificate.json'); - expect(bootstrapAttestation).not.toContain( - 'windows-installer-upgrade-certificate.json', - ); - - const upgradeAttestation = step(attestationJob, 'Attest upgrade Windows artifacts'); - expect(upgradeAttestation).toContain( - "if: needs.certify-windows.outputs.release_mode == 'upgrade'", - ); - expect(upgradeAttestation).toContain('windows-installer-certificate.json'); - expect(upgradeAttestation).toContain( - 'windows-installer-upgrade-certificate.json', - ); - - const publishStep = step(publicationJob, 'Publish certified Windows release'); - expect(publishStep).toContain( - "if: success() && startsWith(github.ref, 'refs/tags/v')", - ); - expect(publishStep).toContain('GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}'); - expect(publishStep).toContain( - 'WINDOWS_CODESIGN_APPROVED_SUBJECT: ${{ needs.certify-windows.outputs.signer_subject }}', - ); - expect(publishStep).toContain( - 'WAGGLE_RELEASE_MODE: ${{ needs.certify-windows.outputs.release_mode }}', - ); - expect(publishStep).toContain( - 'WAGGLE_CERTIFIED_CANDIDATE_SHA256: ${{ needs.certify-windows.outputs.candidate_sha256 }}', - ); - expect(publishStep).toContain( - './scripts/publish-windows-release.ps1 -Mode $env:WAGGLE_RELEASE_MODE', - ); - expect(publishStep).not.toContain('gh release '); - - expect(publisher).toContain( - "[ValidateSet('bootstrap', 'upgrade')]", - ); - expect(publisher).toContain( - '$expectedBootstrapIdentity = "v0.2.0@$env:GITHUB_SHA"', - ); - expect(publisher).toContain( - 'Bootstrap publication is not bound to the exact authorized v0.2.0 release', - ); - expect(publisher).toContain( - 'Upgrade publication requires an empty bootstrap authorization and all baseline inputs', - ); - expect(publisher).toContain( - 'Bootstrap publication found an unexpected upgrade certificate', - ); - expect(publisher).toContain('$releaseAssets = @($installer, $cleanReceipt)'); - expect(publisher).toContain( - '$releaseAssets = @($installer, $cleanReceipt, $upgradeReceipt)', - ); - expect(publisher).toContain('Assert-PassingWindowsCertificateReceipt'); - expect(publisher).toContain('Assert-ExpectedAuthenticodeSignature'); - expect(publisher).toContain('Assert-RemoteTagCommit'); - expect(publisher).toContain('Refusing to use a pre-existing release'); - expect([ - ...publisher.matchAll( - /^\s*\$createdReleaseId\s*=/gm, - ), - ]).toHaveLength(0); - expect([...publisher.matchAll(/^function Set-ReadOnlyCreatedReleaseId \{/gm)]) - .toHaveLength(1); - expect([ - ...publisher.matchAll( - /^Set-ReadOnlyCreatedReleaseId \(\[string\]\$releaseData\.id\)\s*$/gm, - ), - ]).toHaveLength(1); - expect(publisher).not.toMatch(/Set-Variable[^\r\n]*-Force/); - expect(publisher).toContain( - 'Published release assets do not exactly match the certified artifact set', - ); - expect(publisher).toContain('[System.StringComparer]::Ordinal'); - expect(publisher).not.toContain('Compare-Object'); - expect([...publisher.matchAll(/^function Assert-ExactReleaseAssets \{/gm)]) - .toHaveLength(1); - expect([...publisher.matchAll(/^function Assert-ReleaseIdentity \{/gm)]) - .toHaveLength(1); - expect([...publisher.matchAll(/^function New-ReleaseAssetManifest \{/gm)]) - .toHaveLength(1); - expect([...publisher.matchAll(/^function Assert-RemoteReleaseAssetContents \{/gm)]) - .toHaveLength(1); - expect([ - ...publisher.matchAll( - /^function Assert-ReleaseAssetFileMatchesManifest \{/gm, - ), - ]).toHaveLength(1); - expect([ - ...publisher.matchAll( - /^function Assert-LocalReleaseAssetsUnchanged \{/gm, - ), - ]).toHaveLength(1); - expect([...publisher.matchAll(/^\s*gh release create \$tag\b/gm)]) - .toHaveLength(1); - expect([...publisher.matchAll(/^\s*gh release upload \$tag\b/gm)]) - .toHaveLength(1); - expect([ - ...publisher.matchAll( - /^\s*gh release edit \$tag --draft=false --prerelease=false\s*$/gm, - ), - ]).toHaveLength(1); - expect([ - ...publisher.matchAll( - /^\s*Assert-ExactReleaseAssets \$uploadedRelease \$releaseAssets\s*$/gm, - ), - ]).toHaveLength(1); - expect([ - ...publisher.matchAll( - /^\s*Assert-ExactReleaseAssets \$publishedRelease \$releaseAssets\s*$/gm, - ), - ]).toHaveLength(1); - expect([ - ...publisher.matchAll( - /^\s*Assert-RemoteReleaseAssetContents \$tag \$uploadedRelease \$releaseAssetManifest 'uploaded'\s*$/gm, - ), - ]).toHaveLength(1); - expect([ - ...publisher.matchAll( - /^\s*Assert-RemoteReleaseAssetContents \$tag \$publishedRelease \$releaseAssetManifest 'published'\s*$/gm, - ), - ]).toHaveLength(1); - const uploadIndex = publisher.indexOf('gh release upload $tag @releaseAssetPaths'); - const uploadedHashIndex = publisher.indexOf( - "Assert-RemoteReleaseAssetContents $tag $uploadedRelease $releaseAssetManifest 'uploaded'", - ); - const publishIndex = publisher.indexOf( - 'gh release edit $tag --draft=false --prerelease=false', - ); - const publishedHashIndex = publisher.indexOf( - "Assert-RemoteReleaseAssetContents $tag $publishedRelease $releaseAssetManifest 'published'", - ); - expect(uploadIndex).toBeGreaterThanOrEqual(0); - expect(uploadedHashIndex).toBeGreaterThan(uploadIndex); - expect(publishIndex).toBeGreaterThan(uploadedHashIndex); - expect(publishedHashIndex).toBeGreaterThan(publishIndex); - const tagBindingIndices = [ - ...publisher.matchAll( - /^Assert-PublicationTagBindings \$Mode \$tag \$sourceRevision\s*$/gm, - ), - ].map((match) => match.index); - expect(tagBindingIndices).toHaveLength(3); - expect(tagBindingIndices[0]).toBeLessThan( - publisher.indexOf('gh release create $tag'), - ); - expect(tagBindingIndices[1]).toBeGreaterThan( - publisher.indexOf('gh release create $tag'), - ); - expect(tagBindingIndices[1]).toBeLessThan(uploadIndex); - expect(tagBindingIndices[2]).toBeGreaterThan(uploadIndex); - expect(tagBindingIndices[2]).toBeLessThan(publishIndex); - const remoteHelperStart = publisher.indexOf( - 'function Assert-RemoteReleaseAssetContents {', - ); - const remoteHelperEnd = publisher.indexOf( - '\nfunction Assert-ManagedModelAndMemoryEvidence {', - remoteHelperStart, - ); - const remoteHelper = publisher.slice(remoteHelperStart, remoteHelperEnd); - expect([ - ...remoteHelper.matchAll( - /^\s*Assert-ReleaseAssetFileMatchesManifest `\s*$/gm, - ), - ]).toHaveLength(1); - const remoteDownloadIndex = remoteHelper.indexOf( - 'gh release download $Tag --dir $downloadRoot', - ); - const remoteCountIndex = remoteHelper.indexOf( - 'if ($downloadedFiles.Count -ne $Manifest.Count)', - ); - const remoteHashIndex = remoteHelper.indexOf( - 'Assert-ReleaseAssetFileMatchesManifest `', - ); - expect(remoteDownloadIndex).toBeGreaterThanOrEqual(0); - expect(remoteCountIndex).toBeGreaterThan(remoteDownloadIndex); - expect(remoteHashIndex).toBeGreaterThan(remoteCountIndex); - expect([ - ...publisher.matchAll( - /^Assert-ReleaseIdentity `\s*$/gm, - ), - ]).toHaveLength(3); - }); - - it('keeps Azure signing, candidate execution, GitHub attestation, and publication in separate jobs', () => { - const workflow = fs - .readFileSync(path.join(ROOT, '.github', 'workflows', 'release.yml'), 'utf-8') - .replace(/\r\n/g, '\n'); - const job = (name: string, nextName: string) => { - const start = workflow.indexOf(` ${name}:`); - const end = workflow.indexOf(`\n ${nextName}:`, start); - expect(start, name).toBeGreaterThanOrEqual(0); - expect(end, nextName).toBeGreaterThan(start); - return workflow.slice(start, end); - }; - const signingJob = job('sign-windows', 'certify-windows'); - const preparationJob = job('prepare-windows-signing', 'sign-windows'); - const certificationJob = job('certify-windows', 'attest-windows'); - const attestationJob = job('attest-windows', 'publish-windows'); - const publicationJob = job('publish-windows', 'build-macos'); - - expect(preparationJob).toContain('needs: build-windows-prebuilt'); - expect(signingJob).toContain( - 'needs: [build-windows-prebuilt, prepare-windows-signing]', - ); - expect(signingJob).not.toMatch(/^ {4}environment:/m); - expect(signingJob).toContain('id-token: write'); - expect(signingJob).toContain('azure/login@'); - expect(signingJob).toContain('Package and sign from immutable prepared inputs'); - expect(signingJob).not.toContain('certify-windows-installer.ps1'); - expect(signingJob).not.toContain('attest-build-provenance@'); - expect(signingJob).not.toContain('GH_TOKEN:'); - - expect(certificationJob).toContain('needs: sign-windows'); - expect(certificationJob).toContain('runs-on: windows-latest'); - expect(certificationJob).toContain('permissions:\n contents: read'); - expect(certificationJob).not.toMatch(/^ {4}environment:/m); - expect(certificationJob).not.toContain('id-token: write'); - expect(certificationJob).not.toContain('attestations: write'); - expect(certificationJob).not.toContain('azure/login@'); - expect(certificationJob).toContain('Validate exact signed handoff before candidate execution'); - expect(certificationJob).toContain('Certify Windows Solo installer lifecycle'); - expect(certificationJob.indexOf('Validate exact signed handoff before candidate execution')) - .toBeLessThan(certificationJob.indexOf('Certify Windows Solo installer lifecycle')); - - expect(attestationJob).toContain('needs: certify-windows'); - expect(attestationJob).toContain('if: github.event.repository.private == false'); - expect(attestationJob).toContain('runs-on: ubuntu-latest'); - expect(attestationJob).toContain('attestations: write'); - expect(attestationJob).toContain('id-token: write'); - expect(attestationJob).toContain('environment: production'); - expect(attestationJob).not.toContain('azure/login@'); - expect(attestationJob).not.toContain('certify-windows-installer.ps1'); - expect(attestationJob).not.toContain('Start-Process'); - expect(attestationJob).not.toContain('& $installer'); - - expect(publicationJob).toContain('needs: [certify-windows, attest-windows]'); - expect(publicationJob).not.toContain('id-token: write'); - expect(publicationJob).not.toContain('azure/login@'); - expect(workflow).toContain('artifact-ids: ${{ needs.build-windows-prebuilt.outputs.artifact_id }}'); - expect(workflow).toContain('artifact-ids: ${{ needs.prepare-windows-signing.outputs.artifact_id }}'); - expect(workflow).toContain('artifact-ids: ${{ needs.sign-windows.outputs.artifact_id }}'); - expect(workflow).toContain('artifact-ids: ${{ needs.certify-windows.outputs.artifact_id }}'); - expect(workflow).not.toMatch(/^\s+[a-z_]*path:\s*\$\{\{\s*steps\.[^\n]+outputs\.[^\n]+\}\}/m); - }); - - it('confines OIDC to a minimal receipt-bound Windows signing job', () => { - const workflow = parseYaml( - fs.readFileSync(path.join(ROOT, '.github', 'workflows', 'release.yml'), 'utf-8'), - ) as { - jobs?: Record< - string, - { - needs?: unknown; - permissions?: Record; - if?: unknown; - environment?: unknown; - outputs?: Record; - steps?: Array<{ - name?: string; - uses?: string; - id?: string; - env?: Record; - with?: Record; - run?: string; - if?: unknown; - 'continue-on-error'?: unknown; - }>; - } - >; - }; - const jobs = workflow.jobs ?? {}; - const preparationJob = jobs['prepare-windows-signing']; - const signingJob = jobs['sign-windows']; - - expect(preparationJob).toBeDefined(); - expect(preparationJob?.needs).toBe('build-windows-prebuilt'); - expect(preparationJob?.permissions).toEqual({ contents: 'read' }); - expect(preparationJob).not.toHaveProperty('environment'); - expect(JSON.stringify(preparationJob)).not.toContain('id-token'); - expect(JSON.stringify(preparationJob)).not.toContain('azure/login@'); - expect(JSON.stringify(preparationJob)).not.toContain('contents":"write'); - expect(preparationJob?.outputs).toMatchObject({ - preparation_receipt_sha256: '${{ steps.stage-prepared.outputs.receipt_sha256 }}', - preparation_size_bytes: '${{ steps.stage-prepared.outputs.size_bytes }}', - artifact_id: '${{ steps.upload-prepared.outputs.artifact-id }}', - artifact_digest: '${{ steps.upload-prepared.outputs.artifact-digest }}', - }); - - expect(signingJob?.needs).toEqual([ - 'build-windows-prebuilt', - 'prepare-windows-signing', - ]); - expect(signingJob?.permissions).toEqual({ contents: 'read', 'id-token': 'write' }); - expect(signingJob).not.toHaveProperty('environment'); - const signingSteps = signingJob?.steps ?? []; - expect(signingSteps.map(({ name, uses }) => name ?? uses)).toEqual([ - 'actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5', - 'Validate exact hosted OIDC release boundary', - 'Validate initial signing revision on fresh origin main', - 'Download immutable prepared Windows signing handoff', - 'Verify and restore immutable prepared Windows signing handoff', - 'Refresh exact signing repository refs', - 'Revalidate exact signing revision against fresh origin main', - 'Authenticate Azure Artifact Signing with OIDC', - 'Package and sign from immutable prepared inputs', - 'Stage exact signed handoff', - 'Upload immutable signed Windows handoff', - ]); - expect(JSON.stringify(signingJob)).not.toMatch( - /actions\/setup-node@|npm ci|Invoke-WebRequest|Invoke-RestMethod|Provision pinned|Resolve Windows release mode|Validate protected signer subject|Validate capacity before/, - ); - for (const step of signingSteps) { - expect(step).not.toHaveProperty('if'); - expect(step).not.toHaveProperty('continue-on-error'); - } - const signingRunBodies = signingSteps.map(({ run }) => run ?? '').join('\n'); - expect(signingRunBodies).not.toMatch( - /\b(?:curl(?:\.exe)?|wget(?:\.exe)?|Start-BitsTransfer|winget|choco|scoop|npm|npx|pnpm|yarn|pip|nuget)\b|\bgh\s+(?:api|release)\b|Invoke-(?:WebRequest|RestMethod)/i, - ); - expect([...signingRunBodies.matchAll(/\bgit fetch\b/g)]).toHaveLength(0); - - const preparedDownload = signingSteps.find( - ({ name }) => name === 'Download immutable prepared Windows signing handoff', - ); - expect(preparedDownload).toMatchObject({ - uses: 'actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093', - with: { - 'artifact-ids': '${{ needs.prepare-windows-signing.outputs.artifact_id }}', - path: '${{ runner.temp }}\\waggle-windows-signing-prepared', - 'merge-multiple': true, - }, - }); - const preparedVerification = signingSteps.find( - ({ name }) => name === 'Verify and restore immutable prepared Windows signing handoff', - ); - expect(preparedVerification?.env).toMatchObject({ - EXPECTED_PREPARATION_RECEIPT_SHA256: - '${{ needs.prepare-windows-signing.outputs.preparation_receipt_sha256 }}', - EXPECTED_PREPARATION_ARTIFACT_ID: - '${{ needs.prepare-windows-signing.outputs.artifact_id }}', - EXPECTED_PREPARATION_ARTIFACT_DIGEST: - '${{ needs.prepare-windows-signing.outputs.artifact_digest }}', - }); - expect(preparedVerification?.run).toContain('Get-FileHash'); - expect(preparedVerification?.run).toContain('$env:EXPECTED_PREPARATION_RECEIPT_SHA256'); - expect(preparedVerification?.run).toContain('$env:EXPECTED_PREPARATION_ARTIFACT_ID'); - expect(preparedVerification?.run).toContain('$env:EXPECTED_PREPARATION_ARTIFACT_DIGEST'); - - const preparationSteps = preparationJob?.steps ?? []; - const preparedStage = preparationSteps.find( - ({ name }) => name === 'Stage fully inventoried Windows signing preparation', - ); - const assertPreparedHandoffContract = (stageSource: string, verifySource: string) => { - for (const required of [ - 'Assert-WagglePreparedTree $payloadRoot', - 'Windows signing preparation contains a non-allowlisted payload path', - '[IO.FileAttributes]::ReparsePoint', - 'Get-Item -LiteralPath $item.FullName -Stream *', - ]) { - if (!stageSource.includes(required)) throw new Error(`missing preparation guard: ${required}`); - } - for (const required of [ - 'Assert-WaggleTransportTree $preparedRoot', - '$actualSizeBytes -ne [long]$env:EXPECTED_PREPARATION_SIZE_BYTES', - 'Get-FileHash -LiteralPath $receiptPath -Algorithm SHA256', - "Assert-WaggleExactValue $receipt.build.artifactId", - "Assert-WaggleExactValue $receipt.build.artifactDigest", - "Assert-WaggleExactValue $receipt.release.mode", - "Assert-WaggleExactValue $receipt.signerSubject", - "Assert-WaggleExactValue $receipt.azure.clientId", - '$actualPayloadInventory | ConvertTo-Json -Depth 32 -Compress', - 'Get-TrustedPath', - '$destination.StartsWith($canonicalPrefix', - ]) { - if (!verifySource.includes(required)) throw new Error(`missing verification guard: ${required}`); - } - }; - const stageSource = preparedStage?.run ?? ''; - const verificationSource = preparedVerification?.run ?? ''; - expect(() => assertPreparedHandoffContract(stageSource, verificationSource)).not.toThrow(); - for (const marker of [ - 'Assert-WagglePreparedTree $payloadRoot', - 'Windows signing preparation contains a non-allowlisted payload path', - '[IO.FileAttributes]::ReparsePoint', - 'Get-Item -LiteralPath $item.FullName -Stream *', - ]) { - expect(() => assertPreparedHandoffContract(stageSource.split(marker).join(''), verificationSource)) - .toThrow(); - } - for (const marker of [ - 'Assert-WaggleTransportTree $preparedRoot', - '$actualSizeBytes -ne [long]$env:EXPECTED_PREPARATION_SIZE_BYTES', - 'Get-FileHash -LiteralPath $receiptPath -Algorithm SHA256', - 'Assert-WaggleExactValue $receipt.build.artifactId', - 'Assert-WaggleExactValue $receipt.build.artifactDigest', - 'Assert-WaggleExactValue $receipt.release.mode', - 'Assert-WaggleExactValue $receipt.signerSubject', - 'Assert-WaggleExactValue $receipt.azure.clientId', - '$actualPayloadInventory | ConvertTo-Json -Depth 32 -Compress', - 'Get-TrustedPath', - '$destination.StartsWith($canonicalPrefix', - ]) { - expect(() => assertPreparedHandoffContract(stageSource, verificationSource.split(marker).join(''))) - .toThrow(); - } - - expect(signingJob?.outputs).toMatchObject({ - release_mode: '${{ needs.prepare-windows-signing.outputs.release_mode }}', - bootstrap_identity: '${{ needs.prepare-windows-signing.outputs.bootstrap_identity }}', - signer_subject: '${{ needs.prepare-windows-signing.outputs.signer_subject }}', - candidate_sha256: '${{ steps.stage-signed.outputs.candidate_sha256 }}', - handoff_receipt_sha256: '${{ steps.stage-signed.outputs.receipt_sha256 }}', - artifact_id: '${{ steps.upload-signed.outputs.artifact-id }}', - artifact_digest: '${{ steps.upload-signed.outputs.artifact-digest }}', - }); - expect(jobs['certify-windows']?.needs).toBe('sign-windows'); - expect(jobs['attest-windows']?.needs).toBe('certify-windows'); - expect(jobs['attest-windows']?.if).toBe('github.event.repository.private == false'); - expect(jobs['attest-windows']?.environment).toBe('production'); - expect(jobs['publish-windows']?.needs).toEqual(['certify-windows', 'attest-windows']); - }); - - it('flattens every immutable artifact-ID download into its exact configured root', () => { - const workflow = parseYaml( - fs.readFileSync(path.join(ROOT, '.github', 'workflows', 'release.yml'), 'utf-8'), - ) as { - jobs?: Record< - string, - { - steps?: Array<{ - name?: string; - uses?: string; - with?: Record; - }>; - } - >; - }; - const idDownloads = Object.entries(workflow.jobs ?? {}).flatMap(([jobName, job]) => - (job.steps ?? []) - .filter( - (step) => - step.uses?.startsWith('actions/download-artifact@') && - typeof step.with?.['artifact-ids'] === 'string', - ) - .map((step) => ({ - jobName, - name: step.name, - artifactIds: step.with?.['artifact-ids'], - path: step.with?.path, - mergeMultiple: step.with?.['merge-multiple'], - })), - ); - - expect(idDownloads).toEqual([ - { - jobName: 'prepare-windows-signing', - name: 'Download immutable prebuilt handoff for unsigned verification', - artifactIds: '${{ needs.build-windows-prebuilt.outputs.artifact_id }}', - path: '${{ runner.temp }}\\waggle-prebuilt-unsigned', - mergeMultiple: true, - }, - { - jobName: 'prepare-windows-signing', - name: 'Download immutable prebuilt handoff for signed packaging', - artifactIds: '${{ needs.build-windows-prebuilt.outputs.artifact_id }}', - path: '${{ runner.temp }}\\waggle-prebuilt-signing', - mergeMultiple: true, - }, - { - jobName: 'sign-windows', - name: 'Download immutable prepared Windows signing handoff', - artifactIds: '${{ needs.prepare-windows-signing.outputs.artifact_id }}', - path: '${{ runner.temp }}\\waggle-windows-signing-prepared', - mergeMultiple: true, - }, - { - jobName: 'certify-windows', - name: 'Download immutable signed Windows handoff', - artifactIds: '${{ needs.sign-windows.outputs.artifact_id }}', - path: '${{ runner.temp }}\\waggle-windows-signed', - mergeMultiple: true, - }, - { - jobName: 'attest-windows', - name: 'Download certified Windows release by immutable artifact ID', - artifactIds: '${{ needs.certify-windows.outputs.artifact_id }}', - path: '${{ runner.temp }}/waggle-windows-sealed', - mergeMultiple: true, - }, - { - jobName: 'publish-windows', - name: 'Download sealed Windows release outputs', - artifactIds: '${{ needs.certify-windows.outputs.artifact_id }}', - path: '${{ runner.temp }}\\waggle-windows-sealed', - mergeMultiple: true, - }, - ]); - }); - - it.runIf(process.platform === 'win32')( - 'normalizes lowercase upload-artifact digests before exact signed-handoff comparison', - () => { - const workflow = fs - .readFileSync(path.join(ROOT, '.github', 'workflows', 'release.yml'), 'utf-8') - .replace(/\r\n/g, '\n'); - const stepMarker = ' - name: Validate exact signed handoff before candidate execution\n'; - const stepStart = workflow.indexOf(stepMarker); - const stepEnd = workflow.indexOf('\n - name:', stepStart + stepMarker.length); - const stepSource = workflow.slice(stepStart, stepEnd); - const runMarker = ' run: |\n'; - const runStart = stepSource.indexOf(runMarker); - expect(stepStart).toBeGreaterThanOrEqual(0); - expect(stepEnd).toBeGreaterThan(stepStart); - expect(runStart).toBeGreaterThanOrEqual(0); - const stepScript = stepSource - .slice(runStart + runMarker.length) - .split('\n') - .map((line) => line.replace(/^ {10}/, '')) - .join('\n'); - const bindingStart = stepScript.indexOf('$receipt = Get-Content'); - const bindingEnd = stepScript.indexOf('. ./app/scripts/sign-windows-artifact.ps1'); - expect(bindingStart).toBeGreaterThanOrEqual(0); - expect(bindingEnd).toBeGreaterThan(bindingStart); - - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-signed-binding-')); - try { - const receiptPath = path.join(root, 'signing-handoff-receipt.json'); - const sourceRevision = '1'.repeat(40); - const candidateSha256 = 'A'.repeat(64); - const buildReceiptSha256 = 'B'.repeat(64); - const lowercaseBuildArtifactDigest = 'c1'.repeat(32); - fs.writeFileSync( - receiptPath, - JSON.stringify({ - schemaVersion: 1, - sourceRevision, - candidateTag: 'v0.2.0', - candidateVersion: '0.2.0', - releaseMode: 'bootstrap', - bootstrapIdentity: 'v0.2.0', - upgradeBaseTag: '', - upgradeBaseAssetName: '', - upgradeBaseSha256: '', - upgradeBaseCommit: '', - signerSubject: 'CN=Waggle Test', - candidateSha256, - buildReceiptSha256, - buildArtifactId: '123', - buildArtifactDigest: lowercaseBuildArtifactDigest.toUpperCase(), - timestampPolicy: 'fresh-certification-monotonic-v1', - }), - 'utf-8', - ); - const scriptPath = path.join(root, 'validate-binding.ps1'); - fs.writeFileSync( - scriptPath, - `$receiptPath = $env:WAGGLE_FIXTURE_RECEIPT\n${stepScript.slice(bindingStart, bindingEnd)}`, - 'utf-8', - ); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoLogo', '-NoProfile', '-NonInteractive', '-File', scriptPath], - { - cwd: ROOT, - encoding: 'utf-8', - windowsHide: true, - env: { - ...process.env, - WAGGLE_FIXTURE_RECEIPT: receiptPath, - GITHUB_SHA: sourceRevision, - GITHUB_REF_NAME: 'v0.2.0', - EXPECTED_CANDIDATE_VERSION: '0.2.0', - EXPECTED_RELEASE_MODE: 'bootstrap', - EXPECTED_BOOTSTRAP_IDENTITY: 'v0.2.0', - EXPECTED_UPGRADE_BASE_TAG: '', - EXPECTED_UPGRADE_BASE_ASSET_NAME: '', - EXPECTED_UPGRADE_BASE_SHA256: '', - EXPECTED_UPGRADE_BASE_COMMIT: '', - EXPECTED_SIGNER_SUBJECT: 'CN=Waggle Test', - EXPECTED_CANDIDATE_SHA256: candidateSha256, - EXPECTED_BUILD_RECEIPT_SHA256: buildReceiptSha256, - EXPECTED_BUILD_ARTIFACT_ID: '123', - EXPECTED_BUILD_ARTIFACT_DIGEST: lowercaseBuildArtifactDigest, - }, - }, - ); - expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); - } finally { - fs.rmSync(root, { recursive: true, force: true }); - } - }, - 30_000, - ); - - it.runIf(process.platform === 'win32')( - 'executes exact publication staging for bootstrap and upgrade and rejects tampering', - () => { - const workflow = fs - .readFileSync(path.join(ROOT, '.github', 'workflows', 'release.yml'), 'utf-8') - .replace(/\r\n/g, '\n'); - const stepMarker = ' - name: Stage exact publication inputs\n'; - const stepStart = workflow.indexOf(stepMarker); - const stepEnd = workflow.indexOf('\n - name:', stepStart + stepMarker.length); - const stepSource = workflow.slice(stepStart, stepEnd); - const runMarker = ' run: |\n'; - const runStart = stepSource.indexOf(runMarker); - expect(stepStart).toBeGreaterThanOrEqual(0); - expect(stepEnd).toBeGreaterThan(stepStart); - expect(runStart).toBeGreaterThanOrEqual(0); - const stageScript = stepSource - .slice(runStart + runMarker.length) - .split('\n') - .map((line) => line.replace(/^ {10}/, '')) - .join('\n'); - - const sha256 = (value: string) => createHash('sha256').update(value).digest('hex').toUpperCase(); - const runFixture = ( - mode: 'bootstrap' | 'upgrade', - mutation?: 'tampered-source' | 'unexpected-file', - ) => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), `waggle-publish-stage-${mode}-`)); - const runnerTemp = path.join(root, 'runner'); - const sealedRoot = path.join(runnerTemp, 'waggle-windows-sealed'); - const releaseRoot = path.join(sealedRoot, 'release'); - const sourceNsisRoot = path.join(sealedRoot, 'source', 'release-nsis'); - const sourceResourcesRoot = path.join(sealedRoot, 'source', 'resources'); - const provenanceRoot = path.join(sealedRoot, 'provenance'); - const repositoryRoot = path.join(root, 'repo'); - const outputPath = path.join(root, 'github-output.txt'); - const envPath = path.join(root, 'github-env.txt'); - const candidateVersion = mode === 'bootstrap' ? '0.2.0' : '0.3.0'; - const candidateSha = '1'.repeat(40); - const installerName = `Waggle_${candidateVersion}_x64-setup.exe`; - const installer = 'signed-installer'; - const nsis = 'signed-nsis'; - const service = 'signed-service'; - fs.mkdirSync(releaseRoot, { recursive: true }); - fs.mkdirSync(sourceNsisRoot, { recursive: true }); - fs.mkdirSync(sourceResourcesRoot, { recursive: true }); - fs.mkdirSync(provenanceRoot, { recursive: true }); - fs.mkdirSync(path.join(repositoryRoot, 'app', 'src-tauri', 'resources'), { recursive: true }); - fs.writeFileSync(path.join(releaseRoot, installerName), installer); - fs.writeFileSync(path.join(sourceNsisRoot, 'installer.nsi'), nsis); - fs.writeFileSync(path.join(sourceResourcesRoot, 'service.js'), service); - fs.writeFileSync(path.join(provenanceRoot, 'provenance-receipt.json'), '{}'); - fs.writeFileSync( - path.join(releaseRoot, 'windows-installer-certificate.json'), - JSON.stringify({ - evidence: { - generatedInstallerScriptSha256: sha256(nsis), - sidecarBundleSha256: sha256(service), - }, - }), - ); - let baseName = ''; - let baseSha256 = ''; - if (mode === 'upgrade') { - fs.writeFileSync(path.join(releaseRoot, 'windows-installer-upgrade-certificate.json'), '{}'); - const baselineRoot = path.join(sealedRoot, 'baseline'); - fs.mkdirSync(baselineRoot, { recursive: true }); - baseName = 'Waggle_0.2.0_x64-setup.exe'; - const baseline = 'baseline-installer'; - baseSha256 = sha256(baseline); - fs.writeFileSync(path.join(baselineRoot, baseName), baseline); - } - if (mutation === 'tampered-source') { - fs.appendFileSync(path.join(sourceResourcesRoot, 'service.js'), '-tampered'); - } - const inventoryEntries = listFiles(sealedRoot) - .map((file) => ({ - path: path.relative(sealedRoot, file).split(path.sep).join('\\'), - size: fs.statSync(file).size, - sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex').toUpperCase(), - })) - .sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0)); - const bootstrapIdentity = mode === 'bootstrap' ? `v0.2.0@${candidateSha}` : ''; - const baseTag = mode === 'upgrade' ? 'v0.2.0' : ''; - const baseCommit = mode === 'upgrade' ? '2'.repeat(40) : ''; - const signerSubject = 'CN=EGZAKTA DOO BEOGRAD, O=EGZAKTA DOO BEOGRAD, L=Amsterdam, C=NL'; - const sealedReceipt = { - schemaVersion: 1, - sourceRevision: candidateSha, - candidateTag: `v${candidateVersion}`, - candidateVersion, - releaseMode: mode, - bootstrapIdentity, - upgradeBaseTag: baseTag, - upgradeBaseAssetName: baseName, - upgradeBaseSha256: baseSha256, - upgradeBaseCommit: baseCommit, - signerSubject, - candidateSha256: sha256(installer), - signedHandoffReceiptSha256: 'A'.repeat(64), - signedHandoffArtifactId: '123', - signedHandoffArtifactDigest: 'B'.repeat(64), - inventory: { - entries: inventoryEntries, - sha256: sha256(JSON.stringify(inventoryEntries)), - }, - }; - const sealedReceiptPath = path.join(sealedRoot, 'sealed-release-receipt.json'); - fs.writeFileSync(sealedReceiptPath, JSON.stringify(sealedReceipt)); - if (mutation === 'unexpected-file') { - fs.writeFileSync(path.join(sealedRoot, 'unexpected.txt'), 'unexpected'); - } - const scriptPath = path.join(root, 'stage.ps1'); - fs.writeFileSync(scriptPath, stageScript); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', scriptPath], - { - cwd: repositoryRoot, - encoding: 'utf-8', - timeout: 30_000, - windowsHide: true, - env: { - ...process.env, - RUNNER_TEMP: runnerTemp, - GITHUB_OUTPUT: outputPath, - GITHUB_ENV: envPath, - GITHUB_SHA: candidateSha, - GITHUB_REF_NAME: `v${candidateVersion}`, - WAGGLE_RELEASE_MODE: mode, - EXPECTED_CANDIDATE_SHA256: sha256(installer), - EXPECTED_CANDIDATE_VERSION: candidateVersion, - EXPECTED_BOOTSTRAP_IDENTITY: bootstrapIdentity, - EXPECTED_BASE_TAG: baseTag, - EXPECTED_BASE_ASSET_NAME: baseName, - EXPECTED_BASE_SHA256: baseSha256, - EXPECTED_BASE_COMMIT: baseCommit, - EXPECTED_SIGNER_SUBJECT: signerSubject, - EXPECTED_SEALED_RECEIPT_SHA256: createHash('sha256') - .update(fs.readFileSync(sealedReceiptPath)) - .digest('hex') - .toUpperCase(), - EXPECTED_SEALED_ARTIFACT_ID: '456', - EXPECTED_SEALED_ARTIFACT_DIGEST: 'C'.repeat(64), - }, - }, - ); - return { root, result, outputPath, envPath }; - }; - - for (const mode of ['bootstrap', 'upgrade'] as const) { - const positive = runFixture(mode); - try { - expect(positive.result.status, positive.result.stderr || positive.result.stdout).toBe(0); - const statePath = fs.existsSync(positive.envPath) ? positive.envPath : positive.outputPath; - const state = fs.readFileSync(statePath, 'utf-8'); - expect(state).toContain('WAGGLE_UPGRADE_BASE_INSTALLER_PATH='); - if (mode === 'upgrade') expect(state).toContain('Waggle_0.2.0_x64-setup.exe'); - } finally { - fs.rmSync(positive.root, { recursive: true, force: true }); - } - - const tampered = runFixture(mode, 'tampered-source'); - try { - expect(tampered.result.status).not.toBe(0); - expect(tampered.result.stderr).toContain( - 'Sealed publication source inputs differ from their certified hashes.', - ); - } finally { - fs.rmSync(tampered.root, { recursive: true, force: true }); - } - - const unexpected = runFixture(mode, 'unexpected-file'); - try { - expect(unexpected.result.status).not.toBe(0); - expect(unexpected.result.stderr).toContain( - 'Sealed publication artifact topology is not exact.', - ); - } finally { - fs.rmSync(unexpected.root, { recursive: true, force: true }); - } - } - }, - 180_000, - ); - - it('release workflow binds one immutable prebuilt handoff and restores its exact NSIS closure', () => { - const workflow = fs - .readFileSync(path.join(ROOT, '.github', 'workflows', 'release.yml'), 'utf-8') - .replace(/\r\n/g, '\n'); - const buildStart = workflow.indexOf(' build-windows-prebuilt:'); - const preparationStart = workflow.indexOf('\n prepare-windows-signing:', buildStart); - const signingStart = workflow.indexOf('\n sign-windows:', preparationStart); - const certificationStart = workflow.indexOf('\n certify-windows:', signingStart); - expect(buildStart).toBeGreaterThanOrEqual(0); - expect(preparationStart).toBeGreaterThan(buildStart); - expect(signingStart).toBeGreaterThan(preparationStart); - expect(certificationStart).toBeGreaterThan(signingStart); - const buildJob = workflow.slice(buildStart, preparationStart); - const preparationJob = workflow.slice(preparationStart, signingStart); - const signingJob = workflow.slice(signingStart, certificationStart); - - const buildIndex = buildJob.indexOf('Build full unsigned Tauri NSIS package'); - const handoffIndex = buildJob.indexOf('Issue immutable Windows signing handoff'); - const uploadIndex = buildJob.indexOf('Upload immutable Windows signing handoff'); - expect(buildIndex).toBeGreaterThanOrEqual(0); - expect(handoffIndex).toBeGreaterThan(buildIndex); - expect(uploadIndex).toBeGreaterThan(handoffIndex); - expect(buildJob).toContain('./app/scripts/new-windows-signing-handoff.ps1'); - expect(buildJob).toContain( - 'build_receipt_sha256: ${{ steps.handoff.outputs.receipt_sha256 }}', - ); - expect(buildJob).toContain('name: waggle-windows-prebuilt-${{ github.sha }}'); - expect(buildJob).toContain('include-hidden-files: true'); - - expect([ - ...preparationJob.matchAll(/artifact-ids: \$\{\{ needs\.build-windows-prebuilt\.outputs\.artifact_id \}\}/g), - ]).toHaveLength(2); - expect(preparationJob).toContain('waggle-prebuilt-unsigned'); - expect(preparationJob).toContain('waggle-prebuilt-signing'); - expect(preparationJob).toContain( - 'EXPECTED_BUILD_RECEIPT_SHA256: ${{ needs.build-windows-prebuilt.outputs.build_receipt_sha256 }}', - ); - expect(preparationJob).toContain('foreach ($path in @($unsignedReceipt, $signingReceipt))'); - expect(preparationJob).toContain('build-receipt.package.json'); - expect(preparationJob).toContain( - "@($receipt.nsisInventory.entries).Count -ne 442", - ); - expect(preparationJob).toContain( - "1FC822D1A183552A80ADEA01B0BF456F462B90518256EF1FE9EDFA22D76CD85A", - ); - expect(preparationJob).toContain("Join-Path $env:LOCALAPPDATA 'tauri\\NSIS'"); - expect(preparationJob).toContain( - 'Fresh protected signer runner unexpectedly already contains a Tauri NSIS closure.', - ); - expect(preparationJob).toContain('[IO.Directory]::Move($temporaryNsisRoot, $installedNsisRoot)'); - expect(preparationJob).toContain( - '($receipt.nsisInventory | ConvertTo-Json -Depth 8 -Compress)', - ); - expect(preparationJob).toContain('Assert-WaggleCanonicalInventoryEntries $resourceEntries'); - expect(preparationJob).toContain( - 'Materialized canonical repository resources differ from the hosted build receipt.', - ); - for (const argument of [ - "-UnsignedInputRoot '${{ steps.verify-prepared.outputs.unsigned_root }}'", - "-SigningInputRoot '${{ steps.verify-prepared.outputs.signing_root }}'", - "-BuildReceiptPath '${{ steps.verify-prepared.outputs.build_receipt_path }}'", - '-BuildReceiptSha256 $env:EXPECTED_BUILD_RECEIPT_SHA256', - ]) { - expect(signingJob).toContain(argument); - } - expect(signingJob).not.toContain('node node_modules/@tauri-apps/cli/tauri.js build'); - expect(signingJob).not.toContain('node scripts/build-sidecar.mjs'); - expect(signingJob).not.toContain('node scripts/bundle-node.mjs'); - }); - - it('protected signer uses only pinned explicit portable package tools', () => { - const workflow = fs.readFileSync( - path.join(ROOT, '.github', 'workflows', 'release.yml'), - 'utf-8', - ); - const wrapper = fs.readFileSync( - path.join(ROOT, 'app', 'scripts', 'sign-windows-artifact.ps1'), - 'utf-8', - ); - const signingStart = workflow.indexOf(' sign-windows:'); - const preparationStart = workflow.indexOf(' prepare-windows-signing:'); - const certificationStart = workflow.indexOf('\n certify-windows:', signingStart); - const signingJob = workflow.slice(signingStart, certificationStart); - const preparationJob = workflow.slice(preparationStart, signingStart); - - for (const expected of [ - 'https://nodejs.org/dist/v22.22.2/node-v22.22.2-win-x64.zip', - '7C93E9D92BF68C07182B471AA187E35EE6CD08EF0F24AB060DFFF605FCC1C57C', - 'https://github.com/git-for-windows/git/releases/download/v2.51.0.windows.1/MinGit-2.51.0-64-bit.zip', - 'C2C955A21FA99889D83F485F24FA5D9A38FFFC2D509D4022385510E11C26B250', - 'https://www.7-zip.org/a/7z2501-x64.exe', - '78AFA2A1C773CAF3CF7EDF62F857D2A8A5DA55FB0FFF5DA416074C0D28B2B55F', - 'AE1A50511BE58E987483FDBC12125407443926D2D394669ADE2352776E920DD3', - '34A408843194BE320D8A87A3C12CD5C7D2E08D03B24567A41DB32E21D12569D2', - '4CD7D776C686427226A151789D2D61F0B2ED2C392148CC4E69C0238362FAFECF', - '5BD20FB38499D95C39594F41D4781B6181B3304B7F1F4D06B0182F514E7EAA74', - 'CN=OpenJS Foundation, O=OpenJS Foundation, L=San Francisco, S=California, C=US', - 'CN=Johannes Schindelin, O=Johannes Schindelin, S=Nordrhein-Westfalen, C=DE', - 'linked file or alternate data stream', - '@($toolchainInventory.entries).Count -ne 2495', - 'D64F897D4E1A7F07FE9BA62D6AF062EF9F0E41C595CDAF2F3C4F73991BBEA0F5', - 'portable-toolchain-receipt.json', - 'inventory = $toolchainInventory', - 'receipt_path=$receiptPath', - 'receipt_sha256=$receiptSha256', - ]) { - expect(preparationJob).toContain(expected); - } - for (const argument of [ - "-PortableToolchainRoot '${{ steps.verify-prepared.outputs.portable_root }}'", - "-PortableToolchainReceiptPath '${{ steps.verify-prepared.outputs.portable_receipt_path }}'", - "-PortableToolchainReceiptSha256 '${{ steps.verify-prepared.outputs.portable_receipt_sha256 }}'", - "-PortableNodePath '${{ steps.verify-prepared.outputs.portable_node }}'", - "-PortableGitPath '${{ steps.verify-prepared.outputs.portable_git }}'", - "-PortableSevenZipPath '${{ steps.verify-prepared.outputs.portable_sevenzip }}'", - ]) { - expect(signingJob).toContain(argument); - } - expect(signingJob).toContain( - "& 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'", - ); - for (const parameter of [ - 'PortableToolchainRoot', - 'PortableNodePath', - 'PortableGitPath', - 'PortableSevenZipPath', - ]) { - expect(wrapper).toContain(`[string]$${parameter}`); - } - expect(wrapper).toContain('function Get-WagglePortableToolchain'); - expect(wrapper).toContain( - "$DotNetPublisher = 'CN=.NET, O=Microsoft Corporation, L=Redmond, S=Washington, C=US'", - ); - }); - - it('sealed Windows publication reconstructs certified NSIS and sidecar source evidence', () => { - const workflow = fs - .readFileSync(path.join(ROOT, '.github', 'workflows', 'release.yml'), 'utf-8') - .replace(/\r\n/g, '\n'); - const certificationStart = workflow.indexOf(' certify-windows:'); - const attestationStart = workflow.indexOf('\n attest-windows:', certificationStart); - const publicationStart = workflow.indexOf('\n publish-windows:', attestationStart); - const macStart = workflow.indexOf('\n build-macos:', publicationStart); - const certificationJob = workflow.slice(certificationStart, attestationStart); - const attestationJob = workflow.slice(attestationStart, publicationStart); - const publicationJob = workflow.slice(publicationStart, macStart); - - const certifyIndex = certificationJob.indexOf('Certify Windows Solo installer lifecycle'); - const sealIndex = certificationJob.indexOf('Stage sealed Windows release outputs'); - const uploadIndex = certificationJob.indexOf('Upload sealed Windows release outputs'); - const attestIndex = attestationJob.indexOf('Attest bootstrap Windows artifacts'); - expect(certifyIndex).toBeGreaterThanOrEqual(0); - expect(sealIndex).toBeGreaterThan(certifyIndex); - expect(uploadIndex).toBeGreaterThan(sealIndex); - expect(attestIndex).toBeGreaterThanOrEqual(0); - expect(certificationJob).toContain("Join-Path $sealedRoot 'source\\release-nsis'"); - expect(certificationJob).toContain("Get-Item -LiteralPath 'app/src-tauri/resources/service.js'"); - expect(certificationJob).toContain('evidence.generatedInstallerScriptSha256'); - expect(certificationJob).toContain('evidence.sidecarBundleSha256'); - expect(attestationJob).toContain('waggle-windows-sealed/source/release-nsis/installer.nsi'); - expect(attestationJob).toContain('waggle-windows-sealed/source/resources/service.js'); - expect(certificationJob).toContain("Join-Path $sealedRoot 'provenance'"); - - const stageIndex = publicationJob.indexOf('Stage exact publication inputs'); - const publishIndex = publicationJob.indexOf('Publish certified Windows release'); - expect(stageIndex).toBeGreaterThanOrEqual(0); - expect(publishIndex).toBeGreaterThan(stageIndex); - expect(publicationJob).toContain( - "'app/src-tauri/target/x86_64-pc-windows-msvc/release'", - ); - expect(publicationJob).toContain("Join-Path $targetReleaseRoot 'bundle\\nsis'"); - expect(publicationJob).toContain("Join-Path $targetReleaseRoot 'nsis'"); - expect(publicationJob).toContain("'app/src-tauri/resources/service.js'"); - expect(publicationJob).toContain( - 'Publication bundle contains an unexpected asset; provenance must remain separate.', - ); - expect(publicationJob).not.toContain('npm ci'); - expect(publicationJob).not.toContain('cargo '); - expect(publicationJob).not.toContain('@tauri-apps/cli/tauri.js'); - - const publisher = fs.readFileSync( - path.join(ROOT, 'scripts', 'publish-windows-release.ps1'), - 'utf-8', - ); - expect(publisher).toContain( - 'Assert-ReceiptSourceHashes $receiptDataSet $installer $sourceRevision', - ); - expect(publisher).toContain("Join-Path $releaseDirectory 'nsis'"); - expect(publisher).toContain("$currentSidecarPath = 'app/src-tauri/resources/service.js'"); - }); - - it.runIf(process.platform === 'win32')( - 'release publisher rejects differently-cased asset names', - () => { - const publisher = fs - .readFileSync(path.join(ROOT, 'scripts', 'publish-windows-release.ps1'), 'utf-8') - .replace(/\r\n/g, '\n'); - const helperStart = publisher.indexOf('function Assert-ExactReleaseAssets {'); - const helperEnd = publisher.indexOf('\nfunction ', helperStart + 1); - expect(helperStart).toBeGreaterThanOrEqual(0); - expect(helperEnd).toBeGreaterThan(helperStart); - - const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-release-assets-')); - const probePath = path.join(probeRoot, 'probe.ps1'); - const fixtureSource = String.raw` -function Expect-Rejection { - param([scriptblock]$Action, [string]$Label) - $rejected = $false - try { & $Action } catch { $rejected = $true } - if (-not $rejected) { throw "$Label was accepted" } -} - -$expectedPath = Join-Path $PSScriptRoot 'Waggle_0.2.0_x64-setup.exe' -$receiptPath = Join-Path $PSScriptRoot 'windows-installer-certificate.json' -[System.IO.File]::WriteAllText($expectedPath, 'fixture') -[System.IO.File]::WriteAllText($receiptPath, 'receipt') -$expectedAssets = @( - Get-Item -LiteralPath $expectedPath - Get-Item -LiteralPath $receiptPath -) -$exactRelease = [pscustomobject]@{ - assets = @( - [pscustomobject]@{ name = 'Waggle_0.2.0_x64-setup.exe' } - [pscustomobject]@{ name = 'windows-installer-certificate.json' } - ) -} -$wrongCaseRelease = [pscustomobject]@{ - assets = @( - [pscustomobject]@{ name = 'waggle_0.2.0_x64-setup.exe' } - [pscustomobject]@{ name = 'windows-installer-certificate.json' } - ) -} -$missingRelease = [pscustomobject]@{ - assets = @([pscustomobject]@{ name = 'Waggle_0.2.0_x64-setup.exe' }) -} -$extraRelease = [pscustomobject]@{ - assets = @( - [pscustomobject]@{ name = 'Waggle_0.2.0_x64-setup.exe' } - [pscustomobject]@{ name = 'windows-installer-certificate.json' } - [pscustomobject]@{ name = 'unexpected.txt' } - ) -} -$duplicateRelease = [pscustomobject]@{ - assets = @( - [pscustomobject]@{ name = 'Waggle_0.2.0_x64-setup.exe' } - [pscustomobject]@{ name = 'Waggle_0.2.0_x64-setup.exe' } - ) -} - -Assert-ExactReleaseAssets $exactRelease $expectedAssets -Expect-Rejection { - Assert-ExactReleaseAssets $wrongCaseRelease $expectedAssets -} 'differently-cased asset' -Expect-Rejection { - Assert-ExactReleaseAssets $missingRelease $expectedAssets -} 'missing asset' -Expect-Rejection { - Assert-ExactReleaseAssets $extraRelease $expectedAssets -} 'extra asset' -Expect-Rejection { - Assert-ExactReleaseAssets $duplicateRelease $expectedAssets -} 'duplicate asset' -`; - - try { - fs.writeFileSync( - probePath, - `${publisher.slice(helperStart, helperEnd)}\n${fixtureSource}`, - 'utf-8', - ); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath], - { encoding: 'utf-8', timeout: 30_000, windowsHide: true }, - ); - if (result.status !== 0) { - throw new Error(`Release asset probe failed: ${result.stderr || result.stdout}`); - } - } finally { - fs.rmSync(probeRoot, { recursive: true, force: true }); - } - }, - ); - - it.runIf(process.platform === 'win32')( - 'release signer identity accepts exact subjects or legacy thumbprints, never both', - () => { - const publisher = fs - .readFileSync(path.join(ROOT, 'scripts', 'publish-windows-release.ps1'), 'utf-8') - .replace(/\r\n/g, '\n'); - const helperStart = publisher.indexOf('function Get-ProtectedSignerIdentity {'); - const helperEnd = publisher.indexOf( - '\nfunction Assert-PassingWindowsCertificateReceipt {', - helperStart, - ); - expect(helperStart).toBeGreaterThanOrEqual(0); - expect(helperEnd).toBeGreaterThan(helperStart); - - const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-signer-identity-')); - const probePath = path.join(probeRoot, 'probe.ps1'); - const fixtureSource = String.raw` -function Expect-Rejection { - param([scriptblock]$Action, [string]$Label) - $rejected = $false - try { & $Action } catch { $rejected = $true } - if (-not $rejected) { throw "$Label was accepted" } -} - -$subject = 'CN=Managed Identity, O=Fixture Corp, C=NL' -$thumbprint = '0123456789abcdef0123456789abcdef01234567' -$artifactPath = Join-Path $PSScriptRoot 'fixture.exe' -[System.IO.File]::WriteAllText($artifactPath, 'fixture') -$artifact = Get-Item -LiteralPath $artifactPath -$script:fakeSignature = [pscustomobject]@{ - Status = 'Valid' - SignatureType = 'Authenticode' - SignerCertificate = [pscustomobject]@{ - Subject = $subject - Thumbprint = $thumbprint - } - TimeStamperCertificate = [pscustomobject]@{ Subject = 'CN=Timestamp Fixture' } -} -function Get-AuthenticodeSignature { return $script:fakeSignature } - -Remove-Item Env:WINDOWS_CODESIGN_APPROVED_SUBJECT -ErrorAction SilentlyContinue -Remove-Item Env:WINDOWS_CODESIGN_APPROVED_THUMBPRINT -ErrorAction SilentlyContinue -Expect-Rejection { Get-ProtectedSignerIdentity } 'missing identity' -$env:WINDOWS_CODESIGN_APPROVED_SUBJECT = $subject -$env:WINDOWS_CODESIGN_APPROVED_THUMBPRINT = $thumbprint -Expect-Rejection { Get-ProtectedSignerIdentity } 'ambiguous identity' - -Remove-Item Env:WINDOWS_CODESIGN_APPROVED_THUMBPRINT -$subjectBinding = Get-ProtectedSignerIdentity -if ($subjectBinding.mode -cne 'subject' -or $subjectBinding.subject -cne $subject) { - throw 'Exact subject binding was not preserved' -} -$actualSubjectIdentity = Assert-ExpectedAuthenticodeSignature $artifact $subjectBinding - -Remove-Item Env:WINDOWS_CODESIGN_APPROVED_SUBJECT -$env:WINDOWS_CODESIGN_APPROVED_THUMBPRINT = '01 23 45 67 89 ab cd ef 01 23 45 67 89 ab cd ef 01 23 45 67' -$thumbprintBinding = Get-ProtectedSignerIdentity -if ($thumbprintBinding.mode -cne 'thumbprint' -or - $thumbprintBinding.thumbprint -cne $thumbprint.ToUpperInvariant()) { - throw 'Legacy thumbprint binding was not normalized' -} -$actualThumbprintIdentity = Assert-ExpectedAuthenticodeSignature $artifact $thumbprintBinding - -$receiptArtifact = [pscustomobject]@{ - signerSubject = $subject - signerThumbprint = $thumbprint -} -Assert-ReceiptSignerIdentity $receiptArtifact $actualSubjectIdentity 'valid receipt' -$receiptArtifact.signerSubject = $subject.ToLowerInvariant() -Expect-Rejection { - Assert-ReceiptSignerIdentity $receiptArtifact $actualSubjectIdentity 'wrong-case subject' -} 'wrong-case subject receipt' -$receiptArtifact.signerSubject = $subject -$receiptArtifact.signerThumbprint = 'ffffffffffffffffffffffffffffffffffffffff' -Expect-Rejection { - Assert-ReceiptSignerIdentity $receiptArtifact $actualThumbprintIdentity 'wrong thumbprint' -} 'wrong thumbprint receipt' - -$script:fakeSignature.SignatureType = 'Catalog' -Expect-Rejection { - Assert-ExpectedAuthenticodeSignature $artifact $subjectBinding -} 'non-embedded signature' -`; - - try { - fs.writeFileSync( - probePath, - `${publisher.slice(helperStart, helperEnd)}\n${fixtureSource}`, - 'utf-8', - ); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath], - { encoding: 'utf-8', timeout: 30_000, windowsHide: true }, - ); - if (result.status !== 0) { - throw new Error(`Signer identity probe failed: ${result.stderr || result.stdout}`); - } - } finally { - fs.rmSync(probeRoot, { recursive: true, force: true }); - } - }, - ); - - it.runIf(process.platform === 'win32')( - 'release identity receipts remain rotation-safe without weakening legacy pinning', - () => { - const publisher = fs - .readFileSync(path.join(ROOT, 'scripts', 'publish-windows-release.ps1'), 'utf-8') - .replace(/\r\n/g, '\n'); - const helperStart = publisher.indexOf('function Get-ProtectedSignerIdentity {'); - const helperEnd = publisher.indexOf( - '\nfunction Assert-PassingWindowsCertificateReceipt {', - helperStart, - ); - expect(helperStart).toBeGreaterThanOrEqual(0); - expect(helperEnd).toBeGreaterThan(helperStart); - - const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-signer-rotation-')); - const probePath = path.join(probeRoot, 'probe.ps1'); - const fixtureSource = String.raw` -function Expect-Rejection { - param([scriptblock]$Action, [string]$Label) - $rejected = $false - try { & $Action } catch { $rejected = $true } - if (-not $rejected) { throw "$Label was accepted" } -} - -$subject = 'CN=Managed Identity, O=Fixture Corp, C=NL' -$previousThumbprint = '1111111111111111111111111111111111111111' -$candidateThumbprint = '2222222222222222222222222222222222222222' -$previousPath = Join-Path $PSScriptRoot 'previous.exe' -$candidatePath = Join-Path $PSScriptRoot 'candidate.exe' -[System.IO.File]::WriteAllText($previousPath, 'previous') -[System.IO.File]::WriteAllText($candidatePath, 'candidate') -$previousArtifact = Get-Item -LiteralPath $previousPath -$candidateArtifact = Get-Item -LiteralPath $candidatePath -$script:signatureByName = @{ - 'previous.exe' = [pscustomobject]@{ - Status = 'Valid' - SignatureType = 'Authenticode' - SignerCertificate = [pscustomobject]@{ - Subject = $subject - Thumbprint = $previousThumbprint - } - TimeStamperCertificate = [pscustomobject]@{ Subject = 'CN=Timestamp Fixture' } - } - 'candidate.exe' = [pscustomobject]@{ - Status = 'Valid' - SignatureType = 'Authenticode' - SignerCertificate = [pscustomobject]@{ - Subject = $subject - Thumbprint = $candidateThumbprint - } - TimeStamperCertificate = [pscustomobject]@{ Subject = 'CN=Timestamp Fixture' } - } -} -function Get-AuthenticodeSignature { - param([string]$FilePath) - return $script:signatureByName[(Split-Path -Leaf $FilePath)] -} - -$env:WINDOWS_CODESIGN_APPROVED_SUBJECT = $subject -Remove-Item Env:WINDOWS_CODESIGN_APPROVED_THUMBPRINT -ErrorAction SilentlyContinue -$subjectBinding = Get-ProtectedSignerIdentity -$previousIdentity = Assert-ExpectedAuthenticodeSignature $previousArtifact $subjectBinding -$candidateIdentity = Assert-ExpectedAuthenticodeSignature $candidateArtifact $subjectBinding -if ($previousIdentity.thumbprint -ceq $candidateIdentity.thumbprint) { - throw 'Rotation fixture did not produce distinct certificate thumbprints' -} - -$previousReceiptIdentity = [pscustomobject]@{ - signerSubject = $subject - signerThumbprint = $previousThumbprint -} -$candidateReceiptIdentity = [pscustomobject]@{ - signerSubject = $subject - signerThumbprint = $candidateThumbprint -} -$lifecycleReceipt = [pscustomobject]@{ - previousInstaller = $previousReceiptIdentity - previousInstalledApp = $previousReceiptIdentity - installer = $candidateReceiptIdentity - installedApp = $candidateReceiptIdentity -} -Assert-LifecycleReceiptSignerIdentities $lifecycleReceipt $previousIdentity $candidateIdentity -$swappedLifecycleReceipt = [pscustomobject]@{ - previousInstaller = $candidateReceiptIdentity - previousInstalledApp = $candidateReceiptIdentity - installer = $previousReceiptIdentity - installedApp = $previousReceiptIdentity -} -Expect-Rejection { - Assert-LifecycleReceiptSignerIdentities $swappedLifecycleReceipt $previousIdentity $candidateIdentity -} 'swapped lifecycle receipt mappings' - -Remove-Item Env:WINDOWS_CODESIGN_APPROVED_SUBJECT -$env:WINDOWS_CODESIGN_APPROVED_THUMBPRINT = $previousThumbprint -$legacyBinding = Get-ProtectedSignerIdentity -$null = Assert-ExpectedAuthenticodeSignature $previousArtifact $legacyBinding -Expect-Rejection { - Assert-ExpectedAuthenticodeSignature $candidateArtifact $legacyBinding -} 'legacy fixed-thumbprint rotation' -`; - - try { - fs.writeFileSync( - probePath, - `${publisher.slice(helperStart, helperEnd)}\n${fixtureSource}`, - 'utf-8', - ); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath], - { encoding: 'utf-8', timeout: 30_000, windowsHide: true }, - ); - if (result.status !== 0) { - throw new Error(`Signer rotation probe failed: ${result.stderr || result.stdout}`); - } - } finally { - fs.rmSync(probeRoot, { recursive: true, force: true }); - } - }, - ); - - it.runIf(process.platform === 'win32')( - 'installer certifier applies the chosen signer identity to Authenticode evidence', - () => { - const certifier = fs - .readFileSync(path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), 'utf-8') - .replace(/\r\n/g, '\n'); - const helperStart = certifier.indexOf('function Assert-True {'); - const helperEnd = certifier.indexOf( - '\nfunction ConvertTo-StrictSemanticVersion {', - helperStart, - ); - const environmentHelperStart = certifier.indexOf( - 'function Remove-CertificationControlEnvironment {', - ); - const environmentHelperEnd = certifier.indexOf( - '\nfunction Invoke-RawProcess {', - environmentHelperStart, - ); - expect(helperStart).toBeGreaterThanOrEqual(0); - expect(helperEnd).toBeGreaterThan(helperStart); - expect(environmentHelperStart).toBeGreaterThanOrEqual(0); - expect(environmentHelperEnd).toBeGreaterThan(environmentHelperStart); - - const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-certifier-signer-')); - const probePath = path.join(probeRoot, 'probe.ps1'); - const fixtureSource = String.raw` -function Expect-Rejection { - param([scriptblock]$Action, [string]$Label) - $rejected = $false - try { & $Action } catch { $rejected = $true } - if (-not $rejected) { throw "$Label was accepted" } -} - -$subject = 'CN=Managed Identity, O=Fixture Corp, C=NL' -$thumbprint = '0123456789abcdef0123456789abcdef01234567' -$signature = [pscustomobject]@{ - Status = [System.Management.Automation.SignatureStatus]::Valid - SignatureType = 'Authenticode' - SignerCertificate = [pscustomobject]@{ - Subject = $subject - Thumbprint = $thumbprint - } - TimeStamperCertificate = [pscustomobject]@{ Subject = 'CN=Timestamp Fixture' } -} - -Assert-ExpectedAuthenticodeSignature $signature '' $subject 'subject fixture' -Assert-ExpectedAuthenticodeSignature $signature $thumbprint '' 'thumbprint fixture' -$rotatedThumbprint = 'fedcba9876543210fedcba9876543210fedcba98' -$previousReceiptIdentity = [pscustomobject]@{ - signerSubject = $subject - signerThumbprint = $thumbprint -} -$candidateReceiptIdentity = [pscustomobject]@{ - signerSubject = $subject - signerThumbprint = $rotatedThumbprint -} -$lifecycleReceipt = [pscustomobject]@{ - previousInstaller = $previousReceiptIdentity - previousInstalledApp = $previousReceiptIdentity - installer = $candidateReceiptIdentity - installedApp = $candidateReceiptIdentity -} -Assert-LifecycleReceiptApprovedSigner $lifecycleReceipt '' $subject -Expect-Rejection { - Assert-LifecycleReceiptApprovedSigner $lifecycleReceipt $thumbprint '' -} 'legacy certifier rotated candidate' -$processInfo = [System.Diagnostics.ProcessStartInfo]::new() -$protectedIdentityNames = @( - 'WINDOWS_CODESIGN_APPROVED_SUBJECT', - 'WINDOWS_CODESIGN_APPROVED_THUMBPRINT', - 'WAGGLE_APPROVED_CODESIGN_SUBJECT', - 'WAGGLE_APPROVED_CODESIGN_THUMBPRINT', - 'WAGGLE_CODESIGN_SUBJECT', - 'WAGGLE_CODESIGN_THUMBPRINT' -) -foreach ($name in $protectedIdentityNames) { - $processInfo.Environment[$name] = 'must-not-reach-installed-process' -} -$processInfo.Environment['WAGGLE_NON_CONTROL_FIXTURE'] = 'preserve' -Remove-CertificationControlEnvironment $processInfo -foreach ($name in $protectedIdentityNames) { - if ($processInfo.Environment.ContainsKey($name)) { - throw "Protected signer identity environment escaped certification: $name" - } -} -if ($processInfo.Environment['WAGGLE_NON_CONTROL_FIXTURE'] -cne 'preserve') { - throw 'Unrelated application environment was removed' -} -Expect-Rejection { - Assert-ExpectedAuthenticodeSignature $signature '' '' 'missing binding' -} 'missing signer binding' -Expect-Rejection { - Assert-ExpectedAuthenticodeSignature $signature $thumbprint $subject 'ambiguous binding' -} 'ambiguous signer binding' -Expect-Rejection { - Assert-ExpectedAuthenticodeSignature $signature '' $subject.ToLowerInvariant() 'wrong subject' -} 'wrong-case signer subject' -$signature.SignatureType = 'Catalog' -Expect-Rejection { - Assert-ExpectedAuthenticodeSignature $signature '' $subject 'catalog signature' -} 'non-embedded signature' -`; - - try { - fs.writeFileSync( - probePath, - `${certifier.slice(helperStart, helperEnd)}\n${certifier.slice(environmentHelperStart, environmentHelperEnd)}\n${fixtureSource}`, - 'utf-8', - ); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath], - { encoding: 'utf-8', timeout: 30_000, windowsHide: true }, - ); - if (result.status !== 0) { - throw new Error(`Certifier signer identity probe failed: ${result.stderr || result.stdout}`); - } - } finally { - fs.rmSync(probeRoot, { recursive: true, force: true }); - } - }, - ); - - it.runIf(process.platform === 'win32')( - 'release publisher binds release identity and exact asset bytes', - () => { - const publisher = fs - .readFileSync(path.join(ROOT, 'scripts', 'publish-windows-release.ps1'), 'utf-8') - .replace(/\r\n/g, '\n'); - const helperStart = publisher.indexOf('function Assert-ExactReleaseAssets {'); - const helperEnd = publisher.indexOf( - '\nfunction Assert-ManagedModelAndMemoryEvidence {', - helperStart, - ); - expect(helperStart).toBeGreaterThanOrEqual(0); - expect(helperEnd).toBeGreaterThan(helperStart); - - const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-release-bytes-')); - const probePath = path.join(probeRoot, 'probe.ps1'); - const fixtureSource = String.raw` -function Expect-Rejection { - param([scriptblock]$Action, [string]$Label) - $rejected = $false - try { & $Action } catch { $rejected = $true } - if (-not $rejected) { throw "$Label was accepted" } -} - -$expectedDirectory = New-Item -ItemType Directory -Path ( - Join-Path $PSScriptRoot 'expected' -) -$changedDirectory = New-Item -ItemType Directory -Path ( - Join-Path $PSScriptRoot 'changed' -) -$expectedPath = Join-Path $expectedDirectory.FullName 'asset.bin' -$changedPath = Join-Path $changedDirectory.FullName 'asset.bin' -[System.IO.File]::WriteAllText($expectedPath, 'AAAA') -[System.IO.File]::WriteAllText($changedPath, 'BBBB') -$manifest = New-ReleaseAssetManifest @((Get-Item -LiteralPath $expectedPath)) -Assert-ReleaseAssetFileMatchesManifest $expectedPath $manifest[0] 'unchanged local asset' -Expect-Rejection { - Assert-ReleaseAssetFileMatchesManifest $changedPath $manifest[0] 'same-size changed asset' -} 'same-name-size content substitution' - -Set-ReadOnlyCreatedReleaseId 'release-A' -Expect-Rejection { - $script:createdReleaseId = 'release-B' -} 'read-only created release id reassignment' -if ($script:createdReleaseId -cne 'release-A') { - throw 'Read-only created release id changed' -} - -$env:RUNNER_TEMP = Join-Path $PSScriptRoot 'runner' -New-Item -ItemType Directory -Path $env:RUNNER_TEMP | Out-Null -$remoteRelease = [pscustomobject]@{ - assets = @([pscustomobject]@{ name = 'asset.bin' }) -} -$script:fakeGhAssetPath = $expectedPath -function gh { - if ($args.Count -ne 5 -or - [string]$args[0] -cne 'release' -or - [string]$args[1] -cne 'download' -or - [string]$args[3] -cne '--dir') { - throw 'Unexpected fake gh invocation' - } - Copy-Item -LiteralPath $script:fakeGhAssetPath -Destination ( - Join-Path ([string]$args[4]) 'asset.bin' - ) - $global:LASTEXITCODE = 0 -} -Assert-RemoteReleaseAssetContents 'v0.2.0' $remoteRelease $manifest 'fake-valid' -$script:fakeGhAssetPath = $changedPath -Expect-Rejection { - Assert-RemoteReleaseAssetContents 'v0.2.0' $remoteRelease $manifest 'fake-upload' -} 'same-name-size remote content substitution' - -$created = [pscustomobject]@{ - id = 'release-A' - tagName = 'v0.2.0' - name = 'Waggle v0.2.0' - isDraft = $true - isPrerelease = $false -} -$substituted = [pscustomobject]@{ - id = 'release-B' - tagName = 'v0.2.0' - name = 'Waggle v0.2.0' - isDraft = $true - isPrerelease = $false -} -Assert-ReleaseIdentity $created 'release-A' 'v0.2.0' $true 'created release' -Expect-Rejection { - Assert-ReleaseIdentity $substituted 'release-A' 'v0.2.0' $true 'substituted release' -} 'release id substitution' -`; - - try { - fs.writeFileSync( - probePath, - `${publisher.slice(helperStart, helperEnd)}\n${fixtureSource}`, - 'utf-8', - ); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath], - { encoding: 'utf-8', timeout: 30_000, windowsHide: true }, - ); - if (result.status !== 0) { - throw new Error( - `Release byte-integrity probe failed: ${result.stderr || result.stdout}`, - ); - } - } finally { - fs.rmSync(probeRoot, { recursive: true, force: true }); - } - }, - ); - - it('release and PR macOS builds pin each target to a matching runner architecture', () => { - for (const workflowName of ['release.yml', 'tauri-build-pr.yml']) { - const workflow = fs.readFileSync( - path.join(ROOT, '.github', 'workflows', workflowName), - 'utf-8', - ); - expect(workflow).toContain('target: aarch64-apple-darwin'); - expect(workflow).toContain('arch: arm64'); - expect(workflow).toContain('runner: macos-15'); - expect(workflow).toContain('target: x86_64-apple-darwin'); - expect(workflow).toContain('arch: x64'); - expect(workflow).toContain('runner: macos-15-intel'); - expect(workflow).toContain('Verify runner architecture'); - } - }); - - it('release workflow does NOT publish a broken (empty-signature) updater manifest', () => { - // The update-manifest job was removed with the updater config: it published - // latest.json with empty signatures, which every client would reject. Re-add - // it together with real updater signing (see tauri.conf updater note). - const workflow = fs.readFileSync( - path.join(ROOT, '.github', 'workflows', 'release.yml'), - 'utf-8', - ); - // No active `update-manifest:` job (a re-enable note in comments is fine). - expect(workflow).not.toMatch(/^\s*update-manifest:/m); - }); - - it('release workflow stages sidecar dependencies before packaging', () => { - // P0-2: the packaged sidecar require()s esbuild-externalized deps that must - // be staged into resources/node_modules or it dies with MODULE_NOT_FOUND. - const workflow = fs.readFileSync( - path.join(ROOT, '.github', 'workflows', 'release.yml'), - 'utf-8', - ); - expect(workflow).toContain('stage-sidecar-deps'); - }); - - it('PR Windows workflow certifies the locally built NSIS lifecycle before upload', () => { - const workflow = fs.readFileSync( - path.join(ROOT, '.github', 'workflows', 'tauri-build-pr.yml'), - 'utf-8', - ); - const windowsStart = workflow.indexOf(' verify-windows:'); - const macStart = workflow.indexOf('\n verify-macos:', windowsStart); - expect(windowsStart).toBeGreaterThanOrEqual(0); - expect(macStart).toBeGreaterThan(windowsStart); - const windowsSteps = workflow.slice(windowsStart, macStart); - const buildIndex = windowsSteps.indexOf('Build Tauri (Windows)'); - const certificateIndex = windowsSteps.indexOf('Certify Windows Solo installer lifecycle'); - const uploadIndex = windowsSteps.indexOf('Upload Windows artifacts'); - expect(buildIndex).toBeGreaterThanOrEqual(0); - expect(certificateIndex).toBeGreaterThan(buildIndex); - expect(uploadIndex).toBeGreaterThan(certificateIndex); - expect(windowsSteps).toContain('--bundles nsis'); - expect(windowsSteps).toContain('npm ci --prefix app --ignore-scripts'); - expect(windowsSteps).toContain('node node_modules/@tauri-apps/cli/tauri.js build'); - expect(windowsSteps).toContain('-ExpectedSourceRevision $env:GITHUB_SHA'); - expect(windowsSteps).not.toContain('-RequireAuthenticodeSignature'); - expect(windowsSteps).not.toContain('-VerifyManagedModel'); - expect(windowsSteps).not.toContain('-RequireVersionToVersionUpgrade'); - expect(windowsSteps).not.toContain('-PreviousInstallerPath'); - }); - - it('PR Windows workflow reports the exact worktree mutation boundary around Tauri', () => { - const workflow = fs.readFileSync( - path.join(ROOT, '.github', 'workflows', 'tauri-build-pr.yml'), - 'utf-8', - ); - const parsedWorkflow = parseYaml(workflow) as { - jobs?: Record< - string, - { - steps?: Array<{ - name?: string; - id?: string; - if?: unknown; - run?: string; - 'continue-on-error'?: unknown; - }>; - } - >; - }; - const windowsSteps = parsedWorkflow.jobs?.['verify-windows']?.steps ?? []; - const namedStep = (name: string) => { - const matches = windowsSteps.filter((step) => step.name === name); - expect(matches).toHaveLength(1); - return matches[0]!; - }; - const preBuild = namedStep('Verify repository cleanliness before Tauri build'); - const build = namedStep('Build Tauri (Windows)'); - const postBuild = namedStep('Report repository changes after Tauri build'); - const certificate = namedStep('Certify Windows Solo installer lifecycle'); - - expect(windowsSteps.indexOf(preBuild)).toBeLessThan(windowsSteps.indexOf(build)); - expect(windowsSteps.indexOf(build)).toBeLessThan(windowsSteps.indexOf(postBuild)); - expect(windowsSteps.indexOf(postBuild)).toBeLessThan(windowsSteps.indexOf(certificate)); - expect(build.id).toBe('tauri-build-windows'); - expect(postBuild.if).toBe( - "${{ always() && steps.tauri-build-windows.outcome != 'skipped' }}", - ); - - for (const diagnosticStep of [preBuild, postBuild]) { - const run = diagnosticStep.run ?? ''; - expect([ - ...run.matchAll(/git status --porcelain=v1 --untracked-files=all/g), - ]).toHaveLength(1); - expect(run).toContain('if ($LASTEXITCODE -ne 0)'); - expect(run).toContain('if ($sourceStatus.Count -ne 0)'); - expect(run).not.toMatch(/git\s+(?:reset|clean|checkout|restore|stash)\b/i); - expect(run).not.toMatch(/\b(?:Remove-Item|Clear-Content|Set-Content)\b/i); - expect(diagnosticStep['continue-on-error']).toBeUndefined(); - } - - const postBuildRun = postBuild.run ?? ''; - expect(postBuildRun).toContain( - '$trackedPaths = @(& git diff --name-only --diff-filter=ACDMRTUXB)', - ); - expect(postBuildRun).toContain('& git rev-parse "HEAD:$trackedPath"'); - expect(postBuildRun).toContain('& git rev-parse ":$trackedPath"'); - expect(postBuildRun).toContain('Get-FileHash -LiteralPath $trackedPath -Algorithm SHA256'); - expect(postBuildRun).toContain('& git diff --numstat -- $trackedPath'); - expect(postBuildRun).not.toContain('git diff --no-ext-diff'); - expect(postBuildRun).not.toContain('$diffLines'); - expect(postBuildRun.indexOf('$trackedPaths = @(')).toBeLessThan( - postBuildRun.indexOf('throw "Windows Tauri build mutated repository worktree.'), - ); - }); - - it.runIf(process.platform === 'win32')( - 'installer certifier reports every dirty tracked and untracked path without mutation', - () => { - const certifier = fs - .readFileSync(path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), 'utf-8') - .replace(/\r\n/g, '\n'); - const helperStart = certifier.indexOf('function Assert-CleanRepositoryWorktree {'); - const helperEnd = certifier.indexOf( - '\nfunction Test-CertificateTimestamp {', - helperStart, - ); - expect(helperStart).toBeGreaterThanOrEqual(0); - expect(helperEnd).toBeGreaterThan(helperStart); - - const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-source-clean-')); - const repositoryRoot = path.join(probeRoot, 'repository'); - const probePath = path.join(probeRoot, 'probe.ps1'); - const runGit = (args: string[]) => spawnSync('git', args, { - cwd: repositoryRoot, - encoding: 'utf-8', - timeout: 30_000, - windowsHide: true, - }); - const status = () => runGit([ - 'status', - '--porcelain=v1', - '--untracked-files=all', - ]); - - try { - fs.mkdirSync(repositoryRoot, { recursive: true }); - expect(runGit(['init']).status).toBe(0); - fs.writeFileSync(path.join(repositoryRoot, 'tracked.txt'), 'clean\n', 'utf-8'); - expect(runGit(['add', 'tracked.txt']).status).toBe(0); - expect(runGit([ - '-c', - 'user.name=Waggle Fixture', - '-c', - 'user.email=fixture@waggle.invalid', - 'commit', - '-m', - 'fixture', - ]).status).toBe(0); - - fs.writeFileSync( - probePath, - `${certifier.slice(helperStart, helperEnd)}\nAssert-CleanRepositoryWorktree -GitExecutable 'git' -RepositoryRoot $args[0]\n`, - 'utf-8', - ); - const cleanResult = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath, repositoryRoot], - { encoding: 'utf-8', timeout: 30_000, windowsHide: true }, - ); - expect(cleanResult.status, cleanResult.stderr || cleanResult.stdout).toBe(0); - - fs.writeFileSync(path.join(repositoryRoot, 'tracked.txt'), 'dirty\n', 'utf-8'); - fs.mkdirSync(path.join(repositoryRoot, 'nested'), { recursive: true }); - fs.writeFileSync( - path.join(repositoryRoot, 'nested', 'untracked.txt'), - 'untracked\n', - 'utf-8', - ); - const before = status(); - expect(before.status, before.stderr || before.stdout).toBe(0); - const trackedBefore = fs.readFileSync(path.join(repositoryRoot, 'tracked.txt')); - const untrackedBefore = fs.readFileSync( - path.join(repositoryRoot, 'nested', 'untracked.txt'), - ); - - const dirtyResult = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath, repositoryRoot], - { encoding: 'utf-8', timeout: 30_000, windowsHide: true }, - ); - const dirtyOutput = `${dirtyResult.stdout ?? ''}\n${dirtyResult.stderr ?? ''}`; - expect(dirtyResult.status).not.toBe(0); - expect(dirtyOutput).toContain(' M tracked.txt'); - expect(dirtyOutput).toContain('?? nested/untracked.txt'); - - const after = status(); - expect(after.status, after.stderr || after.stdout).toBe(0); - expect(after.stdout).toBe(before.stdout); - expect(fs.readFileSync(path.join(repositoryRoot, 'tracked.txt'))).toEqual( - trackedBefore, - ); - expect( - fs.readFileSync(path.join(repositoryRoot, 'nested', 'untracked.txt')), - ).toEqual(untrackedBefore); - } finally { - fs.rmSync(probeRoot, { recursive: true, force: true }); - } - }, - 60_000, - ); - - it('PR desktop verification runs when either Windows workflow changes', () => { - const workflow = fs.readFileSync( - path.join(ROOT, '.github', 'workflows', 'tauri-build-pr.yml'), - 'utf-8', - ); - expect([...workflow.matchAll(/\.github\/workflows\/release\.yml/g)]).toHaveLength(2); - expect([...workflow.matchAll(/\.github\/workflows\/tauri-build-pr\.yml/g)]).toHaveLength(2); - expect([...workflow.matchAll(/'scripts\/\*\*'/g)]).toHaveLength(2); - const windowsJobStart = workflow.indexOf(' verify-windows:'); - const windowsJobEnd = workflow.indexOf('\n verify-macos:', windowsJobStart); - expect(windowsJobStart).toBeGreaterThanOrEqual(0); - expect(windowsJobEnd).toBeGreaterThan(windowsJobStart); - const windowsJob = workflow.slice(windowsJobStart, windowsJobEnd); - expect(windowsJob).toContain('runs-on: windows-latest'); - expect([ - ...windowsJob.matchAll(/- name: Verify Windows release-mode and publication guards/g), - ]).toHaveLength(1); - expect(windowsJob).toContain('shell: pwsh'); - expect(windowsJob).toContain("WAGGLE_REQUIRE_PWSH7: '1'"); - expect(windowsJob).toContain( - 'packages/server/tests/tauri-config.test.ts -t "CI/CD Configuration"', - ); - expect(windowsJob.indexOf('- name: Install dependencies')).toBeLessThan( - windowsJob.indexOf('- name: Verify Windows release-mode and publication guards'), - ); - expect( - windowsJob.indexOf('- name: Verify Windows release-mode and publication guards'), - ).toBeLessThan(windowsJob.indexOf('- name: Install locked Tauri CLI')); - }); - - it('desktop workflows pin every third-party action to a full commit SHA', () => { - for (const name of ['release.yml', 'tauri-build-pr.yml']) { - const workflow = fs.readFileSync( - path.join(ROOT, '.github', 'workflows', name), - 'utf-8', - ); - const actionRefs = [...workflow.matchAll(/uses:\s+[^@\s]+@([^\s#]+)/g)] - .map((match) => match[1]); - expect(actionRefs.length).toBeGreaterThan(0); - for (const actionRef of actionRefs) { - expect(actionRef).toMatch(/^[0-9a-f]{40}$/); - } - } - }); - - it('Windows installer certificate is fail-closed across isolated boot, repair, and uninstall', () => { - const script = fs.readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf-8', - ); - - expect(script.startsWith('#Requires -Version 7.0')).toBe(true); - expect(script).toContain('Set-StrictMode -Version Latest'); - expect(script).toContain('"/S /D=$installDir"'); - expect(script).toContain('function Assert-SafeReceiptPath'); - expect(script).toContain('Assert-SafeReceiptPath $ReceiptPath'); - expect(script).toContain('function Reserve-CertificateReceiptPath'); - expect(script).toContain( - '$receiptReservation = Reserve-CertificateReceiptPath $ReceiptPath', - ); - expect(script).toContain( - 'Write-CertificateReceipt $receiptReservation $receiptJson', - ); - expect(script).toContain('Receipt path already exists; refusing to overwrite'); - expect(script).toContain('Receipt parent must not be a reparse point'); - expect(script).not.toContain('Set-Content -LiteralPath $ReceiptPath'); - expect( - script.indexOf('$receiptReservation = Reserve-CertificateReceiptPath $ReceiptPath'), - ).toBeLessThan( - script.indexOf('$scratchOwnershipMarker = New-CertificateScratchRoot'), - ); - expect(script).toContain('function New-CertificateScratchRoot'); - expect(script).toContain('function Remove-CertificateScratchRoot'); - expect(script).toContain('[System.IO.FileMode]::CreateNew'); - expect(script).toContain( - '$scratchOwnershipMarker = New-CertificateScratchRoot $scratchRoot $runId', - ); - expect(script).toContain( - 'Remove-CertificateScratchRoot $scratchRoot $scratchOwnershipMarker $runId', - ); - expect(script).not.toContain( - 'New-Item -ItemType Directory -Path $scratchRoot -Force | Out-Null', - ); - expect(script).not.toContain( - 'Remove-Item -LiteralPath $resolvedRoot -Recurse -Force', - ); - expect(script).not.toContain( - 'Remove-Item -LiteralPath $scratchRoot -Recurse -Force', - ); - expect(script).toContain("$env:WAGGLE_PORT = '3333'"); - expect(script).toContain('Assert-TcpPortAvailable 3333'); - expect(script).toContain("$profileDataDir = Join-Path $env:USERPROFILE '.waggle'"); - expect(script.indexOf('Assert-TcpPortAvailable 3333')).toBeLessThan( - script.indexOf('New-Item -ItemType Directory -Path $profileDataDir'), - ); - expect(script).toContain('$dataDir = $profileDataDir'); - expect(script).not.toContain("$dataDir = Join-Path $scratchRoot 'data'"); - expect(script).not.toContain('$env:WAGGLE_DATA_DIR = $dataDir'); - expect(script).toContain("'OPENROUTER_API_KEY'"); - expect(script).toContain("resources\\node.exe"); - expect(script).toContain("resources\\service.js"); - expect(script).toContain("resources\\marketplace.db"); - expect(script).not.toContain('--install-links'); - expect(script).toContain("$offlinePackageTar = Join-Path $isolationPath 'tar.exe'"); - expect(script).toContain( - "$offlinePackageArchive = Join-Path $scratchRoot 'waggle-offline-install-probe-1.0.0.tgz'", - ); - expect(script).toContain('Invoke-RawProcess $offlinePackageTar'); - expect(script).toContain('-- $offlinePackageArchive 2>&1'); - expect(script).toContain( - 'Bundled npm installed the local offline package as a reparse point.', - ); - expect(script).toContain('prepare-ran.txt'); - expect(script).toContain('prepack-ran.txt'); - expect(script).toContain('install-ran.txt'); - expect(script).toContain("$receipt.Contains('scratchCleanupError')"); - expect(script).toContain("Join-Path $dataDir 'marketplace.db'"); - const jsonRequestHelper = script.slice( - script.indexOf('function Invoke-JsonRequest {'), - script.indexOf('\nfunction Invoke-JsonPostRequest {'), - ); - expect(jsonRequestHelper).toContain( - '[ValidateRange(1, 30)] [int]$TimeoutSeconds = 5', - ); - expect(jsonRequestHelper).toContain('-TimeoutSec $TimeoutSeconds'); - - const marketplaceProbeStart = script.indexOf( - '$marketplace = Invoke-JsonRequest', - ); - const marketplaceProbe = script.slice( - marketplaceProbeStart, - script.indexOf('$marketplacePackages =', marketplaceProbeStart), - ); - expect(marketplaceProbe).toContain('-TimeoutSeconds 30'); - expect(script).toContain( - '$baseUrl/api/marketplace/search?type=mcp&source=mcp_registry&limit=100', - ); - expect(script).toContain('marketplaceResourceSha256'); - expect(script).toContain("$receipt.checks['marketplaceResource']"); - expect(script).toContain("$receipt.checks['marketplaceApi']"); - expect(script).toContain('Same-version repair did not restore resources/marketplace.db'); - expect(script).toContain('/v1/health/liveliness'); - expect(script).toContain( - '$proxy = Invoke-BuiltInProxyLivenessProbe -Uri "$baseUrl/v1/health/liveliness"', - ); - expect(script).toContain('/api/auth/session-token'); - expect(script).toContain('$BaseUrl/api/workspaces'); - expect(script).toContain('$BaseUrl/api/memory/frames?extract=false'); - expect(script).toContain('New-CertificateLifecycleData'); - expect(script).toContain('Assert-CertificateLifecycleData'); - expect(script).toContain('Get-CertificateDataManifest'); - expect(script).toContain('Assert-CertificateDataManifest'); - expect(script).toContain('Get-CertificateDataManifestDigest'); - expect(script).toContain('Get-CertificateRelativePath'); - expect(script).toContain('function Get-ExternalProfileRootSnapshot'); - expect(script).toContain('function Assert-ExternalProfileRootsUnchanged'); - expect(script).toContain('Get-ChildItem -LiteralPath $parentPath -Force'); - expect(script).toContain("Join-Path $env:USERPROFILE '.hive-mind'"); - expect(script).toContain("Join-Path $env:USERPROFILE '.ollama'"); - expect(script).toContain('ConvertTo-Json -InputObject @($manifest)'); - expect(script).toContain('$externalProfileRootsPreProven = $true'); - expect(script).toContain("$receipt.checks['externalProfileRootsUnchanged'] = $true"); - expect(script).toContain("$receipt['externalProfileIsolationError']"); - expect(script).toContain("$receipt.Contains('externalProfileIsolationError')"); - for (const cacheVariable of [ - 'OLLAMA_MODELS', - 'HF_HOME', - 'HF_HUB_CACHE', - 'TRANSFORMERS_CACHE', - 'XDG_CACHE_HOME', - ]) { - expect(script).toContain(`'${cacheVariable}'`); - } - expect(script).not.toContain('[System.IO.Path]::GetRelativePath'); - expect(script).toContain("$receipt.checks['defaultProfileDataDir']"); - expect(script).toContain("$receipt.checks['realWorkspaceAndMemorySeeded']"); - expect(script).toContain("$receipt.checks['upgradeRealWorkspaceAndMemoryPreserved']"); - expect(script).toContain("$receipt.checks['repairRealWorkspaceAndMemoryPreserved']"); - expect(script).toContain("$receipt.checks['uninstallRealWorkspaceAndMemoryPreserved']"); - expect(script).toContain('Remove-CertificateProfileData'); - expect(script).not.toContain('Remove-CertificateProfileMarker'); - expect(script).not.toContain('$_.path -cne $markerRelativePath'); - const finalUninstallerCleanup = script.match( - /if \(Test-Path -LiteralPath \$uninstaller -PathType Leaf\) \{\s*try \{([\s\S]*?)Invoke-RawProcess \$uninstaller/, - )?.[1]; - expect(finalUninstallerCleanup).toBeDefined(); - const shutdownProofReset = - finalUninstallerCleanup?.indexOf('$runtimeConfirmedStopped = $false') ?? -1; - const preUninstallProcessAssertion = - finalUninstallerCleanup?.indexOf('Assert-NoForeignWaggleProcesses') ?? -1; - expect(shutdownProofReset).toBeGreaterThanOrEqual(0); - expect(preUninstallProcessAssertion).toBeGreaterThanOrEqual(0); - expect(shutdownProofReset).toBeLessThan(preUninstallProcessAssertion); - expect(script).toContain("$baseUrl/api/chat"); - expect(script).toContain('No AI model is ready'); - expect(script).toContain("$receipt.checks['noModelChatSetupRequired']"); - expect(script).toContain("$baseUrl/api/tier"); - expect(script).toContain("$receipt.certifiedTier = 'FREE'"); - expect(script).toContain("$receipt.checks['soloTier']"); - expect(script).toContain("$receipt.checks['previousSoloTier']"); - expect(script).toContain("$receipt.checks['repairSoloTier']"); - expect(script).toMatch( - /if \(-not \$RequireVersionToVersionUpgrade\) \{[\s\S]*?\$chatProbeMessage/, - ); - expect(script).toContain('unauthenticatedProtectedRoute'); - expect(script).toContain("'WAGGLE_TRUST_LOCALHOST'"); - expect(script).toContain("'WAGGLE_SQLITE_VEC_PATH'"); - expect(script).toContain("'ONNXRUNTIME_NODE_BINDING_PATH'"); - expect(script).toContain("'VOYAGE_API_KEY'"); - expect(script).toContain("'EMBEDDING_PROVIDER'"); - expect(script).toContain('environmentSnapshot'); - expect(script).toContain('environmentRestored'); - expect(script).toContain("$isolationPath = Join-Path $scratchRoot 'isolated-path'"); - expect(script).toContain('$env:PATH = $isolationPath'); - expect(script).not.toContain('$env:PATH = "$env:SystemRoot\\System32;$env:SystemRoot"'); - expect(script).toContain('/api/embedding/status'); - expect(script).toContain('/api/local-inference/status'); - expect(script).toContain('/api/local-inference/bootstrap'); - expect(script).toContain('/api/local-inference/pull'); - expect(script).toContain('[switch]$VerifyManagedModel'); - expect(script).toContain("[Environment]::GetFolderPath('System')"); - expect(script).toContain("@('tar.exe', 'taskkill.exe')"); - expect(script).toContain("$receipt.checks['windowsInboxTools']"); - expect(script).toContain('$managedOperationTimeoutSeconds = 3600'); - expect(script).toContain('$receipt.managedModelVerified = $true'); - expect(script).toContain("$receipt.checks['managedModelChat']"); - expect(script).toContain('$baseUrl/v1/chat/completions'); - expect(script).toContain('model = "ollama/$managedModelName"'); - expect(script).toContain("$receipt.checks['managedModelProxyRestartChat']"); - expect(script).toContain("$receipt.checks['previousManagedModelSeeded']"); - expect(script).toContain("$receipt.checks['upgradeManagedModelPreserved']"); - expect(script).toContain("$receipt.checks['repairManagedModelDigestPreserved']"); - expect(script).toContain('managedModelDigest'); - expect(script).toContain('managedRuntimeCleanup'); - expect(script).toContain('Stop-InstalledProcesses $appExecutable $serviceScript $managedRuntimeRoot'); - expect(script).toContain('dockerRequired'); - expect(script).toContain('sameVersionRepair'); - expect(script).toContain('$firstProcess.HasExited'); - expect(script).toContain('$secondProcess.HasExited'); - expect(script).toContain('Wait-ForInstalledRuntimeStop'); - expect(script).toContain('Assert-NoForeignWaggleProcesses'); - expect(script).toContain('function Assert-CertificateUninstallPostconditions'); - const uninstallPostconditionCalls = [ - ...script.matchAll(/^\s+Assert-CertificateUninstallPostconditions\s+`/gm), - ]; - expect(uninstallPostconditionCalls).toHaveLength(2); - const outerFinallyStart = script.lastIndexOf('} finally {'); - const successUninstallStart = script.indexOf( - "$receipt.checks['uninstallerCleanup'] = $true", - ); - expect(successUninstallStart).toBeGreaterThanOrEqual(0); - expect(outerFinallyStart).toBeGreaterThan(successUninstallStart); - expect( - script.slice(successUninstallStart, outerFinallyStart), - ).toContain('Assert-CertificateUninstallPostconditions `'); - expect(script.slice(outerFinallyStart)).toContain( - 'Assert-CertificateUninstallPostconditions `', - ); - const uninstallPostconditionHelper = script.match( - /function Assert-CertificateUninstallPostconditions \{([\s\S]*?)\r?\n\}/, - )?.[1]; - expect(uninstallPostconditionHelper).toBeDefined(); - expect(uninstallPostconditionHelper).toContain('Wait-ForPathState $InstallDir $false'); - expect(uninstallPostconditionHelper).toContain( - 'Wait-ForPathState $UninstallRegistry $false', - ); - expect(uninstallPostconditionHelper).toContain( - 'Wait-ForPathState $ProductRegistry $false', - ); - expect(uninstallPostconditionHelper).toContain( - 'Test-RegistryValue $RunRegistry $RunRegistryValue', - ); - expect(uninstallPostconditionHelper).toContain('Wait-ForPathState $shortcut $false'); - expect(uninstallPostconditionHelper).toContain('Wait-ForInstalledRuntimeStop'); - expect(uninstallPostconditionHelper).toContain( - '-ManagedRuntimeRoot $ManagedRuntimeRoot -AdditionalPorts $AdditionalPorts', - ); - expect(uninstallPostconditionHelper).toContain('Assert-NoForeignWaggleProcesses'); - expect(uninstallPostconditionHelper).toContain('Assert-TcpPortAvailable $Port'); - expect(script).toContain('foreignProcessCollisionGuard'); - expect(script).not.toMatch(/Get-CimInstance[^\r\n]+-ErrorAction\s+SilentlyContinue/); - expect(script).toContain('Stop-StartedProcessTree'); - expect(script).toContain('"/PID $($Process.Id) /T /F"'); - expect(script).toContain('repairRegistrations'); - expect(script).toContain('runRegistryCollisionGuard'); - expect(script).toContain('UninstallString'); - expect(script).toContain("Invoke-RawProcess $registeredUninstaller '/S'"); - expect(script).toContain('Wait-ForPathState $uninstallRegistry $false 30'); - expect(script).toContain("HKCU:\\Software\\egzakta\\Waggle"); - expect(script).toContain('Remove-CertificateProductRegistry'); - expect(script).toContain('Clear-AbandonedCertificateProductRegistry'); - expect(script).toContain('certificateRegistryCleanup'); - expect(script).toContain('profileDataDeletionAbsent'); - expect(script).toContain('baseAppDataDeletionNeutralized'); - expect(script).toContain('profileDataPathPreserved'); - expect(script).toContain('configuredDataDirPreserved'); - expect(script).not.toContain('uninstallPreservedData'); - expect(script).not.toContain('embeddingModelVerified'); - expect(script).toContain('RequireAuthenticodeSignature'); - expect(script).toContain('ExpectedSignerThumbprint'); - expect(script).toContain('ExpectedSignerSubject'); - expect(script).toContain('Exactly one expected signer identity binding is required'); - expect(script).toContain('function Assert-LifecycleReceiptApprovedSigner'); - expect([ - ...script.matchAll(/^\s+Assert-LifecycleReceiptApprovedSigner `$/gm), - ]).toHaveLength(1); - expect(script).toContain('[System.StringComparison]::Ordinal'); - expect(script).not.toContain( - 'CN=EGZAKTA DOO BEOGRAD, O=EGZAKTA DOO BEOGRAD, L=Amsterdam, C=NL', - ); - expect(script).toContain('ExpectedSourceRevision'); - expect(script).toContain('function Get-SidecarProvenance'); - expect(script).toContain('Packaged resources/service.js does not match a clean sidecar rebuild.'); - expect(script).toContain("$receipt.checks['sidecarSourceProvenance']"); - expect(script).toContain('$receipt.evidence.sidecarBundleSha256'); - expect(script).toContain('$receipt.evidence.sidecarProvenanceSha256'); - expect(script).toContain('$receipt.evidence.sidecarSourceInputCount'); - expect(script).toContain('RequireVersionToVersionUpgrade'); - expect(script).toContain('PreviousInstallerPath'); - expect(script).toContain('ExpectedPreviousInstallerSha256'); - expect(script).toContain('ExpectedPreviousVersion'); - expect(script).toContain('ExpectedPreviousSourceRevision'); - expect(script).toContain('ExpectedCandidateInstallerSha256'); - expect(script).toContain('ExpectedCandidateVersion'); - expect(script).toContain('version-to-version-upgrade'); - expect(script).toContain('Previous installer SHA-256 must be exactly 64 hexadecimal characters.'); - expect(script).toContain('Candidate installer SHA-256 must be exactly 64 hexadecimal characters.'); - expect(script).toContain('Previous source revision must be exactly 40 hexadecimal characters.'); - expect(script).toContain('Previous installer and candidate installer must be distinct files.'); - expect(script).toContain('Candidate version must be newer than the previous version.'); - expect(script).toContain("$receipt.checks['previousInstallerHash']"); - expect(script).toContain("$receipt.checks['previousInstallerAuthenticodeSignature']"); - expect(script).toContain("$receipt.checks['previousInstalledAppAuthenticodeSignature']"); - expect(script).toContain("$receipt.checks['versionOrder']"); - expect(script).toContain("$receipt.checks['versionToVersionUpgrade']"); - expect(script).toContain("$receipt.checks['upgradeSameInstallDirectory']"); - expect(script).toContain("$receipt.checks['upgradeConfiguredDataPreserved']"); - expect(script).toContain("$receipt.checks['upgradeProfileDataPreserved']"); - expect(script).toContain("$receipt.checks['upgradeVaultKeyPreserved']"); - expect(script).toContain("$receipt.checks['relaunchAfterUpgrade']"); - expect(script).toContain('Candidate installer before upgrade'); - expect(script).toContain('Candidate installer after upgrade'); - expect(script).toContain('Candidate installer before repair'); - expect(script).toContain('Candidate installer after repair'); - expect(script).toContain('previousSourceRevision = $ExpectedPreviousSourceRevision'); - expect(script).toContain('Remove-CertificationControlEnvironment'); - expect(script).toContain("'^(?:ACTIONS_|GITHUB_|RUNNER_|WAGGLE_UPGRADE_BASE_)'"); - expect(script).toContain("'GH_TOKEN', 'GITHUB_TOKEN'"); - expect(script).toContain("'WINDOWS_CODESIGN_APPROVED_SUBJECT'"); - expect(script).toContain("'WINDOWS_CODESIGN_APPROVED_THUMBPRINT'"); - expect(script).toContain("'WAGGLE_APPROVED_CODESIGN_SUBJECT'"); - expect(script).toContain("'WAGGLE_CODESIGN_SUBJECT'"); - expect(script).toContain("$receipt.checks['candidateInstallerHash']"); - const previousInstallIndex = script.indexOf('Invoke-RawProcess $PreviousInstallerPath'); - const previousLaunchIndex = script.indexOf('$previousProcess = Start-InstalledApp'); - const candidateInstallIndex = script.indexOf('Invoke-RawProcess $InstallerPath', previousInstallIndex); - const candidateLaunchIndex = script.indexOf('$firstProcess = Start-InstalledApp'); - const candidateRepairIndex = script.lastIndexOf('Invoke-RawProcess $InstallerPath'); - const previousSoloTierIndex = script.indexOf("$receipt.checks['previousSoloTier']"); - const previousManagedModelSeedIndex = script.indexOf( - "$receipt.checks['previousManagedModelSeeded']", - ); - const upgradeManagedModelPreservedIndex = script.indexOf( - "$receipt.checks['upgradeManagedModelPreserved']", - ); - const managedModelProxyRestartIndex = script.indexOf( - "$receipt.checks['managedModelProxyRestartChat']", - ); - const repairSoloTierIndex = script.indexOf("$receipt.checks['repairSoloTier']"); - const repairManagedModelDigestIndex = script.indexOf( - "$receipt.checks['repairManagedModelDigestPreserved']", - ); - const uninstallIndex = script.indexOf("Invoke-RawProcess $registeredUninstaller '/S'"); - expect(previousInstallIndex).toBeGreaterThanOrEqual(0); - expect(previousLaunchIndex).toBeGreaterThan(previousInstallIndex); - expect(previousSoloTierIndex).toBeGreaterThan(previousLaunchIndex); - expect(previousManagedModelSeedIndex).toBeGreaterThan(previousSoloTierIndex); - expect(previousManagedModelSeedIndex).toBeLessThan(candidateInstallIndex); - expect(candidateInstallIndex).toBeGreaterThan(previousLaunchIndex); - expect(candidateLaunchIndex).toBeGreaterThan(candidateInstallIndex); - expect(upgradeManagedModelPreservedIndex).toBeGreaterThan(candidateLaunchIndex); - expect(upgradeManagedModelPreservedIndex).toBeLessThan(candidateRepairIndex); - expect(candidateRepairIndex).toBeGreaterThan(candidateLaunchIndex); - expect(repairSoloTierIndex).toBeGreaterThan(candidateRepairIndex); - expect(repairManagedModelDigestIndex).toBeGreaterThan(repairSoloTierIndex); - expect(repairManagedModelDigestIndex).toBeLessThan(managedModelProxyRestartIndex); - expect(repairSoloTierIndex).toBeLessThan(managedModelProxyRestartIndex); - expect(managedModelProxyRestartIndex).toBeGreaterThan(candidateRepairIndex); - expect(managedModelProxyRestartIndex).toBeLessThan(uninstallIndex); - expect(uninstallIndex).toBeGreaterThan(candidateRepairIndex); - expect(script).toContain('sourceFilesClean'); - expect(script).toContain('status --porcelain=v1 --untracked-files=all'); - expect(script).toMatch( - /\$gitCommand\s*=\s*Get-Command git -CommandType Application -ErrorAction SilentlyContinue\s*\|\s*Select-Object -First 1/, - ); - expect(script).toContain('schemaVersion = 4'); - expect(script).toContain('-UseBasicParsing'); - expect(script).toContain('authenticodeStatus'); - expect(script).toContain('signerThumbprint'); - expect(script).toContain('TimeStamperCertificate'); - expect(script).toContain('timestampAuthorityThumbprint'); - expect(script).toContain('SignatureType'); - expect(script).toContain('portable embedded Authenticode signature'); - expect(script).toContain('installedAppAuthenticodeSignature'); - expect(script).toContain('Installed Waggle executable'); - expect(script).toContain('certifierSha256'); - expect(script).toContain('installerHookSha256'); - expect(script).toContain('generatedInstallerScriptSha256'); - expect(script).toContain('generatedInstallerInclude'); - expect(script).toContain('$installerHookFile.LastWriteTimeUtc'); - expect(script).toContain('!macro\\s+NSIS_HOOK_POSTUNINSTALL\\b'); - expect(script).toContain('!include\\s+"(?[^"]+)"\\s*$'); - expect(script).not.toContain("$generatedInstallerContent.Contains('NSIS_HOOK_POSTUNINSTALL')"); - expect(script).not.toContain("$receipt.checks['builtInProxy']"); - expect(script).not.toContain("$receipt.checks['uninstallCleanup']"); - expect(script).toContain("$receipt.checks['uninstallerCleanup']"); - expect(script).toContain('embeddingPayloadReady'); - expect(script).toContain('Assert-VaultKeyAclRestricted'); - expect(script).toContain("Join-Path $dataDir '.vault-key'"); - expect(script).toContain('AreAccessRulesProtected'); - expect(script).toContain('[Security.Principal.WindowsIdentity]::GetCurrent().User'); - expect(script).toContain("$receipt.checks['vaultKeyAclRestricted']"); - expect(script).toContain('sourceRevision'); - expect(script).toContain('certificateRunId'); - expect(script).toContain('$desktopShortcut'); - expect(script).toContain('$startMenuShortcuts'); - expect(script).toContain('Assert-SafeScratchRoot'); - expect(script).not.toMatch(/Get-Process\s+(?:-Name\s+)?['"]?waggle/i); - expect(script.lastIndexOf( - 'Remove-CertificateScratchRoot $scratchRoot $scratchOwnershipMarker $runId', - )) - .toBeLessThan(script.lastIndexOf('$receipt | ConvertTo-Json')); - }); - - it.runIf(process.platform === 'win32')( - 'Windows installer external-profile proof detects created and changed roots', - () => { - const script = fs - .readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf-8', - ) - .replace(/\r\n/g, '\n'); - const helperStart = script.indexOf('function Assert-True {'); - const helperEnd = script.indexOf('\nfunction Get-HttpStatusCode {', helperStart); - expect(helperStart).toBeGreaterThanOrEqual(0); - expect(helperEnd).toBeGreaterThan(helperStart); - - const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-profile-proof-')); - const probePath = path.join(probeRoot, 'profile-proof.ps1'); - const escapedRoot = probeRoot.replace(/'/g, "''"); - const fixtureSource = ` -$fixtureRoot = '${escapedRoot}' -$absentRoot = Join-Path $fixtureRoot 'absent-root' -$absentSnapshot = Get-ExternalProfileRootSnapshot -Name '.absent' -Path $absentRoot -if ($absentSnapshot.existedBefore) { throw 'Absent fixture was reported present' } -Set-Content -LiteralPath $absentRoot -Value 'unexpected file' -Encoding UTF8 -$fileMutationRejected = $false -try { Assert-ExternalProfileRootsUnchanged @($absentSnapshot) } catch { $fileMutationRejected = $true } -if (-not $fileMutationRejected) { throw 'External file root was accepted as absent' } -Remove-Item -LiteralPath $absentRoot -Force -New-Item -ItemType Directory -Path $absentRoot | Out-Null -$absentMutationRejected = $false -try { Assert-ExternalProfileRootsUnchanged @($absentSnapshot) } catch { $absentMutationRejected = $true } -if (-not $absentMutationRejected) { throw 'Created external root was accepted' } -Remove-Item -LiteralPath $absentRoot -Recurse -Force - -$junctionRoot = Join-Path $fixtureRoot 'dangling-junction' -$junctionSnapshot = Get-ExternalProfileRootSnapshot -Name '.junction' -Path $junctionRoot -$junctionTarget = Join-Path $fixtureRoot 'junction-target' -New-Item -ItemType Directory -Path $junctionTarget | Out-Null -New-Item -ItemType Junction -Path $junctionRoot -Target $junctionTarget | Out-Null -Remove-Item -LiteralPath $junctionTarget -Recurse -Force -$junctionMutationRejected = $false -try { Assert-ExternalProfileRootsUnchanged @($junctionSnapshot) } catch { $junctionMutationRejected = $true } -if (-not $junctionMutationRejected) { throw 'Dangling junction was accepted as absent' } -Remove-Item -LiteralPath $junctionRoot -Force - -$emptyRoot = Join-Path $fixtureRoot 'empty-root' -New-Item -ItemType Directory -Path $emptyRoot | Out-Null -$emptySnapshot = Get-ExternalProfileRootSnapshot -Name '.empty' -Path $emptyRoot -if ([string]::IsNullOrWhiteSpace([string]$emptySnapshot.manifestSha256)) { - throw 'Empty external root did not receive a stable manifest digest' -} -Assert-ExternalProfileRootsUnchanged @($emptySnapshot) - -$presentRoot = Join-Path $fixtureRoot 'present-root' -New-Item -ItemType Directory -Path $presentRoot | Out-Null -Set-Content -LiteralPath (Join-Path $presentRoot 'sentinel.txt') -Value 'before' -Encoding UTF8 -$presentSnapshot = Get-ExternalProfileRootSnapshot -Name '.present' -Path $presentRoot -Assert-ExternalProfileRootsUnchanged @($presentSnapshot) -Set-Content -LiteralPath (Join-Path $presentRoot 'sentinel.txt') -Value 'after' -Encoding UTF8 -$contentMutationRejected = $false -try { Assert-ExternalProfileRootsUnchanged @($presentSnapshot) } catch { $contentMutationRejected = $true } -if (-not $contentMutationRejected) { throw 'Changed external root was accepted' } -`; - - try { - fs.writeFileSync( - probePath, - `${script.slice(helperStart, helperEnd)}\n${fixtureSource}`, - 'utf-8', - ); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath], - { encoding: 'utf-8', timeout: 30_000, windowsHide: true }, - ); - if (result.status !== 0) { - throw new Error( - `Windows external-profile proof probe failed: ${result.stderr || result.stdout}`, - ); - } - } finally { - fs.rmSync(probeRoot, { recursive: true, force: true }); - } - }, - ); - - it.runIf(process.platform === 'win32')( - 'Windows installer timestamp validation survives JSON date coercion under non-US culture', - () => { - const script = fs - .readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf-8', - ) - .replace(/\r\n/g, '\n'); - const helperStart = script.indexOf('function Test-CertificateTimestamp {'); - const helperEnd = script.indexOf( - '\nfunction Assert-ExpectedAuthenticodeSignature {', - helperStart, - ); - expect(helperStart).toBeGreaterThanOrEqual(0); - expect(helperEnd).toBeGreaterThan(helperStart); - expect(script).toContain('Test-CertificateTimestamp $frame.timestamp'); - expect(script).toContain('Test-CertificateTimestamp $workspace.created'); - expect(script).not.toContain('TryParse([string]$frame.timestamp'); - expect(script).not.toContain('TryParse([string]$workspace.created'); - - const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-cert-time-')); - const probePath = path.join(probeRoot, 'probe.ps1'); - const fixtureSource = String.raw` -$culture = [Globalization.CultureInfo]::GetCultureInfo('sr-Latn-RS') -[Threading.Thread]::CurrentThread.CurrentCulture = $culture -[Threading.Thread]::CurrentThread.CurrentUICulture = $culture -$coercedTimestamp = [datetime]::Parse( - '2026-07-31T23:24:03.123Z', - [Globalization.CultureInfo]::InvariantCulture, - [Globalization.DateTimeStyles]::RoundtripKind -) -$legacyParsed = [DateTimeOffset]::MinValue -if ([DateTimeOffset]::TryParse([string]$coercedTimestamp, [ref]$legacyParsed)) { - throw 'Fixture no longer reproduces the culture-sensitive cast failure' -} -if (-not (Test-CertificateTimestamp $coercedTimestamp)) { - throw 'A valid JSON-coerced DateTime was rejected' -} -if (-not (Test-CertificateTimestamp '2026-07-31T23:24:03.123Z')) { - throw 'A valid ISO timestamp string was rejected' -} -foreach ($invalid in @($null, '', 'not-a-timestamp')) { - if (Test-CertificateTimestamp $invalid) { - throw 'An invalid timestamp was accepted' - } -} -`; - - try { - fs.writeFileSync( - probePath, - `${script.slice(helperStart, helperEnd)}\n${fixtureSource}`, - 'utf-8', - ); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath], - { encoding: 'utf-8', timeout: 30_000, windowsHide: true }, - ); - if (result.status !== 0) { - throw new Error( - `Windows installer timestamp probe failed: ${result.stderr || result.stdout}`, - ); - } - } finally { - fs.rmSync(probeRoot, { recursive: true, force: true }); - } - }, - ); - - it.runIf(process.platform === 'win32')( - 'Windows installer certificate preserves sentinels when receipt paths are unsafe', - () => { - const script = fs - .readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf-8', - ) - .replace(/\r\n/g, '\n'); - const helperStart = script.indexOf('function Assert-SafeReceiptPath {'); - const helperEnd = script.indexOf( - '\nfunction Assert-SafeScratchRoot {', - helperStart + 1, - ); - expect(helperStart).toBeGreaterThanOrEqual(0); - expect(helperEnd).toBeGreaterThan(helperStart); - - const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-cert-receipt-')); - const outsideRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-cert-outside-')); - const probePath = path.join(probeRoot, 'probe.ps1'); - const existingReceipt = path.join(probeRoot, 'existing.json'); - const hardlinkTarget = path.join(probeRoot, 'hardlink-target.json'); - const hardlinkReceipt = path.join(probeRoot, 'hardlink.json'); - const junctionParent = path.join(probeRoot, 'receipt-parent'); - const outsideSentinel = path.join(outsideRoot, 'sentinel.txt'); - fs.writeFileSync(existingReceipt, 'existing-receipt-sentinel', 'utf-8'); - fs.writeFileSync(hardlinkTarget, 'hardlink-sentinel', 'utf-8'); - fs.linkSync(hardlinkTarget, hardlinkReceipt); - fs.writeFileSync(outsideSentinel, 'outside-sentinel', 'utf-8'); - fs.symlinkSync(outsideRoot, junctionParent, 'junction'); - - const fixtureSource = String.raw` -Set-StrictMode -Version Latest -$ErrorActionPreference = 'Stop' -function Assert-True { - param([Parameter(Mandatory = $true)] [bool]$Condition, [Parameter(Mandatory = $true)] [string]$Message) - if (-not $Condition) { throw $Message } -} -function Expect-Rejection { - param([scriptblock]$Action, [string]$Label) - $rejected = $false - try { & $Action } catch { $rejected = $true } - if (-not $rejected) { throw "$Label was accepted" } -} - -$existingReceipt = Join-Path $PSScriptRoot 'existing.json' -$hardlinkReceipt = Join-Path $PSScriptRoot 'hardlink.json' -$hardlinkTarget = Join-Path $PSScriptRoot 'hardlink-target.json' -$junctionReceipt = Join-Path (Join-Path $PSScriptRoot 'receipt-parent') 'receipt.json' -$reservedReceipt = Join-Path $PSScriptRoot 'reserved.json' -Expect-Rejection { Assert-SafeReceiptPath $existingReceipt } 'existing receipt' -Expect-Rejection { Reserve-CertificateReceiptPath $hardlinkReceipt } 'hardlink receipt' -Expect-Rejection { Assert-SafeReceiptPath $junctionReceipt } 'junction receipt parent' -$reservation = Reserve-CertificateReceiptPath $reservedReceipt -Expect-Rejection { Reserve-CertificateReceiptPath $reservedReceipt } 'second receipt reservation' -Write-CertificateReceipt $reservation 'reserved-receipt' -if ((Get-Content -Raw -LiteralPath $existingReceipt) -cne 'existing-receipt-sentinel') { - throw 'Existing receipt sentinel changed' -} -if ((Get-Content -Raw -LiteralPath $hardlinkTarget) -cne 'hardlink-sentinel') { - throw 'Hardlink receipt sentinel changed' -} -if ((Get-Content -Raw -LiteralPath $reservedReceipt) -cne 'reserved-receipt') { - throw 'Reserved receipt content was not written through its owned handle' -} -if ((Get-Content -Raw -LiteralPath '${outsideSentinel.replaceAll('\\', '\\\\')}') -cne 'outside-sentinel') { - throw 'Outside sentinel changed' -} -if (Test-Path -LiteralPath $junctionReceipt) { - throw 'Receipt was written through the junction' -} -`; - - try { - fs.writeFileSync( - probePath, - `${script.slice(helperStart, helperEnd)}\n${fixtureSource}`, - 'utf-8', - ); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath], - { encoding: 'utf-8', timeout: 30_000, windowsHide: true }, - ); - if (result.status !== 0) { - throw new Error( - `Windows installer receipt safety probe failed: ${result.stderr || result.stdout}`, - ); - } - } finally { - fs.rmSync(probeRoot, { recursive: true, force: true }); - fs.rmSync(outsideRoot, { recursive: true, force: true }); - } - }, - ); - - it.runIf(process.platform === 'win32')( - 'Windows installer certificate owns scratch roots before guarded cleanup', - () => { - const script = fs - .readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf-8', - ) - .replace(/\r\n/g, '\n'); - const manifestStart = script.indexOf('function Get-CertificateRelativePath {'); - const manifestEnd = script.indexOf( - '\nfunction Assert-CertificateDataManifest {', - manifestStart, - ); - const scratchStart = script.indexOf('function Assert-SafeScratchRoot {'); - const scratchEnd = script.indexOf( - '\nfunction Remove-CertificateProductRegistry {', - scratchStart, - ); - expect(manifestStart).toBeGreaterThanOrEqual(0); - expect(manifestEnd).toBeGreaterThan(manifestStart); - expect(scratchStart).toBeGreaterThanOrEqual(0); - expect(scratchEnd).toBeGreaterThan(scratchStart); - - const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-cert-scratch-')); - const outsideRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-cert-owned-')); - const probePath = path.join(probeRoot, 'probe.ps1'); - const fixtureSource = String.raw` -function Assert-True { - param([Parameter(Mandatory = $true)] [bool]$Condition, [Parameter(Mandatory = $true)] [string]$Message) - if (-not $Condition) { throw $Message } -} -function Expect-Rejection { - param([scriptblock]$Action, [string]$Label) - $rejected = $false - try { & $Action } catch { $rejected = $true } - if (-not $rejected) { throw "$Label was accepted" } -} - -$existingRunId = '11111111111111111111111111111111' -$existingRoot = Join-Path $PSScriptRoot "waggle-installer-cert-$existingRunId" -New-Item -ItemType Directory -Path $existingRoot | Out-Null -$existingSentinel = Join-Path $existingRoot 'sentinel.txt' -Set-Content -NoNewline -LiteralPath $existingSentinel -Value 'existing-root-sentinel' -Expect-Rejection { - New-CertificateScratchRoot $existingRoot $existingRunId -} 'pre-existing scratch root' -if ((Get-Content -Raw -LiteralPath $existingSentinel) -cne 'existing-root-sentinel') { - throw 'Pre-existing scratch sentinel changed' -} - -$validRunId = '22222222222222222222222222222222' -$validRoot = Join-Path $PSScriptRoot "waggle-installer-cert-$validRunId" -$validMarker = New-CertificateScratchRoot $validRoot $validRunId -if ((Split-Path -Leaf $validMarker) -cne ".waggle-installer-certificate-owner-$validRunId") { - throw 'Scratch ownership marker name is not exact' -} -if ((Get-Content -Raw -LiteralPath $validMarker) -cne $validRunId) { - throw 'Scratch ownership marker content is not exact' -} -Set-Content -NoNewline -LiteralPath (Join-Path $validRoot 'owned.txt') -Value 'owned' -$nestedRoot = New-Item -ItemType Directory -Path (Join-Path $validRoot 'nested') -Set-Content -NoNewline -LiteralPath (Join-Path $nestedRoot 'owned.txt') -Value 'owned' -Remove-CertificateScratchRoot $validRoot $validMarker $validRunId -if (Test-Path -LiteralPath $validRoot) { - throw 'Owned scratch root was not removed' -} - -$tamperedRunId = '33333333333333333333333333333333' -$tamperedRoot = Join-Path $PSScriptRoot "waggle-installer-cert-$tamperedRunId" -$tamperedMarker = New-CertificateScratchRoot $tamperedRoot $tamperedRunId -$tamperedSentinel = Join-Path $tamperedRoot 'sentinel.txt' -Set-Content -NoNewline -LiteralPath $tamperedMarker -Value 'wrong-owner' -Set-Content -NoNewline -LiteralPath $tamperedSentinel -Value 'tampered-root-sentinel' -Expect-Rejection { - Remove-CertificateScratchRoot $tamperedRoot $tamperedMarker $tamperedRunId -} 'tampered ownership marker' -if ((Get-Content -Raw -LiteralPath $tamperedSentinel) -cne 'tampered-root-sentinel') { - throw 'Tampered scratch sentinel changed' -} - -$reparseRunId = '44444444444444444444444444444444' -$reparseRoot = Join-Path $PSScriptRoot "waggle-installer-cert-$reparseRunId" -$reparseMarker = New-CertificateScratchRoot $reparseRoot $reparseRunId -$outsideRoot = '${outsideRoot.replaceAll('\\', '\\\\')}' -$outsideSentinel = Join-Path $outsideRoot 'sentinel.txt' -Set-Content -NoNewline -LiteralPath $outsideSentinel -Value 'outside-sentinel' -New-Item -ItemType Junction -Path (Join-Path $reparseRoot 'outside') -Target $outsideRoot | - Out-Null -Expect-Rejection { - Remove-CertificateScratchRoot $reparseRoot $reparseMarker $reparseRunId -} 'scratch child reparse point' -if ((Get-Content -Raw -LiteralPath $outsideSentinel) -cne 'outside-sentinel') { - throw 'Outside scratch sentinel changed' -} -`; - - try { - fs.writeFileSync( - probePath, - [ - script.slice(manifestStart, manifestEnd), - script.slice(scratchStart, scratchEnd), - fixtureSource, - ].join('\n'), - 'utf-8', - ); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath], - { - encoding: 'utf-8', - timeout: 30_000, - windowsHide: true, - env: { ...process.env, TEMP: probeRoot, TMP: probeRoot }, - }, - ); - if (result.status !== 0) { - throw new Error( - `Windows installer scratch safety probe failed: ${result.stderr || result.stdout}`, - ); - } - } finally { - fs.rmSync(probeRoot, { recursive: true, force: true }); - fs.rmSync(outsideRoot, { recursive: true, force: true }); - } - }, - ); - it('accepts Tauri generated NSIS hook dispatch while binding the exact custom include', () => { const hookPath = path.join(TAURI_DIR, 'nsis', 'installer.nsi'); const generatedFixture = [ @@ -6099,21 +2933,6 @@ if ($arguments.Contains('test-results')) { throw 'Playwright default output dire ); }); - it('Windows installer shutdown checks listeners instead of rejecting TCP TIME_WAIT', () => { - const script = fs.readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf8', - ); - const shutdownHelper = script.match( - /function Wait-ForInstalledRuntimeStop \{([\s\S]*?)\r?\n\}/, - )?.[1]; - - expect(shutdownHelper).toBeDefined(); - expect(script).toContain('function Test-TcpPortHasListener'); - expect(shutdownHelper).toContain('Test-TcpPortHasListener $_'); - expect(shutdownHelper).not.toContain('Test-TcpPortAvailable $_'); - }); - it('keeps the three-agent live collaboration contract regression-locked', () => { const liveSpec = fs.readFileSync( path.join(ROOT, 'tests', 'integration', 'external-agent-collaboration.live.test.ts'), @@ -6572,655 +3391,160 @@ if ($arguments.Contains('test-results')) { throw 'Playwright default output dire expect(publish).toBeGreaterThan(failureWrite); expect(nonZero).toBeGreaterThan(publish); }); - - it('release workflow builds packages before bundling the desktop sidecar', () => { - // Release builds must follow the same package -> sidecar ordering as the - // PR Tauri verification lane, otherwise tag artifacts can ship stale or - // missing workspace dist outputs even when PR verification was green. - const workflow = fs.readFileSync( - path.join(ROOT, '.github', 'workflows', 'release.yml'), - 'utf-8', - ); - const buildPackageIndexes = [...workflow.matchAll(/npm run build:packages/g)].map( - (match) => match.index ?? -1, - ); - const sidecarIndexes = [...workflow.matchAll(/node scripts\/build-sidecar\.mjs/g)].map( - (match) => match.index ?? -1, - ); - - expect(buildPackageIndexes).toHaveLength(sidecarIndexes.length); - expect(sidecarIndexes).toHaveLength(2); - for (const [index, sidecarIndex] of sidecarIndexes.entries()) { - expect(buildPackageIndexes[index]).toBeLessThan(sidecarIndex); - } - }); - - it('release publication requires the verified Windows vault-key ACL receipt', () => { - const publisher = fs.readFileSync( - path.join(ROOT, 'scripts', 'publish-windows-release.ps1'), - 'utf-8', - ); - - expect(publisher).toMatch(/\$cleanRequiredChecks\s*=\s*@\([\s\S]*'vaultKeyAclRestricted'[\s\S]*\)/); - expect(publisher).toMatch(/\$upgradeRequiredChecks\s*=\s*@\([\s\S]*'vaultKeyAclRestricted'[\s\S]*\)/); - }); - - it('release publication requires external profile isolation evidence', () => { - const publisher = fs.readFileSync( - path.join(ROOT, 'scripts', 'publish-windows-release.ps1'), - 'utf-8', - ); - expect(publisher).toMatch( - /\$cleanRequiredChecks\s*=\s*@\([\s\S]*'externalProfileRootsUnchanged'[\s\S]*\)/, - ); - expect(publisher).toMatch( - /\$upgradeRequiredChecks\s*=\s*@\([\s\S]*'externalProfileRootsUnchanged'[\s\S]*\)/, - ); - }); - - it('release publication requires real default-profile workspace and memory lifecycle evidence', () => { - const publisher = fs.readFileSync( - path.join(ROOT, 'scripts', 'publish-windows-release.ps1'), - 'utf-8', - ); - const cleanRequiredChecks = publisher.match( - /\$cleanRequiredChecks\s*=\s*@\(([\s\S]*?)\r?\n\s*\)/, - )?.[1]; - const upgradeRequiredChecks = publisher.match( - /\$upgradeRequiredChecks\s*=\s*@\(([\s\S]*?)\r?\n\s*\)/, - )?.[1]; - expect(cleanRequiredChecks).toBeDefined(); - expect(upgradeRequiredChecks).toBeDefined(); - - for (const check of [ - 'defaultProfileDataDir', - 'realWorkspaceAndMemorySeeded', - 'repairRealWorkspaceAndMemoryPreserved', - 'uninstallRealWorkspaceAndMemoryPreserved', - 'certificateProfileCleanup', - ]) { - expect(cleanRequiredChecks).toContain(`'${check}'`); - expect(upgradeRequiredChecks).toContain(`'${check}'`); - } - expect(upgradeRequiredChecks).toContain("'upgradeRealWorkspaceAndMemoryPreserved'"); - expect(publisher).toContain('lifecycleData.workspaceId'); - expect(publisher).toContain('lifecycleData.personalFrameId'); - expect(publisher).toContain('lifecycleData.workspaceFrameId'); - expect(publisher).toContain('lifecycleData.preUninstallManifestEntryCount'); - expect(publisher).toContain('lifecycleData.preUninstallManifestSha256'); - expect(publisher).toContain('lifecycleData.postUninstallManifestSha256'); - expect(publisher).toContain('unchanged uninstall manifest'); - }); - - it.runIf(process.platform === 'win32')( - 'release receipt guards reject stringified schema versions and truthy non-booleans', - () => { - const publisher = fs - .readFileSync(path.join(ROOT, 'scripts', 'publish-windows-release.ps1'), 'utf-8') - .replace(/\r\n/g, '\n'); - const envelopeStart = publisher.indexOf( - 'function Assert-PassingWindowsCertificateReceipt {', - ); - const checkStart = publisher.indexOf( - 'function Assert-PassingWindowsCertificateCheck {', - ); - const verifierStart = publisher.indexOf( - '\nfunction Assert-ExactReleaseAssets {', - checkStart, - ); - expect(envelopeStart).toBeGreaterThanOrEqual(0); - expect(checkStart).toBeGreaterThan(envelopeStart); - expect(verifierStart).toBeGreaterThan(checkStart); - expect([ - ...publisher.matchAll( - /^function Assert-PassingWindowsCertificateReceipt \{/gm, - ), - ]).toHaveLength(1); - expect([ - ...publisher.matchAll( - /^function Assert-PassingWindowsCertificateCheck \{/gm, - ), - ]).toHaveLength(1); - - const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-receipt-types-')); - const probePath = path.join(probeRoot, 'probe.ps1'); - const helperSource = publisher.slice(envelopeStart, verifierStart); - const fixtureSource = String.raw` -function Expect-Rejection { - param([scriptblock]$Action, [string]$Label) - $rejected = $false - try { & $Action } catch { $rejected = $true } - if (-not $rejected) { throw "$Label was accepted" } -} - -$good = '{"schemaVersion":4,"certificationMode":"same-version-repair","status":"passed","checks":{"proof":true}}' | ConvertFrom-Json -$longVersion = '{"schemaVersion":4,"certificationMode":"same-version-repair","status":"passed","checks":{"proof":true}}' | ConvertFrom-Json -$longVersion.schemaVersion = [long]4 -$stringVersion = '{"schemaVersion":"4","certificationMode":"same-version-repair","status":"passed","checks":{"proof":true}}' | ConvertFrom-Json -$wrongVersion = '{"schemaVersion":3,"certificationMode":"same-version-repair","status":"passed","checks":{"proof":true}}' | ConvertFrom-Json -$missingMode = '{"schemaVersion":4,"status":"passed","checks":{"proof":true}}' | ConvertFrom-Json -$wrongMode = '{"schemaVersion":4,"certificationMode":"version-to-version-upgrade","status":"passed","checks":{"proof":true}}' | ConvertFrom-Json -$numericMode = '{"schemaVersion":4,"certificationMode":1,"status":"passed","checks":{"proof":true}}' | ConvertFrom-Json -$missingStatus = '{"schemaVersion":4,"certificationMode":"same-version-repair","checks":{"proof":true}}' | ConvertFrom-Json -$wrongStatus = '{"schemaVersion":4,"certificationMode":"same-version-repair","status":"failed","checks":{"proof":true}}' | ConvertFrom-Json -$numericStatus = '{"schemaVersion":4,"certificationMode":"same-version-repair","status":1,"checks":{"proof":true}}' | ConvertFrom-Json -$stringCheck = '{"schemaVersion":4,"certificationMode":"same-version-repair","status":"passed","checks":{"proof":"true"}}' | ConvertFrom-Json -$numericCheck = '{"schemaVersion":4,"certificationMode":"same-version-repair","status":"passed","checks":{"proof":1}}' | ConvertFrom-Json -$falseCheck = '{"schemaVersion":4,"certificationMode":"same-version-repair","status":"passed","checks":{"proof":false}}' | ConvertFrom-Json -$missingCheck = '{"schemaVersion":4,"certificationMode":"same-version-repair","status":"passed","checks":{}}' | ConvertFrom-Json -Assert-PassingWindowsCertificateReceipt $good 'same-version-repair' 'good fixture' -Assert-PassingWindowsCertificateReceipt $longVersion 'same-version-repair' 'PowerShell 7 integer fixture' -Assert-PassingWindowsCertificateCheck $good 'proof' 'good fixture' -Expect-Rejection { Assert-PassingWindowsCertificateReceipt $stringVersion 'same-version-repair' 'string version' } 'string version' -Expect-Rejection { Assert-PassingWindowsCertificateReceipt $wrongVersion 'same-version-repair' 'wrong version' } 'wrong version' -Expect-Rejection { Assert-PassingWindowsCertificateReceipt $missingMode 'same-version-repair' 'missing mode' } 'missing mode' -Expect-Rejection { Assert-PassingWindowsCertificateReceipt $wrongMode 'same-version-repair' 'wrong mode' } 'wrong mode' -Expect-Rejection { Assert-PassingWindowsCertificateReceipt $numericMode 'same-version-repair' 'numeric mode' } 'numeric mode' -Expect-Rejection { Assert-PassingWindowsCertificateReceipt $missingStatus 'same-version-repair' 'missing status' } 'missing status' -Expect-Rejection { Assert-PassingWindowsCertificateReceipt $wrongStatus 'same-version-repair' 'wrong status' } 'wrong status' -Expect-Rejection { Assert-PassingWindowsCertificateReceipt $numericStatus 'same-version-repair' 'numeric status' } 'numeric status' -Expect-Rejection { Assert-PassingWindowsCertificateCheck $stringCheck 'proof' 'string check' } 'string check' -Expect-Rejection { Assert-PassingWindowsCertificateCheck $numericCheck 'proof' 'numeric check' } 'numeric check' -Expect-Rejection { Assert-PassingWindowsCertificateCheck $falseCheck 'proof' 'false check' } 'false check' -Expect-Rejection { Assert-PassingWindowsCertificateCheck $missingCheck 'proof' 'missing check' } 'missing check' -`; - - try { - fs.writeFileSync(probePath, `${helperSource}\n${fixtureSource}`, 'utf-8'); - const result = spawnSync( - powershellProbeExecutable(), - ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath], - { encoding: 'utf-8', timeout: 30_000, windowsHide: true }, - ); - if (result.status !== 0) { - throw new Error(`Receipt type probe failed: ${result.stderr || result.stdout}`); - } - } finally { - fs.rmSync(probeRoot, { recursive: true, force: true }); - } - }, - ); - it.runIf(process.platform === 'win32')( - 'executes sidecar source installed-bundle and publication provenance gates', - () => { - const certifier = fs - .readFileSync(path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), 'utf8') - .replace(/\r\n/g, '\n'); - const publisher = fs - .readFileSync(path.join(ROOT, 'scripts', 'publish-windows-release.ps1'), 'utf8') - .replace(/\r\n/g, '\n'); - const sliceFunctions = (source: string, start: string, end: string) => { - const startIndex = source.indexOf(start); - const endIndex = source.indexOf(end, startIndex + start.length); - expect(startIndex).toBeGreaterThanOrEqual(0); - expect(endIndex).toBeGreaterThan(startIndex); - return source.slice(startIndex, endIndex); - }; - const assertTrue = sliceFunctions( - certifier, - 'function Assert-True {', - '\nfunction Get-HttpStatusCode {', - ); - const sidecarHelpers = sliceFunctions( - certifier, - 'function Get-SidecarProvenance {', - '\nfunction Get-ExternalProfileRootSnapshot {', - ); - const publisherHelper = sliceFunctions( - publisher, - 'function Assert-ReceiptSourceHashes {', - '\nfunction Assert-ReleaseDoesNotExist {', - ); - const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-sidecar-binding-')); - const sourceContents = new Map([ - ['package-lock.json', '{"lockfileVersion":3}\n'], - ['package.json', '{"name":"binding-fixture"}\n'], - ['packages/server/package.json', '{"name":"@waggle/server"}\n'], - ['packages/server/src/local/service.ts', 'export const fixture = true;\n'], - ['packages/server/tsconfig.json', '{"extends":"../../tsconfig.base.json"}\n'], - ['scripts/build-sidecar.mjs', 'export {};\n'], - ['tsconfig.base.json', '{"compilerOptions":{"target":"ES2022"}}\n'], - ]); - const writeRelative = (relative: string, content: string | Buffer) => { - const target = path.join(fixtureRoot, ...relative.split('/')); - fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.writeFileSync(target, content); - return target; - }; - const hash = (value: string | Buffer) => createHash('sha256').update(value).digest('hex'); - const inputs = () => [...sourceContents.keys()] - .sort((left, right) => left < right ? -1 : left > right ? 1 : 0) - .map((relative) => ({ - path: relative, - sha256: hash(fs.readFileSync(path.join(fixtureRoot, ...relative.split('/')))), - })); - const serviceBytes = (revision: string, payload: string) => { - const payloadBytes = Buffer.from(payload, 'utf8'); - const manifest = { - schemaVersion: 1, - sourceRevision: revision, - entryPoint: 'packages/server/src/local/service.ts', - sourceInputs: inputs(), - bundlePayload: { sizeBytes: payloadBytes.byteLength, sha256: hash(payloadBytes) }, - }; - return Buffer.concat([ - Buffer.from( - `// Waggle-Sidecar-Provenance: ${Buffer.from(JSON.stringify(manifest)).toString('base64')}\n`, - 'utf8', - ), - payloadBytes, - ]); - }; - const run = (command: string, args: string[], cwd = fixtureRoot) => { - const result = spawnSync(command, args, { - cwd, - encoding: 'utf8', - timeout: 60_000, - windowsHide: true, - }); - expect(result.status, result.stderr || result.stdout).toBe(0); - return result; - }; - - try { - for (const [relative, content] of sourceContents) writeRelative(relative, content); - run('git', ['init']); - run('git', ['config', 'user.email', 'sidecar-fixture@waggle.invalid']); - run('git', ['config', 'user.name', 'Waggle Fixture']); - run('git', ['add', '--', ...sourceContents.keys()]); - run('git', ['commit', '-m', 'fixture']); - const revision = run('git', ['rev-parse', 'HEAD']).stdout.trim(); - const packagedPath = writeRelative('packaged-service.js', serviceBytes(revision, 'ok\n')); - const installedPath = writeRelative('installed-service.js', serviceBytes(revision, 'ok\n')); - const changedBundlePath = writeRelative( - 'changed-bundle.js', - serviceBytes(revision, 'changed\n'), - ); - const wrongRevisionPath = writeRelative( - 'wrong-revision.js', - serviceBytes('b'.repeat(40), 'ok\n'), - ); - const tamperedPath = writeRelative( - 'tampered-service.js', - Buffer.concat([serviceBytes(revision, 'ok\n'), Buffer.from('tampered\n')]), - ); - const probePath = writeRelative( - 'sidecar-probe.ps1', - `${String.raw`param( - [string]$Mode, - [string]$RepositoryRoot, - [string]$ExpectedRevision, - [string]$PackagedPath, - [string]$InstalledPath, - [string]$ChangedBundlePath, - [string]$WrongRevisionPath, - [string]$TamperedPath -) -`}${assertTrue}\n${sidecarHelpers}\n${String.raw` -$ErrorActionPreference = 'Stop' -Set-StrictMode -Version Latest -function Expect-Rejection { - param([scriptblock]$Action, [string]$Label) - $rejected = $false - try { & $Action } catch { $rejected = $true } - if (-not $rejected) { throw "$Label was accepted" } -} -$git = (Get-Command git -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source -if ($Mode -eq 'clean') { - $packaged = Get-SidecarProvenance $PackagedPath - $installed = Get-SidecarProvenance $InstalledPath - Assert-SidecarBundleBinding -Packaged $packaged -Installed $installed - Assert-SidecarSourceBinding -Provenance $packaged -RepositoryRoot $RepositoryRoot -ExpectedRevision $ExpectedRevision -GitExecutable $git -} elseif ($Mode -eq 'bundle-rejections') { - $packaged = Get-SidecarProvenance $PackagedPath - $changed = Get-SidecarProvenance $ChangedBundlePath - $wrongRevision = Get-SidecarProvenance $WrongRevisionPath - Expect-Rejection { Assert-SidecarBundleBinding -Packaged $packaged -Installed $changed } 'Changed bundle' - Expect-Rejection { Assert-SidecarBundleBinding -Packaged $packaged -Installed $wrongRevision } 'Changed provenance revision' - $wrongCount = Get-SidecarProvenance $InstalledPath - $wrongCount.sourceInputCount = [int]$wrongCount.sourceInputCount + 1 - Expect-Rejection { Assert-SidecarBundleBinding -Packaged $packaged -Installed $wrongCount } 'Changed input count' - Expect-Rejection { Get-SidecarProvenance $TamperedPath | Out-Null } 'Tampered payload' -} elseif ($Mode -eq 'source-rejection') { - $provenance = Get-SidecarProvenance $PackagedPath - Expect-Rejection { Assert-SidecarSourceBinding -Provenance $provenance -RepositoryRoot $RepositoryRoot -ExpectedRevision $ExpectedRevision -GitExecutable $git } 'Dirty or wrong-revision source' -} else { - throw 'Unknown probe mode' -} -`}`, - 'utf8', - ); - const powershell = powershellProbeExecutable(); - const probe = (mode: string, sourcePath = packagedPath) => run( - powershell, - [ - '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', probePath, - '-Mode', mode, - '-RepositoryRoot', fixtureRoot, - '-ExpectedRevision', revision, - '-PackagedPath', sourcePath, - '-InstalledPath', installedPath, - '-ChangedBundlePath', changedBundlePath, - '-WrongRevisionPath', wrongRevisionPath, - '-TamperedPath', tamperedPath, - ], - ); - probe('clean'); - probe('bundle-rejections'); - - const configRelative = 'packages/server/tsconfig.json'; - fs.appendFileSync( - path.join(fixtureRoot, ...configRelative.split('/')), - '// dirty transform config\n', - ); - const dirtyServicePath = writeRelative( - 'dirty-source-service.js', - serviceBytes(revision, 'ok\n'), - ); - probe('source-rejection', dirtyServicePath); - probe('source-rejection', wrongRevisionPath); - - const releaseInstaller = writeRelative( - 'target/release/bundle/nsis/Waggle.exe', - 'installer', - ); - const generatedInstaller = writeRelative( - 'target/release/nsis/installer.nsi', - 'generated installer', - ); - const certifierFixture = writeRelative( - 'scripts/certify-windows-installer.ps1', - 'certifier', - ); - const hookFixture = writeRelative('app/src-tauri/nsis/installer.nsi', 'hook'); - const currentSidecar = writeRelative( - 'app/src-tauri/resources/service.js', - serviceBytes(revision, 'ok\n'), - ); - const firstLine = fs.readFileSync(currentSidecar).subarray( - 0, - fs.readFileSync(currentSidecar).indexOf(0x0a), - ).toString('utf8'); - const provenanceBytes = Buffer.from( - firstLine.slice('// Waggle-Sidecar-Provenance: '.length), - 'base64', - ); - const receiptPath = writeRelative( - 'receipt.json', - JSON.stringify({ - evidence: { - certifierSha256: hash(fs.readFileSync(certifierFixture)), - installerHookSha256: hash(fs.readFileSync(hookFixture)), - generatedInstallerScriptSha256: hash(fs.readFileSync(generatedInstaller)), - sidecarBundleSha256: hash(fs.readFileSync(currentSidecar)), - sidecarProvenanceSha256: hash(provenanceBytes), - sidecarSourceRevision: revision, - sidecarSourceInputCount: inputs().length, - }, - }), - ); - const publisherProbePath = writeRelative( - 'publisher-probe.ps1', - `${String.raw`param([string]$FixtureRoot, [string]$InstallerPath, [string]$ReceiptPath, [string]$SourceRevision) -`}${publisherHelper}\n${String.raw` -$ErrorActionPreference = 'Stop' -Set-StrictMode -Version Latest -Set-Location -LiteralPath $FixtureRoot -function Expect-Rejection { - param([scriptblock]$Action, [string]$Label) - $rejected = $false - try { & $Action } catch { $rejected = $true } - if (-not $rejected) { throw "$Label was accepted" } -} -$installer = Get-Item -LiteralPath $InstallerPath -$receipt = Get-Content -Raw -LiteralPath $ReceiptPath | ConvertFrom-Json -Assert-ReceiptSourceHashes @($receipt) $installer $SourceRevision -foreach ($property in @('sidecarBundleSha256', 'sidecarProvenanceSha256', 'sidecarSourceRevision', 'sidecarSourceInputCount')) { - $changed = ($receipt | ConvertTo-Json -Depth 8 | ConvertFrom-Json) - if ($property -eq 'sidecarSourceInputCount') { $changed.evidence.$property = [int]$changed.evidence.$property + 1 } - elseif ($property -eq 'sidecarSourceRevision') { $changed.evidence.$property = ('f' * 40) } - else { $changed.evidence.$property = ('0' * 64) } - Expect-Rejection { Assert-ReceiptSourceHashes @($changed) $installer $SourceRevision } "Changed $property receipt" -} -$sidecarPath = Join-Path $FixtureRoot 'app/src-tauri/resources/service.js' -$original = [System.IO.File]::ReadAllBytes($sidecarPath) -[System.IO.File]::AppendAllText($sidecarPath, 'tampered') -try { - Expect-Rejection { Assert-ReceiptSourceHashes @($receipt) $installer $SourceRevision } 'Changed current bundle' -} finally { - [System.IO.File]::WriteAllBytes($sidecarPath, $original) -} -`}`, - 'utf8', - ); - run( - powershell, - [ - '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', publisherProbePath, - '-FixtureRoot', fixtureRoot, - '-InstallerPath', releaseInstaller, - '-ReceiptPath', receiptPath, - '-SourceRevision', revision, - ], - ); - } finally { - fs.rmSync(fixtureRoot, { recursive: true, force: true }); - } - }, - 120_000, - ); }); -describe('Windows installer certifier timeout contract', () => { - it('honors one bounded JSON GET timeout override and still fails closed', async () => { - if (process.platform !== 'win32') return; +describe('Release workflow (release.yml)', () => { + type Step = { name?: string; uses?: string; if?: string; run?: string; env?: Record }; + type Job = { + 'runs-on'?: string; + needs?: string; + if?: string; + permissions?: Record; + env?: Record; + strategy?: { matrix?: { include?: Array> } }; + steps?: Step[]; + }; + const WORKFLOW_PATH = path.join(ROOT, '.github', 'workflows', 'release.yml'); + const text = fs.readFileSync(WORKFLOW_PATH, 'utf-8'); + const workflow = parseYaml(text) as { + on?: { + push?: { tags?: string[]; branches?: string[] }; + pull_request?: { paths?: string[] }; + workflow_dispatch?: unknown; + }; + permissions?: Record; + jobs?: Record; + }; + const build = workflow.jobs?.build ?? {}; + const steps = build.steps ?? []; + const stepIndex = (name: string) => { + const index = steps.findIndex((step) => step.name === name); + expect(index, name).toBeGreaterThanOrEqual(0); + return index; + }; - const pwsh = powershellProbeExecutable(); - const script = fs.readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf-8', - ); - const helperStart = script.indexOf('function Invoke-JsonRequest {'); - const helperEnd = script.indexOf('\nfunction Invoke-JsonPostRequest {'); - expect(helperStart).toBeGreaterThanOrEqual(0); - expect(helperEnd).toBeGreaterThan(helperStart); - const helper = script.slice(helperStart, helperEnd); - - let responseDelayMs = 1_200; - const server = http.createServer((_request, response) => { - setTimeout(() => { - response.writeHead(200, { 'content-type': 'application/json' }); - response.end('{"ok":true}'); - }, responseDelayMs); - }); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); - const address = server.address(); - if (!address || typeof address === 'string') { - server.close(); - throw new Error('Could not bind delayed loopback probe server'); - } - const uri = `http://127.0.0.1:${address.port}/`; - const runProbe = (timeoutSeconds: number) => - new Promise((resolve, reject) => { - execFile( - pwsh, - [ - '-NoLogo', - '-NoProfile', - '-NonInteractive', - '-Command', - `${helper}\n$result = Invoke-JsonRequest -Uri '${uri}' -Headers @{} -TimeoutSeconds ${timeoutSeconds}\nif (-not $result.ok) { throw 'Unexpected JSON payload' }`, - ], - { encoding: 'utf-8', timeout: 10_000, windowsHide: true }, - (error) => (error ? reject(error) : resolve()), - ); - }); - - try { - await expect(runProbe(2)).resolves.toBeUndefined(); - responseDelayMs = 1_500; - await expect(runProbe(1)).rejects.toBeDefined(); - } finally { - await new Promise((resolve, reject) => { - server.close((error) => (error ? reject(error) : resolve())); - }); - } + it('builds the four release targets on runners of the matching architecture', () => { + expect(build.strategy?.matrix?.include).toEqual([ + { runner: 'windows-latest', rust_target: 'x86_64-pc-windows-msvc', release_target: 'windows-x64', arch: 'x64', bundles: 'nsis,msi' }, + { runner: 'macos-15', rust_target: 'aarch64-apple-darwin', release_target: 'macos-arm64', arch: 'arm64', bundles: 'app,dmg' }, + { runner: 'macos-15-intel', rust_target: 'x86_64-apple-darwin', release_target: 'macos-x64', arch: 'x64', bundles: 'app,dmg' }, + { runner: 'ubuntu-22.04', rust_target: 'x86_64-unknown-linux-gnu', release_target: 'linux-x64', arch: 'x64', bundles: 'deb,appimage' }, + ]); + expect(build['runs-on']).toBe('${{ matrix.runner }}'); + expect(build.env?.TARGET_ARCH).toBe('${{ matrix.arch }}'); + expect(steps[stepIndex('Verify runner architecture')].run).toContain('process.env.TARGET_ARCH'); + expect(steps[stepIndex('Install Linux system packages')].run).toContain('libwebkit2gtk-4.1-dev'); }); - it('retries one transient built-in proxy liveness timeout and stays bounded', async () => { - if (process.platform !== 'win32') return; - - const pwsh = powershellProbeExecutable(); - const script = fs.readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf-8', - ); - const helperStart = script.indexOf('function Invoke-JsonRequest {'); - const helperEnd = script.indexOf('\nfunction Invoke-JsonPostRequest {'); - expect(helperStart).toBeGreaterThanOrEqual(0); - expect(helperEnd).toBeGreaterThan(helperStart); - const helpers = script.slice(helperStart, helperEnd); - expect(helpers).toContain('function Invoke-BuiltInProxyLivenessProbe {'); - expect(helpers).toContain('[int]$AttemptTimeoutSeconds = 5'); - expect(helpers).toContain('[int]$MaxAttempts = 2'); - - const runProbe = (mode: 'recover' | 'fail') => - new Promise((resolve, reject) => { - const stub = mode === 'recover' - ? ` -$script:requestCount = 0 -function Invoke-JsonRequest { - param([string]$Uri, [int]$TimeoutSeconds) - $script:requestCount += 1 - if ($script:requestCount -eq 1) { throw 'simulated timeout' } - return [pscustomobject]@{ status = 'healthy' } -} -$result = Invoke-BuiltInProxyLivenessProbe -Uri 'http://127.0.0.1:1/' -AttemptTimeoutSeconds 1 -MaxAttempts 2 -RetryDelayMilliseconds 0 -if ($result.status -cne 'healthy') { throw 'Unexpected liveness payload' } -if ($script:requestCount -ne 2) { throw "Expected two liveness requests, got $script:requestCount" } -` - : ` -$script:requestCount = 0 -function Invoke-JsonRequest { - param([string]$Uri, [int]$TimeoutSeconds) - $script:requestCount += 1 - throw 'simulated timeout' -} -$failed = $false -try { - [void](Invoke-BuiltInProxyLivenessProbe -Uri 'http://127.0.0.1:1/' -AttemptTimeoutSeconds 1 -MaxAttempts 2 -RetryDelayMilliseconds 0) -} catch { - $failed = $true - if ($_.Exception.Message -cne 'simulated timeout') { throw } -} -if (-not $failed) { throw 'Persistent liveness failure was not rethrown' } -if ($script:requestCount -ne 2) { throw "Expected two liveness requests, got $script:requestCount" } -`; - execFile( - pwsh, - [ - '-NoLogo', - '-NoProfile', - '-NonInteractive', - '-Command', - `${helpers}\n${stub}`, - ], - { encoding: 'utf-8', timeout: 10_000, windowsHide: true }, - (error) => (error ? reject(error) : resolve()), - ); - }); - - await expect(runProbe('recover')).resolves.toBeUndefined(); - await expect(runProbe('fail')).resolves.toBeUndefined(); + it('runs on version tags, desktop pull requests and manual dispatch, replacing the PR build', () => { + expect(workflow.on?.push?.tags).toEqual(['v*']); + expect(workflow.on?.push?.branches).toBeUndefined(); + expect(workflow.on?.pull_request?.paths).toEqual(expect.arrayContaining([ + 'app/**', 'apps/web/**', 'packages/**', 'scripts/**', 'package.json', 'package-lock.json', + ])); + expect(workflow.on).toHaveProperty('workflow_dispatch'); + expect(fs.readdirSync(path.join(ROOT, '.github', 'workflows')).sort()).toEqual(['ci.yml', 'release.yml']); }); - it('retries only transient desktop session bootstrap failures and preserves the service log', async () => { - if (process.platform !== 'win32') return; + it('stages, checks and archives the sidecar, and smoke-tests it on every target', () => { + const order = [ + 'Install dependencies', + 'Build packages', + 'Build installer', + 'Bundle Node.js runtime', + 'Build sidecar', + 'Bundle native dependencies', + 'Stage sidecar dependencies', + 'Check sidecar resources', + 'Build web UI', + 'Build server archive', + 'Installer smoke test', + 'Build desktop app', + 'Desktop smoke test (Windows)', + 'Collect installers', + 'Upload build outputs', + ].map(stepIndex); + expect(order).toEqual([...order].sort((left, right) => left - right)); + for (const name of ['Check sidecar resources', 'Build server archive', 'Installer smoke test', 'Upload build outputs']) { + expect(steps[stepIndex(name)].if, name).toBeUndefined(); + } + expect(steps[stepIndex('Build server archive')].run).toBe('node scripts/build-server-archive.mjs'); + expect(steps[stepIndex('Installer smoke test')].run).toBe('node scripts/release-smoke.mjs installer'); - const pwsh = powershellProbeExecutable(); - const script = fs.readFileSync( - path.join(ROOT, 'scripts', 'certify-windows-installer.ps1'), - 'utf-8', - ); - const helperStart = script.indexOf('function Invoke-JsonRequest {'); - const helperEnd = script.indexOf('\nfunction Invoke-JsonPostRequest {'); - expect(helperStart).toBeGreaterThanOrEqual(0); - expect(helperEnd).toBeGreaterThan(helperStart); - const helpers = script.slice(helperStart, helperEnd); - const sessionHelperStart = helpers.indexOf('function Invoke-SessionTokenBootstrapProbe {'); - expect(sessionHelperStart).toBeGreaterThanOrEqual(0); - const sessionHelper = helpers.slice(sessionHelperStart); - expect(sessionHelper).toContain('[int]$AttemptTimeoutSeconds = 5'); - expect(sessionHelper).toContain('[int]$MaxAttempts = 2'); - expect(script).toContain( - '$tokenResponse = Invoke-SessionTokenBootstrapProbe `', - ); - expect(script).toContain( - "-Headers @{ 'x-waggle-desktop-bootstrap' = $bootstrapToken }", - ); - expect(script).toContain("$serviceLog = Join-Path $dataDir 'logs\\service.log'"); + // Every system builds its installers and runs the packaged app once. + const builds = steps.filter((step) => step.name?.startsWith('Build desktop app')); + expect(builds.map((step) => step.if).sort()).toEqual(["runner.os != 'macOS'", "runner.os == 'macOS'"]); + for (const step of builds) { + expect(step.run).toContain('node node_modules/@tauri-apps/cli/tauri.js build --target ${{ matrix.rust_target }}'); + expect(step.run).toContain('--bundles "${{ matrix.bundles }}"'); + } + const smokes = steps.filter((step) => step.name?.startsWith('Desktop smoke test')); + expect(smokes.map((step) => step.if)).toEqual([ + "runner.os == 'Windows'", + "runner.os == 'macOS'", + "runner.os == 'Linux'", + ]); + for (const step of smokes) expect(step.run).toContain('node scripts/release-smoke.mjs desktop --app'); + expect(smokes[2].run).toContain('xvfb-run'); - const runProbe = (mode: 'recover' | 'persistent' | 'forbidden') => - new Promise((resolve, reject) => { - const stub = ` -$script:requests = @() -function Invoke-JsonRequest { - param([string]$Uri, [hashtable]$Headers, [int]$TimeoutSeconds) - $script:requests += [pscustomobject]@{ - Uri = $Uri - Bootstrap = [string]$Headers['x-waggle-desktop-bootstrap'] - TimeoutSeconds = $TimeoutSeconds - } - if ('${mode}' -eq 'recover' -and $script:requests.Count -gt 1) { - return [pscustomobject]@{ token = 'certifier-session-token' } - } - if ('${mode}' -eq 'forbidden') { - $exception = [System.Exception]::new('simulated HTTP 403') - $exception | Add-Member -NotePropertyName Response -NotePropertyValue ( - [pscustomobject]@{ StatusCode = 403 } - ) - throw $exception - } - throw [System.Threading.Tasks.TaskCanceledException]::new('simulated timeout') -} -$failed = $false -try { - $result = Invoke-SessionTokenBootstrapProbe -Uri 'http://127.0.0.1:1/api/auth/session-token' -Headers @{ 'x-waggle-desktop-bootstrap' = 'sentinel-bootstrap' } -AttemptTimeoutSeconds 1 -MaxAttempts 2 -RetryDelayMilliseconds 0 - if ('${mode}' -ne 'recover') { throw 'Expected session bootstrap failure' } - if ($result.token -cne 'certifier-session-token') { throw 'Unexpected token payload' } -} catch { - $failed = $true - if ('${mode}' -eq 'recover') { throw } - if ('${mode}' -eq 'forbidden' -and [int]$_.Exception.Response.StatusCode -ne 403) { throw } -} -if ('${mode}' -ne 'recover' -and -not $failed) { throw 'Failure was not rethrown' } -$expectedCount = if ('${mode}' -eq 'forbidden') { 1 } else { 2 } -if ($script:requests.Count -ne $expectedCount) { - throw "Expected $expectedCount session bootstrap requests, got $($script:requests.Count)" -} -foreach ($request in $script:requests) { - if ($request.Uri -cne 'http://127.0.0.1:1/api/auth/session-token') { throw 'Session bootstrap URI was not forwarded' } - if ($request.Bootstrap -cne 'sentinel-bootstrap') { throw 'Session bootstrap header was not forwarded' } - if ($request.TimeoutSeconds -ne 1) { throw 'Session bootstrap timeout was not forwarded' } -} -`; - execFile( - pwsh, - [ - '-NoLogo', - '-NoProfile', - '-NonInteractive', - '-Command', - `Set-StrictMode -Version Latest\n${helpers}\n${stub}`, - ], - { encoding: 'utf-8', timeout: 10_000, windowsHide: true }, - (error) => (error ? reject(error) : resolve()), - ); - }); + const upload = steps[stepIndex('Upload build outputs')] as Step & { with?: Record }; + expect(upload.with?.name).toBe('waggle-${{ matrix.release_target }}'); + expect(upload.with?.path).toBe('artifacts/'); + expect(upload.with?.['if-no-files-found']).toBe('error'); + }); - await expect(runProbe('recover')).resolves.toBeUndefined(); - await expect(runProbe('persistent')).resolves.toBeUndefined(); - await expect(runProbe('forbidden')).resolves.toBeUndefined(); + it('signs nothing and uses no secret but GITHUB_TOKEN', () => { + const secrets = [...text.matchAll(/secrets\.([A-Za-z0-9_]+)/g)].map((match) => match[1]); + expect(new Set(secrets)).toEqual(new Set(['GITHUB_TOKEN'])); + const code = text.split('\n').filter((line) => !line.trim().startsWith('#')).join('\n'); + expect(code).not.toMatch(/azure|id-token|attest|notari[sz]|signtool|TAURI_SIGNING|TAURI_PRIVATE_KEY|APPLE_|certificate|\.pfx|codesign/i); + // The only signature is macOS's ad-hoc one, which takes no identity. + expect([...text.matchAll(/"signingIdentity":"([^"]*)"/g)].map((match) => match[1])).toEqual(['-']); + expect(workflow.permissions).toEqual({ contents: 'read' }); + expect(build.permissions).toBeUndefined(); + }); + + it('publishes only for pushed v* tags, and only as a draft with SHA256SUMS', () => { + const publish = workflow.jobs?.publish ?? {}; + expect(publish.needs).toBe('build'); + expect(publish.if).toBe("github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')"); + expect(publish.permissions).toEqual({ contents: 'write' }); + const publishSteps = publish.steps ?? []; + const sums = publishSteps.findIndex((step) => step.name === 'Write SHA256SUMS'); + const create = publishSteps.findIndex((step) => step.name === 'Create draft release'); + expect(sums).toBeGreaterThanOrEqual(0); + expect(create).toBeGreaterThan(sums); + expect(publishSteps[sums].run).toContain('sha256sum'); + expect(publishSteps[create].run).toMatch(/^gh release create "\$TAG" release\/\* --draft /); + expect(publishSteps[create].env?.GH_TOKEN).toBe('${{ secrets.GITHUB_TOKEN }}'); + expect([...text.matchAll(/gh release/g)]).toHaveLength(1); + }); + + it('pins every action to a full commit SHA', () => { + const actionRefs = [...text.matchAll(/uses:\s+[^@\s]+@([^\s#]+)/g)].map((match) => match[1]); + expect(actionRefs.length).toBeGreaterThan(0); + for (const actionRef of actionRefs) expect(actionRef).toMatch(/^[0-9a-f]{40}$/); + }); + + it('local build scripts stage the sidecar before tauri build on every system', () => { + const manifest = JSON.parse( + fs.readFileSync(path.join(ROOT, 'app', 'package.json'), 'utf-8'), + ) as { scripts: Record }; + const targets = { + 'tauri:build:win': 'x86_64-pc-windows-msvc', + 'tauri:build:mac:arm64': 'aarch64-apple-darwin', + 'tauri:build:mac:x64': 'x86_64-apple-darwin', + 'tauri:build:linux': 'x86_64-unknown-linux-gnu', + }; + for (const [name, triple] of Object.entries(targets)) { + const command = manifest.scripts[name] ?? ''; + expect(command.indexOf('stage-sidecar-deps.mjs'), name).toBeGreaterThanOrEqual(0); + expect(command.indexOf('npx tauri build'), name).toBeGreaterThan(command.indexOf('stage-sidecar-deps.mjs')); + expect(command, name).toContain(`--target ${triple}`); + } + expect(Object.keys(manifest.scripts).filter((name) => /sign/.test(name))).toEqual([]); + const conf = JSON.parse(fs.readFileSync(path.join(TAURI_DIR, 'tauri.conf.json'), 'utf-8')); + expect(conf.build.beforeBuildCommand).toContain('check-sidecar-resources.mjs'); }); }); diff --git a/scripts/certify-windows-installer.ps1 b/scripts/certify-windows-installer.ps1 deleted file mode 100644 index 3ef3b57..0000000 --- a/scripts/certify-windows-installer.ps1 +++ /dev/null @@ -1,3422 +0,0 @@ -#Requires -Version 7.0 - -[CmdletBinding()] -param( - [Parameter(Mandatory = $true)] - [string]$InstallerPath, - - [ValidateRange(30, 600)] - [int]$StartupTimeoutSeconds = 150, - - [string]$ReceiptPath, - - [switch]$KeepArtifacts, - - [switch]$RequireAuthenticodeSignature, - - [string]$ExpectedSignerThumbprint, - - [string]$ExpectedSignerSubject, - - [string]$ExpectedSourceRevision, - - [int]$WebViewDebugPort = 0, - - [switch]$VerifyManagedModel, - - [switch]$RequireVersionToVersionUpgrade, - - [string]$PreviousInstallerPath, - - [string]$ExpectedPreviousInstallerSha256, - - [string]$ExpectedPreviousVersion, - - [string]$ExpectedPreviousSourceRevision, - - [string]$ExpectedCandidateInstallerSha256, - - [string]$ExpectedCandidateVersion -) - -Set-StrictMode -Version Latest -$ErrorActionPreference = 'Stop' - -function Assert-True { - param( - [Parameter(Mandatory = $true)] [bool]$Condition, - [Parameter(Mandatory = $true)] [string]$Message - ) - if (-not $Condition) { throw $Message } -} - -function Assert-CleanRepositoryWorktree { - param( - [Parameter(Mandatory = $true)] [string]$GitExecutable, - [Parameter(Mandatory = $true)] [string]$RepositoryRoot - ) - - $sourceStatus = @( - & $GitExecutable -C $RepositoryRoot status --porcelain=v1 --untracked-files=all - ) - if ($LASTEXITCODE -ne 0) { - throw 'Could not inspect the repository source state.' - } - if ($sourceStatus.Count -ne 0) { - $sourceDetails = ($sourceStatus | ForEach-Object { [string]$_ }) -join [Environment]::NewLine - throw "Installer certification requires the complete repository worktree to match the expected revision.$([Environment]::NewLine)$sourceDetails" - } -} - -function Test-CertificateTimestamp { - param([AllowNull()] [object]$Value) - - if ($null -eq $Value) { return $false } - if ($Value -is [DateTime] -or $Value -is [DateTimeOffset]) { return $true } - - $text = [string]$Value - if ([string]::IsNullOrWhiteSpace($text)) { return $false } - - $parsed = [DateTimeOffset]::MinValue - return [DateTimeOffset]::TryParse( - $text, - [Globalization.CultureInfo]::InvariantCulture, - [Globalization.DateTimeStyles]::RoundtripKind, - [ref]$parsed - ) -} - -function Assert-ExpectedAuthenticodeSignature { - param( - [Parameter(Mandatory = $true)] [object]$Signature, - [AllowEmptyString()] [string]$ExpectedThumbprint, - [AllowEmptyString()] [string]$ExpectedSubject, - [Parameter(Mandatory = $true)] [string]$ArtifactLabel - ) - - $hasExpectedThumbprint = -not [string]::IsNullOrWhiteSpace($ExpectedThumbprint) - $hasExpectedSubject = -not [string]::IsNullOrWhiteSpace($ExpectedSubject) - Assert-True ($hasExpectedThumbprint -xor $hasExpectedSubject) ` - 'Exactly one expected signer identity binding is required.' - Assert-True ([string]$Signature.SignatureType -eq 'Authenticode') ` - "$ArtifactLabel does not contain a portable embedded Authenticode signature." - Assert-True ($Signature.Status -eq [System.Management.Automation.SignatureStatus]::Valid) ` - "$ArtifactLabel Authenticode signature is not valid: $($Signature.Status)" - Assert-True ($null -ne $Signature.SignerCertificate) ` - "$ArtifactLabel has no Authenticode signer certificate." - if ($hasExpectedThumbprint) { - $normalizedExpectedThumbprint = ($ExpectedThumbprint -replace '\s', '').ToUpperInvariant() - Assert-True ($normalizedExpectedThumbprint -match '^[0-9A-F]{40}$') ` - 'Expected signer thumbprint must be exactly 40 hexadecimal characters.' - Assert-True ( - [string]::Equals( - ($Signature.SignerCertificate.Thumbprint -replace '\s', '').ToUpperInvariant(), - $normalizedExpectedThumbprint, - [System.StringComparison]::Ordinal - ) - ) "$ArtifactLabel signer does not match the imported production certificate." - } else { - Assert-True ( - [string]::Equals( - [string]$Signature.SignerCertificate.Subject, - $ExpectedSubject, - [System.StringComparison]::Ordinal - ) - ) "$ArtifactLabel signer subject does not match the approved production identity." - } - Assert-True ($null -ne $Signature.TimeStamperCertificate) ` - "$ArtifactLabel has no validated Authenticode timestamp certificate." -} - -function Assert-LifecycleReceiptApprovedSigner { - param( - [Parameter(Mandatory = $true)] [object]$Receipt, - [AllowEmptyString()] [string]$ExpectedThumbprint, - [AllowEmptyString()] [string]$ExpectedSubject - ) - - $hasExpectedThumbprint = -not [string]::IsNullOrWhiteSpace($ExpectedThumbprint) - $hasExpectedSubject = -not [string]::IsNullOrWhiteSpace($ExpectedSubject) - Assert-True ($hasExpectedThumbprint -xor $hasExpectedSubject) ` - 'Exactly one expected signer identity binding is required.' - $expectedSigner = if ($hasExpectedSubject) { - $ExpectedSubject - } else { - $normalizedExpectedThumbprint = ($ExpectedThumbprint -replace '\s', '').ToUpperInvariant() - Assert-True ($normalizedExpectedThumbprint -match '^[0-9A-F]{40}$') ` - 'Expected signer thumbprint must be exactly 40 hexadecimal characters.' - $normalizedExpectedThumbprint - } - $comparison = if ($hasExpectedSubject) { - [System.StringComparison]::Ordinal - } else { - [System.StringComparison]::OrdinalIgnoreCase - } - foreach ($artifact in @( - $Receipt.previousInstaller, - $Receipt.previousInstalledApp, - $Receipt.installer, - $Receipt.installedApp - )) { - $actualSigner = if ($hasExpectedSubject) { - [string]$artifact.signerSubject - } else { - [string]$artifact.signerThumbprint - } - Assert-True ([string]::Equals( - $actualSigner, - $expectedSigner, - $comparison - )) 'Previous and candidate artifacts are not signed by the same approved signer.' - } -} - -function ConvertTo-StrictSemanticVersion { - param( - [Parameter(Mandatory = $true)] [string]$Value, - [Parameter(Mandatory = $true)] [string]$Label - ) - - Assert-True ($Value -match '^\d+\.\d+\.\d+$') ` - "$Label must use strict numeric x.y.z format." - return [version]$Value -} - -function Get-InstalledProductVersion { - param( - [Parameter(Mandatory = $true)] [string]$ExecutablePath, - [Parameter(Mandatory = $true)] [string]$ArtifactLabel - ) - - $rawVersion = [string](Get-Item -LiteralPath $ExecutablePath).VersionInfo.ProductVersion - Assert-True (-not [string]::IsNullOrWhiteSpace($rawVersion)) ` - "$ArtifactLabel has no embedded product version." - Assert-True ($rawVersion -match '^(?\d+\.\d+\.\d+)(?:\.0)?(?:[+-].*)?$') ` - "$ArtifactLabel product version is not a supported x.y.z value: $rawVersion" - return [ordered]@{ - raw = $rawVersion - normalized = $Matches['version'] - } -} - -function New-AuthenticodeArtifactReceipt { - param( - [Parameter(Mandatory = $true)] [System.IO.FileInfo]$File, - [Parameter(Mandatory = $true)] [object]$Signature - ) - - $artifact = [ordered]@{ - name = $File.Name - sha256 = (Get-FileHash -LiteralPath $File.FullName -Algorithm SHA256).Hash - sizeBytes = $File.Length - authenticodeStatus = [string]$Signature.Status - signatureType = [string]$Signature.SignatureType - signerSubject = $null - signerThumbprint = $null - timestampAuthoritySubject = $null - timestampAuthorityThumbprint = $null - timestampAuthorityNotBefore = $null - timestampAuthorityNotAfter = $null - } - if ($Signature.SignerCertificate) { - $artifact.signerSubject = $Signature.SignerCertificate.Subject - $artifact.signerThumbprint = $Signature.SignerCertificate.Thumbprint - } - if ($Signature.TimeStamperCertificate) { - $artifact.timestampAuthoritySubject = $Signature.TimeStamperCertificate.Subject - $artifact.timestampAuthorityThumbprint = $Signature.TimeStamperCertificate.Thumbprint - $artifact.timestampAuthorityNotBefore = $Signature.TimeStamperCertificate.NotBefore.ToUniversalTime().ToString('o') - $artifact.timestampAuthorityNotAfter = $Signature.TimeStamperCertificate.NotAfter.ToUniversalTime().ToString('o') - } - return $artifact -} - -function Assert-ArtifactIdentity { - param( - [Parameter(Mandatory = $true)] [string]$FilePath, - [Parameter(Mandatory = $true)] [string]$ExpectedSha256, - [AllowEmptyString()] [string]$ExpectedSignerThumbprint, - [AllowEmptyString()] [string]$ExpectedSignerSubject, - [Parameter(Mandatory = $true)] [string]$ArtifactLabel - ) - - Assert-True (Test-Path -LiteralPath $FilePath -PathType Leaf) ` - "$ArtifactLabel is missing." - $actualSha256 = (Get-FileHash -LiteralPath $FilePath -Algorithm SHA256).Hash - Assert-True ([string]::Equals( - $actualSha256, - $ExpectedSha256, - [System.StringComparison]::OrdinalIgnoreCase - )) "$ArtifactLabel SHA-256 changed during certification." - $signature = Get-AuthenticodeSignature -LiteralPath $FilePath - Assert-ExpectedAuthenticodeSignature ` - $signature $ExpectedSignerThumbprint $ExpectedSignerSubject $ArtifactLabel -} - -function Get-FreeTcpPort { - $listener = [System.Net.Sockets.TcpListener]::new( - [System.Net.IPAddress]::Loopback, - 0 - ) - try { - $listener.Start() - return ([System.Net.IPEndPoint]$listener.LocalEndpoint).Port - } finally { - $listener.Stop() - } -} - -function Assert-TcpPortAvailable { - param([Parameter(Mandatory = $true)] [int]$Port) - - Assert-True (Test-TcpPortAvailable $Port) ` - "Required desktop port $Port is already in use; refusing to disturb another service." -} - -function Assert-VaultKeyAclRestricted { - param([Parameter(Mandatory = $true)] [string]$KeyPath) - - Assert-True (Test-Path -LiteralPath $KeyPath -PathType Leaf) ` - 'Windows vault key was not created during first boot.' - $acl = Get-Acl -LiteralPath $KeyPath - Assert-True ($acl.AreAccessRulesProtected) ` - 'Windows vault key still inherits filesystem permissions.' - - $currentSid = [Security.Principal.WindowsIdentity]::GetCurrent().User - Assert-True ($null -ne $currentSid) 'Could not resolve the current Windows security identifier.' - $ownerSid = $acl.GetOwner([Security.Principal.SecurityIdentifier]) - Assert-True ([string]::Equals( - $ownerSid.Value, - $currentSid.Value, - [System.StringComparison]::OrdinalIgnoreCase - )) 'Windows vault key is not owned by the current user.' - $rules = @( - $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]) - ) - Assert-True ($rules.Count -eq 1) ` - "Windows vault key must have exactly one access rule; found $($rules.Count)." - $allowRules = @( - $rules | - Where-Object { - $_.AccessControlType -eq [Security.AccessControl.AccessControlType]::Allow - } - ) - $currentUserAllows = @( - $allowRules | Where-Object { - [string]::Equals( - $_.IdentityReference.Value, - $currentSid.Value, - [System.StringComparison]::OrdinalIgnoreCase - ) - } - ) - $unexpectedAllows = @( - $allowRules | Where-Object { - -not [string]::Equals( - $_.IdentityReference.Value, - $currentSid.Value, - [System.StringComparison]::OrdinalIgnoreCase - ) - } - ) - $unexpectedPrincipals = @( - $unexpectedAllows | ForEach-Object { $_.IdentityReference.Value } - ) - Assert-True ($unexpectedAllows.Count -eq 0) ` - "Windows vault key grants access to unexpected principals: $($unexpectedPrincipals -join ', ')" - $fullControl = [Security.AccessControl.FileSystemRights]::FullControl - $hasCurrentUserFullControl = @( - $currentUserAllows | Where-Object { - ($_.FileSystemRights -band $fullControl) -eq $fullControl - } - ).Count -gt 0 - Assert-True $hasCurrentUserFullControl ` - 'Windows vault key does not grant the current user full control.' -} - -function Test-TcpPortAvailable { - param([Parameter(Mandatory = $true)] [int]$Port) - - $listener = [System.Net.Sockets.TcpListener]::new( - [System.Net.IPAddress]::Loopback, - $Port - ) - try { - $listener.Start() - return $true - } catch { - return $false - } finally { - $listener.Stop() - } -} - -function Stop-StartedProcessTree { - param([Parameter(Mandatory = $true)] [System.Diagnostics.Process]$Process) - - $taskkill = Join-Path $env:SystemRoot 'System32\taskkill.exe' - $killInfo = [System.Diagnostics.ProcessStartInfo]::new() - $killInfo.FileName = $taskkill - $killInfo.Arguments = "/PID $($Process.Id) /T /F" - $killInfo.UseShellExecute = $false - $killInfo.CreateNoWindow = $true - $killInfo.RedirectStandardOutput = $true - $killInfo.RedirectStandardError = $true - $killInfo.WorkingDirectory = Split-Path -Parent $taskkill - - $killProcess = [System.Diagnostics.Process]::new() - $killProcess.StartInfo = $killInfo - try { - Assert-True ($killProcess.Start()) "Could not start taskkill for process $($Process.Id)" - Assert-True ($killProcess.WaitForExit(20000)) "Timed out terminating process tree $($Process.Id)" - $killProcess.WaitForExit() - if ($killProcess.ExitCode -ne 0) { - $detail = $killProcess.StandardError.ReadToEnd().Trim() - throw "Could not terminate process tree $($Process.Id): $detail" - } - Assert-True ($Process.WaitForExit(20000)) "Process tree root $($Process.Id) did not exit" - } finally { - $killProcess.Dispose() - } -} - -function Remove-CertificationControlEnvironment { - param([Parameter(Mandatory = $true)] [System.Diagnostics.ProcessStartInfo]$Info) - - $explicitNames = @( - 'CI', 'GH_TOKEN', 'GITHUB_TOKEN', - 'WINDOWS_CODESIGN_PFX_BASE64', 'WINDOWS_CODESIGN_PFX_PASSWORD', - 'WINDOWS_CODESIGN_APPROVED_SUBJECT', 'WINDOWS_CODESIGN_APPROVED_THUMBPRINT', - 'WINDOWS_UPGRADE_BASE_SHA256', 'WAGGLE_APPROVED_CODESIGN_SUBJECT', - 'WAGGLE_APPROVED_CODESIGN_THUMBPRINT', 'WAGGLE_CODESIGN_SUBJECT', - 'WAGGLE_CODESIGN_THUMBPRINT', 'WAGGLE_RELEASE_VERSION' - ) - foreach ($name in @($Info.Environment.Keys)) { - if ($name -match '^(?:ACTIONS_|GITHUB_|RUNNER_|WAGGLE_UPGRADE_BASE_)' -or - $explicitNames -contains $name) { - $null = $Info.Environment.Remove($name) - } - } -} - -function Test-TcpPortHasListener { - param([Parameter(Mandatory = $true)] [int]$Port) - - return @( - [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().GetActiveTcpListeners() | - Where-Object { $_.Port -eq $Port } - ).Count -gt 0 -} - -function Invoke-RawProcess { - param( - [Parameter(Mandatory = $true)] [string]$FilePath, - [Parameter(Mandatory = $true)] [string]$Arguments, - [ValidateRange(1, 900)] [int]$TimeoutSeconds = 300 - ) - - $info = [System.Diagnostics.ProcessStartInfo]::new() - $info.FileName = $FilePath - $info.Arguments = $Arguments - $info.UseShellExecute = $false - $info.CreateNoWindow = $true - $info.WorkingDirectory = Split-Path -Parent $FilePath - Remove-CertificationControlEnvironment $info - - $process = [System.Diagnostics.Process]::new() - $process.StartInfo = $info - try { - Assert-True ($process.Start()) "Could not start $FilePath" - if (-not $process.WaitForExit($TimeoutSeconds * 1000)) { - Stop-StartedProcessTree $process - throw "Timed out after ${TimeoutSeconds}s: $FilePath $Arguments" - } - $process.WaitForExit() - if ($process.ExitCode -ne 0) { - throw "Process exited $($process.ExitCode): $FilePath $Arguments" - } - } finally { - $process.Dispose() - } -} - -function Start-InstalledApp { - param( - [Parameter(Mandatory = $true)] [string]$ExecutablePath, - [ValidateRange(1024, 65535)] [int]$DebugPort = 0 - ) - - $info = [System.Diagnostics.ProcessStartInfo]::new() - $info.FileName = $ExecutablePath - $info.UseShellExecute = $false - $info.WorkingDirectory = Split-Path -Parent $ExecutablePath - Remove-CertificationControlEnvironment $info - if ($DebugPort -gt 0) { - $info.Environment['WAGGLE_CERTIFIER_WEBVIEW_DEBUG_PORT'] = [string]$DebugPort - } - $process = [System.Diagnostics.Process]::new() - $process.StartInfo = $info - Assert-True ($process.Start()) "Could not start installed Waggle: $ExecutablePath" - return $process -} - -function Invoke-JsonRequest { - param( - [Parameter(Mandatory = $true)] [string]$Uri, - [hashtable]$Headers = @{}, - [ValidateRange(1, 30)] [int]$TimeoutSeconds = 5 - ) - - return Invoke-RestMethod -Uri $Uri -Method Get -Headers $Headers -TimeoutSec $TimeoutSeconds -} - -function Invoke-BuiltInProxyLivenessProbe { - param( - [Parameter(Mandatory = $true)] [string]$Uri, - [ValidateRange(1, 30)] [int]$AttemptTimeoutSeconds = 5, - [ValidateRange(1, 2)] [int]$MaxAttempts = 2, - [ValidateRange(0, 2000)] [int]$RetryDelayMilliseconds = 250 - ) - - for ($attempt = 1; $attempt -le $MaxAttempts; $attempt += 1) { - try { - return Invoke-JsonRequest -Uri $Uri -TimeoutSeconds $AttemptTimeoutSeconds - } catch { - if ($attempt -ge $MaxAttempts) { throw } - if ($RetryDelayMilliseconds -gt 0) { - Start-Sleep -Milliseconds $RetryDelayMilliseconds - } - } - } -} - -function Test-TransientLoopbackRequestFailure { - param( - [Parameter(Mandatory = $true)] - [System.Management.Automation.ErrorRecord]$ErrorRecord - ) - - $responseProperty = $ErrorRecord.Exception.PSObject.Properties['Response'] - if ($null -ne $responseProperty) { - $response = $responseProperty.Value - try { - return @(408, 425, 429, 500, 502, 503, 504) -contains [int]$response.StatusCode - } catch { - return $false - } - } - - $exception = $ErrorRecord.Exception - return ( - $exception -is [System.Net.Http.HttpRequestException] -or - $exception -is [System.Net.WebException] -or - $exception -is [System.Threading.Tasks.TaskCanceledException] -or - $exception -is [System.TimeoutException] - ) -} - -function Invoke-SessionTokenBootstrapProbe { - param( - [Parameter(Mandatory = $true)] [string]$Uri, - [hashtable]$Headers = @{}, - [ValidateRange(1, 30)] [int]$AttemptTimeoutSeconds = 5, - [ValidateRange(1, 2)] [int]$MaxAttempts = 2, - [ValidateRange(0, 2000)] [int]$RetryDelayMilliseconds = 250 - ) - - for ($attempt = 1; $attempt -le $MaxAttempts; $attempt += 1) { - try { - return Invoke-JsonRequest ` - -Uri $Uri ` - -Headers $Headers ` - -TimeoutSeconds $AttemptTimeoutSeconds - } catch { - if ( - $attempt -ge $MaxAttempts -or - -not (Test-TransientLoopbackRequestFailure -ErrorRecord $_) - ) { - throw - } - if ($RetryDelayMilliseconds -gt 0) { - Start-Sleep -Milliseconds $RetryDelayMilliseconds - } - } - } -} - -function Invoke-JsonPostRequest { - param( - [Parameter(Mandatory = $true)] [string]$Uri, - [Parameter(Mandatory = $true)] [hashtable]$Body, - [hashtable]$Headers = @{}, - [ValidateRange(1, 3600)] [int]$TimeoutSeconds = 30 - ) - - $json = $Body | ConvertTo-Json -Compress -Depth 8 - return Invoke-WebRequest ` - -Uri $Uri ` - -Method Post ` - -Headers $Headers ` - -ContentType 'application/json; charset=utf-8' ` - -Body ([System.Text.Encoding]::UTF8.GetBytes($json)) ` - -TimeoutSec $TimeoutSeconds ` - -UseBasicParsing -} - -function Get-CertificateSessionHeaders { - param( - [Parameter(Mandatory = $true)] [string]$BaseUrl, - [Parameter(Mandatory = $true)] [string]$NodeExecutable, - [Parameter(Mandatory = $true)] [string]$BootstrapHelperPath, - [ValidateRange(1024, 65535)] [int]$DebugPort, - [switch]$AllowLegacyUi - ) - - Assert-True (Test-Path -LiteralPath $BootstrapHelperPath -PathType Leaf) ` - 'Tauri bootstrap helper is missing.' - $stderrPath = Join-Path ([System.IO.Path]::GetTempPath()) ` - "waggle-bootstrap-token-$([Guid]::NewGuid().ToString('N')).stderr.log" - $tokenResponse = $null - try { - $helperArguments = @( - '--experimental-websocket', - $BootstrapHelperPath, - '--port', - [string]$DebugPort, - '--timeout-ms', - '60000' - ) - if ($AllowLegacyUi) { $helperArguments += '--allow-legacy-ui' } - $tokenJson = & $NodeExecutable @helperArguments 2> $stderrPath - $tokenExitCode = $LASTEXITCODE - $tokenErrorRaw = if (Test-Path -LiteralPath $stderrPath) { - Get-Content -Raw -LiteralPath $stderrPath - } else { - '' - } - $tokenError = (@($tokenErrorRaw) -join [Environment]::NewLine).Trim() - Assert-True ($tokenExitCode -eq 0) ` - "Tauri bootstrap IPC helper failed: $tokenError" - $tokenJsonText = ([string](@($tokenJson) -join [Environment]::NewLine)).Trim() - $tokenPayload = $null - if (-not [string]::IsNullOrWhiteSpace($tokenJsonText)) { - try { - $tokenPayload = ConvertFrom-Json -InputObject $tokenJsonText -ErrorAction Stop - } catch { - $tokenPayload = $null - } - } - Assert-True ($null -ne $tokenPayload) ` - 'Tauri bootstrap IPC helper returned invalid JSON output.' - $bootstrapTokenProperty = $tokenPayload.PSObject.Properties['bootstrapToken'] - Assert-True ($null -ne $bootstrapTokenProperty) ` - 'Tauri bootstrap IPC helper returned no credential field.' - $uiReadyProperty = $tokenPayload.PSObject.Properties['uiReady'] - $uiStartupStateProperty = $tokenPayload.PSObject.Properties['uiStartupState'] - $uiPathProperty = $tokenPayload.PSObject.Properties['uiPath'] - $uiTextLengthProperty = $tokenPayload.PSObject.Properties['uiTextLength'] - Assert-True ( - $null -ne $uiReadyProperty -and - $uiReadyProperty.Value -is [bool] -and - $uiReadyProperty.Value - ) 'Installed Waggle WebView did not render its application shell.' - Assert-True ( - $null -ne $uiStartupStateProperty -and - $uiStartupStateProperty.Value -is [string] -and - [string]$uiStartupStateProperty.Value -ceq $( - if ($AllowLegacyUi) { 'legacy-ready' } else { 'ready' } - ) - ) 'Installed Waggle WebView did not commit its application shell.' - Assert-True ( - $null -ne $uiPathProperty -and - $uiPathProperty.Value -is [string] -and - ([string]$uiPathProperty.Value).StartsWith('/') - ) 'Installed Waggle WebView returned an invalid application route.' - Assert-True ( - $null -ne $uiTextLengthProperty -and - ($uiTextLengthProperty.Value -is [int] -or $uiTextLengthProperty.Value -is [long]) -and - [long]$uiTextLengthProperty.Value -gt 0 - ) 'Installed Waggle WebView rendered no visible application content.' - $bootstrapToken = [string]$bootstrapTokenProperty.Value - Assert-True ($bootstrapToken.Length -ge 32 -and $bootstrapToken.Length -le 200) ` - 'Tauri bootstrap IPC helper returned an invalid credential.' - $tokenResponse = Invoke-SessionTokenBootstrapProbe ` - -Uri "$BaseUrl/api/auth/session-token" ` - -Headers @{ 'x-waggle-desktop-bootstrap' = $bootstrapToken } - } finally { - if (Test-Path -LiteralPath $stderrPath) { - Remove-Item -LiteralPath $stderrPath -Force -ErrorAction SilentlyContinue - } - } - Assert-True ($null -ne $tokenResponse) ` - 'Session-token bootstrap returned no JSON response.' - $sessionTokenProperty = $tokenResponse.PSObject.Properties['token'] - Assert-True ($null -ne $sessionTokenProperty) ` - 'Session-token bootstrap returned no token field.' - $sessionToken = [string]$sessionTokenProperty.Value - Assert-True (-not [string]::IsNullOrWhiteSpace($sessionToken)) ` - 'Session-token bootstrap returned no token.' - return @{ Authorization = "Bearer $sessionToken" } -} - -function Assert-CertificateLifecycleData { - param( - [Parameter(Mandatory = $true)] [string]$BaseUrl, - [Parameter(Mandatory = $true)] [hashtable]$Headers, - [Parameter(Mandatory = $true)] [object]$State, - [Parameter(Mandatory = $true)] [string]$DataDir - ) - - $escapedWorkspaceId = [uri]::EscapeDataString([string]$State.workspaceId) - $workspace = Invoke-JsonRequest "$BaseUrl/api/workspaces/$escapedWorkspaceId" $Headers - Assert-True ([string]$workspace.id -ceq [string]$State.workspaceId) ` - 'Persisted workspace id changed or disappeared.' - Assert-True ([string]$workspace.name -ceq [string]$State.workspaceName) ` - 'Persisted workspace name changed or disappeared.' - Assert-True ([string]$workspace.group -ceq [string]$State.workspaceGroup) ` - 'Persisted workspace group changed or disappeared.' - - $personalList = Invoke-JsonRequest "$BaseUrl/api/memory/frames?limit=200" $Headers - $personalResults = @($personalList.results) - Assert-True ([long]$personalList.count -eq $personalResults.Count) ` - 'Personal memory response count does not match its result set.' - $personalMatches = @($personalResults | Where-Object { - [long]$_.id -eq [long]$State.personalFrameId -and - [string]$_.mind -ceq 'personal' -and - [string]$_.source_mind -ceq 'personal' -and - [string]$_.content -ceq [string]$State.personalContent - }) - Assert-True ($personalMatches.Count -eq 1) ` - 'Persisted personal memory marker is missing or ambiguous.' - - $workspaceList = Invoke-JsonRequest ` - "$BaseUrl/api/memory/frames?workspaceId=$escapedWorkspaceId&limit=200" ` - $Headers - $workspaceResults = @($workspaceList.results) - Assert-True ([long]$workspaceList.count -eq $workspaceResults.Count) ` - 'Workspace memory response count does not match its result set.' - $workspaceMatches = @($workspaceResults | Where-Object { - [long]$_.id -eq [long]$State.workspaceFrameId -and - [string]$_.mind -ceq 'workspace' -and - [string]$_.source_mind -ceq 'workspace' -and - [string]$_.content -ceq [string]$State.workspaceContent - }) - Assert-True ($workspaceMatches.Count -eq 1) ` - 'Persisted workspace memory marker is missing or ambiguous.' - - foreach ($frame in @($personalMatches[0], $workspaceMatches[0])) { - Assert-True ([string]$frame.source -ceq 'tool_verified') ` - 'Persisted lifecycle memory lost its provenance.' - Assert-True ([string]$frame.importance -ceq 'important') ` - 'Persisted lifecycle memory lost its importance.' - Assert-True (@('I', 'P', 'B') -contains [string]$frame.frameType) ` - 'Persisted lifecycle memory returned an invalid frame type.' - Assert-True (Test-CertificateTimestamp $frame.timestamp) ` - 'Persisted lifecycle memory returned an invalid timestamp.' - $parsedAccessCount = 0L - Assert-True ([long]::TryParse([string]$frame.accessCount, [ref]$parsedAccessCount)) ` - 'Persisted lifecycle memory returned an invalid access count.' - } - - $workspaceDir = Join-Path $DataDir "workspaces\$($State.workspaceId)" - foreach ($path in @( - (Join-Path $DataDir 'personal.mind'), - (Join-Path $workspaceDir 'workspace.json'), - (Join-Path $workspaceDir 'workspace.mind') - )) { - Assert-True (Test-Path -LiteralPath $path -PathType Leaf) ` - "Lifecycle data file is missing: $path" - } - foreach ($path in @( - (Join-Path $workspaceDir 'sessions'), - (Join-Path $workspaceDir 'files\attachments'), - (Join-Path $workspaceDir 'files\exports'), - (Join-Path $workspaceDir 'files\notes') - )) { - Assert-True (Test-Path -LiteralPath $path -PathType Container) ` - "Lifecycle workspace directory is missing: $path" - } -} - -function New-CertificateLifecycleData { - param( - [Parameter(Mandatory = $true)] [string]$BaseUrl, - [Parameter(Mandatory = $true)] [hashtable]$Headers, - [Parameter(Mandatory = $true)] [string]$RunId, - [Parameter(Mandatory = $true)] [string]$DataDir - ) - - $workspaceName = "Installer certificate $RunId" - $workspaceGroup = 'Installer certificate' - $workspaceResponse = Invoke-JsonPostRequest "$BaseUrl/api/workspaces" @{ - name = $workspaceName - group = $workspaceGroup - } $Headers - $workspace = $workspaceResponse.Content | ConvertFrom-Json - Assert-True ([int]$workspaceResponse.StatusCode -eq 201) ` - 'Could not create the lifecycle certificate workspace.' - Assert-True ([string]$workspace.id -match '^[a-z0-9]+(?:-[a-z0-9]+)*$') ` - 'Lifecycle certificate workspace returned an invalid id.' - Assert-True ([string]$workspace.name -ceq $workspaceName) ` - 'Lifecycle certificate workspace returned an unexpected name.' - Assert-True ([string]$workspace.group -ceq $workspaceGroup) ` - 'Lifecycle certificate workspace returned an unexpected group.' - Assert-True (Test-CertificateTimestamp $workspace.created) ` - 'Lifecycle certificate workspace returned an invalid creation timestamp.' - - $personalContent = "installer-certificate-personal-memory-$RunId" - $personalResponse = Invoke-JsonPostRequest "$BaseUrl/api/memory/frames?extract=false" @{ - content = $personalContent - importance = 'important' - source = 'tool_verified' - } $Headers - $personal = $personalResponse.Content | ConvertFrom-Json - Assert-True ( - [int]$personalResponse.StatusCode -eq 200 -and - $personal.saved -eq $true -and - [string]$personal.mind -ceq 'personal' -and - [string]$personal.importance -ceq 'important' -and - [string]$personal.source -ceq 'tool_verified' - ) 'Could not seed the lifecycle certificate personal memory.' - Assert-True ($personal.frameId -is [int] -or $personal.frameId -is [long]) ` - 'Lifecycle certificate personal memory returned no numeric frame id.' - - $workspaceContent = "installer-certificate-workspace-memory-$RunId" - $workspaceMemoryResponse = Invoke-JsonPostRequest "$BaseUrl/api/memory/frames?extract=false" @{ - content = $workspaceContent - workspaceId = [string]$workspace.id - importance = 'important' - source = 'tool_verified' - } $Headers - $workspaceMemory = $workspaceMemoryResponse.Content | ConvertFrom-Json - Assert-True ( - [int]$workspaceMemoryResponse.StatusCode -eq 200 -and - $workspaceMemory.saved -eq $true -and - [string]$workspaceMemory.mind -ceq 'workspace' -and - [string]$workspaceMemory.importance -ceq 'important' -and - [string]$workspaceMemory.source -ceq 'tool_verified' - ) 'Could not seed the lifecycle certificate workspace memory.' - Assert-True ($workspaceMemory.frameId -is [int] -or $workspaceMemory.frameId -is [long]) ` - 'Lifecycle certificate workspace memory returned no numeric frame id.' - - $state = [ordered]@{ - workspaceId = [string]$workspace.id - workspaceName = $workspaceName - workspaceGroup = $workspaceGroup - personalContent = $personalContent - personalFrameId = [long]$personal.frameId - workspaceContent = $workspaceContent - workspaceFrameId = [long]$workspaceMemory.frameId - } - Assert-CertificateLifecycleData $BaseUrl $Headers $state $DataDir - return $state -} - -function Get-CertificateRelativePath { - param( - [Parameter(Mandatory = $true)] [string]$Root, - [Parameter(Mandatory = $true)] [string]$Child - ) - - $resolvedRoot = [System.IO.Path]::GetFullPath($Root).TrimEnd('\') + '\' - $resolvedChild = [System.IO.Path]::GetFullPath($Child) - Assert-True ( - $resolvedChild.StartsWith($resolvedRoot, [System.StringComparison]::OrdinalIgnoreCase) - ) "Certificate profile entry escapes the owned root: $resolvedChild" - return $resolvedChild.Substring($resolvedRoot.Length).Replace('\', '/') -} - -function Get-CertificateDataManifest { - param( - [Parameter(Mandatory = $true)] [string]$ProfileDataDir, - [switch]$SkipHashes - ) - - $resolvedRoot = [System.IO.Path]::GetFullPath($ProfileDataDir).TrimEnd('\') - Assert-True (Test-Path -LiteralPath $resolvedRoot -PathType Container) ` - "Certificate profile directory is missing: $resolvedRoot" - $root = Get-Item -LiteralPath $resolvedRoot -Force - Assert-True (($root.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0) ` - "Certificate profile root must not be a reparse point: $resolvedRoot" - - $queue = [System.Collections.Generic.Queue[System.IO.DirectoryInfo]]::new() - $queue.Enqueue([System.IO.DirectoryInfo]$root) - $paths = [System.Collections.Generic.HashSet[string]]::new( - [System.StringComparer]::OrdinalIgnoreCase - ) - $entries = @() - while ($queue.Count -gt 0) { - $directory = $queue.Dequeue() - foreach ($item in @(Get-ChildItem -LiteralPath $directory.FullName -Force)) { - Assert-True (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0) ` - "Certificate profile contains a reparse point: $($item.FullName)" - $relativePath = Get-CertificateRelativePath $resolvedRoot $item.FullName - Assert-True ($paths.Add($relativePath)) ` - "Certificate profile contains an ambiguous path: $relativePath" - if ($item.PSIsContainer) { - $entries += [ordered]@{ - path = $relativePath - type = 'directory' - sizeBytes = 0L - sha256 = $null - } - $queue.Enqueue([System.IO.DirectoryInfo]$item) - } else { - $entries += [ordered]@{ - path = $relativePath - type = 'file' - sizeBytes = [long]$item.Length - sha256 = if ($SkipHashes) { - $null - } else { - (Get-FileHash -LiteralPath $item.FullName -Algorithm SHA256).Hash - } - } - } - } - } - return @($entries | Sort-Object { [string]$_.path }) -} - -function Assert-CertificateDataManifest { - param( - [Parameter(Mandatory = $true)] [object[]]$Expected, - [Parameter(Mandatory = $true)] [object[]]$Actual - ) - - Assert-True ($Actual.Count -eq $Expected.Count) ` - 'Silent uninstall changed the default-profile manifest entry count.' - for ($index = 0; $index -lt $Expected.Count; $index++) { - foreach ($property in @('path', 'type', 'sizeBytes', 'sha256')) { - Assert-True ( - [string]::Equals( - [string]$Actual[$index][$property], - [string]$Expected[$index][$property], - [System.StringComparison]::Ordinal - ) - ) "Silent uninstall changed default-profile manifest entry '$($Expected[$index].path)' ($property)." - } - } -} - -function Get-CertificateDataManifestDigest { - param( - [Parameter(Mandatory = $true)] - [AllowEmptyCollection()] - [object[]]$manifest - ) - - $payload = ConvertTo-Json -InputObject @($manifest) -Compress -Depth 4 - $sha256 = [System.Security.Cryptography.SHA256]::Create() - try { - $digest = $sha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($payload)) - return ([System.BitConverter]::ToString($digest)).Replace('-', '') - } finally { - $sha256.Dispose() - } -} - -function Get-SidecarProvenance { - param([Parameter(Mandatory = $true)] [string]$Path) - - Assert-True (Test-Path -LiteralPath $Path -PathType Leaf) ` - "Sidecar bundle is missing: $Path" - $file = Get-Item -LiteralPath $Path - Assert-True (($file.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0) ` - "Sidecar bundle must not be a reparse point: $Path" - $bytes = [System.IO.File]::ReadAllBytes($file.FullName) - $newlineIndex = [Array]::IndexOf($bytes, [byte]10) - Assert-True ($newlineIndex -gt 0) 'Sidecar bundle is missing embedded provenance.' - $firstLine = [System.Text.Encoding]::UTF8.GetString($bytes, 0, $newlineIndex) - $prefix = '// Waggle-Sidecar-Provenance: ' - Assert-True ($firstLine.StartsWith($prefix, [System.StringComparison]::Ordinal)) ` - 'Sidecar bundle is missing embedded provenance.' - $encoded = $firstLine.Substring($prefix.Length) - Assert-True ( - $encoded.Length -gt 0 -and - ($encoded.Length % 4) -eq 0 -and - $encoded -cmatch '^[A-Za-z0-9+/]+={0,2}$' - ) 'Sidecar embedded provenance is not canonical base64.' - try { - $jsonBytes = [Convert]::FromBase64String($encoded) - } catch { - throw 'Sidecar embedded provenance is not canonical base64.' - } - Assert-True ( - [string]::Equals( - [Convert]::ToBase64String($jsonBytes), - $encoded, - [System.StringComparison]::Ordinal - ) - ) 'Sidecar embedded provenance is not canonical base64.' - try { - $manifest = [System.Text.Encoding]::UTF8.GetString($jsonBytes) | - ConvertFrom-Json - } catch { - throw 'Sidecar embedded provenance is not valid JSON.' - } - Assert-True ($null -ne $manifest -and [int]$manifest.schemaVersion -eq 1) ` - 'Sidecar embedded provenance schemaVersion must be 1.' - Assert-True ([string]$manifest.sourceRevision -cmatch '^[0-9a-f]{40}$') ` - 'Sidecar embedded provenance sourceRevision is invalid.' - Assert-True ( - [string]::Equals( - [string]$manifest.entryPoint, - 'packages/server/src/local/service.ts', - [System.StringComparison]::Ordinal - ) - ) 'Sidecar embedded provenance entryPoint is invalid.' - - $sourceInputs = @($manifest.sourceInputs) - Assert-True ($sourceInputs.Count -gt 0) 'Sidecar embedded provenance sourceInputs are missing.' - $requiredInputs = [System.Collections.Generic.HashSet[string]]::new( - [System.StringComparer]::Ordinal - ) - foreach ($required in @( - 'package-lock.json', - 'package.json', - 'packages/server/src/local/service.ts', - 'scripts/build-sidecar.mjs' - )) { - [void]$requiredInputs.Add($required) - } - $previousPath = $null - foreach ($input in $sourceInputs) { - $relative = [string]$input.path - $parts = @($relative.Split('/')) - Assert-True ( - -not [string]::IsNullOrWhiteSpace($relative) -and - -not $relative.Contains('\') -and - -not $relative.Contains([char]0) -and - -not [System.IO.Path]::IsPathRooted($relative.Replace('/', '\')) -and - -not ($parts | Where-Object { $_ -in @('', '.', '..', 'node_modules') }) - ) 'Sidecar embedded provenance source input path is unsafe.' - if ($null -ne $previousPath) { - Assert-True ([string]::CompareOrdinal($previousPath, $relative) -lt 0) ` - 'Sidecar embedded provenance source inputs are not unique and sorted.' - } - Assert-True ([string]$input.sha256 -cmatch '^[0-9a-f]{64}$') ` - 'Sidecar embedded provenance source input hash is invalid.' - $previousPath = $relative - [void]$requiredInputs.Remove($relative) - } - Assert-True ($requiredInputs.Count -eq 0) ` - 'Sidecar embedded provenance omits required source inputs.' - - $payloadOffset = $newlineIndex + 1 - $payloadLength = $bytes.Length - $payloadOffset - Assert-True ( - $null -ne $manifest.bundlePayload -and - [long]$manifest.bundlePayload.sizeBytes -eq $payloadLength -and - [string]$manifest.bundlePayload.sha256 -cmatch '^[0-9a-f]{64}$' - ) 'Sidecar bundle payload does not match embedded provenance.' - $sha256 = [System.Security.Cryptography.SHA256]::Create() - try { - $payloadDigest = $sha256.ComputeHash($bytes, $payloadOffset, $payloadLength) - } finally { - $sha256.Dispose() - } - $payloadSha256 = ([System.BitConverter]::ToString($payloadDigest)).Replace('-', '') - Assert-True ( - [string]::Equals( - $payloadSha256, - [string]$manifest.bundlePayload.sha256, - [System.StringComparison]::OrdinalIgnoreCase - ) - ) 'Sidecar bundle payload does not match embedded provenance.' - - $provenanceSha = [System.Security.Cryptography.SHA256]::Create() - try { - $provenanceDigest = $provenanceSha.ComputeHash($jsonBytes) - } finally { - $provenanceSha.Dispose() - } - return [ordered]@{ - manifest = $manifest - bundleSha256 = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash - provenanceSha256 = ([System.BitConverter]::ToString($provenanceDigest)).Replace('-', '') - payloadSha256 = $payloadSha256 - sourceInputCount = $sourceInputs.Count - } -} - -function Assert-SidecarBundleBinding { - param( - [Parameter(Mandatory = $true)] [object]$Packaged, - [Parameter(Mandatory = $true)] [object]$Installed - ) - - Assert-True ( - [string]::Equals( - [string]$Installed.bundleSha256, - [string]$Packaged.bundleSha256, - [System.StringComparison]::OrdinalIgnoreCase - ) - ) 'Installed resources/service.js does not match the source-bound bundle.' - Assert-True ( - [string]::Equals( - [string]$Installed.provenanceSha256, - [string]$Packaged.provenanceSha256, - [System.StringComparison]::OrdinalIgnoreCase - ) -and - [string]::Equals( - [string]$Installed.manifest.sourceRevision, - [string]$Packaged.manifest.sourceRevision, - [System.StringComparison]::Ordinal - ) -and - [int]$Installed.sourceInputCount -eq [int]$Packaged.sourceInputCount - ) 'Installed resources/service.js provenance does not match the certified source.' -} - -function Assert-SidecarSourceBinding { - param( - [Parameter(Mandatory = $true)] [object]$Provenance, - [Parameter(Mandatory = $true)] [string]$RepositoryRoot, - [Parameter(Mandatory = $true)] [string]$ExpectedRevision, - [Parameter(Mandatory = $true)] [string]$GitExecutable - ) - - Assert-True ( - [string]::Equals( - [string]$Provenance.manifest.sourceRevision, - $ExpectedRevision, - [System.StringComparison]::Ordinal - ) - ) 'Sidecar provenance revision does not match expected source revision.' - $repositoryRootItem = Get-Item -LiteralPath $RepositoryRoot -ErrorAction Stop - Assert-True $repositoryRootItem.PSIsContainer ` - "Sidecar provenance repository root is not a directory: $RepositoryRoot" - $resolvedRepositoryRoot = $repositoryRootItem.FullName.TrimEnd('\') - $repositoryPrefix = $resolvedRepositoryRoot + '\' - $sourceInputs = @($Provenance.manifest.sourceInputs) - $sourcePaths = @($sourceInputs | ForEach-Object { [string]$_.path }) - foreach ($input in $sourceInputs) { - $relative = [string]$input.path - $sourcePath = [System.IO.Path]::GetFullPath( - (Join-Path $resolvedRepositoryRoot ($relative.Replace('/', '\'))) - ) - Assert-True ( - $sourcePath.StartsWith($repositoryPrefix, [System.StringComparison]::OrdinalIgnoreCase) - ) "Sidecar provenance source path escapes the repository: $relative" - Assert-True (Test-Path -LiteralPath $sourcePath -PathType Leaf) ` - "Sidecar provenance source input is missing: $relative" - $sourceFile = Get-Item -LiteralPath $sourcePath - Assert-True (($sourceFile.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0) ` - "Sidecar provenance source input is a reparse point: $relative" - Assert-True ( - [string]::Equals( - (Get-FileHash -LiteralPath $sourcePath -Algorithm SHA256).Hash, - [string]$input.sha256, - [System.StringComparison]::OrdinalIgnoreCase - ) - ) "Sidecar provenance source hash changed: $relative" - & $GitExecutable -C $RepositoryRoot ls-files --error-unmatch -- $relative 2>$null | - Out-Null - Assert-True ($LASTEXITCODE -eq 0) "Sidecar provenance source is not tracked: $relative" - & $GitExecutable -C $RepositoryRoot cat-file -e "${ExpectedRevision}:$relative" 2>$null - Assert-True ($LASTEXITCODE -eq 0) ` - "Sidecar provenance source is absent from expected revision: $relative" - } - for ($offset = 0; $offset -lt $sourcePaths.Count; $offset += 100) { - $lastIndex = [Math]::Min($offset + 99, $sourcePaths.Count - 1) - $sourceChunk = @($sourcePaths[$offset..$lastIndex]) - $diffArguments = @( - '-C', - $RepositoryRoot, - 'diff', - '--quiet', - $ExpectedRevision, - '--' - ) + $sourceChunk - & $GitExecutable @diffArguments - Assert-True ($LASTEXITCODE -eq 0) ` - 'Sidecar provenance source inputs differ from the expected revision.' - } -} - -function Get-ExternalProfileRootSnapshot { - param( - [Parameter(Mandatory = $true)] [string]$Name, - [Parameter(Mandatory = $true)] [string]$Path - ) - - $resolvedPath = [System.IO.Path]::GetFullPath($Path).TrimEnd('\') - $parentPath = [System.IO.Path]::GetDirectoryName($resolvedPath) - $leafName = [System.IO.Path]::GetFileName($resolvedPath) - Assert-True (-not [string]::IsNullOrWhiteSpace($parentPath)) ` - "External profile root has no parent directory: $resolvedPath" - Assert-True (Test-Path -LiteralPath $parentPath -PathType Container) ` - "External profile root parent is missing: $parentPath" - $matches = @( - Get-ChildItem -LiteralPath $parentPath -Force | - Where-Object { - [string]::Equals($_.Name, $leafName, [System.StringComparison]::OrdinalIgnoreCase) - } - ) - Assert-True ($matches.Count -le 1) ` - "External profile root has ambiguous directory entries: $resolvedPath" - if ($matches.Count -eq 0) { - return [ordered]@{ - name = $Name - path = $resolvedPath - existedBefore = $false - entryCount = 0 - manifestSha256 = $null - } - } - - $root = $matches[0] - Assert-True ($root.PSIsContainer) ` - "External profile root must be a directory: $resolvedPath" - Assert-True (($root.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0) ` - "External profile root must not be a reparse point: $resolvedPath" - $manifest = @(Get-CertificateDataManifest $resolvedPath) - return [ordered]@{ - name = $Name - path = $resolvedPath - existedBefore = $true - entryCount = $manifest.Count - manifestSha256 = (Get-CertificateDataManifestDigest $manifest) - } -} - -function Assert-ExternalProfileRootsUnchanged { - param([Parameter(Mandatory = $true)] [object[]]$Expected) - - foreach ($baseline in @($Expected)) { - if (-not [bool]$baseline.existedBefore) { - $actual = Get-ExternalProfileRootSnapshot ` - -Name ([string]$baseline.name) ` - -Path ([string]$baseline.path) - Assert-True (-not [bool]$actual.existedBefore) ` - "Installer created external profile root '$($baseline.name)': $($baseline.path)" - continue - } - - $actual = Get-ExternalProfileRootSnapshot ` - -Name ([string]$baseline.name) ` - -Path ([string]$baseline.path) - Assert-True ([bool]$actual.existedBefore) ` - "Installer removed external profile root '$($baseline.name)': $($baseline.path)" - Assert-True ([long]$actual.entryCount -eq [long]$baseline.entryCount) ` - "Installer changed external profile root entry count '$($baseline.name)'." - Assert-True ([string]::Equals( - [string]$actual.manifestSha256, - [string]$baseline.manifestSha256, - [System.StringComparison]::Ordinal - )) "Installer changed external profile root '$($baseline.name)'." - } -} - -function Get-HttpStatusCode { - param([Parameter(Mandatory = $true)] [string]$Uri) - - try { - return [int](Invoke-WebRequest -Uri $Uri -Method Get -TimeoutSec 5 -UseBasicParsing).StatusCode - } catch { - if ($_.Exception.Response) { - return [int]$_.Exception.Response.StatusCode - } - throw - } -} - -function Wait-ForHealth { - param( - [Parameter(Mandatory = $true)] [string]$BaseUrl, - [Parameter(Mandatory = $true)] [int]$TimeoutSeconds - ) - - $deadline = [DateTime]::UtcNow.AddSeconds($TimeoutSeconds) - $lastError = $null - while ([DateTime]::UtcNow -lt $deadline) { - try { - $health = Invoke-JsonRequest "$BaseUrl/health" - if ($health.mode -eq 'local' -and $health.database.healthy -eq $true) { - return $health - } - $lastError = 'Unexpected health payload' - } catch { - $lastError = $_.Exception.Message - } - Start-Sleep -Milliseconds 500 - } - throw "Waggle did not become healthy within ${TimeoutSeconds}s. Last error: $lastError" -} - -function Get-InstalledProcessIds { - param( - [Parameter(Mandatory = $true)] [string]$AppExecutable, - [Parameter(Mandatory = $true)] [string]$ServiceScript, - [string]$ManagedRuntimeRoot = '' - ) - - $ids = [System.Collections.Generic.HashSet[int]]::new() - $managedRoot = if ([string]::IsNullOrWhiteSpace($ManagedRuntimeRoot)) { - $null - } else { - [System.IO.Path]::GetFullPath($ManagedRuntimeRoot).TrimEnd('\', '/') - } - $processes = Get-CimInstance Win32_Process -ErrorAction Stop - foreach ($process in $processes) { - $exactApp = $process.ExecutablePath -and - [string]::Equals( - [System.IO.Path]::GetFullPath($process.ExecutablePath), - [System.IO.Path]::GetFullPath($AppExecutable), - [System.StringComparison]::OrdinalIgnoreCase - ) - $exactSidecar = $process.CommandLine -and - $process.CommandLine.IndexOf( - $ServiceScript, - [System.StringComparison]::OrdinalIgnoreCase - ) -ge 0 - $managedRuntime = $managedRoot -and ( - ($process.ExecutablePath -and - [System.IO.Path]::GetFullPath($process.ExecutablePath).StartsWith( - "$managedRoot\", - [System.StringComparison]::OrdinalIgnoreCase - )) -or - ($process.CommandLine -and - $process.CommandLine.IndexOf( - $managedRoot, - [System.StringComparison]::OrdinalIgnoreCase - ) -ge 0) - ) - if ($exactApp -or $exactSidecar -or $managedRuntime) { - $null = $ids.Add([int]$process.ProcessId) - } - } - return @($ids) -} - -function Assert-NoVisibleConsoleDescendant { - param([Parameter(Mandatory = $true)] [int]$RootProcessId) - - if ($null -eq ('WaggleInstallerWindowProbe' -as [type])) { - Add-Type -TypeDefinition @' -using System; -using System.Runtime.InteropServices; - -public static class WaggleInstallerWindowProbe -{ - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool IsWindowVisible(IntPtr hWnd); -} -'@ - } - - $processes = @(Get-CimInstance Win32_Process -ErrorAction Stop) - $descendantIds = [System.Collections.Generic.HashSet[int]]::new() - $frontier = @($RootProcessId) - while ($frontier.Count -gt 0) { - $next = @() - foreach ($process in $processes) { - if ($frontier -contains [int]$process.ParentProcessId -and - $descendantIds.Add([int]$process.ProcessId)) { - $next += [int]$process.ProcessId - } - } - $frontier = $next - } - $consoleHosts = @( - $processes | Where-Object { - $descendantIds.Contains([int]$_.ProcessId) -and [string]::Equals( - [string]$_.Name, - 'conhost.exe', - [System.StringComparison]::OrdinalIgnoreCase - ) - } - ) - $visibleConsoles = @( - $consoleHosts | Where-Object { - $consoleProcessId = [int]$_.ProcessId - $consoleProcess = Get-Process -Id $consoleProcessId -ErrorAction SilentlyContinue - if ($null -eq $consoleProcess) { return $false } - try { - $consoleProcess.Refresh() - $windowHandle = $consoleProcess.MainWindowHandle - return $windowHandle -ne [IntPtr]::Zero -and - [WaggleInstallerWindowProbe]::IsWindowVisible($windowHandle) - } catch { - if ($null -ne (Get-Process -Id $consoleProcessId -ErrorAction SilentlyContinue)) { - throw - } - return $false - } - } - ) - Assert-True ($visibleConsoles.Count -eq 0) ` - 'Installed Waggle spawned a visible console host.' -} - -function Wait-ForInstalledRuntimeStop { - param( - [Parameter(Mandatory = $true)] [string]$AppExecutable, - [Parameter(Mandatory = $true)] [string]$ServiceScript, - [Parameter(Mandatory = $true)] [int]$Port, - [string]$ManagedRuntimeRoot = '', - [int[]]$AdditionalPorts = @(), - [ValidateRange(5, 120)] [int]$TimeoutSeconds = 30 - ) - - $ports = @($Port) + @($AdditionalPorts | Where-Object { $_ -ge 1 -and $_ -le 65535 }) - $deadline = [DateTime]::UtcNow.AddSeconds($TimeoutSeconds) - $consecutiveAvailableProbes = 0 - do { - $ownedProcessIds = @( - Get-InstalledProcessIds $AppExecutable $ServiceScript $ManagedRuntimeRoot - ) - $busyPorts = @($ports | Where-Object { Test-TcpPortHasListener $_ }) - if ($ownedProcessIds.Count -eq 0 -and $busyPorts.Count -eq 0) { - $consecutiveAvailableProbes++ - if ($consecutiveAvailableProbes -ge 2) { return } - } else { - $consecutiveAvailableProbes = 0 - } - Start-Sleep -Milliseconds 300 - } while ([DateTime]::UtcNow -lt $deadline) - - $remainingProcessIds = @( - Get-InstalledProcessIds $AppExecutable $ServiceScript $ManagedRuntimeRoot - ) - $remainingBusyPorts = @($ports | Where-Object { Test-TcpPortHasListener $_ }) - throw "Installed runtime did not stop cleanly; owned PIDs=$($remainingProcessIds -join ',') ports=$($remainingBusyPorts -join ',')" -} - -function Assert-NoForeignWaggleProcesses { - param([Parameter(Mandatory = $true)] [string]$ExpectedAppExecutable) - - $expectedPath = [System.IO.Path]::GetFullPath($ExpectedAppExecutable) - $foreignProcesses = @( - Get-CimInstance Win32_Process -Filter "Name = 'waggle.exe'" -ErrorAction Stop | - Where-Object { - -not $_.ExecutablePath -or -not [string]::Equals( - [System.IO.Path]::GetFullPath($_.ExecutablePath), - $expectedPath, - [System.StringComparison]::OrdinalIgnoreCase - ) - } - ) - $details = @($foreignProcesses | ForEach-Object { "$($_.ProcessId):$($_.ExecutablePath)" }) - Assert-True ($foreignProcesses.Count -eq 0) ` - "A non-certificate Waggle process could be terminated by NSIS: $($details -join ', ')" -} - -function Test-RegistryValue { - param( - [Parameter(Mandatory = $true)] [string]$KeyPath, - [Parameter(Mandatory = $true)] [string]$ValueName - ) - - if (-not (Test-Path -LiteralPath $KeyPath)) { return $false } - $key = Get-Item -LiteralPath $KeyPath - return $key.GetValueNames() -contains $ValueName -} - -function Stop-InstalledProcesses { - param( - [Parameter(Mandatory = $true)] [string]$AppExecutable, - [Parameter(Mandatory = $true)] [string]$ServiceScript, - [string]$ManagedRuntimeRoot = '' - ) - - $taskkill = Join-Path $env:SystemRoot 'System32\taskkill.exe' - foreach ($processId in (Get-InstalledProcessIds $AppExecutable $ServiceScript $ManagedRuntimeRoot)) { - try { - Invoke-RawProcess $taskkill "/PID $processId /T /F" 20 - } catch { - # Killing the main process tree can make a separately captured child PID - # disappear. Re-check exact ownership before treating that as a failure. - $stillOwned = Get-InstalledProcessIds $AppExecutable $ServiceScript $ManagedRuntimeRoot - if ($stillOwned -contains $processId) { throw } - } - } -} - -function Wait-ForPathState { - param( - [Parameter(Mandatory = $true)] [string]$LiteralPath, - [Parameter(Mandatory = $true)] [bool]$ShouldExist, - [ValidateRange(5, 120)] [int]$TimeoutSeconds = 60 - ) - - $deadline = [DateTime]::UtcNow.AddSeconds($TimeoutSeconds) - while ([DateTime]::UtcNow -lt $deadline) { - if ((Test-Path -LiteralPath $LiteralPath) -eq $ShouldExist) { return } - Start-Sleep -Milliseconds 300 - } - throw "Path did not reach expected state (exists=$ShouldExist): $LiteralPath" -} - -function Get-WaggleShortcutPaths { - $desktop = [Environment]::GetFolderPath('Desktop') - $programs = [Environment]::GetFolderPath('Programs') - return @( - (Join-Path $desktop 'Waggle.lnk'), - (Join-Path $programs 'Waggle.lnk'), - (Join-Path $programs 'Waggle\Waggle.lnk') - ) -} - -function Assert-CertificateUninstallPostconditions { - param( - [Parameter(Mandatory = $true)] [string]$InstallDir, - [Parameter(Mandatory = $true)] [string]$UninstallRegistry, - [Parameter(Mandatory = $true)] [string]$ProductRegistry, - [Parameter(Mandatory = $true)] [string]$RunRegistry, - [Parameter(Mandatory = $true)] [string]$RunRegistryValue, - [Parameter(Mandatory = $true)] [string[]]$ShortcutPaths, - [Parameter(Mandatory = $true)] [string]$AppExecutable, - [Parameter(Mandatory = $true)] [string]$ServiceScript, - [Parameter(Mandatory = $true)] [int]$Port, - [string]$ManagedRuntimeRoot = '', - [int[]]$AdditionalPorts = @() - ) - - Wait-ForPathState $InstallDir $false 90 - Wait-ForPathState $UninstallRegistry $false 30 - Wait-ForPathState $ProductRegistry $false 30 - Assert-True (-not (Test-RegistryValue $RunRegistry $RunRegistryValue)) ` - 'Silent uninstall left or replaced the Waggle autostart entry.' - foreach ($shortcut in $ShortcutPaths) { - Wait-ForPathState $shortcut $false 30 - } - Wait-ForInstalledRuntimeStop $AppExecutable $ServiceScript $Port ` - -ManagedRuntimeRoot $ManagedRuntimeRoot -AdditionalPorts $AdditionalPorts - Assert-NoForeignWaggleProcesses $AppExecutable - Assert-TcpPortAvailable $Port -} - -function Assert-ShortcutTargets { - param( - [Parameter(Mandatory = $true)] [string[]]$ShortcutPaths, - [Parameter(Mandatory = $true)] [string]$ExpectedTarget - ) - - $shell = New-Object -ComObject WScript.Shell - foreach ($shortcutPath in $ShortcutPaths) { - $shortcut = $shell.CreateShortcut($shortcutPath) - Assert-True ( - [string]::Equals( - [System.IO.Path]::GetFullPath($shortcut.TargetPath), - [System.IO.Path]::GetFullPath($ExpectedTarget), - [System.StringComparison]::OrdinalIgnoreCase - ) - ) "Shortcut does not target the installed Waggle executable: $shortcutPath" - } -} - -function Assert-SafeReceiptPath { - param([Parameter(Mandatory = $true)] [string]$ReceiptPath) - - $resolvedReceipt = [System.IO.Path]::GetFullPath($ReceiptPath) - $existingReceipt = Get-Item -LiteralPath $resolvedReceipt -Force -ErrorAction SilentlyContinue - Assert-True ($null -eq $existingReceipt) ` - "Receipt path already exists; refusing to overwrite: $resolvedReceipt" - - $parent = Split-Path -Parent $resolvedReceipt - Assert-True (-not [string]::IsNullOrWhiteSpace($parent)) ` - "Receipt path has no parent directory: $resolvedReceipt" - $resolvedParent = [System.IO.Path]::GetFullPath($parent).TrimEnd('\') - Assert-True (Test-Path -LiteralPath $resolvedParent -PathType Container) ` - "Receipt parent directory must already exist: $resolvedParent" - $cursor = Get-Item -LiteralPath $resolvedParent -Force - while ($null -ne $cursor) { - Assert-True ($cursor -is [System.IO.DirectoryInfo]) ` - "Receipt parent is not a directory: $($cursor.FullName)" - Assert-True (($cursor.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0) ` - "Receipt parent must not be a reparse point: $($cursor.FullName)" - $cursor = $cursor.Parent - } -} - -function Reserve-CertificateReceiptPath { - param([Parameter(Mandatory = $true)] [string]$ReceiptPath) - - Assert-SafeReceiptPath $ReceiptPath - return [System.IO.File]::Open( - $ReceiptPath, - [System.IO.FileMode]::CreateNew, - [System.IO.FileAccess]::Write, - [System.IO.FileShare]::None - ) -} - -function Write-CertificateReceipt { - param( - [Parameter(Mandatory = $true)] [System.IO.FileStream]$Reservation, - [Parameter(Mandatory = $true)] [string]$Content - ) - - $bytes = [System.Text.UTF8Encoding]::new($false).GetBytes($Content) - try { - Assert-True ($Reservation.CanWrite -and $Reservation.Length -eq 0) ` - 'Certificate receipt reservation is not exclusively writable and empty.' - $Reservation.Write($bytes, 0, $bytes.Length) - $Reservation.Flush($true) - } finally { - $Reservation.Dispose() - } -} - -function Assert-SafeScratchRoot { - param( - [Parameter(Mandatory = $true)] [string]$ScratchRoot, - [Parameter(Mandatory = $true)] [string]$RunId - ) - - $resolved = [System.IO.Path]::GetFullPath($ScratchRoot).TrimEnd('\') - $expected = [System.IO.Path]::GetFullPath( - (Join-Path ([System.IO.Path]::GetTempPath()) "waggle-installer-cert-$RunId") - ).TrimEnd('\') - Assert-True ([string]::Equals( - $resolved, - $expected, - [System.StringComparison]::OrdinalIgnoreCase - )) "Scratch root is not the exact temp root for certificate run ${RunId}: $resolved" -} - -function Assert-CertificateScratchOwnership { - param( - [Parameter(Mandatory = $true)] [string]$ScratchRoot, - [Parameter(Mandatory = $true)] [string]$OwnershipMarker, - [Parameter(Mandatory = $true)] [string]$RunId, - [switch]$RequireOnlyMarker - ) - - $resolvedRoot = [System.IO.Path]::GetFullPath($ScratchRoot).TrimEnd('\') - Assert-SafeScratchRoot $resolvedRoot $RunId - $rootItem = Get-Item -LiteralPath $resolvedRoot -Force - Assert-True ($rootItem.PSIsContainer -and ( - $rootItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint - ) -eq 0) "Scratch root is missing or is a reparse point: $resolvedRoot" - $expectedMarker = Join-Path $resolvedRoot ".waggle-installer-certificate-owner-$RunId" - Assert-True ([string]::Equals( - [System.IO.Path]::GetFullPath($OwnershipMarker), - $expectedMarker, - [System.StringComparison]::OrdinalIgnoreCase - )) "Scratch ownership marker has an unexpected path: $OwnershipMarker" - $markerItem = Get-Item -LiteralPath $expectedMarker -Force - Assert-True (-not $markerItem.PSIsContainer -and ( - $markerItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint - ) -eq 0) "Scratch ownership marker is missing or is a reparse point: $expectedMarker" - Assert-True ((Get-Content -Raw -LiteralPath $expectedMarker) -ceq $RunId) ` - "Scratch ownership marker does not match certificate run ${RunId}." - $manifest = @(Get-CertificateDataManifest $resolvedRoot -SkipHashes) - if ($RequireOnlyMarker) { - Assert-True ( - $manifest.Count -eq 1 -and - [string]$manifest[0].path -ceq (Split-Path -Leaf $expectedMarker) - ) "Scratch root changed before ownership was established: $resolvedRoot" - } -} - -function New-CertificateScratchRoot { - param( - [Parameter(Mandatory = $true)] [string]$ScratchRoot, - [Parameter(Mandatory = $true)] [string]$RunId - ) - - $resolvedRoot = [System.IO.Path]::GetFullPath($ScratchRoot).TrimEnd('\') - Assert-SafeScratchRoot $resolvedRoot $RunId - Assert-True (-not (Test-Path -LiteralPath $resolvedRoot)) ` - "Scratch root already exists; refusing to adopt it: $resolvedRoot" - $createdRoot = New-Item -ItemType Directory -Path $resolvedRoot -ErrorAction Stop - Assert-True ($createdRoot.PSIsContainer -and ( - $createdRoot.Attributes -band [System.IO.FileAttributes]::ReparsePoint - ) -eq 0) "New scratch root is not a normal directory: $resolvedRoot" - $ownershipMarker = Join-Path $resolvedRoot ".waggle-installer-certificate-owner-$RunId" - $markerBytes = [System.Text.UTF8Encoding]::new($false).GetBytes($RunId) - $markerStream = [System.IO.File]::Open( - $ownershipMarker, - [System.IO.FileMode]::CreateNew, - [System.IO.FileAccess]::Write, - [System.IO.FileShare]::None - ) - try { - $markerStream.Write($markerBytes, 0, $markerBytes.Length) - $markerStream.Flush($true) - } finally { - $markerStream.Dispose() - } - Assert-CertificateScratchOwnership $resolvedRoot $ownershipMarker $RunId -RequireOnlyMarker - return $ownershipMarker -} - -function Remove-CertificateScratchRoot { - param( - [Parameter(Mandatory = $true)] [string]$ScratchRoot, - [Parameter(Mandatory = $true)] [string]$OwnershipMarker, - [Parameter(Mandatory = $true)] [string]$RunId - ) - - $resolvedRoot = [System.IO.Path]::GetFullPath($ScratchRoot).TrimEnd('\') - Assert-CertificateScratchOwnership $resolvedRoot $OwnershipMarker $RunId - $manifest = @(Get-CertificateDataManifest $resolvedRoot -SkipHashes) - $markerRelativePath = Get-CertificateRelativePath $resolvedRoot $OwnershipMarker - foreach ($entry in @($manifest | Where-Object { - $_.type -eq 'file' -and -not [string]::Equals( - [string]$_.path, - $markerRelativePath, - [System.StringComparison]::OrdinalIgnoreCase - ) - })) { - $entryPath = Join-Path $resolvedRoot ([string]$entry.path).Replace('/', '\') - $item = Get-Item -LiteralPath $entryPath -Force -ErrorAction Stop - Assert-True (-not $item.PSIsContainer -and ( - $item.Attributes -band [System.IO.FileAttributes]::ReparsePoint - ) -eq 0) "Refusing to remove replaced scratch file: $entryPath" - Remove-Item -LiteralPath $entryPath -Force - } - $directories = @($manifest | Where-Object { - $_.type -eq 'directory' - } | Sort-Object { ([string]$_.path).Length } -Descending) - foreach ($entry in $directories) { - $entryPath = Join-Path $resolvedRoot ([string]$entry.path).Replace('/', '\') - $item = Get-Item -LiteralPath $entryPath -Force -ErrorAction Stop - Assert-True ($item.PSIsContainer -and ( - $item.Attributes -band [System.IO.FileAttributes]::ReparsePoint - ) -eq 0) "Refusing to remove replaced scratch directory: $entryPath" - Assert-True (@(Get-ChildItem -LiteralPath $entryPath -Force).Count -eq 0) ` - "Certificate scratch directory changed during cleanup: $entryPath" - Remove-Item -LiteralPath $entryPath -Force - } - $remaining = @(Get-ChildItem -LiteralPath $resolvedRoot -Force) - Assert-True ( - $remaining.Count -eq 1 -and - [string]::Equals( - $remaining[0].FullName, - [System.IO.Path]::GetFullPath($OwnershipMarker), - [System.StringComparison]::OrdinalIgnoreCase - ) - ) 'Certificate scratch changed before ownership-marker cleanup.' - Assert-CertificateScratchOwnership $resolvedRoot $OwnershipMarker $RunId -RequireOnlyMarker - Remove-Item -LiteralPath $OwnershipMarker -Force - $rootItem = Get-Item -LiteralPath $resolvedRoot -Force -ErrorAction Stop - Assert-True ($rootItem.PSIsContainer -and ( - $rootItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint - ) -eq 0) "Refusing to remove replaced scratch root: $resolvedRoot" - Assert-True (@(Get-ChildItem -LiteralPath $resolvedRoot -Force).Count -eq 0) ` - "Certificate scratch root changed during cleanup: $resolvedRoot" - Remove-Item -LiteralPath $resolvedRoot -Force - Assert-True (-not (Test-Path -LiteralPath $resolvedRoot)) ` - "Certificate scratch cleanup did not remove the owned root: $resolvedRoot" -} - -function Remove-CertificateProductRegistry { - param( - [Parameter(Mandatory = $true)] [string]$ProductRegistry, - [Parameter(Mandatory = $true)] [string]$ExpectedInstallDir - ) - - if (-not (Test-Path -LiteralPath $ProductRegistry)) { return } - $item = Get-Item -LiteralPath $ProductRegistry - $storedInstallDir = [string]$item.GetValue('') - Assert-True (-not [string]::IsNullOrWhiteSpace($storedInstallDir)) ` - "Refusing to remove product registry key without an owned install path: $ProductRegistry" - Assert-True ( - [string]::Equals( - [System.IO.Path]::GetFullPath($storedInstallDir.Trim('"')), - [System.IO.Path]::GetFullPath($ExpectedInstallDir), - [System.StringComparison]::OrdinalIgnoreCase - ) - ) "Refusing to remove product registry key owned by another install: $storedInstallDir" - Remove-Item -LiteralPath $ProductRegistry -Recurse -Force -} - -function Clear-AbandonedCertificateProductRegistry { - param( - [Parameter(Mandatory = $true)] [string]$ProductRegistry, - [Parameter(Mandatory = $true)] [string]$UninstallRegistry - ) - - if (-not (Test-Path -LiteralPath $ProductRegistry)) { return } - Assert-True (-not (Test-Path -LiteralPath $UninstallRegistry)) ` - 'Refusing to remove product metadata while Waggle is registered.' - - $item = Get-Item -LiteralPath $ProductRegistry - $storedInstallDir = [string]$item.GetValue('') - Assert-True (-not [string]::IsNullOrWhiteSpace($storedInstallDir)) ` - "Refusing to remove product registry key without an install path: $ProductRegistry" - - $resolvedInstallDir = [System.IO.Path]::GetFullPath($storedInstallDir.Trim('"')).TrimEnd('\') - $certificateRoot = Split-Path -Parent $resolvedInstallDir - $tempRoot = [System.IO.Path]::GetFullPath([System.IO.Path]::GetTempPath()).TrimEnd('\') + '\' - Assert-True ($resolvedInstallDir.StartsWith($tempRoot, [System.StringComparison]::OrdinalIgnoreCase)) ` - "Refusing to remove product metadata outside the system temp directory: $resolvedInstallDir" - Assert-True ((Split-Path -Leaf $resolvedInstallDir) -eq 'install') ` - "Refusing to remove product metadata for an unexpected install directory: $resolvedInstallDir" - Assert-True ((Split-Path -Leaf $certificateRoot).StartsWith('waggle-installer-cert-', [System.StringComparison]::Ordinal)) ` - "Refusing to remove product metadata not owned by the installer certificate: $resolvedInstallDir" - Assert-True (-not (Test-Path -LiteralPath $resolvedInstallDir)) ` - "Refusing to remove product metadata for an install directory that still exists: $resolvedInstallDir" - - Remove-CertificateProductRegistry $ProductRegistry $resolvedInstallDir -} - -function Remove-CertificateProfileData { - param( - [Parameter(Mandatory = $true)] [string]$ProfileDataDir, - [Parameter(Mandatory = $true)] [string]$ProfileDataMarker, - [Parameter(Mandatory = $true)] [string]$RunId, - [Parameter(Mandatory = $true)] [bool]$ProfileAbsenceProven, - [Parameter(Mandatory = $true)] [bool]$RuntimeConfirmedStopped - ) - - Assert-True $ProfileAbsenceProven ` - 'Refusing to clean a profile whose pre-certificate absence was not proven.' - Assert-True $RuntimeConfirmedStopped ` - 'Refusing to clean the certificate profile before runtime shutdown is proven.' - $expectedDataDir = [System.IO.Path]::GetFullPath((Join-Path $env:USERPROFILE '.waggle')).TrimEnd('\') - $resolvedDataDir = [System.IO.Path]::GetFullPath($ProfileDataDir).TrimEnd('\') - Assert-True ( - [string]::Equals($resolvedDataDir, $expectedDataDir, [System.StringComparison]::OrdinalIgnoreCase) - ) "Refusing to clean an unexpected profile directory: $resolvedDataDir" - Assert-True ( - [string]::Equals( - [System.IO.Path]::GetFullPath((Split-Path -Parent $ProfileDataMarker)).TrimEnd('\'), - $resolvedDataDir, - [System.StringComparison]::OrdinalIgnoreCase - ) - ) "Refusing to clean a profile marker outside the certificate directory: $ProfileDataMarker" - Assert-True ((Split-Path -Leaf $ProfileDataMarker) -eq "installer-certificate-profile-marker-$RunId.txt") ` - "Refusing to clean an unexpected profile marker: $ProfileDataMarker" - Assert-True (Test-Path -LiteralPath $ProfileDataMarker -PathType Leaf) ` - "Certificate ownership marker is missing: $ProfileDataMarker" - Assert-True ((Get-Content -Raw -LiteralPath $ProfileDataMarker).Trim() -eq $RunId) ` - "Refusing to remove a profile marker not owned by this certificate: $ProfileDataMarker" - - $entries = @(Get-CertificateDataManifest $resolvedDataDir -SkipHashes) - $markerRelativePath = Get-CertificateRelativePath $resolvedDataDir $ProfileDataMarker - foreach ($entry in @($entries | Where-Object { - $_.type -eq 'file' -and -not [string]::Equals( - [string]$_.path, - $markerRelativePath, - [System.StringComparison]::OrdinalIgnoreCase - ) - })) { - $entryPath = Join-Path $resolvedDataDir ([string]$entry.path).Replace('/', '\') - $item = Get-Item -LiteralPath $entryPath -Force - Assert-True (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0) ` - "Refusing to remove a replaced profile entry: $entryPath" - Remove-Item -LiteralPath $entryPath -Force - } - $directories = @($entries | Where-Object { $_.type -eq 'directory' } | Sort-Object { - ([string]$_.path).Length - } -Descending) - foreach ($entry in $directories) { - $entryPath = Join-Path $resolvedDataDir ([string]$entry.path).Replace('/', '\') - $item = Get-Item -LiteralPath $entryPath -Force - Assert-True (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0) ` - "Refusing to remove a replaced profile directory: $entryPath" - Assert-True (@(Get-ChildItem -LiteralPath $entryPath -Force).Count -eq 0) ` - "Certificate profile directory changed during cleanup: $entryPath" - Remove-Item -LiteralPath $entryPath -Force - } - $remaining = @(Get-ChildItem -LiteralPath $resolvedDataDir -Force) - Assert-True ( - $remaining.Count -eq 1 -and - [string]::Equals( - $remaining[0].FullName, - [System.IO.Path]::GetFullPath($ProfileDataMarker), - [System.StringComparison]::OrdinalIgnoreCase - ) - ) 'Certificate profile changed before ownership-marker cleanup.' - Remove-Item -LiteralPath $ProfileDataMarker -Force - Remove-Item -LiteralPath $resolvedDataDir -Force - Assert-True (-not (Test-Path -LiteralPath $resolvedDataDir)) ` - 'Certificate profile cleanup did not remove the owned profile root.' -} - -$hasExpectedSignerThumbprint = -not [string]::IsNullOrWhiteSpace($ExpectedSignerThumbprint) -$hasExpectedSignerSubject = -not [string]::IsNullOrWhiteSpace($ExpectedSignerSubject) -if ($RequireAuthenticodeSignature) { - Assert-True ($hasExpectedSignerThumbprint -xor $hasExpectedSignerSubject) ` - 'Exactly one expected signer identity binding is required when Authenticode is required.' - if ($hasExpectedSignerThumbprint) { - $normalizedExpectedSignerThumbprint = ( - $ExpectedSignerThumbprint -replace '\s', '' - ).ToUpperInvariant() - Assert-True ($normalizedExpectedSignerThumbprint -match '^[0-9A-F]{40}$') ` - 'Expected signer thumbprint must be exactly 40 hexadecimal characters.' - } -} - -$installer = Get-Item -LiteralPath $InstallerPath -Assert-True (-not $installer.PSIsContainer) 'InstallerPath must be a file' -Assert-True ($installer.Extension -eq '.exe') 'InstallerPath must be an NSIS .exe' -$InstallerPath = $installer.FullName -$candidateInstallerHash = (Get-FileHash -LiteralPath $InstallerPath -Algorithm SHA256).Hash - -$previousInstaller = $null -$previousInstallerSignature = $null -$previousInstallerEvidence = $null -$previousVersionObject = $null -$candidateVersionObject = $null -$upgradeInputs = @( - $PreviousInstallerPath, - $ExpectedPreviousInstallerSha256, - $ExpectedPreviousVersion, - $ExpectedPreviousSourceRevision, - $ExpectedCandidateInstallerSha256, - $ExpectedCandidateVersion -) -$hasUpgradeInputs = @( - $upgradeInputs | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) } -).Count -gt 0 -Assert-True ($RequireVersionToVersionUpgrade -or -not $hasUpgradeInputs) ` - 'Version-to-version inputs require RequireVersionToVersionUpgrade.' -if ($RequireVersionToVersionUpgrade) { - Assert-True $RequireAuthenticodeSignature ` - 'Version-to-version certification requires Authenticode signature enforcement.' - Assert-True ($hasUpgradeInputs -and @( - $upgradeInputs | Where-Object { [string]::IsNullOrWhiteSpace([string]$_) } - ).Count -eq 0) 'Version-to-version certification requires every previous and candidate input.' - Assert-True ($ExpectedPreviousInstallerSha256 -match '^[0-9A-Fa-f]{64}$') ` - 'Previous installer SHA-256 must be exactly 64 hexadecimal characters.' - Assert-True ($ExpectedCandidateInstallerSha256 -match '^[0-9A-Fa-f]{64}$') ` - 'Candidate installer SHA-256 must be exactly 64 hexadecimal characters.' - Assert-True ($ExpectedPreviousSourceRevision -match '^[0-9A-Fa-f]{40}$') ` - 'Previous source revision must be exactly 40 hexadecimal characters.' - Assert-True ([string]::Equals( - $candidateInstallerHash, - $ExpectedCandidateInstallerSha256, - [System.StringComparison]::OrdinalIgnoreCase - )) 'Candidate installer does not match the pre-certification SHA-256.' - $previousVersionObject = ConvertTo-StrictSemanticVersion ` - $ExpectedPreviousVersion 'Previous version' - $candidateVersionObject = ConvertTo-StrictSemanticVersion ` - $ExpectedCandidateVersion 'Candidate version' - Assert-True ($candidateVersionObject -gt $previousVersionObject) ` - 'Candidate version must be newer than the previous version.' - - $previousInstaller = Get-Item -LiteralPath $PreviousInstallerPath - Assert-True (-not $previousInstaller.PSIsContainer) 'PreviousInstallerPath must be a file.' - Assert-True ($previousInstaller.Extension -eq '.exe') ` - 'PreviousInstallerPath must be an NSIS .exe.' - $PreviousInstallerPath = $previousInstaller.FullName - Assert-True (-not [string]::Equals( - $PreviousInstallerPath, - $InstallerPath, - [System.StringComparison]::OrdinalIgnoreCase - )) 'Previous installer and candidate installer must be distinct files.' - $previousInstallerHash = ( - Get-FileHash -LiteralPath $PreviousInstallerPath -Algorithm SHA256 - ).Hash - Assert-True ([string]::Equals( - $previousInstallerHash, - $ExpectedPreviousInstallerSha256, - [System.StringComparison]::OrdinalIgnoreCase - )) 'Previous installer does not match the protected SHA-256.' - $previousInstallerSignature = Get-AuthenticodeSignature -LiteralPath $PreviousInstallerPath - Assert-ExpectedAuthenticodeSignature ` - $previousInstallerSignature ` - $ExpectedSignerThumbprint ` - $ExpectedSignerSubject ` - 'Previous release installer' - $previousInstallerEvidence = New-AuthenticodeArtifactReceipt ` - $previousInstaller $previousInstallerSignature - $previousInstallerEvidence['expectedVersion'] = $ExpectedPreviousVersion -} - -if (-not $ReceiptPath) { - $ReceiptPath = Join-Path $installer.DirectoryName 'windows-installer-certificate.json' -} -$ReceiptPath = [System.IO.Path]::GetFullPath($ReceiptPath) -$installerHookPath = [System.IO.Path]::GetFullPath( - (Join-Path $PSScriptRoot '..\app\src-tauri\nsis\installer.nsi') -) - -$runId = [Guid]::NewGuid().ToString('N') -$scratchRoot = Join-Path ([System.IO.Path]::GetTempPath()) "waggle-installer-cert-$runId" -Assert-SafeScratchRoot $scratchRoot $runId -$installDir = Join-Path $scratchRoot 'install' -$profileDataDir = Join-Path $env:USERPROFILE '.waggle' -$externalProfileRootTargets = @( - [ordered]@{ name = '.hive-mind'; path = (Join-Path $env:USERPROFILE '.hive-mind') } - [ordered]@{ name = '.ollama'; path = (Join-Path $env:USERPROFILE '.ollama') } -) -$dataDir = $profileDataDir -$appExecutable = Join-Path $installDir 'waggle.exe' -$serviceScript = Join-Path $installDir 'resources\service.js' -$packagedServiceScript = [System.IO.Path]::GetFullPath( - (Join-Path $PSScriptRoot '..\app\src-tauri\resources\service.js') -) -$canonicalMarketplaceDb = [System.IO.Path]::GetFullPath( - (Join-Path $PSScriptRoot '..\packages\marketplace\marketplace.db') -) -$installedMarketplaceDb = Join-Path $installDir 'resources\marketplace.db' -$writableMarketplaceDb = Join-Path $dataDir 'marketplace.db' -$bundledNode = Join-Path $installDir 'resources\node.exe' -$bundledNpmRuntime = Join-Path $installDir 'resources\node_modules\waggle-node-runtime' -$bundledNpmCli = Join-Path $bundledNpmRuntime 'node_modules\npm\bin\npm-cli.js' -$bundledNpxCli = Join-Path $bundledNpmRuntime 'node_modules\npm\bin\npx-cli.js' -$bundledNpmWrapper = Join-Path $bundledNpmRuntime 'bin\npm.cmd' -$bundledNpxWrapper = Join-Path $bundledNpmRuntime 'bin\npx.cmd' -$uninstaller = Join-Path $installDir 'uninstall.exe' -$dataMarker = Join-Path $dataDir 'installer-certificate-marker.txt' -$profileDataMarker = Join-Path $profileDataDir "installer-certificate-profile-marker-$runId.txt" -$uninstallRegistry = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\Waggle' -$productRegistry = 'HKCU:\Software\egzakta\Waggle' -$runRegistry = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -$runRegistryValue = 'Waggle' -$shortcutCandidates = Get-WaggleShortcutPaths -$startedAt = [DateTime]::UtcNow -$installerStarted = $false -$profileAbsenceProven = $false -$externalProfileRootsPreProven = $false -$externalProfileRootBaselines = @() -$profileRootOwned = $false -$runtimeConfirmedStopped = $false -$certificateLifecycleData = $null -$preUninstallDataManifest = @() -$installedShortcuts = @() -$uninstallPostconditionsConfirmed = $false -$environmentNamesToClear = @( - 'WAGGLE_NODE_PATH', 'WAGGLE_DATA_DIR', 'NODE_PATH', 'NODE_OPTIONS', 'DOCKER_HOST', - 'WAGGLE_TRUST_LOCALHOST', 'WAGGLE_SQLITE_VEC_PATH', 'ONNXRUNTIME_NODE_BINDING_PATH', - 'EMBEDDING_PROVIDER', 'EMBEDDING_MODEL', 'OLLAMA_EMBED_MODEL', - 'WAGGLE_EMBEDDING_PROVIDER', 'HIVE_MIND_EMBEDDING_PROVIDER', - 'VOYAGE_API_KEY', 'WAGGLE_VOYAGE_API_KEY', 'WAGGLE_EVAL_MODE', - 'WAGGLE_SUPPRESS_EMBEDDING_WARNING', 'WAGGLE_LITELLM_URL', - 'WAGGLE_NPM_LIFECYCLE_WITNESS_PREFIX', - 'OLLAMA_MODELS', 'HF_HOME', 'HF_HUB_CACHE', 'TRANSFORMERS_CACHE', 'XDG_CACHE_HOME', - 'LITELLM_API_KEY', 'LITELLM_MASTER_KEY', - 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GEMINI_API_KEY', - 'GOOGLE_API_KEY', 'XAI_API_KEY', 'DEEPSEEK_API_KEY', - 'MISTRAL_API_KEY', 'DASHSCOPE_API_KEY', 'MINIMAX_API_KEY', - 'ZHIPU_API_KEY', 'MOONSHOT_API_KEY', 'PERPLEXITY_API_KEY', - 'OPENROUTER_API_KEY' -) -$environmentNamesToClear += @( - Get-ChildItem Env: | - Where-Object { $_.Name -match '(?i)^npm_' } | - ForEach-Object { $_.Name } -) -$environmentNamesToClear = @($environmentNamesToClear | Sort-Object -Unique) -$isolatedEnvironmentNames = @( - 'PATH', 'WAGGLE_PORT', 'WAGGLE_DATA_DIR', 'WAGGLE_HOST', - 'OLLAMA_HOST', 'VLLM_HOST', 'WAGGLE_SKIP_MARKETPLACE_SYNC' -) + $environmentNamesToClear -$environmentSnapshot = @{} -foreach ($name in $isolatedEnvironmentNames) { - $environmentSnapshot[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') -} - -$receipt = [ordered]@{ - schemaVersion = 4 - certificationMode = if ($RequireVersionToVersionUpgrade) { - 'version-to-version-upgrade' - } else { - 'same-version-repair' - } - status = 'running' - startedAt = $startedAt.ToString('o') - finishedAt = $null - installer = [ordered]@{ - name = $installer.Name - sha256 = $candidateInstallerHash - sizeBytes = $installer.Length - authenticodeStatus = $null - signatureType = $null - signerSubject = $null - signerThumbprint = $null - timestampAuthoritySubject = $null - timestampAuthorityThumbprint = $null - timestampAuthorityNotBefore = $null - timestampAuthorityNotAfter = $null - } - previousInstaller = $previousInstallerEvidence - previousInstalledApp = $null - installedApp = $null - platform = [ordered]@{ - os = [Environment]::OSVersion.VersionString - architecture = $env:PROCESSOR_ARCHITECTURE - powershell = $PSVersionTable.PSVersion.ToString() - } - evidence = [ordered]@{ - certificateRunId = $runId - sourceRevision = $null - workflowRunId = [Environment]::GetEnvironmentVariable('GITHUB_RUN_ID', 'Process') - workflowRunAttempt = [Environment]::GetEnvironmentVariable('GITHUB_RUN_ATTEMPT', 'Process') - certifierSha256 = $null - installerHookSha256 = $null - generatedInstallerScriptSha256 = $null - generatedInstallerHookPath = $null - sidecarSourceRevision = $null - sidecarBundleSha256 = $null - sidecarProvenanceSha256 = $null - sidecarSourceInputCount = 0 - windowsInboxTools = [ordered]@{} - } - scratchRoot = $scratchRoot - embeddingPayloadReady = $false - embeddingPayload = $null - certifiedTier = $null - managedModelVerified = $false - managedModelDigest = $null - lifecycleData = $null - bundledNpm = $null - upgrade = if ($RequireVersionToVersionUpgrade) { - [ordered]@{ - previousVersion = $ExpectedPreviousVersion - candidateVersion = $ExpectedCandidateVersion - previousSourceRevision = $ExpectedPreviousSourceRevision.ToLowerInvariant() - installDirectory = $installDir - observedPreviousVersion = $null - observedCandidateVersion = $null - configuredDataMarkerSha256 = $null - profileMarkerSha256 = $null - vaultKeySha256 = $null - managedModelName = $null - managedModelDigest = $null - } - } else { - $null - } - checks = [ordered]@{} - error = $null -} - -if ($RequireVersionToVersionUpgrade) { - $receipt.checks['previousInstallerHash'] = $true - $receipt.checks['previousInstallerAuthenticodeSignature'] = $true - $receipt.checks['previousInstallerAuthenticodeSigner'] = $true - $receipt.checks['previousInstallerAuthenticodeTimestamp'] = $true - $receipt.checks['candidateInstallerHash'] = $true - $receipt.checks['versionOrder'] = $true -} - -$receiptReservation = Reserve-CertificateReceiptPath $ReceiptPath -$scratchOwnershipMarker = $null -$ollamaPort = 0 -Assert-True ( - $WebViewDebugPort -eq 0 -or - ($WebViewDebugPort -ge 1024 -and $WebViewDebugPort -le 65535) -) 'WebViewDebugPort must be 0 or an integer between 1024 and 65535.' -$managedRuntimeRoot = Join-Path $dataDir 'runtimes\ollama' -$managedCertificateModel = 'qwen2.5:0.5b' -$managedOperationTimeoutSeconds = 3600 - -try { - $scratchOwnershipMarker = New-CertificateScratchRoot $scratchRoot $runId - Assert-True (Test-Path -LiteralPath $installerHookPath -PathType Leaf) ` - 'Configured NSIS installer hook is missing.' - $installerHookFile = Get-Item -LiteralPath $installerHookPath - $installerHook = Get-Content -Raw -LiteralPath $installerHookPath - Assert-True (-not ($installerHook -match '(?im)^\s*!macro\s+NSIS_HOOK_POSTUNINSTALL\b')) ` - 'Custom post-uninstall behavior could affect profile data.' - Assert-True ($installerHook -match '(?im)^\s*!macro\s+NSIS_HOOK_PREUNINSTALL\b') ` - 'Custom pre-uninstall data-preservation hook is missing.' - Assert-True ($installerHook -match '(?im)^\s*StrCpy\s+\$DeleteAppDataCheckboxState\s+0\s*$') ` - 'Custom pre-uninstall hook does not neutralize Tauri app-data deletion.' - Assert-True (-not ( - $installerHook -match '(?im)^\s*(?:RMDir|Delete)\b[^\r\n]*\$PROFILE[\\/]+\.waggle(?:[\\/"\s]|$)' - )) 'NSIS hook contains a destructive Waggle-data operation.' - - $nodeCommand = Get-Command node -CommandType Application -ErrorAction SilentlyContinue | - Select-Object -First 1 - Assert-True ($null -ne $nodeCommand) 'Node.js is required to reproduce the sidecar bundle.' - $bootstrapHelperPath = Join-Path $PSScriptRoot 'read-tauri-bootstrap-token.mjs' - Assert-True (Test-Path -LiteralPath $bootstrapHelperPath -PathType Leaf) ` - 'Tauri bootstrap helper is missing.' - Assert-True (Test-Path -LiteralPath $packagedServiceScript -PathType Leaf) ` - 'Packaged resources/service.js is missing before certification.' - $sidecarHashBeforeRebuild = ( - Get-FileHash -LiteralPath $packagedServiceScript -Algorithm SHA256 - ).Hash - & $nodeCommand.Source (Join-Path $PSScriptRoot 'build-sidecar.mjs') - Assert-True ($LASTEXITCODE -eq 0) 'Could not reproduce packaged resources/service.js.' - $sidecarHashAfterRebuild = ( - Get-FileHash -LiteralPath $packagedServiceScript -Algorithm SHA256 - ).Hash - Assert-True ( - [string]::Equals( - $sidecarHashBeforeRebuild, - $sidecarHashAfterRebuild, - [System.StringComparison]::OrdinalIgnoreCase - ) - ) 'Packaged resources/service.js does not match a clean sidecar rebuild.' - $packagedSidecarProvenance = Get-SidecarProvenance $packagedServiceScript - & $nodeCommand.Source ` - (Join-Path $PSScriptRoot 'check-sidecar-resources.mjs') ` - --expected-source-revision ` - ([string]$packagedSidecarProvenance.manifest.sourceRevision) - Assert-True ($LASTEXITCODE -eq 0) 'Packaged sidecar resources failed provenance preflight.' - if ($RequireAuthenticodeSignature) { - Assert-True (-not [string]::IsNullOrWhiteSpace($ExpectedSourceRevision)) ` - 'Release certification requires the expected source revision.' - } - if (-not [string]::IsNullOrWhiteSpace($ExpectedSourceRevision)) { - $normalizedExpectedSourceRevision = $ExpectedSourceRevision.Trim().ToLowerInvariant() - Assert-True ($normalizedExpectedSourceRevision -match '^[0-9a-f]{40}$') ` - 'Expected source revision must be exactly 40 hexadecimal characters.' - $gitCommand = Get-Command git -CommandType Application -ErrorAction SilentlyContinue | - Select-Object -First 1 - Assert-True ($null -ne $gitCommand) 'git is required to bind the installer receipt to source.' - $repositoryRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) - $revisionOutput = @(& $gitCommand.Source -C $repositoryRoot rev-parse HEAD 2>$null) - Assert-True ($LASTEXITCODE -eq 0 -and $revisionOutput.Count -eq 1) ` - 'Could not resolve the repository source revision.' - $repositoryRevision = ([string]$revisionOutput[0]).Trim().ToLowerInvariant() - Assert-True ($repositoryRevision -eq $normalizedExpectedSourceRevision) ` - "Repository revision $repositoryRevision does not match expected source $normalizedExpectedSourceRevision." - Assert-CleanRepositoryWorktree ` - -GitExecutable $gitCommand.Source ` - -RepositoryRoot $repositoryRoot - $receipt.evidence.sourceRevision = $repositoryRevision - $receipt.checks['sourceRevision'] = $true - $receipt.checks['sourceFilesClean'] = $true - - Assert-SidecarSourceBinding ` - -Provenance $packagedSidecarProvenance ` - -RepositoryRoot $repositoryRoot ` - -ExpectedRevision $repositoryRevision ` - -GitExecutable $gitCommand.Source - } else { - $receipt.evidence.sourceRevision = [Environment]::GetEnvironmentVariable('GITHUB_SHA', 'Process') - } - if ([string]::IsNullOrWhiteSpace([string]$receipt.evidence.sourceRevision)) { - $receipt.evidence.sourceRevision = [string]$packagedSidecarProvenance.manifest.sourceRevision - } - $receipt.evidence.sidecarSourceRevision = - [string]$packagedSidecarProvenance.manifest.sourceRevision - $receipt.evidence.sidecarBundleSha256 = [string]$packagedSidecarProvenance.bundleSha256 - $receipt.evidence.sidecarProvenanceSha256 = - [string]$packagedSidecarProvenance.provenanceSha256 - $receipt.evidence.sidecarSourceInputCount = - [int]$packagedSidecarProvenance.sourceInputCount - $receipt.evidence.certifierSha256 = (Get-FileHash -LiteralPath $PSCommandPath -Algorithm SHA256).Hash - $receipt.evidence.installerHookSha256 = (Get-FileHash -LiteralPath $installerHookPath -Algorithm SHA256).Hash - $releaseDirectory = Split-Path -Parent (Split-Path -Parent $installer.DirectoryName) - $generatedInstallerScripts = @( - Get-ChildItem -LiteralPath (Join-Path $releaseDirectory 'nsis') -Recurse -Filter 'installer.nsi' -File - ) - Assert-True ($generatedInstallerScripts.Count -eq 1) ` - "Expected exactly one generated NSIS script, found $($generatedInstallerScripts.Count)" - $generatedInstallerScript = $generatedInstallerScripts[0] - Assert-True ($generatedInstallerScript.LastWriteTimeUtc -ge $installerHookFile.LastWriteTimeUtc) ` - 'Generated NSIS source predates the configured installer hook; the build is stale.' - Assert-True ($installer.LastWriteTimeUtc -ge $installerHookFile.LastWriteTimeUtc) ` - 'Setup executable predates the configured installer hook; the artifact is stale.' - Assert-True ($installer.LastWriteTimeUtc -ge $generatedInstallerScript.LastWriteTimeUtc) ` - 'Generated NSIS source is newer than the setup executable; the artifact is stale.' - $generatedInstallerContent = Get-Content -Raw -LiteralPath $generatedInstallerScript.FullName - $matchingHookIncludes = 0 - foreach ($includeMatch in [regex]::Matches( - $generatedInstallerContent, - '(?im)^\s*!include\s+"(?[^"]+)"\s*$' - )) { - try { - $resolvedIncludePath = [System.IO.Path]::GetFullPath($includeMatch.Groups['path'].Value) - } catch { - continue - } - if ([string]::Equals( - $resolvedIncludePath, - $installerHookFile.FullName, - [System.StringComparison]::OrdinalIgnoreCase - )) { - $matchingHookIncludes++ - } - } - Assert-True ($matchingHookIncludes -eq 1) ` - "Generated NSIS source must include the exact configured hook once; found $matchingHookIncludes matches." - $receipt.evidence.generatedInstallerScriptSha256 = ( - Get-FileHash -LiteralPath $generatedInstallerScript.FullName -Algorithm SHA256 - ).Hash - $receipt.evidence.generatedInstallerHookPath = $installerHookFile.FullName - $receipt.checks['generatedInstallerSource'] = $true - $receipt.checks['generatedInstallerInclude'] = $true - $receipt.checks['profileDataDeletionAbsent'] = $true - $receipt.checks['baseAppDataDeletionNeutralized'] = $true - - $signature = Get-AuthenticodeSignature -LiteralPath $InstallerPath - $receipt.installer.authenticodeStatus = [string]$signature.Status - $receipt.installer.signatureType = [string]$signature.SignatureType - if ($signature.SignerCertificate) { - $receipt.installer.signerSubject = $signature.SignerCertificate.Subject - $receipt.installer.signerThumbprint = $signature.SignerCertificate.Thumbprint - } - if ($signature.TimeStamperCertificate) { - $receipt.installer.timestampAuthoritySubject = $signature.TimeStamperCertificate.Subject - $receipt.installer.timestampAuthorityThumbprint = $signature.TimeStamperCertificate.Thumbprint - $receipt.installer.timestampAuthorityNotBefore = $signature.TimeStamperCertificate.NotBefore.ToUniversalTime().ToString('o') - $receipt.installer.timestampAuthorityNotAfter = $signature.TimeStamperCertificate.NotAfter.ToUniversalTime().ToString('o') - } - if ($RequireAuthenticodeSignature) { - Assert-ExpectedAuthenticodeSignature ` - $signature $ExpectedSignerThumbprint $ExpectedSignerSubject 'Release installer' - $receipt.checks['authenticodeSignature'] = $true - $receipt.checks['authenticodeSigner'] = $true - $receipt.checks['authenticodeTimestamp'] = $true - } - - Clear-AbandonedCertificateProductRegistry $productRegistry $uninstallRegistry - Assert-True (-not (Test-Path -LiteralPath $uninstallRegistry)) ` - 'A current-user Waggle installation is already registered; refusing to replace it during certification.' - Assert-True (-not (Test-Path -LiteralPath $productRegistry)) ` - 'Waggle installer metadata already exists; refusing to overwrite another installation location.' - Assert-True (-not (Test-RegistryValue $runRegistry $runRegistryValue)) ` - 'A pre-existing Waggle autostart entry makes this certificate unsafe.' - $receipt.checks['runRegistryCollisionGuard'] = $true - Assert-NoForeignWaggleProcesses $appExecutable - $receipt.checks['foreignProcessCollisionGuard'] = $true - foreach ($shortcut in $shortcutCandidates) { - Assert-True (-not (Test-Path -LiteralPath $shortcut)) ` - "A pre-existing Waggle shortcut makes this certificate unsafe: $shortcut" - } - Assert-True (-not (Test-Path -LiteralPath $profileDataDir)) ` - "Profile data already exists at $profileDataDir; run this certificate under a disposable Windows user." - $profileAbsenceProven = $true - $processHome = [Environment]::GetEnvironmentVariable('HOME', 'Process') - if (-not [string]::IsNullOrWhiteSpace($processHome)) { - Assert-True ([string]::Equals( - [System.IO.Path]::GetFullPath($processHome).TrimEnd('\'), - [System.IO.Path]::GetFullPath($env:USERPROFILE).TrimEnd('\'), - [System.StringComparison]::OrdinalIgnoreCase - )) 'HOME must resolve to USERPROFILE so external profile isolation cannot be redirected.' - } - $externalProfileRootBaselines = @( - foreach ($target in $externalProfileRootTargets) { - Get-ExternalProfileRootSnapshot ` - -Name ([string]$target.name) ` - -Path ([string]$target.path) - } - ) - $receipt.evidence['externalProfileRoots'] = @( - foreach ($baseline in $externalProfileRootBaselines) { - [ordered]@{ - name = [string]$baseline.name - path = [string]$baseline.path - existedBefore = [bool]$baseline.existedBefore - entryCount = [long]$baseline.entryCount - manifestSha256 = $baseline.manifestSha256 - } - } - ) - $externalProfileRootsPreProven = $true - $receipt.checks['externalProfileRootsPreProven'] = $true - # The desktop webview and Rust shell currently share the fixed loopback port - # 3333 contract. Refuse before creating profile state rather than clean up - # after colliding with another installation. - Assert-TcpPortAvailable 3333 - New-Item -ItemType Directory -Path $profileDataDir | Out-Null - $profileRoot = Get-Item -LiteralPath $profileDataDir -Force - Assert-True (($profileRoot.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0) ` - 'Certificate profile root must not be a reparse point.' - Set-Content -LiteralPath $profileDataMarker -Value $runId -Encoding UTF8 - $profileRootOwned = $true - - $env:WAGGLE_PORT = '3333' - $env:WAGGLE_HOST = '127.0.0.1' - $ollamaPort = Get-FreeTcpPort - $env:OLLAMA_HOST = "http://127.0.0.1:$ollamaPort" - $env:VLLM_HOST = "http://127.0.0.1:$(Get-FreeTcpPort)" - $env:WAGGLE_SKIP_MARKETPLACE_SYNC = '1' - $isolationPath = Join-Path $scratchRoot 'isolated-path' - New-Item -ItemType Directory -Path $isolationPath -Force | Out-Null - $systemDirectory = [Environment]::GetFolderPath('System') - foreach ($toolName in @('tar.exe', 'taskkill.exe')) { - $sourceTool = Join-Path $systemDirectory $toolName - Assert-True (Test-Path -LiteralPath $sourceTool -PathType Leaf) ` - "Required Windows inbox tool is missing: $sourceTool" - $toolSignature = Get-AuthenticodeSignature -LiteralPath $sourceTool - Assert-True ($toolSignature.Status -eq [System.Management.Automation.SignatureStatus]::Valid) ` - "Required Windows inbox tool has no valid signature: $sourceTool" - $stagedTool = Join-Path $isolationPath $toolName - Copy-Item -LiteralPath $sourceTool -Destination $stagedTool - $sourceToolHash = (Get-FileHash -LiteralPath $sourceTool -Algorithm SHA256).Hash - Assert-True ((Get-FileHash -LiteralPath $stagedTool -Algorithm SHA256).Hash -eq $sourceToolHash) ` - "Staged Windows inbox tool differs from its signed source: $toolName" - $receipt.evidence.windowsInboxTools[$toolName] = $sourceToolHash - } - $env:PATH = $isolationPath - foreach ($toolName in @('tar.exe', 'taskkill.exe')) { - $resolvedTool = Get-Command $toolName -CommandType Application -ErrorAction Stop | - Select-Object -First 1 - Assert-True ( - [string]::Equals( - [System.IO.Path]::GetFullPath($resolvedTool.Source), - [System.IO.Path]::GetFullPath((Join-Path $isolationPath $toolName)), - [System.StringComparison]::OrdinalIgnoreCase - ) - ) "Isolation PATH did not resolve the staged Windows inbox tool: $toolName" - } - $receipt.checks['windowsInboxTools'] = $true - foreach ($name in $environmentNamesToClear) { - [Environment]::SetEnvironmentVariable($name, $null, 'Process') - } - Assert-True ( - [string]::IsNullOrEmpty( - [Environment]::GetEnvironmentVariable('WAGGLE_DATA_DIR', 'Process') - ) - ) 'WAGGLE_DATA_DIR must be absent so the packaged default-profile fallback is exercised.' - Assert-True ( - [string]::Equals( - [System.IO.Path]::GetFullPath($dataDir).TrimEnd('\'), - [System.IO.Path]::GetFullPath((Join-Path $env:USERPROFILE '.waggle')).TrimEnd('\'), - [System.StringComparison]::OrdinalIgnoreCase - ) - ) 'Certificate data directory is not the real Windows default profile.' - $receipt.checks['defaultProfileDataDir'] = $true - - $unexpectedApplications = @( - @('node.exe', 'npm.cmd', 'npx.cmd', 'docker.exe', 'ollama.exe', 'python.exe') | - Where-Object { Get-Command $_ -CommandType Application -ErrorAction SilentlyContinue } - ) - Assert-True ($unexpectedApplications.Count -eq 0) ` - "Isolation PATH still exposes external runtimes: $($unexpectedApplications -join ', ')" - $receipt.checks['externalRuntimeIsolation'] = $true - - # NSIS /D must be the final argument and must not be quoted, even when its - # absolute path contains spaces. Do not add /R: the certificate launches and - # owns the exact installed process itself. - Assert-NoForeignWaggleProcesses $appExecutable - $installerStarted = $true - $upgradeVaultKeySha256 = $null - $upgradeDataMarkerSha256 = $null - $upgradeProfileMarkerSha256 = $null - $upgradeManagedModelName = $null - $upgradeManagedModelDigest = $null - if ($RequireVersionToVersionUpgrade) { - Assert-ArtifactIdentity ` - $PreviousInstallerPath ` - $ExpectedPreviousInstallerSha256 ` - $ExpectedSignerThumbprint ` - $ExpectedSignerSubject ` - 'Previous installer before install' - Invoke-RawProcess $PreviousInstallerPath "/S /D=$installDir" 420 - Wait-ForPathState $appExecutable $true - Assert-True (Test-Path -LiteralPath $uninstaller -PathType Leaf) ` - 'Previous installer did not create uninstall.exe.' - $previousRegistration = Get-ItemProperty -LiteralPath $uninstallRegistry - Assert-True ([string]$previousRegistration.DisplayVersion -eq $ExpectedPreviousVersion) ` - 'Previous installer registry version does not match the protected previous version.' - Assert-True ([string]::Equals( - ([string]$previousRegistration.InstallLocation).Trim('"'), - $installDir, - [System.StringComparison]::OrdinalIgnoreCase - )) 'Previous installer did not use the isolated install directory.' - $previousRegisteredUninstaller = ([string]$previousRegistration.UninstallString).Trim().Trim('"') - Assert-True ([string]::Equals( - [System.IO.Path]::GetFullPath($previousRegisteredUninstaller), - [System.IO.Path]::GetFullPath($uninstaller), - [System.StringComparison]::OrdinalIgnoreCase - )) 'Previous installer registered an unexpected uninstaller.' - $previousProductRegistration = Get-Item -LiteralPath $productRegistry - Assert-True ([string]::Equals( - [System.IO.Path]::GetFullPath(([string]$previousProductRegistration.GetValue('')).Trim('"')), - [System.IO.Path]::GetFullPath($installDir), - [System.StringComparison]::OrdinalIgnoreCase - )) 'Previous installer product metadata does not match the isolated target.' - - $previousInstalledAppFile = Get-Item -LiteralPath $appExecutable - $previousInstalledAppSignature = Get-AuthenticodeSignature -LiteralPath $appExecutable - Assert-ExpectedAuthenticodeSignature ` - $previousInstalledAppSignature ` - $ExpectedSignerThumbprint ` - $ExpectedSignerSubject ` - 'Previous installed Waggle executable' - $previousInstalledProductVersion = Get-InstalledProductVersion ` - $appExecutable 'Previous installed Waggle executable' - Assert-True ($previousInstalledProductVersion.normalized -eq $ExpectedPreviousVersion) ` - 'Previous installed executable version does not match the protected previous version.' - $receipt.previousInstalledApp = New-AuthenticodeArtifactReceipt ` - $previousInstalledAppFile $previousInstalledAppSignature - $receipt.previousInstalledApp['productVersion'] = $previousInstalledProductVersion.raw - $receipt.upgrade.observedPreviousVersion = $previousInstalledProductVersion.normalized - $receipt.checks['previousInstall'] = $true - $receipt.checks['previousVersion'] = $true - $receipt.checks['previousInstalledAppAuthenticodeSignature'] = $true - $receipt.checks['previousInstalledAppAuthenticodeSigner'] = $true - $receipt.checks['previousInstalledAppAuthenticodeTimestamp'] = $true - - $previousBaseUrl = "http://127.0.0.1:$($env:WAGGLE_PORT)" - Assert-TcpPortAvailable 3333 - $webViewDebugPort = if ($WebViewDebugPort -gt 0) { $WebViewDebugPort } else { Get-FreeTcpPort } - $previousProcess = Start-InstalledApp $appExecutable $webViewDebugPort - try { - $null = Wait-ForHealth $previousBaseUrl $StartupTimeoutSeconds - $previousProcess.Refresh() - Assert-True (-not $previousProcess.HasExited) ` - 'The previous desktop process exited before upgrade state was prepared.' - $previousVaultKeyPath = Join-Path $dataDir '.vault-key' - Assert-VaultKeyAclRestricted $previousVaultKeyPath - New-Item -ItemType Directory -Path $dataDir -Force | Out-Null - Set-Content -LiteralPath $dataMarker -Value $runId -Encoding UTF8 - Assert-True (Test-Path -LiteralPath $profileDataMarker -PathType Leaf) ` - 'Previous launch removed the profile preservation marker.' - $previousHeaders = Get-CertificateSessionHeaders ` - $previousBaseUrl $nodeCommand.Source $bootstrapHelperPath $webViewDebugPort ` - -AllowLegacyUi - $receipt.checks['previousUi'] = $true - $previousTier = Invoke-JsonRequest "$previousBaseUrl/api/tier" $previousHeaders - Assert-True ([string]$previousTier.tier -ceq 'FREE') ` - "The protected previous release reported an unexpected effective tier: $($previousTier.tier)" - $receipt.checks['previousSoloTier'] = $true - if ($VerifyManagedModel) { - $previousBootstrapResponse = Invoke-JsonPostRequest ` - "$previousBaseUrl/api/local-inference/bootstrap" ` - @{} ` - $previousHeaders ` - $managedOperationTimeoutSeconds - $previousBootstrap = $previousBootstrapResponse.Content | ConvertFrom-Json - Assert-True ( - [int]$previousBootstrapResponse.StatusCode -eq 200 -and - $previousBootstrap.ok -eq $true -and - $previousBootstrap.dockerRequired -eq $false - ) 'The protected previous release could not bootstrap its managed local runtime.' - $previousPullResponse = Invoke-JsonPostRequest ` - "$previousBaseUrl/api/local-inference/pull" ` - @{ model = $managedCertificateModel } ` - $previousHeaders ` - $managedOperationTimeoutSeconds - $previousPull = $previousPullResponse.Content | ConvertFrom-Json - Assert-True ( - [int]$previousPullResponse.StatusCode -eq 200 -and - $previousPull.ok -eq $true -and - $previousPull.verifiedGeneration -eq $true - ) 'The protected previous release could not seed the managed local model.' - Assert-True ([string]$previousPull.digest -match '^sha256:[0-9a-f]{64}$') ` - 'The protected previous release returned no immutable managed-model digest.' - $upgradeManagedModelName = [string]$previousPull.model - $upgradeManagedModelDigest = [string]$previousPull.digest - Assert-True (-not [string]::IsNullOrWhiteSpace($upgradeManagedModelName)) ` - 'The protected previous release returned no managed-model identity.' - $receipt.upgrade.managedModelName = $upgradeManagedModelName - $receipt.upgrade.managedModelDigest = $upgradeManagedModelDigest - $receipt.checks['previousManagedModelSeeded'] = $true - } - $certificateLifecycleData = New-CertificateLifecycleData ` - $previousBaseUrl $previousHeaders $runId $dataDir - $receipt.lifecycleData = $certificateLifecycleData - $receipt.checks['realWorkspaceAndMemorySeeded'] = $true - $upgradeVaultKeySha256 = ( - Get-FileHash -LiteralPath $previousVaultKeyPath -Algorithm SHA256 - ).Hash - $upgradeDataMarkerSha256 = ( - Get-FileHash -LiteralPath $dataMarker -Algorithm SHA256 - ).Hash - $upgradeProfileMarkerSha256 = ( - Get-FileHash -LiteralPath $profileDataMarker -Algorithm SHA256 - ).Hash - $receipt.upgrade.vaultKeySha256 = $upgradeVaultKeySha256 - $receipt.upgrade.configuredDataMarkerSha256 = $upgradeDataMarkerSha256 - $receipt.upgrade.profileMarkerSha256 = $upgradeProfileMarkerSha256 - $receipt.checks['previousLaunch'] = $true - } finally { - Stop-InstalledProcesses $appExecutable $serviceScript $managedRuntimeRoot - Wait-ForInstalledRuntimeStop $appExecutable $serviceScript 3333 ` - -ManagedRuntimeRoot $managedRuntimeRoot -AdditionalPorts @($ollamaPort, $webViewDebugPort) - $previousProcess.Dispose() - } - - Assert-NoForeignWaggleProcesses $appExecutable - Assert-ArtifactIdentity ` - $InstallerPath ` - $ExpectedCandidateInstallerSha256 ` - $ExpectedSignerThumbprint ` - $ExpectedSignerSubject ` - 'Candidate installer before upgrade' - Invoke-RawProcess $InstallerPath "/S /D=$installDir" 420 - Assert-ArtifactIdentity ` - $InstallerPath ` - $ExpectedCandidateInstallerSha256 ` - $ExpectedSignerThumbprint ` - $ExpectedSignerSubject ` - 'Candidate installer after upgrade' - Wait-ForInstalledRuntimeStop $appExecutable $serviceScript 3333 ` - -ManagedRuntimeRoot $managedRuntimeRoot -AdditionalPorts @($ollamaPort, $webViewDebugPort) - Wait-ForPathState $appExecutable $true - $upgradeRegistration = Get-ItemProperty -LiteralPath $uninstallRegistry - Assert-True ([string]$upgradeRegistration.DisplayVersion -eq $ExpectedCandidateVersion) ` - 'Candidate installer registry version does not match the protected candidate version.' - Assert-True ([string]::Equals( - ([string]$upgradeRegistration.InstallLocation).Trim('"'), - $installDir, - [System.StringComparison]::OrdinalIgnoreCase - )) 'Upgrade changed the registered install directory.' - Assert-True ([string]::Equals( - [System.IO.Path]::GetFullPath(([string]$upgradeRegistration.UninstallString).Trim().Trim('"')), - [System.IO.Path]::GetFullPath($previousRegisteredUninstaller), - [System.StringComparison]::OrdinalIgnoreCase - )) 'Upgrade changed the registered uninstaller location.' - $upgradeProductRegistration = Get-Item -LiteralPath $productRegistry - Assert-True ([string]::Equals( - [System.IO.Path]::GetFullPath(([string]$upgradeProductRegistration.GetValue('')).Trim('"')), - [System.IO.Path]::GetFullPath($installDir), - [System.StringComparison]::OrdinalIgnoreCase - )) 'Upgrade changed the product install location.' - Assert-True ( - (Get-FileHash -LiteralPath $dataMarker -Algorithm SHA256).Hash -eq $upgradeDataMarkerSha256 - ) 'Upgrade changed or removed configured user data.' - Assert-True ( - (Get-FileHash -LiteralPath $profileDataMarker -Algorithm SHA256).Hash -eq - $upgradeProfileMarkerSha256 - ) 'Upgrade changed or removed the profile data marker.' - $receipt.checks['candidateVersion'] = $true - $receipt.checks['versionToVersionUpgrade'] = $true - $receipt.checks['upgradeSameInstallDirectory'] = $true - $receipt.checks['upgradeConfiguredDataPreserved'] = $true - $receipt.checks['upgradeProfileDataPreserved'] = $true - $receipt.checks['upgradeRegistrations'] = $true - } else { - Invoke-RawProcess $InstallerPath "/S /D=$installDir" 420 - } - Wait-ForPathState $appExecutable $true - Assert-True (Test-Path -LiteralPath $uninstaller -PathType Leaf) 'Installer did not create uninstall.exe' - Assert-True (Test-Path -LiteralPath $serviceScript -PathType Leaf) 'Installer omitted resources/service.js' - $installedSidecarProvenance = Get-SidecarProvenance $serviceScript - Assert-SidecarBundleBinding ` - -Packaged $packagedSidecarProvenance ` - -Installed $installedSidecarProvenance - $receipt.checks['sidecarSourceProvenance'] = $true - Assert-True (Test-Path -LiteralPath $canonicalMarketplaceDb -PathType Leaf) ` - 'The tracked canonical marketplace database is missing.' - Assert-True (Test-Path -LiteralPath $installedMarketplaceDb -PathType Leaf) ` - 'Installer omitted resources\marketplace.db' - $installedMarketplaceFile = Get-Item -LiteralPath $installedMarketplaceDb - Assert-True ( - ($installedMarketplaceFile.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0 - ) 'Installed resources\marketplace.db must not be a reparse point.' - $marketplaceResourceSha256 = ( - Get-FileHash -LiteralPath $canonicalMarketplaceDb -Algorithm SHA256 - ).Hash - Assert-True ( - (Get-FileHash -LiteralPath $installedMarketplaceDb -Algorithm SHA256).Hash -eq - $marketplaceResourceSha256 - ) 'Installed resources\marketplace.db does not match the tracked canonical database.' - $receipt.evidence['marketplaceResourceSha256'] = $marketplaceResourceSha256 - $receipt.checks['marketplaceResource'] = $true - Assert-True (Test-Path -LiteralPath $bundledNode -PathType Leaf) ` - 'Installer omitted the bundled Node.js runtime' - Assert-True (Test-Path -LiteralPath (Join-Path $installDir 'resources\node_modules') -PathType Container) ` - 'Installer omitted staged runtime dependencies' - $bundledRuntimeFiles = @( - (Join-Path $bundledNpmRuntime 'package.json'), - (Join-Path $bundledNpmRuntime 'NODE-LICENSE'), - (Join-Path $bundledNpmRuntime 'node_modules\npm\LICENSE'), - $bundledNpmCli, - $bundledNpxCli, - $bundledNpmWrapper, - $bundledNpxWrapper - ) - foreach ($runtimeFile in $bundledRuntimeFiles) { - Assert-True (Test-Path -LiteralPath $runtimeFile -PathType Leaf) ` - "Installer omitted bundled npm runtime file: $runtimeFile" - } - - $npmVersionOutput = @(& $bundledNode $bundledNpmCli --version 2>$null) - Assert-True ($LASTEXITCODE -eq 0 -and $npmVersionOutput.Count -eq 1) ` - 'Bundled npm CLI did not execute through the installed Node runtime.' - $npxVersionOutput = @(& $bundledNode $bundledNpxCli --version 2>$null) - Assert-True ($LASTEXITCODE -eq 0 -and $npxVersionOutput.Count -eq 1) ` - 'Bundled npx CLI did not execute through the installed Node runtime.' - $npmVersion = ([string]$npmVersionOutput[0]).Trim() - $npxVersion = ([string]$npxVersionOutput[0]).Trim() - Assert-True ($npmVersion -match '^\d+\.\d+\.\d+$' -and $npmVersion -eq $npxVersion) ` - "Bundled npm/npx versions do not match: npm=$npmVersion npx=$npxVersion" - $cmdExe = Join-Path $env:SystemRoot 'System32\cmd.exe' - Invoke-RawProcess $cmdExe ('/d /s /c ""{0}" --version"' -f $bundledNpmWrapper) 60 - Invoke-RawProcess $cmdExe ('/d /s /c ""{0}" --version"' -f $bundledNpxWrapper) 60 - - $offlinePackageSource = Join-Path $scratchRoot 'offline-npm-package' - $offlinePackageArchiveRoot = Join-Path $scratchRoot 'offline-npm-archive' - $offlinePackageArchivePayload = Join-Path $offlinePackageArchiveRoot 'package' - $offlinePackageArchive = Join-Path $scratchRoot 'waggle-offline-install-probe-1.0.0.tgz' - $offlinePackageTar = Join-Path $isolationPath 'tar.exe' - $offlineLifecycleWitnessPrefix = Join-Path $scratchRoot 'offline-npm-lifecycle' - $offlineInstallRoot = Join-Path $scratchRoot 'offline-npm-install' - $offlineCache = Join-Path $scratchRoot 'offline-npm-cache' - $isolatedUserConfig = Join-Path $scratchRoot 'empty-user.npmrc' - $isolatedGlobalConfig = Join-Path $scratchRoot 'empty-global.npmrc' - New-Item -ItemType Directory -Path @( - $offlinePackageSource, - $offlinePackageArchivePayload, - $offlineInstallRoot, - $offlineCache - ) -Force | Out-Null - Set-Content -LiteralPath $isolatedUserConfig -Value '' -NoNewline - Set-Content -LiteralPath $isolatedGlobalConfig -Value '' -NoNewline - $offlinePackageManifest = [ordered]@{ - name = 'waggle-offline-install-probe' - version = '1.0.0' - scripts = [ordered]@{ - prepare = "node -e `"require('node:fs').writeFileSync(process.env.WAGGLE_NPM_LIFECYCLE_WITNESS_PREFIX + '-prepare-ran.txt','unexpected')`"" - prepack = "node -e `"require('node:fs').writeFileSync(process.env.WAGGLE_NPM_LIFECYCLE_WITNESS_PREFIX + '-prepack-ran.txt','unexpected')`"" - install = "node -e `"require('node:fs').writeFileSync(process.env.WAGGLE_NPM_LIFECYCLE_WITNESS_PREFIX + '-install-ran.txt','unexpected')`"" - } - } - $offlinePackageManifest | ConvertTo-Json -Depth 4 | - Set-Content -LiteralPath (Join-Path $offlinePackageSource 'package.json') -Encoding UTF8 - Copy-Item ` - -LiteralPath (Join-Path $offlinePackageSource 'package.json') ` - -Destination (Join-Path $offlinePackageArchivePayload 'package.json') - Invoke-RawProcess $offlinePackageTar ( - '-czf "{0}" -C "{1}" package' -f $offlinePackageArchive, $offlinePackageArchiveRoot - ) 60 - $offlinePackageArchiveItem = Get-Item -LiteralPath $offlinePackageArchive -Force - Assert-True ( - $offlinePackageArchiveItem -is [System.IO.FileInfo] -and - ($offlinePackageArchiveItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0 - ) 'Offline npm probe archive is missing or is a reparse point.' - Assert-True (@(Get-ChildItem -LiteralPath $offlineCache -Force).Count -eq 0) ` - 'Offline npm certificate cache was not clean before the probe.' - [Environment]::SetEnvironmentVariable( - 'WAGGLE_NPM_LIFECYCLE_WITNESS_PREFIX', - $offlineLifecycleWitnessPrefix, - 'Process' - ) - $npmInstallOutput = @( - & $bundledNode $bundledNpmCli install --offline --ignore-scripts --no-audit --no-fund ` - --package-lock=false --save=false --userconfig $isolatedUserConfig ` - --globalconfig $isolatedGlobalConfig --cache $offlineCache --prefix $offlineInstallRoot ` - -- $offlinePackageArchive 2>&1 - ) - Assert-True ($LASTEXITCODE -eq 0) ` - "Bundled npm offline local install failed: $($npmInstallOutput -join [Environment]::NewLine)" - $installedOfflinePackage = Join-Path $offlineInstallRoot 'node_modules\waggle-offline-install-probe' - Assert-True (Test-Path -LiteralPath (Join-Path $installedOfflinePackage 'package.json') -PathType Leaf) ` - 'Bundled npm did not install the local offline package.' - $installedOfflinePackageItem = Get-Item -LiteralPath $installedOfflinePackage -Force - Assert-True ( - $installedOfflinePackageItem -is [System.IO.DirectoryInfo] -and - ($installedOfflinePackageItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0 - ) 'Bundled npm installed the local offline package as a reparse point.' - foreach ($lifecycleMarker in @('prepare-ran.txt', 'prepack-ran.txt', 'install-ran.txt')) { - $lifecycleWitness = "$offlineLifecycleWitnessPrefix-$lifecycleMarker" - Assert-True (-not (Test-Path -LiteralPath $lifecycleWitness)) ` - "Bundled npm executed lifecycle script marker $lifecycleMarker despite --ignore-scripts." - } - $receipt.checks['silentInstall'] = $true - $receipt.checks['bundledRuntimePayload'] = $true - $receipt.checks['bundledNpmCli'] = $true - $receipt.checks['bundledNpmWrappers'] = $true - $receipt.checks['bundledNpmOfflineInstall'] = $true - $receipt.checks['bundledNpmIgnoreScriptsFlagHonored'] = $true - $receipt.bundledNpm = [ordered]@{ - version = $npmVersion - npmCli = $bundledNpmCli - npxCli = $bundledNpxCli - cacheWasClean = $true - offlinePackage = 'waggle-offline-install-probe@1.0.0' - ignoreScriptsFlagHonored = $true - } - $installedAppFile = Get-Item -LiteralPath $appExecutable - $installedAppSignature = Get-AuthenticodeSignature -LiteralPath $appExecutable - $receipt.installedApp = [ordered]@{ - name = $installedAppFile.Name - sha256 = (Get-FileHash -LiteralPath $appExecutable -Algorithm SHA256).Hash - sizeBytes = $installedAppFile.Length - authenticodeStatus = [string]$installedAppSignature.Status - signatureType = [string]$installedAppSignature.SignatureType - signerSubject = $null - signerThumbprint = $null - timestampAuthoritySubject = $null - timestampAuthorityThumbprint = $null - timestampAuthorityNotBefore = $null - timestampAuthorityNotAfter = $null - } - if ($installedAppSignature.SignerCertificate) { - $receipt.installedApp.signerSubject = $installedAppSignature.SignerCertificate.Subject - $receipt.installedApp.signerThumbprint = $installedAppSignature.SignerCertificate.Thumbprint - } - if ($installedAppSignature.TimeStamperCertificate) { - $receipt.installedApp.timestampAuthoritySubject = $installedAppSignature.TimeStamperCertificate.Subject - $receipt.installedApp.timestampAuthorityThumbprint = $installedAppSignature.TimeStamperCertificate.Thumbprint - $receipt.installedApp.timestampAuthorityNotBefore = $installedAppSignature.TimeStamperCertificate.NotBefore.ToUniversalTime().ToString('o') - $receipt.installedApp.timestampAuthorityNotAfter = $installedAppSignature.TimeStamperCertificate.NotAfter.ToUniversalTime().ToString('o') - } - $receipt.checks['installedAppPayload'] = $true - if ($RequireAuthenticodeSignature) { - Assert-ExpectedAuthenticodeSignature ` - $installedAppSignature $ExpectedSignerThumbprint $ExpectedSignerSubject 'Installed Waggle executable' - $receipt.checks['installedAppAuthenticodeSignature'] = $true - $receipt.checks['installedAppAuthenticodeSigner'] = $true - $receipt.checks['installedAppAuthenticodeTimestamp'] = $true - } - if ($RequireVersionToVersionUpgrade) { - $installedProductVersion = Get-InstalledProductVersion ` - $appExecutable 'Installed Waggle executable' - Assert-True ($installedProductVersion.normalized -eq $ExpectedCandidateVersion) ` - 'Installed candidate executable version does not match the protected candidate version.' - $receipt.installedApp['productVersion'] = $installedProductVersion.raw - $receipt.upgrade.observedCandidateVersion = $installedProductVersion.normalized - Assert-LifecycleReceiptApprovedSigner ` - $receipt $ExpectedSignerThumbprint $ExpectedSignerSubject - $receipt.checks['sameApprovedSigner'] = $true - } - - $registered = Get-ItemProperty -LiteralPath $uninstallRegistry - Assert-True ( - [string]::Equals( - ([string]$registered.InstallLocation).Trim('"'), - $installDir, - [System.StringComparison]::OrdinalIgnoreCase - ) - ) 'Installer registry location does not match the isolated target' - $registeredUninstallerCommand = ([string]$registered.UninstallString).Trim() - Assert-True ( - $registeredUninstallerCommand.StartsWith('"') -and $registeredUninstallerCommand.EndsWith('"') - ) 'Installer registered an ambiguous uninstall command' - $registeredUninstaller = $registeredUninstallerCommand.Trim('"') - Assert-True ( - [string]::Equals( - [System.IO.Path]::GetFullPath($registeredUninstaller), - [System.IO.Path]::GetFullPath($uninstaller), - [System.StringComparison]::OrdinalIgnoreCase - ) - ) 'Installer registry uninstall command does not target the isolated uninstaller' - $receipt.checks['uninstallRegistration'] = $true - $receipt.checks['registeredUninstaller'] = $true - $productRegistration = Get-Item -LiteralPath $productRegistry - Assert-True ( - [string]::Equals( - [System.IO.Path]::GetFullPath(([string]$productRegistration.GetValue('')).Trim('"')), - [System.IO.Path]::GetFullPath($installDir), - [System.StringComparison]::OrdinalIgnoreCase - ) - ) 'Installer product metadata does not match the isolated target' - $receipt.checks['productRegistration'] = $true - - $desktopShortcut = $shortcutCandidates[0] - $startMenuShortcuts = @( - $shortcutCandidates | Select-Object -Skip 1 | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } - ) - Assert-True (Test-Path -LiteralPath $desktopShortcut -PathType Leaf) ` - 'Installer did not create the desktop shortcut' - Assert-True ($startMenuShortcuts.Count -ge 1) 'Installer did not create a Start Menu shortcut' - $installedShortcuts = @($desktopShortcut) + $startMenuShortcuts - Assert-ShortcutTargets $installedShortcuts $appExecutable - $receipt.checks['shortcuts'] = $true - - $baseUrl = "http://127.0.0.1:$($env:WAGGLE_PORT)" - Assert-TcpPortAvailable 3333 - $webViewDebugPort = if ($WebViewDebugPort -gt 0) { $WebViewDebugPort } else { Get-FreeTcpPort } - $firstProcess = Start-InstalledApp $appExecutable $webViewDebugPort - try { - $health = Wait-ForHealth $baseUrl $StartupTimeoutSeconds - $firstProcess.Refresh() - Assert-True (-not $firstProcess.HasExited) 'The installed desktop process exited during first boot' - Assert-NoVisibleConsoleDescendant $firstProcess.Id - $serviceLogPath = Join-Path $dataDir 'logs\service.log' - Assert-True (Test-Path -LiteralPath $serviceLogPath -PathType Leaf) ` - 'Hidden sidecar did not create its diagnostic service log.' - $receipt.checks['firstBootHiddenService'] = $true - $receipt.checks['serviceLog'] = $true - $sidecarNpmPrefix = Join-Path $dataDir 'npm\prefix' - $sidecarNpmCache = Join-Path $dataDir 'npm\cache' - Assert-True (Test-Path -LiteralPath $sidecarNpmPrefix -PathType Container) ` - 'First boot did not create the sidecar npm prefix directory.' - Assert-True (Test-Path -LiteralPath $sidecarNpmCache -PathType Container) ` - 'First boot did not create the sidecar npm cache directory.' - $receipt.checks['sidecarNpmDataDirectories'] = $true - $vaultKeyPath = Join-Path $dataDir '.vault-key' - Assert-VaultKeyAclRestricted $vaultKeyPath - $receipt.checks['vaultKeyAclRestricted'] = $true - if ($RequireVersionToVersionUpgrade) { - Assert-True ( - (Get-FileHash -LiteralPath $vaultKeyPath -Algorithm SHA256).Hash -eq $upgradeVaultKeySha256 - ) 'Upgrade changed the existing Windows vault key.' - Assert-True ( - (Get-FileHash -LiteralPath $dataMarker -Algorithm SHA256).Hash -eq $upgradeDataMarkerSha256 - ) 'Candidate launch changed or removed configured user data.' - Assert-True ( - (Get-FileHash -LiteralPath $profileDataMarker -Algorithm SHA256).Hash -eq - $upgradeProfileMarkerSha256 - ) 'Candidate launch changed or removed the profile data marker.' - $receipt.checks['upgradeVaultKeyPreserved'] = $true - $receipt.checks['candidateLaunch'] = $true - $receipt.checks['relaunchAfterUpgrade'] = $true - } - $proxy = Invoke-BuiltInProxyLivenessProbe -Uri "$baseUrl/v1/health/liveliness" - Assert-True ($proxy.status -eq 'healthy') 'Built-in provider proxy is not healthy' - Assert-True ((Get-HttpStatusCode "$baseUrl/api/tier") -eq 401) ` - 'A protected API route did not reject an unauthenticated loopback request' - $receipt.checks['unauthenticatedProtectedRoute'] = $true - $headers = Get-CertificateSessionHeaders ` - $baseUrl $nodeCommand.Source $bootstrapHelperPath $webViewDebugPort - $receipt.checks['firstBootUi'] = $true - $tier = Invoke-JsonRequest "$baseUrl/api/tier" $headers - Assert-True ([string]$tier.tier -ceq 'FREE') ` - "A clean Solo install reported an unexpected effective tier: $($tier.tier)" - $receipt.certifiedTier = 'FREE' - $receipt.checks['soloTier'] = $true - if ($RequireVersionToVersionUpgrade) { - Assert-True ($null -ne $certificateLifecycleData) ` - 'Upgrade lifecycle data was not created by the previous release.' - Assert-CertificateLifecycleData $baseUrl $headers $certificateLifecycleData $dataDir - $receipt.checks['upgradeRealWorkspaceAndMemoryPreserved'] = $true - } else { - $certificateLifecycleData = New-CertificateLifecycleData ` - $baseUrl $headers $runId $dataDir - $receipt.lifecycleData = $certificateLifecycleData - $receipt.checks['realWorkspaceAndMemorySeeded'] = $true - } - $marketplace = Invoke-JsonRequest ` - "$baseUrl/api/marketplace/search?type=mcp&source=mcp_registry&limit=100" ` - $headers ` - -TimeoutSeconds 30 - $marketplacePackages = @($marketplace.packages) - Assert-True ($marketplacePackages.Count -ge 1) ` - 'Clean installed marketplace API returned no trusted MCP catalog entries.' - $marketplaceNames = @($marketplacePackages | ForEach-Object { [string]$_.name }) - Assert-True ($marketplaceNames -contains 'memory') ` - 'Clean installed marketplace API did not return the canonical memory MCP.' - Assert-True (Test-Path -LiteralPath $writableMarketplaceDb -PathType Leaf) ` - 'First boot did not create the writable marketplace database.' - Assert-True ( - (Get-FileHash -LiteralPath $installedMarketplaceDb -Algorithm SHA256).Hash -eq - $marketplaceResourceSha256 - ) 'First boot modified the immutable resources\marketplace.db payload.' - $receipt.checks['marketplaceApi'] = $true - if (-not $RequireVersionToVersionUpgrade) { - $chatProbeMessage = "installer-certificate-no-model-$runId" - $chatResponse = Invoke-JsonPostRequest "$baseUrl/api/chat" @{ - message = $chatProbeMessage - sessionId = "installer-certificate-no-model-$runId" - } $headers - $chatContent = [string]$chatResponse.Content - Assert-True ([int]$chatResponse.StatusCode -eq 200) ` - 'Clean no-model chat did not return HTTP 200.' - Assert-True ( - ([string]$chatResponse.Headers['Content-Type']).StartsWith('text/event-stream') - ) 'Clean no-model chat did not return an SSE stream.' - Assert-True ([regex]::Matches( - $chatContent, - '(?m)^event:[ \t]*done[ \t]*\r?$' - ).Count -eq 1) 'Clean no-model chat did not complete with exactly one done event.' - Assert-True (-not ($chatContent -match '(?m)^event:[ \t]*error[ \t]*\r?$')) ` - 'Clean no-model chat emitted an error event.' - Assert-True ($chatContent.Contains('No AI model is ready')) ` - 'Clean no-model chat did not report that model setup is required.' - Assert-True (-not $chatContent.Contains($chatProbeMessage)) ` - 'Clean no-model chat echoed the prompt instead of reporting setup-required state.' - $receipt.checks['noModelChatSetupRequired'] = $true - } - $embedding = Invoke-JsonRequest "$baseUrl/api/embedding/status" $headers - Assert-True ($embedding.activeProvider -eq 'inprocess') ` - "Clean install did not load the in-process embedding model: $($embedding.activeProvider)" - Assert-True ($embedding.modelName -eq 'Xenova/all-MiniLM-L6-v2') ` - "Clean install loaded an unexpected embedding model: $($embedding.modelName)" - $embeddingModelPath = Join-Path $dataDir 'models\Xenova\all-MiniLM-L6-v2\onnx\model.onnx' - Assert-True (Test-Path -LiteralPath $embeddingModelPath -PathType Leaf) ` - 'In-process embedding model reported ready without a model payload' - $embeddingModelFile = Get-Item -LiteralPath $embeddingModelPath - Assert-True ($embeddingModelFile.Length -gt 10MB) 'Downloaded embedding model payload is unexpectedly small' - $localInference = Invoke-JsonRequest "$baseUrl/api/local-inference/status" $headers - Assert-True ($localInference.dockerRequired -eq $false) 'Local inference incorrectly requires Docker' - Assert-True ($localInference.managedRuntime.supported -eq $true) ` - 'Managed local inference runtime is not supported by the packaged Windows app' - if ($VerifyManagedModel) { - $bootstrapResponse = Invoke-JsonPostRequest ` - "$baseUrl/api/local-inference/bootstrap" ` - @{} ` - $headers ` - $managedOperationTimeoutSeconds - $bootstrap = $bootstrapResponse.Content | ConvertFrom-Json - Assert-True ([int]$bootstrapResponse.StatusCode -eq 200 -and $bootstrap.ok -eq $true) ` - 'The packaged managed local runtime did not bootstrap successfully.' - Assert-True ($bootstrap.dockerRequired -eq $false) ` - 'The packaged managed local runtime unexpectedly requires Docker.' - $receipt.checks['managedRuntimeBootstrap'] = $true - - if ($RequireVersionToVersionUpgrade) { - Assert-True ( - -not [string]::IsNullOrWhiteSpace($upgradeManagedModelName) -and - $upgradeManagedModelDigest -match '^sha256:[0-9a-f]{64}$' - ) 'The upgrade certificate has no previous managed-model identity.' - $preservedStatus = Invoke-JsonRequest "$baseUrl/api/local-inference/status" $headers - $preservedOllamaServers = @( - $preservedStatus.servers | Where-Object { [string]$_.type -eq 'ollama' } - ) - Assert-True ($preservedStatus.offlineReady -eq $true -and $preservedOllamaServers.Count -eq 1) ` - 'The candidate did not start the managed model preserved from the previous release.' - Assert-True (@($preservedOllamaServers[0].models) -contains $upgradeManagedModelName) ` - 'The candidate did not advertise the managed model preserved from the previous release.' - Assert-True ($null -ne $preservedOllamaServers[0].modelDigests) ` - 'The candidate did not advertise managed-model digests after upgrade.' - $preservedDigestProperty = $preservedOllamaServers[0].modelDigests.PSObject.Properties[ - $upgradeManagedModelName - ] - Assert-True ( - $null -ne $preservedDigestProperty -and - [string]$preservedDigestProperty.Value -ceq $upgradeManagedModelDigest - ) 'The candidate changed the managed-model digest during upgrade.' - $receipt.checks['upgradeManagedModelPreserved'] = $true - } - - $pullResponse = Invoke-JsonPostRequest ` - "$baseUrl/api/local-inference/pull" ` - @{ model = $managedCertificateModel } ` - $headers ` - $managedOperationTimeoutSeconds - $pull = $pullResponse.Content | ConvertFrom-Json - Assert-True ( - [int]$pullResponse.StatusCode -eq 200 -and - $pull.ok -eq $true -and - $pull.verifiedGeneration -eq $true - ) 'The managed local model did not complete its generation probe.' - Assert-True (-not [string]::IsNullOrWhiteSpace([string]$pull.model)) ` - 'The managed local model pull returned no installed model identity.' - Assert-True ([string]$pull.digest -match '^sha256:[0-9a-f]{64}$') ` - 'The managed local model pull returned no immutable manifest digest.' - if ($RequireVersionToVersionUpgrade) { - Assert-True ( - [string]$pull.model -ceq $upgradeManagedModelName -and - [string]$pull.digest -ceq $upgradeManagedModelDigest - ) 'The candidate managed-model verification did not preserve the previous release digest.' - } - $receipt.checks['managedModelPull'] = $true - - $managedStatus = Invoke-JsonRequest "$baseUrl/api/local-inference/status" $headers - Assert-True ($managedStatus.offlineReady -eq $true) ` - 'The managed local model was pulled but offline readiness is false.' - Assert-True ([int]$managedStatus.totalLocalModels -ge 1) ` - 'The managed runtime did not advertise an installed local model.' - $localChatResponse = Invoke-JsonPostRequest "$baseUrl/api/chat" @{ - message = 'Reply with one short sentence confirming that local inference works.' - model = "ollama/$($pull.model)" - sessionId = "installer-certificate-managed-model-$runId" - } $headers 300 - $localChatContent = [string]$localChatResponse.Content - Assert-True ([int]$localChatResponse.StatusCode -eq 200) ` - 'Managed local-model chat did not return HTTP 200.' - Assert-True ( - ([string]$localChatResponse.Headers['Content-Type']).StartsWith('text/event-stream') - ) 'Managed local-model chat did not return an SSE stream.' - Assert-True (-not ($localChatContent -match '(?m)^event:[ \t]*error[ \t]*\r?$')) ` - 'Managed local-model chat emitted an error event.' - Assert-True (-not $localChatContent.Contains('No AI model is ready')) ` - 'Managed local-model chat fell back to setup-required mode.' - $localDoneMatches = [regex]::Matches( - $localChatContent, - '(?m)^event:[ \t]*done[ \t]*\r?\ndata:[ \t]*(?[^\r\n]+)\r?$' - ) - Assert-True ($localDoneMatches.Count -eq 1) ` - 'Managed local-model chat did not complete with exactly one done event.' - $localDone = $localDoneMatches[0].Groups['data'].Value | ConvertFrom-Json - Assert-True (-not [string]::IsNullOrWhiteSpace([string]$localDone.content)) ` - 'Managed local-model chat completed without response content.' - Assert-True ([string]$localDone.model -eq "ollama/$($pull.model)") ` - 'Managed local-model chat reported a model other than the requested local model.' - $receipt.managedModelVerified = $true - $receipt.managedModelDigest = [string]$pull.digest - $receipt.managedModel = [ordered]@{ - name = [string]$pull.model - manifestDigest = [string]$pull.digest - pullGenerationVerified = $true - chatResponseChars = ([string]$localDone.content).Length - } - $receipt.checks['managedModelChat'] = $true - } - $receipt.checks['firstBoot'] = $true - $receipt.checks['database'] = $health.database.healthy - $receipt.checks['builtInProxyLiveness'] = $true - $receipt.checks['sessionAuth'] = $true - $receipt.embeddingPayloadReady = $true - $receipt.embeddingPayload = [ordered]@{ - name = $embedding.modelName - sizeBytes = $embeddingModelFile.Length - } - $receipt.checks['embeddingPayloadReady'] = $true - $receipt.checks['dockerIndependentRuntimePrerequisites'] = $true - if ($RequireVersionToVersionUpgrade) { - Assert-True ( - (Get-FileHash -LiteralPath (Join-Path $dataDir '.vault-key') -Algorithm SHA256).Hash -eq - $upgradeVaultKeySha256 - ) 'Candidate activity changed the upgraded Windows vault key.' - Assert-True ( - (Get-FileHash -LiteralPath $dataMarker -Algorithm SHA256).Hash -eq - $upgradeDataMarkerSha256 - ) 'Candidate activity changed or removed upgraded user data.' - Assert-True ( - (Get-FileHash -LiteralPath $profileDataMarker -Algorithm SHA256).Hash -eq - $upgradeProfileMarkerSha256 - ) 'Candidate activity changed or removed upgraded profile data.' - } else { - New-Item -ItemType Directory -Path $dataDir -Force | Out-Null - Set-Content -LiteralPath $dataMarker -Value $runId -Encoding UTF8 - } - } finally { - Stop-InstalledProcesses $appExecutable $serviceScript $managedRuntimeRoot - Wait-ForInstalledRuntimeStop $appExecutable $serviceScript 3333 ` - -ManagedRuntimeRoot $managedRuntimeRoot -AdditionalPorts @($ollamaPort, $webViewDebugPort) - $firstProcess.Dispose() - } - - # Prove a same-version repair actually restores installed bytes instead of - # merely returning success while leaving a stale payload in place. - $serviceHash = (Get-FileHash -LiteralPath $serviceScript -Algorithm SHA256).Hash - Set-Content -LiteralPath $serviceScript -Value '// deliberately corrupted by installer certificate' -Encoding UTF8 - Set-Content -LiteralPath $installedMarketplaceDb ` - -Value 'deliberately corrupted by installer certificate' -Encoding UTF8 - Assert-True ((Get-FileHash -LiteralPath $serviceScript -Algorithm SHA256).Hash -ne $serviceHash) ` - 'Could not prepare the repair probe' - Assert-True ( - (Get-FileHash -LiteralPath $installedMarketplaceDb -Algorithm SHA256).Hash -ne - $marketplaceResourceSha256 - ) 'Could not prepare the marketplace repair probe' - Assert-NoForeignWaggleProcesses $appExecutable - if ($RequireVersionToVersionUpgrade) { - Assert-ArtifactIdentity ` - $InstallerPath ` - $ExpectedCandidateInstallerSha256 ` - $ExpectedSignerThumbprint ` - $ExpectedSignerSubject ` - 'Candidate installer before repair' - } - Invoke-RawProcess $InstallerPath "/S /D=$installDir" 420 - if ($RequireVersionToVersionUpgrade) { - Assert-ArtifactIdentity ` - $InstallerPath ` - $ExpectedCandidateInstallerSha256 ` - $ExpectedSignerThumbprint ` - $ExpectedSignerSubject ` - 'Candidate installer after repair' - } - Wait-ForInstalledRuntimeStop $appExecutable $serviceScript 3333 ` - -ManagedRuntimeRoot $managedRuntimeRoot -AdditionalPorts @($ollamaPort, $webViewDebugPort) - Assert-True ((Get-FileHash -LiteralPath $serviceScript -Algorithm SHA256).Hash -eq $serviceHash) ` - 'Same-version repair did not restore resources/service.js' - Assert-True ( - (Get-FileHash -LiteralPath $installedMarketplaceDb -Algorithm SHA256).Hash -eq - $marketplaceResourceSha256 - ) 'Same-version repair did not restore resources/marketplace.db' - Assert-True (Test-Path -LiteralPath $dataMarker -PathType Leaf) 'Repair removed user data' - if ($RequireVersionToVersionUpgrade) { - Assert-True ( - (Get-FileHash -LiteralPath (Join-Path $dataDir '.vault-key') -Algorithm SHA256).Hash -eq - $upgradeVaultKeySha256 - ) 'Same-version repair changed the upgraded Windows vault key.' - Assert-True ( - (Get-FileHash -LiteralPath $dataMarker -Algorithm SHA256).Hash -eq $upgradeDataMarkerSha256 - ) 'Same-version repair changed upgraded user data.' - Assert-True ( - (Get-FileHash -LiteralPath $profileDataMarker -Algorithm SHA256).Hash -eq - $upgradeProfileMarkerSha256 - ) 'Same-version repair changed upgraded profile data.' - } - $repairRegistration = Get-ItemProperty -LiteralPath $uninstallRegistry - Assert-True ( - [string]::Equals( - ([string]$repairRegistration.InstallLocation).Trim('"'), - $installDir, - [System.StringComparison]::OrdinalIgnoreCase - ) - ) 'Repair changed the registered install location' - Assert-True ( - [string]::Equals( - [System.IO.Path]::GetFullPath(([string]$repairRegistration.UninstallString).Trim().Trim('"')), - [System.IO.Path]::GetFullPath($registeredUninstaller), - [System.StringComparison]::OrdinalIgnoreCase - ) - ) 'Repair changed the registered uninstaller' - $repairProductRegistration = Get-Item -LiteralPath $productRegistry - Assert-True ( - [string]::Equals( - [System.IO.Path]::GetFullPath(([string]$repairProductRegistration.GetValue('')).Trim('"')), - [System.IO.Path]::GetFullPath($installDir), - [System.StringComparison]::OrdinalIgnoreCase - ) - ) 'Repair changed the product install location' - foreach ($shortcut in $installedShortcuts) { - Assert-True (Test-Path -LiteralPath $shortcut -PathType Leaf) ` - "Repair removed an installed shortcut: $shortcut" - } - Assert-ShortcutTargets $installedShortcuts $appExecutable - $receipt.checks['sameVersionRepair'] = $true - $receipt.checks['repairRegistrations'] = $true - - $runtimeConfirmedStopped = $false - $webViewDebugPort = if ($WebViewDebugPort -gt 0) { $WebViewDebugPort } else { Get-FreeTcpPort } - $secondProcess = Start-InstalledApp $appExecutable $webViewDebugPort - try { - $null = Wait-ForHealth $baseUrl $StartupTimeoutSeconds - $secondProcess.Refresh() - Assert-True (-not $secondProcess.HasExited) 'The installed desktop process exited after repair' - Assert-NoVisibleConsoleDescendant $secondProcess.Id - $receipt.checks['repairHiddenService'] = $true - $repairHeaders = Get-CertificateSessionHeaders ` - $baseUrl $nodeCommand.Source $bootstrapHelperPath $webViewDebugPort - $receipt.checks['repairUi'] = $true - $repairTier = Invoke-JsonRequest "$baseUrl/api/tier" $repairHeaders - Assert-True ([string]$repairTier.tier -ceq 'FREE') ` - "The repaired Solo install reported an unexpected effective tier: $($repairTier.tier)" - $receipt.checks['repairSoloTier'] = $true - Assert-CertificateLifecycleData $baseUrl $repairHeaders $certificateLifecycleData $dataDir - if ($VerifyManagedModel) { - $managedModelName = [string]$receipt.managedModel.name - Assert-True (-not [string]::IsNullOrWhiteSpace($managedModelName)) ` - 'The repair certificate lost the managed model identity.' - $repairManagedStatus = $null - $repairManagedDeadline = [DateTime]::UtcNow.AddSeconds(300) - do { - try { - $repairManagedStatus = Invoke-JsonRequest "$baseUrl/api/local-inference/status" $repairHeaders - } catch { - $repairManagedStatus = $null - } - if ($null -ne $repairManagedStatus -and $repairManagedStatus.offlineReady -eq $true) { - break - } - Start-Sleep -Seconds 1 - } while ([DateTime]::UtcNow -lt $repairManagedDeadline) - Assert-True ($null -ne $repairManagedStatus -and $repairManagedStatus.offlineReady -eq $true) ` - 'The persisted managed local model did not become ready after repair.' - $repairOllamaServers = @( - $repairManagedStatus.servers | Where-Object { [string]$_.type -eq 'ollama' } - ) - Assert-True ($repairOllamaServers.Count -eq 1) ` - 'The repaired install did not expose exactly one Ollama runtime.' - Assert-True (@($repairOllamaServers[0].models) -contains $managedModelName) ` - 'The repaired install did not preserve the certified managed model.' - Assert-True ($null -ne $repairOllamaServers[0].modelDigests) ` - 'The repaired install did not advertise managed-model digests.' - $repairDigestProperty = $repairOllamaServers[0].modelDigests.PSObject.Properties[ - $managedModelName - ] - Assert-True ( - $null -ne $repairDigestProperty -and - [string]$repairDigestProperty.Value -ceq [string]$receipt.managedModelDigest - ) 'The repaired install changed the certified managed-model digest.' - $receipt.checks['repairManagedModelDigestPreserved'] = $true - - $proxyChatResponse = Invoke-JsonPostRequest "$baseUrl/v1/chat/completions" @{ - model = "ollama/$managedModelName" - messages = @( - [ordered]@{ - role = 'user' - content = 'Reply with one short sentence confirming that local proxy inference works.' - } - ) - max_tokens = 32 - stream = $false - } $repairHeaders 300 - Assert-True ([int]$proxyChatResponse.StatusCode -eq 200) ` - 'The repaired built-in proxy did not complete a managed local-model request.' - $proxyChat = $proxyChatResponse.Content | ConvertFrom-Json - $proxyChoices = @($proxyChat.choices) - Assert-True ($proxyChoices.Count -eq 1) ` - 'The repaired built-in proxy returned an unexpected choice count.' - $proxyContent = [string]$proxyChoices[0].message.content - Assert-True (-not [string]::IsNullOrWhiteSpace($proxyContent)) ` - 'The repaired built-in proxy completed without response content.' - Assert-True ([string]$proxyChat.model -eq $managedModelName) ` - 'The repaired built-in proxy did not strip the Ollama routing prefix.' - $receipt.managedModel['proxyRestartChatResponseChars'] = $proxyContent.Length - $receipt.checks['managedModelProxyRestartChat'] = $true - } - $receipt.checks['repairPreservedData'] = $true - $receipt.checks['repairRealWorkspaceAndMemoryPreserved'] = $true - $receipt.checks['relaunchAfterRepair'] = $true - } finally { - Stop-InstalledProcesses $appExecutable $serviceScript $managedRuntimeRoot - Wait-ForInstalledRuntimeStop $appExecutable $serviceScript 3333 ` - -ManagedRuntimeRoot $managedRuntimeRoot -AdditionalPorts @($ollamaPort, $webViewDebugPort) - $runtimeConfirmedStopped = $true - $secondProcess.Dispose() - } - - Assert-NoForeignWaggleProcesses $appExecutable - $preUninstallDataManifest = @(Get-CertificateDataManifest $profileDataDir) - Assert-True ($preUninstallDataManifest.Count -gt 0) ` - 'Default-profile manifest is empty before uninstall.' - $receipt.lifecycleData['preUninstallManifestEntryCount'] = $preUninstallDataManifest.Count - $receipt.lifecycleData['preUninstallManifestSha256'] = Get-CertificateDataManifestDigest ` - $preUninstallDataManifest - $runtimeConfirmedStopped = $false - Invoke-RawProcess $registeredUninstaller '/S' 300 - Wait-ForPathState $installDir $false 90 - # NSIS copies the uninstaller to a temporary process. The launcher can exit - # and the install directory can disappear before that process finishes the - # registry and shortcut tail, so wait on the actual postconditions. - Wait-ForPathState $uninstallRegistry $false 30 - $receipt.checks['uninstallerCleanup'] = $true - Remove-CertificateProductRegistry $productRegistry $installDir - Assert-CertificateUninstallPostconditions ` - -InstallDir $installDir ` - -UninstallRegistry $uninstallRegistry ` - -ProductRegistry $productRegistry ` - -RunRegistry $runRegistry ` - -RunRegistryValue $runRegistryValue ` - -ShortcutPaths $shortcutCandidates ` - -AppExecutable $appExecutable ` - -ServiceScript $serviceScript ` - -Port 3333 ` - -ManagedRuntimeRoot $managedRuntimeRoot ` - -AdditionalPorts @($ollamaPort, $webViewDebugPort) - $uninstallPostconditionsConfirmed = $true - $runtimeConfirmedStopped = $true - $postUninstallDataManifest = @(Get-CertificateDataManifest $profileDataDir) - Assert-CertificateDataManifest $preUninstallDataManifest $postUninstallDataManifest - $postUninstallManifestSha256 = Get-CertificateDataManifestDigest $postUninstallDataManifest - Assert-True ( - [string]$postUninstallManifestSha256 -ceq - [string]$receipt.lifecycleData.preUninstallManifestSha256 - ) 'Silent uninstall changed the default-profile manifest digest.' - $receipt.lifecycleData['postUninstallManifestSha256'] = $postUninstallManifestSha256 - $receipt.checks['uninstallRealWorkspaceAndMemoryPreserved'] = $true - if ($VerifyManagedModel) { - $receipt.checks['managedRuntimeCleanup'] = $true - } - $installerStarted = $false - Assert-True (Test-Path -LiteralPath $dataMarker -PathType Leaf) ` - 'Silent uninstall did not preserve user data by default' - Assert-True (Test-Path -LiteralPath $profileDataMarker -PathType Leaf) ` - 'Silent uninstall removed the Windows profile data path' - Assert-True ((Get-Content -Raw -LiteralPath $profileDataMarker).Trim() -eq $runId) ` - 'Silent uninstall changed the Windows profile data marker' - if ($RequireVersionToVersionUpgrade) { - Assert-True ( - (Get-FileHash -LiteralPath (Join-Path $dataDir '.vault-key') -Algorithm SHA256).Hash -eq - $upgradeVaultKeySha256 - ) 'Silent uninstall changed the upgraded Windows vault key.' - Assert-True ( - (Get-FileHash -LiteralPath $dataMarker -Algorithm SHA256).Hash -eq $upgradeDataMarkerSha256 - ) 'Silent uninstall changed upgraded user data.' - Assert-True ( - (Get-FileHash -LiteralPath $profileDataMarker -Algorithm SHA256).Hash -eq - $upgradeProfileMarkerSha256 - ) 'Silent uninstall changed upgraded profile data.' - } - $receipt.checks['silentUninstall'] = $true - $receipt.checks['certificateRegistryCleanup'] = $true - $receipt.checks['configuredDataDirPreserved'] = $true - $receipt.checks['profileDataPathPreserved'] = $true - Remove-CertificateProfileData ` - $profileDataDir $profileDataMarker $runId $profileAbsenceProven $runtimeConfirmedStopped - $profileRootOwned = $false - $receipt.checks['certificateProfileCleanup'] = $true - $receipt.status = 'passed' -} catch { - $receipt.status = 'failed' - $receipt.error = $_.Exception.Message - $serviceLog = Join-Path $dataDir 'logs\service.log' - if (Test-Path -LiteralPath $serviceLog -PathType Leaf) { - $receipt['serviceLogTail'] = @(Get-Content -LiteralPath $serviceLog -Tail 80) - } - throw -} finally { - try { - $runtimeConfirmedStopped = $false - Stop-InstalledProcesses $appExecutable $serviceScript $managedRuntimeRoot - Wait-ForInstalledRuntimeStop $appExecutable $serviceScript 3333 ` - -ManagedRuntimeRoot $managedRuntimeRoot -AdditionalPorts @($ollamaPort, $webViewDebugPort) - Assert-NoForeignWaggleProcesses $appExecutable - Assert-TcpPortAvailable 3333 - $runtimeConfirmedStopped = $true - } catch { - $receipt.status = 'failed' - $receipt['runtimeCleanupError'] = $_.Exception.Message - } - if (Test-Path -LiteralPath $uninstaller -PathType Leaf) { - try { - $runtimeConfirmedStopped = $false - Assert-NoForeignWaggleProcesses $appExecutable - Invoke-RawProcess $uninstaller '/S' 300 - Wait-ForPathState $installDir $false 90 - } catch { - $receipt.status = 'failed' - $receipt['uninstallerCleanupError'] = $_.Exception.Message - } - } - if ($installerStarted) { - try { - Remove-CertificateProductRegistry $productRegistry $installDir - } catch { - $receipt.status = 'failed' - $receipt['cleanupError'] = $_.Exception.Message - } - } - if ($installerStarted) { - $uninstallPostconditionsConfirmed = $false - try { - Assert-CertificateUninstallPostconditions ` - -InstallDir $installDir ` - -UninstallRegistry $uninstallRegistry ` - -ProductRegistry $productRegistry ` - -RunRegistry $runRegistry ` - -RunRegistryValue $runRegistryValue ` - -ShortcutPaths $shortcutCandidates ` - -AppExecutable $appExecutable ` - -ServiceScript $serviceScript ` - -Port 3333 ` - -ManagedRuntimeRoot $managedRuntimeRoot ` - -AdditionalPorts @($ollamaPort, $webViewDebugPort) - $runtimeConfirmedStopped = $true - $uninstallPostconditionsConfirmed = $true - } catch { - $receipt.status = 'failed' - $receipt['uninstallPostconditionError'] = $_.Exception.Message - } - } elseif (-not $uninstallPostconditionsConfirmed) { - $uninstallPostconditionsConfirmed = $runtimeConfirmedStopped - } - if ($profileRootOwned -and $uninstallPostconditionsConfirmed) { - try { - Remove-CertificateProfileData ` - $profileDataDir $profileDataMarker $runId $profileAbsenceProven $runtimeConfirmedStopped - $profileRootOwned = $false - } catch { - $receipt.status = 'failed' - $receipt['profileCleanupError'] = $_.Exception.Message - } - } elseif ($profileRootOwned) { - $receipt.status = 'failed' - $receipt['profileCleanupError'] = ` - 'Certificate profile was preserved because uninstall postconditions were not proven.' - } - if ($externalProfileRootsPreProven) { - try { - Assert-ExternalProfileRootsUnchanged $externalProfileRootBaselines - $receipt.checks['externalProfileRootsUnchanged'] = $true - } catch { - $receipt.status = 'failed' - $receipt['externalProfileIsolationError'] = $_.Exception.Message - } - } elseif ($receipt.status -eq 'passed') { - $receipt.status = 'failed' - $receipt['externalProfileIsolationError'] = ` - 'External profile roots were not proven before installer execution.' - } - if ($receipt.status -eq 'passed' -and -not $KeepArtifacts) { - try { - Remove-CertificateScratchRoot $scratchRoot $scratchOwnershipMarker $runId - } catch { - $receipt.status = 'failed' - $receipt['scratchCleanupError'] = $_.Exception.Message - } - } - try { - foreach ($name in $isolatedEnvironmentNames) { - [Environment]::SetEnvironmentVariable($name, $environmentSnapshot[$name], 'Process') - } - $receipt.checks['environmentRestored'] = $true - } catch { - $receipt.status = 'failed' - $receipt['environmentRestoreError'] = $_.Exception.Message - } - $receipt.finishedAt = [DateTime]::UtcNow.ToString('o') - $receipt['durationSeconds'] = [Math]::Round(([DateTime]::UtcNow - $startedAt).TotalSeconds, 3) - $receiptJson = $receipt | ConvertTo-Json -Depth 8 - Write-CertificateReceipt $receiptReservation $receiptJson -} - -if ($receipt.status -ne 'passed') { - $failureDetail = if ($receipt.error) { - $receipt.error - } elseif ($receipt.Contains('externalProfileIsolationError')) { - $receipt['externalProfileIsolationError'] - } elseif ($receipt.Contains('environmentRestoreError')) { - $receipt['environmentRestoreError'] - } elseif ($receipt.Contains('scratchCleanupError')) { - $receipt['scratchCleanupError'] - } else { - 'unknown failure' - } - throw "Windows installer certificate failed: $failureDetail" -} -Write-Host "Windows installer certificate passed: $ReceiptPath" diff --git a/scripts/publish-windows-release.ps1 b/scripts/publish-windows-release.ps1 deleted file mode 100644 index 78619e3..0000000 --- a/scripts/publish-windows-release.ps1 +++ /dev/null @@ -1,918 +0,0 @@ -[CmdletBinding()] -param( - [Parameter(Mandatory)] - [ValidateSet('bootstrap', 'upgrade')] - [string]$Mode -) - -Set-StrictMode -Version Latest -$ErrorActionPreference = 'Stop' - -function Assert-RemoteTagCommit { - param([string]$Tag, [string]$ExpectedCommit) - - $remoteTagLines = @( - git ls-remote --tags origin "refs/tags/$Tag" "refs/tags/$Tag^{}" - ) - if ($LASTEXITCODE -ne 0 -or $remoteTagLines.Count -eq 0) { - throw "Could not resolve remote release tag $Tag" - } - $resolvedTagLine = @( - $remoteTagLines | - Where-Object { $_ -match '\^\{\}$' } | - Select-Object -First 1 - ) - if ($resolvedTagLine.Count -eq 0) { - $resolvedTagLine = @($remoteTagLines | Select-Object -First 1) - } - $remoteTagSha = ( - [regex]::Split(([string]$resolvedTagLine[0]).Trim(), '\s+') - )[0] - if (-not [string]::Equals( - $remoteTagSha, - $ExpectedCommit, - [System.StringComparison]::OrdinalIgnoreCase - )) { - throw "Remote release tag $Tag no longer resolves to the certified commit" - } -} - -function Get-ProtectedSignerIdentity { - $approvedSubject = [string]$env:WINDOWS_CODESIGN_APPROVED_SUBJECT - $approvedThumbprint = [string]$env:WINDOWS_CODESIGN_APPROVED_THUMBPRINT - $hasApprovedSubject = -not [string]::IsNullOrWhiteSpace($approvedSubject) - $hasApprovedThumbprint = -not [string]::IsNullOrWhiteSpace($approvedThumbprint) - if ($hasApprovedSubject -eq $hasApprovedThumbprint) { - throw 'Exactly one protected publication signer identity must be configured' - } - if ($hasApprovedSubject) { - return [pscustomobject][ordered]@{ - mode = 'subject' - subject = $approvedSubject - thumbprint = $null - } - } - - $normalizedThumbprint = ($approvedThumbprint -replace '\s', '').ToUpperInvariant() - if ($normalizedThumbprint -notmatch '^[0-9A-F]{40}$') { - throw 'Protected publication signer thumbprint is invalid' - } - return [pscustomobject][ordered]@{ - mode = 'thumbprint' - subject = $null - thumbprint = $normalizedThumbprint - } -} - -function Assert-ExpectedAuthenticodeSignature { - param([System.IO.FileInfo]$Artifact, [object]$ExpectedIdentity) - - $signature = Get-AuthenticodeSignature -FilePath $Artifact.FullName - if ($signature.Status -ne 'Valid' -or - [string]$signature.SignatureType -ne 'Authenticode' -or - $null -eq $signature.SignerCertificate -or - $null -eq $signature.TimeStamperCertificate) { - throw "Artifact signature is no longer valid for the approved signer: $($Artifact.FullName)" - } - $signerSubject = [string]$signature.SignerCertificate.Subject - $signerThumbprint = ( - [string]$signature.SignerCertificate.Thumbprint -replace '\s', '' - ).ToUpperInvariant() - $matchesProtectedIdentity = if ($ExpectedIdentity.mode -ceq 'subject') { - [string]::Equals( - $signerSubject, - [string]$ExpectedIdentity.subject, - [System.StringComparison]::Ordinal - ) - } else { - [string]::Equals( - $signerThumbprint, - [string]$ExpectedIdentity.thumbprint, - [System.StringComparison]::Ordinal - ) - } - if (-not $matchesProtectedIdentity) { - throw "Artifact signature is no longer valid for the approved signer: $($Artifact.FullName)" - } - return [pscustomobject][ordered]@{ - subject = $signerSubject - thumbprint = $signerThumbprint - } -} - -function Assert-ReceiptSignerIdentity { - param([object]$ReceiptArtifact, [object]$ActualIdentity, [string]$Label) - - if ([string]::IsNullOrWhiteSpace([string]$ReceiptArtifact.signerSubject) -or - [string]::IsNullOrWhiteSpace([string]$ReceiptArtifact.signerThumbprint) -or - -not [string]::Equals( - [string]$ReceiptArtifact.signerSubject, - [string]$ActualIdentity.subject, - [System.StringComparison]::Ordinal - ) -or - -not [string]::Equals( - ([string]$ReceiptArtifact.signerThumbprint -replace '\s', '').ToUpperInvariant(), - [string]$ActualIdentity.thumbprint, - [System.StringComparison]::Ordinal - )) { - throw "$Label signer identity does not match the certified Authenticode artifact" - } -} - -function Assert-LifecycleReceiptSignerIdentities { - param( - [object]$Receipt, - [object]$PreviousLiveIdentity, - [object]$CandidateLiveIdentity - ) - - Assert-ReceiptSignerIdentity ` - $Receipt.previousInstaller ` - $PreviousLiveIdentity ` - 'Upgrade previous-installer receipt' - Assert-ReceiptSignerIdentity ` - $Receipt.previousInstalledApp ` - $PreviousLiveIdentity ` - 'Upgrade previous-installed-app receipt' - Assert-ReceiptSignerIdentity ` - $Receipt.installer ` - $CandidateLiveIdentity ` - 'Upgrade candidate-installer receipt' - Assert-ReceiptSignerIdentity ` - $Receipt.installedApp ` - $CandidateLiveIdentity ` - 'Upgrade candidate-installed-app receipt' -} - -function Assert-PassingWindowsCertificateReceipt { - param([object]$Receipt, [string]$ExpectedMode, [string]$Label) - - $schemaVersionIsIntegral = ( - $Receipt.schemaVersion -is [int] -or - $Receipt.schemaVersion -is [long] - ) - if (-not $schemaVersionIsIntegral -or - [long]$Receipt.schemaVersion -ne 4 -or - -not ($Receipt.certificationMode -is [string]) -or - -not [string]::Equals( - $Receipt.certificationMode, - $ExpectedMode, - [System.StringComparison]::Ordinal - ) -or - -not ($Receipt.status -is [string]) -or - -not [string]::Equals( - $Receipt.status, - 'passed', - [System.StringComparison]::Ordinal - )) { - throw "$Label is not a passing schema-v4 certificate" - } -} - -function Assert-PassingWindowsCertificateCheck { - param([object]$Receipt, [string]$CheckName, [string]$Label) - - $check = $Receipt.checks.PSObject.Properties[$CheckName] - if ($null -eq $check -or -not [bool]::True.Equals($check.Value)) { - throw "$Label check did not pass: $CheckName" - } -} - -function Assert-ExactReleaseAssets { - param([object]$Release, [object[]]$ExpectedAssets) - - $expectedNames = [string[]]@( - $ExpectedAssets | ForEach-Object { [string]$_.Name } - ) - $actualNames = [string[]]@( - $Release.assets | ForEach-Object { [string]$_.name } - ) - [System.Array]::Sort($expectedNames, [System.StringComparer]::Ordinal) - [System.Array]::Sort($actualNames, [System.StringComparer]::Ordinal) - if ($expectedNames.Count -ne $actualNames.Count) { - throw 'Published release assets do not exactly match the certified artifact set' - } - for ($index = 0; $index -lt $expectedNames.Count; $index += 1) { - if (-not [string]::Equals( - $expectedNames[$index], - $actualNames[$index], - [System.StringComparison]::Ordinal - )) { - throw 'Published release assets do not exactly match the certified artifact set' - } - } -} - -function Set-ReadOnlyCreatedReleaseId { - param([string]$Value) - - if ([string]::IsNullOrWhiteSpace($Value) -or - $null -ne ( - Get-Variable -Name createdReleaseId -Scope Script ` - -ErrorAction SilentlyContinue - )) { - throw 'Created release identity must be set exactly once' - } - Set-Variable ` - -Name createdReleaseId ` - -Scope Script ` - -Value $Value ` - -Option ReadOnly -} - -function Assert-ReleaseIdentity { - param( - [object]$Release, - [string]$ExpectedId, - [string]$ExpectedTag, - [bool]$ExpectedDraft, - [string]$Label - ) - - if ([string]::IsNullOrWhiteSpace($ExpectedId) -or - [string]$Release.id -cne $ExpectedId -or - [string]$Release.tagName -cne $ExpectedTag -or - [string]$Release.name -cne "Waggle $ExpectedTag" -or - -not ($Release.isDraft -is [bool]) -or - -not [bool]::Equals($Release.isDraft, $ExpectedDraft) -or - -not ($Release.isPrerelease -is [bool]) -or - [bool]::True.Equals($Release.isPrerelease)) { - throw "$Label identity does not match the newly-created release" - } -} - -function New-ReleaseAssetManifest { - param([System.IO.FileInfo[]]$Assets) - - $manifest = @( - foreach ($asset in $Assets) { - if ($null -eq $asset -or - -not $asset.Exists -or - [System.IO.Path]::GetFileName($asset.Name) -cne $asset.Name) { - throw 'Release asset manifest contains an invalid local file' - } - [pscustomobject]@{ - Name = [string]$asset.Name - FullName = [string]$asset.FullName - SizeBytes = [int64]$asset.Length - Sha256 = ( - Get-FileHash -LiteralPath $asset.FullName -Algorithm SHA256 - ).Hash.ToUpperInvariant() - } - } - ) - for ($left = 0; $left -lt $manifest.Count; $left += 1) { - for ($right = $left + 1; $right -lt $manifest.Count; $right += 1) { - if ([string]::Equals( - [string]$manifest[$left].Name, - [string]$manifest[$right].Name, - [System.StringComparison]::Ordinal - )) { - throw 'Release asset manifest contains a duplicate exact filename' - } - } - } - return $manifest -} - -function Assert-ReleaseAssetFileMatchesManifest { - param( - [string]$Path, - [object]$ExpectedAsset, - [string]$Label - ) - - $asset = Get-Item -LiteralPath $Path -ErrorAction Stop - $sha256 = ( - Get-FileHash -LiteralPath $asset.FullName -Algorithm SHA256 - ).Hash - if (-not ($asset -is [System.IO.FileInfo]) -or - [string]$asset.Name -cne [string]$ExpectedAsset.Name -or - [int64]$asset.Length -ne [int64]$ExpectedAsset.SizeBytes -or - -not [string]::Equals( - $sha256, - [string]$ExpectedAsset.Sha256, - [System.StringComparison]::OrdinalIgnoreCase - )) { - throw "$Label does not match the immutable release-asset manifest" - } -} - -function Assert-LocalReleaseAssetsUnchanged { - param([object[]]$Manifest) - - foreach ($expectedAsset in $Manifest) { - Assert-ReleaseAssetFileMatchesManifest ` - ([string]$expectedAsset.FullName) ` - $expectedAsset ` - "Local release asset $($expectedAsset.Name)" - } -} - -function Assert-RemoteReleaseAssetContents { - param( - [string]$Tag, - [object]$Release, - [object[]]$Manifest, - [string]$Stage - ) - - Assert-ExactReleaseAssets $Release $Manifest - Assert-LocalReleaseAssetsUnchanged $Manifest - if ([string]::IsNullOrWhiteSpace([string]$env:RUNNER_TEMP)) { - throw 'RUNNER_TEMP is required for remote release-asset verification' - } - $downloadRoot = Join-Path ` - ([string]$env:RUNNER_TEMP) ` - "waggle-release-$Stage-$([guid]::NewGuid().ToString('N'))" - New-Item -ItemType Directory -Path $downloadRoot -ErrorAction Stop | - Out-Null - try { - gh release download $Tag --dir $downloadRoot - if ($LASTEXITCODE -ne 0) { - throw "Could not download $Stage release assets for byte verification" - } - $downloadedFiles = @( - Get-ChildItem -LiteralPath $downloadRoot -File - ) - if ($downloadedFiles.Count -ne $Manifest.Count) { - throw "$Stage release download does not contain the exact asset count" - } - foreach ($expectedAsset in $Manifest) { - Assert-ReleaseAssetFileMatchesManifest ` - (Join-Path $downloadRoot ([string]$expectedAsset.Name)) ` - $expectedAsset ` - "$Stage remote release asset $($expectedAsset.Name)" - } - } finally { - if (Test-Path -LiteralPath $downloadRoot) { - Remove-Item -LiteralPath $downloadRoot -Recurse -Force - } - } - Assert-LocalReleaseAssetsUnchanged $Manifest -} - -function Assert-ManagedModelAndMemoryEvidence { - param([object]$Receipt, [string]$Label) - - if (-not [bool]::True.Equals($Receipt.managedModelVerified)) { - throw "$Label does not prove a managed local-model chat completion" - } - if ([string]$Receipt.managedModelDigest -notmatch '^sha256:[0-9a-f]{64}$') { - throw "$Label does not bind the managed model to an immutable manifest digest" - } - if (-not [string]::Equals( - [string]$Receipt.certifiedTier, - 'FREE', - [System.StringComparison]::Ordinal - )) { - throw "$Label does not certify the Solo/FREE tier" - } - if ([string]::IsNullOrWhiteSpace( - [string]$Receipt.lifecycleData.workspaceId - ) -or - [long]$Receipt.lifecycleData.personalFrameId -lt 1 -or - [long]$Receipt.lifecycleData.workspaceFrameId -lt 1 -or - [int]$Receipt.lifecycleData.preUninstallManifestEntryCount -lt 1 -or - [string]$Receipt.lifecycleData.preUninstallManifestSha256 -notmatch '^[0-9A-F]{64}$' -or - [string]$Receipt.lifecycleData.postUninstallManifestSha256 -notmatch '^[0-9A-F]{64}$' -or - -not [string]::Equals( - [string]$Receipt.lifecycleData.preUninstallManifestSha256, - [string]$Receipt.lifecycleData.postUninstallManifestSha256, - [System.StringComparison]::Ordinal - )) { - throw "$Label does not bind real workspace and memory data to an unchanged uninstall manifest" - } -} - -function Assert-ReceiptSourceHashes { - param( - [object[]]$Receipts, - [System.IO.FileInfo]$Installer, - [string]$SourceRevision - ) - - $currentCertifierHash = ( - Get-FileHash -LiteralPath 'scripts/certify-windows-installer.ps1' ` - -Algorithm SHA256 - ).Hash - $currentHookHash = ( - Get-FileHash -LiteralPath 'app/src-tauri/nsis/installer.nsi' ` - -Algorithm SHA256 - ).Hash - $releaseDirectory = Split-Path -Parent ( - Split-Path -Parent $Installer.DirectoryName - ) - $generatedInstallerScripts = @( - Get-ChildItem -LiteralPath (Join-Path $releaseDirectory 'nsis') ` - -Recurse -Filter 'installer.nsi' -File - ) - if ($generatedInstallerScripts.Count -ne 1) { - throw 'Could not uniquely resolve generated NSIS source during publication' - } - $currentGeneratedInstallerHash = ( - Get-FileHash -LiteralPath $generatedInstallerScripts[0].FullName ` - -Algorithm SHA256 - ).Hash - $currentSidecarPath = 'app/src-tauri/resources/service.js' - if (-not (Test-Path -LiteralPath $currentSidecarPath -PathType Leaf)) { - throw 'Current source-bound sidecar bundle is missing during publication' - } - $currentSidecarBytes = [System.IO.File]::ReadAllBytes( - (Get-Item -LiteralPath $currentSidecarPath).FullName - ) - $sidecarNewlineIndex = [Array]::IndexOf($currentSidecarBytes, [byte]10) - if ($sidecarNewlineIndex -le 0) { - throw 'Current sidecar bundle is missing embedded provenance' - } - $sidecarFirstLine = [System.Text.Encoding]::UTF8.GetString( - $currentSidecarBytes, - 0, - $sidecarNewlineIndex - ) - $sidecarPrefix = '// Waggle-Sidecar-Provenance: ' - if (-not $sidecarFirstLine.StartsWith($sidecarPrefix, [System.StringComparison]::Ordinal)) { - throw 'Current sidecar bundle is missing embedded provenance' - } - $sidecarEncodedProvenance = $sidecarFirstLine.Substring($sidecarPrefix.Length) - try { - $sidecarProvenanceBytes = [Convert]::FromBase64String($sidecarEncodedProvenance) - if (-not [string]::Equals( - [Convert]::ToBase64String($sidecarProvenanceBytes), - $sidecarEncodedProvenance, - [System.StringComparison]::Ordinal - )) { - throw 'non-canonical provenance' - } - $sidecarManifest = [System.Text.Encoding]::UTF8.GetString($sidecarProvenanceBytes) | - ConvertFrom-Json - } catch { - throw 'Current sidecar bundle has invalid embedded provenance' - } - if (-not [string]::Equals( - [string]$sidecarManifest.sourceRevision, - $SourceRevision, - [System.StringComparison]::Ordinal - ) -or @($sidecarManifest.sourceInputs).Count -lt 4) { - throw 'Current sidecar provenance does not bind the publication source revision' - } - $sidecarProvenanceHasher = [System.Security.Cryptography.SHA256]::Create() - try { - $currentSidecarProvenanceHash = ( - [System.BitConverter]::ToString( - $sidecarProvenanceHasher.ComputeHash($sidecarProvenanceBytes) - ) - ).Replace('-', '') - } finally { - $sidecarProvenanceHasher.Dispose() - } - $currentSidecarHash = ( - Get-FileHash -LiteralPath $currentSidecarPath -Algorithm SHA256 - ).Hash - $currentSidecarSourceInputCount = @($sidecarManifest.sourceInputs).Count - - foreach ($certificateData in $Receipts) { - if (-not [string]::Equals( - $currentCertifierHash, - [string]$certificateData.evidence.certifierSha256, - [System.StringComparison]::OrdinalIgnoreCase - ) -or - -not [string]::Equals( - $currentHookHash, - [string]$certificateData.evidence.installerHookSha256, - [System.StringComparison]::OrdinalIgnoreCase - ) -or - -not [string]::Equals( - $currentGeneratedInstallerHash, - [string]$certificateData.evidence.generatedInstallerScriptSha256, - [System.StringComparison]::OrdinalIgnoreCase - ) -or - -not [string]::Equals( - $currentSidecarHash, - [string]$certificateData.evidence.sidecarBundleSha256, - [System.StringComparison]::OrdinalIgnoreCase - ) -or - -not [string]::Equals( - $currentSidecarProvenanceHash, - [string]$certificateData.evidence.sidecarProvenanceSha256, - [System.StringComparison]::OrdinalIgnoreCase - ) -or - -not [string]::Equals( - $SourceRevision, - [string]$certificateData.evidence.sidecarSourceRevision, - [System.StringComparison]::Ordinal - ) -or - [int]$certificateData.evidence.sidecarSourceInputCount -ne - $currentSidecarSourceInputCount - ) { - throw 'Lifecycle receipt source hashes do not match the release checkout' - } - } -} - -function Assert-ReleaseDoesNotExist { - param([string]$Tag) - - $probeOutput = @(gh release view $Tag --json id 2>&1) - $probeExitCode = $LASTEXITCODE - if ($probeExitCode -eq 0) { - throw "Refusing to use a pre-existing release: $Tag" - } - $probeText = [string]::Join("`n", [string[]]$probeOutput) - if ($probeText -notmatch '(?i)(release not found|HTTP\s+404)') { - throw "Could not prove that release $Tag does not already exist" - } -} - -function Assert-PublicationTagBindings { - param([string]$ReleaseMode, [string]$Tag, [string]$Commit) - - if ($ReleaseMode -ceq 'upgrade') { - Assert-RemoteTagCommit ` - ([string]$env:WINDOWS_UPGRADE_BASE_TAG) ` - ([string]$env:WAGGLE_UPGRADE_BASE_COMMIT) - } - Assert-RemoteTagCommit $Tag $Commit -} - -if (-not [string]::Equals( - $Mode, - [string]$env:WAGGLE_RELEASE_MODE, - [System.StringComparison]::Ordinal -)) { - throw 'Publisher mode does not match the resolved Windows release mode' -} - -$tag = [string]$env:GITHUB_REF_NAME -$sourceRevision = [string]$env:GITHUB_SHA -if ($tag -notmatch '^v\d+\.\d+\.\d+$' -or - $sourceRevision -cnotmatch '^[0-9a-f]{40}$') { - throw 'Publication requires an exact release tag and lowercase commit identity' -} - -$baselineInputs = @( - [string]$env:WINDOWS_UPGRADE_BASE_TAG, - [string]$env:WINDOWS_UPGRADE_BASE_ASSET_NAME, - [string]$env:WINDOWS_UPGRADE_BASE_SHA256, - [string]$env:WINDOWS_UPGRADE_BASE_COMMIT -) -if (@($baselineInputs | Where-Object { $_ -ne $_.Trim() }).Count -gt 0) { - throw 'Protected Windows upgrade-baseline inputs must not contain surrounding whitespace' -} - -if ($Mode -ceq 'bootstrap') { - $expectedBootstrapIdentity = "v0.2.0@$env:GITHUB_SHA" - if ($tag -cne 'v0.2.0' -or - -not [string]::Equals( - [string]$env:WINDOWS_BOOTSTRAP_RELEASE_IDENTITY, - $expectedBootstrapIdentity, - [System.StringComparison]::Ordinal - ) -or - @($baselineInputs | Where-Object { - -not [string]::IsNullOrEmpty($_) - }).Count -ne 0) { - throw 'Bootstrap publication is not bound to the exact authorized v0.2.0 release' - } -} else { - if (-not [string]::IsNullOrEmpty( - [string]$env:WINDOWS_BOOTSTRAP_RELEASE_IDENTITY - ) -or - @($baselineInputs | Where-Object { - [string]::IsNullOrEmpty($_) - }).Count -ne 0) { - throw 'Upgrade publication requires an empty bootstrap authorization and all baseline inputs' - } -} - -$installers = @( - Get-ChildItem -LiteralPath 'app/src-tauri/target' -Recurse ` - -Filter '*-setup.exe' -File | - Where-Object { $_.DirectoryName -match '[\\/]bundle[\\/]nsis$' } -) -if ($installers.Count -ne 1) { - throw "Expected exactly one certified NSIS installer, found $($installers.Count)" -} -$installer = $installers[0] -$cleanReceipt = Get-Item -LiteralPath ( - Join-Path $installer.DirectoryName 'windows-installer-certificate.json' -) -$upgradeReceiptPath = Join-Path ` - $installer.DirectoryName ` - 'windows-installer-upgrade-certificate.json' -if ($Mode -ceq 'bootstrap' -and - (Test-Path -LiteralPath $upgradeReceiptPath)) { - throw 'Bootstrap publication found an unexpected upgrade certificate' -} - -$cleanReceiptData = Get-Content -Raw -LiteralPath $cleanReceipt.FullName | - ConvertFrom-Json -Assert-PassingWindowsCertificateReceipt ` - $cleanReceiptData 'same-version-repair' 'Windows clean-install receipt' - -if (-not [string]::Equals( - [string]$cleanReceiptData.evidence.sourceRevision, - $sourceRevision, - [System.StringComparison]::Ordinal - ) -or - -not [string]::Equals( - [string]$cleanReceiptData.installer.name, - $installer.Name, - [System.StringComparison]::Ordinal - ) -or - [int64]$cleanReceiptData.installer.sizeBytes -ne $installer.Length) { - throw 'Clean-install receipt identity does not match the release artifact and commit' -} - -$candidateVersion = [string]( - Get-Content -Raw -LiteralPath 'app/src-tauri/tauri.conf.json' | - ConvertFrom-Json -).version -if ($candidateVersion -notmatch '^\d+\.\d+\.\d+$' -or - $tag -cne "v$candidateVersion" -or - [string]$env:WAGGLE_CERTIFIED_CANDIDATE_VERSION -cne $candidateVersion -or - ($Mode -ceq 'bootstrap' -and $candidateVersion -cne '0.2.0')) { - throw 'Published candidate version is not independently bound to the release tag' -} - -$installerSha256 = ( - Get-FileHash -LiteralPath $installer.FullName -Algorithm SHA256 -).Hash -if (-not [string]::Equals( - $installerSha256, - [string]$env:WAGGLE_CERTIFIED_CANDIDATE_SHA256, - [System.StringComparison]::OrdinalIgnoreCase - ) -or - -not [string]::Equals( - $installerSha256, - [string]$cleanReceiptData.installer.sha256, - [System.StringComparison]::OrdinalIgnoreCase - )) { - throw 'Certified installer hash no longer matches the clean receipt and pre-publication output' -} - -$approvedSignerIdentity = Get-ProtectedSignerIdentity -$installerSignerIdentity = Assert-ExpectedAuthenticodeSignature $installer $approvedSignerIdentity -if ($cleanReceiptData.installer.authenticodeStatus -ne 'Valid' -or - $cleanReceiptData.installedApp.authenticodeStatus -ne 'Valid' -or - $cleanReceiptData.installer.signatureType -ne 'Authenticode' -or - $cleanReceiptData.installedApp.signatureType -ne 'Authenticode' -or - [string]::IsNullOrWhiteSpace( - [string]$cleanReceiptData.installer.timestampAuthorityThumbprint - ) -or - [string]::IsNullOrWhiteSpace( - [string]$cleanReceiptData.installedApp.timestampAuthorityThumbprint - )) { - throw 'Clean-install receipt does not preserve valid signer and timestamp evidence' -} -Assert-ReceiptSignerIdentity ` - $cleanReceiptData.installer $installerSignerIdentity 'Clean-install installer receipt' -Assert-ReceiptSignerIdentity ` - $cleanReceiptData.installedApp $installerSignerIdentity 'Clean-install installed-app receipt' -Assert-ManagedModelAndMemoryEvidence ` - $cleanReceiptData ` - 'Clean-install receipt' - -$cleanRequiredChecks = @( - 'sourceRevision', 'sourceFilesClean', 'sidecarSourceProvenance', - 'generatedInstallerInclude', - 'profileDataDeletionAbsent', 'baseAppDataDeletionNeutralized', - 'authenticodeSignature', 'authenticodeSigner', 'authenticodeTimestamp', - 'installedAppAuthenticodeSignature', 'installedAppAuthenticodeSigner', - 'installedAppAuthenticodeTimestamp', 'silentInstall', - 'vaultKeyAclRestricted', 'windowsInboxTools', 'noModelChatSetupRequired', - 'soloTier', 'dockerIndependentRuntimePrerequisites', - 'managedRuntimeBootstrap', 'managedModelPull', 'managedModelChat', - 'managedModelProxyRestartChat', 'managedRuntimeCleanup', - 'sameVersionRepair', 'repairSoloTier', 'repairManagedModelDigestPreserved', - 'relaunchAfterRepair', 'silentUninstall', 'defaultProfileDataDir', - 'realWorkspaceAndMemorySeeded', 'repairRealWorkspaceAndMemoryPreserved', - 'uninstallRealWorkspaceAndMemoryPreserved', 'configuredDataDirPreserved', - 'profileDataPathPreserved', 'certificateProfileCleanup', - 'externalProfileRootsUnchanged', 'environmentRestored' -) -foreach ($checkName in $cleanRequiredChecks) { - Assert-PassingWindowsCertificateCheck ` - $cleanReceiptData $checkName 'Clean-install receipt' -} - -$receiptDataSet = @($cleanReceiptData) -if ($Mode -ceq 'bootstrap') { - $releaseAssets = @($installer, $cleanReceipt) -} else { - $upgradeReceipt = Get-Item -LiteralPath $upgradeReceiptPath - $receiptData = Get-Content -Raw -LiteralPath $upgradeReceipt.FullName | - ConvertFrom-Json - Assert-PassingWindowsCertificateReceipt ` - $receiptData 'version-to-version-upgrade' 'Windows lifecycle receipt' - - if (-not [string]::Equals( - [string]$receiptData.evidence.sourceRevision, - $sourceRevision, - [System.StringComparison]::Ordinal - ) -or - -not [string]::Equals( - [string]$receiptData.installer.name, - $installer.Name, - [System.StringComparison]::Ordinal - ) -or - [int64]$receiptData.installer.sizeBytes -ne $installer.Length -or - -not [string]::Equals( - $installerSha256, - [string]$receiptData.installer.sha256, - [System.StringComparison]::OrdinalIgnoreCase - )) { - throw 'Upgrade receipt does not match the release artifact and commit' - } - - $baseInstaller = Get-Item -LiteralPath ( - [string]$env:WAGGLE_UPGRADE_BASE_INSTALLER_PATH - ) - $baseSha256 = ( - Get-FileHash -LiteralPath $baseInstaller.FullName -Algorithm SHA256 - ).Hash - if (-not [string]::Equals( - [string]$env:WAGGLE_UPGRADE_BASE_COMMIT, - [string]$env:WINDOWS_UPGRADE_BASE_COMMIT, - [System.StringComparison]::OrdinalIgnoreCase - )) { - throw 'Certified Windows upgrade baseline commit no longer matches the protected commit' - } - Assert-RemoteTagCommit ` - ([string]$env:WINDOWS_UPGRADE_BASE_TAG) ` - ([string]$env:WAGGLE_UPGRADE_BASE_COMMIT) - if ([string]$env:WINDOWS_UPGRADE_BASE_TAG -notmatch '^v(?\d+\.\d+\.\d+)$' -or - $Matches['version'] -cne [string]$receiptData.upgrade.previousVersion -or - $Matches['version'] -cne [string]$env:WAGGLE_UPGRADE_BASE_VERSION -or - [string]$receiptData.upgrade.previousSourceRevision -cne - [string]$env:WAGGLE_UPGRADE_BASE_COMMIT -or - [string]$receiptData.upgrade.candidateVersion -cne $candidateVersion -or - [string]$receiptData.upgrade.observedPreviousVersion -cne - [string]$receiptData.upgrade.previousVersion -or - [string]$receiptData.upgrade.observedCandidateVersion -cne - [string]$receiptData.upgrade.candidateVersion) { - throw 'Lifecycle receipt does not bind the observed upgrade versions to the protected release versions' - } - if ($baseInstaller.Name -cne [string]$env:WINDOWS_UPGRADE_BASE_ASSET_NAME -or - [string]$receiptData.previousInstaller.name -cne $baseInstaller.Name -or - [int64]$receiptData.previousInstaller.sizeBytes -ne $baseInstaller.Length -or - -not [string]::Equals( - $baseSha256, - [string]$env:WINDOWS_UPGRADE_BASE_SHA256, - [System.StringComparison]::OrdinalIgnoreCase - ) -or - -not [string]::Equals( - $baseSha256, - [string]$receiptData.previousInstaller.sha256, - [System.StringComparison]::OrdinalIgnoreCase - )) { - throw 'Lifecycle receipt previous installer does not match the protected upgrade baseline' - } - if ($receiptData.installer.authenticodeStatus -ne 'Valid' -or - $receiptData.installedApp.authenticodeStatus -ne 'Valid' -or - $receiptData.previousInstaller.authenticodeStatus -ne 'Valid' -or - $receiptData.previousInstalledApp.authenticodeStatus -ne 'Valid' -or - $receiptData.installer.signatureType -ne 'Authenticode' -or - $receiptData.installedApp.signatureType -ne 'Authenticode' -or - $receiptData.previousInstaller.signatureType -ne 'Authenticode' -or - $receiptData.previousInstalledApp.signatureType -ne 'Authenticode') { - throw 'Lifecycle receipt does not contain valid previous and candidate signatures' - } - $baseInstallerSignerIdentity = Assert-ExpectedAuthenticodeSignature $baseInstaller $approvedSignerIdentity - Assert-LifecycleReceiptSignerIdentities ` - $receiptData $baseInstallerSignerIdentity $installerSignerIdentity - foreach ($timestampThumbprint in @( - $receiptData.previousInstaller.timestampAuthorityThumbprint, - $receiptData.previousInstalledApp.timestampAuthorityThumbprint, - $receiptData.installer.timestampAuthorityThumbprint, - $receiptData.installedApp.timestampAuthorityThumbprint - )) { - if ([string]::IsNullOrWhiteSpace([string]$timestampThumbprint)) { - throw 'Lifecycle receipt is missing a validated Authenticode timestamp' - } - } - Assert-ManagedModelAndMemoryEvidence $receiptData 'Upgrade receipt' - if ([string]::IsNullOrWhiteSpace( - [string]$receiptData.upgrade.managedModelName - ) -or - [string]$receiptData.upgrade.managedModelDigest -notmatch - '^sha256:[0-9a-f]{64}$' -or - -not [string]::Equals( - [string]$receiptData.upgrade.managedModelName, - [string]$receiptData.managedModel.name, - [System.StringComparison]::Ordinal - ) -or - -not [string]::Equals( - [string]$receiptData.upgrade.managedModelDigest, - [string]$receiptData.managedModelDigest, - [System.StringComparison]::Ordinal - )) { - throw 'Upgrade receipt does not preserve the previous managed-model identity and digest' - } - - $upgradeRequiredChecks = @( - 'sourceRevision', 'sourceFilesClean', 'sidecarSourceProvenance', - 'generatedInstallerInclude', - 'profileDataDeletionAbsent', 'baseAppDataDeletionNeutralized', - 'authenticodeSignature', 'authenticodeSigner', 'authenticodeTimestamp', - 'installedAppAuthenticodeSignature', 'installedAppAuthenticodeSigner', - 'installedAppAuthenticodeTimestamp', 'previousInstallerHash', - 'previousInstallerAuthenticodeSignature', - 'previousInstallerAuthenticodeSigner', - 'previousInstallerAuthenticodeTimestamp', - 'previousInstalledAppAuthenticodeSignature', - 'previousInstalledAppAuthenticodeSigner', - 'previousInstalledAppAuthenticodeTimestamp', 'candidateInstallerHash', - 'versionOrder', 'previousVersion', 'candidateVersion', 'previousInstall', - 'previousLaunch', 'sameApprovedSigner', 'versionToVersionUpgrade', - 'upgradeSameInstallDirectory', 'upgradeConfiguredDataPreserved', - 'upgradeProfileDataPreserved', 'upgradeVaultKeyPreserved', - 'upgradeRegistrations', 'candidateLaunch', 'relaunchAfterUpgrade', - 'silentInstall', 'vaultKeyAclRestricted', 'windowsInboxTools', 'soloTier', - 'previousSoloTier', 'dockerIndependentRuntimePrerequisites', - 'managedRuntimeBootstrap', 'managedModelPull', 'managedModelChat', - 'managedModelProxyRestartChat', 'managedRuntimeCleanup', - 'previousManagedModelSeeded', 'upgradeManagedModelPreserved', - 'sameVersionRepair', 'repairSoloTier', 'repairManagedModelDigestPreserved', - 'relaunchAfterRepair', 'silentUninstall', 'defaultProfileDataDir', - 'realWorkspaceAndMemorySeeded', 'upgradeRealWorkspaceAndMemoryPreserved', - 'repairRealWorkspaceAndMemoryPreserved', - 'uninstallRealWorkspaceAndMemoryPreserved', - 'configuredDataDirPreserved', 'profileDataPathPreserved', - 'certificateProfileCleanup', 'externalProfileRootsUnchanged', 'environmentRestored' - ) - foreach ($checkName in $upgradeRequiredChecks) { - Assert-PassingWindowsCertificateCheck ` - $receiptData $checkName 'Upgrade receipt' - } - $receiptDataSet = @($cleanReceiptData, $receiptData) - $releaseAssets = @($installer, $cleanReceipt, $upgradeReceipt) -} - -$nonPassingChecks = @( - foreach ($certificateData in $receiptDataSet) { - $certificateData.checks.PSObject.Properties | - Where-Object { -not [bool]::True.Equals($_.Value) } - } -) -if ($nonPassingChecks.Count -gt 0) { - throw "Lifecycle receipts contain non-passing checks: $($nonPassingChecks.Name -join ', ')" -} - -$releaseAssetManifest = @(New-ReleaseAssetManifest $releaseAssets) -Assert-LocalReleaseAssetsUnchanged $releaseAssetManifest -Assert-ReceiptSourceHashes $receiptDataSet $installer $sourceRevision -Assert-PublicationTagBindings $Mode $tag $sourceRevision -Assert-ReleaseDoesNotExist $tag - -gh release create $tag --verify-tag --draft --title "Waggle $tag" ` - --notes 'See the release notes for details.' -if ($LASTEXITCODE -ne 0) { - throw "Could not create a dedicated $Mode draft release: $tag" -} -$releaseData = gh release view $tag ` - --json id,isDraft,isPrerelease,tagName,name,assets | - ConvertFrom-Json -if ($LASTEXITCODE -ne 0) { - throw "Could not inspect newly-created $Mode draft release $tag" -} -Set-ReadOnlyCreatedReleaseId ([string]$releaseData.id) -Assert-ReleaseIdentity ` - $releaseData $createdReleaseId $tag $true 'Newly-created draft release' -if (@($releaseData.assets).Count -ne 0) { - throw "Could not verify newly-created $Mode draft release $tag" -} - -Assert-PublicationTagBindings $Mode $tag $sourceRevision -$releaseAssetPaths = [string[]]@( - $releaseAssetManifest | ForEach-Object { $_.FullName } -) -gh release upload $tag @releaseAssetPaths -if ($LASTEXITCODE -ne 0) { - throw "Could not upload certified Windows $Mode assets to $tag" -} -$uploadedRelease = gh release view $tag ` - --json id,isDraft,isPrerelease,tagName,name,assets | - ConvertFrom-Json -if ($LASTEXITCODE -ne 0) { - throw "Could not verify uploaded $Mode draft $tag" -} -Assert-ReleaseIdentity ` - $uploadedRelease $createdReleaseId $tag $true 'Uploaded draft release' -Assert-ExactReleaseAssets $uploadedRelease $releaseAssets -Assert-RemoteReleaseAssetContents $tag $uploadedRelease $releaseAssetManifest 'uploaded' - -Assert-PublicationTagBindings $Mode $tag $sourceRevision -gh release edit $tag --draft=false --prerelease=false -if ($LASTEXITCODE -ne 0) { - throw "Could not publish certified Windows $Mode release $tag" -} -$publishedRelease = gh release view $tag ` - --json id,isDraft,isPrerelease,tagName,name,assets | - ConvertFrom-Json -if ($LASTEXITCODE -ne 0) { - throw "Published Windows $Mode release $tag is not final" -} -Assert-ReleaseIdentity ` - $publishedRelease $createdReleaseId $tag $false 'Published release' -Assert-ExactReleaseAssets $publishedRelease $releaseAssets -Assert-RemoteReleaseAssetContents $tag $publishedRelease $releaseAssetManifest 'published' diff --git a/scripts/read-tauri-bootstrap-token.mjs b/scripts/read-tauri-bootstrap-token.mjs deleted file mode 100644 index ce15974..0000000 --- a/scripts/read-tauri-bootstrap-token.mjs +++ /dev/null @@ -1,262 +0,0 @@ -#!/usr/bin/env node - -import process from 'node:process'; -import WebSocket from 'ws'; - -const DEFAULT_TIMEOUT_MS = 60_000; -const MIN_TOKEN_LENGTH = 32; -const MAX_TOKEN_LENGTH = 200; - -function fail(message) { - console.error(`tauri-bootstrap-token: ${message}`); - process.exitCode = 1; -} - -function parseArgs(argv) { - const options = { - port: null, - timeoutMs: DEFAULT_TIMEOUT_MS, - selfTest: false, - allowLegacyUi: false, - }; - for (let index = 0; index < argv.length; index += 1) { - const argument = argv[index]; - if (argument === '--self-test') { - options.selfTest = true; - continue; - } - if (argument === '--allow-legacy-ui') { - options.allowLegacyUi = true; - continue; - } - if (argument === '--port' || argument === '--timeout-ms') { - const value = argv[index + 1]; - index += 1; - if (value === undefined) throw new Error(`${argument} requires a value`); - if (argument === '--port') options.port = Number(value); - else options.timeoutMs = Number(value); - continue; - } - if (argument.startsWith('--port=')) options.port = Number(argument.slice(7)); - else if (argument.startsWith('--timeout-ms=')) options.timeoutMs = Number(argument.slice(13)); - else throw new Error(`unknown argument: ${argument}`); - } - if (!Number.isInteger(options.port) || options.port < 1024 || options.port > 65535) { - throw new Error('port must be an integer between 1024 and 65535'); - } - if (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1000 || options.timeoutMs > 300_000) { - throw new Error('timeout-ms must be an integer between 1000 and 300000'); - } - return options; -} - -function isValidEndpoint(value) { - return value !== null - && typeof value === 'object' - && Number.isInteger(value.port) - && value.port > 0 - && value.port <= 65535 - && typeof value.instanceId === 'string' - && value.instanceId.trim().length > 0 - && typeof value.bootstrapToken === 'string' - && value.bootstrapToken.length >= MIN_TOKEN_LENGTH - && value.bootstrapToken.length <= MAX_TOKEN_LENGTH; -} - -function isValidDesktopRuntime(value, allowLegacyUi = false) { - return isValidEndpoint(value) - && value.uiReady === true - && value.uiStartupState === (allowLegacyUi ? 'legacy-ready' : 'ready') - && typeof value.uiPath === 'string' - && value.uiPath.startsWith('/') - && Number.isInteger(value.uiTextLength) - && value.uiTextLength > 0; -} - -async function fetchTargets(port) { - const response = await fetch(`http://127.0.0.1:${port}/json/list`); - if (!response.ok) throw new Error(`WebView debug endpoint returned HTTP ${response.status}`); - const targets = await response.json(); - if (!Array.isArray(targets)) throw new Error('WebView debug endpoint returned an invalid target list'); - return targets.filter((target) => target?.type === 'page' && typeof target.webSocketDebuggerUrl === 'string'); -} - -async function evaluateEnsureService(webSocketUrl, timeoutMs, allowLegacyUi) { - const socket = new WebSocket(webSocketUrl); - let nextId = 1; - const pending = new Map(); - const timer = setTimeout(() => { - for (const pendingRequest of pending.values()) pendingRequest.reject(new Error('CDP request timed out')); - pending.clear(); - socket.close(); - }, timeoutMs); - - try { - await new Promise((resolve, reject) => { - const openTimer = setTimeout(() => reject(new Error('CDP WebSocket open timed out')), timeoutMs); - socket.addEventListener('open', () => { - clearTimeout(openTimer); - resolve(); - }, { once: true }); - socket.addEventListener('error', () => { - clearTimeout(openTimer); - reject(new Error('CDP WebSocket connection failed')); - }, { once: true }); - }); - - socket.addEventListener('message', (event) => { - let message; - try { - message = JSON.parse(String(event.data)); - } catch { - return; - } - const request = pending.get(message.id); - if (!request) return; - pending.delete(message.id); - if (message.error) request.reject(new Error('Tauri IPC evaluation failed')); - else request.resolve(message.result); - }); - - const result = await new Promise((resolve, reject) => { - const id = nextId; - nextId += 1; - pending.set(id, { resolve, reject }); - socket.send(JSON.stringify({ - id, - method: 'Runtime.evaluate', - params: { - awaitPromise: true, - returnByValue: true, - expression: ` - (async () => { - const invoke = globalThis.__TAURI_INTERNALS__?.invoke; - if (typeof invoke !== 'function') throw new Error('Tauri IPC is unavailable'); - const endpoint = await invoke('ensure_service'); - const deadline = Date.now() + 10_000; - for (;;) { - const root = document.getElementById('root'); - const startup = root?.querySelector('[data-waggle-startup]'); - const startupState = startup?.getAttribute('data-waggle-startup') ?? null; - const readyState = root?.getAttribute('data-waggle-ui-ready') ?? null; - const uiTextLength = root?.innerText?.trim().length ?? 0; - const strictUiReady = Boolean( - root - && root.childElementCount > 0 - && !startup - && readyState === 'ready' - && uiTextLength > 0 - ); - const legacyUiReady = Boolean( - root - && root.childElementCount > 0 - && !startup - && uiTextLength > 0 - ); - const uiReady = ${allowLegacyUi ? 'legacyUiReady' : 'strictUiReady'}; - if (uiReady || startupState === 'failed' || Date.now() >= deadline) { - return { - ...endpoint, - uiPath: globalThis.location?.pathname ?? '', - uiReady, - uiStartupState: ${allowLegacyUi ? "uiReady ? 'legacy-ready' : (readyState ?? startupState)" : 'readyState ?? startupState'}, - uiTextLength, - }; - } - await new Promise((resolve) => setTimeout(resolve, 100)); - } - })() - `, - }, - })); - }); - const remote = result?.result?.value; - if (!isValidEndpoint(remote)) throw new Error('Tauri returned an invalid service endpoint'); - if (!isValidDesktopRuntime(remote, allowLegacyUi)) { - throw new Error('Waggle UI did not render its application shell'); - } - return { - bootstrapToken: remote.bootstrapToken, - uiPath: remote.uiPath, - uiReady: remote.uiReady, - uiStartupState: remote.uiStartupState, - uiTextLength: remote.uiTextLength, - }; - } finally { - clearTimeout(timer); - socket.close(); - } -} - -async function resolveToken(port, timeoutMs, allowLegacyUi) { - const deadline = Date.now() + timeoutMs; - let lastError = 'WebView target not ready'; - while (Date.now() < deadline) { - try { - const targets = await fetchTargets(port); - for (const target of targets) { - try { - return await evaluateEnsureService( - target.webSocketDebuggerUrl, - Math.min(15_000, deadline - Date.now()), - allowLegacyUi, - ); - } catch (error) { - lastError = error instanceof Error ? error.message : 'CDP evaluation failed'; - } - } - } catch (error) { - lastError = error instanceof Error ? error.message : 'WebView debug endpoint unavailable'; - } - await new Promise((resolve) => setTimeout(resolve, 250)); - } - throw new Error(lastError); -} - -async function main() { - if (process.argv.includes('--self-test')) { - if (typeof WebSocket !== 'function') throw new Error('WebSocket client is unavailable'); - const valid = 'a'.repeat(MIN_TOKEN_LENGTH); - if (!isValidEndpoint({ port: 3333, instanceId: 'test-instance', bootstrapToken: valid })) { - throw new Error('valid endpoint fixture rejected'); - } - if (isValidEndpoint({ port: 3333, instanceId: 'test-instance', bootstrapToken: 'short' })) { - throw new Error('short token fixture accepted'); - } - const validRuntime = { - port: 3333, - instanceId: 'test-instance', - bootstrapToken: valid, - uiPath: '/home', - uiReady: true, - uiStartupState: 'ready', - uiTextLength: 10, - }; - if (!isValidDesktopRuntime(validRuntime)) throw new Error('valid desktop runtime rejected'); - if (isValidDesktopRuntime({ ...validRuntime, uiReady: false })) { - throw new Error('blank desktop runtime accepted'); - } - if (isValidDesktopRuntime({ ...validRuntime, uiTextLength: 0 })) { - throw new Error('empty desktop runtime accepted'); - } - if (isValidDesktopRuntime({ ...validRuntime, uiStartupState: 'loading' })) { - throw new Error('loading desktop runtime accepted'); - } - if (isValidDesktopRuntime({ ...validRuntime, uiStartupState: 'failed' })) { - throw new Error('failed desktop runtime accepted'); - } - if (!isValidDesktopRuntime({ ...validRuntime, uiStartupState: 'legacy-ready' }, true)) { - throw new Error('valid legacy desktop runtime rejected'); - } - if (isValidDesktopRuntime({ ...validRuntime, uiReady: false, uiStartupState: 'legacy-ready' }, true)) { - throw new Error('blank legacy desktop runtime accepted'); - } - console.log(JSON.stringify({ pass: true, cases: 9 })); - return; - } - const options = parseArgs(process.argv.slice(2)); - const runtime = await resolveToken(options.port, options.timeoutMs, options.allowLegacyUi); - console.log(JSON.stringify(runtime)); -} - -main().catch((error) => fail(error instanceof Error ? error.message : 'unknown failure')); diff --git a/scripts/release-smoke.mjs b/scripts/release-smoke.mjs new file mode 100644 index 0000000..b2c5fdd --- /dev/null +++ b/scripts/release-smoke.mjs @@ -0,0 +1,336 @@ +#!/usr/bin/env node +/** + * Smoke tests the release workflow runs on every target after building. + * + * node scripts/release-smoke.mjs installer [--archive FILE] [--timeout SECONDS] + * + * Installs the server archive with the built installer + * (packages/launcher/dist/cli.js) into a temporary directory, runs + * `doctor`, starts `run` on a free port with a temporary data directory, + * waits for /health, stops the server and uninstalls. The default archive + * is the one in artifacts/ for this system. + * + * node scripts/release-smoke.mjs desktop --app PATH [--port 3333] [--timeout SECONDS] + * + * Starts the built desktop app (its executable, or a macOS .app bundle) + * with a temporary data directory, waits until its sidecar answers + * /health on 127.0.0.1:, then stops the app and its sidecar and + * checks that the port is released. On Linux run it under xvfb-run. + */ +import { spawn, spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import net from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const isWindows = process.platform === 'win32'; + +// Keep in step with releaseTarget() in packages/launcher/src/platform.ts. +const TARGETS = { + 'win32-x64': 'windows-x64', + 'darwin-arm64': 'macos-arm64', + 'darwin-x64': 'macos-x64', + 'linux-x64': 'linux-x64', +}; + +class SmokeError extends Error {} + +function log(message) { + console.log(`[release-smoke] ${message}`); +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function parseArgs(argv) { + const [command, ...rest] = argv; + if (command !== 'installer' && command !== 'desktop') { + throw new SmokeError('Usage: release-smoke.mjs installer|desktop [options]'); + } + const options = { port: 3333, timeout: 300 }; + for (let i = 0; i < rest.length; i += 2) { + const [flag, value] = [rest[i], rest[i + 1]]; + if (value === undefined) throw new SmokeError(`Missing value for ${flag}`); + if (flag === '--archive') options.archive = path.resolve(value); + else if (flag === '--app') options.app = path.resolve(value); + else if (flag === '--port' || flag === '--timeout') { + const number = Number(value); + if (!Number.isInteger(number) || number < 1) throw new SmokeError(`Invalid ${flag}: ${value}`); + options[flag.slice(2)] = number; + } else { + throw new SmokeError(`Unknown option: ${flag}`); + } + } + return { command, options }; +} + +function tempRoot(name) { + return fs.mkdtempSync(path.join(process.env.RUNNER_TEMP || os.tmpdir(), `waggle-smoke-${name}-`)); +} + +function removeTree(dir) { + fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 1000 }); +} + +function portIsFree(port) { + return new Promise((resolve) => { + const server = net.createServer(); + server.once('error', () => resolve(false)); + server.listen(port, '127.0.0.1', () => server.close(() => resolve(true))); + }); +} + +function freePort() { + return new Promise((resolve, reject) => { + const server = net.createServer(); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const { port } = server.address(); + server.close(() => resolve(port)); + }); + }); +} + +/** The /health body of a Waggle server on this port, or null. */ +async function health(port) { + try { + const response = await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(2000) }); + if (!response.ok) return null; + const body = await response.json(); + return body && body.mode === 'local' ? body : null; + } catch { + return null; + } +} + +/** + * Starts a long-running process. On macOS and Linux it leads its own process + * group, so stopping the group also stops the sidecar it starts. + */ +function startBackground(label, command, args, env) { + const child = spawn(command, args, { + env, + stdio: ['ignore', 'inherit', 'inherit'], + detached: !isWindows, + windowsHide: true, + }); + const state = { label, child, error: null, exited: false }; + child.once('error', (error) => { + state.error = error; + }); + child.once('exit', () => { + state.exited = true; + }); + return state; +} + +function waitForExit(state, ms) { + if (state.exited || state.error) return Promise.resolve(true); + return new Promise((resolve) => { + const timer = setTimeout(() => resolve(false), ms); + state.child.once('exit', () => { + clearTimeout(timer); + resolve(true); + }); + }); +} + +async function waitForHealth(state, port, timeoutSeconds) { + const deadline = Date.now() + timeoutSeconds * 1000; + while (Date.now() < deadline) { + if (state.error) throw new SmokeError(`${state.label} did not start: ${state.error.message}`); + if (state.exited) { + const { exitCode, signalCode } = state.child; + throw new SmokeError(`${state.label} exited (code ${exitCode}, signal ${signalCode}) before /health answered`); + } + const body = await health(port); + if (body) return body; + await sleep(1000); + } + throw new SmokeError(`${state.label} did not answer /health on 127.0.0.1:${port} within ${timeoutSeconds} s`); +} + +function signalGroup(pid, signal) { + try { + process.kill(-pid, signal); + } catch (error) { + if (error.code !== 'ESRCH') throw error; + } +} + +async function waitForPortFree(port, ms) { + const deadline = Date.now() + ms; + while (Date.now() < deadline) { + if (await portIsFree(port)) return true; + await sleep(500); + } + return false; +} + +/** Stops the process and everything it started, then checks the port is released. */ +async function stopTree(state, port) { + if (state.child.pid === undefined) return; + if (isWindows) { + spawnSync('taskkill', ['/PID', String(state.child.pid), '/T', '/F'], { stdio: 'inherit', windowsHide: true }); + await waitForExit(state, 10_000); + } else { + signalGroup(state.child.pid, 'SIGTERM'); + if (!(await waitForExit(state, 15_000))) signalGroup(state.child.pid, 'SIGKILL'); + await waitForExit(state, 5_000); + } + if (await waitForPortFree(port, 20_000)) return; + if (!isWindows) { + signalGroup(state.child.pid, 'SIGKILL'); + if (await waitForPortFree(port, 10_000)) return; + } + throw new SmokeError(`Port ${port} is still in use after stopping ${state.label}: its server outlived it`); +} + +/** + * Waits for /health from a started process, then stops it. A failure to stop + * is reported after, not instead of, a failed health check. + */ +async function checkHealthThenStop(state, port, timeoutSeconds, onFailure = () => {}) { + let failure = null; + try { + await waitForHealth(state, port, timeoutSeconds); + log(`${state.label} answers /health on 127.0.0.1:${port}`); + } catch (error) { + failure = error; + onFailure(); + } + try { + await stopTree(state, port); + } catch (error) { + if (failure) console.error(`[release-smoke] ${error.message}`); + else failure = error; + } + if (failure) throw failure; +} + +// ── installer ──────────────────────────────────────────────────────────────── + +function defaultArchive() { + const target = TARGETS[`${process.platform}-${process.arch}`]; + if (!target) throw new SmokeError(`No release target for ${process.platform}-${process.arch}`); + const dir = path.join(root, 'artifacts'); + const pattern = new RegExp(`^waggle-server-.+-${target}\\.tar\\.gz$`); + const matches = fs.existsSync(dir) ? fs.readdirSync(dir).filter((name) => pattern.test(name)) : []; + if (matches.length !== 1) { + throw new SmokeError(`Expected one ${target} server archive in artifacts/, found ${matches.length}. Pass --archive.`); + } + return path.join(dir, matches[0]); +} + +function runLauncher(launcher, args) { + log(`waggle-server ${args.join(' ')}`); + const result = spawnSync(process.execPath, [launcher, ...args], { encoding: 'utf8', windowsHide: true }); + process.stdout.write(result.stdout ?? ''); + process.stderr.write(result.stderr ?? ''); + if (result.error) throw result.error; + return result; +} + +/** doctor must pass; the only warning allowed is that the command's directory is not on PATH. */ +function checkDoctor(result) { + if (result.status !== 0) throw new SmokeError(`doctor failed with exit code ${result.status}`); + const warnings = result.stdout.split(/\r?\n/).filter((line) => /^\s*warn\s/.test(line)); + const unexpected = warnings.filter((line) => !/^\s*warn\s+Command: .+ is not on your PATH$/.test(line)); + if (unexpected.length > 0) throw new SmokeError(`doctor warned:\n${unexpected.join('\n')}`); + if (!/^\s*ok\s+Native modules: SQLite loads$/m.test(result.stdout)) { + throw new SmokeError('doctor did not report that SQLite loads with the bundled runtime'); + } +} + +async function installerSmoke(options) { + const launcher = path.join(root, 'packages', 'launcher', 'dist', 'cli.js'); + if (!fs.existsSync(launcher)) { + throw new SmokeError('packages/launcher/dist/cli.js is missing. Run: npm run build --workspace @waggle-ai/waggle'); + } + const archive = options.archive ?? defaultArchive(); + log(`Archive: ${archive}`); + const temp = tempRoot('installer'); + const installDir = path.join(temp, 'install'); + const dataDir = path.join(temp, 'data'); + const location = ['--dir', installDir, '--bin-dir', path.join(temp, 'bin')]; + try { + const install = runLauncher(launcher, ['install', '--from', archive, ...location]); + if (install.status !== 0) throw new SmokeError(`install failed with exit code ${install.status}`); + + const port = await freePort(); + checkDoctor(runLauncher(launcher, ['doctor', ...location, '--data-dir', dataDir, '--port', String(port)])); + + log(`waggle-server run --no-open --port ${port}`); + const server = startBackground( + 'The installed server', + process.execPath, + [launcher, 'run', '--no-open', '--port', String(port), '--dir', installDir, '--data-dir', dataDir], + process.env, + ); + await checkHealthThenStop(server, port, options.timeout); + + // Windows can hold the stopped runtime's files for a moment. + let uninstall; + for (let attempt = 1; attempt <= 5; attempt++) { + uninstall = runLauncher(launcher, ['uninstall', ...location, '--data-dir', dataDir]); + if (uninstall.status === 0) break; + await sleep(2000); + } + if (uninstall.status !== 0) throw new SmokeError(`uninstall failed with exit code ${uninstall.status}`); + if (fs.existsSync(installDir)) throw new SmokeError(`uninstall left ${installDir}`); + if (!fs.existsSync(dataDir)) throw new SmokeError('uninstall removed the data directory'); + log('Installer smoke test passed'); + } finally { + removeTree(temp); + } +} + +// ── desktop ────────────────────────────────────────────────────────────────── + +/** The executable of a macOS .app bundle, or the given executable. */ +function appExecutable(app) { + if (!fs.existsSync(app)) throw new SmokeError(`${app} does not exist`); + if (!app.endsWith('.app') || !fs.statSync(app).isDirectory()) return app; + const plist = fs.readFileSync(path.join(app, 'Contents', 'Info.plist'), 'utf8'); + const name = /CFBundleExecutable<\/key>\s*([^<]+)<\/string>/.exec(plist)?.[1]; + if (!name) throw new SmokeError(`${app}/Contents/Info.plist names no CFBundleExecutable`); + return path.join(app, 'Contents', 'MacOS', name); +} + +function printServiceLog(dataDir) { + const file = path.join(dataDir, 'logs', 'service.log'); + if (!fs.existsSync(file)) return; + const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/); + log(`Last lines of ${file}:`); + console.log(lines.slice(-200).join('\n')); +} + +async function desktopSmoke(options) { + if (!options.app) throw new SmokeError('desktop needs --app '); + const executable = appExecutable(options.app); + if (!(await portIsFree(options.port))) { + throw new SmokeError(`Port ${options.port} is in use; the desktop smoke test needs it free`); + } + const temp = tempRoot('desktop'); + const dataDir = path.join(temp, 'data'); + fs.mkdirSync(dataDir, { recursive: true }); + try { + log(`Starting ${executable}`); + const app = startBackground('The desktop app', executable, [], { ...process.env, WAGGLE_DATA_DIR: dataDir }); + await checkHealthThenStop(app, options.port, options.timeout, () => printServiceLog(dataDir)); + log('Desktop smoke test passed'); + } finally { + removeTree(temp); + } +} + +try { + const { command, options } = parseArgs(process.argv.slice(2)); + await (command === 'installer' ? installerSmoke(options) : desktopSmoke(options)); +} catch (error) { + console.error(`[release-smoke] FAILED: ${error instanceof Error ? error.message : String(error)}`); + process.exit(1); +} diff --git a/scripts/release-smoke.test.ts b/scripts/release-smoke.test.ts new file mode 100644 index 0000000..2d31387 --- /dev/null +++ b/scripts/release-smoke.test.ts @@ -0,0 +1,146 @@ +/** + * scripts/release-smoke.mjs against stand-in payloads. The installer smoke + * test installs, checks, runs and removes a packed archive whose service is a + * small HTTP server; the desktop smoke test starts a stand-in .app that starts + * a stand-in sidecar, and must stop both. + */ +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import net from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; + +const ROOT = path.resolve(import.meta.dirname, '..'); +const SMOKE = path.join(ROOT, 'scripts', 'release-smoke.mjs'); +const LAUNCHER = path.join(ROOT, 'packages', 'launcher', 'dist', 'cli.js'); +const TARGETS: Record = { + 'win32-x64': 'windows-x64', + 'darwin-arm64': 'macos-arm64', + 'darwin-x64': 'macos-x64', + 'linux-x64': 'linux-x64', +}; +const target = TARGETS[`${process.platform}-${process.arch}`]; + +// Answers /health the way the sidecar does. +const healthServer = (port: string) => ` +const http = require('node:http'); +const port = Number(${port}); +http.createServer((request, response) => { + response.setHeader('content-type', 'application/json'); + response.end(JSON.stringify(request.url === '/health' ? { status: 'ok', mode: 'local', port } : {})); +}).listen(port, '127.0.0.1'); +`; + +const temps: string[] = []; +function tempDir(prefix: string): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); + temps.push(dir); + return dir; +} +afterEach(() => { + for (const dir of temps.splice(0)) fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 500 }); +}); + +function write(file: string, content: string, mode?: number): void { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content, { mode }); +} + +function freePort(): Promise { + return new Promise((resolve, reject) => { + const server = net.createServer(); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address() as net.AddressInfo; + server.close(() => resolve(address.port)); + }); + }); +} + +function runSmoke(args: string[]) { + return spawnSync(process.execPath, [SMOKE, ...args], { encoding: 'utf8', timeout: 120_000, windowsHide: true }); +} + +describe('release smoke tests', () => { + it.skipIf(!target || !fs.existsSync(LAUNCHER))( + 'installs, checks, runs and uninstalls a server archive', + () => { + const work = tempDir('waggle-smoke-archive-'); + const resources = path.join(work, 'resources'); + const runtime = path.join(resources, process.platform === 'win32' ? 'node.exe' : 'node'); + fs.mkdirSync(resources, { recursive: true }); + // The payload runs on its own Node; this test's Node stands in for it. + if (process.platform === 'win32') fs.copyFileSync(process.execPath, runtime); + else fs.symlinkSync(process.execPath, runtime); + write(path.join(resources, 'service.js'), healthServer('process.env.WAGGLE_PORT')); + write( + path.join(resources, 'node_modules', 'better-sqlite3', 'index.js'), + 'module.exports = class { prepare() { return { get: () => ({ 1: 1 }) }; } };\n', + ); + write(path.join(work, 'web', 'index.html'), ''); + const out = path.join(work, 'out'); + const pack = spawnSync( + process.execPath, + [ + path.join(ROOT, 'scripts', 'build-server-archive.mjs'), + '--resources', resources, '--web', path.join(work, 'web'), '--out', out, + ], + { encoding: 'utf8' }, + ); + expect(pack.status, pack.stderr).toBe(0); + const archive = path.join(out, fs.readdirSync(out).find((name) => name.endsWith('.tar.gz'))!); + + const result = runSmoke(['installer', '--archive', archive, '--timeout', '60']); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); + expect(result.stdout).toContain('The installed server answers /health'); + expect(result.stdout).toContain('Installer smoke test passed'); + }, + 150_000, + ); + + it.skipIf(process.platform === 'win32')( + 'starts a desktop app bundle and stops it together with its sidecar', + async () => { + const port = await freePort(); + const work = tempDir('waggle-smoke-desktop-'); + const contents = path.join(work, 'Stand-in.app', 'Contents'); + write( + path.join(contents, 'Info.plist'), + 'CFBundleExecutable\n stand-in\n', + ); + write(path.join(work, 'sidecar.js'), healthServer(String(port))); + // The app stays alive and owns a child process that serves /health. + write( + path.join(work, 'app.js'), + `require('node:child_process').spawn(process.execPath, [${JSON.stringify(path.join(work, 'sidecar.js'))}], { stdio: 'inherit' });\n` + + 'setInterval(() => {}, 1000);\n', + ); + write( + path.join(contents, 'MacOS', 'stand-in'), + `#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(path.join(work, 'app.js'))}\n`, + 0o755, + ); + + const result = runSmoke(['desktop', '--app', path.join(work, 'Stand-in.app'), '--port', String(port), '--timeout', '30']); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); + expect(result.stdout).toContain(`answers /health on 127.0.0.1:${port}`); + expect(result.stdout).toContain('Desktop smoke test passed'); + + const probe = net.connect(port, '127.0.0.1'); + const connected = await new Promise((resolve) => { + probe.once('connect', () => resolve(true)); + probe.once('error', () => resolve(false)); + }); + probe.destroy(); + expect(connected).toBe(false); + }, + 90_000, + ); + + it('rejects a desktop run without an app and unknown options', () => { + expect(runSmoke(['desktop']).stderr).toContain('desktop needs --app'); + expect(runSmoke(['installer', '--fast', '1']).stderr).toContain('Unknown option: --fast'); + expect(runSmoke(['publish']).status).toBe(1); + }); +});