Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(release): verify desktop artifacts before publish (#848)
Gener274d15c0fe0d
diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex 272f94eb2..d5347dae9 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -6,25 +6,30 @@ on:paths:- "src/desktop/.deploy-version"+concurrency:+ group: desktop-release-${{ github.ref }}+ cancel-in-progress: false+jobs:- build:+ build-unix:permissions:- contents: write+ contents: readstrategy:fail-fast: falsematrix:include:- platform: macos-latesttarget: aarch64-apple-darwin+ stage-target: macos-aarch64- platform: macos-latesttarget: x86_64-apple-darwin+ stage-target: macos-x86_64- platform: ubuntu-22.04target: x86_64-unknown-linux-gnu- - platform: windows-latest- target: x86_64-pc-windows-msvc+ stage-target: linux-x86_64runs-on: ${{ matrix.platform }}- timeout-minutes: 30+ timeout-minutes: 45steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7@@ -50,7 +55,7 @@ jobs:key: ${{ matrix.target }}- name: Install dependencies (Linux)- if: matrix.platform == 'ubuntu-22.04'+ if: runner.os == 'Linux'run: |sudo apt-get updatesudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf@@ -64,135 +69,433 @@ jobs:shell: bashrun: echo "version=$(tr -d '\n' < src/desktop/.deploy-version)" >> "$GITHUB_OUTPUT"- - name: Resolve existing release- id: release- shell: bash- env:- GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}- TAG: v${{ steps.version.outputs.version }}- run: |- for attempt in {1..30}; do- if release_id=$(gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}" --jq '.id' 2>/dev/null); then- echo "id=${release_id}" >> "$GITHUB_OUTPUT"- exit 0- fi- echo "Waiting for ${TAG} release (${attempt}/30)..."- sleep 2- done- echo "::error::Release ${TAG} was not created within 60 seconds"- exit 1-- - name: Prepare App Store Connect API key+ - name: Prepare fail-closed macOS signingif: runner.os == 'macOS'shell: bashenv:+ APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}+ APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}+ APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}APPLE_API_PRIVATE_KEY: ${{ secrets.APPLE_API_PRIVATE_KEY }}+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}run: |- test -n "$APPLE_API_KEY"- test -n "$APPLE_API_PRIVATE_KEY"- key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY}.p8"+ set -euo pipefail+ for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD APPLE_SIGNING_IDENTITY APPLE_TEAM_ID APPLE_API_ISSUER APPLE_API_KEY APPLE_API_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD; do+ test -n "${!name}" || { echo "::error::Missing required macOS release input: $name"; exit 1; }+ done+ [[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]]+ [[ "$APPLE_SIGNING_IDENTITY" == Developer\ ID\ Application:*"($APPLE_TEAM_ID)" ]]+umask 077- printf '%s' "$APPLE_API_PRIVATE_KEY" > "$key_path"- echo "APPLE_API_KEY_PATH=$key_path" >> "$GITHUB_ENV"+ p12_path="$RUNNER_TEMP/alook-release-certificate.p12"+ api_key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY}.p8"+ keychain_path="$RUNNER_TEMP/alook-release.keychain-db"+ keychain_list="$RUNNER_TEMP/alook-keychain-list.txt"+ keychain_password=$(openssl rand -hex 32)+ echo "::add-mask::$keychain_password"+ {+ echo "APPLE_API_KEY_PATH=$api_key_path"+ echo "ALOOK_MACOS_P12_PATH=$p12_path"+ echo "ALOOK_MACOS_KEYCHAIN_PATH=$keychain_path"+ echo "ALOOK_MACOS_KEYCHAIN_LIST=$keychain_list"+ } >> "$GITHUB_ENV"++ printf '%s' "$APPLE_CERTIFICATE" | base64 -D > "$p12_path"+ printf '%s' "$APPLE_API_PRIVATE_KEY" > "$api_key_path"+ security list-keychains -d user | sed 's/^[[:space:]]*"//; s/"$//' > "$keychain_list"+ security create-keychain -p "$keychain_password" "$keychain_path"+ security set-keychain-settings -lut 21600 "$keychain_path"+ security unlock-keychain -p "$keychain_password" "$keychain_path"+ security import "$p12_path" -k "$keychain_path" -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign -T /usr/bin/security+ security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$keychain_password" "$keychain_path"+ existing_keychains=()+ while IFS= read -r keychain; do [[ -n "$keychain" ]] && existing_keychains+=("$keychain"); done < "$keychain_list"+ security list-keychains -d user -s "$keychain_path" "${existing_keychains[@]}"- - name: Build Tauri app+ - name: Build signed and notarized macOS app+ if: runner.os == 'macOS'uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1.0.0env:- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}- APPLE_CERTIFICATE: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE || '' }}- APPLE_CERTIFICATE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE_PASSWORD || '' }}- APPLE_SIGNING_IDENTITY: ${{ runner.os == 'macOS' && secrets.APPLE_SIGNING_IDENTITY || '' }}- APPLE_API_ISSUER: ${{ runner.os == 'macOS' && secrets.APPLE_API_ISSUER || '' }}- APPLE_API_KEY: ${{ runner.os == 'macOS' && secrets.APPLE_API_KEY || '' }}+ APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}+ APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}+ APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}APPLE_API_KEY_PATH: ${{ env.APPLE_API_KEY_PATH }}- APPLE_TEAM_ID: ${{ runner.os == 'macOS' && secrets.APPLE_TEAM_ID || '' }}with:projectPath: src/desktop- releaseId: ${{ steps.release.outputs.id }}- uploadUpdaterJson: trueargs: --target ${{ matrix.target }}- - name: Verify signed and notarized macOS artifact+ - name: Build Linux app+ if: runner.os == 'Linux'+ uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1.0.0+ env:+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}+ with:+ projectPath: src/desktop+ args: --target ${{ matrix.target }}++ - name: Stage exact release bytes+ shell: bash+ env:+ TARGET: ${{ matrix.target }}+ STAGE_TARGET: ${{ matrix.stage-target }}+ VERSION: ${{ steps.version.outputs.version }}+ run: |+ set -euo pipefail+ stage="$RUNNER_TEMP/desktop-release-${STAGE_TARGET}"+ node scripts/ci/desktop-release-artifacts.mjs collect \+ --target "$STAGE_TARGET" \+ --version "$VERSION" \+ --source "src/desktop/src-tauri/target/${TARGET}/release" \+ --stage "$stage"+ echo "DESKTOP_STAGE=$stage" >> "$GITHUB_ENV"++ - name: Verify staged macOS bytesif: runner.os == 'macOS'shell: bashenv:+ STAGE_DIR: ${{ env.DESKTOP_STAGE }}EXPECTED_TARGET: ${{ matrix.target }}EXPECTED_VERSION: ${{ steps.version.outputs.version }}+ EXPECTED_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}+ EXPECTED_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}+ run: bash scripts/ci/verify-desktop-macos.sh++ - name: Verify staged Linux updater signatures+ if: runner.os == 'Linux'+ shell: bash+ env:+ VERSION: ${{ steps.version.outputs.version }}run: |set -euo pipefail- bundle_root="src/desktop/src-tauri/target/${EXPECTED_TARGET}/release/bundle"- dmg_path=$(find "$bundle_root/dmg" -maxdepth 1 -type f -name '*.dmg' -print -quit)- test -n "$dmg_path"-- mount_dir=$(mktemp -d "$RUNNER_TEMP/alook-dmg.XXXXXX")- cleanup() {- hdiutil detach "$mount_dir" -quiet || true- rmdir "$mount_dir" || true- }- trap cleanup EXIT- hdiutil attach "$dmg_path" -nobrowse -readonly -mountpoint "$mount_dir" -quiet-- app_path=$(find "$mount_dir" -maxdepth 1 -type d -name '*.app' -print -quit)- test -n "$app_path"- executable=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$app_path/Contents/Info.plist")- test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$app_path/Contents/Info.plist")" = "$EXPECTED_VERSION"-- codesign --verify --deep --strict --verbose=2 "$app_path"- signature=$(codesign -dvvv "$app_path" 2>&1)- grep -q 'Authority=Developer ID Application:' <<<"$signature"- grep -q 'flags=.*runtime' <<<"$signature"- xcrun stapler validate "$app_path"- spctl --assess --type execute --verbose=4 "$app_path"-- archs=$(lipo -archs "$app_path/Contents/MacOS/$executable")- case "$EXPECTED_TARGET" in- aarch64-apple-darwin) grep -qw arm64 <<<"$archs" ;;- x86_64-apple-darwin) grep -qw x86_64 <<<"$archs" ;;- *) exit 1 ;;- esac-- update-release-notes:- needs: build- runs-on: ubuntu-latest+ node scripts/ci/desktop-release-artifacts.mjs validate \+ --target linux-x86_64 --version "$VERSION" --stage "$DESKTOP_STAGE"+ for asset in \+ "Alook_${VERSION}_amd64.deb" \+ "Alook-${VERSION}-1.x86_64.rpm" \+ "Alook_${VERSION}_amd64.AppImage"; do+ node scripts/ci/verify-minisign.mjs \+ --file "$DESKTOP_STAGE/files/$asset" \+ --signature "$DESKTOP_STAGE/files/$asset.sig" \+ --config src/desktop/src-tauri/tauri.conf.json \+ --version "$VERSION" --trusted-file "$asset"+ done++ - name: Upload private verified stage+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7+ with:+ name: desktop-release-${{ matrix.stage-target }}+ path: ${{ env.DESKTOP_STAGE }}+ if-no-files-found: error+ retention-days: 7++ - name: Clean temporary macOS signing material+ if: always() && runner.os == 'macOS'+ shell: bash+ run: |+ set +e+ if [[ -f "${ALOOK_MACOS_KEYCHAIN_LIST:-}" ]]; then+ original_keychains=()+ while IFS= read -r keychain; do [[ -n "$keychain" ]] && original_keychains+=("$keychain"); done < "$ALOOK_MACOS_KEYCHAIN_LIST"+ security list-keychains -d user -s "${original_keychains[@]}"+ fi+ [[ -n "${ALOOK_MACOS_KEYCHAIN_PATH:-}" ]] && security delete-keychain "$ALOOK_MACOS_KEYCHAIN_PATH"+ rm -f "${ALOOK_MACOS_P12_PATH:-}" "${APPLE_API_KEY_PATH:-}" "${ALOOK_MACOS_KEYCHAIN_LIST:-}"++ build-windows:+ runs-on: windows-latest+ timeout-minutes: 45permissions:- contents: write+ contents: read+ id-token: writesteps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - name: Install pnpm+ uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0++ - name: Setup Node.js+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7+ with:+ node-version: 22+ cache: pnpm+ cache-dependency-path: pnpm-lock.yaml++ - name: Install Rust stable+ uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stable+ with:+ targets: x86_64-pc-windows-msvc++ - name: Restore Rust cache+ uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2+ with:+ workspaces: src/desktop/src-tauri+ key: x86_64-pc-windows-msvc++ - name: Install frontend dependencies+ run: pnpm install --frozen-lockfile+ working-directory: src/desktop+- name: Read versionid: version+ shell: bashrun: echo "version=$(tr -d '\n' < src/desktop/.deploy-version)" >> "$GITHUB_OUTPUT"- - name: Append download links to release body+ - name: Preflight Windows release inputs+ shell: pwsh+ env:+ AZURE_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }}+ AZURE_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}+ AZURE_SUBSCRIPTION_ID: ${{ vars.AZURE_SUBSCRIPTION_ID }}+ ALOOK_ARTIFACT_SIGNING_ENDPOINT: ${{ vars.AZURE_ARTIFACT_SIGNING_ENDPOINT }}+ ALOOK_ARTIFACT_SIGNING_ACCOUNT_NAME: ${{ vars.AZURE_ARTIFACT_SIGNING_ACCOUNT_NAME }}+ ALOOK_ARTIFACT_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ vars.AZURE_ARTIFACT_SIGNING_CERTIFICATE_PROFILE_NAME }}+ ALOOK_WINDOWS_SIGNING_PUBLISHER: ${{ vars.WINDOWS_SIGNING_PUBLISHER }}+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}+ run: |+ $required = @(+ "AZURE_CLIENT_ID", "AZURE_TENANT_ID", "AZURE_SUBSCRIPTION_ID",+ "ALOOK_ARTIFACT_SIGNING_ENDPOINT", "ALOOK_ARTIFACT_SIGNING_ACCOUNT_NAME",+ "ALOOK_ARTIFACT_SIGNING_CERTIFICATE_PROFILE_NAME", "ALOOK_WINDOWS_SIGNING_PUBLISHER",+ "TAURI_SIGNING_PRIVATE_KEY", "TAURI_SIGNING_PRIVATE_KEY_PASSWORD"+ )+ foreach ($name in $required) {+ if ([string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($name))) {+ throw "Missing required Windows release input: $name"+ }+ }+ [Uri]$endpoint = $null+ if (-not [Uri]::TryCreate($env:ALOOK_ARTIFACT_SIGNING_ENDPOINT, [UriKind]::Absolute, [ref]$endpoint) -or+ $endpoint.Scheme -ne [Uri]::UriSchemeHttps -or+ $endpoint.DnsSafeHost -notmatch '^[a-z0-9-]+\.codesigning\.azure\.net$' -or+ -not $endpoint.IsDefaultPort -or+ $endpoint.AbsolutePath -ne '/' -or+ $endpoint.UserInfo -ne '' -or+ $endpoint.Query -ne '' -or+ $endpoint.Fragment -ne '') {+ throw "Artifact Signing endpoint must be an HTTPS regional codesigning.azure.net root URL"+ }++ - name: Login to Azure with GitHub OIDC+ uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0+ with:+ client-id: ${{ vars.AZURE_CLIENT_ID }}+ tenant-id: ${{ vars.AZURE_TENANT_ID }}+ subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}++ - name: Prepare digest-verified Artifact Signing module+ shell: pwsh+ run: |+ $destination = Join-Path $env:RUNNER_TEMP "alook-artifact-signing-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT"+ "ALOOK_ARTIFACT_SIGNING_ROOT=$destination" | Out-File -LiteralPath $env:GITHUB_ENV -Append -Encoding utf8+ ./scripts/ci/prepare-desktop-windows-signing.ps1 -DestinationRoot $destination++ - name: Prepare canonical Tauri signing root+ shell: pwsh+ run: |+ $root = [IO.Path]::GetFullPath((Join-Path $env:GITHUB_WORKSPACE "src\desktop\src-tauri\target\x86_64-pc-windows-msvc\release"))+ $temp = Join-Path $root "tauri-sign-temp"+ New-Item -Path $temp -ItemType Directory -Force | Out-Null+ "ALOOK_WINDOWS_SIGNING_ROOT=$root" | Out-File -LiteralPath $env:GITHUB_ENV -Append -Encoding utf8+ "TEMP=$temp" | Out-File -LiteralPath $env:GITHUB_ENV -Append -Encoding utf8+ "TMP=$temp" | Out-File -LiteralPath $env:GITHUB_ENV -Append -Encoding utf8++ - name: Build signed Windows app+ uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1.0.0+ env:+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}+ ALOOK_ARTIFACT_SIGNING_ENDPOINT: ${{ vars.AZURE_ARTIFACT_SIGNING_ENDPOINT }}+ ALOOK_ARTIFACT_SIGNING_ACCOUNT_NAME: ${{ vars.AZURE_ARTIFACT_SIGNING_ACCOUNT_NAME }}+ ALOOK_ARTIFACT_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ vars.AZURE_ARTIFACT_SIGNING_CERTIFICATE_PROFILE_NAME }}+ with:+ projectPath: src/desktop+ args: --target x86_64-pc-windows-msvc --config src-tauri/tauri.windows.signing.conf.json++ - name: Stage exact Windows release bytes+ shell: pwshenv:- GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}VERSION: ${{ steps.version.outputs.version }}run: |- TAG="v${VERSION}"- BASE="https://github.com/${{ github.repository }}/releases/download/${TAG}"+ $stage = Join-Path $env:RUNNER_TEMP "desktop-release-windows-x86_64"+ node scripts/ci/desktop-release-artifacts.mjs collect --target windows-x86_64 --version $env:VERSION --source "src/desktop/src-tauri/target/x86_64-pc-windows-msvc/release" --stage $stage+ if ($LASTEXITCODE -ne 0) { throw "Windows release staging failed" }+ "DESKTOP_STAGE=$stage" | Out-File -LiteralPath $env:GITHUB_ENV -Append -Encoding utf8++ - name: Verify staged Windows bytes+ shell: pwsh+ env:+ EXPECTED_PUBLISHER: ${{ vars.WINDOWS_SIGNING_PUBLISHER }}+ VERSION: ${{ steps.version.outputs.version }}+ run: |+ ./scripts/ci/verify-desktop-windows.ps1 -StageDirectory $env:DESKTOP_STAGE -ExpectedVersion $env:VERSION -ExpectedPublisher $env:EXPECTED_PUBLISHER -TauriConfigPath "src/desktop/src-tauri/tauri.conf.json"++ - name: Upload private verified Windows stage+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7+ with:+ name: desktop-release-windows-x86_64+ path: ${{ env.DESKTOP_STAGE }}+ if-no-files-found: error+ retention-days: 7++ - name: Clean temporary Windows signing state+ if: always()+ shell: pwsh+ run: |+ $ErrorActionPreference = "SilentlyContinue"+ $PSNativeCommandUseErrorActionPreference = $false+ az logout 2>$null+ az account clear 2>$null+ if ($env:ALOOK_ARTIFACT_SIGNING_ROOT) {+ Remove-Item -LiteralPath $env:ALOOK_ARTIFACT_SIGNING_ROOT -Recurse -Force -ErrorAction SilentlyContinue+ }+ if ($env:TEMP -and $env:ALOOK_WINDOWS_SIGNING_ROOT -and $env:TEMP.StartsWith($env:ALOOK_WINDOWS_SIGNING_ROOT)) {+ Remove-Item -LiteralPath $env:TEMP -Recurse -Force -ErrorAction SilentlyContinue+ }++ publish:+ needs: [build-unix, build-windows]+ runs-on: ubuntu-latest+ permissions:+ contents: write+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7++ - name: Setup Node.js+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7+ with:+ node-version: 22++ - name: Download all private verified stages+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8+ with:+ pattern: desktop-release-*+ path: ${{ runner.temp }}/desktop-release-stages+ merge-multiple: false++ - name: Aggregate exact bytes and deterministic updater metadata+ id: aggregate+ shell: bash+ run: |+ set -euo pipefail+ version=$(tr -d '\n' < src/desktop/.deploy-version)+ pub_date=$(node -e 'process.stdout.write(new Date(process.argv[1]).toISOString())' "$(git show -s --format=%cI "$GITHUB_SHA")")+ publish_dir="$RUNNER_TEMP/desktop-release-publish"+ node scripts/ci/desktop-release-artifacts.mjs aggregate \+ --root "$RUNNER_TEMP/desktop-release-stages" \+ --output "$publish_dir" \+ --version "$version" \+ --repository "$GITHUB_REPOSITORY" \+ --pub-date "$pub_date" \+ --config src/desktop/src-tauri/tauri.conf.json+ {+ echo "version=$version"+ echo "tag=v$version"+ echo "publish_dir=$publish_dir"+ } >> "$GITHUB_OUTPUT"- EXISTING=$(gh release view "$TAG" --json body --jq '.body' 2>/dev/null || echo "")+ - name: Resolve existing release after every verification gate+ shell: bash+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ TAG: ${{ steps.aggregate.outputs.tag }}+ run: |+ set -euo pipefail+ release_found=false+ for attempt in {1..30}; do+ if gh api "repos/$GITHUB_REPOSITORY/releases/tags/$TAG" >/dev/null 2>&1; then+ release_found=true+ break+ fi+ echo "Waiting for $TAG release ($attempt/30)..."+ sleep 2+ done+ [[ "$release_found" == true ]] || {+ echo "::error::Release $TAG was not created within 60 seconds"+ exit 1+ }- DOWNLOADS="+ git fetch --force --no-tags origin "refs/tags/$TAG:refs/tags/$TAG"+ tag_commit=$(git rev-parse "$TAG^{commit}")+ [[ "$tag_commit" == "$GITHUB_SHA" ]] || {+ echo "::error::Tag $TAG points to $tag_commit instead of workflow commit $GITHUB_SHA"+ exit 1+ }+ release_json="$RUNNER_TEMP/desktop-release-before-upload.json"+ gh api "repos/$GITHUB_REPOSITORY/releases/tags/$TAG" > "$release_json"+ node scripts/ci/desktop-release-artifacts.mjs assert-publishable \+ --release "$release_json" --tag "$TAG"+ - name: Upload verified binary and signature assets+ shell: bash+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ TAG: ${{ steps.aggregate.outputs.tag }}+ PUBLISH_DIR: ${{ steps.aggregate.outputs.publish_dir }}+ run: |+ set -euo pipefail+ gh release upload "$TAG" "$PUBLISH_DIR"/assets/*+ gh api "repos/$GITHUB_REPOSITORY/releases/tags/$TAG" > "$RUNNER_TEMP/desktop-release-after-assets.json"+ node scripts/ci/desktop-release-artifacts.mjs verify-published \+ --manifest "$PUBLISH_DIR/release-manifest.json" \+ --release "$RUNNER_TEMP/desktop-release-after-assets.json" \+ --tag "$TAG"++ - name: Upload latest.json last+ shell: bash+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ TAG: ${{ steps.aggregate.outputs.tag }}+ PUBLISH_DIR: ${{ steps.aggregate.outputs.publish_dir }}+ run: |+ set -euo pipefail+ gh release upload "$TAG" "$PUBLISH_DIR/latest.json"+ gh api "repos/$GITHUB_REPOSITORY/releases/tags/$TAG" > "$RUNNER_TEMP/desktop-release-complete.json"+ node scripts/ci/desktop-release-artifacts.mjs verify-published \+ --manifest "$PUBLISH_DIR/release-manifest.json" \+ --release "$RUNNER_TEMP/desktop-release-complete.json" \+ --latest "$PUBLISH_DIR/latest.json" \+ --tag "$TAG"++ - name: Append verified download links+ shell: bash+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ TAG: ${{ steps.aggregate.outputs.tag }}+ VERSION: ${{ steps.aggregate.outputs.version }}+ run: |+ set -euo pipefail+ base="https://github.com/$GITHUB_REPOSITORY/releases/download/$TAG"+ existing="$RUNNER_TEMP/existing-release-notes.md"+ notes="$RUNNER_TEMP/verified-release-notes.md"+ gh release view "$TAG" --json body --jq '.body' > "$existing"+ awk '/^<!-- alook-desktop-downloads -->$/{exit} {print}' "$existing" > "$notes"+ cat >> "$notes" <<EOF++ <!-- alook-desktop-downloads -->---## Download### macOS- [Apple Silicon](${BASE}/Alook_${VERSION}_aarch64.dmg) | [Intel](${BASE}/Alook_${VERSION}_x64.dmg)+ [Apple Silicon](${base}/Alook_${VERSION}_aarch64.dmg) | [Intel](${base}/Alook_${VERSION}_x64.dmg)- These macOS builds are Developer ID signed, hardened-runtime enabled, notarized by Apple, and validated for their advertised architecture.+ Developer ID signed, hardened-runtime enabled, notarized, stapled, and Gatekeeper verified.### Windows- [.exe Installer](${BASE}/Alook_${VERSION}_x64-setup.exe) | [.msi](${BASE}/Alook_${VERSION}_x64_en-US.msi)+ [.exe Installer](${base}/Alook_${VERSION}_x64-setup.exe) | [.msi](${base}/Alook_${VERSION}_x64_en-US.msi)- These Windows builds are not Authenticode code-signed. On first launch, Microsoft Defender SmartScreen may block the app; choose **More info** → **Run anyway** to continue.+ Authenticode signed with SHA-256 and an RFC 3161 timestamp. Embedded application executables and exact updater signatures are verified before publication.### Linux- [.deb](${BASE}/Alook_${VERSION}_amd64.deb) | [.rpm](${BASE}/Alook-${VERSION}-1.x86_64.rpm) | [.AppImage](${BASE}/Alook_${VERSION}_amd64.AppImage)"-- gh release edit "$TAG" --notes "${EXISTING}${DOWNLOADS}"+ [.deb](${base}/Alook_${VERSION}_amd64.deb) | [.rpm](${base}/Alook-${VERSION}-1.x86_64.rpm) | [.AppImage](${base}/Alook_${VERSION}_amd64.AppImage)+ EOF+ gh release edit "$TAG" --notes-file "$notes"diff --git a/scripts/ci/desktop-release-artifacts.mjs b/scripts/ci/desktop-release-artifacts.mjsnew file mode 100644index 000000000..52959654f--- /dev/null+++ b/scripts/ci/desktop-release-artifacts.mjs@@ -0,0 +1,409 @@+import { createHash } from "node:crypto"+import {+ constants,+ copyFileSync,+ createReadStream,+ lstatSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ writeFileSync,+} from "node:fs"+import { basename, dirname, join, relative, resolve, sep } from "node:path"+import { pathToFileURL } from "node:url"++import { readUpdaterPublicKey, verifyMinisignFile } from "./verify-minisign.mjs"++export const REQUIRED_TARGETS = ["macos-aarch64", "macos-x86_64", "linux-x86_64", "windows-x86_64"]+export const REQUIRED_PLATFORM_KEYS = [+ "darwin-aarch64",+ "darwin-aarch64-app",+ "darwin-x86_64",+ "darwin-x86_64-app",+ "linux-x86_64",+ "linux-x86_64-appimage",+ "linux-x86_64-deb",+ "linux-x86_64-rpm",+ "windows-x86_64",+ "windows-x86_64-msi",+ "windows-x86_64-nsis",+]++const DESKTOP_RELEASE_SUFFIXES = [".dmg", ".app.tar.gz", ".deb", ".rpm", ".AppImage", ".msi", "-setup.exe"]+const DESKTOP_ARCHITECTURE_PATTERN = /(?:^|[._-])(?:aarch64|amd64|x64|x86_64)(?:[._-]|$)/i++function asset(source, name, roles, updaterPlatformKeys = []) {+ return { source, name, roles, updaterPlatformKeys }+}++function signature(source, signedFile) {+ return {+ source,+ name: `${signedFile}.sig`,+ roles: ["signature"],+ updaterPlatformKeys: [],+ signedFile,+ trustedFile: basename(source.slice(0, -".sig".length)),+ }+}++export function targetSpec(target, version) {+ if (!/^\d+\.\d+\.\d+$/.test(version)) throw new Error(`Release version must be numeric semver: ${version}`)+ const specs = {+ "macos-aarch64": [+ asset(`bundle/dmg/Alook_${version}_aarch64.dmg`, `Alook_${version}_aarch64.dmg`, ["installer"]),+ asset("bundle/macos/Alook.app.tar.gz", `Alook_${version}_aarch64.app.tar.gz`, ["updater"], ["darwin-aarch64", "darwin-aarch64-app"]),+ signature("bundle/macos/Alook.app.tar.gz.sig", `Alook_${version}_aarch64.app.tar.gz`),+ ],+ "macos-x86_64": [+ asset(`bundle/dmg/Alook_${version}_x64.dmg`, `Alook_${version}_x64.dmg`, ["installer"]),+ asset("bundle/macos/Alook.app.tar.gz", `Alook_${version}_x64.app.tar.gz`, ["updater"], ["darwin-x86_64", "darwin-x86_64-app"]),+ signature("bundle/macos/Alook.app.tar.gz.sig", `Alook_${version}_x64.app.tar.gz`),+ ],+ "linux-x86_64": [+ asset(`bundle/deb/Alook_${version}_amd64.deb`, `Alook_${version}_amd64.deb`, ["installer", "updater"], ["linux-x86_64-deb"]),+ signature(`bundle/deb/Alook_${version}_amd64.deb.sig`, `Alook_${version}_amd64.deb`),+ asset(`bundle/rpm/Alook-${version}-1.x86_64.rpm`, `Alook-${version}-1.x86_64.rpm`, ["installer", "updater"], ["linux-x86_64-rpm"]),+ signature(`bundle/rpm/Alook-${version}-1.x86_64.rpm.sig`, `Alook-${version}-1.x86_64.rpm`),+ asset(`bundle/appimage/Alook_${version}_amd64.AppImage`, `Alook_${version}_amd64.AppImage`, ["installer", "updater"], ["linux-x86_64", "linux-x86_64-appimage"]),+ signature(`bundle/appimage/Alook_${version}_amd64.AppImage.sig`, `Alook_${version}_amd64.AppImage`),+ ],+ "windows-x86_64": [+ asset(`bundle/msi/Alook_${version}_x64_en-US.msi`, `Alook_${version}_x64_en-US.msi`, ["installer", "updater"], ["windows-x86_64", "windows-x86_64-msi"]),+ signature(`bundle/msi/Alook_${version}_x64_en-US.msi.sig`, `Alook_${version}_x64_en-US.msi`),+ asset(`bundle/nsis/Alook_${version}_x64-setup.exe`, `Alook_${version}_x64-setup.exe`, ["installer", "updater"], ["windows-x86_64-nsis"]),+ signature(`bundle/nsis/Alook_${version}_x64-setup.exe.sig`, `Alook_${version}_x64-setup.exe`),+ ],+ }+ const spec = specs[target]+ if (!spec) throw new Error(`Unsupported desktop release target: ${target}`)+ return spec+}++async function sha256(path) {+ const hash = createHash("sha256")+ for await (const chunk of createReadStream(path)) hash.update(chunk)+ return hash.digest("hex")+}++function assertRegularFile(path, label = path) {+ const stat = lstatSync(path)+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`${label} must be a regular non-symlink file`)+ return stat+}++function safeRelativePath(path) {+ if (typeof path !== "string" || path.length === 0 || path.includes("\\")) return false+ return !path.startsWith("/") && !path.split("/").some((part) => part === "" || part === "." || part === "..")+}++function stableJson(value) {+ return `${JSON.stringify(value, null, 2)}\n`+}++export function resolveSourcePath(sourceRoot, candidate) {+ const sourcePath = resolve(sourceRoot, candidate)+ const sourceRelativePath = relative(sourceRoot, sourcePath)+ if (sourceRelativePath.startsWith(`..${sep}`) || sourceRelativePath === "..") {+ throw new Error(`Source path escapes the bundle root: ${candidate}`)+ }+ return sourcePath+}++export async function collectTarget({ target, version, sourceRoot, stageDirectory }) {+ const source = resolve(sourceRoot)+ const stage = resolve(stageDirectory)+ mkdirSync(stage)+ const filesDirectory = join(stage, "files")+ mkdirSync(filesDirectory)++ const files = []+ for (const expected of targetSpec(target, version).toSorted((left, right) => left.name.localeCompare(right.name))) {+ if (basename(expected.name) !== expected.name) throw new Error(`Unsafe release asset name: ${expected.name}`)+ const sourcePath = resolveSourcePath(source, expected.source)+ assertRegularFile(sourcePath, expected.source)+ const destination = join(filesDirectory, expected.name)+ copyFileSync(sourcePath, destination, constants.COPYFILE_EXCL)+ const stat = assertRegularFile(destination)+ files.push({+ name: expected.name,+ path: `files/${expected.name}`,+ roles: expected.roles,+ updaterPlatformKeys: expected.updaterPlatformKeys,+ ...(expected.signedFile ? { signedFile: expected.signedFile } : {}),+ ...(expected.trustedFile ? { trustedFile: expected.trustedFile } : {}),+ size: stat.size,+ sha256: await sha256(destination),+ })+ }++ const manifest = { schemaVersion: 1, target, version, files }+ writeFileSync(join(stage, "manifest.json"), stableJson(manifest), { flag: "wx" })+ return manifest+}++function assertStringArray(actual, expected, label) {+ if (!Array.isArray(actual) || actual.length !== expected.length || actual.some((value, index) => value !== expected[index])) {+ throw new Error(`${label} does not match the release contract`)+ }+}++export async function validateStage(stageDirectory, expectedTarget, expectedVersion) {+ const stage = resolve(stageDirectory)+ const stageEntries = readdirSync(stage, { withFileTypes: true })+ if (stageEntries.length !== 2 || !stageEntries.some((entry) => entry.isDirectory() && entry.name === "files") || !stageEntries.some((entry) => entry.isFile() && entry.name === "manifest.json")) {+ throw new Error(`${expectedTarget} stage must contain only files/ and manifest.json`)+ }++ const manifestPath = join(stage, "manifest.json")+ assertRegularFile(manifestPath)+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"))+ if (manifest.schemaVersion !== 1 || manifest.target !== expectedTarget || manifest.version !== expectedVersion) {+ throw new Error(`${expectedTarget} manifest identity or version drift`)+ }++ const expectedFiles = targetSpec(expectedTarget, expectedVersion).toSorted((left, right) => left.name.localeCompare(right.name))+ if (!Array.isArray(manifest.files) || manifest.files.length !== expectedFiles.length) {+ throw new Error(`${expectedTarget} manifest has an incomplete or extra file set`)+ }++ const actualDirectoryEntries = readdirSync(join(stage, "files"), { withFileTypes: true })+ if (actualDirectoryEntries.length !== expectedFiles.length || actualDirectoryEntries.some((entry) => !entry.isFile() || entry.isSymbolicLink())) {+ throw new Error(`${expectedTarget} files directory contains an unexpected entry`)+ }++ const actualFiles = [...manifest.files].toSorted((left, right) => String(left.name).localeCompare(String(right.name)))+ for (let index = 0; index < expectedFiles.length; index += 1) {+ const expected = expectedFiles[index]+ const actual = actualFiles[index]+ if (actual.name !== expected.name || actual.path !== `files/${expected.name}` || !safeRelativePath(actual.path)) {+ throw new Error(`${expectedTarget} manifest contains an unsafe or unexpected asset path`)+ }+ assertStringArray(actual.roles, expected.roles, `${actual.name} roles`)+ assertStringArray(actual.updaterPlatformKeys, expected.updaterPlatformKeys, `${actual.name} updater keys`)+ if ((actual.signedFile ?? null) !== (expected.signedFile ?? null)) throw new Error(`${actual.name} signature association drift`)+ if ((actual.trustedFile ?? null) !== (expected.trustedFile ?? null)) throw new Error(`${actual.name} trusted filename drift`)+ if (!Number.isSafeInteger(actual.size) || actual.size < 0 || !/^[0-9a-f]{64}$/.test(actual.sha256)) {+ throw new Error(`${actual.name} has invalid digest metadata`)+ }++ const filePath = join(stage, actual.path)+ const stat = assertRegularFile(filePath)+ if (stat.size !== actual.size || (await sha256(filePath)) !== actual.sha256) {+ throw new Error(`${actual.name} staged bytes do not match the manifest`)+ }+ }++ return { ...manifest, files: actualFiles }+}++export async function aggregateStages({ stageRoot, outputDirectory, version, repository, pubDate, configPath }) {+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) throw new Error(`Invalid GitHub repository: ${repository}`)+ const date = new Date(pubDate)+ if (!Number.isFinite(date.valueOf()) || date.toISOString() !== pubDate) throw new Error(`pubDate must be a canonical ISO timestamp: ${pubDate}`)++ const root = resolve(stageRoot)+ const rootEntries = readdirSync(root, { withFileTypes: true })+ const expectedDirectories = REQUIRED_TARGETS.map((target) => `desktop-release-${target}`).toSorted()+ const actualDirectories = rootEntries.map((entry) => entry.name).toSorted()+ if (rootEntries.some((entry) => !entry.isDirectory() || entry.isSymbolicLink()) || JSON.stringify(actualDirectories) !== JSON.stringify(expectedDirectories)) {+ throw new Error("Downloaded release stages do not match the four required targets")+ }++ const publicKey = readUpdaterPublicKey(configPath)+ const manifests = []+ for (const target of REQUIRED_TARGETS) {+ manifests.push(await validateStage(join(root, `desktop-release-${target}`), target, version))+ }++ const names = new Set()+ const platformKeys = new Map()+ const assets = []+ for (const manifest of manifests) {+ const stage = join(root, `desktop-release-${manifest.target}`)+ const byName = new Map(manifest.files.map((file) => [file.name, file]))+ for (const file of manifest.files) {+ if (names.has(file.name)) throw new Error(`Duplicate release asset name: ${file.name}`)+ names.add(file.name)+ const path = join(stage, file.path)+ assets.push({ name: file.name, sha256: file.sha256, size: file.size, sourcePath: path, target: manifest.target })++ if (file.signedFile) {+ const signed = byName.get(file.signedFile)+ if (!signed) throw new Error(`${file.name} refers to a missing signed file`)+ await verifyMinisignFile({+ filePath: join(stage, signed.path),+ signaturePath: path,+ encodedPublicKey: publicKey,+ expectedVersion: version,+ expectedTrustedFile: file.trustedFile,+ })+ }+ }++ for (const file of manifest.files.filter((candidate) => candidate.updaterPlatformKeys.length > 0)) {+ const signature = byName.get(`${file.name}.sig`)+ if (!signature || signature.signedFile !== file.name) throw new Error(`${file.name} is missing its adjacent updater signature`)+ const signatureText = readFileSync(join(stage, signature.path), "utf8")+ for (const key of file.updaterPlatformKeys) {+ if (platformKeys.has(key)) throw new Error(`Duplicate updater platform key: ${key}`)+ platformKeys.set(key, {+ signature: signatureText,+ url: `https://github.com/${repository}/releases/download/v${version}/${encodeURIComponent(file.name)}`,+ })+ }+ }+ }++ const actualKeys = [...platformKeys.keys()].toSorted()+ assertCompletePlatformKeys(actualKeys)++ const output = resolve(outputDirectory)+ mkdirSync(output)+ const assetsDirectory = join(output, "assets")+ mkdirSync(assetsDirectory)+ const releaseAssets = []+ for (const asset of assets.toSorted((left, right) => left.name.localeCompare(right.name))) {+ const destination = join(assetsDirectory, asset.name)+ copyFileSync(asset.sourcePath, destination, constants.COPYFILE_EXCL)+ if ((await sha256(destination)) !== asset.sha256) throw new Error(`Copied release asset digest drift: ${asset.name}`)+ releaseAssets.push({ name: asset.name, sha256: asset.sha256, size: asset.size, target: asset.target })+ }++ const platforms = Object.fromEntries([...platformKeys.entries()].toSorted(([left], [right]) => left.localeCompare(right)))+ const latest = {+ version,+ notes: `See https://github.com/${repository}/releases/tag/v${version}`,+ pub_date: pubDate,+ platforms,+ }+ const releaseManifest = { schemaVersion: 1, version, assets: releaseAssets }+ writeFileSync(join(output, "latest.json"), stableJson(latest), { flag: "wx" })+ writeFileSync(join(output, "release-manifest.json"), stableJson(releaseManifest), { flag: "wx" })+ return { latest, releaseManifest }+}++function readRelease(releaseJsonPath, expectedTag) {+ if (typeof expectedTag !== "string" || !/^v\d+\.\d+\.\d+$/.test(expectedTag)) {+ throw new Error(`Expected release tag must be numeric semver: ${String(expectedTag)}`)+ }+ const release = JSON.parse(readFileSync(releaseJsonPath, "utf8"))+ if (release.tag_name !== expectedTag) {+ throw new Error(`Release tag mismatch: expected ${expectedTag}, got ${String(release.tag_name)}`)+ }+ if (release.draft !== false || release.prerelease !== false) {+ throw new Error(`Release ${expectedTag} must be a published non-prerelease`)+ }+ if (!Array.isArray(release.assets)) throw new Error("Release API response has no assets array")+ const remote = new Map()+ for (const asset of release.assets) {+ if (typeof asset?.name !== "string") {+ throw new Error("Release API response contains invalid asset metadata")+ }+ if (remote.has(asset.name)) throw new Error(`Remote release contains duplicate asset name: ${asset.name}`)+ remote.set(asset.name, asset.digest)+ }+ return remote+}++function isDesktopReleaseAsset(name) {+ if (name === "latest.json") return true+ const binaryName = name.endsWith(".sig") ? name.slice(0, -".sig".length) : name+ return DESKTOP_RELEASE_SUFFIXES.some((suffix) => binaryName.endsWith(suffix)) && DESKTOP_ARCHITECTURE_PATTERN.test(binaryName)+}++export function assertPublishableRelease({ releaseJsonPath, expectedTag }) {+ const remote = readRelease(releaseJsonPath, expectedTag)+ const existingDesktopAssets = [...remote.keys()].filter(isDesktopReleaseAsset).toSorted()+ if (existingDesktopAssets.length > 0) {+ throw new Error(`Desktop release namespace is immutable and must start empty: ${existingDesktopAssets.join(", ")}`)+ }+}++export function verifyPublishedAssets({ releaseManifestPath, releaseJsonPath, includeLatestPath, expectedTag }) {+ const manifest = JSON.parse(readFileSync(releaseManifestPath, "utf8"))+ if (manifest.schemaVersion !== 1 || manifest.version !== expectedTag.slice(1) || !Array.isArray(manifest.assets)) {+ throw new Error("Published release manifest identity or version drift")+ }+ const remote = readRelease(releaseJsonPath, expectedTag)+ const expected = [...manifest.assets]+ if (includeLatestPath) {+ const latestStat = assertRegularFile(includeLatestPath)+ expected.push({ name: "latest.json", size: latestStat.size, sha256: createHash("sha256").update(readFileSync(includeLatestPath)).digest("hex") })+ }+ const expectedNames = new Set(expected.map((asset) => asset.name))+ const unexpectedDesktopAssets = [...remote.keys()]+ .filter((name) => isDesktopReleaseAsset(name) && !expectedNames.has(name))+ .toSorted()+ if (unexpectedDesktopAssets.length > 0) {+ throw new Error(`Remote release contains unexpected desktop asset candidates: ${unexpectedDesktopAssets.join(", ")}`)+ }+ for (const asset of expected) {+ if (remote.get(asset.name) !== `sha256:${asset.sha256}`) throw new Error(`Remote digest mismatch or missing asset: ${asset.name}`)+ }+}++export function assertCompletePlatformKeys(actualKeys) {+ if (JSON.stringify(actualKeys) !== JSON.stringify(REQUIRED_PLATFORM_KEYS)) {+ throw new Error(`Updater platform set is incomplete: ${actualKeys.join(", ")}`)+ }+}++export function parseArgs(argv) {+ const [command, ...rest] = argv+ const args = { command }+ for (let index = 0; index < rest.length; index += 2) {+ const key = rest[index]+ const value = rest[index + 1]+ if (!key?.startsWith("--") || value == null) throw new Error(`Invalid argument: ${key ?? "<missing>"}`)+ args[key.slice(2)] = value+ }+ return args+}++export async function main(argv = process.argv.slice(2)) {+ const args = parseArgs(argv)+ if (args.command === "collect") {+ await collectTarget({ target: args.target, version: args.version, sourceRoot: args.source, stageDirectory: args.stage })+ } else if (args.command === "validate") {+ await validateStage(args.stage, args.target, args.version)+ } else if (args.command === "aggregate") {+ await aggregateStages({+ stageRoot: args.root,+ outputDirectory: args.output,+ version: args.version,+ repository: args.repository,+ pubDate: args["pub-date"],+ configPath: args.config,+ })+ } else if (args.command === "verify-published") {+ verifyPublishedAssets({+ releaseManifestPath: args.manifest,+ releaseJsonPath: args.release,+ includeLatestPath: args.latest,+ expectedTag: args.tag,+ })+ } else if (args.command === "assert-publishable") {+ assertPublishableRelease({ releaseJsonPath: args.release, expectedTag: args.tag })+ } else {+ throw new Error("Expected collect, validate, aggregate, assert-publishable, or verify-published command")+ }+}++export async function runIfMain(+ metaUrl,+ argvPath = process.argv[1],+ argv = process.argv.slice(2),+ runtime = process,+) {+ if (!argvPath || pathToFileURL(argvPath).href !== metaUrl) return false+ try {+ await main(argv)+ } catch (error) {+ runtime.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)+ runtime.exitCode = 1+ }+ return true+}++void runIfMain(import.meta.url)diff --git a/scripts/ci/desktop-release-artifacts.test.ts b/scripts/ci/desktop-release-artifacts.test.tsnew file mode 100644index 000000000..d98b2b4e9--- /dev/null+++ b/scripts/ci/desktop-release-artifacts.test.ts@@ -0,0 +1,396 @@+import { createHash, generateKeyPairSync, randomBytes, sign } from "node:crypto"+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import { dirname, join } from "node:path"+import { pathToFileURL } from "node:url"+import { afterEach, describe, expect, it } from "vitest"++import {+ REQUIRED_PLATFORM_KEYS,+ REQUIRED_TARGETS,+ aggregateStages,+ assertCompletePlatformKeys,+ assertPublishableRelease,+ collectTarget,+ main as runDesktopReleaseCli,+ parseArgs as parseDesktopReleaseArgs,+ resolveSourcePath,+ runIfMain as runDesktopReleaseIfMain,+ targetSpec,+ validateStage,+ verifyPublishedAssets,+} from "./desktop-release-artifacts.mjs"++const version = "1.2.3"+const temporaryDirectories: string[] = []++function createSigningFixture() {+ const { privateKey, publicKey } = generateKeyPairSync("ed25519")+ const publicDer = publicKey.export({ format: "der", type: "spki" })+ const keyId = randomBytes(8)+ const publicPacket = Buffer.concat([Buffer.from("ED"), keyId, publicDer.subarray(-32)])+ const publicFile = `untrusted comment: fixture key\n${publicPacket.toString("base64")}\n`+ return {+ encodedPublicKey: Buffer.from(publicFile).toString("base64"),+ sign(data: Buffer, name: string) {+ const digest = createHash("blake2b512").update(data).digest()+ const fileSignature = sign(null, digest, privateKey)+ const trustedComment = `timestamp:1\tfile:${name}\tversion:${version}`+ const globalSignature = sign(null, Buffer.concat([fileSignature, Buffer.from(trustedComment)]), privateKey)+ const packet = Buffer.concat([Buffer.from("ED"), keyId, fileSignature])+ const signatureBox = `untrusted comment: fixture signature\n${packet.toString("base64")}\ntrusted comment: ${trustedComment}\n${globalSignature.toString("base64")}\n`+ return Buffer.from(signatureBox).toString("base64")+ },+ }+}++async function createAllStages() {+ const directory = mkdtempSync(join(tmpdir(), "alook-release-artifacts-"))+ temporaryDirectories.push(directory)+ const stages = join(directory, "stages")+ mkdirSync(stages)+ const signer = createSigningFixture()+ const configPath = join(directory, "tauri.conf.json")+ writeFileSync(configPath, JSON.stringify({ plugins: { updater: { pubkey: signer.encodedPublicKey } } }))++ for (const target of REQUIRED_TARGETS) {+ const source = join(directory, `source-${target}`)+ mkdirSync(source)+ const contents = new Map<string, Buffer>()+ for (const expected of targetSpec(target, version)) {+ const path = join(source, expected.source)+ mkdirSync(dirname(path), { recursive: true })+ if (expected.signedFile) {+ const signedContents = contents.get(expected.signedFile)+ if (!signedContents) throw new Error(`Fixture signature appears before signed file: ${expected.signedFile}`)+ writeFileSync(path, signer.sign(signedContents, expected.trustedFile))+ } else {+ const data = Buffer.from(`${target}:${expected.name}`)+ contents.set(expected.name, data)+ writeFileSync(path, data)+ }+ }+ await collectTarget({ target, version, sourceRoot: source, stageDirectory: join(stages, `desktop-release-${target}`) })+ }+ return { directory, stages, configPath }+}++afterEach(() => {+ for (const directory of temporaryDirectories.splice(0)) rmSync(directory, { force: true, recursive: true })+})++describe("desktop release artifact staging", () => {+ it("rejects unsupported target metadata and source path escapes", () => {+ expect(() => targetSpec("linux-x86_64", "v1.2.3")).toThrow("numeric semver")+ expect(() => targetSpec("freebsd-x86_64", version)).toThrow("Unsupported desktop release target")++ const root = join(tmpdir(), "alook-release-source")+ expect(resolveSourcePath(root, "bundle/app")).toBe(join(root, "bundle/app"))+ expect(() => resolveSourcePath(root, "../escape")).toThrow("escapes the bundle root")++ expect(() => assertCompletePlatformKeys(REQUIRED_PLATFORM_KEYS)).not.toThrow()+ expect(() => assertCompletePlatformKeys(REQUIRED_PLATFORM_KEYS.slice(1))).toThrow("platform set is incomplete")+ })++ it("collects exact allowlisted bytes and records stable digests", async () => {+ const fixture = await createAllStages()+ for (const target of REQUIRED_TARGETS) {+ const manifest = await validateStage(join(fixture.stages, `desktop-release-${target}`), target, version)+ expect(manifest.files.map((file: { name: string }) => file.name)).toEqual(+ [...manifest.files.map((file: { name: string }) => file.name)].sort((left, right) => left.localeCompare(right)),+ )+ }+ })++ it("aggregates all eleven updater keys deterministically", async () => {+ const fixture = await createAllStages()+ const firstOutput = join(fixture.directory, "output-a")+ const first = await aggregateStages({+ stageRoot: fixture.stages,+ outputDirectory: firstOutput,+ version,+ repository: "alookai/alook",+ pubDate: "2026-09-29T00:00:00.000Z",+ configPath: fixture.configPath,+ })++ for (const target of REQUIRED_TARGETS) {+ const manifestPath = join(fixture.stages, `desktop-release-${target}`, "manifest.json")+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"))+ manifest.files.reverse()+ writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)+ }+ const secondOutput = join(fixture.directory, "output-b")+ const second = await aggregateStages({+ stageRoot: fixture.stages,+ outputDirectory: secondOutput,+ version,+ repository: "alookai/alook",+ pubDate: "2026-09-29T00:00:00.000Z",+ configPath: fixture.configPath,+ })++ expect(Object.keys(first.latest.platforms)).toEqual(REQUIRED_PLATFORM_KEYS)+ expect(readFileSync(join(firstOutput, "latest.json"))).toEqual(readFileSync(join(secondOutput, "latest.json")))+ expect(second.releaseManifest).toEqual(first.releaseManifest)+ })++ it.each([+ ["version drift", (manifest: any) => (manifest.version = "9.9.9"), "identity or version drift"],+ ["traversal", (manifest: any) => (manifest.files[0].path = "../escape"), "unsafe or unexpected asset path"],+ ["duplicate asset", (manifest: any) => (manifest.files[1].name = manifest.files[0].name), "unsafe or unexpected asset path"],+ ["platform key drift", (manifest: any) => (manifest.files.find((file: any) => file.updaterPlatformKeys.length).updaterPlatformKeys = ["bad-key"]), "updater keys"],+ ["incomplete file set", (manifest: any) => manifest.files.pop(), "incomplete or extra file set"],+ ["role drift", (manifest: any) => (manifest.files[0].roles = ["wrong"]), "roles"],+ ["signature association drift", (manifest: any) => (manifest.files.find((file: any) => file.signedFile).signedFile = "wrong"), "signature association drift"],+ ["trusted filename drift", (manifest: any) => (manifest.files.find((file: any) => file.trustedFile).trustedFile = "wrong"), "trusted filename drift"],+ ["invalid digest metadata", (manifest: any) => (manifest.files[0].size = -1), "invalid digest metadata"],+ ])("rejects %s in a stage manifest", async (_label, mutate, message) => {+ const fixture = await createAllStages()+ const stage = join(fixture.stages, "desktop-release-windows-x86_64")+ const manifestPath = join(stage, "manifest.json")+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"))+ mutate(manifest)+ writeFileSync(manifestPath, JSON.stringify(manifest))+ await expect(validateStage(stage, "windows-x86_64", version)).rejects.toThrow(message)+ })++ it("rejects digest drift, extra files, symlinks, and missing targets", async () => {+ const fixture = await createAllStages()+ const stage = join(fixture.stages, "desktop-release-linux-x86_64")+ const manifest = JSON.parse(readFileSync(join(stage, "manifest.json"), "utf8"))+ writeFileSync(join(stage, manifest.files[0].path), "mutated")+ await expect(validateStage(stage, "linux-x86_64", version)).rejects.toThrow("staged bytes")++ const fresh = await createAllStages()+ const freshStage = join(fresh.stages, "desktop-release-macos-aarch64")+ writeFileSync(join(freshStage, "files", "extra"), "extra")+ await expect(validateStage(freshStage, "macos-aarch64", version)).rejects.toThrow("unexpected entry")++ const invalidShape = await createAllStages()+ const invalidShapeStage = join(invalidShape.stages, "desktop-release-macos-aarch64")+ writeFileSync(join(invalidShapeStage, "unexpected"), "unexpected")+ await expect(validateStage(invalidShapeStage, "macos-aarch64", version)).rejects.toThrow("only files/")++ const symlinkFixture = await createAllStages()+ const symlinkStage = join(symlinkFixture.stages, "desktop-release-macos-x86_64")+ symlinkSync(join(symlinkStage, "manifest.json"), join(symlinkStage, "files", "link"))+ await expect(validateStage(symlinkStage, "macos-x86_64", version)).rejects.toThrow("unexpected entry")++ const missing = await createAllStages()+ rmSync(join(missing.stages, "desktop-release-windows-x86_64"), { recursive: true })+ await expect(+ aggregateStages({+ stageRoot: missing.stages,+ outputDirectory: join(missing.directory, "output"),+ version,+ repository: "alookai/alook",+ pubDate: "2026-09-29T00:00:00.000Z",+ configPath: missing.configPath,+ }),+ ).rejects.toThrow("four required targets")+ })++ it("rejects a wrong minisign signature before producing publish bytes", async () => {+ const fixture = await createAllStages()+ const signature = join(fixture.stages, "desktop-release-windows-x86_64", "files", `Alook_${version}_x64-setup.exe.sig`)+ const signatureBox = Buffer.from(readFileSync(signature, "utf8"), "base64")+ .toString("utf8")+ .replace("timestamp:1", "timestamp:2")+ const contents = Buffer.from(signatureBox).toString("base64")+ writeFileSync(signature, contents)+ const manifestPath = join(fixture.stages, "desktop-release-windows-x86_64", "manifest.json")+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"))+ const entry = manifest.files.find((file: { name: string }) => file.name.endsWith("setup.exe.sig"))+ entry.size = Buffer.byteLength(contents)+ entry.sha256 = createHash("sha256").update(contents).digest("hex")+ writeFileSync(manifestPath, JSON.stringify(manifest))+ await expect(+ aggregateStages({+ stageRoot: fixture.stages,+ outputDirectory: join(fixture.directory, "output"),+ version,+ repository: "alookai/alook",+ pubDate: "2026-09-29T00:00:00.000Z",+ configPath: fixture.configPath,+ }),+ ).rejects.toThrow("trusted-comment")+ })++ it("accepts an empty desktop namespace alongside Android and rejects wrong tags or reruns", () => {+ const directory = mkdtempSync(join(tmpdir(), "alook-release-state-"))+ temporaryDirectories.push(directory)+ const releaseJsonPath = join(directory, "release.json")+ const writeRelease = (tag: string, names: string[]) => writeFileSync(+ releaseJsonPath,+ JSON.stringify({ tag_name: tag, draft: false, prerelease: false, assets: names.map((name) => ({ name, digest: "sha256:fixture" })) }),+ )++ writeRelease("v1.2.3", ["Alook_1.2.3_universal.apk"])+ expect(() => assertPublishableRelease({ releaseJsonPath, expectedTag: "v1.2.3" })).not.toThrow()+ expect(() => assertPublishableRelease({ releaseJsonPath, expectedTag: "v1.2.4" })).toThrow("Release tag mismatch")++ writeRelease("v1.2.3", [`Alook_${version}_x64-setup.exe`, `Alook_${version}_x64-setup.exe.sig`])+ expect(() => assertPublishableRelease({ releaseJsonPath, expectedTag: "v1.2.3" })).toThrow("must start empty")+ })++ it("rejects malformed release API and release-manifest state", () => {+ const directory = mkdtempSync(join(tmpdir(), "alook-release-invalid-state-"))+ temporaryDirectories.push(directory)+ const releaseJsonPath = join(directory, "release.json")+ const manifestPath = join(directory, "release-manifest.json")++ writeFileSync(releaseJsonPath, JSON.stringify({ tag_name: "v1.2.3", draft: false, prerelease: false, assets: [] }))+ expect(() => assertPublishableRelease({ releaseJsonPath, expectedTag: "1.2.3" })).toThrow("numeric semver")++ writeFileSync(releaseJsonPath, JSON.stringify({ tag_name: "v1.2.3", draft: true, prerelease: false, assets: [] }))+ expect(() => assertPublishableRelease({ releaseJsonPath, expectedTag: "v1.2.3" })).toThrow("published non-prerelease")++ writeFileSync(releaseJsonPath, JSON.stringify({ tag_name: "v1.2.3", draft: false, prerelease: false }))+ expect(() => assertPublishableRelease({ releaseJsonPath, expectedTag: "v1.2.3" })).toThrow("no assets array")++ writeFileSync(releaseJsonPath, JSON.stringify({ tag_name: "v1.2.3", draft: false, prerelease: false, assets: [{}] }))+ expect(() => assertPublishableRelease({ releaseJsonPath, expectedTag: "v1.2.3" })).toThrow("invalid asset metadata")++ writeFileSync(releaseJsonPath, JSON.stringify({+ tag_name: "v1.2.3",+ draft: false,+ prerelease: false,+ assets: [{ name: "duplicate" }, { name: "duplicate" }],+ }))+ expect(() => assertPublishableRelease({ releaseJsonPath, expectedTag: "v1.2.3" })).toThrow("duplicate asset name")++ writeFileSync(manifestPath, JSON.stringify({ schemaVersion: 2, version, assets: [] }))+ writeFileSync(releaseJsonPath, JSON.stringify({ tag_name: "v1.2.3", draft: false, prerelease: false, assets: [] }))+ expect(() => verifyPublishedAssets({+ releaseManifestPath: manifestPath,+ releaseJsonPath,+ expectedTag: "v1.2.3",+ })).toThrow("manifest identity or version drift")+ })++ it("compares exact published desktop digests while allowing an Android APK", async () => {+ const fixture = await createAllStages()+ const output = join(fixture.directory, "output")+ const { releaseManifest } = await aggregateStages({+ stageRoot: fixture.stages,+ outputDirectory: output,+ version,+ repository: "alookai/alook",+ pubDate: "2026-09-29T00:00:00.000Z",+ configPath: fixture.configPath,+ })+ const releaseJsonPath = join(fixture.directory, "release.json")+ writeFileSync(+ releaseJsonPath,+ JSON.stringify({+ tag_name: "v1.2.3",+ draft: false,+ prerelease: false,+ assets: [+ ...releaseManifest.assets.map((asset) => ({ name: asset.name, digest: `sha256:${asset.sha256}` })),+ { name: "Alook_1.2.3_universal.apk", digest: "sha256:android" },+ ],+ }),+ )+ expect(() =>+ verifyPublishedAssets({+ releaseManifestPath: join(output, "release-manifest.json"),+ releaseJsonPath,+ expectedTag: "v1.2.3",+ }),+ ).not.toThrow()+ const withLatest = JSON.parse(readFileSync(releaseJsonPath, "utf8"))+ const latestBytes = readFileSync(join(output, "latest.json"))+ withLatest.assets.push({+ name: "latest.json",+ digest: `sha256:${createHash("sha256").update(latestBytes).digest("hex")}`,+ })+ writeFileSync(releaseJsonPath, JSON.stringify(withLatest))+ expect(() => verifyPublishedAssets({+ releaseManifestPath: join(output, "release-manifest.json"),+ releaseJsonPath,+ includeLatestPath: join(output, "latest.json"),+ expectedTag: "v1.2.3",+ })).not.toThrow()+ const remote = JSON.parse(readFileSync(releaseJsonPath, "utf8"))+ remote.assets[0].digest = "sha256:deadbeef"+ writeFileSync(releaseJsonPath, JSON.stringify(remote))+ expect(() =>+ verifyPublishedAssets({+ releaseManifestPath: join(output, "release-manifest.json"),+ releaseJsonPath,+ includeLatestPath: join(output, "latest.json"),+ expectedTag: "v1.2.3",+ }),+ ).toThrow("Remote digest mismatch")+ })++ it("rejects stale desktop candidates after publication", async () => {+ const fixture = await createAllStages()+ const output = join(fixture.directory, "output")+ const { releaseManifest } = await aggregateStages({+ stageRoot: fixture.stages,+ outputDirectory: output,+ version,+ repository: "alookai/alook",+ pubDate: "2026-09-29T00:00:00.000Z",+ configPath: fixture.configPath,+ })+ const releaseJsonPath = join(fixture.directory, "release.json")+ writeFileSync(releaseJsonPath, JSON.stringify({+ tag_name: "v1.2.3",+ draft: false,+ prerelease: false,+ assets: [+ ...releaseManifest.assets.map((asset) => ({ name: asset.name, digest: `sha256:${asset.sha256}` })),+ { name: "other_9.9.9_x64-setup.exe.sig", digest: "sha256:stale" },+ ],+ }))+ expect(() => verifyPublishedAssets({+ releaseManifestPath: join(output, "release-manifest.json"),+ releaseJsonPath,+ expectedTag: "v1.2.3",+ })).toThrow("unexpected desktop asset candidates")+ })++ it("covers every CLI dispatch and fail-closed entrypoint handling", async () => {+ expect(parseDesktopReleaseArgs(["aggregate", "--root", "stages"])).toEqual({ command: "aggregate", root: "stages" })+ expect(() => parseDesktopReleaseArgs(["aggregate", "root"])).toThrow("Invalid argument")++ const directory = mkdtempSync(join(tmpdir(), "alook-release-cli-"))+ temporaryDirectories.push(directory)+ const source = join(directory, "source")+ mkdirSync(source)++ await expect(runDesktopReleaseCli([+ "collect", "--target", "macos-aarch64", "--version", "bad", "--source", source, "--stage", join(directory, "stage"),+ ])).rejects.toThrow("numeric semver")+ await expect(runDesktopReleaseCli([+ "validate", "--stage", join(directory, "missing"), "--target", "macos-aarch64", "--version", version,+ ])).rejects.toThrow()+ await expect(runDesktopReleaseCli([+ "aggregate", "--root", directory, "--output", join(directory, "output"), "--version", version,+ "--repository", "invalid", "--pub-date", "invalid", "--config", join(directory, "config.json"),+ ])).rejects.toThrow("Invalid GitHub repository")+ await expect(runDesktopReleaseCli([+ "verify-published", "--manifest", join(directory, "missing-manifest.json"), "--release", join(directory, "missing-release.json"),+ "--latest", join(directory, "latest.json"), "--tag", "v1.2.3",+ ])).rejects.toThrow()+ await expect(runDesktopReleaseCli([+ "assert-publishable", "--release", join(directory, "missing-release.json"), "--tag", "invalid",+ ])).rejects.toThrow("numeric semver")+ await expect(runDesktopReleaseCli(["unknown"])).rejects.toThrow("Expected collect")++ const entryPath = join(directory, "desktop-release-artifacts.mjs")+ const stderr: string[] = []+ const runtime = {+ stderr: { write: (value: string) => stderr.push(value) },+ exitCode: 0,+ }+ await expect(runDesktopReleaseIfMain(pathToFileURL(entryPath).href, join(directory, "other.mjs"), [], runtime)).resolves.toBe(false)+ await expect(runDesktopReleaseIfMain(pathToFileURL(entryPath).href, entryPath, ["unknown"], runtime)).resolves.toBe(true)+ expect(stderr.join("")).toContain("Expected collect")+ expect(runtime.exitCode).toBe(1)+ })+})diff --git a/scripts/ci/desktop-signing-dependencies.json b/scripts/ci/desktop-signing-dependencies.jsonnew file mode 100644index 000000000..fc15d6332--- /dev/null+++ b/scripts/ci/desktop-signing-dependencies.json@@ -0,0 +1,33 @@+{+ "schemaVersion": 1,+ "packages": [+ {+ "name": "ArtifactSigning",+ "version": "0.1.8",+ "source": "https://www.powershellgallery.com/api/v2/package/ArtifactSigning/0.1.8",+ "sha256": "3221344b8c627915d3870f23e80816f31a5d8c2bae1d7c0cdd6c9652f6c4e089",+ "kind": "module"+ },+ {+ "name": "Microsoft.Windows.SDK.BuildTools",+ "version": "10.0.26100.4188",+ "source": "https://api.nuget.org/v3-flatcontainer/microsoft.windows.sdk.buildtools/10.0.26100.4188/microsoft.windows.sdk.buildtools.10.0.26100.4188.nupkg",+ "sha256": "180deb372659029864c10a0c04787833234d64aacd1d2c0661d2c00295d8e022",+ "kind": "dependency"+ },+ {+ "name": "Microsoft.ArtifactSigning.Client",+ "version": "1.0.128",+ "source": "https://api.nuget.org/v3-flatcontainer/microsoft.artifactsigning.client/1.0.128/microsoft.artifactsigning.client.1.0.128.nupkg",+ "sha256": "74bd7d27e6ce1051409c38d9b46bc8df0400ecd643d51ffbf2ac00869061e40b",+ "kind": "dependency"+ },+ {+ "name": "sign",+ "version": "0.9.1-beta.26227.3",+ "source": "https://api.nuget.org/v3-flatcontainer/sign/0.9.1-beta.26227.3/sign.0.9.1-beta.26227.3.nupkg",+ "sha256": "34fd0d4aeabdbc363a48883881865b4dd65e6c11ba916028082fa23f3e1b1ba1",+ "kind": "dependency"+ }+ ]+}diff --git a/scripts/ci/prepare-desktop-windows-signing.ps1 b/scripts/ci/prepare-desktop-windows-signing.ps1new file mode 100644index 000000000..39af9ff9f--- /dev/null+++ b/scripts/ci/prepare-desktop-windows-signing.ps1@@ -0,0 +1,113 @@+[CmdletBinding()]+param(+ [Parameter()]+ [string]$ManifestPath = (Join-Path $PSScriptRoot "desktop-signing-dependencies.json"),++ [Parameter(Mandatory)]+ [string]$DestinationRoot+)++Set-StrictMode -Version Latest+$ErrorActionPreference = "Stop"++$expectedPackages = @{+ "ArtifactSigning" = "0.1.8"+ "Microsoft.Windows.SDK.BuildTools" = "10.0.26100.4188"+ "Microsoft.ArtifactSigning.Client" = "1.0.128"+ "sign" = "0.9.1-beta.26227.3"+}++$manifest = Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json+if ($manifest.schemaVersion -ne 1) {+ throw "Unsupported signing dependency manifest schema: $($manifest.schemaVersion)"+}+if ($manifest.packages.Count -ne $expectedPackages.Count) {+ throw "Signing dependency manifest must contain exactly $($expectedPackages.Count) packages"+}++$seen = @{}+foreach ($package in $manifest.packages) {+ if (-not $expectedPackages.ContainsKey($package.name)) {+ throw "Unexpected signing dependency: $($package.name)"+ }+ if ($seen.ContainsKey($package.name)) {+ throw "Duplicate signing dependency: $($package.name)"+ }+ $seen[$package.name] = $true+ if ($package.version -ne $expectedPackages[$package.name]) {+ throw "Unexpected version for $($package.name): $($package.version)"+ }+ if ($package.source -notmatch '^https://(www\.powershellgallery\.com|api\.nuget\.org)/') {+ throw "Unapproved package source for $($package.name)"+ }+ if ($package.sha256 -notmatch '^[0-9a-f]{64}$') {+ throw "Invalid SHA-256 for $($package.name)"+ }+}++$destination = [IO.Path]::GetFullPath($DestinationRoot)+if (Test-Path -LiteralPath $destination) {+ throw "Signing dependency destination must be fresh: $destination"+}++$packagesRoot = Join-Path $destination "packages"+$moduleRoot = Join-Path $destination "modules\ArtifactSigning\0.1.8"+$localAppData = Join-Path $destination "localappdata"+New-Item -Path $packagesRoot -ItemType Directory | Out-Null+New-Item -Path $moduleRoot -ItemType Directory | Out-Null+New-Item -Path $localAppData -ItemType Directory | Out-Null++Add-Type -AssemblyName System.IO.Compression.FileSystem++foreach ($package in $manifest.packages) {+ $archive = Join-Path $packagesRoot "$($package.name).$($package.version).nupkg"+ & curl.exe --fail --location --silent --show-error `+ --proto '=https' --tlsv1.2 `+ --connect-timeout 15 --max-time 600 `+ --retry 3 --retry-delay 2 --retry-all-errors `+ --output $archive $package.source+ if ($LASTEXITCODE -ne 0) {+ throw "Official package download failed for $($package.name) after bounded retries"+ }++ $actualHash = (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant()+ if ($actualHash -ne $package.sha256) {+ throw "SHA-256 mismatch for $($package.name): expected $($package.sha256), got $actualHash"+ }++ if ($package.kind -eq "module") {+ $extractPath = $moduleRoot+ } else {+ $packageVersionsPath = Join-Path $localAppData "ArtifactSigning\$($package.name)"+ $extractPath = Join-Path $packageVersionsPath "$($package.name).$($package.version)"+ New-Item -Path $packageVersionsPath -ItemType Directory -Force | Out-Null+ }++ [IO.Compression.ZipFile]::ExtractToDirectory($archive, $extractPath)+}++$modulePath = Join-Path $moduleRoot "ArtifactSigning.psd1"+if (-not (Test-Path -LiteralPath $modulePath -PathType Leaf)) {+ throw "ArtifactSigning module was not extracted to the expected path"+}++$requiredContent = @(+ (Join-Path $localAppData "ArtifactSigning\Microsoft.Windows.SDK.BuildTools\Microsoft.Windows.SDK.BuildTools.10.0.26100.4188\bin\10.0.26100.0\x64\signtool.exe"),+ (Join-Path $localAppData "ArtifactSigning\Microsoft.ArtifactSigning.Client\Microsoft.ArtifactSigning.Client.1.0.128\bin\x64\Azure.CodeSigning.Dlib.dll"),+ (Join-Path $localAppData "ArtifactSigning\sign\sign.0.9.1-beta.26227.3\tools\net8.0\any\sign.dll")+)+foreach ($requiredPath in $requiredContent) {+ if (-not (Test-Path -LiteralPath $requiredPath -PathType Leaf)) {+ throw "Signing dependency is missing expected content: $requiredPath"+ }+}++if (-not $env:GITHUB_ENV) {+ throw "GITHUB_ENV is required so Tauri's child signing commands inherit the verified paths"+}++"LOCALAPPDATA=$localAppData" | Out-File -LiteralPath $env:GITHUB_ENV -Append -Encoding utf8+"ALOOK_ARTIFACT_SIGNING_MODULE_PATH=$modulePath" | Out-File -LiteralPath $env:GITHUB_ENV -Append -Encoding utf8+"PSModulePath=$(Split-Path $moduleRoot -Parent);$env:PSModulePath" | Out-File -LiteralPath $env:GITHUB_ENV -Append -Encoding utf8++Write-Host "Prepared four digest-verified signing packages in a fresh runner-temporary directory."diff --git a/scripts/ci/sign-desktop-windows.ps1 b/scripts/ci/sign-desktop-windows.ps1new file mode 100644index 000000000..f76075c1d--- /dev/null+++ b/scripts/ci/sign-desktop-windows.ps1@@ -0,0 +1,92 @@+[CmdletBinding()]+param(+ [Parameter(Mandatory, Position = 0)]+ [string]$FilePath+)++Set-StrictMode -Version Latest+$ErrorActionPreference = "Stop"++$requiredEnvironment = @(+ "ALOOK_WINDOWS_SIGNING_ROOT",+ "ALOOK_ARTIFACT_SIGNING_MODULE_PATH",+ "ALOOK_ARTIFACT_SIGNING_ENDPOINT",+ "ALOOK_ARTIFACT_SIGNING_ACCOUNT_NAME",+ "ALOOK_ARTIFACT_SIGNING_CERTIFICATE_PROFILE_NAME"+)+foreach ($name in $requiredEnvironment) {+ $value = [Environment]::GetEnvironmentVariable($name)+ if ([string]::IsNullOrWhiteSpace($value)) {+ throw "Required signing environment variable is missing: $name"+ }+}++[Uri]$endpoint = $null+if (-not [Uri]::TryCreate($env:ALOOK_ARTIFACT_SIGNING_ENDPOINT, [UriKind]::Absolute, [ref]$endpoint) -or+ $endpoint.Scheme -ne [Uri]::UriSchemeHttps -or+ $endpoint.DnsSafeHost -notmatch '^[a-z0-9-]+\.codesigning\.azure\.net$' -or+ -not $endpoint.IsDefaultPort -or+ $endpoint.AbsolutePath -ne '/' -or+ $endpoint.UserInfo -ne '' -or+ $endpoint.Query -ne '' -or+ $endpoint.Fragment -ne '') {+ throw "Artifact Signing endpoint must be an HTTPS regional codesigning.azure.net root URL"+}++$root = (Resolve-Path -LiteralPath $env:ALOOK_WINDOWS_SIGNING_ROOT).Path.TrimEnd('\', '/')+$resolved = (Resolve-Path -LiteralPath $FilePath).Path+$item = Get-Item -LiteralPath $resolved+if (-not $item.PSIsContainer -and $item.LinkType -eq $null) {+ $relative = [IO.Path]::GetRelativePath($root, $resolved)+} else {+ throw "Tauri signCommand accepts exactly one regular file"+}++if ([IO.Path]::IsPathRooted($relative) -or $relative -eq ".." -or $relative.StartsWith("..$([IO.Path]::DirectorySeparatorChar)")) {+ throw "Refusing to sign a path outside the expected Tauri release root: $resolved"+}++$normalized = $relative.Replace('/', '\')+# NSIS !uninstfinalize writes the generated uninstaller beneath %TEMP%\~nsu.tmp.+$allowed = @(+ '^alook-desktop\.exe$',+ '^bundle\\msi\\Alook_[0-9]+\.[0-9]+\.[0-9]+_x64_en-US\.msi$',+ '^bundle\\nsis\\Alook_[0-9]+\.[0-9]+\.[0-9]+_x64-setup\.exe$',+ '^wix\\x64\\wix\\Wix(?:UI|Util)Extension\.dll$',+ '^nsis\\x64\\Plugins\\x86-unicode\\(?:NSISdl|StartMenu|System|nsDialogs)\.dll$',+ '^nsis\\x64\\Plugins\\x86-unicode\\additional\\nsis_tauri_utils\.dll$',+ '^tauri-sign-temp\\~nsu\.tmp\\Un_[A-Za-z0-9]+\.exe$'+)+if (-not ($allowed | Where-Object { $normalized -match $_ })) {+ throw "Refusing unexpected Tauri signing path: $relative"+}++$modulePath = (Resolve-Path -LiteralPath $env:ALOOK_ARTIFACT_SIGNING_MODULE_PATH).Path+Import-Module $modulePath -Force++$signingParameters = @{+ Endpoint = $env:ALOOK_ARTIFACT_SIGNING_ENDPOINT+ CodeSigningAccountName = $env:ALOOK_ARTIFACT_SIGNING_ACCOUNT_NAME+ CertificateProfileName = $env:ALOOK_ARTIFACT_SIGNING_CERTIFICATE_PROFILE_NAME+ Files = $resolved+ FileDigest = "SHA256"+ TimestampRfc3161 = "http://timestamp.acs.microsoft.com"+ TimestampDigest = "SHA256"+ ExcludeEnvironmentCredential = $true+ ExcludeWorkloadIdentityCredential = $true+ ExcludeManagedIdentityCredential = $true+ ExcludeSharedTokenCacheCredential = $true+ ExcludeVisualStudioCredential = $true+ ExcludeVisualStudioCodeCredential = $true+ ExcludeAzureCliCredential = $false+ ExcludeAzurePowerShellCredential = $true+ ExcludeAzureDeveloperCliCredential = $true+ ExcludeInteractiveBrowserCredential = $true+}++Invoke-ArtifactSigning @signingParameters++$signature = Get-AuthenticodeSignature -LiteralPath $resolved+if ($signature.Status -ne [System.Management.Automation.SignatureStatus]::Valid) {+ throw "Artifact Signing returned without a valid Authenticode signature: $relative ($($signature.Status))"+}diff --git a/scripts/ci/verify-desktop-macos.sh b/scripts/ci/verify-desktop-macos.shnew file mode 100644index 000000000..3f0756dec--- /dev/null+++ b/scripts/ci/verify-desktop-macos.sh@@ -0,0 +1,108 @@+#!/usr/bin/env bash+set -euo pipefail++: "${STAGE_DIR:?STAGE_DIR is required}"+: "${EXPECTED_TARGET:?EXPECTED_TARGET is required}"+: "${EXPECTED_VERSION:?EXPECTED_VERSION is required}"+: "${EXPECTED_TEAM_ID:?EXPECTED_TEAM_ID is required}"+: "${EXPECTED_SIGNING_IDENTITY:?EXPECTED_SIGNING_IDENTITY is required}"++case "$EXPECTED_TARGET" in+ aarch64-apple-darwin)+ stage_target="macos-aarch64"+ release_arch="aarch64"+ binary_arch="arm64"+ ;;+ x86_64-apple-darwin)+ stage_target="macos-x86_64"+ release_arch="x64"+ binary_arch="x86_64"+ ;;+ *)+ echo "Unsupported macOS target: $EXPECTED_TARGET" >&2+ exit 1+ ;;+esac++repository_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)+stage_dir=$(cd "$STAGE_DIR" && pwd)+dmg="$stage_dir/files/Alook_${EXPECTED_VERSION}_${release_arch}.dmg"+archive="$stage_dir/files/Alook_${EXPECTED_VERSION}_${release_arch}.app.tar.gz"+archive_signature="${archive}.sig"++node "$repository_root/scripts/ci/desktop-release-artifacts.mjs" validate \+ --target "$stage_target" --version "$EXPECTED_VERSION" --stage "$stage_dir"+node "$repository_root/scripts/ci/verify-minisign.mjs" \+ --file "$archive" --signature "$archive_signature" \+ --config "$repository_root/src/desktop/src-tauri/tauri.conf.json" \+ --version "$EXPECTED_VERSION" --trusted-file "Alook.app.tar.gz"++work_dir=$(mktemp -d "$RUNNER_TEMP/alook-macos-verify.XXXXXX")+mount_dir="$work_dir/dmg"+archive_dir="$work_dir/archive"+mkdir "$mount_dir" "$archive_dir"+mounted=0+cleanup() {+ if [[ "$mounted" == 1 ]]; then hdiutil detach "$mount_dir" -quiet || true; fi+ rm -rf "$work_dir"+}+trap cleanup EXIT++assert_app() {+ local app_path=$1+ local label=$2+ local signature entitlements executable architectures version identifier++ codesign --verify --deep --strict --verbose=2 "$app_path"+ signature=$(codesign -dvvv "$app_path" 2>&1)+ grep -Fq "Identifier=ai.alook.desktop" <<<"$signature"+ grep -Fq "TeamIdentifier=${EXPECTED_TEAM_ID}" <<<"$signature"+ grep -Fq "Authority=${EXPECTED_SIGNING_IDENTITY}" <<<"$signature"+ grep -Eq 'flags=.*runtime' <<<"$signature"+ grep -Eq '^Timestamp=.+$' <<<"$signature"+ if grep -Eq '^Timestamp=(none|)$' <<<"$signature"; then+ echo "$label is missing a secure timestamp" >&2+ return 1+ fi++ entitlements="$work_dir/${label}.entitlements.plist"+ codesign -d --entitlements :- "$app_path" >"$entitlements" 2>/dev/null+ if value=$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.get-task-allow' "$entitlements" 2>/dev/null); then+ [[ "$value" != "true" ]] || { echo "$label enables get-task-allow" >&2; return 1; }+ fi++ version=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$app_path/Contents/Info.plist")+ identifier=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app_path/Contents/Info.plist")+ [[ "$version" == "$EXPECTED_VERSION" ]]+ [[ "$identifier" == "ai.alook.desktop" ]]++ executable=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$app_path/Contents/Info.plist")+ architectures=$(lipo -archs "$app_path/Contents/MacOS/$executable")+ [[ "$architectures" == "$binary_arch" ]] || { echo "$label has unexpected architecture: $architectures" >&2; return 1; }++ xcrun stapler validate "$app_path"+ spctl --assess --type execute --verbose=4 "$app_path"+}++xcrun stapler validate "$dmg"+spctl --assess --type open --context context:primary-signature --verbose=4 "$dmg"+hdiutil attach "$dmg" -nobrowse -readonly -mountpoint "$mount_dir" -quiet+mounted=1+dmg_apps=("$mount_dir"/*.app)+[[ ${#dmg_apps[@]} -eq 1 && -d "${dmg_apps[0]}" ]] || { echo "DMG must contain exactly one top-level app" >&2; exit 1; }+assert_app "${dmg_apps[0]}" "dmg-app"+hdiutil detach "$mount_dir" -quiet+mounted=0++while IFS= read -r member; do+ [[ "$member" != /* && "$member" != ".." && "$member" != ../* && "$member" != */../* ]] || {+ echo "Updater archive contains an unsafe path: $member" >&2+ exit 1+ }+done < <(tar -tzf "$archive")+tar -xzf "$archive" -C "$archive_dir"+archive_apps=("$archive_dir"/*.app)+[[ ${#archive_apps[@]} -eq 1 && -d "${archive_apps[0]}" ]] || { echo "Updater archive must contain exactly one top-level app" >&2; exit 1; }+assert_app "${archive_apps[0]}" "updater-app"++echo "Verified staged macOS DMG and updater app for $EXPECTED_TARGET."diff --git a/scripts/ci/verify-desktop-windows.ps1 b/scripts/ci/verify-desktop-windows.ps1new file mode 100644index 000000000..73d5f2ded--- /dev/null+++ b/scripts/ci/verify-desktop-windows.ps1@@ -0,0 +1,91 @@+[CmdletBinding()]+param(+ [Parameter(Mandatory)]+ [string]$StageDirectory,++ [Parameter(Mandatory)]+ [string]$ExpectedVersion,++ [Parameter(Mandatory)]+ [string]$ExpectedPublisher,++ [Parameter(Mandatory)]+ [string]$TauriConfigPath+)++Set-StrictMode -Version Latest+$ErrorActionPreference = "Stop"++$repositoryRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\.."))+$stage = (Resolve-Path -LiteralPath $StageDirectory).Path++& node (Join-Path $repositoryRoot "scripts\ci\desktop-release-artifacts.mjs") validate `+ --target "windows-x86_64" --version $ExpectedVersion --stage $stage+if ($LASTEXITCODE -ne 0) { throw "Windows staged artifact manifest validation failed" }++$msi = Join-Path $stage "files\Alook_${ExpectedVersion}_x64_en-US.msi"+$nsis = Join-Path $stage "files\Alook_${ExpectedVersion}_x64-setup.exe"++function Assert-Authenticode {+ param(+ [Parameter(Mandatory)]+ [string]$Path,++ [Parameter(Mandatory)]+ [string]$Label+ )++ $output = & signtool.exe verify /pa /all /v $Path 2>&1 | Out-String+ if ($LASTEXITCODE -ne 0) { throw "signtool rejected $Label`n$output" }+ if ($output -notmatch '(?im)^Hash of file \(sha256\): [0-9a-f]+$') { throw "$Label does not use a SHA-256 Authenticode file digest" }+ if ($output -notmatch '(?im)^The signature is timestamped:') { throw "$Label is missing a verified timestamp" }+ if ($output -notmatch '(?im)^Timestamp Verified by:') { throw "$Label is missing a timestamp certificate chain" }+ if (($output | Select-String -Pattern '(?im)^Signing Certificate Chain:' -AllMatches).Matches.Count -ne 1) {+ throw "$Label must contain exactly one Authenticode signature"+ }++ $signature = Get-AuthenticodeSignature -LiteralPath $Path+ if ($signature.Status -ne [System.Management.Automation.SignatureStatus]::Valid) {+ throw "$Label Authenticode status is $($signature.Status)"+ }+ if ($signature.SignerCertificate.Subject -ne $ExpectedPublisher) {+ throw "$Label publisher mismatch: $($signature.SignerCertificate.Subject)"+ }+ if ($null -eq $signature.TimeStamperCertificate) { throw "$Label has no timestamp certificate" }+}++function Assert-EmbeddedMainExecutable {+ param(+ [Parameter(Mandatory)]+ [string]$Installer,++ [Parameter(Mandatory)]+ [string]$Label+ )++ $extractRoot = Join-Path $env:RUNNER_TEMP "alook-$Label-$([Guid]::NewGuid().ToString('N'))"+ New-Item -Path $extractRoot -ItemType Directory | Out-Null+ try {+ & 7z.exe x -y "-o$extractRoot" $Installer | Out-Null+ if ($LASTEXITCODE -ne 0) { throw "7-Zip could not extract $Label" }+ $executables = @(Get-ChildItem -LiteralPath $extractRoot -Recurse -File -Filter "alook-desktop.exe")+ if ($executables.Count -ne 1) { throw "$Label must contain exactly one alook-desktop.exe" }+ Assert-Authenticode -Path $executables[0].FullName -Label "$Label embedded main executable"+ } finally {+ Remove-Item -LiteralPath $extractRoot -Recurse -Force -ErrorAction SilentlyContinue+ }+}++foreach ($installer in @($msi, $nsis)) {+ $signaturePath = "$installer.sig"+ & node (Join-Path $repositoryRoot "scripts\ci\verify-minisign.mjs") `+ --file $installer --signature $signaturePath --config $TauriConfigPath `+ --version $ExpectedVersion --trusted-file ([IO.Path]::GetFileName($installer))+ if ($LASTEXITCODE -ne 0) { throw "Minisign verification failed for $installer" }+ Assert-Authenticode -Path $installer -Label ([IO.Path]::GetFileName($installer))+}++Assert-EmbeddedMainExecutable -Installer $msi -Label "msi"+Assert-EmbeddedMainExecutable -Installer $nsis -Label "nsis"++Write-Host "Verified staged Windows installers, embedded main executables, and exact-byte updater signatures."diff --git a/scripts/ci/verify-minisign.mjs b/scripts/ci/verify-minisign.mjsnew file mode 100644index 000000000..fa5bc4d1b--- /dev/null+++ b/scripts/ci/verify-minisign.mjs@@ -0,0 +1,160 @@+import { createHash, createPublicKey, verify } from "node:crypto"+import { createReadStream, lstatSync, readFileSync } from "node:fs"+import { pathToFileURL } from "node:url"++const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex")++export function parseArgs(argv) {+ const args = {}+ for (let index = 0; index < argv.length; index += 2) {+ const key = argv[index]+ const value = argv[index + 1]+ if (!key?.startsWith("--") || value == null) throw new Error(`Invalid argument: ${key ?? "<missing>"}`)+ args[key.slice(2)] = value+ }+ return args+}++function decodeBase64(value, label) {+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value)) throw new Error(`${label} is not canonical base64`)+ const decoded = Buffer.from(value, "base64")+ if (decoded.toString("base64") !== value) throw new Error(`${label} is not canonical base64`)+ return decoded+}++export function parseTauriPublicKey(encodedPublicKey) {+ const publicKeyFile = decodeBase64(encodedPublicKey, "Tauri updater public key").toString("utf8")+ const lines = publicKeyFile.trimEnd().split(/\r?\n/)+ if (lines.length !== 2 || !lines[0].startsWith("untrusted comment: ")) {+ throw new Error("Tauri updater public key must contain one comment and one key line")+ }++ const packet = decodeBase64(lines[1], "Minisign public key")+ if (packet.length !== 42) throw new Error("Minisign public key packet must be 42 bytes")+ const algorithm = packet.subarray(0, 2).toString("ascii")+ if (algorithm !== "Ed" && algorithm !== "ED") throw new Error(`Unsupported Minisign key algorithm: ${algorithm}`)++ return {+ keyId: packet.subarray(2, 10),+ publicKey: createPublicKey({+ key: Buffer.concat([ED25519_SPKI_PREFIX, packet.subarray(10)]),+ format: "der",+ type: "spki",+ }),+ }+}++export function parseMinisignSignature(contents) {+ const encodedSignature = contents.trimEnd()+ if (encodedSignature.includes("\n") || encodedSignature.includes("\r")) {+ throw new Error("Tauri updater signature must be one canonical base64 line")+ }+ const signatureBox = decodeBase64(encodedSignature, "Tauri updater signature").toString("utf8")+ const lines = signatureBox.trimEnd().split(/\r?\n/)+ if (lines.length !== 4 || !lines[0].startsWith("untrusted comment: ") || !lines[2].startsWith("trusted comment: ")) {+ throw new Error("Minisign signature must contain exactly four canonical lines")+ }++ const packet = decodeBase64(lines[1], "Minisign signature")+ const globalSignature = decodeBase64(lines[3], "Minisign global signature")+ if (packet.length !== 74 || globalSignature.length !== 64) throw new Error("Invalid Minisign signature packet length")+ if (packet.subarray(0, 2).toString("ascii") !== "ED") {+ throw new Error("Legacy non-prehashed Minisign signatures are not accepted")+ }++ const trustedComment = lines[2].slice("trusted comment: ".length)+ const trustedFields = /^timestamp:([0-9]+)\tfile:([^\t\r\n]+)\tversion:([^\t\r\n]+)$/.exec(trustedComment)+ if (!trustedFields || trustedFields[1] === "0") {+ throw new Error("Minisign trusted comment must bind a timestamp, file, and version")+ }++ return {+ keyId: packet.subarray(2, 10),+ signature: packet.subarray(10),+ trustedComment,+ trustedFile: trustedFields[2],+ version: trustedFields[3],+ globalSignature,+ }+}++async function blake2b512(path) {+ const hash = createHash("blake2b512")+ for await (const chunk of createReadStream(path)) hash.update(chunk)+ return hash.digest()+}++export async function verifyMinisignFile({+ filePath,+ signaturePath,+ encodedPublicKey,+ expectedVersion,+ expectedTrustedFile,+}) {+ for (const path of [filePath, signaturePath]) {+ const stat = lstatSync(path)+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Minisign input must be a regular file: ${path}`)+ }++ const publicKey = parseTauriPublicKey(encodedPublicKey)+ const signature = parseMinisignSignature(readFileSync(signaturePath, "utf8"))+ if (!publicKey.keyId.equals(signature.keyId)) throw new Error("Minisign signature key id does not match the updater public key")+ if (expectedVersion && signature.version !== expectedVersion) {+ throw new Error(`Minisign trusted version mismatch: expected ${expectedVersion}, got ${signature.version}`)+ }+ if (expectedTrustedFile && signature.trustedFile !== expectedTrustedFile) {+ throw new Error(`Minisign trusted file mismatch: expected ${expectedTrustedFile}, got ${signature.trustedFile}`)+ }++ const digest = await blake2b512(filePath)+ if (!verify(null, digest, publicKey.publicKey, signature.signature)) {+ throw new Error(`Invalid Minisign file signature: ${filePath}`)+ }++ const globalPayload = Buffer.concat([signature.signature, Buffer.from(signature.trustedComment, "utf8")])+ if (!verify(null, globalPayload, publicKey.publicKey, signature.globalSignature)) {+ throw new Error(`Invalid Minisign trusted-comment signature: ${signaturePath}`)+ }+}++export function readUpdaterPublicKey(configPath) {+ const config = JSON.parse(readFileSync(configPath, "utf8"))+ const key = config?.plugins?.updater?.pubkey+ if (typeof key !== "string" || key.length === 0) throw new Error("Tauri updater public key is missing from config")+ return key+}++export async function main(argv = process.argv.slice(2), stdout = process.stdout) {+ const args = parseArgs(argv)+ if (!args.file || !args.signature || !args.config || !args.version || !args["trusted-file"]) {+ throw new Error(+ "Usage: verify-minisign.mjs --file <path> --signature <path> --config <tauri.conf.json> --version <version> --trusted-file <name>",+ )+ }+ await verifyMinisignFile({+ filePath: args.file,+ signaturePath: args.signature,+ encodedPublicKey: readUpdaterPublicKey(args.config),+ expectedVersion: args.version,+ expectedTrustedFile: args["trusted-file"],+ })+ stdout.write(`Verified Minisign signature for ${args.file}\n`)+}++export async function runIfMain(+ metaUrl,+ argvPath = process.argv[1],+ argv = process.argv.slice(2),+ runtime = process,+) {+ if (!argvPath || pathToFileURL(argvPath).href !== metaUrl) return false+ try {+ await main(argv, runtime.stdout)+ } catch (error) {+ runtime.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)+ runtime.exitCode = 1+ }+ return true+}++void runIfMain(import.meta.url)diff --git a/scripts/ci/verify-minisign.test.ts b/scripts/ci/verify-minisign.test.tsnew file mode 100644index 000000000..353fab770--- /dev/null+++ b/scripts/ci/verify-minisign.test.ts@@ -0,0 +1,180 @@+import { createHash, generateKeyPairSync, randomBytes, sign } from "node:crypto"+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import { join } from "node:path"+import { pathToFileURL } from "node:url"+import { afterEach, describe, expect, it } from "vitest"++import {+ main as runMinisignCli,+ parseArgs as parseMinisignArgs,+ parseMinisignSignature,+ parseTauriPublicKey,+ readUpdaterPublicKey,+ runIfMain as runMinisignIfMain,+ verifyMinisignFile,+} from "./verify-minisign.mjs"++const temporaryDirectories: string[] = []++function fixture(data: Buffer) {+ const directory = mkdtempSync(join(tmpdir(), "alook-minisign-"))+ temporaryDirectories.push(directory)+ const filePath = join(directory, "artifact.bin")+ const signaturePath = `${filePath}.sig`+ writeFileSync(filePath, data)++ const { privateKey, publicKey } = generateKeyPairSync("ed25519")+ const publicDer = publicKey.export({ format: "der", type: "spki" })+ const keyId = randomBytes(8)+ const publicPacket = Buffer.concat([Buffer.from("ED"), keyId, publicDer.subarray(-32)])+ const publicFile = `untrusted comment: fixture key\n${publicPacket.toString("base64")}\n`+ const encodedPublicKey = Buffer.from(publicFile).toString("base64")++ const digest = createHash("blake2b512").update(data).digest()+ const fileSignature = sign(null, digest, privateKey)+ const trustedComment = "timestamp:1\tfile:artifact.bin\tversion:1.2.3"+ const globalSignature = sign(null, Buffer.concat([fileSignature, Buffer.from(trustedComment)]), privateKey)+ const signaturePacket = Buffer.concat([Buffer.from("ED"), keyId, fileSignature])+ const signatureBox = `untrusted comment: fixture signature\n${signaturePacket.toString("base64")}\ntrusted comment: ${trustedComment}\n${globalSignature.toString("base64")}\n`+ writeFileSync(signaturePath, Buffer.from(signatureBox).toString("base64"))++ return { directory, encodedPublicKey, filePath, signaturePath }+}++afterEach(() => {+ for (const directory of temporaryDirectories.splice(0)) rmSync(directory, { force: true, recursive: true })+})++describe("verifyMinisignFile", () => {+ it("verifies the prehashed file signature and trusted comment", async () => {+ const files = fixture(Buffer.from("exact release bytes"))+ await expect(+ verifyMinisignFile({ ...files, expectedVersion: "1.2.3", expectedTrustedFile: "artifact.bin" }),+ ).resolves.toBeUndefined()+ })++ it("rejects mutated artifact bytes", async () => {+ const files = fixture(Buffer.from("exact release bytes"))+ writeFileSync(files.filePath, "mutated release bytes")+ await expect(+ verifyMinisignFile({ ...files, expectedVersion: "1.2.3", expectedTrustedFile: "artifact.bin" }),+ ).rejects.toThrow("Invalid Minisign file signature")+ })++ it("rejects a forged trusted comment", async () => {+ const files = fixture(Buffer.from("exact release bytes"))+ const signature = Buffer.from(readFileSync(files.signaturePath, "utf8"), "base64")+ .toString("utf8")+ .replace("timestamp:1", "timestamp:2")+ writeFileSync(files.signaturePath, Buffer.from(signature).toString("base64"))+ await expect(+ verifyMinisignFile({ ...files, expectedVersion: "1.2.3", expectedTrustedFile: "artifact.bin" }),+ ).rejects.toThrow("trusted-comment")+ })++ it("rejects trusted version and filename drift", async () => {+ const files = fixture(Buffer.from("exact release bytes"))+ await expect(+ verifyMinisignFile({ ...files, expectedVersion: "9.9.9", expectedTrustedFile: "artifact.bin" }),+ ).rejects.toThrow("trusted version mismatch")+ await expect(+ verifyMinisignFile({ ...files, expectedVersion: "1.2.3", expectedTrustedFile: "renamed.bin" }),+ ).rejects.toThrow("trusted file mismatch")+ })++ it("rejects malformed and legacy packets", () => {+ const files = fixture(Buffer.from("exact release bytes"))+ expect(() => parseTauriPublicKey(`${files.encodedPublicKey}=`)).toThrow("canonical base64")++ const malformedPublicFile = Buffer.from("not a Minisign key\n").toString("base64")+ expect(() => parseTauriPublicKey(malformedPublicFile)).toThrow("one comment and one key line")++ const shortPublicPacket = Buffer.alloc(41).toString("base64")+ expect(() => parseTauriPublicKey(Buffer.from(`untrusted comment: short\n${shortPublicPacket}\n`).toString("base64"))).toThrow("42 bytes")++ const unsupportedPublicPacket = Buffer.concat([Buffer.from("XX"), Buffer.alloc(40)]).toString("base64")+ expect(() => parseTauriPublicKey(Buffer.from(`untrusted comment: unsupported\n${unsupportedPublicPacket}\n`).toString("base64"))).toThrow("Unsupported Minisign key algorithm")++ expect(() => parseMinisignSignature("YQ==\nYg==")).toThrow("one canonical base64 line")+ expect(() => parseMinisignSignature(Buffer.from("not four lines\n").toString("base64"))).toThrow("exactly four canonical lines")++ const lines = Buffer.from(readFileSync(files.signaturePath, "utf8"), "base64").toString("utf8").trimEnd().split("\n")+ const shortPacket = [...lines]+ shortPacket[1] = Buffer.alloc(10).toString("base64")+ expect(() => parseMinisignSignature(Buffer.from(`${shortPacket.join("\n")}\n`).toString("base64"))).toThrow("packet length")++ const missingTrustedBinding = [...lines]+ missingTrustedBinding[2] = missingTrustedBinding[2].replace("timestamp:1", "timestamp:0")+ expect(() => parseMinisignSignature(Buffer.from(`${missingTrustedBinding.join("\n")}\n`).toString("base64"))).toThrow("must bind")++ const packet = Buffer.from(lines[1], "base64")+ packet[1] = 0x64+ lines[1] = packet.toString("base64")+ expect(() => parseMinisignSignature(Buffer.from(`${lines.join("\n")}\n`).toString("base64"))).toThrow("Legacy")+ })++ it("rejects noncanonical base64, non-files, mismatched keys, and missing config keys", async () => {+ const files = fixture(Buffer.from("exact release bytes"))+ expect(() => parseTauriPublicKey("ZE==")).toThrow("canonical base64")++ const directoryInput = join(files.directory, "directory-input")+ mkdirSync(directoryInput)+ await expect(verifyMinisignFile({+ ...files,+ filePath: directoryInput,+ expectedVersion: "1.2.3",+ expectedTrustedFile: "artifact.bin",+ })).rejects.toThrow("regular file")++ const signatureLines = Buffer.from(readFileSync(files.signaturePath, "utf8"), "base64").toString("utf8").trimEnd().split("\n")+ const signaturePacket = Buffer.from(signatureLines[1], "base64")+ signaturePacket[2] ^= 0xff+ signatureLines[1] = signaturePacket.toString("base64")+ writeFileSync(files.signaturePath, Buffer.from(`${signatureLines.join("\n")}\n`).toString("base64"))+ await expect(verifyMinisignFile({+ ...files,+ expectedVersion: "1.2.3",+ expectedTrustedFile: "artifact.bin",+ })).rejects.toThrow("key id does not match")++ const configPath = join(files.directory, "tauri.conf.json")+ writeFileSync(configPath, JSON.stringify({ plugins: { updater: {} } }))+ expect(() => readUpdaterPublicKey(configPath)).toThrow("public key is missing")+ })++ it("covers CLI parsing, success output, usage errors, and entrypoint failures", async () => {+ expect(parseMinisignArgs(["--file", "artifact", "--signature", "signature"])).toEqual({+ file: "artifact",+ signature: "signature",+ })+ expect(() => parseMinisignArgs(["file", "artifact"])).toThrow("Invalid argument")++ await expect(runMinisignCli([])).rejects.toThrow("Usage")++ const files = fixture(Buffer.from("exact release bytes"))+ const configPath = join(files.directory, "tauri.conf.json")+ writeFileSync(configPath, JSON.stringify({ plugins: { updater: { pubkey: files.encodedPublicKey } } }))+ const stdout: string[] = []+ await expect(runMinisignCli([+ "--file", files.filePath,+ "--signature", files.signaturePath,+ "--config", configPath,+ "--version", "1.2.3",+ "--trusted-file", "artifact.bin",+ ], { write: (value: string) => stdout.push(value) })).resolves.toBeUndefined()+ expect(stdout.join("")).toContain("Verified Minisign signature")++ const entryPath = join(files.directory, "verify-minisign.mjs")+ const stderr: string[] = []+ const runtime = {+ stdout: { write: (value: string) => stdout.push(value) },+ stderr: { write: (value: string) => stderr.push(value) },+ exitCode: 0,+ }+ await expect(runMinisignIfMain(pathToFileURL(entryPath).href, join(files.directory, "other.mjs"), [], runtime)).resolves.toBe(false)+ await expect(runMinisignIfMain(pathToFileURL(entryPath).href, entryPath, [], runtime)).resolves.toBe(true)+ expect(stderr.join("")).toContain("Usage")+ expect(runtime.exitCode).toBe(1)+ })+})diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.tsindex 7dd8c715d..d4211626b 100644--- a/scripts/ci/workflow-contract.test.ts+++ b/scripts/ci/workflow-contract.test.ts@@ -65,6 +65,35 @@ const autoTagReleaseWorkflow = normalizeWorkflow(readFileSync(resolve(workflowRoot, "auto-tag-release.yml"), "utf8"),)const desktopReleaseWorkflow = normalizeWorkflow(readFileSync(resolve(workflowRoot, "desktop-release.yml"), "utf8"))+const desktopReleaseArtifacts = readFileSync(+ resolve(repositoryRoot, "scripts/ci/desktop-release-artifacts.mjs"),+ "utf8",+)+const desktopMacVerifier = readFileSync(+ resolve(repositoryRoot, "scripts/ci/verify-desktop-macos.sh"),+ "utf8",+)+const desktopWindowsVerifier = readFileSync(+ resolve(repositoryRoot, "scripts/ci/verify-desktop-windows.ps1"),+ "utf8",+)+const desktopWindowsSigner = readFileSync(+ resolve(repositoryRoot, "scripts/ci/sign-desktop-windows.ps1"),+ "utf8",+)+const desktopWindowsSigningSetup = readFileSync(+ resolve(repositoryRoot, "scripts/ci/prepare-desktop-windows-signing.ps1"),+ "utf8",+)+const desktopWindowsSigningConfig = JSON.parse(+ readFileSync(+ resolve(repositoryRoot, "src/desktop/src-tauri/tauri.windows.signing.conf.json"),+ "utf8",+ ),+) as { bundle: { windows: { signCommand: { cmd: string; args: string[] } } } }+const desktopSigningDependencies = JSON.parse(+ readFileSync(resolve(repositoryRoot, "scripts/ci/desktop-signing-dependencies.json"), "utf8"),+) as { schemaVersion: number; packages: Array<{ name: string; version: string; source: string; sha256: string }> }const mobileReleaseWorkflowPath = resolve(workflowRoot, "mobile-release.yml")const mobileReleaseWorkflow = normalizeWorkflow(readFileSync(mobileReleaseWorkflowPath, "utf8"))const desktopConfig = JSON.parse(@@ -1079,28 +1108,72 @@ describe("Desktop window contract", () => {})describe("Desktop updater release", () => {- it("uploads assets without replacing the auto-tag title or changelog", () => {+ it("keeps every build private until one publisher revalidates all four stages", () => {expect(autoTagReleaseWorkflow).toContain('--title "$TAG"')+ expect(desktopReleaseWorkflow.match(/contents: write/g)).toHaveLength(1)+ expect(desktopReleaseWorkflow.match(/id-token: write/g)).toHaveLength(1)+ expect(desktopReleaseWorkflow).toContain("group: desktop-release-${{ github.ref }}")+ expect(desktopReleaseWorkflow).toContain("cancel-in-progress: false")+ expect(desktopReleaseWorkflow).toContain("needs: [build-unix, build-windows]")+ expect(desktopReleaseWorkflow).toContain(+ "actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7",+ )+ expect(desktopReleaseWorkflow).toContain(+ "actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8",+ )+ expect(desktopReleaseWorkflow).toContain("pattern: desktop-release-*")+ expect(desktopReleaseWorkflow).toContain("merge-multiple: false")+ expect(desktopReleaseWorkflow).toContain("desktop-release-artifacts.mjs aggregate")+ expect(desktopReleaseWorkflow).toContain("desktop-release-artifacts.mjs verify-published")+ expect(desktopReleaseWorkflow).toContain("desktop-release-artifacts.mjs assert-publishable")expect(desktopReleaseWorkflow).toContain("for attempt in {1..30}")- expect(desktopReleaseWorkflow).toContain('releases/tags/${TAG}')- expect(desktopReleaseWorkflow).toContain('releaseId: ${{ steps.release.outputs.id }}')+ expect(desktopReleaseWorkflow).toContain('releases/tags/$TAG')+ expect(desktopReleaseWorkflow).toContain('git fetch --force --no-tags origin "refs/tags/$TAG:refs/tags/$TAG"')+ expect(desktopReleaseWorkflow).toContain('git rev-parse "$TAG^{commit}"')+ expect(desktopReleaseWorkflow).toContain('[[ "$tag_commit" == "$GITHUB_SHA" ]]')+ expect(desktopReleaseWorkflow).not.toContain("--clobber")+ expect(desktopReleaseArtifacts).toContain("Desktop release namespace is immutable and must start empty")+ expect(desktopReleaseArtifacts).toContain("unexpected desktop asset candidates")+ expect(desktopReleaseWorkflow).not.toContain("releaseId:")+ expect(desktopReleaseWorkflow).not.toContain("uploadUpdaterJson")expect(desktopReleaseWorkflow).not.toContain("tagName:")expect(desktopReleaseWorkflow).not.toContain("releaseName:")expect(desktopReleaseWorkflow).not.toContain("releaseBody:")expect(desktopReleaseWorkflow).not.toContain("releaseDraft:")expect(desktopReleaseWorkflow).not.toContain("prerelease:")- expect(desktopReleaseWorkflow).toContain('EXISTING=$(gh release view "$TAG" --json body')- expect(desktopReleaseWorkflow).toContain('gh release edit "$TAG" --notes "${EXISTING}${DOWNLOADS}"')+ const aggregate = desktopReleaseWorkflow.indexOf("desktop-release-artifacts.mjs aggregate")+ const releaseLookup = desktopReleaseWorkflow.indexOf("Resolve existing release after every verification gate")+ const binaryUpload = desktopReleaseWorkflow.indexOf("Upload verified binary and signature assets")+ const metadataUpload = desktopReleaseWorkflow.indexOf("Upload latest.json last")+ expect(aggregate).toBeLessThan(releaseLookup)+ expect(releaseLookup).toBeLessThan(binaryUpload)+ expect(binaryUpload).toBeLessThan(metadataUpload)})- it("builds signed updater artifacts and publishes updater metadata", () => {+ it("builds exact self-contained updater assets and one deterministic eleven-key latest.json", () => {expect(desktopConfig.bundle?.createUpdaterArtifacts).toBe(true)expect(desktopConfig.plugins?.updater?.endpoints).toEqual(["https://alook.ai/api/desktop/update/{{target}}/{{arch}}/{{current_version}}?bundle_type={{bundle_type}}",])- expect(desktopReleaseWorkflow).toContain("uploadUpdaterJson: true")- expect(desktopReleaseWorkflow).not.toContain("includeUpdaterJson")expect(desktopReleaseWorkflow).toContain("TAURI_SIGNING_PRIVATE_KEY:")+ expect(desktopReleaseWorkflow).not.toContain("v1Compatible")+ expect(desktopReleaseArtifacts).not.toContain(".nsis.zip")+ expect(desktopReleaseArtifacts).not.toContain(".msi.zip")+ for (const platform of [+ "darwin-aarch64",+ "darwin-aarch64-app",+ "darwin-x86_64",+ "darwin-x86_64-app",+ "linux-x86_64",+ "linux-x86_64-appimage",+ "linux-x86_64-deb",+ "linux-x86_64-rpm",+ "windows-x86_64",+ "windows-x86_64-msi",+ "windows-x86_64-nsis",+ ]) {+ expect(desktopReleaseArtifacts).toContain(`"${platform}"`)+ }expect(desktopUpdateRoute).toContain('"darwin-aarch64-app"')expect(desktopUpdateRoute).toContain('"linux-x86_64-appimage"')expect(desktopUpdateRoute).toContain('"linux-x86_64-deb"')@@ -1128,18 +1201,133 @@ describe("Desktop updater release", () => {expect(desktopReleaseWorkflow).toContain("APPLE_SIGNING_IDENTITY:")expect(desktopReleaseWorkflow).toContain("APPLE_API_ISSUER:")expect(desktopReleaseWorkflow).toContain("APPLE_API_KEY_PATH:")- expect(desktopReleaseWorkflow).toContain("codesign --verify --deep --strict")- expect(desktopReleaseWorkflow).toContain("flags=.*runtime")- expect(desktopReleaseWorkflow).toContain("xcrun stapler validate")- expect(desktopReleaseWorkflow).toContain("spctl --assess --type execute")- expect(desktopReleaseWorkflow).toContain("CFBundleShortVersionString")+ expect(desktopReleaseWorkflow).toContain("Clean temporary macOS signing material")+ expect(desktopReleaseWorkflow).toContain("if: always() && runner.os == 'macOS'")+ const persistedMacCleanupPath = desktopReleaseWorkflow.indexOf('echo "ALOOK_MACOS_P12_PATH=$p12_path"')+ const firstMacSecretWrite = desktopReleaseWorkflow.indexOf("base64 -D > \"$p12_path\"")+ expect(persistedMacCleanupPath).toBeGreaterThan(-1)+ expect(persistedMacCleanupPath).toBeLessThan(firstMacSecretWrite)+ expect(desktopReleaseWorkflow).not.toContain("ALOOK_MACOS_KEYCHAIN_PASSWORD=")+ expect(desktopMacVerifier).toContain("codesign --verify --deep --strict")+ expect(desktopMacVerifier).toContain("flags=.*runtime")+ expect(desktopMacVerifier).toContain("xcrun stapler validate")+ expect(desktopMacVerifier).toContain("spctl --assess --type execute")+ expect(desktopMacVerifier).toContain("CFBundleShortVersionString")+ expect(desktopMacVerifier).toContain("com.apple.security.get-task-allow")+ expect(desktopMacVerifier).toContain("verify-minisign.mjs")expect(desktopReleaseWorkflow).toContain("EXPECTED_VERSION:")expect(desktopReleaseWorkflow).toContain("Developer ID signed")expect(desktopReleaseWorkflow).not.toContain("ad-hoc signed and are not notarized")expect(desktopReleaseWorkflow).not.toContain("Privacy & Security")- expect(desktopReleaseWorkflow).toContain("not Authenticode code-signed")- expect(desktopReleaseWorkflow).toContain("More info")- expect(desktopReleaseWorkflow).toContain("Run anyway")+ expect(desktopReleaseWorkflow).not.toContain("not Authenticode code-signed")+ expect(desktopReleaseWorkflow).not.toContain("Run anyway")+ })++ it("uses OIDC-only Microsoft Artifact Signing inside Tauri's exact sign hook", () => {+ expect(desktopReleaseWorkflow).toContain(+ "azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0",+ )+ expect(desktopReleaseWorkflow).toContain("tauri.windows.signing.conf.json")+ expect(desktopReleaseWorkflow).not.toContain("AZURE_CLIENT_SECRET")+ expect(desktopReleaseWorkflow).not.toContain(".pfx")+ expect(desktopWindowsSigningConfig.bundle.windows.signCommand).toEqual({+ cmd: "pwsh",+ args: [+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-File",+ "../../../scripts/ci/sign-desktop-windows.ps1",+ "%1",+ ],+ })+ expect(desktopSigningDependencies.schemaVersion).toBe(1)+ expect(desktopSigningDependencies.packages).toEqual([+ {+ name: "ArtifactSigning",+ version: "0.1.8",+ source: "https://www.powershellgallery.com/api/v2/package/ArtifactSigning/0.1.8",+ sha256: "3221344b8c627915d3870f23e80816f31a5d8c2bae1d7c0cdd6c9652f6c4e089",+ kind: "module",+ },+ {+ name: "Microsoft.Windows.SDK.BuildTools",+ version: "10.0.26100.4188",+ source:+ "https://api.nuget.org/v3-flatcontainer/microsoft.windows.sdk.buildtools/10.0.26100.4188/microsoft.windows.sdk.buildtools.10.0.26100.4188.nupkg",+ sha256: "180deb372659029864c10a0c04787833234d64aacd1d2c0661d2c00295d8e022",+ kind: "dependency",+ },+ {+ name: "Microsoft.ArtifactSigning.Client",+ version: "1.0.128",+ source:+ "https://api.nuget.org/v3-flatcontainer/microsoft.artifactsigning.client/1.0.128/microsoft.artifactsigning.client.1.0.128.nupkg",+ sha256: "74bd7d27e6ce1051409c38d9b46bc8df0400ecd643d51ffbf2ac00869061e40b",+ kind: "dependency",+ },+ {+ name: "sign",+ version: "0.9.1-beta.26227.3",+ source:+ "https://api.nuget.org/v3-flatcontainer/sign/0.9.1-beta.26227.3/sign.0.9.1-beta.26227.3.nupkg",+ sha256: "34fd0d4aeabdbc363a48883881865b4dd65e6c11ba916028082fa23f3e1b1ba1",+ kind: "dependency",+ },+ ])+ for (const dependency of desktopSigningDependencies.packages) {+ expect(dependency.source).toMatch(/^https:\/\/(?:www\.powershellgallery\.com|api\.nuget\.org)\//)+ expect(dependency.sha256).toMatch(/^[0-9a-f]{64}$/)+ }+ expect(desktopWindowsSigningSetup).toContain("Get-FileHash -LiteralPath $archive -Algorithm SHA256")+ expect(desktopWindowsSigningSetup).toContain("destination must be fresh")+ expect(desktopWindowsSigningSetup).toContain("--connect-timeout 15 --max-time 600")+ expect(desktopWindowsSigningSetup).toContain("--retry 3 --retry-delay 2 --retry-all-errors")+ expect(desktopWindowsSigningSetup).not.toContain("Invoke-WebRequest")+ expect(desktopWindowsSigningSetup).toContain("[IO.Compression.ZipFile]::ExtractToDirectory")+ for (const requiredPackageFile of [+ "ArtifactSigning.psd1",+ "signtool.exe",+ "Azure.CodeSigning.Dlib.dll",+ "sign.dll",+ ]) {+ expect(desktopWindowsSigningSetup).toContain(requiredPackageFile)+ }+ const windowsCleanupRoot = desktopReleaseWorkflow.indexOf('"ALOOK_ARTIFACT_SIGNING_ROOT=$destination"')+ const windowsPreparation = desktopReleaseWorkflow.indexOf("./scripts/ci/prepare-desktop-windows-signing.ps1")+ expect(windowsCleanupRoot).toBeGreaterThan(-1)+ expect(windowsCleanupRoot).toBeLessThan(windowsPreparation)+ expect(desktopWindowsSigner).toContain("GetRelativePath")+ expect(desktopWindowsSigner).toContain("^[a-z0-9-]+\\.codesigning\\.azure\\.net$")+ expect(desktopWindowsSigner).toContain("IsDefaultPort")+ expect(desktopWindowsSigner).toContain("AbsolutePath -ne '/'")+ expect(desktopReleaseWorkflow).toContain("^[a-z0-9-]+\\.codesigning\\.azure\\.net$")+ expect(desktopWindowsSigner).toContain("Wix(?:UI|Util)Extension")+ expect(desktopWindowsSigner).toContain("(?:NSISdl|StartMenu|System|nsDialogs)")+ expect(desktopWindowsSigner).toContain("additional\\\\nsis_tauri_utils\\.dll")+ expect(desktopWindowsSigner).not.toContain("[A-Za-z0-9_.-]+\\.dll")+ expect(desktopWindowsSigner).toContain('FileDigest = "SHA256"')+ expect(desktopWindowsSigner).toContain('TimestampRfc3161 = "http://timestamp.acs.microsoft.com"')+ expect(desktopWindowsSigner).toContain('TimestampDigest = "SHA256"')+ expect(desktopWindowsSigner).toContain("ExcludeAzureCliCredential = $false")+ for (const credential of [+ "Environment",+ "WorkloadIdentity",+ "ManagedIdentity",+ "SharedTokenCache",+ "VisualStudio",+ "VisualStudioCode",+ "AzurePowerShell",+ "AzureDeveloperCli",+ "InteractiveBrowser",+ ]) {+ expect(desktopWindowsSigner).toContain(`Exclude${credential}Credential = $true`)+ }+ expect(desktopWindowsVerifier).toContain("signtool.exe verify /pa /all /v")+ expect(desktopWindowsVerifier).toContain("Hash of file \\(sha256\\)")+ expect(desktopWindowsVerifier).toContain("TimeStamperCertificate")+ expect(desktopWindowsVerifier).toContain('Filter "alook-desktop.exe"')+ expect(desktopWindowsVerifier).toContain("verify-minisign.mjs")})})diff --git a/src/desktop/src-tauri/tauri.windows.signing.conf.json b/src/desktop/src-tauri/tauri.windows.signing.conf.jsonnew file mode 100644index 000000000..084275585--- /dev/null+++ b/src/desktop/src-tauri/tauri.windows.signing.conf.json@@ -0,0 +1,17 @@+{+ "bundle": {+ "windows": {+ "signCommand": {+ "cmd": "pwsh",+ "args": [+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-File",+ "../../../scripts/ci/sign-desktop-windows.ps1",+ "%1"+ ]+ }+ }+ }+}