Merge P1.3d: unsigned release workflow for three systems
This commit is contained in:
2656
.github/workflows/release.yml
vendored
2656
.github/workflows/release.yml
vendored
File diff suppressed because it is too large
Load Diff
281
.github/workflows/tauri-build-pr.yml
vendored
281
.github/workflows/tauri-build-pr.yml
vendored
@@ -1,281 +0,0 @@
|
|||||||
# Waggle — Tauri Build Verification (per-PR + main pushes)
|
|
||||||
#
|
|
||||||
# CC Sesija A §2.4 Task A13 (PM-reframed scope). Verifies the desktop app
|
|
||||||
# builds cleanly on Win + macOS for every PR + main push, so a regression
|
|
||||||
# can't sneak in unnoticed between releases. Distinct from release.yml
|
|
||||||
# which only triggers on `v*` tags + uploads to GitHub Releases (this
|
|
||||||
# workflow only uploads to the workflow run as artifacts for download
|
|
||||||
# verification, no release publishing).
|
|
||||||
#
|
|
||||||
# Exit signal: green CI here means tag-push to release.yml is safe to
|
|
||||||
# pull the trigger on. Red CI here = same investigation flow as release.yml
|
|
||||||
# (Rust compile / Vite build / sidecar bundle / native dep failure).
|
|
||||||
|
|
||||||
name: Tauri Build Verification
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
paths:
|
|
||||||
- 'app/**'
|
|
||||||
- 'apps/web/**'
|
|
||||||
- 'packages/**'
|
|
||||||
- 'scripts/**'
|
|
||||||
- 'package.json'
|
|
||||||
- 'package-lock.json'
|
|
||||||
- '.github/workflows/release.yml'
|
|
||||||
- '.github/workflows/tauri-build-pr.yml'
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
paths:
|
|
||||||
- 'app/**'
|
|
||||||
- 'apps/web/**'
|
|
||||||
- 'packages/**'
|
|
||||||
- 'scripts/**'
|
|
||||||
- 'package.json'
|
|
||||||
- 'package-lock.json'
|
|
||||||
- '.github/workflows/release.yml'
|
|
||||||
- '.github/workflows/tauri-build-pr.yml'
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
verify-windows:
|
|
||||||
runs-on: windows-latest
|
|
||||||
timeout-minutes: 45
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: Setup Node.js
|
|
||||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
|
||||||
with:
|
|
||||||
node-version: 22.23.2
|
|
||||||
cache: npm
|
|
||||||
|
|
||||||
- name: Setup Rust
|
|
||||||
uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4
|
|
||||||
with:
|
|
||||||
toolchain: 1.94.0
|
|
||||||
|
|
||||||
- name: Rust cache
|
|
||||||
uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2
|
|
||||||
with:
|
|
||||||
workspaces: app/src-tauri
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: Verify Windows skill-audit and vault regressions
|
|
||||||
shell: pwsh
|
|
||||||
run: node node_modules/vitest/vitest.mjs run --root . --config vitest.config.ts packages/agent/tests/skill-audit-store.test.ts packages/core/tests/vault.test.ts --maxWorkers=1 --no-file-parallelism
|
|
||||||
|
|
||||||
- name: Verify Windows release-mode and publication guards
|
|
||||||
shell: pwsh
|
|
||||||
env:
|
|
||||||
WAGGLE_REQUIRE_PWSH7: '1'
|
|
||||||
run: node node_modules/vitest/vitest.mjs run --root . --config vitest.config.ts packages/server/tests/tauri-config.test.ts -t "CI/CD Configuration"
|
|
||||||
|
|
||||||
- name: Install locked Tauri CLI
|
|
||||||
run: npm ci --prefix app --ignore-scripts
|
|
||||||
|
|
||||||
- name: Build packages (shared → core → agent → server)
|
|
||||||
run: npm run build:packages
|
|
||||||
|
|
||||||
- name: Bundle Node.js runtime
|
|
||||||
run: node scripts/bundle-node.mjs
|
|
||||||
|
|
||||||
- name: Build sidecar
|
|
||||||
run: node scripts/build-sidecar.mjs
|
|
||||||
|
|
||||||
- name: Bundle native dependencies
|
|
||||||
run: node scripts/bundle-native-deps.mjs
|
|
||||||
|
|
||||||
- name: Stage sidecar dependencies
|
|
||||||
run: node scripts/stage-sidecar-deps.mjs
|
|
||||||
|
|
||||||
- name: Build frontend
|
|
||||||
run: cd apps/web && npx vite build
|
|
||||||
|
|
||||||
- name: Verify repository cleanliness before Tauri build
|
|
||||||
shell: pwsh
|
|
||||||
run: |
|
|
||||||
$sourceStatus = @(& git status --porcelain=v1 --untracked-files=all)
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'Could not inspect repository source state before Tauri build.' }
|
|
||||||
if ($sourceStatus.Count -ne 0) {
|
|
||||||
$sourceDetails = $sourceStatus -join [Environment]::NewLine
|
|
||||||
throw "Repository must be clean before Windows Tauri build.$([Environment]::NewLine)$sourceDetails"
|
|
||||||
}
|
|
||||||
|
|
||||||
- name: Build Tauri (Windows)
|
|
||||||
id: tauri-build-windows
|
|
||||||
# app/package-lock.json pins the CLI and platform binary. Invoke that
|
|
||||||
# local copy so verification builds cannot drift to a newer 2.x release.
|
|
||||||
run: cd app && node node_modules/@tauri-apps/cli/tauri.js build --bundles nsis
|
|
||||||
env:
|
|
||||||
# Skip code signing for PR verification — release.yml handles signing
|
|
||||||
# only on tag push.
|
|
||||||
TAURI_PRIVATE_KEY: ''
|
|
||||||
TAURI_KEY_PASSWORD: ''
|
|
||||||
|
|
||||||
- name: Report repository changes after Tauri build
|
|
||||||
if: ${{ always() && steps.tauri-build-windows.outcome != 'skipped' }}
|
|
||||||
shell: pwsh
|
|
||||||
run: |
|
|
||||||
$sourceStatus = @(& git status --porcelain=v1 --untracked-files=all)
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'Could not inspect repository source state after Tauri build.' }
|
|
||||||
if ($sourceStatus.Count -ne 0) {
|
|
||||||
$trackedPaths = @(& git diff --name-only --diff-filter=ACDMRTUXB)
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'Could not enumerate tracked Tauri build mutations.' }
|
|
||||||
foreach ($trackedPath in $trackedPaths) {
|
|
||||||
Write-Host "::group::Tracked mutation: $trackedPath"
|
|
||||||
$headBlob = @(& git rev-parse "HEAD:$trackedPath" 2>&1) -join ''
|
|
||||||
$headBlobExit = $LASTEXITCODE
|
|
||||||
$indexBlob = @(& git rev-parse ":$trackedPath" 2>&1) -join ''
|
|
||||||
$indexBlobExit = $LASTEXITCODE
|
|
||||||
if (Test-Path -LiteralPath $trackedPath -PathType Leaf) {
|
|
||||||
$worktreeHash = (Get-FileHash -LiteralPath $trackedPath -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
||||||
$filteredBlob = @(& git hash-object "--path=$trackedPath" -- $trackedPath 2>&1) -join ''
|
|
||||||
$filteredBlobExit = $LASTEXITCODE
|
|
||||||
$resolvedPath = (Resolve-Path -LiteralPath $trackedPath).Path
|
|
||||||
$bytes = [IO.File]::ReadAllBytes($resolvedPath)
|
|
||||||
$crlfCount = 0
|
|
||||||
$lfOnlyCount = 0
|
|
||||||
for ($index = 0; $index -lt $bytes.Length; $index += 1) {
|
|
||||||
if ($bytes[$index] -ne 10) { continue }
|
|
||||||
if ($index -gt 0 -and $bytes[$index - 1] -eq 13) { $crlfCount += 1 }
|
|
||||||
else { $lfOnlyCount += 1 }
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
$worktreeHash = '<missing>'
|
|
||||||
$filteredBlob = '<missing>'
|
|
||||||
$filteredBlobExit = 0
|
|
||||||
$crlfCount = 0
|
|
||||||
$lfOnlyCount = 0
|
|
||||||
}
|
|
||||||
Write-Host "HEAD blob (exit $headBlobExit): $headBlob"
|
|
||||||
Write-Host "Index blob (exit $indexBlobExit): $indexBlob"
|
|
||||||
Write-Host "Git-filtered worktree blob (exit $filteredBlobExit): $filteredBlob"
|
|
||||||
Write-Host "Raw worktree SHA256: $worktreeHash; CRLF=$crlfCount; LF-only=$lfOnlyCount"
|
|
||||||
$changeSummary = @(& git diff --numstat -- $trackedPath)
|
|
||||||
$changeSummaryExit = $LASTEXITCODE
|
|
||||||
if ($changeSummaryExit -ne 0) {
|
|
||||||
Write-Host "Could not render numeric diff summary (exit $changeSummaryExit)."
|
|
||||||
} else {
|
|
||||||
Write-Host "Numeric diff summary: $($changeSummary -join '; ')"
|
|
||||||
}
|
|
||||||
Write-Host '::endgroup::'
|
|
||||||
}
|
|
||||||
$sourceDetails = $sourceStatus -join [Environment]::NewLine
|
|
||||||
throw "Windows Tauri build mutated repository worktree.$([Environment]::NewLine)$sourceDetails"
|
|
||||||
}
|
|
||||||
|
|
||||||
- name: Certify Windows Solo installer lifecycle
|
|
||||||
shell: pwsh
|
|
||||||
run: |
|
|
||||||
$installers = @(Get-ChildItem -LiteralPath 'app/src-tauri/target' -Recurse -Filter '*-setup.exe' -File | Where-Object { $_.DirectoryName -match '[\\/]bundle[\\/]nsis$' })
|
|
||||||
if ($installers.Count -ne 1) { throw "Expected exactly one NSIS setup executable, found $($installers.Count)" }
|
|
||||||
$installer = $installers[0]
|
|
||||||
& ./scripts/certify-windows-installer.ps1 -InstallerPath $installer.FullName -ExpectedSourceRevision $env:GITHUB_SHA
|
|
||||||
|
|
||||||
- name: Upload Windows artifacts
|
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
|
||||||
with:
|
|
||||||
name: waggle-windows-${{ github.sha }}
|
|
||||||
path: |
|
|
||||||
app/src-tauri/target/**/bundle/nsis/*.exe
|
|
||||||
app/src-tauri/target/**/bundle/nsis/windows-installer-certificate.json
|
|
||||||
if-no-files-found: error
|
|
||||||
retention-days: 7
|
|
||||||
|
|
||||||
verify-macos:
|
|
||||||
timeout-minutes: 60
|
|
||||||
strategy:
|
|
||||||
# Per-arch, matching release.yml. Universal builds are rejected by the
|
|
||||||
# bundle scripts (sqlite-vec / onnxruntime / node ship per-arch binaries),
|
|
||||||
# so each arch is staged and built separately.
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- target: aarch64-apple-darwin
|
|
||||||
arch: arm64
|
|
||||||
runner: macos-15
|
|
||||||
bundles: dmg
|
|
||||||
artifact_path: app/src-tauri/target/aarch64-apple-darwin/release/bundle/dmg/*.dmg
|
|
||||||
- target: x86_64-apple-darwin
|
|
||||||
arch: x64
|
|
||||||
runner: macos-15-intel
|
|
||||||
bundles: app
|
|
||||||
artifact_path: app/src-tauri/target/x86_64-apple-darwin/release/bundle/macos/*.app
|
|
||||||
runs-on: ${{ matrix.runner }}
|
|
||||||
env:
|
|
||||||
TARGET_ARCH: ${{ matrix.arch }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: Setup Node.js
|
|
||||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
|
||||||
with:
|
|
||||||
node-version: 22.23.2
|
|
||||||
cache: npm
|
|
||||||
|
|
||||||
- name: Verify runner architecture
|
|
||||||
run: node -e "if (process.arch !== process.env.TARGET_ARCH) { console.error('Expected ' + process.env.TARGET_ARCH + ' runner, got ' + process.arch); process.exit(1); }"
|
|
||||||
|
|
||||||
- name: Setup Rust
|
|
||||||
uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4
|
|
||||||
with:
|
|
||||||
toolchain: 1.94.0
|
|
||||||
targets: ${{ matrix.target }}
|
|
||||||
|
|
||||||
- name: Rust cache
|
|
||||||
uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2
|
|
||||||
with:
|
|
||||||
workspaces: app/src-tauri
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: Install locked Tauri CLI
|
|
||||||
run: npm ci --prefix app --ignore-scripts
|
|
||||||
|
|
||||||
- name: Build packages (shared → core → agent → server)
|
|
||||||
run: npm run build:packages
|
|
||||||
|
|
||||||
- name: Bundle Node.js runtime
|
|
||||||
run: node scripts/bundle-node.mjs
|
|
||||||
|
|
||||||
- name: Build sidecar
|
|
||||||
run: node scripts/build-sidecar.mjs
|
|
||||||
|
|
||||||
- name: Bundle native dependencies
|
|
||||||
run: node scripts/bundle-native-deps.mjs
|
|
||||||
|
|
||||||
- name: Stage sidecar dependencies
|
|
||||||
run: node scripts/stage-sidecar-deps.mjs
|
|
||||||
|
|
||||||
- name: Build frontend
|
|
||||||
run: cd apps/web && npx vite build
|
|
||||||
|
|
||||||
- name: Build Tauri (macOS ${{ matrix.target }})
|
|
||||||
# See verify-windows note: use the app-local lockfile-pinned CLI.
|
|
||||||
# Built per-arch — universal is rejected by the bundle scripts
|
|
||||||
# (per-arch native modules), matching release.yml.
|
|
||||||
run: cd app && node node_modules/@tauri-apps/cli/tauri.js build --target ${{ matrix.target }} --bundles ${{ matrix.bundles }}
|
|
||||||
env:
|
|
||||||
TAURI_PRIVATE_KEY: ''
|
|
||||||
TAURI_KEY_PASSWORD: ''
|
|
||||||
|
|
||||||
- name: Upload macOS artifacts
|
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
|
||||||
with:
|
|
||||||
name: waggle-macos-${{ matrix.target }}-${{ github.sha }}
|
|
||||||
path: ${{ matrix.artifact_path }}
|
|
||||||
if-no-files-found: error
|
|
||||||
retention-days: 7
|
|
||||||
@@ -13,15 +13,11 @@
|
|||||||
"tauri:build": "node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && node ../scripts/bundle-native-deps.mjs && node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build",
|
"tauri:build": "node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && node ../scripts/bundle-native-deps.mjs && node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build",
|
||||||
"tauri:build:local": "node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && node ../scripts/bundle-native-deps.mjs && node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --debug",
|
"tauri:build:local": "node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && node ../scripts/bundle-native-deps.mjs && node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --debug",
|
||||||
"tauri:build:win": "node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && node ../scripts/bundle-native-deps.mjs && node ../scripts/stage-sidecar-deps.mjs && node ../scripts/check-sidecar-resources.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --target x86_64-pc-windows-msvc",
|
"tauri:build:win": "node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && node ../scripts/bundle-native-deps.mjs && node ../scripts/stage-sidecar-deps.mjs && node ../scripts/check-sidecar-resources.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --target x86_64-pc-windows-msvc",
|
||||||
"tauri:build:win:pilot-signed": "npm run tauri:sign:pilot:win:apply && npm run tauri:build:win -- --config src-tauri/tauri.build-override.conf.json",
|
|
||||||
"tauri:build:mac": "npm run tauri:build:mac:arm64 && npm run tauri:build:mac:x64",
|
"tauri:build:mac": "npm run tauri:build:mac:arm64 && npm run tauri:build:mac:x64",
|
||||||
"tauri:build:mac:arm64": "TARGET_ARCH=arm64 node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && TARGET_ARCH=arm64 node ../scripts/bundle-native-deps.mjs && TARGET_ARCH=arm64 node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --target aarch64-apple-darwin",
|
"tauri:build:mac:arm64": "TARGET_ARCH=arm64 node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && TARGET_ARCH=arm64 node ../scripts/bundle-native-deps.mjs && TARGET_ARCH=arm64 node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --target aarch64-apple-darwin",
|
||||||
"tauri:build:mac:x64": "TARGET_ARCH=x64 node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && TARGET_ARCH=x64 node ../scripts/bundle-native-deps.mjs && TARGET_ARCH=x64 node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --target x86_64-apple-darwin",
|
"tauri:build:mac:x64": "TARGET_ARCH=x64 node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && TARGET_ARCH=x64 node ../scripts/bundle-native-deps.mjs && TARGET_ARCH=x64 node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --target x86_64-apple-darwin",
|
||||||
"tauri:dev": "npx tauri dev",
|
"tauri:build:linux": "node ../scripts/bundle-node.mjs && node ../scripts/build-sidecar.mjs && node ../scripts/bundle-native-deps.mjs && node ../scripts/stage-sidecar-deps.mjs && cd ../apps/web && npx vite build && cd ../../app && npx tauri build --target x86_64-unknown-linux-gnu",
|
||||||
"tauri:sign:pilot:win:setup": "powershell -ExecutionPolicy Bypass -File scripts/sign-windows-pilot.ps1 -Mode Setup",
|
"tauri:dev": "npx tauri dev"
|
||||||
"tauri:sign:pilot:win:apply": "node scripts/apply-signing-config.mjs",
|
|
||||||
"tauri:sign:pilot:win:sign": "powershell -ExecutionPolicy Bypass -File scripts/sign-windows-pilot.ps1 -Mode Sign -ArtifactPath",
|
|
||||||
"tauri:sign:pilot:mac:adhoc": "bash scripts/sign-macos-adhoc.sh"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@base-ui/react": "^1.3.0",
|
"@base-ui/react": "^1.3.0",
|
||||||
|
|||||||
@@ -1,145 +0,0 @@
|
|||||||
#!/usr/bin/env node
|
|
||||||
/**
|
|
||||||
* apply-signing-config.mjs — write the captured Windows code-signing thumbprint
|
|
||||||
* into app/src-tauri/tauri.build-override.conf.json.
|
|
||||||
*
|
|
||||||
* Read by `npm run tauri:sign:pilot:win:apply`. Idempotent: re-running with the
|
|
||||||
* same thumbprint produces an identical file. Updating the cert (rotation) is
|
|
||||||
* handled by re-running the upstream cert-gen script + this CLI.
|
|
||||||
*
|
|
||||||
* Pure logic lives in `signing-config.ts`; this is the thin file-I/O wrapper.
|
|
||||||
*
|
|
||||||
* Reference: docs/code-signing-pilot-and-launch.md §1.1
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
|
|
||||||
import { resolve, dirname } from 'node:path';
|
|
||||||
import { fileURLToPath } from 'node:url';
|
|
||||||
|
|
||||||
// The pure helpers below mirror the certificate-store helpers in
|
|
||||||
// app/scripts/signing-config.ts so this pilot CLI has zero TS-loader dependency
|
|
||||||
// at runtime. Keep parseThumbprintString and addWindowsSigningToOverride in
|
|
||||||
// lockstep with the canonical TypeScript implementation.
|
|
||||||
|
|
||||||
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
|
|
||||||
const APP_DIR = resolve(SCRIPT_DIR, '..');
|
|
||||||
const REPO_ROOT = resolve(APP_DIR, '..');
|
|
||||||
|
|
||||||
const OVERRIDE_PATH = resolve(
|
|
||||||
APP_DIR,
|
|
||||||
'src-tauri',
|
|
||||||
'tauri.build-override.conf.json',
|
|
||||||
);
|
|
||||||
const THUMBPRINT_PATH = resolve(APP_DIR, 'src-tauri', '.thumbprint.txt');
|
|
||||||
const DEFAULT_DIGEST_ALGORITHM = 'sha256';
|
|
||||||
const DEFAULT_TIMESTAMP_URL = 'http://timestamp.digicert.com';
|
|
||||||
const THUMBPRINT_LENGTH = 40;
|
|
||||||
const HEX_PATTERN = /^[0-9A-F]+$/;
|
|
||||||
const WINDOWS_SIGNING_MODE =
|
|
||||||
process.env.WAGGLE_WINDOWS_SIGNING_MODE ?? 'certificate-store';
|
|
||||||
|
|
||||||
function parseThumbprintString(raw) {
|
|
||||||
if (!raw || raw.trim().length === 0) {
|
|
||||||
throw new Error('Thumbprint is empty — cert generation may have failed.');
|
|
||||||
}
|
|
||||||
const compact = raw.replace(/\s+/g, '').toUpperCase();
|
|
||||||
if (compact.length !== THUMBPRINT_LENGTH || !HEX_PATTERN.test(compact)) {
|
|
||||||
throw new Error(
|
|
||||||
`Thumbprint must be 40 hex characters; got ${compact.length} chars (sample: "${compact.slice(0, 16)}...").`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return compact;
|
|
||||||
}
|
|
||||||
|
|
||||||
function addWindowsSigningToOverride(config, thumbprint, options = {}) {
|
|
||||||
const normalisedThumbprint = parseThumbprintString(thumbprint);
|
|
||||||
const digestAlgorithm = options.digestAlgorithm ?? DEFAULT_DIGEST_ALGORITHM;
|
|
||||||
const timestampUrl = options.timestampUrl ?? DEFAULT_TIMESTAMP_URL;
|
|
||||||
|
|
||||||
const existingBundle = config.bundle ?? {};
|
|
||||||
const existingWindows = existingBundle.windows ?? {};
|
|
||||||
const nonCustomCommandWindows = { ...existingWindows };
|
|
||||||
delete nonCustomCommandWindows.signCommand;
|
|
||||||
|
|
||||||
return {
|
|
||||||
...config,
|
|
||||||
bundle: {
|
|
||||||
...existingBundle,
|
|
||||||
windows: {
|
|
||||||
...nonCustomCommandWindows,
|
|
||||||
certificateThumbprint: normalisedThumbprint,
|
|
||||||
digestAlgorithm,
|
|
||||||
timestampUrl,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Main ───────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function main() {
|
|
||||||
if (!['certificate-store', 'artifact-signing'].includes(WINDOWS_SIGNING_MODE)) {
|
|
||||||
console.error(
|
|
||||||
`[apply-signing-config] unsupported WAGGLE_WINDOWS_SIGNING_MODE: ${WINDOWS_SIGNING_MODE}`,
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
if (WINDOWS_SIGNING_MODE === 'artifact-signing') {
|
|
||||||
console.error(
|
|
||||||
'[apply-signing-config] Azure Artifact Signing is hosted-only. '
|
|
||||||
+ 'Run the protected GitHub-hosted release workflow; this local helper cannot issue '
|
|
||||||
+ 'the immutable build receipt, protected OIDC identity, session manifest, or callback ledger.',
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
if (!existsSync(THUMBPRINT_PATH)) {
|
|
||||||
console.error(
|
|
||||||
`[apply-signing-config] thumbprint file missing: ${THUMBPRINT_PATH}`,
|
|
||||||
);
|
|
||||||
console.error(
|
|
||||||
'[apply-signing-config] Run `npm run tauri:sign:pilot:win:setup` (or app/scripts/sign-windows-pilot.ps1 -Mode Setup) first.',
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
if (!existsSync(OVERRIDE_PATH)) {
|
|
||||||
console.error(
|
|
||||||
`[apply-signing-config] override config missing: ${OVERRIDE_PATH}`,
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const overrideRaw = readFileSync(OVERRIDE_PATH, 'utf8');
|
|
||||||
|
|
||||||
let override;
|
|
||||||
try {
|
|
||||||
override = JSON.parse(overrideRaw);
|
|
||||||
} catch (err) {
|
|
||||||
console.error(
|
|
||||||
`[apply-signing-config] failed to parse ${OVERRIDE_PATH}: ${err instanceof Error ? err.message : String(err)}`,
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
let updated;
|
|
||||||
try {
|
|
||||||
const rawThumbprint = readFileSync(THUMBPRINT_PATH, 'utf8');
|
|
||||||
updated = addWindowsSigningToOverride(override, rawThumbprint);
|
|
||||||
} catch (err) {
|
|
||||||
console.error(
|
|
||||||
`[apply-signing-config] failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Format with 2-space indent + trailing newline (matches existing JSON files
|
|
||||||
// in the repo). Idempotent: same input → same output bytes.
|
|
||||||
const serialised = JSON.stringify(updated, null, 2) + '\n';
|
|
||||||
writeFileSync(OVERRIDE_PATH, serialised, 'utf8');
|
|
||||||
|
|
||||||
const relativePath = OVERRIDE_PATH.replace(REPO_ROOT, '').replace(/^\\/, '');
|
|
||||||
const signingDescription =
|
|
||||||
`thumbprint ${updated.bundle.windows.certificateThumbprint.slice(0, 8)}...`;
|
|
||||||
console.log(`[apply-signing-config] wrote ${signingDescription} to ${relativePath}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
main();
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,57 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# sign-macos-adhoc.sh — re-sign + verify a Tauri-built .app bundle for the
|
|
||||||
# Wave-1 Egzakta-internal pilot using ad-hoc signing.
|
|
||||||
#
|
|
||||||
# Implements docs/code-signing-pilot-and-launch.md §1.2 (macOS ad-hoc).
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# ./sign-macos-adhoc.sh <path-to-Waggle.app>
|
|
||||||
#
|
|
||||||
# Ordinary `npm run tauri:build:mac` does not load the optional build override.
|
|
||||||
# Treat the input as unsigned until this script signs and verifies it. This script:
|
|
||||||
#
|
|
||||||
# 1. Signs or re-signs the bundle with --force --deep to catch nested helpers
|
|
||||||
# (sidecar binary, native deps) that Tauri's pass missed.
|
|
||||||
# 2. Verifies the signature with --verify --deep --strict.
|
|
||||||
#
|
|
||||||
# Distribute the result wrapped in .zip (NOT .dmg — Gatekeeper enforces
|
|
||||||
# notarization more aggressively on disk images since macOS 10.15).
|
|
||||||
#
|
|
||||||
# NOT for public Day-0 — that requires Apple Developer ID + notarization
|
|
||||||
# per docs/code-signing-pilot-and-launch.md §2.2.
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
APP_PATH="${1:-}"
|
|
||||||
|
|
||||||
if [[ -z "$APP_PATH" ]]; then
|
|
||||||
echo "usage: $0 <path-to-Waggle.app>" >&2
|
|
||||||
exit 64 # EX_USAGE
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! -d "$APP_PATH" ]]; then
|
|
||||||
echo "[sign-macos-adhoc] not a directory: $APP_PATH" >&2
|
|
||||||
exit 66 # EX_NOINPUT
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! "$APP_PATH" =~ \.app$ ]]; then
|
|
||||||
echo "[sign-macos-adhoc] path must end in .app: $APP_PATH" >&2
|
|
||||||
exit 64
|
|
||||||
fi
|
|
||||||
|
|
||||||
if ! command -v codesign >/dev/null 2>&1; then
|
|
||||||
echo "[sign-macos-adhoc] codesign not found — Xcode command-line tools required." >&2
|
|
||||||
exit 69 # EX_UNAVAILABLE
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "[sign-macos-adhoc] re-signing: $APP_PATH"
|
|
||||||
codesign --force --deep --sign - "$APP_PATH"
|
|
||||||
|
|
||||||
echo "[sign-macos-adhoc] verifying signature"
|
|
||||||
codesign --verify --deep --strict "$APP_PATH"
|
|
||||||
|
|
||||||
echo "[sign-macos-adhoc] OK"
|
|
||||||
echo ""
|
|
||||||
echo "Next:"
|
|
||||||
echo " ditto -c -k --keepParent \"$APP_PATH\" \"${APP_PATH%.app}.zip\""
|
|
||||||
echo " # Distribute the .zip, NOT a .dmg, for the pilot."
|
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,202 +0,0 @@
|
|||||||
<#
|
|
||||||
.SYNOPSIS
|
|
||||||
Self-sign cert generation + signtool wrapper for the Wave-1 Egzakta-internal pilot build.
|
|
||||||
|
|
||||||
.DESCRIPTION
|
|
||||||
Implements docs/code-signing-pilot-and-launch.md §1.1 (Windows self-sign).
|
|
||||||
Two modes:
|
|
||||||
|
|
||||||
-Mode Setup Generate self-signed cert (idempotent — reuses existing cert
|
|
||||||
by subject if it exists), export to .pfx, write thumbprint
|
|
||||||
to app/src-tauri/.thumbprint.txt.
|
|
||||||
-Mode Sign Sign the artefact at -ArtifactPath using the cert produced
|
|
||||||
by Setup. Wraps signtool.exe.
|
|
||||||
|
|
||||||
Password resolution order (Setup): env WAGGLE_PILOT_PFX_PASSWORD; otherwise
|
|
||||||
Read-Host -AsSecureString prompt. Setup writes the .pfx to %USERPROFILE%
|
|
||||||
so it never lands inside the repo working tree.
|
|
||||||
|
|
||||||
NOT for public Day-0 signing — that uses a real EV Authenticode cert per §2.
|
|
||||||
|
|
||||||
.PARAMETER Mode
|
|
||||||
Setup or Sign. Setup is idempotent — safe to re-run.
|
|
||||||
|
|
||||||
.PARAMETER ArtifactPath
|
|
||||||
Required when -Mode Sign. Path to the .msi or .exe to sign.
|
|
||||||
|
|
||||||
.PARAMETER Subject
|
|
||||||
Cert subject. Default: "CN=Egzakta Internal Pilot, O=Egzakta Group, C=RS".
|
|
||||||
Override only if rotating cert identity.
|
|
||||||
|
|
||||||
.PARAMETER PfxPath
|
|
||||||
Where to write the exported .pfx. Default:
|
|
||||||
$env:USERPROFILE\waggle-pilot-codesign.pfx
|
|
||||||
|
|
||||||
.PARAMETER ThumbprintFile
|
|
||||||
Where to write the captured thumbprint for downstream consumption by
|
|
||||||
apply-signing-config.mjs. Default: app/src-tauri/.thumbprint.txt
|
|
||||||
(relative to repo root, resolved via this script's location).
|
|
||||||
|
|
||||||
.PARAMETER TimestampUrl
|
|
||||||
RFC3161 timestamp server. Default: http://timestamp.digicert.com.
|
|
||||||
|
|
||||||
.EXAMPLE
|
|
||||||
PS> $env:WAGGLE_PILOT_PFX_PASSWORD = "your-strong-pw"
|
|
||||||
PS> .\sign-windows-pilot.ps1 -Mode Setup
|
|
||||||
Generates cert (or reuses existing), writes thumbprint to .thumbprint.txt.
|
|
||||||
|
|
||||||
.EXAMPLE
|
|
||||||
PS> .\sign-windows-pilot.ps1 -Mode Sign -ArtifactPath .\target\release\bundle\msi\Waggle_0.2.0_x64_en-US.msi
|
|
||||||
Signs the MSI using the cert from Setup.
|
|
||||||
|
|
||||||
.NOTES
|
|
||||||
Last updated: LAUNCH-06 (Phase 2 Step 4).
|
|
||||||
#>
|
|
||||||
|
|
||||||
[CmdletBinding()]
|
|
||||||
param(
|
|
||||||
[Parameter(Mandatory = $true)]
|
|
||||||
[ValidateSet('Setup', 'Sign')]
|
|
||||||
[string]$Mode,
|
|
||||||
|
|
||||||
[Parameter()]
|
|
||||||
[string]$ArtifactPath,
|
|
||||||
|
|
||||||
[Parameter()]
|
|
||||||
[string]$Subject = 'CN=Egzakta Internal Pilot, O=Egzakta Group, C=RS',
|
|
||||||
|
|
||||||
[Parameter()]
|
|
||||||
[string]$PfxPath = (Join-Path $env:USERPROFILE 'waggle-pilot-codesign.pfx'),
|
|
||||||
|
|
||||||
[Parameter()]
|
|
||||||
[string]$ThumbprintFile,
|
|
||||||
|
|
||||||
[Parameter()]
|
|
||||||
[string]$TimestampUrl = 'http://timestamp.digicert.com'
|
|
||||||
)
|
|
||||||
|
|
||||||
$ErrorActionPreference = 'Stop'
|
|
||||||
|
|
||||||
# ─── Resolve repo-root paths ────────────────────────────────────────────────
|
|
||||||
|
|
||||||
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
|
||||||
$AppDir = Split-Path -Parent $ScriptDir # ...\waggle-os\app
|
|
||||||
$RepoRoot = Split-Path -Parent $AppDir # ...\waggle-os
|
|
||||||
|
|
||||||
if (-not $ThumbprintFile) {
|
|
||||||
$ThumbprintFile = Join-Path $AppDir 'src-tauri\.thumbprint.txt'
|
|
||||||
}
|
|
||||||
|
|
||||||
# ─── Helpers ────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function Resolve-Password {
|
|
||||||
if ($env:WAGGLE_PILOT_PFX_PASSWORD) {
|
|
||||||
return ConvertTo-SecureString -String $env:WAGGLE_PILOT_PFX_PASSWORD -Force -AsPlainText
|
|
||||||
}
|
|
||||||
Write-Host 'WAGGLE_PILOT_PFX_PASSWORD not set in env — prompting.' -ForegroundColor Yellow
|
|
||||||
return Read-Host -Prompt 'Enter password to protect the .pfx export' -AsSecureString
|
|
||||||
}
|
|
||||||
|
|
||||||
function Find-Signtool {
|
|
||||||
# Prefer signtool from latest installed Windows SDK; fall back to PATH.
|
|
||||||
$candidates = @(
|
|
||||||
'C:\Program Files (x86)\Windows Kits\10\bin\10.0.22621.0\x64\signtool.exe',
|
|
||||||
'C:\Program Files (x86)\Windows Kits\10\bin\10.0.22000.0\x64\signtool.exe',
|
|
||||||
'C:\Program Files (x86)\Windows Kits\10\bin\10.0.19041.0\x64\signtool.exe'
|
|
||||||
)
|
|
||||||
foreach ($candidate in $candidates) {
|
|
||||||
if (Test-Path $candidate) { return $candidate }
|
|
||||||
}
|
|
||||||
$fromPath = Get-Command signtool.exe -ErrorAction SilentlyContinue
|
|
||||||
if ($fromPath) { return $fromPath.Source }
|
|
||||||
throw 'signtool.exe not found. Install Windows 10 SDK or add signtool to PATH.'
|
|
||||||
}
|
|
||||||
|
|
||||||
# ─── Mode: Setup ────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
if ($Mode -eq 'Setup') {
|
|
||||||
Write-Host "[setup] subject: $Subject"
|
|
||||||
Write-Host "[setup] pfx path: $PfxPath"
|
|
||||||
Write-Host "[setup] thumbprint out: $ThumbprintFile"
|
|
||||||
|
|
||||||
# Reuse existing cert by subject if present (idempotency).
|
|
||||||
$existing = Get-ChildItem 'Cert:\CurrentUser\My' |
|
|
||||||
Where-Object { $_.Subject -eq $Subject -and $_.HasPrivateKey } |
|
|
||||||
Sort-Object NotAfter -Descending |
|
|
||||||
Select-Object -First 1
|
|
||||||
|
|
||||||
if ($existing -and $existing.NotAfter -gt (Get-Date)) {
|
|
||||||
Write-Host "[setup] reusing existing cert (NotAfter $($existing.NotAfter))" -ForegroundColor Green
|
|
||||||
$cert = $existing
|
|
||||||
} else {
|
|
||||||
Write-Host '[setup] generating new self-signed code-signing cert' -ForegroundColor Cyan
|
|
||||||
$cert = New-SelfSignedCertificate `
|
|
||||||
-Type CodeSigningCert `
|
|
||||||
-Subject $Subject `
|
|
||||||
-KeyUsage DigitalSignature `
|
|
||||||
-KeySpec Signature `
|
|
||||||
-KeyAlgorithm RSA -KeyLength 2048 `
|
|
||||||
-NotAfter (Get-Date).AddYears(2) `
|
|
||||||
-CertStoreLocation 'Cert:\CurrentUser\My' `
|
|
||||||
-TextExtension @('2.5.29.37={text}1.3.6.1.5.5.7.3.3', '2.5.29.19={text}')
|
|
||||||
}
|
|
||||||
|
|
||||||
# Export .pfx (always — re-export is harmless and refreshes the file).
|
|
||||||
$pwd = Resolve-Password
|
|
||||||
Export-PfxCertificate -Cert $cert -FilePath $PfxPath -Password $pwd | Out-Null
|
|
||||||
Write-Host "[setup] exported .pfx -> $PfxPath" -ForegroundColor Green
|
|
||||||
|
|
||||||
# Write thumbprint where apply-signing-config.mjs expects it.
|
|
||||||
$thumbprintDir = Split-Path -Parent $ThumbprintFile
|
|
||||||
if (-not (Test-Path $thumbprintDir)) {
|
|
||||||
New-Item -ItemType Directory -Force -Path $thumbprintDir | Out-Null
|
|
||||||
}
|
|
||||||
Set-Content -Path $ThumbprintFile -Value $cert.Thumbprint -Encoding ascii -NoNewline
|
|
||||||
Write-Host "[setup] thumbprint -> $ThumbprintFile" -ForegroundColor Green
|
|
||||||
Write-Host ''
|
|
||||||
Write-Host 'Next:' -ForegroundColor Cyan
|
|
||||||
Write-Host ' 1. npm run tauri:build:win:pilot-signed'
|
|
||||||
Write-Host ' 2. .\scripts\sign-windows-pilot.ps1 -Mode Sign -ArtifactPath <path-to-msi> # optional'
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
# ─── Mode: Sign ─────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
if ($Mode -eq 'Sign') {
|
|
||||||
if (-not $ArtifactPath) {
|
|
||||||
throw '-ArtifactPath required when -Mode Sign'
|
|
||||||
}
|
|
||||||
if (-not (Test-Path $ArtifactPath)) {
|
|
||||||
throw "Artifact not found: $ArtifactPath"
|
|
||||||
}
|
|
||||||
if (-not (Test-Path $PfxPath)) {
|
|
||||||
throw "PFX not found at $PfxPath. Run -Mode Setup first."
|
|
||||||
}
|
|
||||||
|
|
||||||
$signtool = Find-Signtool
|
|
||||||
$pwd = Resolve-Password
|
|
||||||
$plainPwd = [System.Net.NetworkCredential]::new('', $pwd).Password
|
|
||||||
|
|
||||||
Write-Host "[sign] signtool: $signtool"
|
|
||||||
Write-Host "[sign] artifact: $ArtifactPath"
|
|
||||||
|
|
||||||
& $signtool sign `
|
|
||||||
/f $PfxPath `
|
|
||||||
/p $plainPwd `
|
|
||||||
/tr $TimestampUrl `
|
|
||||||
/td sha256 /fd sha256 `
|
|
||||||
$ArtifactPath
|
|
||||||
|
|
||||||
if ($LASTEXITCODE -ne 0) {
|
|
||||||
throw "signtool failed with exit code $LASTEXITCODE"
|
|
||||||
}
|
|
||||||
|
|
||||||
Write-Host '[sign] verifying signature' -ForegroundColor Cyan
|
|
||||||
& $signtool verify /pa /v $ArtifactPath
|
|
||||||
if ($LASTEXITCODE -ne 0) {
|
|
||||||
throw "signtool verify failed with exit code $LASTEXITCODE"
|
|
||||||
}
|
|
||||||
|
|
||||||
Write-Host '[sign] OK' -ForegroundColor Green
|
|
||||||
return
|
|
||||||
}
|
|
||||||
@@ -1,346 +0,0 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
|
||||||
import { spawnSync } from 'node:child_process';
|
|
||||||
import { dirname, resolve } from 'node:path';
|
|
||||||
import { fileURLToPath } from 'node:url';
|
|
||||||
import {
|
|
||||||
parseThumbprintString,
|
|
||||||
addWindowsArtifactSigningToOverride,
|
|
||||||
addWindowsSigningToOverride,
|
|
||||||
addMacosAdhocToOverride,
|
|
||||||
type TauriOverrideConfig,
|
|
||||||
} from './signing-config.js';
|
|
||||||
|
|
||||||
// ─── parseThumbprintString ──────────────────────────────────────────────────
|
|
||||||
|
|
||||||
describe('parseThumbprintString', () => {
|
|
||||||
it('returns the uppercased thumbprint when given valid 40-hex input', () => {
|
|
||||||
const raw = 'abcdef0123456789abcdef0123456789abcdef01';
|
|
||||||
expect(parseThumbprintString(raw)).toBe(
|
|
||||||
'ABCDEF0123456789ABCDEF0123456789ABCDEF01',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('strips surrounding whitespace and trailing newline (PowerShell output shape)', () => {
|
|
||||||
const raw = ' ABCDEF0123456789ABCDEF0123456789ABCDEF01\r\n';
|
|
||||||
expect(parseThumbprintString(raw)).toBe(
|
|
||||||
'ABCDEF0123456789ABCDEF0123456789ABCDEF01',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('removes embedded whitespace inside the thumbprint (some clipboards introduce spaces)', () => {
|
|
||||||
const raw = 'AB CD EF 01 23 45 67 89 AB CD EF 01 23 45 67 89 AB CD EF 01';
|
|
||||||
expect(parseThumbprintString(raw)).toBe(
|
|
||||||
'ABCDEF0123456789ABCDEF0123456789ABCDEF01',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when the thumbprint is shorter than 40 chars', () => {
|
|
||||||
expect(() => parseThumbprintString('ABCDEF')).toThrow(
|
|
||||||
/must be 40 hex characters/i,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when the thumbprint contains non-hex characters', () => {
|
|
||||||
const raw = 'ZZCDEF0123456789ABCDEF0123456789ABCDEF01';
|
|
||||||
expect(() => parseThumbprintString(raw)).toThrow(/must be 40 hex characters/i);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws on empty input', () => {
|
|
||||||
expect(() => parseThumbprintString('')).toThrow(/empty/i);
|
|
||||||
expect(() => parseThumbprintString(' ')).toThrow(/empty/i);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// ─── addWindowsSigningToOverride ────────────────────────────────────────────
|
|
||||||
|
|
||||||
describe('addWindowsSigningToOverride', () => {
|
|
||||||
const VALID_THUMBPRINT = 'ABCDEF0123456789ABCDEF0123456789ABCDEF01';
|
|
||||||
|
|
||||||
it('writes certificateThumbprint + sensible defaults when no options given', () => {
|
|
||||||
const input: TauriOverrideConfig = { build: { beforeBuildCommand: '' } };
|
|
||||||
const out = addWindowsSigningToOverride(input, VALID_THUMBPRINT);
|
|
||||||
|
|
||||||
expect(out.bundle?.windows?.certificateThumbprint).toBe(VALID_THUMBPRINT);
|
|
||||||
expect(out.bundle?.windows?.digestAlgorithm).toBe('sha256');
|
|
||||||
expect(out.bundle?.windows?.timestampUrl).toBe(
|
|
||||||
'http://timestamp.digicert.com',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('preserves existing top-level fields (build, app, etc.)', () => {
|
|
||||||
const input: TauriOverrideConfig = {
|
|
||||||
build: { beforeBuildCommand: 'echo hello' },
|
|
||||||
app: { security: { csp: 'default-src self' } },
|
|
||||||
};
|
|
||||||
const out = addWindowsSigningToOverride(input, VALID_THUMBPRINT);
|
|
||||||
|
|
||||||
expect(out.build).toEqual({ beforeBuildCommand: 'echo hello' });
|
|
||||||
expect(out.app).toEqual({ security: { csp: 'default-src self' } });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('preserves existing bundle.windows fields not related to signing', () => {
|
|
||||||
const input: TauriOverrideConfig = {
|
|
||||||
bundle: {
|
|
||||||
windows: { nsis: { installMode: 'currentUser' } },
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const out = addWindowsSigningToOverride(input, VALID_THUMBPRINT);
|
|
||||||
|
|
||||||
expect(out.bundle?.windows?.nsis).toEqual({ installMode: 'currentUser' });
|
|
||||||
expect(out.bundle?.windows?.certificateThumbprint).toBe(VALID_THUMBPRINT);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('removes an Azure signCommand when returning to certificate-store signing', () => {
|
|
||||||
const azure: TauriOverrideConfig = addWindowsArtifactSigningToOverride(
|
|
||||||
{
|
|
||||||
bundle: {
|
|
||||||
windows: { nsis: { installMode: 'currentUser' } },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
String.raw`D:\a\waggle-os\app\scripts\sign-windows-artifact.ps1`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const out = addWindowsSigningToOverride(azure, VALID_THUMBPRINT);
|
|
||||||
|
|
||||||
expect(out.bundle?.windows?.signCommand).toBeUndefined();
|
|
||||||
expect(out.bundle?.windows?.certificateThumbprint).toBe(VALID_THUMBPRINT);
|
|
||||||
expect(out.bundle?.windows?.nsis).toEqual({ installMode: 'currentUser' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('overrides custom digestAlgorithm and timestampUrl when options provided', () => {
|
|
||||||
const out = addWindowsSigningToOverride({}, VALID_THUMBPRINT, {
|
|
||||||
digestAlgorithm: 'sha384',
|
|
||||||
timestampUrl: 'http://timestamp.sectigo.com',
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(out.bundle?.windows?.digestAlgorithm).toBe('sha384');
|
|
||||||
expect(out.bundle?.windows?.timestampUrl).toBe(
|
|
||||||
'http://timestamp.sectigo.com',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not mutate the input config (immutability invariant)', () => {
|
|
||||||
const input: TauriOverrideConfig = { build: { beforeBuildCommand: '' } };
|
|
||||||
const inputSnapshot = JSON.parse(JSON.stringify(input));
|
|
||||||
addWindowsSigningToOverride(input, VALID_THUMBPRINT);
|
|
||||||
expect(input).toEqual(inputSnapshot);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is idempotent — applying twice with the same thumbprint yields equal output', () => {
|
|
||||||
const input: TauriOverrideConfig = {};
|
|
||||||
const once = addWindowsSigningToOverride(input, VALID_THUMBPRINT);
|
|
||||||
const twice = addWindowsSigningToOverride(once, VALID_THUMBPRINT);
|
|
||||||
expect(twice).toEqual(once);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('replaces an old thumbprint when called with a new one (cert rotation)', () => {
|
|
||||||
const input: TauriOverrideConfig = {};
|
|
||||||
const v1 = addWindowsSigningToOverride(input, VALID_THUMBPRINT);
|
|
||||||
const newThumb = '1234567890ABCDEF1234567890ABCDEF12345678';
|
|
||||||
const v2 = addWindowsSigningToOverride(v1, newThumb);
|
|
||||||
expect(v2.bundle?.windows?.certificateThumbprint).toBe(newThumb);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects an invalid thumbprint up front', () => {
|
|
||||||
expect(() =>
|
|
||||||
addWindowsSigningToOverride({}, 'too-short'),
|
|
||||||
).toThrow(/must be 40 hex characters/i);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// ─── addWindowsArtifactSigningToOverride ───────────────────────────────────
|
|
||||||
|
|
||||||
describe('addWindowsArtifactSigningToOverride', () => {
|
|
||||||
const WRAPPER_PATH = String.raw`D:\a\waggle-os\app\scripts\sign-windows-artifact.ps1`;
|
|
||||||
const SYSTEM_POWERSHELL_PATH =
|
|
||||||
String.raw`C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`;
|
|
||||||
|
|
||||||
it('configures an object-form Tauri signCommand with one artifact placeholder', () => {
|
|
||||||
const out = addWindowsArtifactSigningToOverride(
|
|
||||||
{},
|
|
||||||
WRAPPER_PATH,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(out.bundle?.windows?.signCommand).toEqual({
|
|
||||||
cmd: SYSTEM_POWERSHELL_PATH,
|
|
||||||
args: [
|
|
||||||
'-NoLogo',
|
|
||||||
'-NoProfile',
|
|
||||||
'-NonInteractive',
|
|
||||||
'-ExecutionPolicy',
|
|
||||||
'Bypass',
|
|
||||||
'-File',
|
|
||||||
WRAPPER_PATH,
|
|
||||||
'-ArtifactPath',
|
|
||||||
'%1',
|
|
||||||
],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('removes mutually exclusive certificate-store signing fields', () => {
|
|
||||||
const input: TauriOverrideConfig = {
|
|
||||||
bundle: {
|
|
||||||
windows: {
|
|
||||||
certificateThumbprint: 'AB'.repeat(20),
|
|
||||||
digestAlgorithm: 'sha256',
|
|
||||||
timestampUrl: 'http://timestamp.digicert.com',
|
|
||||||
tsp: true,
|
|
||||||
nsis: { installMode: 'currentUser' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const out = addWindowsArtifactSigningToOverride(
|
|
||||||
input,
|
|
||||||
WRAPPER_PATH,
|
|
||||||
);
|
|
||||||
expect(out.bundle?.windows?.certificateThumbprint).toBeUndefined();
|
|
||||||
expect(out.bundle?.windows?.digestAlgorithm).toBeUndefined();
|
|
||||||
expect(out.bundle?.windows?.timestampUrl).toBeUndefined();
|
|
||||||
expect(out.bundle?.windows?.tsp).toBeUndefined();
|
|
||||||
expect(out.bundle?.windows?.nsis).toEqual({ installMode: 'currentUser' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is immutable and idempotent', () => {
|
|
||||||
const input: TauriOverrideConfig = {
|
|
||||||
build: {
|
|
||||||
beforeBuildCommand: 'npm run build',
|
|
||||||
beforeBundleCommand: 'node mutate-bundle.mjs',
|
|
||||||
},
|
|
||||||
bundle: {
|
|
||||||
active: false,
|
|
||||||
targets: ['msi'],
|
|
||||||
windows: { nsis: { installMode: 'currentUser' } },
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const snapshot = JSON.parse(JSON.stringify(input));
|
|
||||||
const once = addWindowsArtifactSigningToOverride(
|
|
||||||
input,
|
|
||||||
WRAPPER_PATH,
|
|
||||||
);
|
|
||||||
const twice = addWindowsArtifactSigningToOverride(
|
|
||||||
once,
|
|
||||||
WRAPPER_PATH,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(input).toEqual(snapshot);
|
|
||||||
expect(twice).toEqual(once);
|
|
||||||
expect(once.build).toEqual({
|
|
||||||
beforeBuildCommand: '',
|
|
||||||
beforeBundleCommand: '',
|
|
||||||
});
|
|
||||||
expect(once.bundle?.active).toBe(true);
|
|
||||||
expect(once.bundle?.targets).toEqual(['nsis']);
|
|
||||||
expect(once.bundle?.windows?.nsis).toEqual({ installMode: 'currentUser' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects non-absolute, placeholder-bearing, or control-character wrapper paths', () => {
|
|
||||||
expect(() =>
|
|
||||||
addWindowsArtifactSigningToOverride(
|
|
||||||
{},
|
|
||||||
'scripts/sign.ps1',
|
|
||||||
),
|
|
||||||
).toThrow(/absolute Windows path/i);
|
|
||||||
expect(() =>
|
|
||||||
addWindowsArtifactSigningToOverride(
|
|
||||||
{},
|
|
||||||
String.raw`D:\a\%1\sign-windows-artifact.ps1`,
|
|
||||||
),
|
|
||||||
).toThrow(/placeholder/i);
|
|
||||||
expect(() =>
|
|
||||||
addWindowsArtifactSigningToOverride(
|
|
||||||
{},
|
|
||||||
'D:\\safe\nmalicious.ps1',
|
|
||||||
),
|
|
||||||
).toThrow(/control characters/i);
|
|
||||||
expect(() =>
|
|
||||||
addWindowsArtifactSigningToOverride(
|
|
||||||
{},
|
|
||||||
String.raw`D:\safe\..\malicious.ps1`,
|
|
||||||
),
|
|
||||||
).toThrow(/canonical local Windows/i);
|
|
||||||
expect(() =>
|
|
||||||
addWindowsArtifactSigningToOverride(
|
|
||||||
{},
|
|
||||||
String.raw`D:\safe\sign.ps1:payload`,
|
|
||||||
),
|
|
||||||
).toThrow(/canonical local Windows/i);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('contains exactly one artifact placeholder across the complete command', () => {
|
|
||||||
const out = addWindowsArtifactSigningToOverride({}, WRAPPER_PATH);
|
|
||||||
const command = out.bundle?.windows?.signCommand;
|
|
||||||
const placeholderCount = [command?.cmd, ...(command?.args ?? [])]
|
|
||||||
.flatMap((part) => part?.match(/%1/g) ?? [])
|
|
||||||
.length;
|
|
||||||
expect(placeholderCount).toBe(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('apply-signing-config Artifact Signing boundary', () => {
|
|
||||||
it('fails closed toward the protected hosted release workflow, never local Build mode', () => {
|
|
||||||
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
|
||||||
const result = spawnSync(
|
|
||||||
process.execPath,
|
|
||||||
[resolve(scriptDir, 'apply-signing-config.mjs')],
|
|
||||||
{
|
|
||||||
cwd: resolve(scriptDir, '..'),
|
|
||||||
env: { ...process.env, WAGGLE_WINDOWS_SIGNING_MODE: 'artifact-signing' },
|
|
||||||
encoding: 'utf8',
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const output = `${result.stdout}\n${result.stderr}`;
|
|
||||||
expect(result.status).not.toBe(0);
|
|
||||||
expect(output).toMatch(/protected GitHub-hosted release workflow/i);
|
|
||||||
expect(output).not.toMatch(/-Mode Build/i);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// ─── addMacosAdhocToOverride ────────────────────────────────────────────────
|
|
||||||
|
|
||||||
describe('addMacosAdhocToOverride', () => {
|
|
||||||
it('sets bundle.macOS.signingIdentity to "-" (ad-hoc sign sentinel)', () => {
|
|
||||||
const out = addMacosAdhocToOverride({});
|
|
||||||
expect(out.bundle?.macOS?.signingIdentity).toBe('-');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('preserves existing top-level and bundle fields', () => {
|
|
||||||
const input: TauriOverrideConfig = {
|
|
||||||
build: { beforeBuildCommand: 'echo' },
|
|
||||||
bundle: {
|
|
||||||
windows: { certificateThumbprint: 'AB'.repeat(20) },
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const out = addMacosAdhocToOverride(input);
|
|
||||||
|
|
||||||
expect(out.build).toEqual({ beforeBuildCommand: 'echo' });
|
|
||||||
expect(out.bundle?.windows?.certificateThumbprint).toBe('AB'.repeat(20));
|
|
||||||
expect(out.bundle?.macOS?.signingIdentity).toBe('-');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not mutate the input config', () => {
|
|
||||||
const input: TauriOverrideConfig = { bundle: { macOS: {} } };
|
|
||||||
const snapshot = JSON.parse(JSON.stringify(input));
|
|
||||||
addMacosAdhocToOverride(input);
|
|
||||||
expect(input).toEqual(snapshot);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is idempotent', () => {
|
|
||||||
const once = addMacosAdhocToOverride({});
|
|
||||||
const twice = addMacosAdhocToOverride(once);
|
|
||||||
expect(twice).toEqual(once);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('preserves additional macOS fields (entitlements, providerShortName)', () => {
|
|
||||||
const input: TauriOverrideConfig = {
|
|
||||||
bundle: {
|
|
||||||
macOS: { entitlements: './ent.plist', providerShortName: 'TEAM' },
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const out = addMacosAdhocToOverride(input);
|
|
||||||
|
|
||||||
expect(out.bundle?.macOS?.entitlements).toBe('./ent.plist');
|
|
||||||
expect(out.bundle?.macOS?.providerShortName).toBe('TEAM');
|
|
||||||
expect(out.bundle?.macOS?.signingIdentity).toBe('-');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,257 +0,0 @@
|
|||||||
/**
|
|
||||||
* signing-config.ts — Pure utilities for managing code-signing fields in
|
|
||||||
* Tauri's `tauri.build-override.conf.json`.
|
|
||||||
*
|
|
||||||
* Used by:
|
|
||||||
* - `apply-signing-config.mjs` (LAUNCH-06 pilot wiring)
|
|
||||||
* - `tauri:sign:pilot:win:apply` npm script
|
|
||||||
*
|
|
||||||
* No filesystem side effects — safe to import in tests. The thin CLI wrapper
|
|
||||||
* does the file I/O.
|
|
||||||
*
|
|
||||||
* Reference: docs/code-signing-pilot-and-launch.md §1.1 (Windows self-sign)
|
|
||||||
* docs/code-signing-pilot-and-launch.md §1.2 (macOS ad-hoc)
|
|
||||||
*/
|
|
||||||
|
|
||||||
// ─── Types ──────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface TauriBundleWindows {
|
|
||||||
certificateThumbprint?: string;
|
|
||||||
digestAlgorithm?: string;
|
|
||||||
signCommand?: TauriSignCommand;
|
|
||||||
timestampUrl?: string;
|
|
||||||
tsp?: boolean;
|
|
||||||
[key: string]: unknown;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TauriSignCommand {
|
|
||||||
cmd: string;
|
|
||||||
args: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TauriBundleMacOS {
|
|
||||||
signingIdentity?: string;
|
|
||||||
[key: string]: unknown;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TauriBundle {
|
|
||||||
windows?: TauriBundleWindows;
|
|
||||||
macOS?: TauriBundleMacOS;
|
|
||||||
[key: string]: unknown;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TauriOverrideConfig {
|
|
||||||
build?: Record<string, unknown>;
|
|
||||||
bundle?: TauriBundle;
|
|
||||||
[key: string]: unknown;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface WindowsSigningOptions {
|
|
||||||
digestAlgorithm?: string;
|
|
||||||
timestampUrl?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Defaults ───────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const DEFAULT_DIGEST_ALGORITHM = 'sha256';
|
|
||||||
const DEFAULT_TIMESTAMP_URL = 'http://timestamp.digicert.com';
|
|
||||||
const MACOS_ADHOC_IDENTITY = '-';
|
|
||||||
const THUMBPRINT_LENGTH = 40;
|
|
||||||
const HEX_PATTERN = /^[0-9A-F]+$/;
|
|
||||||
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
|
||||||
const WINDOWS_POWERSHELL_PATH =
|
|
||||||
String.raw`C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`;
|
|
||||||
|
|
||||||
function containsControlCharacter(value: string): boolean {
|
|
||||||
return [...value].some((character) => {
|
|
||||||
const codePoint = character.codePointAt(0) ?? 0;
|
|
||||||
return codePoint <= 31 || codePoint === 127;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertCanonicalWindowsFilePath(value: string): void {
|
|
||||||
if (containsControlCharacter(value)) {
|
|
||||||
throw new Error('Artifact Signing wrapper path contains control characters.');
|
|
||||||
}
|
|
||||||
if (!WINDOWS_ABSOLUTE_PATH_PATTERN.test(value)) {
|
|
||||||
throw new Error('Artifact Signing wrapper must use an absolute Windows path.');
|
|
||||||
}
|
|
||||||
const pathTail = value.slice(3);
|
|
||||||
const segments = pathTail.split(/[\\/]/);
|
|
||||||
if (
|
|
||||||
pathTail.length === 0
|
|
||||||
|| value.slice(2).includes(':')
|
|
||||||
|| segments.some(
|
|
||||||
(segment) => segment.length === 0
|
|
||||||
|| segment === '.'
|
|
||||||
|| segment === '..'
|
|
||||||
|| /[. ]$/.test(segment),
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
throw new Error('Artifact Signing wrapper must use a canonical local Windows file path.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── parseThumbprintString ──────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Normalise a raw thumbprint string into the canonical 40-char uppercase form.
|
|
||||||
*
|
|
||||||
* Accepts whitespace anywhere (tab, space, newline) since PowerShell's
|
|
||||||
* `$cert.Thumbprint` plus clipboard round-tripping can introduce arbitrary
|
|
||||||
* spacing. Throws when the result is not exactly 40 hex characters.
|
|
||||||
*/
|
|
||||||
export function parseThumbprintString(raw: string): string {
|
|
||||||
if (!raw || raw.trim().length === 0) {
|
|
||||||
throw new Error('Thumbprint is empty — cert generation may have failed.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const compact = raw.replace(/\s+/g, '').toUpperCase();
|
|
||||||
|
|
||||||
if (compact.length !== THUMBPRINT_LENGTH || !HEX_PATTERN.test(compact)) {
|
|
||||||
throw new Error(
|
|
||||||
`Thumbprint must be 40 hex characters; got ${compact.length} chars (sample: "${compact.slice(0, 16)}...").`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return compact;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── addWindowsSigningToOverride ────────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return a new override config with Windows code-signing fields applied.
|
|
||||||
*
|
|
||||||
* Preserves all existing top-level and bundle fields; replaces only the
|
|
||||||
* signing-specific keys under `bundle.windows`. Idempotent — calling
|
|
||||||
* twice with the same thumbprint yields an equal result.
|
|
||||||
*/
|
|
||||||
export function addWindowsSigningToOverride<T extends TauriOverrideConfig>(
|
|
||||||
config: Readonly<T>,
|
|
||||||
thumbprint: string,
|
|
||||||
options?: WindowsSigningOptions,
|
|
||||||
): T {
|
|
||||||
const normalisedThumbprint = parseThumbprintString(thumbprint);
|
|
||||||
const digestAlgorithm = options?.digestAlgorithm ?? DEFAULT_DIGEST_ALGORITHM;
|
|
||||||
const timestampUrl = options?.timestampUrl ?? DEFAULT_TIMESTAMP_URL;
|
|
||||||
|
|
||||||
const existingBundle: TauriBundle = config.bundle ?? {};
|
|
||||||
const existingWindows: TauriBundleWindows = existingBundle.windows ?? {};
|
|
||||||
const nonCustomCommandWindows: TauriBundleWindows = { ...existingWindows };
|
|
||||||
delete nonCustomCommandWindows.signCommand;
|
|
||||||
|
|
||||||
const nextWindows: TauriBundleWindows = {
|
|
||||||
...nonCustomCommandWindows,
|
|
||||||
certificateThumbprint: normalisedThumbprint,
|
|
||||||
digestAlgorithm,
|
|
||||||
timestampUrl,
|
|
||||||
};
|
|
||||||
|
|
||||||
const nextBundle: TauriBundle = {
|
|
||||||
...existingBundle,
|
|
||||||
windows: nextWindows,
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
...config,
|
|
||||||
bundle: nextBundle,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── addWindowsArtifactSigningToOverride ───────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return a new override config that delegates every Tauri Windows signing
|
|
||||||
* target to the fail-closed Azure Artifact Signing wrapper.
|
|
||||||
*
|
|
||||||
* Tauri replaces `%1` with each binary path. Object form keeps the absolute
|
|
||||||
* wrapper path intact when the checkout contains spaces. Certificate-store
|
|
||||||
* fields are removed because Tauri must not combine them with `signCommand`.
|
|
||||||
*/
|
|
||||||
export function addWindowsArtifactSigningToOverride<
|
|
||||||
T extends TauriOverrideConfig,
|
|
||||||
>(config: Readonly<T>, wrapperPath: string): T {
|
|
||||||
assertCanonicalWindowsFilePath(wrapperPath);
|
|
||||||
if (wrapperPath.includes('%1')) {
|
|
||||||
throw new Error('Artifact Signing wrapper path cannot contain the %1 placeholder.');
|
|
||||||
}
|
|
||||||
const existingBuild = config.build ?? {};
|
|
||||||
const existingBundle: TauriBundle = config.bundle ?? {};
|
|
||||||
const existingWindows: TauriBundleWindows = existingBundle.windows ?? {};
|
|
||||||
const nonSigningWindows: TauriBundleWindows = { ...existingWindows };
|
|
||||||
delete nonSigningWindows.certificateThumbprint;
|
|
||||||
delete nonSigningWindows.digestAlgorithm;
|
|
||||||
delete nonSigningWindows.timestampUrl;
|
|
||||||
delete nonSigningWindows.tsp;
|
|
||||||
|
|
||||||
const nextWindows: TauriBundleWindows = {
|
|
||||||
...nonSigningWindows,
|
|
||||||
signCommand: {
|
|
||||||
cmd: WINDOWS_POWERSHELL_PATH,
|
|
||||||
args: [
|
|
||||||
'-NoLogo',
|
|
||||||
'-NoProfile',
|
|
||||||
'-NonInteractive',
|
|
||||||
'-ExecutionPolicy',
|
|
||||||
'Bypass',
|
|
||||||
'-File',
|
|
||||||
wrapperPath,
|
|
||||||
'-ArtifactPath',
|
|
||||||
'%1',
|
|
||||||
],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const placeholderCount = [
|
|
||||||
nextWindows.signCommand?.cmd,
|
|
||||||
...(nextWindows.signCommand?.args ?? []),
|
|
||||||
].flatMap((part) => part?.match(/%1/g) ?? []).length;
|
|
||||||
if (placeholderCount !== 1) {
|
|
||||||
throw new Error('Artifact Signing command must contain exactly one %1 placeholder.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...config,
|
|
||||||
build: {
|
|
||||||
...existingBuild,
|
|
||||||
beforeBuildCommand: '',
|
|
||||||
beforeBundleCommand: '',
|
|
||||||
},
|
|
||||||
bundle: {
|
|
||||||
...existingBundle,
|
|
||||||
active: true,
|
|
||||||
targets: ['nsis'],
|
|
||||||
windows: nextWindows,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── addMacosAdhocToOverride ────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return a new override config with macOS ad-hoc signing applied.
|
|
||||||
*
|
|
||||||
* Sets `bundle.macOS.signingIdentity` to "-" (Tauri / codesign sentinel for
|
|
||||||
* ad-hoc sign). Preserves all other fields. Used during pilot before a real
|
|
||||||
* Apple Developer ID cert is procured.
|
|
||||||
*/
|
|
||||||
export function addMacosAdhocToOverride<T extends TauriOverrideConfig>(
|
|
||||||
config: Readonly<T>,
|
|
||||||
): T {
|
|
||||||
const existingBundle: TauriBundle = config.bundle ?? {};
|
|
||||||
const existingMacOS: TauriBundleMacOS = existingBundle.macOS ?? {};
|
|
||||||
|
|
||||||
const nextMacOS: TauriBundleMacOS = {
|
|
||||||
...existingMacOS,
|
|
||||||
signingIdentity: MACOS_ADHOC_IDENTITY,
|
|
||||||
};
|
|
||||||
|
|
||||||
const nextBundle: TauriBundle = {
|
|
||||||
...existingBundle,
|
|
||||||
macOS: nextMacOS,
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
...config,
|
|
||||||
bundle: nextBundle,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -55,9 +55,8 @@ pub fn run() {
|
|||||||
commands::onboarding::reset_first_launch,
|
commands::onboarding::reset_first_launch,
|
||||||
])
|
])
|
||||||
.setup(|app| {
|
.setup(|app| {
|
||||||
// Create the configured window here so the Windows certifier can
|
// The main window is configured with `create: false` and built
|
||||||
// opt into a loopback-only WebView CDP port without shipping
|
// here, before the tray, the shortcut and the sidecar start.
|
||||||
// remote debugging enabled for normal launches.
|
|
||||||
let main_window_config = app
|
let main_window_config = app
|
||||||
.config()
|
.config()
|
||||||
.app
|
.app
|
||||||
@@ -71,35 +70,7 @@ pub fn run() {
|
|||||||
"configured main window is missing",
|
"configured main window is missing",
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let mut main_window = tauri::WebviewWindowBuilder::from_config(
|
tauri::WebviewWindowBuilder::from_config(app.handle(), &main_window_config)?.build()?;
|
||||||
app.handle(),
|
|
||||||
&main_window_config,
|
|
||||||
)?;
|
|
||||||
#[cfg(windows)]
|
|
||||||
if let Some(raw_port) = std::env::var_os("WAGGLE_CERTIFIER_WEBVIEW_DEBUG_PORT") {
|
|
||||||
let raw_port = raw_port.to_string_lossy();
|
|
||||||
let port = raw_port.parse::<u16>().map_err(|_| {
|
|
||||||
std::io::Error::new(
|
|
||||||
std::io::ErrorKind::InvalidInput,
|
|
||||||
"WAGGLE_CERTIFIER_WEBVIEW_DEBUG_PORT must be an integer",
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
if port < 1024 {
|
|
||||||
return Err(std::io::Error::new(
|
|
||||||
std::io::ErrorKind::InvalidInput,
|
|
||||||
"WAGGLE_CERTIFIER_WEBVIEW_DEBUG_PORT must be >= 1024",
|
|
||||||
)
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
let browser_args = format!(
|
|
||||||
"--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --remote-debugging-port={port}"
|
|
||||||
);
|
|
||||||
main_window = main_window.additional_browser_args(&browser_args);
|
|
||||||
eprintln!(
|
|
||||||
"[waggle] WebView certifier debug endpoint enabled on 127.0.0.1:{port}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
main_window.build()?;
|
|
||||||
|
|
||||||
tray::setup_tray(app.handle())?;
|
tray::setup_tray(app.handle())?;
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
{
|
|
||||||
"build": {
|
|
||||||
"beforeBuildCommand": ""
|
|
||||||
},
|
|
||||||
"bundle": {
|
|
||||||
"macOS": {
|
|
||||||
"signingIdentity": "-"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,8 +8,9 @@
|
|||||||
*
|
*
|
||||||
* Release flow:
|
* Release flow:
|
||||||
* git tag v1.0.1 && git push --tags
|
* git tag v1.0.1 && git push --tags
|
||||||
* This triggers release.yml which builds + signs + publishes to GitHub Releases.
|
* This triggers release.yml, which builds and smoke-tests unsigned installers
|
||||||
* Tauri updater fetches latest.json from the release assets.
|
* for Windows, macOS and Linux and creates a draft GitHub release. There is
|
||||||
|
* no update manifest while the updater is disabled.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect } from 'vitest';
|
||||||
@@ -101,6 +102,10 @@ describe('auto-update configuration', () => {
|
|||||||
expect(workflow).toContain('x86_64-apple-darwin');
|
expect(workflow).toContain('x86_64-apple-darwin');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('builds for Linux', () => {
|
||||||
|
expect(workflow).toContain('x86_64-unknown-linux-gnu');
|
||||||
|
});
|
||||||
|
|
||||||
it('uses the app-lockfile-pinned Tauri CLI for builds', () => {
|
it('uses the app-lockfile-pinned Tauri CLI for builds', () => {
|
||||||
expect(workflow).toContain('node node_modules/@tauri-apps/cli/tauri.js build');
|
expect(workflow).toContain('node node_modules/@tauri-apps/cli/tauri.js build');
|
||||||
expect(workflow).not.toMatch(/^\s*uses:\s+tauri-apps\/tauri-action/m);
|
expect(workflow).not.toMatch(/^\s*uses:\s+tauri-apps\/tauri-action/m);
|
||||||
|
|||||||
@@ -5,8 +5,10 @@ branch. The build has to run on Windows: the packaging scripts take the bundled
|
|||||||
runtime and the native modules (better-sqlite3, onnxruntime) from the machine they run on,
|
runtime and the native modules (better-sqlite3, onnxruntime) from the machine they run on,
|
||||||
so a build made on macOS would ship macOS binaries.
|
so a build made on macOS would ship macOS binaries.
|
||||||
|
|
||||||
The community edition has not been built on Windows yet. The first build is part of the
|
The release workflow (`.github/workflows/release.yml`) runs the same build on GitHub's
|
||||||
week 3 acceptance; record what fails in `docs/oss/upstream-fixes.md` or `docs/oss/baseline.md`.
|
`windows-latest` runner for every `v*` tag and for pull requests that touch the desktop app.
|
||||||
|
It has not run yet; the first build is part of the week 3 acceptance. Record what fails in
|
||||||
|
`docs/oss/upstream-fixes.md` or `docs/oss/baseline.md`.
|
||||||
|
|
||||||
## 1. Prepare the machine
|
## 1. Prepare the machine
|
||||||
|
|
||||||
@@ -74,8 +76,8 @@ copies the native modules, builds the web UI and then the Tauri shell. The first
|
|||||||
the Rust shell from scratch and takes much longer than later runs.
|
the Rust shell from scratch and takes much longer than later runs.
|
||||||
|
|
||||||
`--bundles nsis` builds only the NSIS installer, the one the app is configured for (a
|
`--bundles nsis` builds only the NSIS installer, the one the app is configured for (a
|
||||||
per-user install without administrator rights); CI builds the same. Without the flag Tauri
|
per-user install without administrator rights). Without the flag Tauri also builds an MSI,
|
||||||
also builds an MSI, for which it downloads WiX.
|
for which it downloads WiX; the release workflow builds both (`--bundles nsis,msi`).
|
||||||
|
|
||||||
The installer:
|
The installer:
|
||||||
|
|
||||||
@@ -83,6 +85,27 @@ The installer:
|
|||||||
app\src-tauri\target\x86_64-pc-windows-msvc\release\bundle\nsis\Waggle_0.2.0_x64-setup.exe
|
app\src-tauri\target\x86_64-pc-windows-msvc\release\bundle\nsis\Waggle_0.2.0_x64-setup.exe
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The same staged files make the server archive that the installer tool
|
||||||
|
(`packages/launcher`) installs. To build it and run the release workflow's smoke tests:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd C:\w\waggle-os
|
||||||
|
npm run build --workspace @waggle-ai/waggle
|
||||||
|
node scripts/build-server-archive.mjs
|
||||||
|
node scripts/release-smoke.mjs installer
|
||||||
|
```
|
||||||
|
|
||||||
|
The archive is `artifacts\waggle-server-<version>-windows-x64.tar.gz`. The installer test
|
||||||
|
installs it into a temporary folder, runs `doctor`, starts the server on a free port and
|
||||||
|
uninstalls it.
|
||||||
|
|
||||||
|
After installing the app (section 4), the desktop test starts it, waits until its sidecar
|
||||||
|
answers on port 3333, then stops both. Close Waggle first so the port is free:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node scripts/release-smoke.mjs desktop --app "$env:LOCALAPPDATA\Waggle\waggle.exe"
|
||||||
|
```
|
||||||
|
|
||||||
## 4. Check the result
|
## 4. Check the result
|
||||||
|
|
||||||
1. Run the installer. It is not signed, so SmartScreen shows "Windows protected your PC":
|
1. Run the installer. It is not signed, so SmartScreen shows "Windows protected your PC":
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,918 +0,0 @@
|
|||||||
[CmdletBinding()]
|
|
||||||
param(
|
|
||||||
[Parameter(Mandatory)]
|
|
||||||
[ValidateSet('bootstrap', 'upgrade')]
|
|
||||||
[string]$Mode
|
|
||||||
)
|
|
||||||
|
|
||||||
Set-StrictMode -Version Latest
|
|
||||||
$ErrorActionPreference = 'Stop'
|
|
||||||
|
|
||||||
function Assert-RemoteTagCommit {
|
|
||||||
param([string]$Tag, [string]$ExpectedCommit)
|
|
||||||
|
|
||||||
$remoteTagLines = @(
|
|
||||||
git ls-remote --tags origin "refs/tags/$Tag" "refs/tags/$Tag^{}"
|
|
||||||
)
|
|
||||||
if ($LASTEXITCODE -ne 0 -or $remoteTagLines.Count -eq 0) {
|
|
||||||
throw "Could not resolve remote release tag $Tag"
|
|
||||||
}
|
|
||||||
$resolvedTagLine = @(
|
|
||||||
$remoteTagLines |
|
|
||||||
Where-Object { $_ -match '\^\{\}$' } |
|
|
||||||
Select-Object -First 1
|
|
||||||
)
|
|
||||||
if ($resolvedTagLine.Count -eq 0) {
|
|
||||||
$resolvedTagLine = @($remoteTagLines | Select-Object -First 1)
|
|
||||||
}
|
|
||||||
$remoteTagSha = (
|
|
||||||
[regex]::Split(([string]$resolvedTagLine[0]).Trim(), '\s+')
|
|
||||||
)[0]
|
|
||||||
if (-not [string]::Equals(
|
|
||||||
$remoteTagSha,
|
|
||||||
$ExpectedCommit,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
)) {
|
|
||||||
throw "Remote release tag $Tag no longer resolves to the certified commit"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-ProtectedSignerIdentity {
|
|
||||||
$approvedSubject = [string]$env:WINDOWS_CODESIGN_APPROVED_SUBJECT
|
|
||||||
$approvedThumbprint = [string]$env:WINDOWS_CODESIGN_APPROVED_THUMBPRINT
|
|
||||||
$hasApprovedSubject = -not [string]::IsNullOrWhiteSpace($approvedSubject)
|
|
||||||
$hasApprovedThumbprint = -not [string]::IsNullOrWhiteSpace($approvedThumbprint)
|
|
||||||
if ($hasApprovedSubject -eq $hasApprovedThumbprint) {
|
|
||||||
throw 'Exactly one protected publication signer identity must be configured'
|
|
||||||
}
|
|
||||||
if ($hasApprovedSubject) {
|
|
||||||
return [pscustomobject][ordered]@{
|
|
||||||
mode = 'subject'
|
|
||||||
subject = $approvedSubject
|
|
||||||
thumbprint = $null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$normalizedThumbprint = ($approvedThumbprint -replace '\s', '').ToUpperInvariant()
|
|
||||||
if ($normalizedThumbprint -notmatch '^[0-9A-F]{40}$') {
|
|
||||||
throw 'Protected publication signer thumbprint is invalid'
|
|
||||||
}
|
|
||||||
return [pscustomobject][ordered]@{
|
|
||||||
mode = 'thumbprint'
|
|
||||||
subject = $null
|
|
||||||
thumbprint = $normalizedThumbprint
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-ExpectedAuthenticodeSignature {
|
|
||||||
param([System.IO.FileInfo]$Artifact, [object]$ExpectedIdentity)
|
|
||||||
|
|
||||||
$signature = Get-AuthenticodeSignature -FilePath $Artifact.FullName
|
|
||||||
if ($signature.Status -ne 'Valid' -or
|
|
||||||
[string]$signature.SignatureType -ne 'Authenticode' -or
|
|
||||||
$null -eq $signature.SignerCertificate -or
|
|
||||||
$null -eq $signature.TimeStamperCertificate) {
|
|
||||||
throw "Artifact signature is no longer valid for the approved signer: $($Artifact.FullName)"
|
|
||||||
}
|
|
||||||
$signerSubject = [string]$signature.SignerCertificate.Subject
|
|
||||||
$signerThumbprint = (
|
|
||||||
[string]$signature.SignerCertificate.Thumbprint -replace '\s', ''
|
|
||||||
).ToUpperInvariant()
|
|
||||||
$matchesProtectedIdentity = if ($ExpectedIdentity.mode -ceq 'subject') {
|
|
||||||
[string]::Equals(
|
|
||||||
$signerSubject,
|
|
||||||
[string]$ExpectedIdentity.subject,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
[string]::Equals(
|
|
||||||
$signerThumbprint,
|
|
||||||
[string]$ExpectedIdentity.thumbprint,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (-not $matchesProtectedIdentity) {
|
|
||||||
throw "Artifact signature is no longer valid for the approved signer: $($Artifact.FullName)"
|
|
||||||
}
|
|
||||||
return [pscustomobject][ordered]@{
|
|
||||||
subject = $signerSubject
|
|
||||||
thumbprint = $signerThumbprint
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-ReceiptSignerIdentity {
|
|
||||||
param([object]$ReceiptArtifact, [object]$ActualIdentity, [string]$Label)
|
|
||||||
|
|
||||||
if ([string]::IsNullOrWhiteSpace([string]$ReceiptArtifact.signerSubject) -or
|
|
||||||
[string]::IsNullOrWhiteSpace([string]$ReceiptArtifact.signerThumbprint) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
[string]$ReceiptArtifact.signerSubject,
|
|
||||||
[string]$ActualIdentity.subject,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
([string]$ReceiptArtifact.signerThumbprint -replace '\s', '').ToUpperInvariant(),
|
|
||||||
[string]$ActualIdentity.thumbprint,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
)) {
|
|
||||||
throw "$Label signer identity does not match the certified Authenticode artifact"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-LifecycleReceiptSignerIdentities {
|
|
||||||
param(
|
|
||||||
[object]$Receipt,
|
|
||||||
[object]$PreviousLiveIdentity,
|
|
||||||
[object]$CandidateLiveIdentity
|
|
||||||
)
|
|
||||||
|
|
||||||
Assert-ReceiptSignerIdentity `
|
|
||||||
$Receipt.previousInstaller `
|
|
||||||
$PreviousLiveIdentity `
|
|
||||||
'Upgrade previous-installer receipt'
|
|
||||||
Assert-ReceiptSignerIdentity `
|
|
||||||
$Receipt.previousInstalledApp `
|
|
||||||
$PreviousLiveIdentity `
|
|
||||||
'Upgrade previous-installed-app receipt'
|
|
||||||
Assert-ReceiptSignerIdentity `
|
|
||||||
$Receipt.installer `
|
|
||||||
$CandidateLiveIdentity `
|
|
||||||
'Upgrade candidate-installer receipt'
|
|
||||||
Assert-ReceiptSignerIdentity `
|
|
||||||
$Receipt.installedApp `
|
|
||||||
$CandidateLiveIdentity `
|
|
||||||
'Upgrade candidate-installed-app receipt'
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-PassingWindowsCertificateReceipt {
|
|
||||||
param([object]$Receipt, [string]$ExpectedMode, [string]$Label)
|
|
||||||
|
|
||||||
$schemaVersionIsIntegral = (
|
|
||||||
$Receipt.schemaVersion -is [int] -or
|
|
||||||
$Receipt.schemaVersion -is [long]
|
|
||||||
)
|
|
||||||
if (-not $schemaVersionIsIntegral -or
|
|
||||||
[long]$Receipt.schemaVersion -ne 4 -or
|
|
||||||
-not ($Receipt.certificationMode -is [string]) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
$Receipt.certificationMode,
|
|
||||||
$ExpectedMode,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
) -or
|
|
||||||
-not ($Receipt.status -is [string]) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
$Receipt.status,
|
|
||||||
'passed',
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
)) {
|
|
||||||
throw "$Label is not a passing schema-v4 certificate"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-PassingWindowsCertificateCheck {
|
|
||||||
param([object]$Receipt, [string]$CheckName, [string]$Label)
|
|
||||||
|
|
||||||
$check = $Receipt.checks.PSObject.Properties[$CheckName]
|
|
||||||
if ($null -eq $check -or -not [bool]::True.Equals($check.Value)) {
|
|
||||||
throw "$Label check did not pass: $CheckName"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-ExactReleaseAssets {
|
|
||||||
param([object]$Release, [object[]]$ExpectedAssets)
|
|
||||||
|
|
||||||
$expectedNames = [string[]]@(
|
|
||||||
$ExpectedAssets | ForEach-Object { [string]$_.Name }
|
|
||||||
)
|
|
||||||
$actualNames = [string[]]@(
|
|
||||||
$Release.assets | ForEach-Object { [string]$_.name }
|
|
||||||
)
|
|
||||||
[System.Array]::Sort($expectedNames, [System.StringComparer]::Ordinal)
|
|
||||||
[System.Array]::Sort($actualNames, [System.StringComparer]::Ordinal)
|
|
||||||
if ($expectedNames.Count -ne $actualNames.Count) {
|
|
||||||
throw 'Published release assets do not exactly match the certified artifact set'
|
|
||||||
}
|
|
||||||
for ($index = 0; $index -lt $expectedNames.Count; $index += 1) {
|
|
||||||
if (-not [string]::Equals(
|
|
||||||
$expectedNames[$index],
|
|
||||||
$actualNames[$index],
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
)) {
|
|
||||||
throw 'Published release assets do not exactly match the certified artifact set'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Set-ReadOnlyCreatedReleaseId {
|
|
||||||
param([string]$Value)
|
|
||||||
|
|
||||||
if ([string]::IsNullOrWhiteSpace($Value) -or
|
|
||||||
$null -ne (
|
|
||||||
Get-Variable -Name createdReleaseId -Scope Script `
|
|
||||||
-ErrorAction SilentlyContinue
|
|
||||||
)) {
|
|
||||||
throw 'Created release identity must be set exactly once'
|
|
||||||
}
|
|
||||||
Set-Variable `
|
|
||||||
-Name createdReleaseId `
|
|
||||||
-Scope Script `
|
|
||||||
-Value $Value `
|
|
||||||
-Option ReadOnly
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-ReleaseIdentity {
|
|
||||||
param(
|
|
||||||
[object]$Release,
|
|
||||||
[string]$ExpectedId,
|
|
||||||
[string]$ExpectedTag,
|
|
||||||
[bool]$ExpectedDraft,
|
|
||||||
[string]$Label
|
|
||||||
)
|
|
||||||
|
|
||||||
if ([string]::IsNullOrWhiteSpace($ExpectedId) -or
|
|
||||||
[string]$Release.id -cne $ExpectedId -or
|
|
||||||
[string]$Release.tagName -cne $ExpectedTag -or
|
|
||||||
[string]$Release.name -cne "Waggle $ExpectedTag" -or
|
|
||||||
-not ($Release.isDraft -is [bool]) -or
|
|
||||||
-not [bool]::Equals($Release.isDraft, $ExpectedDraft) -or
|
|
||||||
-not ($Release.isPrerelease -is [bool]) -or
|
|
||||||
[bool]::True.Equals($Release.isPrerelease)) {
|
|
||||||
throw "$Label identity does not match the newly-created release"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function New-ReleaseAssetManifest {
|
|
||||||
param([System.IO.FileInfo[]]$Assets)
|
|
||||||
|
|
||||||
$manifest = @(
|
|
||||||
foreach ($asset in $Assets) {
|
|
||||||
if ($null -eq $asset -or
|
|
||||||
-not $asset.Exists -or
|
|
||||||
[System.IO.Path]::GetFileName($asset.Name) -cne $asset.Name) {
|
|
||||||
throw 'Release asset manifest contains an invalid local file'
|
|
||||||
}
|
|
||||||
[pscustomobject]@{
|
|
||||||
Name = [string]$asset.Name
|
|
||||||
FullName = [string]$asset.FullName
|
|
||||||
SizeBytes = [int64]$asset.Length
|
|
||||||
Sha256 = (
|
|
||||||
Get-FileHash -LiteralPath $asset.FullName -Algorithm SHA256
|
|
||||||
).Hash.ToUpperInvariant()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
for ($left = 0; $left -lt $manifest.Count; $left += 1) {
|
|
||||||
for ($right = $left + 1; $right -lt $manifest.Count; $right += 1) {
|
|
||||||
if ([string]::Equals(
|
|
||||||
[string]$manifest[$left].Name,
|
|
||||||
[string]$manifest[$right].Name,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
)) {
|
|
||||||
throw 'Release asset manifest contains a duplicate exact filename'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return $manifest
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-ReleaseAssetFileMatchesManifest {
|
|
||||||
param(
|
|
||||||
[string]$Path,
|
|
||||||
[object]$ExpectedAsset,
|
|
||||||
[string]$Label
|
|
||||||
)
|
|
||||||
|
|
||||||
$asset = Get-Item -LiteralPath $Path -ErrorAction Stop
|
|
||||||
$sha256 = (
|
|
||||||
Get-FileHash -LiteralPath $asset.FullName -Algorithm SHA256
|
|
||||||
).Hash
|
|
||||||
if (-not ($asset -is [System.IO.FileInfo]) -or
|
|
||||||
[string]$asset.Name -cne [string]$ExpectedAsset.Name -or
|
|
||||||
[int64]$asset.Length -ne [int64]$ExpectedAsset.SizeBytes -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
$sha256,
|
|
||||||
[string]$ExpectedAsset.Sha256,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
)) {
|
|
||||||
throw "$Label does not match the immutable release-asset manifest"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-LocalReleaseAssetsUnchanged {
|
|
||||||
param([object[]]$Manifest)
|
|
||||||
|
|
||||||
foreach ($expectedAsset in $Manifest) {
|
|
||||||
Assert-ReleaseAssetFileMatchesManifest `
|
|
||||||
([string]$expectedAsset.FullName) `
|
|
||||||
$expectedAsset `
|
|
||||||
"Local release asset $($expectedAsset.Name)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-RemoteReleaseAssetContents {
|
|
||||||
param(
|
|
||||||
[string]$Tag,
|
|
||||||
[object]$Release,
|
|
||||||
[object[]]$Manifest,
|
|
||||||
[string]$Stage
|
|
||||||
)
|
|
||||||
|
|
||||||
Assert-ExactReleaseAssets $Release $Manifest
|
|
||||||
Assert-LocalReleaseAssetsUnchanged $Manifest
|
|
||||||
if ([string]::IsNullOrWhiteSpace([string]$env:RUNNER_TEMP)) {
|
|
||||||
throw 'RUNNER_TEMP is required for remote release-asset verification'
|
|
||||||
}
|
|
||||||
$downloadRoot = Join-Path `
|
|
||||||
([string]$env:RUNNER_TEMP) `
|
|
||||||
"waggle-release-$Stage-$([guid]::NewGuid().ToString('N'))"
|
|
||||||
New-Item -ItemType Directory -Path $downloadRoot -ErrorAction Stop |
|
|
||||||
Out-Null
|
|
||||||
try {
|
|
||||||
gh release download $Tag --dir $downloadRoot
|
|
||||||
if ($LASTEXITCODE -ne 0) {
|
|
||||||
throw "Could not download $Stage release assets for byte verification"
|
|
||||||
}
|
|
||||||
$downloadedFiles = @(
|
|
||||||
Get-ChildItem -LiteralPath $downloadRoot -File
|
|
||||||
)
|
|
||||||
if ($downloadedFiles.Count -ne $Manifest.Count) {
|
|
||||||
throw "$Stage release download does not contain the exact asset count"
|
|
||||||
}
|
|
||||||
foreach ($expectedAsset in $Manifest) {
|
|
||||||
Assert-ReleaseAssetFileMatchesManifest `
|
|
||||||
(Join-Path $downloadRoot ([string]$expectedAsset.Name)) `
|
|
||||||
$expectedAsset `
|
|
||||||
"$Stage remote release asset $($expectedAsset.Name)"
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
if (Test-Path -LiteralPath $downloadRoot) {
|
|
||||||
Remove-Item -LiteralPath $downloadRoot -Recurse -Force
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Assert-LocalReleaseAssetsUnchanged $Manifest
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-ManagedModelAndMemoryEvidence {
|
|
||||||
param([object]$Receipt, [string]$Label)
|
|
||||||
|
|
||||||
if (-not [bool]::True.Equals($Receipt.managedModelVerified)) {
|
|
||||||
throw "$Label does not prove a managed local-model chat completion"
|
|
||||||
}
|
|
||||||
if ([string]$Receipt.managedModelDigest -notmatch '^sha256:[0-9a-f]{64}$') {
|
|
||||||
throw "$Label does not bind the managed model to an immutable manifest digest"
|
|
||||||
}
|
|
||||||
if (-not [string]::Equals(
|
|
||||||
[string]$Receipt.certifiedTier,
|
|
||||||
'FREE',
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
)) {
|
|
||||||
throw "$Label does not certify the Solo/FREE tier"
|
|
||||||
}
|
|
||||||
if ([string]::IsNullOrWhiteSpace(
|
|
||||||
[string]$Receipt.lifecycleData.workspaceId
|
|
||||||
) -or
|
|
||||||
[long]$Receipt.lifecycleData.personalFrameId -lt 1 -or
|
|
||||||
[long]$Receipt.lifecycleData.workspaceFrameId -lt 1 -or
|
|
||||||
[int]$Receipt.lifecycleData.preUninstallManifestEntryCount -lt 1 -or
|
|
||||||
[string]$Receipt.lifecycleData.preUninstallManifestSha256 -notmatch '^[0-9A-F]{64}$' -or
|
|
||||||
[string]$Receipt.lifecycleData.postUninstallManifestSha256 -notmatch '^[0-9A-F]{64}$' -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
[string]$Receipt.lifecycleData.preUninstallManifestSha256,
|
|
||||||
[string]$Receipt.lifecycleData.postUninstallManifestSha256,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
)) {
|
|
||||||
throw "$Label does not bind real workspace and memory data to an unchanged uninstall manifest"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-ReceiptSourceHashes {
|
|
||||||
param(
|
|
||||||
[object[]]$Receipts,
|
|
||||||
[System.IO.FileInfo]$Installer,
|
|
||||||
[string]$SourceRevision
|
|
||||||
)
|
|
||||||
|
|
||||||
$currentCertifierHash = (
|
|
||||||
Get-FileHash -LiteralPath 'scripts/certify-windows-installer.ps1' `
|
|
||||||
-Algorithm SHA256
|
|
||||||
).Hash
|
|
||||||
$currentHookHash = (
|
|
||||||
Get-FileHash -LiteralPath 'app/src-tauri/nsis/installer.nsi' `
|
|
||||||
-Algorithm SHA256
|
|
||||||
).Hash
|
|
||||||
$releaseDirectory = Split-Path -Parent (
|
|
||||||
Split-Path -Parent $Installer.DirectoryName
|
|
||||||
)
|
|
||||||
$generatedInstallerScripts = @(
|
|
||||||
Get-ChildItem -LiteralPath (Join-Path $releaseDirectory 'nsis') `
|
|
||||||
-Recurse -Filter 'installer.nsi' -File
|
|
||||||
)
|
|
||||||
if ($generatedInstallerScripts.Count -ne 1) {
|
|
||||||
throw 'Could not uniquely resolve generated NSIS source during publication'
|
|
||||||
}
|
|
||||||
$currentGeneratedInstallerHash = (
|
|
||||||
Get-FileHash -LiteralPath $generatedInstallerScripts[0].FullName `
|
|
||||||
-Algorithm SHA256
|
|
||||||
).Hash
|
|
||||||
$currentSidecarPath = 'app/src-tauri/resources/service.js'
|
|
||||||
if (-not (Test-Path -LiteralPath $currentSidecarPath -PathType Leaf)) {
|
|
||||||
throw 'Current source-bound sidecar bundle is missing during publication'
|
|
||||||
}
|
|
||||||
$currentSidecarBytes = [System.IO.File]::ReadAllBytes(
|
|
||||||
(Get-Item -LiteralPath $currentSidecarPath).FullName
|
|
||||||
)
|
|
||||||
$sidecarNewlineIndex = [Array]::IndexOf($currentSidecarBytes, [byte]10)
|
|
||||||
if ($sidecarNewlineIndex -le 0) {
|
|
||||||
throw 'Current sidecar bundle is missing embedded provenance'
|
|
||||||
}
|
|
||||||
$sidecarFirstLine = [System.Text.Encoding]::UTF8.GetString(
|
|
||||||
$currentSidecarBytes,
|
|
||||||
0,
|
|
||||||
$sidecarNewlineIndex
|
|
||||||
)
|
|
||||||
$sidecarPrefix = '// Waggle-Sidecar-Provenance: '
|
|
||||||
if (-not $sidecarFirstLine.StartsWith($sidecarPrefix, [System.StringComparison]::Ordinal)) {
|
|
||||||
throw 'Current sidecar bundle is missing embedded provenance'
|
|
||||||
}
|
|
||||||
$sidecarEncodedProvenance = $sidecarFirstLine.Substring($sidecarPrefix.Length)
|
|
||||||
try {
|
|
||||||
$sidecarProvenanceBytes = [Convert]::FromBase64String($sidecarEncodedProvenance)
|
|
||||||
if (-not [string]::Equals(
|
|
||||||
[Convert]::ToBase64String($sidecarProvenanceBytes),
|
|
||||||
$sidecarEncodedProvenance,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
)) {
|
|
||||||
throw 'non-canonical provenance'
|
|
||||||
}
|
|
||||||
$sidecarManifest = [System.Text.Encoding]::UTF8.GetString($sidecarProvenanceBytes) |
|
|
||||||
ConvertFrom-Json
|
|
||||||
} catch {
|
|
||||||
throw 'Current sidecar bundle has invalid embedded provenance'
|
|
||||||
}
|
|
||||||
if (-not [string]::Equals(
|
|
||||||
[string]$sidecarManifest.sourceRevision,
|
|
||||||
$SourceRevision,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
) -or @($sidecarManifest.sourceInputs).Count -lt 4) {
|
|
||||||
throw 'Current sidecar provenance does not bind the publication source revision'
|
|
||||||
}
|
|
||||||
$sidecarProvenanceHasher = [System.Security.Cryptography.SHA256]::Create()
|
|
||||||
try {
|
|
||||||
$currentSidecarProvenanceHash = (
|
|
||||||
[System.BitConverter]::ToString(
|
|
||||||
$sidecarProvenanceHasher.ComputeHash($sidecarProvenanceBytes)
|
|
||||||
)
|
|
||||||
).Replace('-', '')
|
|
||||||
} finally {
|
|
||||||
$sidecarProvenanceHasher.Dispose()
|
|
||||||
}
|
|
||||||
$currentSidecarHash = (
|
|
||||||
Get-FileHash -LiteralPath $currentSidecarPath -Algorithm SHA256
|
|
||||||
).Hash
|
|
||||||
$currentSidecarSourceInputCount = @($sidecarManifest.sourceInputs).Count
|
|
||||||
|
|
||||||
foreach ($certificateData in $Receipts) {
|
|
||||||
if (-not [string]::Equals(
|
|
||||||
$currentCertifierHash,
|
|
||||||
[string]$certificateData.evidence.certifierSha256,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
$currentHookHash,
|
|
||||||
[string]$certificateData.evidence.installerHookSha256,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
$currentGeneratedInstallerHash,
|
|
||||||
[string]$certificateData.evidence.generatedInstallerScriptSha256,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
$currentSidecarHash,
|
|
||||||
[string]$certificateData.evidence.sidecarBundleSha256,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
$currentSidecarProvenanceHash,
|
|
||||||
[string]$certificateData.evidence.sidecarProvenanceSha256,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
$SourceRevision,
|
|
||||||
[string]$certificateData.evidence.sidecarSourceRevision,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
) -or
|
|
||||||
[int]$certificateData.evidence.sidecarSourceInputCount -ne
|
|
||||||
$currentSidecarSourceInputCount
|
|
||||||
) {
|
|
||||||
throw 'Lifecycle receipt source hashes do not match the release checkout'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-ReleaseDoesNotExist {
|
|
||||||
param([string]$Tag)
|
|
||||||
|
|
||||||
$probeOutput = @(gh release view $Tag --json id 2>&1)
|
|
||||||
$probeExitCode = $LASTEXITCODE
|
|
||||||
if ($probeExitCode -eq 0) {
|
|
||||||
throw "Refusing to use a pre-existing release: $Tag"
|
|
||||||
}
|
|
||||||
$probeText = [string]::Join("`n", [string[]]$probeOutput)
|
|
||||||
if ($probeText -notmatch '(?i)(release not found|HTTP\s+404)') {
|
|
||||||
throw "Could not prove that release $Tag does not already exist"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-PublicationTagBindings {
|
|
||||||
param([string]$ReleaseMode, [string]$Tag, [string]$Commit)
|
|
||||||
|
|
||||||
if ($ReleaseMode -ceq 'upgrade') {
|
|
||||||
Assert-RemoteTagCommit `
|
|
||||||
([string]$env:WINDOWS_UPGRADE_BASE_TAG) `
|
|
||||||
([string]$env:WAGGLE_UPGRADE_BASE_COMMIT)
|
|
||||||
}
|
|
||||||
Assert-RemoteTagCommit $Tag $Commit
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not [string]::Equals(
|
|
||||||
$Mode,
|
|
||||||
[string]$env:WAGGLE_RELEASE_MODE,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
)) {
|
|
||||||
throw 'Publisher mode does not match the resolved Windows release mode'
|
|
||||||
}
|
|
||||||
|
|
||||||
$tag = [string]$env:GITHUB_REF_NAME
|
|
||||||
$sourceRevision = [string]$env:GITHUB_SHA
|
|
||||||
if ($tag -notmatch '^v\d+\.\d+\.\d+$' -or
|
|
||||||
$sourceRevision -cnotmatch '^[0-9a-f]{40}$') {
|
|
||||||
throw 'Publication requires an exact release tag and lowercase commit identity'
|
|
||||||
}
|
|
||||||
|
|
||||||
$baselineInputs = @(
|
|
||||||
[string]$env:WINDOWS_UPGRADE_BASE_TAG,
|
|
||||||
[string]$env:WINDOWS_UPGRADE_BASE_ASSET_NAME,
|
|
||||||
[string]$env:WINDOWS_UPGRADE_BASE_SHA256,
|
|
||||||
[string]$env:WINDOWS_UPGRADE_BASE_COMMIT
|
|
||||||
)
|
|
||||||
if (@($baselineInputs | Where-Object { $_ -ne $_.Trim() }).Count -gt 0) {
|
|
||||||
throw 'Protected Windows upgrade-baseline inputs must not contain surrounding whitespace'
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($Mode -ceq 'bootstrap') {
|
|
||||||
$expectedBootstrapIdentity = "v0.2.0@$env:GITHUB_SHA"
|
|
||||||
if ($tag -cne 'v0.2.0' -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
[string]$env:WINDOWS_BOOTSTRAP_RELEASE_IDENTITY,
|
|
||||||
$expectedBootstrapIdentity,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
) -or
|
|
||||||
@($baselineInputs | Where-Object {
|
|
||||||
-not [string]::IsNullOrEmpty($_)
|
|
||||||
}).Count -ne 0) {
|
|
||||||
throw 'Bootstrap publication is not bound to the exact authorized v0.2.0 release'
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (-not [string]::IsNullOrEmpty(
|
|
||||||
[string]$env:WINDOWS_BOOTSTRAP_RELEASE_IDENTITY
|
|
||||||
) -or
|
|
||||||
@($baselineInputs | Where-Object {
|
|
||||||
[string]::IsNullOrEmpty($_)
|
|
||||||
}).Count -ne 0) {
|
|
||||||
throw 'Upgrade publication requires an empty bootstrap authorization and all baseline inputs'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$installers = @(
|
|
||||||
Get-ChildItem -LiteralPath 'app/src-tauri/target' -Recurse `
|
|
||||||
-Filter '*-setup.exe' -File |
|
|
||||||
Where-Object { $_.DirectoryName -match '[\\/]bundle[\\/]nsis$' }
|
|
||||||
)
|
|
||||||
if ($installers.Count -ne 1) {
|
|
||||||
throw "Expected exactly one certified NSIS installer, found $($installers.Count)"
|
|
||||||
}
|
|
||||||
$installer = $installers[0]
|
|
||||||
$cleanReceipt = Get-Item -LiteralPath (
|
|
||||||
Join-Path $installer.DirectoryName 'windows-installer-certificate.json'
|
|
||||||
)
|
|
||||||
$upgradeReceiptPath = Join-Path `
|
|
||||||
$installer.DirectoryName `
|
|
||||||
'windows-installer-upgrade-certificate.json'
|
|
||||||
if ($Mode -ceq 'bootstrap' -and
|
|
||||||
(Test-Path -LiteralPath $upgradeReceiptPath)) {
|
|
||||||
throw 'Bootstrap publication found an unexpected upgrade certificate'
|
|
||||||
}
|
|
||||||
|
|
||||||
$cleanReceiptData = Get-Content -Raw -LiteralPath $cleanReceipt.FullName |
|
|
||||||
ConvertFrom-Json
|
|
||||||
Assert-PassingWindowsCertificateReceipt `
|
|
||||||
$cleanReceiptData 'same-version-repair' 'Windows clean-install receipt'
|
|
||||||
|
|
||||||
if (-not [string]::Equals(
|
|
||||||
[string]$cleanReceiptData.evidence.sourceRevision,
|
|
||||||
$sourceRevision,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
[string]$cleanReceiptData.installer.name,
|
|
||||||
$installer.Name,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
) -or
|
|
||||||
[int64]$cleanReceiptData.installer.sizeBytes -ne $installer.Length) {
|
|
||||||
throw 'Clean-install receipt identity does not match the release artifact and commit'
|
|
||||||
}
|
|
||||||
|
|
||||||
$candidateVersion = [string](
|
|
||||||
Get-Content -Raw -LiteralPath 'app/src-tauri/tauri.conf.json' |
|
|
||||||
ConvertFrom-Json
|
|
||||||
).version
|
|
||||||
if ($candidateVersion -notmatch '^\d+\.\d+\.\d+$' -or
|
|
||||||
$tag -cne "v$candidateVersion" -or
|
|
||||||
[string]$env:WAGGLE_CERTIFIED_CANDIDATE_VERSION -cne $candidateVersion -or
|
|
||||||
($Mode -ceq 'bootstrap' -and $candidateVersion -cne '0.2.0')) {
|
|
||||||
throw 'Published candidate version is not independently bound to the release tag'
|
|
||||||
}
|
|
||||||
|
|
||||||
$installerSha256 = (
|
|
||||||
Get-FileHash -LiteralPath $installer.FullName -Algorithm SHA256
|
|
||||||
).Hash
|
|
||||||
if (-not [string]::Equals(
|
|
||||||
$installerSha256,
|
|
||||||
[string]$env:WAGGLE_CERTIFIED_CANDIDATE_SHA256,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
$installerSha256,
|
|
||||||
[string]$cleanReceiptData.installer.sha256,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
)) {
|
|
||||||
throw 'Certified installer hash no longer matches the clean receipt and pre-publication output'
|
|
||||||
}
|
|
||||||
|
|
||||||
$approvedSignerIdentity = Get-ProtectedSignerIdentity
|
|
||||||
$installerSignerIdentity = Assert-ExpectedAuthenticodeSignature $installer $approvedSignerIdentity
|
|
||||||
if ($cleanReceiptData.installer.authenticodeStatus -ne 'Valid' -or
|
|
||||||
$cleanReceiptData.installedApp.authenticodeStatus -ne 'Valid' -or
|
|
||||||
$cleanReceiptData.installer.signatureType -ne 'Authenticode' -or
|
|
||||||
$cleanReceiptData.installedApp.signatureType -ne 'Authenticode' -or
|
|
||||||
[string]::IsNullOrWhiteSpace(
|
|
||||||
[string]$cleanReceiptData.installer.timestampAuthorityThumbprint
|
|
||||||
) -or
|
|
||||||
[string]::IsNullOrWhiteSpace(
|
|
||||||
[string]$cleanReceiptData.installedApp.timestampAuthorityThumbprint
|
|
||||||
)) {
|
|
||||||
throw 'Clean-install receipt does not preserve valid signer and timestamp evidence'
|
|
||||||
}
|
|
||||||
Assert-ReceiptSignerIdentity `
|
|
||||||
$cleanReceiptData.installer $installerSignerIdentity 'Clean-install installer receipt'
|
|
||||||
Assert-ReceiptSignerIdentity `
|
|
||||||
$cleanReceiptData.installedApp $installerSignerIdentity 'Clean-install installed-app receipt'
|
|
||||||
Assert-ManagedModelAndMemoryEvidence `
|
|
||||||
$cleanReceiptData `
|
|
||||||
'Clean-install receipt'
|
|
||||||
|
|
||||||
$cleanRequiredChecks = @(
|
|
||||||
'sourceRevision', 'sourceFilesClean', 'sidecarSourceProvenance',
|
|
||||||
'generatedInstallerInclude',
|
|
||||||
'profileDataDeletionAbsent', 'baseAppDataDeletionNeutralized',
|
|
||||||
'authenticodeSignature', 'authenticodeSigner', 'authenticodeTimestamp',
|
|
||||||
'installedAppAuthenticodeSignature', 'installedAppAuthenticodeSigner',
|
|
||||||
'installedAppAuthenticodeTimestamp', 'silentInstall',
|
|
||||||
'vaultKeyAclRestricted', 'windowsInboxTools', 'noModelChatSetupRequired',
|
|
||||||
'soloTier', 'dockerIndependentRuntimePrerequisites',
|
|
||||||
'managedRuntimeBootstrap', 'managedModelPull', 'managedModelChat',
|
|
||||||
'managedModelProxyRestartChat', 'managedRuntimeCleanup',
|
|
||||||
'sameVersionRepair', 'repairSoloTier', 'repairManagedModelDigestPreserved',
|
|
||||||
'relaunchAfterRepair', 'silentUninstall', 'defaultProfileDataDir',
|
|
||||||
'realWorkspaceAndMemorySeeded', 'repairRealWorkspaceAndMemoryPreserved',
|
|
||||||
'uninstallRealWorkspaceAndMemoryPreserved', 'configuredDataDirPreserved',
|
|
||||||
'profileDataPathPreserved', 'certificateProfileCleanup',
|
|
||||||
'externalProfileRootsUnchanged', 'environmentRestored'
|
|
||||||
)
|
|
||||||
foreach ($checkName in $cleanRequiredChecks) {
|
|
||||||
Assert-PassingWindowsCertificateCheck `
|
|
||||||
$cleanReceiptData $checkName 'Clean-install receipt'
|
|
||||||
}
|
|
||||||
|
|
||||||
$receiptDataSet = @($cleanReceiptData)
|
|
||||||
if ($Mode -ceq 'bootstrap') {
|
|
||||||
$releaseAssets = @($installer, $cleanReceipt)
|
|
||||||
} else {
|
|
||||||
$upgradeReceipt = Get-Item -LiteralPath $upgradeReceiptPath
|
|
||||||
$receiptData = Get-Content -Raw -LiteralPath $upgradeReceipt.FullName |
|
|
||||||
ConvertFrom-Json
|
|
||||||
Assert-PassingWindowsCertificateReceipt `
|
|
||||||
$receiptData 'version-to-version-upgrade' 'Windows lifecycle receipt'
|
|
||||||
|
|
||||||
if (-not [string]::Equals(
|
|
||||||
[string]$receiptData.evidence.sourceRevision,
|
|
||||||
$sourceRevision,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
[string]$receiptData.installer.name,
|
|
||||||
$installer.Name,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
) -or
|
|
||||||
[int64]$receiptData.installer.sizeBytes -ne $installer.Length -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
$installerSha256,
|
|
||||||
[string]$receiptData.installer.sha256,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
)) {
|
|
||||||
throw 'Upgrade receipt does not match the release artifact and commit'
|
|
||||||
}
|
|
||||||
|
|
||||||
$baseInstaller = Get-Item -LiteralPath (
|
|
||||||
[string]$env:WAGGLE_UPGRADE_BASE_INSTALLER_PATH
|
|
||||||
)
|
|
||||||
$baseSha256 = (
|
|
||||||
Get-FileHash -LiteralPath $baseInstaller.FullName -Algorithm SHA256
|
|
||||||
).Hash
|
|
||||||
if (-not [string]::Equals(
|
|
||||||
[string]$env:WAGGLE_UPGRADE_BASE_COMMIT,
|
|
||||||
[string]$env:WINDOWS_UPGRADE_BASE_COMMIT,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
)) {
|
|
||||||
throw 'Certified Windows upgrade baseline commit no longer matches the protected commit'
|
|
||||||
}
|
|
||||||
Assert-RemoteTagCommit `
|
|
||||||
([string]$env:WINDOWS_UPGRADE_BASE_TAG) `
|
|
||||||
([string]$env:WAGGLE_UPGRADE_BASE_COMMIT)
|
|
||||||
if ([string]$env:WINDOWS_UPGRADE_BASE_TAG -notmatch '^v(?<version>\d+\.\d+\.\d+)$' -or
|
|
||||||
$Matches['version'] -cne [string]$receiptData.upgrade.previousVersion -or
|
|
||||||
$Matches['version'] -cne [string]$env:WAGGLE_UPGRADE_BASE_VERSION -or
|
|
||||||
[string]$receiptData.upgrade.previousSourceRevision -cne
|
|
||||||
[string]$env:WAGGLE_UPGRADE_BASE_COMMIT -or
|
|
||||||
[string]$receiptData.upgrade.candidateVersion -cne $candidateVersion -or
|
|
||||||
[string]$receiptData.upgrade.observedPreviousVersion -cne
|
|
||||||
[string]$receiptData.upgrade.previousVersion -or
|
|
||||||
[string]$receiptData.upgrade.observedCandidateVersion -cne
|
|
||||||
[string]$receiptData.upgrade.candidateVersion) {
|
|
||||||
throw 'Lifecycle receipt does not bind the observed upgrade versions to the protected release versions'
|
|
||||||
}
|
|
||||||
if ($baseInstaller.Name -cne [string]$env:WINDOWS_UPGRADE_BASE_ASSET_NAME -or
|
|
||||||
[string]$receiptData.previousInstaller.name -cne $baseInstaller.Name -or
|
|
||||||
[int64]$receiptData.previousInstaller.sizeBytes -ne $baseInstaller.Length -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
$baseSha256,
|
|
||||||
[string]$env:WINDOWS_UPGRADE_BASE_SHA256,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
$baseSha256,
|
|
||||||
[string]$receiptData.previousInstaller.sha256,
|
|
||||||
[System.StringComparison]::OrdinalIgnoreCase
|
|
||||||
)) {
|
|
||||||
throw 'Lifecycle receipt previous installer does not match the protected upgrade baseline'
|
|
||||||
}
|
|
||||||
if ($receiptData.installer.authenticodeStatus -ne 'Valid' -or
|
|
||||||
$receiptData.installedApp.authenticodeStatus -ne 'Valid' -or
|
|
||||||
$receiptData.previousInstaller.authenticodeStatus -ne 'Valid' -or
|
|
||||||
$receiptData.previousInstalledApp.authenticodeStatus -ne 'Valid' -or
|
|
||||||
$receiptData.installer.signatureType -ne 'Authenticode' -or
|
|
||||||
$receiptData.installedApp.signatureType -ne 'Authenticode' -or
|
|
||||||
$receiptData.previousInstaller.signatureType -ne 'Authenticode' -or
|
|
||||||
$receiptData.previousInstalledApp.signatureType -ne 'Authenticode') {
|
|
||||||
throw 'Lifecycle receipt does not contain valid previous and candidate signatures'
|
|
||||||
}
|
|
||||||
$baseInstallerSignerIdentity = Assert-ExpectedAuthenticodeSignature $baseInstaller $approvedSignerIdentity
|
|
||||||
Assert-LifecycleReceiptSignerIdentities `
|
|
||||||
$receiptData $baseInstallerSignerIdentity $installerSignerIdentity
|
|
||||||
foreach ($timestampThumbprint in @(
|
|
||||||
$receiptData.previousInstaller.timestampAuthorityThumbprint,
|
|
||||||
$receiptData.previousInstalledApp.timestampAuthorityThumbprint,
|
|
||||||
$receiptData.installer.timestampAuthorityThumbprint,
|
|
||||||
$receiptData.installedApp.timestampAuthorityThumbprint
|
|
||||||
)) {
|
|
||||||
if ([string]::IsNullOrWhiteSpace([string]$timestampThumbprint)) {
|
|
||||||
throw 'Lifecycle receipt is missing a validated Authenticode timestamp'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Assert-ManagedModelAndMemoryEvidence $receiptData 'Upgrade receipt'
|
|
||||||
if ([string]::IsNullOrWhiteSpace(
|
|
||||||
[string]$receiptData.upgrade.managedModelName
|
|
||||||
) -or
|
|
||||||
[string]$receiptData.upgrade.managedModelDigest -notmatch
|
|
||||||
'^sha256:[0-9a-f]{64}$' -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
[string]$receiptData.upgrade.managedModelName,
|
|
||||||
[string]$receiptData.managedModel.name,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
) -or
|
|
||||||
-not [string]::Equals(
|
|
||||||
[string]$receiptData.upgrade.managedModelDigest,
|
|
||||||
[string]$receiptData.managedModelDigest,
|
|
||||||
[System.StringComparison]::Ordinal
|
|
||||||
)) {
|
|
||||||
throw 'Upgrade receipt does not preserve the previous managed-model identity and digest'
|
|
||||||
}
|
|
||||||
|
|
||||||
$upgradeRequiredChecks = @(
|
|
||||||
'sourceRevision', 'sourceFilesClean', 'sidecarSourceProvenance',
|
|
||||||
'generatedInstallerInclude',
|
|
||||||
'profileDataDeletionAbsent', 'baseAppDataDeletionNeutralized',
|
|
||||||
'authenticodeSignature', 'authenticodeSigner', 'authenticodeTimestamp',
|
|
||||||
'installedAppAuthenticodeSignature', 'installedAppAuthenticodeSigner',
|
|
||||||
'installedAppAuthenticodeTimestamp', 'previousInstallerHash',
|
|
||||||
'previousInstallerAuthenticodeSignature',
|
|
||||||
'previousInstallerAuthenticodeSigner',
|
|
||||||
'previousInstallerAuthenticodeTimestamp',
|
|
||||||
'previousInstalledAppAuthenticodeSignature',
|
|
||||||
'previousInstalledAppAuthenticodeSigner',
|
|
||||||
'previousInstalledAppAuthenticodeTimestamp', 'candidateInstallerHash',
|
|
||||||
'versionOrder', 'previousVersion', 'candidateVersion', 'previousInstall',
|
|
||||||
'previousLaunch', 'sameApprovedSigner', 'versionToVersionUpgrade',
|
|
||||||
'upgradeSameInstallDirectory', 'upgradeConfiguredDataPreserved',
|
|
||||||
'upgradeProfileDataPreserved', 'upgradeVaultKeyPreserved',
|
|
||||||
'upgradeRegistrations', 'candidateLaunch', 'relaunchAfterUpgrade',
|
|
||||||
'silentInstall', 'vaultKeyAclRestricted', 'windowsInboxTools', 'soloTier',
|
|
||||||
'previousSoloTier', 'dockerIndependentRuntimePrerequisites',
|
|
||||||
'managedRuntimeBootstrap', 'managedModelPull', 'managedModelChat',
|
|
||||||
'managedModelProxyRestartChat', 'managedRuntimeCleanup',
|
|
||||||
'previousManagedModelSeeded', 'upgradeManagedModelPreserved',
|
|
||||||
'sameVersionRepair', 'repairSoloTier', 'repairManagedModelDigestPreserved',
|
|
||||||
'relaunchAfterRepair', 'silentUninstall', 'defaultProfileDataDir',
|
|
||||||
'realWorkspaceAndMemorySeeded', 'upgradeRealWorkspaceAndMemoryPreserved',
|
|
||||||
'repairRealWorkspaceAndMemoryPreserved',
|
|
||||||
'uninstallRealWorkspaceAndMemoryPreserved',
|
|
||||||
'configuredDataDirPreserved', 'profileDataPathPreserved',
|
|
||||||
'certificateProfileCleanup', 'externalProfileRootsUnchanged', 'environmentRestored'
|
|
||||||
)
|
|
||||||
foreach ($checkName in $upgradeRequiredChecks) {
|
|
||||||
Assert-PassingWindowsCertificateCheck `
|
|
||||||
$receiptData $checkName 'Upgrade receipt'
|
|
||||||
}
|
|
||||||
$receiptDataSet = @($cleanReceiptData, $receiptData)
|
|
||||||
$releaseAssets = @($installer, $cleanReceipt, $upgradeReceipt)
|
|
||||||
}
|
|
||||||
|
|
||||||
$nonPassingChecks = @(
|
|
||||||
foreach ($certificateData in $receiptDataSet) {
|
|
||||||
$certificateData.checks.PSObject.Properties |
|
|
||||||
Where-Object { -not [bool]::True.Equals($_.Value) }
|
|
||||||
}
|
|
||||||
)
|
|
||||||
if ($nonPassingChecks.Count -gt 0) {
|
|
||||||
throw "Lifecycle receipts contain non-passing checks: $($nonPassingChecks.Name -join ', ')"
|
|
||||||
}
|
|
||||||
|
|
||||||
$releaseAssetManifest = @(New-ReleaseAssetManifest $releaseAssets)
|
|
||||||
Assert-LocalReleaseAssetsUnchanged $releaseAssetManifest
|
|
||||||
Assert-ReceiptSourceHashes $receiptDataSet $installer $sourceRevision
|
|
||||||
Assert-PublicationTagBindings $Mode $tag $sourceRevision
|
|
||||||
Assert-ReleaseDoesNotExist $tag
|
|
||||||
|
|
||||||
gh release create $tag --verify-tag --draft --title "Waggle $tag" `
|
|
||||||
--notes 'See the release notes for details.'
|
|
||||||
if ($LASTEXITCODE -ne 0) {
|
|
||||||
throw "Could not create a dedicated $Mode draft release: $tag"
|
|
||||||
}
|
|
||||||
$releaseData = gh release view $tag `
|
|
||||||
--json id,isDraft,isPrerelease,tagName,name,assets |
|
|
||||||
ConvertFrom-Json
|
|
||||||
if ($LASTEXITCODE -ne 0) {
|
|
||||||
throw "Could not inspect newly-created $Mode draft release $tag"
|
|
||||||
}
|
|
||||||
Set-ReadOnlyCreatedReleaseId ([string]$releaseData.id)
|
|
||||||
Assert-ReleaseIdentity `
|
|
||||||
$releaseData $createdReleaseId $tag $true 'Newly-created draft release'
|
|
||||||
if (@($releaseData.assets).Count -ne 0) {
|
|
||||||
throw "Could not verify newly-created $Mode draft release $tag"
|
|
||||||
}
|
|
||||||
|
|
||||||
Assert-PublicationTagBindings $Mode $tag $sourceRevision
|
|
||||||
$releaseAssetPaths = [string[]]@(
|
|
||||||
$releaseAssetManifest | ForEach-Object { $_.FullName }
|
|
||||||
)
|
|
||||||
gh release upload $tag @releaseAssetPaths
|
|
||||||
if ($LASTEXITCODE -ne 0) {
|
|
||||||
throw "Could not upload certified Windows $Mode assets to $tag"
|
|
||||||
}
|
|
||||||
$uploadedRelease = gh release view $tag `
|
|
||||||
--json id,isDraft,isPrerelease,tagName,name,assets |
|
|
||||||
ConvertFrom-Json
|
|
||||||
if ($LASTEXITCODE -ne 0) {
|
|
||||||
throw "Could not verify uploaded $Mode draft $tag"
|
|
||||||
}
|
|
||||||
Assert-ReleaseIdentity `
|
|
||||||
$uploadedRelease $createdReleaseId $tag $true 'Uploaded draft release'
|
|
||||||
Assert-ExactReleaseAssets $uploadedRelease $releaseAssets
|
|
||||||
Assert-RemoteReleaseAssetContents $tag $uploadedRelease $releaseAssetManifest 'uploaded'
|
|
||||||
|
|
||||||
Assert-PublicationTagBindings $Mode $tag $sourceRevision
|
|
||||||
gh release edit $tag --draft=false --prerelease=false
|
|
||||||
if ($LASTEXITCODE -ne 0) {
|
|
||||||
throw "Could not publish certified Windows $Mode release $tag"
|
|
||||||
}
|
|
||||||
$publishedRelease = gh release view $tag `
|
|
||||||
--json id,isDraft,isPrerelease,tagName,name,assets |
|
|
||||||
ConvertFrom-Json
|
|
||||||
if ($LASTEXITCODE -ne 0) {
|
|
||||||
throw "Published Windows $Mode release $tag is not final"
|
|
||||||
}
|
|
||||||
Assert-ReleaseIdentity `
|
|
||||||
$publishedRelease $createdReleaseId $tag $false 'Published release'
|
|
||||||
Assert-ExactReleaseAssets $publishedRelease $releaseAssets
|
|
||||||
Assert-RemoteReleaseAssetContents $tag $publishedRelease $releaseAssetManifest 'published'
|
|
||||||
@@ -1,262 +0,0 @@
|
|||||||
#!/usr/bin/env node
|
|
||||||
|
|
||||||
import process from 'node:process';
|
|
||||||
import WebSocket from 'ws';
|
|
||||||
|
|
||||||
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
||||||
const MIN_TOKEN_LENGTH = 32;
|
|
||||||
const MAX_TOKEN_LENGTH = 200;
|
|
||||||
|
|
||||||
function fail(message) {
|
|
||||||
console.error(`tauri-bootstrap-token: ${message}`);
|
|
||||||
process.exitCode = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseArgs(argv) {
|
|
||||||
const options = {
|
|
||||||
port: null,
|
|
||||||
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
||||||
selfTest: false,
|
|
||||||
allowLegacyUi: false,
|
|
||||||
};
|
|
||||||
for (let index = 0; index < argv.length; index += 1) {
|
|
||||||
const argument = argv[index];
|
|
||||||
if (argument === '--self-test') {
|
|
||||||
options.selfTest = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (argument === '--allow-legacy-ui') {
|
|
||||||
options.allowLegacyUi = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (argument === '--port' || argument === '--timeout-ms') {
|
|
||||||
const value = argv[index + 1];
|
|
||||||
index += 1;
|
|
||||||
if (value === undefined) throw new Error(`${argument} requires a value`);
|
|
||||||
if (argument === '--port') options.port = Number(value);
|
|
||||||
else options.timeoutMs = Number(value);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (argument.startsWith('--port=')) options.port = Number(argument.slice(7));
|
|
||||||
else if (argument.startsWith('--timeout-ms=')) options.timeoutMs = Number(argument.slice(13));
|
|
||||||
else throw new Error(`unknown argument: ${argument}`);
|
|
||||||
}
|
|
||||||
if (!Number.isInteger(options.port) || options.port < 1024 || options.port > 65535) {
|
|
||||||
throw new Error('port must be an integer between 1024 and 65535');
|
|
||||||
}
|
|
||||||
if (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1000 || options.timeoutMs > 300_000) {
|
|
||||||
throw new Error('timeout-ms must be an integer between 1000 and 300000');
|
|
||||||
}
|
|
||||||
return options;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isValidEndpoint(value) {
|
|
||||||
return value !== null
|
|
||||||
&& typeof value === 'object'
|
|
||||||
&& Number.isInteger(value.port)
|
|
||||||
&& value.port > 0
|
|
||||||
&& value.port <= 65535
|
|
||||||
&& typeof value.instanceId === 'string'
|
|
||||||
&& value.instanceId.trim().length > 0
|
|
||||||
&& typeof value.bootstrapToken === 'string'
|
|
||||||
&& value.bootstrapToken.length >= MIN_TOKEN_LENGTH
|
|
||||||
&& value.bootstrapToken.length <= MAX_TOKEN_LENGTH;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isValidDesktopRuntime(value, allowLegacyUi = false) {
|
|
||||||
return isValidEndpoint(value)
|
|
||||||
&& value.uiReady === true
|
|
||||||
&& value.uiStartupState === (allowLegacyUi ? 'legacy-ready' : 'ready')
|
|
||||||
&& typeof value.uiPath === 'string'
|
|
||||||
&& value.uiPath.startsWith('/')
|
|
||||||
&& Number.isInteger(value.uiTextLength)
|
|
||||||
&& value.uiTextLength > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchTargets(port) {
|
|
||||||
const response = await fetch(`http://127.0.0.1:${port}/json/list`);
|
|
||||||
if (!response.ok) throw new Error(`WebView debug endpoint returned HTTP ${response.status}`);
|
|
||||||
const targets = await response.json();
|
|
||||||
if (!Array.isArray(targets)) throw new Error('WebView debug endpoint returned an invalid target list');
|
|
||||||
return targets.filter((target) => target?.type === 'page' && typeof target.webSocketDebuggerUrl === 'string');
|
|
||||||
}
|
|
||||||
|
|
||||||
async function evaluateEnsureService(webSocketUrl, timeoutMs, allowLegacyUi) {
|
|
||||||
const socket = new WebSocket(webSocketUrl);
|
|
||||||
let nextId = 1;
|
|
||||||
const pending = new Map();
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
for (const pendingRequest of pending.values()) pendingRequest.reject(new Error('CDP request timed out'));
|
|
||||||
pending.clear();
|
|
||||||
socket.close();
|
|
||||||
}, timeoutMs);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await new Promise((resolve, reject) => {
|
|
||||||
const openTimer = setTimeout(() => reject(new Error('CDP WebSocket open timed out')), timeoutMs);
|
|
||||||
socket.addEventListener('open', () => {
|
|
||||||
clearTimeout(openTimer);
|
|
||||||
resolve();
|
|
||||||
}, { once: true });
|
|
||||||
socket.addEventListener('error', () => {
|
|
||||||
clearTimeout(openTimer);
|
|
||||||
reject(new Error('CDP WebSocket connection failed'));
|
|
||||||
}, { once: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.addEventListener('message', (event) => {
|
|
||||||
let message;
|
|
||||||
try {
|
|
||||||
message = JSON.parse(String(event.data));
|
|
||||||
} catch {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const request = pending.get(message.id);
|
|
||||||
if (!request) return;
|
|
||||||
pending.delete(message.id);
|
|
||||||
if (message.error) request.reject(new Error('Tauri IPC evaluation failed'));
|
|
||||||
else request.resolve(message.result);
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await new Promise((resolve, reject) => {
|
|
||||||
const id = nextId;
|
|
||||||
nextId += 1;
|
|
||||||
pending.set(id, { resolve, reject });
|
|
||||||
socket.send(JSON.stringify({
|
|
||||||
id,
|
|
||||||
method: 'Runtime.evaluate',
|
|
||||||
params: {
|
|
||||||
awaitPromise: true,
|
|
||||||
returnByValue: true,
|
|
||||||
expression: `
|
|
||||||
(async () => {
|
|
||||||
const invoke = globalThis.__TAURI_INTERNALS__?.invoke;
|
|
||||||
if (typeof invoke !== 'function') throw new Error('Tauri IPC is unavailable');
|
|
||||||
const endpoint = await invoke('ensure_service');
|
|
||||||
const deadline = Date.now() + 10_000;
|
|
||||||
for (;;) {
|
|
||||||
const root = document.getElementById('root');
|
|
||||||
const startup = root?.querySelector('[data-waggle-startup]');
|
|
||||||
const startupState = startup?.getAttribute('data-waggle-startup') ?? null;
|
|
||||||
const readyState = root?.getAttribute('data-waggle-ui-ready') ?? null;
|
|
||||||
const uiTextLength = root?.innerText?.trim().length ?? 0;
|
|
||||||
const strictUiReady = Boolean(
|
|
||||||
root
|
|
||||||
&& root.childElementCount > 0
|
|
||||||
&& !startup
|
|
||||||
&& readyState === 'ready'
|
|
||||||
&& uiTextLength > 0
|
|
||||||
);
|
|
||||||
const legacyUiReady = Boolean(
|
|
||||||
root
|
|
||||||
&& root.childElementCount > 0
|
|
||||||
&& !startup
|
|
||||||
&& uiTextLength > 0
|
|
||||||
);
|
|
||||||
const uiReady = ${allowLegacyUi ? 'legacyUiReady' : 'strictUiReady'};
|
|
||||||
if (uiReady || startupState === 'failed' || Date.now() >= deadline) {
|
|
||||||
return {
|
|
||||||
...endpoint,
|
|
||||||
uiPath: globalThis.location?.pathname ?? '',
|
|
||||||
uiReady,
|
|
||||||
uiStartupState: ${allowLegacyUi ? "uiReady ? 'legacy-ready' : (readyState ?? startupState)" : 'readyState ?? startupState'},
|
|
||||||
uiTextLength,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
||||||
}
|
|
||||||
})()
|
|
||||||
`,
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
const remote = result?.result?.value;
|
|
||||||
if (!isValidEndpoint(remote)) throw new Error('Tauri returned an invalid service endpoint');
|
|
||||||
if (!isValidDesktopRuntime(remote, allowLegacyUi)) {
|
|
||||||
throw new Error('Waggle UI did not render its application shell');
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
bootstrapToken: remote.bootstrapToken,
|
|
||||||
uiPath: remote.uiPath,
|
|
||||||
uiReady: remote.uiReady,
|
|
||||||
uiStartupState: remote.uiStartupState,
|
|
||||||
uiTextLength: remote.uiTextLength,
|
|
||||||
};
|
|
||||||
} finally {
|
|
||||||
clearTimeout(timer);
|
|
||||||
socket.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function resolveToken(port, timeoutMs, allowLegacyUi) {
|
|
||||||
const deadline = Date.now() + timeoutMs;
|
|
||||||
let lastError = 'WebView target not ready';
|
|
||||||
while (Date.now() < deadline) {
|
|
||||||
try {
|
|
||||||
const targets = await fetchTargets(port);
|
|
||||||
for (const target of targets) {
|
|
||||||
try {
|
|
||||||
return await evaluateEnsureService(
|
|
||||||
target.webSocketDebuggerUrl,
|
|
||||||
Math.min(15_000, deadline - Date.now()),
|
|
||||||
allowLegacyUi,
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
lastError = error instanceof Error ? error.message : 'CDP evaluation failed';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
lastError = error instanceof Error ? error.message : 'WebView debug endpoint unavailable';
|
|
||||||
}
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
||||||
}
|
|
||||||
throw new Error(lastError);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
if (process.argv.includes('--self-test')) {
|
|
||||||
if (typeof WebSocket !== 'function') throw new Error('WebSocket client is unavailable');
|
|
||||||
const valid = 'a'.repeat(MIN_TOKEN_LENGTH);
|
|
||||||
if (!isValidEndpoint({ port: 3333, instanceId: 'test-instance', bootstrapToken: valid })) {
|
|
||||||
throw new Error('valid endpoint fixture rejected');
|
|
||||||
}
|
|
||||||
if (isValidEndpoint({ port: 3333, instanceId: 'test-instance', bootstrapToken: 'short' })) {
|
|
||||||
throw new Error('short token fixture accepted');
|
|
||||||
}
|
|
||||||
const validRuntime = {
|
|
||||||
port: 3333,
|
|
||||||
instanceId: 'test-instance',
|
|
||||||
bootstrapToken: valid,
|
|
||||||
uiPath: '/home',
|
|
||||||
uiReady: true,
|
|
||||||
uiStartupState: 'ready',
|
|
||||||
uiTextLength: 10,
|
|
||||||
};
|
|
||||||
if (!isValidDesktopRuntime(validRuntime)) throw new Error('valid desktop runtime rejected');
|
|
||||||
if (isValidDesktopRuntime({ ...validRuntime, uiReady: false })) {
|
|
||||||
throw new Error('blank desktop runtime accepted');
|
|
||||||
}
|
|
||||||
if (isValidDesktopRuntime({ ...validRuntime, uiTextLength: 0 })) {
|
|
||||||
throw new Error('empty desktop runtime accepted');
|
|
||||||
}
|
|
||||||
if (isValidDesktopRuntime({ ...validRuntime, uiStartupState: 'loading' })) {
|
|
||||||
throw new Error('loading desktop runtime accepted');
|
|
||||||
}
|
|
||||||
if (isValidDesktopRuntime({ ...validRuntime, uiStartupState: 'failed' })) {
|
|
||||||
throw new Error('failed desktop runtime accepted');
|
|
||||||
}
|
|
||||||
if (!isValidDesktopRuntime({ ...validRuntime, uiStartupState: 'legacy-ready' }, true)) {
|
|
||||||
throw new Error('valid legacy desktop runtime rejected');
|
|
||||||
}
|
|
||||||
if (isValidDesktopRuntime({ ...validRuntime, uiReady: false, uiStartupState: 'legacy-ready' }, true)) {
|
|
||||||
throw new Error('blank legacy desktop runtime accepted');
|
|
||||||
}
|
|
||||||
console.log(JSON.stringify({ pass: true, cases: 9 }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const options = parseArgs(process.argv.slice(2));
|
|
||||||
const runtime = await resolveToken(options.port, options.timeoutMs, options.allowLegacyUi);
|
|
||||||
console.log(JSON.stringify(runtime));
|
|
||||||
}
|
|
||||||
|
|
||||||
main().catch((error) => fail(error instanceof Error ? error.message : 'unknown failure'));
|
|
||||||
336
scripts/release-smoke.mjs
Normal file
336
scripts/release-smoke.mjs
Normal file
@@ -0,0 +1,336 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Smoke tests the release workflow runs on every target after building.
|
||||||
|
*
|
||||||
|
* node scripts/release-smoke.mjs installer [--archive FILE] [--timeout SECONDS]
|
||||||
|
*
|
||||||
|
* Installs the server archive with the built installer
|
||||||
|
* (packages/launcher/dist/cli.js) into a temporary directory, runs
|
||||||
|
* `doctor`, starts `run` on a free port with a temporary data directory,
|
||||||
|
* waits for /health, stops the server and uninstalls. The default archive
|
||||||
|
* is the one in artifacts/ for this system.
|
||||||
|
*
|
||||||
|
* node scripts/release-smoke.mjs desktop --app PATH [--port 3333] [--timeout SECONDS]
|
||||||
|
*
|
||||||
|
* Starts the built desktop app (its executable, or a macOS .app bundle)
|
||||||
|
* with a temporary data directory, waits until its sidecar answers
|
||||||
|
* /health on 127.0.0.1:<port>, then stops the app and its sidecar and
|
||||||
|
* checks that the port is released. On Linux run it under xvfb-run.
|
||||||
|
*/
|
||||||
|
import { spawn, spawnSync } from 'node:child_process';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import net from 'node:net';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const isWindows = process.platform === 'win32';
|
||||||
|
|
||||||
|
// Keep in step with releaseTarget() in packages/launcher/src/platform.ts.
|
||||||
|
const TARGETS = {
|
||||||
|
'win32-x64': 'windows-x64',
|
||||||
|
'darwin-arm64': 'macos-arm64',
|
||||||
|
'darwin-x64': 'macos-x64',
|
||||||
|
'linux-x64': 'linux-x64',
|
||||||
|
};
|
||||||
|
|
||||||
|
class SmokeError extends Error {}
|
||||||
|
|
||||||
|
function log(message) {
|
||||||
|
console.log(`[release-smoke] ${message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sleep(ms) {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const [command, ...rest] = argv;
|
||||||
|
if (command !== 'installer' && command !== 'desktop') {
|
||||||
|
throw new SmokeError('Usage: release-smoke.mjs installer|desktop [options]');
|
||||||
|
}
|
||||||
|
const options = { port: 3333, timeout: 300 };
|
||||||
|
for (let i = 0; i < rest.length; i += 2) {
|
||||||
|
const [flag, value] = [rest[i], rest[i + 1]];
|
||||||
|
if (value === undefined) throw new SmokeError(`Missing value for ${flag}`);
|
||||||
|
if (flag === '--archive') options.archive = path.resolve(value);
|
||||||
|
else if (flag === '--app') options.app = path.resolve(value);
|
||||||
|
else if (flag === '--port' || flag === '--timeout') {
|
||||||
|
const number = Number(value);
|
||||||
|
if (!Number.isInteger(number) || number < 1) throw new SmokeError(`Invalid ${flag}: ${value}`);
|
||||||
|
options[flag.slice(2)] = number;
|
||||||
|
} else {
|
||||||
|
throw new SmokeError(`Unknown option: ${flag}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { command, options };
|
||||||
|
}
|
||||||
|
|
||||||
|
function tempRoot(name) {
|
||||||
|
return fs.mkdtempSync(path.join(process.env.RUNNER_TEMP || os.tmpdir(), `waggle-smoke-${name}-`));
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeTree(dir) {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 1000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
function portIsFree(port) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const server = net.createServer();
|
||||||
|
server.once('error', () => resolve(false));
|
||||||
|
server.listen(port, '127.0.0.1', () => server.close(() => resolve(true)));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function freePort() {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const server = net.createServer();
|
||||||
|
server.once('error', reject);
|
||||||
|
server.listen(0, '127.0.0.1', () => {
|
||||||
|
const { port } = server.address();
|
||||||
|
server.close(() => resolve(port));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The /health body of a Waggle server on this port, or null. */
|
||||||
|
async function health(port) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(2000) });
|
||||||
|
if (!response.ok) return null;
|
||||||
|
const body = await response.json();
|
||||||
|
return body && body.mode === 'local' ? body : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts a long-running process. On macOS and Linux it leads its own process
|
||||||
|
* group, so stopping the group also stops the sidecar it starts.
|
||||||
|
*/
|
||||||
|
function startBackground(label, command, args, env) {
|
||||||
|
const child = spawn(command, args, {
|
||||||
|
env,
|
||||||
|
stdio: ['ignore', 'inherit', 'inherit'],
|
||||||
|
detached: !isWindows,
|
||||||
|
windowsHide: true,
|
||||||
|
});
|
||||||
|
const state = { label, child, error: null, exited: false };
|
||||||
|
child.once('error', (error) => {
|
||||||
|
state.error = error;
|
||||||
|
});
|
||||||
|
child.once('exit', () => {
|
||||||
|
state.exited = true;
|
||||||
|
});
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
function waitForExit(state, ms) {
|
||||||
|
if (state.exited || state.error) return Promise.resolve(true);
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const timer = setTimeout(() => resolve(false), ms);
|
||||||
|
state.child.once('exit', () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
resolve(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForHealth(state, port, timeoutSeconds) {
|
||||||
|
const deadline = Date.now() + timeoutSeconds * 1000;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
if (state.error) throw new SmokeError(`${state.label} did not start: ${state.error.message}`);
|
||||||
|
if (state.exited) {
|
||||||
|
const { exitCode, signalCode } = state.child;
|
||||||
|
throw new SmokeError(`${state.label} exited (code ${exitCode}, signal ${signalCode}) before /health answered`);
|
||||||
|
}
|
||||||
|
const body = await health(port);
|
||||||
|
if (body) return body;
|
||||||
|
await sleep(1000);
|
||||||
|
}
|
||||||
|
throw new SmokeError(`${state.label} did not answer /health on 127.0.0.1:${port} within ${timeoutSeconds} s`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function signalGroup(pid, signal) {
|
||||||
|
try {
|
||||||
|
process.kill(-pid, signal);
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== 'ESRCH') throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForPortFree(port, ms) {
|
||||||
|
const deadline = Date.now() + ms;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
if (await portIsFree(port)) return true;
|
||||||
|
await sleep(500);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stops the process and everything it started, then checks the port is released. */
|
||||||
|
async function stopTree(state, port) {
|
||||||
|
if (state.child.pid === undefined) return;
|
||||||
|
if (isWindows) {
|
||||||
|
spawnSync('taskkill', ['/PID', String(state.child.pid), '/T', '/F'], { stdio: 'inherit', windowsHide: true });
|
||||||
|
await waitForExit(state, 10_000);
|
||||||
|
} else {
|
||||||
|
signalGroup(state.child.pid, 'SIGTERM');
|
||||||
|
if (!(await waitForExit(state, 15_000))) signalGroup(state.child.pid, 'SIGKILL');
|
||||||
|
await waitForExit(state, 5_000);
|
||||||
|
}
|
||||||
|
if (await waitForPortFree(port, 20_000)) return;
|
||||||
|
if (!isWindows) {
|
||||||
|
signalGroup(state.child.pid, 'SIGKILL');
|
||||||
|
if (await waitForPortFree(port, 10_000)) return;
|
||||||
|
}
|
||||||
|
throw new SmokeError(`Port ${port} is still in use after stopping ${state.label}: its server outlived it`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Waits for /health from a started process, then stops it. A failure to stop
|
||||||
|
* is reported after, not instead of, a failed health check.
|
||||||
|
*/
|
||||||
|
async function checkHealthThenStop(state, port, timeoutSeconds, onFailure = () => {}) {
|
||||||
|
let failure = null;
|
||||||
|
try {
|
||||||
|
await waitForHealth(state, port, timeoutSeconds);
|
||||||
|
log(`${state.label} answers /health on 127.0.0.1:${port}`);
|
||||||
|
} catch (error) {
|
||||||
|
failure = error;
|
||||||
|
onFailure();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await stopTree(state, port);
|
||||||
|
} catch (error) {
|
||||||
|
if (failure) console.error(`[release-smoke] ${error.message}`);
|
||||||
|
else failure = error;
|
||||||
|
}
|
||||||
|
if (failure) throw failure;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── installer ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function defaultArchive() {
|
||||||
|
const target = TARGETS[`${process.platform}-${process.arch}`];
|
||||||
|
if (!target) throw new SmokeError(`No release target for ${process.platform}-${process.arch}`);
|
||||||
|
const dir = path.join(root, 'artifacts');
|
||||||
|
const pattern = new RegExp(`^waggle-server-.+-${target}\\.tar\\.gz$`);
|
||||||
|
const matches = fs.existsSync(dir) ? fs.readdirSync(dir).filter((name) => pattern.test(name)) : [];
|
||||||
|
if (matches.length !== 1) {
|
||||||
|
throw new SmokeError(`Expected one ${target} server archive in artifacts/, found ${matches.length}. Pass --archive.`);
|
||||||
|
}
|
||||||
|
return path.join(dir, matches[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function runLauncher(launcher, args) {
|
||||||
|
log(`waggle-server ${args.join(' ')}`);
|
||||||
|
const result = spawnSync(process.execPath, [launcher, ...args], { encoding: 'utf8', windowsHide: true });
|
||||||
|
process.stdout.write(result.stdout ?? '');
|
||||||
|
process.stderr.write(result.stderr ?? '');
|
||||||
|
if (result.error) throw result.error;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** doctor must pass; the only warning allowed is that the command's directory is not on PATH. */
|
||||||
|
function checkDoctor(result) {
|
||||||
|
if (result.status !== 0) throw new SmokeError(`doctor failed with exit code ${result.status}`);
|
||||||
|
const warnings = result.stdout.split(/\r?\n/).filter((line) => /^\s*warn\s/.test(line));
|
||||||
|
const unexpected = warnings.filter((line) => !/^\s*warn\s+Command: .+ is not on your PATH$/.test(line));
|
||||||
|
if (unexpected.length > 0) throw new SmokeError(`doctor warned:\n${unexpected.join('\n')}`);
|
||||||
|
if (!/^\s*ok\s+Native modules: SQLite loads$/m.test(result.stdout)) {
|
||||||
|
throw new SmokeError('doctor did not report that SQLite loads with the bundled runtime');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function installerSmoke(options) {
|
||||||
|
const launcher = path.join(root, 'packages', 'launcher', 'dist', 'cli.js');
|
||||||
|
if (!fs.existsSync(launcher)) {
|
||||||
|
throw new SmokeError('packages/launcher/dist/cli.js is missing. Run: npm run build --workspace @waggle-ai/waggle');
|
||||||
|
}
|
||||||
|
const archive = options.archive ?? defaultArchive();
|
||||||
|
log(`Archive: ${archive}`);
|
||||||
|
const temp = tempRoot('installer');
|
||||||
|
const installDir = path.join(temp, 'install');
|
||||||
|
const dataDir = path.join(temp, 'data');
|
||||||
|
const location = ['--dir', installDir, '--bin-dir', path.join(temp, 'bin')];
|
||||||
|
try {
|
||||||
|
const install = runLauncher(launcher, ['install', '--from', archive, ...location]);
|
||||||
|
if (install.status !== 0) throw new SmokeError(`install failed with exit code ${install.status}`);
|
||||||
|
|
||||||
|
const port = await freePort();
|
||||||
|
checkDoctor(runLauncher(launcher, ['doctor', ...location, '--data-dir', dataDir, '--port', String(port)]));
|
||||||
|
|
||||||
|
log(`waggle-server run --no-open --port ${port}`);
|
||||||
|
const server = startBackground(
|
||||||
|
'The installed server',
|
||||||
|
process.execPath,
|
||||||
|
[launcher, 'run', '--no-open', '--port', String(port), '--dir', installDir, '--data-dir', dataDir],
|
||||||
|
process.env,
|
||||||
|
);
|
||||||
|
await checkHealthThenStop(server, port, options.timeout);
|
||||||
|
|
||||||
|
// Windows can hold the stopped runtime's files for a moment.
|
||||||
|
let uninstall;
|
||||||
|
for (let attempt = 1; attempt <= 5; attempt++) {
|
||||||
|
uninstall = runLauncher(launcher, ['uninstall', ...location, '--data-dir', dataDir]);
|
||||||
|
if (uninstall.status === 0) break;
|
||||||
|
await sleep(2000);
|
||||||
|
}
|
||||||
|
if (uninstall.status !== 0) throw new SmokeError(`uninstall failed with exit code ${uninstall.status}`);
|
||||||
|
if (fs.existsSync(installDir)) throw new SmokeError(`uninstall left ${installDir}`);
|
||||||
|
if (!fs.existsSync(dataDir)) throw new SmokeError('uninstall removed the data directory');
|
||||||
|
log('Installer smoke test passed');
|
||||||
|
} finally {
|
||||||
|
removeTree(temp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── desktop ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** The executable of a macOS .app bundle, or the given executable. */
|
||||||
|
function appExecutable(app) {
|
||||||
|
if (!fs.existsSync(app)) throw new SmokeError(`${app} does not exist`);
|
||||||
|
if (!app.endsWith('.app') || !fs.statSync(app).isDirectory()) return app;
|
||||||
|
const plist = fs.readFileSync(path.join(app, 'Contents', 'Info.plist'), 'utf8');
|
||||||
|
const name = /<key>CFBundleExecutable<\/key>\s*<string>([^<]+)<\/string>/.exec(plist)?.[1];
|
||||||
|
if (!name) throw new SmokeError(`${app}/Contents/Info.plist names no CFBundleExecutable`);
|
||||||
|
return path.join(app, 'Contents', 'MacOS', name);
|
||||||
|
}
|
||||||
|
|
||||||
|
function printServiceLog(dataDir) {
|
||||||
|
const file = path.join(dataDir, 'logs', 'service.log');
|
||||||
|
if (!fs.existsSync(file)) return;
|
||||||
|
const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
|
||||||
|
log(`Last lines of ${file}:`);
|
||||||
|
console.log(lines.slice(-200).join('\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function desktopSmoke(options) {
|
||||||
|
if (!options.app) throw new SmokeError('desktop needs --app <executable or .app bundle>');
|
||||||
|
const executable = appExecutable(options.app);
|
||||||
|
if (!(await portIsFree(options.port))) {
|
||||||
|
throw new SmokeError(`Port ${options.port} is in use; the desktop smoke test needs it free`);
|
||||||
|
}
|
||||||
|
const temp = tempRoot('desktop');
|
||||||
|
const dataDir = path.join(temp, 'data');
|
||||||
|
fs.mkdirSync(dataDir, { recursive: true });
|
||||||
|
try {
|
||||||
|
log(`Starting ${executable}`);
|
||||||
|
const app = startBackground('The desktop app', executable, [], { ...process.env, WAGGLE_DATA_DIR: dataDir });
|
||||||
|
await checkHealthThenStop(app, options.port, options.timeout, () => printServiceLog(dataDir));
|
||||||
|
log('Desktop smoke test passed');
|
||||||
|
} finally {
|
||||||
|
removeTree(temp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { command, options } = parseArgs(process.argv.slice(2));
|
||||||
|
await (command === 'installer' ? installerSmoke(options) : desktopSmoke(options));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`[release-smoke] FAILED: ${error instanceof Error ? error.message : String(error)}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
146
scripts/release-smoke.test.ts
Normal file
146
scripts/release-smoke.test.ts
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
/**
|
||||||
|
* scripts/release-smoke.mjs against stand-in payloads. The installer smoke
|
||||||
|
* test installs, checks, runs and removes a packed archive whose service is a
|
||||||
|
* small HTTP server; the desktop smoke test starts a stand-in .app that starts
|
||||||
|
* a stand-in sidecar, and must stop both.
|
||||||
|
*/
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import net from 'node:net';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { afterEach, describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
const ROOT = path.resolve(import.meta.dirname, '..');
|
||||||
|
const SMOKE = path.join(ROOT, 'scripts', 'release-smoke.mjs');
|
||||||
|
const LAUNCHER = path.join(ROOT, 'packages', 'launcher', 'dist', 'cli.js');
|
||||||
|
const TARGETS: Record<string, string> = {
|
||||||
|
'win32-x64': 'windows-x64',
|
||||||
|
'darwin-arm64': 'macos-arm64',
|
||||||
|
'darwin-x64': 'macos-x64',
|
||||||
|
'linux-x64': 'linux-x64',
|
||||||
|
};
|
||||||
|
const target = TARGETS[`${process.platform}-${process.arch}`];
|
||||||
|
|
||||||
|
// Answers /health the way the sidecar does.
|
||||||
|
const healthServer = (port: string) => `
|
||||||
|
const http = require('node:http');
|
||||||
|
const port = Number(${port});
|
||||||
|
http.createServer((request, response) => {
|
||||||
|
response.setHeader('content-type', 'application/json');
|
||||||
|
response.end(JSON.stringify(request.url === '/health' ? { status: 'ok', mode: 'local', port } : {}));
|
||||||
|
}).listen(port, '127.0.0.1');
|
||||||
|
`;
|
||||||
|
|
||||||
|
const temps: string[] = [];
|
||||||
|
function tempDir(prefix: string): string {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||||
|
temps.push(dir);
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
afterEach(() => {
|
||||||
|
for (const dir of temps.splice(0)) fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 500 });
|
||||||
|
});
|
||||||
|
|
||||||
|
function write(file: string, content: string, mode?: number): void {
|
||||||
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||||
|
fs.writeFileSync(file, content, { mode });
|
||||||
|
}
|
||||||
|
|
||||||
|
function freePort(): Promise<number> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const server = net.createServer();
|
||||||
|
server.once('error', reject);
|
||||||
|
server.listen(0, '127.0.0.1', () => {
|
||||||
|
const address = server.address() as net.AddressInfo;
|
||||||
|
server.close(() => resolve(address.port));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function runSmoke(args: string[]) {
|
||||||
|
return spawnSync(process.execPath, [SMOKE, ...args], { encoding: 'utf8', timeout: 120_000, windowsHide: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('release smoke tests', () => {
|
||||||
|
it.skipIf(!target || !fs.existsSync(LAUNCHER))(
|
||||||
|
'installs, checks, runs and uninstalls a server archive',
|
||||||
|
() => {
|
||||||
|
const work = tempDir('waggle-smoke-archive-');
|
||||||
|
const resources = path.join(work, 'resources');
|
||||||
|
const runtime = path.join(resources, process.platform === 'win32' ? 'node.exe' : 'node');
|
||||||
|
fs.mkdirSync(resources, { recursive: true });
|
||||||
|
// The payload runs on its own Node; this test's Node stands in for it.
|
||||||
|
if (process.platform === 'win32') fs.copyFileSync(process.execPath, runtime);
|
||||||
|
else fs.symlinkSync(process.execPath, runtime);
|
||||||
|
write(path.join(resources, 'service.js'), healthServer('process.env.WAGGLE_PORT'));
|
||||||
|
write(
|
||||||
|
path.join(resources, 'node_modules', 'better-sqlite3', 'index.js'),
|
||||||
|
'module.exports = class { prepare() { return { get: () => ({ 1: 1 }) }; } };\n',
|
||||||
|
);
|
||||||
|
write(path.join(work, 'web', 'index.html'), '<!doctype html>');
|
||||||
|
const out = path.join(work, 'out');
|
||||||
|
const pack = spawnSync(
|
||||||
|
process.execPath,
|
||||||
|
[
|
||||||
|
path.join(ROOT, 'scripts', 'build-server-archive.mjs'),
|
||||||
|
'--resources', resources, '--web', path.join(work, 'web'), '--out', out,
|
||||||
|
],
|
||||||
|
{ encoding: 'utf8' },
|
||||||
|
);
|
||||||
|
expect(pack.status, pack.stderr).toBe(0);
|
||||||
|
const archive = path.join(out, fs.readdirSync(out).find((name) => name.endsWith('.tar.gz'))!);
|
||||||
|
|
||||||
|
const result = runSmoke(['installer', '--archive', archive, '--timeout', '60']);
|
||||||
|
expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
|
||||||
|
expect(result.stdout).toContain('The installed server answers /health');
|
||||||
|
expect(result.stdout).toContain('Installer smoke test passed');
|
||||||
|
},
|
||||||
|
150_000,
|
||||||
|
);
|
||||||
|
|
||||||
|
it.skipIf(process.platform === 'win32')(
|
||||||
|
'starts a desktop app bundle and stops it together with its sidecar',
|
||||||
|
async () => {
|
||||||
|
const port = await freePort();
|
||||||
|
const work = tempDir('waggle-smoke-desktop-');
|
||||||
|
const contents = path.join(work, 'Stand-in.app', 'Contents');
|
||||||
|
write(
|
||||||
|
path.join(contents, 'Info.plist'),
|
||||||
|
'<plist><dict><key>CFBundleExecutable</key>\n <string>stand-in</string></dict></plist>\n',
|
||||||
|
);
|
||||||
|
write(path.join(work, 'sidecar.js'), healthServer(String(port)));
|
||||||
|
// The app stays alive and owns a child process that serves /health.
|
||||||
|
write(
|
||||||
|
path.join(work, 'app.js'),
|
||||||
|
`require('node:child_process').spawn(process.execPath, [${JSON.stringify(path.join(work, 'sidecar.js'))}], { stdio: 'inherit' });\n`
|
||||||
|
+ 'setInterval(() => {}, 1000);\n',
|
||||||
|
);
|
||||||
|
write(
|
||||||
|
path.join(contents, 'MacOS', 'stand-in'),
|
||||||
|
`#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(path.join(work, 'app.js'))}\n`,
|
||||||
|
0o755,
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = runSmoke(['desktop', '--app', path.join(work, 'Stand-in.app'), '--port', String(port), '--timeout', '30']);
|
||||||
|
expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
|
||||||
|
expect(result.stdout).toContain(`answers /health on 127.0.0.1:${port}`);
|
||||||
|
expect(result.stdout).toContain('Desktop smoke test passed');
|
||||||
|
|
||||||
|
const probe = net.connect(port, '127.0.0.1');
|
||||||
|
const connected = await new Promise<boolean>((resolve) => {
|
||||||
|
probe.once('connect', () => resolve(true));
|
||||||
|
probe.once('error', () => resolve(false));
|
||||||
|
});
|
||||||
|
probe.destroy();
|
||||||
|
expect(connected).toBe(false);
|
||||||
|
},
|
||||||
|
90_000,
|
||||||
|
);
|
||||||
|
|
||||||
|
it('rejects a desktop run without an app and unknown options', () => {
|
||||||
|
expect(runSmoke(['desktop']).stderr).toContain('desktop needs --app');
|
||||||
|
expect(runSmoke(['installer', '--fast', '1']).stderr).toContain('Unknown option: --fast');
|
||||||
|
expect(runSmoke(['publish']).status).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user