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

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