ci(release): replace the commercial pipeline with an unsigned build for three systems (P1.3d)

release.yml now has one build job with a matrix over the four release
targets (windows-x64, macos-arm64, macos-x64, linux-x64). Each leg stages
the sidecar, checks it, builds the web UI, packs the server archive for
the installer (ADR-0009), runs the installer smoke test, builds the
desktop installers (NSIS and MSI, app and DMG, deb and AppImage), runs
the packaged app until its sidecar answers /health, and uploads the
installers and archives. A pushed v* tag also gets a draft GitHub
release with a SHA256SUMS file, created with GITHUB_TOKEN only. Pull
requests on the desktop paths and manual runs build and test without
publishing, so tauri-build-pr.yml is removed.

Nothing is signed or notarized. The macOS app gets an ad-hoc signature
("-"), which needs no certificate; without it macOS reports a downloaded
Apple Silicon app as damaged.

Removed with the old pipeline, as nothing else used them: the Windows
signing handoff and signer (sign-windows-artifact.ps1 and its tests,
new-windows-signing-handoff.ps1), the pilot signing scripts
(sign-windows-pilot.ps1, apply-signing-config.mjs, signing-config.ts and
its test, sign-macos-adhoc.sh, tauri.build-override.conf.json and the
tauri:sign:* and tauri:build:win:pilot-signed scripts), the installer
certifier with its bootstrap-token helper, and the Windows release
publisher. check-sidecar-resources.mjs stays: tauri.conf.json runs it
before every desktop build and the workflow runs it before packing the
archive.

app/package.json gains tauri:build:linux. The tests that pinned the old
workflows, the certifier, the signer and the publisher are removed;
new tests pin the targets, the step order, the absence of signing and of
secrets other than GITHUB_TOKEN, and the draft-only, tag-only publish.
This commit is contained in:
shumeiko.it
2026-11-01 02:08:31 +01:00
parent a73abd4d54
commit 687e3b86c7
17 changed files with 336 additions and 20751 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -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

View File

@@ -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",

View File

@@ -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

View File

@@ -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

View File

@@ -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
}

View File

@@ -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('-');
});
});

View File

@@ -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,
};
}

View File

@@ -1,10 +0,0 @@
{
"build": {
"beforeBuildCommand": ""
},
"bundle": {
"macOS": {
"signingIdentity": "-"
}
}
}

View File

@@ -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);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -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'

View File

@@ -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'));