Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(release): make macOS signing observable, bounded, and repairable

vastsad54cc16a1d3e
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 2e6670aee..fb4e1af86 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -208,6 +208,14 @@ jobs:
# pattern labels ZIPs, and the dmg target pattern labels DMGs.
pnpm --filter @pi-desktop/desktop run dist:mac -- --${{ matrix.arch }}
+ - name: Diagnose macOS signing environment
+ # Records the runner baseline (system, codesign, identities, keychain,
+ # Xcode tools, Apple timestamp reachability) before electron-builder
+ # imports the certificate. Informational: the Developer ID identity is
+ # absent here by design and is imported from CSC_LINK during packaging.
+ if: matrix.platform == 'macos'
+ run: scripts/macos-signing-diagnostics.sh
+
- name: Require macOS signing and notarization secrets
if: matrix.platform == 'macos' && env.MACOS_SIGN_RELEASE == 'true'
env:
@@ -246,13 +254,46 @@ jobs:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ # electron-builder prints one "signing PI-Desktop.app" line and then
+ # goes quiet: @electron/osx-sign walks Contents and codesigns every
+ # Mach-O serially, builder-util silently retries a failing pass up to
+ # three times, and @electron/notarize zips, uploads, and waits for
+ # Apple's queue. These two namespaces expose all three phases without
+ # leaking credentials, because both render their own command lines
+ # through a password filter. `electron-builder` itself is deliberately
+ # absent: builder-util's `executing` debug line prints every spawned
+ # command with only its own stem list redacted, and that list does not
+ # cover `security set-key-partition-list -k <p12 password>`. The
+ # watchdog redacts the secret values and any --password/-k argument on
+ # top of that.
+ DEBUG: "electron-osx-sign*,electron-notarize*"
+ # 30 minutes keeps a stuck signing/notarization phase reported by the
+ # watchdog (diagnostics + summary) inside the 60-minute job budget.
+ PI_SIGNING_TIMEOUT_SECONDS: "1800"
+ PI_SIGNING_STALL_SECONDS: "300"
run: |
set -euo pipefail
# Artifact names are defined in apps/desktop/package.json: the mac
# pattern labels ZIPs, and the dmg target pattern labels DMGs.
- pnpm --filter @pi-desktop/desktop run dist:mac -- --${{ matrix.arch }} \
- -c.mac.forceCodeSigning=true \
- -c.mac.notarize=true
+ # The watchdog forwards every line unchanged and keeps the child's
+ # exit code; it adds a heartbeat while the phase is silent, dumps the
+ # active codesign target and process state when it stalls, reports
+ # per-file codesign timings, and fails the step after
+ # PI_SIGNING_TIMEOUT_SECONDS instead of waiting for the job timeout.
+ node scripts/macos-signing-watchdog.mjs \
+ --label "dist:mac-${{ matrix.arch }}" \
+ -- pnpm --filter @pi-desktop/desktop run dist:mac -- --${{ matrix.arch }} \
+ -c.mac.forceCodeSigning=true \
+ -c.mac.notarize=true
+
+ - name: Analyze the packaged macOS app bundle
+ # Reports the file / Mach-O / framework / nested-bundle counts that
+ # determine how much work the signing phase had, on the exact bundle the
+ # release just produced. Diagnosis only: continue-on-error keeps a
+ # surprising bundle layout from failing a release.
+ if: matrix.platform == 'macos'
+ continue-on-error: true
+ run: node scripts/macos-bundle-inventory.mjs apps/desktop/release
- name: Notarize and staple the macOS DMG
if: matrix.platform == 'macos' && env.MACOS_SIGN_RELEASE == 'true'
@@ -260,7 +301,17 @@ jobs:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
- run: scripts/notarize-and-staple-macos-release-dmg.sh apps/desktop/release
+ # 20 minutes bounds the second Apple wait; the packaging phase owns
+ # the first one.
+ PI_SIGNING_TIMEOUT_SECONDS: "1200"
+ PI_SIGNING_STALL_SECONDS: "300"
+ run: |
+ set -euo pipefail
+ # notarytool submit --wait blocks until Apple answers; the watchdog
+ # keeps that wait observable and bounded.
+ node scripts/macos-signing-watchdog.mjs \
+ --label "notarize-dmg-${{ matrix.arch }}" \
+ -- scripts/notarize-and-staple-macos-release-dmg.sh apps/desktop/release
- name: Verify signed and notarized macOS installer
if: matrix.platform == 'macos' && env.MACOS_SIGN_RELEASE == 'true'
diff --git a/apps/desktop/test/ci-workflow.test.mjs b/apps/desktop/test/ci-workflow.test.mjs
index ad0ec3e47..053fccba8 100644
--- a/apps/desktop/test/ci-workflow.test.mjs
+++ b/apps/desktop/test/ci-workflow.test.mjs
@@ -1,5 +1,5 @@
import assert from "node:assert/strict";
-import { readFile } from "node:fs/promises";
+import { access, readFile } from "node:fs/promises";
import test from "node:test";
const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
@@ -255,6 +255,24 @@ test("macOS release signing is required on tag pushes", () => {
assert.doesNotMatch(signedBlock, /-c\.mac\.identity=/);
assert.doesNotMatch(signedBlock, /CSC_NAME: "Developer ID Application:/);
assert.match(signedBlock, /-c\.mac\.notarize=true/);
+ // The single "signing PI-Desktop.app" line electron-builder prints does not
+ // tell walking, per-file codesign, silent retries, and the Apple
+ // notarization wait apart; the signing trace and the watchdog carry the rest.
+ assert.match(
+ signedBlock,
+ /DEBUG: "electron-osx-sign\*,electron-notarize\*"/,
+ );
+ // builder-util's `executing` debug line prints every spawned command with a
+ // stem list that does not cover `security set-key-partition-list -k <p12
+ // password>`, so electron-builder's namespace is deliberately excluded.
+ assert.doesNotMatch(signedBlock, /DEBUG: ".*electron-builder.*"/);
+ assert.match(signedBlock, /PI_SIGNING_TIMEOUT_SECONDS: "1800"/);
+ assert.match(signedBlock, /PI_SIGNING_STALL_SECONDS: "300"/);
+ assert.match(
+ signedBlock,
+ /node scripts\/macos-signing-watchdog\.mjs \\\n\s+--label "dist:mac-\$\{\{ matrix\.arch \}\}" \\\n\s+-- pnpm --filter @pi-desktop\/desktop run dist:mac/,
+ "the signed macOS packaging phase runs under the signing watchdog",
+ );
// electron-builder notarizes only the .app; the DMG needs its own
// submission before the ticket can be stapled (error 65 otherwise).
const dmgBlock = releaseWorkflowSource.match(
@@ -274,7 +292,14 @@ test("macOS release signing is required on tag pushes", () => {
}
assert.match(
dmgBlock,
- /run: scripts\/notarize-and-staple-macos-release-dmg\.sh apps\/desktop\/release/,
+ /node scripts\/macos-signing-watchdog\.mjs[\s\S]*?-- scripts\/notarize-and-staple-macos-release-dmg\.sh apps\/desktop\/release/,
+ "the DMG notarization wait runs under the signing watchdog",
+ );
+ assert.match(dmgBlock, /PI_SIGNING_TIMEOUT_SECONDS: "1200"/);
+ assert.match(
+ releaseWorkflowSource,
+ /- name: Analyze the packaged macOS app bundle[\s\S]*?if: matrix\.platform == 'macos'[\s\S]*?continue-on-error: true[\s\S]*?run: node scripts\/macos-bundle-inventory\.mjs apps\/desktop\/release/,
+ "the packaged macOS bundle is measured, without failing a release",
);
assert.match(
releaseWorkflowSource,
@@ -299,6 +324,78 @@ test("the signed local macOS lane selects the native runner architecture", () =>
/-c\.(?:dmg|zip)\.artifactName/,
"the signed local macOS lane uses the shared artifact naming config",
);
+ // The local lane documents itself as Developer ID + mandatory
+ // notarization, so it must pass both flags and must not publish.
+ assert.match(releaseMacScriptSource, /-c\.mac\.notarize=true/);
+ assert.match(releaseMacScriptSource, /-c\.mac\.forceCodeSigning=true/);
+ assert.match(releaseMacScriptSource, /--publish never/);
+ assert.doesNotMatch(
+ releaseMacScriptSource,
+ /DEBUG="\$\{DEBUG:-[^}]*electron-builder/,
+ "the local lane must not enable builder-util's executing debug line",
+ );
+ assert.match(
+ releaseMacScriptSource,
+ /node scripts\/macos-signing-watchdog\.mjs --label "release-macos-\$\{MAC_ARCH\}" --/,
+ "the local signed macOS lane runs under the signing watchdog",
+ );
+ assert.match(
+ releaseMacScriptSource,
+ /node scripts\/macos-bundle-inventory\.mjs apps\/desktop\/release/,
+ );
+ // The DMG is submitted, stapled, and validated once, and the release is
+ // verified exactly once.
+ assert.match(
+ releaseMacScriptSource,
+ /scripts\/notarize-and-staple-macos-release-dmg\.sh apps\/desktop\/release/,
+ );
+ assert.equal(
+ (releaseMacScriptSource.match(/scripts\/verify-macos-release\.sh/g) ?? []).length,
+ 1,
+ "the local signed macOS lane verifies the release exactly once",
+ );
+ assert.doesNotMatch(releaseMacScriptSource, /scripts\/staple-macos-release-dmg\.sh/);
+});
+
+/**
+ * The regression that broke the local signed lane: a rewrite replaced the
+ * electron-builder flags with two commands but kept the line continuation, so
+ * one command became a positional argument while the other still pointed at a
+ * deleted script. Every script path either lane references must exist.
+ */
+test("both macOS lanes only reference scripts that exist", async () => {
+ const referenced = new Set();
+ for (const source of [releaseMacScriptSource, releaseWorkflowSource]) {
+ for (const match of source.matchAll(/(?<![\w./-])scripts\/[A-Za-z0-9._-]+\.(?:sh|mjs)/g)) {
+ referenced.add(match[0]);
+ }
+ }
+ assert.ok(referenced.size >= 6, "the macOS lanes reference their scripts");
+ const missing = [];
+ for (const relPath of referenced) {
+ try {
+ await access(new URL(`../../../${relPath}`, import.meta.url));
+ } catch {
+ missing.push(relPath);
+ }
+ }
+ assert.deepEqual(missing, []);
+});
+
+test("macOS signing instrumentation stays out of the Windows and Linux lanes", () => {
+ const instrumentation =
+ /macos-signing-watchdog|macos-signing-diagnostics|macos-bundle-inventory/;
+ const stepBlock = (name) =>
+ releaseWorkflowSource.match(new RegExp(`- name: ${name}[^]*?(?=\\n - name:)`))?.[0] ??
+ "";
+ assert.doesNotMatch(stepBlock("Package installers"), instrumentation);
+ assert.doesNotMatch(stepBlock("Verify Linux host-core glibc floor"), instrumentation);
+ assert.doesNotMatch(stepBlock("Export Linux ASAR release asset"), instrumentation);
+ // The unsigned macOS debug lane reports its bundle size but must not gain a
+ // signing identity, notarization, or publishing behaviour.
+ const unsignedBlock = stepBlock("Package unsigned macOS installer");
+ assert.ok(unsignedBlock, "unsigned macOS debug package step is missing");
+ assert.doesNotMatch(unsignedBlock, instrumentation);
});
test("GitHub releases trigger the CNB mirror pipeline with a JSON payload", () => {
diff --git a/apps/desktop/test/macos-release-lane.test.mjs b/apps/desktop/test/macos-release-lane.test.mjs
new file mode 100644
index 000000000..f70b0eddb
--- /dev/null
+++ b/apps/desktop/test/macos-release-lane.test.mjs
@@ -0,0 +1,150 @@
+import assert from "node:assert/strict";
+import { chmod, cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { spawnSync } from "node:child_process";
+import test from "node:test";
+
+/**
+ * End-to-end structure test for the signed local macOS lane.
+ *
+ * The lane was broken by a rewrite that turned two electron-builder flags into
+ * two commands but kept the line continuation, so the notarization script
+ * became a positional argument of electron-builder while a second command kept
+ * pointing at a deleted script. Nothing failed until a real signed run weeks
+ * later. This drives the whole script against stub tooling in a temporary
+ * repository root, so the command structure, the flag set, and the phase order
+ * are pinned without a certificate, a network, or a real package build.
+ */
+
+const scripts = new URL("../../../scripts/", import.meta.url);
+const LANE_SCRIPTS = [
+ "release-macos.sh",
+ "notarize-and-staple-macos-release-dmg.sh",
+ "verify-macos-release.sh",
+ "macos-signing-watchdog.mjs",
+ "macos-codesign-shim.sh",
+ "macos-bundle-inventory.mjs",
+];
+const SIGNING_IDENTITY = "Developer ID Application: XingYu Liu (DUV63RKYTW)";
+const SUBMISSION_ID = "11111111-2222-3333-4444-555555555555";
+
+async function writeStubs(bin, log, repoRoot) {
+ await mkdir(bin, { recursive: true });
+ const stubs = {
+ cargo: `#!/usr/bin/env bash
+printf 'cargo %s\\n' "$*" >> "${log}"
+exit 0
+`,
+ // The lane's only job here is to call the toolchain in the documented
+ // order; the packaging stub produces the artifacts the later steps expect.
+ pnpm: `#!/usr/bin/env bash
+printf 'pnpm %s\\n' "$*" >> "${log}"
+case "$*" in
+ *electron-builder*)
+ app="${repoRoot}/apps/desktop/release/mac-arm64/PI-Desktop.app"
+ mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources/bin"
+ : > "$app/Contents/MacOS/PI-Desktop"
+ : > "$app/Contents/Resources/bin/pi-desktop-host-core"
+ : > "${repoRoot}/apps/desktop/release/PI-Desktop-0.0.0-arm64.dmg"
+ ;;
+esac
+exit 0
+`,
+ codesign: `#!/usr/bin/env bash
+printf 'codesign %s\\n' "$*" >> "${log}"
+if [[ "$*" == *"-dv"* ]]; then
+ echo "Authority=${SIGNING_IDENTITY}" >&2
+ echo "flags=0x10000(runtime)" >&2
+fi
+exit 0
+`,
+ spctl: `#!/usr/bin/env bash
+printf 'spctl %s\\n' "$*" >> "${log}"
+echo "source=Notarized Developer ID" >&2
+exit 0
+`,
+ xcrun: `#!/usr/bin/env bash
+printf 'xcrun %s\\n' "$*" >> "${log}"
+case "$1 $2" in
+ "notarytool submit")
+ echo " id: ${SUBMISSION_ID}"
+ echo " status: Accepted"
+ ;;
+esac
+exit 0
+`,
+ };
+ for (const [name, body] of Object.entries(stubs)) {
+ await writeFile(join(bin, name), body);
+ await chmod(join(bin, name), 0o755);
+ }
+}
+
+test(
+ "the signed local macOS lane runs electron-builder with every documented flag",
+ { skip: process.platform !== "darwin" ? "macOS-only lane" : false },
+ async (t) => {
+ const root = await mkdtemp(join(tmpdir(), "pi-desktop-macos-lane-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+
+ const repoRoot = join(root, "repo");
+ const bin = join(root, "bin");
+ const log = join(root, "calls.log");
+ await mkdir(join(repoRoot, "scripts"), { recursive: true });
+ await mkdir(join(repoRoot, "apps/desktop"), { recursive: true });
+ for (const name of LANE_SCRIPTS) {
+ await cp(new URL(name, scripts), join(repoRoot, "scripts", name));
+ }
+ await chmod(join(repoRoot, "scripts", "release-macos.sh"), 0o755);
+ await writeStubs(bin, log, repoRoot);
+
+ const result = spawnSync("bash", [join(repoRoot, "scripts", "release-macos.sh")], {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ PATH: `${bin}:${process.env.PATH}`,
+ APPLE_ID: "[email protected]",
+ APPLE_APP_SPECIFIC_PASSWORD: "app-specific-password",
+ APPLE_TEAM_ID: "DUV63RKYTW",
+ STAPLE_DELAY_SECONDS: "1",
+ },
+ });
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ const calls = (await readFile(log, "utf8")).trim().split("\n");
+
+ const builderCall = calls.find((line) => line.includes("electron-builder"));
+ assert.ok(builderCall, "the lane invokes electron-builder");
+ assert.match(builderCall, /--mac --(?:arm64|x64)/);
+ assert.match(builderCall, /--publish never/);
+ assert.match(builderCall, /-c\.mac\.identity=XingYu Liu \(DUV63RKYTW\)/);
+ assert.match(builderCall, /-c\.mac\.forceCodeSigning=true/);
+ assert.match(builderCall, /-c\.mac\.notarize=true/);
+ assert.doesNotMatch(
+ builderCall,
+ /notarize-and-staple-macos-release-dmg\.sh/,
+ "the DMG script must be a command, not an electron-builder argument",
+ );
+
+ // The lane must submit, staple, and verify exactly once, in that order.
+ const indexOfCall = (pattern) => calls.findIndex((line) => pattern.test(line));
+ const submitIndex = indexOfCall(/^xcrun notarytool submit /);
+ const stapleIndex = indexOfCall(/^xcrun stapler staple /);
+ const validateIndex = calls.findIndex((line) => /^xcrun stapler validate /.test(line));
+ const verifyIndex = calls.findIndex((line) => /verify-macos-release\.sh|^codesign -dv/.test(line));
+ assert.ok(submitIndex > -1 && stapleIndex > submitIndex, "the DMG is submitted before stapling");
+ assert.ok(validateIndex > stapleIndex, "the stapled ticket is validated");
+ assert.ok(verifyIndex > validateIndex, "verification happens after stapling");
+ assert.equal(
+ calls.filter((line) => /^xcrun notarytool submit /.test(line)).length,
+ 1,
+ "one DMG submission",
+ );
+
+ // The packaging phase stays wrapped, and the watchdog reports its summary.
+ assert.match(result.stdout, /\[sign\] summary label=release-macos-/);
+ assert.match(result.stdout, /Analyzing the packaged app bundle/);
+ assert.doesNotMatch(result.stdout, /STALL/);
+ },
+);
diff --git a/apps/desktop/test/macos-signing-diagnostics.test.mjs b/apps/desktop/test/macos-signing-diagnostics.test.mjs
new file mode 100644
index 000000000..f8a7eac29
--- /dev/null
+++ b/apps/desktop/test/macos-signing-diagnostics.test.mjs
@@ -0,0 +1,582 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+// Both scripts are plain bash / node CLI tools with no dependencies, so these
+// tests drive them through a fake PATH and a temporary bundle fixture instead of
+// importing repository code.
+
+const diagnosticsScript = fileURLToPath(
+ new URL("../../../scripts/macos-signing-diagnostics.sh", import.meta.url),
+);
+const inventoryScript = fileURLToPath(
+ new URL("../../../scripts/macos-bundle-inventory.mjs", import.meta.url),
+);
+
+const SIGNING_IDENTITY_NAME = "XingYu Liu (DUV63RKYTW)";
+const SIGNING_IDENTITY = `Developer ID Application: ${SIGNING_IDENTITY_NAME}`;
+const NO_IDENTITIES = " 0 valid identities found";
+const MATCHING_IDENTITY = `echo ' 1) 0123456789ABCDEF "Developer ID Application: ${SIGNING_IDENTITY_NAME}"'
+echo ' 1 valid identities found'`;
+
+const CSC_LINK_SENTINEL = "SENTINEL-CSC-LINK-1234";
+const CSC_PASSWORD_SENTINEL = "SENTINEL-CSC-KEY-PASSWORD-5678";
+const APPLE_PASSWORD_SENTINEL = "SENTINEL-APPLE-PASSWORD-9012";
+const APPLE_ID_SENTINEL = "[email protected]";
+
+// The scripts must behave the same whether or not the surrounding environment
+// carries signing secrets, so every test starts from a scrubbed copy.
+const BASE_ENV = { ...process.env };
+for (const name of [
+ "MAC_SIGNING_IDENTITY",
+ "CSC_LINK",
+ "CSC_KEY_PASSWORD",
+ "APPLE_ID",
+ "APPLE_APP_SPECIFIC_PASSWORD",
+ "APPLE_TEAM_ID",
+]) {
+ delete BASE_ENV[name];
+}
+
+async function writeShim(bin, name, body) {
+ await mkdir(bin, { recursive: true });
+ const file = join(bin, name);
+ await writeFile(file, `#!/usr/bin/env bash\n${body.trim()}\n`);
+ await chmod(file, 0o755);
+ return file;
+}
+
+/**
+ * A complete fake macOS signing environment. `identities` is shell code printed
+ * by `security find-identity`; `leaky` makes every shim echo the signing secrets
+ * from the environment, which is how the redaction contract is tested.
+ */
+async function writeDiagnosticsShims(
+ bin,
+ {
+ identities = NO_IDENTITIES,
+ unameSystem = "Darwin",
+ leaky = false,
+ } = {},
+) {
+ const leak = leaky
+ ? `echo "CSC_LINK=\${CSC_LINK:-}"
+echo "CSC_KEY_PASSWORD=\${CSC_KEY_PASSWORD:-}"
+echo "APPLE_ID=\${APPLE_ID:-}"
+echo "APPLE_APP_SPECIFIC_PASSWORD=\${APPLE_APP_SPECIFIC_PASSWORD:-}"
+echo "APPLE_TEAM_ID=\${APPLE_TEAM_ID:-}"`
+ : "";
+
+ await writeShim(
+ bin,
+ "uname",
+ `case "\${1:-}" in
+ -s) echo "${unameSystem}" ;;
+ -m) echo "arm64" ;;
+ *) echo "${unameSystem} fakehost 24.6.0 arm64" ;;
+esac
+exit 0`,
+ );
+ await writeShim(
+ bin,
+ "sw_vers",
+ `echo "ProductName: macOS"
+echo "ProductVersion: 15.7.5"
+echo "BuildVersion: 24G624"
+${leak}
+exit 0`,
+ );
+ await writeShim(
+ bin,
+ "codesign",
+ `if [[ "\${1:-}" == "--version" ]]; then
+ echo "codesign fake 1.0.0"
+ ${leak}
+fi
+exit 0`,
+ );
+ await writeShim(
+ bin,
+ "security",
+ `if [[ "\${1:-}" == "find-identity" ]]; then
+${identities}
+ exit 0
+fi
+echo "fake keychain"
+${leak}
+exit 0`,
+ );
+ await writeShim(
+ bin,
+ "xcrun",
+ `if [[ "\${1:-}" == "--find" ]]; then
+ echo "/fake/Xcode/usr/bin/\${2:-tool}"
+ exit 0
+fi
+echo "xcrun fake"
+${leak}
+exit 0`,
+ );
+ await writeShim(
+ bin,
+ "curl",
+ `echo "302 0.512345"
+${leak}
+exit 0`,
+ );
+}
+
+function runDiagnostics(bin, { args = [], env = {} } = {}) {
+ return spawnSync("bash", [diagnosticsScript, ...args], {
+ encoding: "utf8",
+ env: { ...BASE_ENV, PATH: `${bin}:${process.env.PATH}`, ...env },
+ });
+}
+
+function runInventory(args, env = {}) {
+ return spawnSync(process.execPath, [inventoryScript, ...args], {
+ encoding: "utf8",
+ env: { ...BASE_ENV, ...env },
+ timeout: 30_000,
+ });
+}
+
+function parseInventoryJson(stdout) {
+ const line = stdout
+ .split("\n")
+ .find((entry) => entry.startsWith("inventory-json: "));
+ assert.ok(line, `no inventory-json line in output:\n${stdout}`);
+ return JSON.parse(line.slice("inventory-json: ".length));
+}
+
+// 64-bit little-endian Mach-O magic, i.e. the first four bytes of every file
+// osx-sign treats as a signing candidate.
+const MACH_O_HEADER = Buffer.from([0xcf, 0xfa, 0xed, 0xfe]);
+
+async function writeFileWithParents(file, content, mode = 0o644) {
+ await mkdir(dirname(file), { recursive: true });
+ await writeFile(file, content);
+ await chmod(file, mode);
+}
+
+async function writeMachO(file, bytes, mode = 0o755) {
+ await writeFileWithParents(
+ file,
+ Buffer.concat([MACH_O_HEADER, Buffer.alloc(Math.max(0, bytes - 4))]),
+ mode,
+ );
+}
+
+/**
+ * A resource that is not Mach-O but looks binary: a NUL byte inside the first
+ * 8 KiB is what makes osx-sign give the file its own `codesign` call.
+ */
+async function writeBinaryResource(file, bytes, mode = 0o644) {
+ await writeFileWithParents(
+ file,
+ Buffer.concat([Buffer.from("RESOURCE"), Buffer.alloc(bytes)]),
+ mode,
+ );
+}
+
+function appFixturePath(release) {
+ return join(release, "mac-arm64", "PI-Desktop.app");
+}
+
+async function tempRoot(t, prefix) {
+ const root = await mkdtemp(join(tmpdir(), prefix));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ return root;
+}
+
+/**
+ * The bundle used by the counting tests:
+ * Contents/MacOS/PI-Desktop mach-o, executable
+ * Contents/Frameworks/Foo.framework/Versions/A/Foo mach-o in a framework
+ * Contents/Frameworks/Foo.framework/Versions/Current symlink to A
+ * Contents/Frameworks/Helper.app/Contents/MacOS/Helper text, nested bundle
+ * Contents/Resources/bin/pi-desktop-host-core mach-o, executable
+ * Contents/Resources/bin/run.sh script, executable
+ * Contents/Resources/native.dylib text
+ * Contents/Resources/native.node text
+ * Contents/Resources/icudtl.dat binary-looking (NUL)
+ * Contents/Info.plist text
+ * => 9 files, 11 directories, 1 symlink, 3 mach-o, 1 nested app, 1 binary
+ * resource
+ */
+async function writeBundleFixture(release) {
+ const app = appFixturePath(release);
+ await writeMachO(join(app, "Contents", "MacOS", "PI-Desktop"), 4100);
+ await writeMachO(
+ join(app, "Contents", "Frameworks", "Foo.framework", "Versions", "A", "Foo"),
+ 516,
+ );
+ await writeMachO(
+ join(app, "Contents", "Resources", "bin", "pi-desktop-host-core"),
+ 2052,
+ );
+ await writeFileWithParents(
+ join(app, "Contents", "Frameworks", "Helper.app", "Contents", "MacOS", "Helper"),
+ "helper-stand-in",
+ );
+ await writeFileWithParents(
+ join(app, "Contents", "Resources", "bin", "run.sh"),
+ "#!/bin/sh\nexit 0\n",
+ 0o755,
+ );
+ await writeFileWithParents(join(app, "Contents", "Resources", "native.dylib"), "dylib-fixture");
+ await writeFileWithParents(join(app, "Contents", "Resources", "native.node"), "node-fixture");
+ await writeBinaryResource(join(app, "Contents", "Resources", "icudtl.dat"), 64);
+ await writeFileWithParents(join(app, "Contents", "Info.plist"), "<plist/>");
+ await symlink(
+ "A",
+ join(app, "Contents", "Frameworks", "Foo.framework", "Versions", "Current"),
+ );
+ return app;
+}
+
+test("diagnostics report an available Developer ID identity", async (t) => {
+ const root = await tempRoot(t, "pi-desktop-signing-diagnostics-");
+ const bin = join(root, "bin");
+ await writeDiagnosticsShims(bin, { identities: MATCHING_IDENTITY });
+
+ const result = runDiagnostics(bin);
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.match(result.stdout, /^==> System$/m);
+ assert.match(result.stdout, /^==> codesign$/m);
+ assert.match(result.stdout, /^==> Keychain$/m);
+ assert.match(result.stdout, /^==> Xcode toolchain$/m);
+ assert.ok(
+ result.stdout.includes(`==> Developer ID identity available: ${SIGNING_IDENTITY}`),
+ result.stdout,
+ );
+ assert.ok(
+ result.stdout.includes(`"${SIGNING_IDENTITY}"`),
+ "the matching find-identity line is echoed",
+ );
+ assert.doesNotMatch(result.stdout, /is not available/);
+});
+
+test("diagnostics fail closed when --require-identity finds no identity", async (t) => {
+ const root = await tempRoot(t, "pi-desktop-signing-required-");
+ const bin = join(root, "bin");
+ await writeDiagnosticsShims(bin, { identities: NO_IDENTITIES });
+
+ const result = runDiagnostics(bin, { args: ["--require-identity"] });
+
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /not available/);
+ assert.ok(
+ result.stdout.includes(
+ `warning: Developer ID Application: ${SIGNING_IDENTITY_NAME} is not available in the current keychain`,
+ ),
+ result.stdout,
+ );
+});
+
+test("diagnostics treat a missing identity as a warning by default", async (t) => {
+ const root = await tempRoot(t, "pi-desktop-signing-optional-");
+ const bin = join(root, "bin");
+ await writeDiagnosticsShims(bin, { identities: NO_IDENTITIES });
+
+ const result = runDiagnostics(bin);
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.ok(
+ result.stdout.includes(
+ `warning: Developer ID Application: ${SIGNING_IDENTITY_NAME} is not available`,
+ ),
+ result.stdout,
+ );
+ assert.doesNotMatch(result.stdout, /Developer ID identity available/);
+});
+
+test("diagnostics refuse to run off macOS", async (t) => {
+ const root = await tempRoot(t, "pi-desktop-signing-linux-");
+ const bin = join(root, "bin");
+ await writeDiagnosticsShims(bin, { unameSystem: "Linux" });
+
+ const result = runDiagnostics(bin);
+
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /must run on macOS/);
+});
+
+test("diagnostics never echo signing secrets", async (t) => {
+ const root = await tempRoot(t, "pi-desktop-signing-redaction-");
+ const bin = join(root, "bin");
+ await writeDiagnosticsShims(bin, { leaky: true });
+
+ const result = runDiagnostics(bin, {
+ env: {
+ CSC_LINK: CSC_LINK_SENTINEL,
+ CSC_KEY_PASSWORD: CSC_PASSWORD_SENTINEL,
+ APPLE_ID: APPLE_ID_SENTINEL,
+ APPLE_APP_SPECIFIC_PASSWORD: APPLE_PASSWORD_SENTINEL,
+ APPLE_TEAM_ID: "DUV63RKYTW",
+ },
+ });
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ const combined = `${result.stdout}${result.stderr}`;
+ // The shims did print the values, so the assertions below are not vacuous.
+ assert.ok(combined.includes("CSC_LINK=[redacted]"), combined);
+ for (const secret of [
+ CSC_LINK_SENTINEL,
+ CSC_PASSWORD_SENTINEL,
+ APPLE_PASSWORD_SENTINEL,
+ APPLE_ID_SENTINEL,
+ ]) {
+ assert.ok(!combined.includes(secret), `secret value leaked: ${secret}`);
+ }
+});
+
+test("inventory counts the signing payload of a release directory", async (t) => {
+ const root = await tempRoot(t, "pi-desktop-bundle-inventory-");
+ const release = join(root, "release");
+ const app = await writeBundleFixture(release);
+
+ const result = runInventory([release, "--json", "--top", "2"]);
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.ok(
+ result.stdout.includes(`==> PI-Desktop.app inventory: ${app}`),
+ result.stdout,
+ );
+ assert.match(result.stdout, /^entries: 21 \(files: 9, directories: 11, symlinks: 1\)$/m);
+ assert.match(
+ result.stdout,
+ /^mach-o: 3 \(dylib: 1, node: 1, framework binaries: 1\)$/m,
+ );
+ assert.match(result.stdout, /^bundles: frameworks=1 nested-apps=1$/m);
+ assert.match(result.stdout, /^executables: script=1 mach-o=3$/m);
+ assert.match(result.stdout, /^binary-resources: 1$/m);
+ assert.match(
+ result.stdout,
+ /^signing-candidates: 5 \(mach-o 3 \+ nested-bundles 1 \+ binary-resources 1\)$/m,
+ );
+ assert.match(
+ result.stdout,
+ /^resources: agent-runtime=<missing>, plugins=<missing>, skills=<missing>, models\.dev=<missing>, bin=2\/\d+$/m,
+ );
+ assert.match(result.stdout, /^top-level-cost: Contents\/MacOS=\d+, Contents\/Resources=\d+$/m);
+ assert.match(
+ result.stdout,
+ /^slowest-likely: Contents\/MacOS\/PI-Desktop \(4100 bytes\), Contents\/Resources\/bin\/pi-desktop-host-core \(2052 bytes\)$/m,
+ );
+ assert.match(result.stdout, /^warning: non-Mach-O regular file in Contents\/Resources\/bin: Contents\/Resources\/bin\/run\.sh$/m);
+
+ const json = parseInventoryJson(result.stdout);
+ assert.equal(json.bundle, app);
+ assert.equal(json.entries, 21);
+ assert.equal(json.files, 9);
+ assert.equal(json.directories, 11);
+ assert.equal(json.symlinks, 1);
+ assert.equal(json.machO, 3);
+ assert.equal(json.dylib, 1);
+ assert.equal(json.nodeModules, 1);
+ assert.equal(json.frameworks, 1);
+ assert.equal(json.nestedApps, 1);
+ assert.equal(json.executableScripts, 1);
+ assert.equal(json.executableMachO, 3);
+ assert.equal(json.machOOutsideFramework, 2);
+ assert.equal(json.binaryResources, 1);
+ assert.equal(json.signingCandidates, 5);
+ assert.equal(json.topLevelCost.length, 2);
+ assert.equal(json.slowestLikely.length, 2);
+ assert.equal(json.slowestLikely[0].path, "Contents/MacOS/PI-Desktop");
+ assert.equal(json.slowestLikely[0].bytes, 4100);
+ assert.equal(json.resources.bin.files, 2);
+ assert.equal(json.resources["models.dev"], null);
+});
+
+test("inventory counts binary-looking resources as signing candidates", async (t) => {
+ const root = await tempRoot(t, "pi-desktop-bundle-binary-resources-");
+ const release = join(root, "release");
+ const app = appFixturePath(release);
+ // One Mach-O, one NUL-carrying resource, one text resource and one nested
+ // bundle: osx-sign signs all of those except the text resource, so the total
+ // is 1 + 1 + 1 = 3.
+ await writeMachO(join(app, "Contents", "MacOS", "PI-Desktop"), 512);
+ await writeBinaryResource(
+ join(app, "Contents", "Frameworks", "Electron Framework.framework", "Resources", "icudtl.dat"),
+ 256,
+ );
+ await writeFileWithParents(
+ join(app, "Contents", "Resources", "notes.txt"),
+ "plain text, no NUL\n",
+ );
+ await writeFileWithParents(
+ join(app, "Contents", "Frameworks", "Helper.app", "Contents", "MacOS", "Helper"),
+ "helper-stand-in",
+ );
+
+ const result = runInventory([app, "--json"]);
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.match(result.stdout, /^mach-o: 1 \(dylib: 0, node: 0, framework binaries: 0\)$/m);
+ assert.match(result.stdout, /^binary-resources: 1$/m);
+ assert.match(result.stdout, /^bundles: frameworks=1 nested-apps=1$/m);
+ assert.match(
+ result.stdout,
+ /^signing-candidates: 3 \(mach-o 1 \+ nested-bundles 1 \+ binary-resources 1\)$/m,
+ );
+
+ const json = parseInventoryJson(result.stdout);
+ assert.equal(json.machO, 1);
+ assert.equal(json.binaryResources, 1);
+ assert.equal(json.nestedApps, 1);
+ assert.equal(json.signingCandidates, 3);
+ // The text file is counted as an entry but is not a signing candidate.
+ assert.equal(json.files, 4);
+ assert.deepEqual(json.warnings, []);
+});
+
+test("inventory does not double count native-extension files as binary resources", async (t) => {
+ const root = await tempRoot(t, "pi-desktop-bundle-native-extensions-");
+ const release = join(root, "release");
+ const app = appFixturePath(release);
+ // A `.dylib` and a `.node` that happen to look binary are already reported by
+ // their own counters, so only the `.dat` may raise `binary-resources`.
+ await writeMachO(
+ join(app, "Contents", "Resources", "bin", "pi-desktop-host-core"),
+ 256,
+ );
+ await writeBinaryResource(
+ join(app, "Contents", "Resources", "libstub.dylib"),
+ 128,
+ );
+ await writeBinaryResource(
+ join(app, "Contents", "Resources", "native.node"),
+ 128,
+ );
+ await writeBinaryResource(
+ join(app, "Contents", "Resources", "icudtl.dat"),
+ 128,
+ );
+
+ const result = runInventory([app, "--json"]);
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.match(result.stdout, /^binary-resources: 1$/m);
+ assert.match(
+ result.stdout,
+ /^signing-candidates: 2 \(mach-o 1 \+ nested-bundles 0 \+ binary-resources 1\)$/m,
+ );
+
+ const json = parseInventoryJson(result.stdout);
+ assert.equal(json.machO, 1);
+ assert.equal(json.binaryResources, 1);
+ assert.equal(json.dylib, 1);
+ assert.equal(json.nodeModules, 1);
+ assert.equal(json.signingCandidates, 2);
+});
+
+test("inventory requires exactly one app bundle under the given path", async (t) => {
+ const root = await tempRoot(t, "pi-desktop-bundle-selection-");
+
+ const empty = join(root, "empty-release");
+ await mkdir(join(empty, "mac-arm64"), { recursive: true });
+ const emptyResult = runInventory([empty]);
+ assert.equal(emptyResult.status, 1);
+ assert.match(emptyResult.stderr, /expected exactly one \*\.app bundle under/);
+
+ const twoApps = join(root, "two-release");
+ await writeFileWithParents(
+ join(twoApps, "mac-arm64", "PI-Desktop.app", "Contents", "Info.plist"),
+ "<plist/>",
+ );
+ await writeFileWithParents(
+ join(twoApps, "mac-x64", "PI-Desktop.app", "Contents", "Info.plist"),
+ "<plist/>",
+ );
+ const twoResult = runInventory([twoApps]);
+ assert.equal(twoResult.status, 1);
+ assert.match(twoResult.stderr, /expected exactly one/);
+
+ const missingResult = runInventory([join(root, "does-not-exist")]);
+ assert.equal(missingResult.status, 1);
+ assert.match(missingResult.stderr, /path does not exist/);
+
+ const fileResult = runInventory([join(root, "two-release", "mac-arm64", "PI-Desktop.app", "Contents", "Info.plist")]);
+ assert.equal(fileResult.status, 1);
+ assert.match(fileResult.stderr, /not a directory/);
+});
+
+test("inventory survives a symlink cycle without hanging or double counting", async (t) => {
+ const root = await tempRoot(t, "pi-desktop-bundle-symlink-");
+ const release = join(root, "release");
+ const app = appFixturePath(release);
+ await writeFileWithParents(join(app, "Contents", "MacOS", "PI-Desktop"), "not-mach-o");
+ await mkdir(join(app, "Contents", "Resources"), { recursive: true });
+ await symlink(
+ join("..", ".."),
+ join(app, "Contents", "Resources", "ancestor-loop"),
+ );
+ await symlink("self-loop", join(app, "Contents", "Resources", "self-loop"));
+
+ const startedAt = Date.now();
+ const result = runInventory([app, "--json"]);
+ const elapsed = Date.now() - startedAt;
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.equal(result.signal, null, "the inventory must terminate on its own");
+ assert.ok(elapsed < 5000, `inventory took ${elapsed}ms`);
+ // Contents, Contents/MacOS and Contents/Resources are real directories; the
+ // ancestor symlink must not make the walker revisit them.
+ assert.match(result.stdout, /^entries: 6 \(files: 1, directories: 3, symlinks: 2\)$/m);
+ const json = parseInventoryJson(result.stdout);
+ assert.equal(json.symlinks, 2);
+ assert.equal(json.files, 1);
+ assert.equal(json.entries, 6);
+});
+
+test("inventory warns about oversized bundles without failing", async (t) => {
+ const root = await tempRoot(t, "pi-desktop-bundle-thresholds-");
+ const release = join(root, "release");
+ const app = appFixturePath(release);
+ for (let index = 0; index < 5; index += 1) {
+ await writeFileWithParents(
+ join(app, "Contents", "MacOS", `tool-${index}`),
+ "plain file",
+ );
+ }
+
+ const result = runInventory([app, "--json"], {
+ PI_DESKTOP_INVENTORY_MAX_FILES: "3",
+ PI_DESKTOP_INVENTORY_MAX_DIR_FILES: "1",
+ });
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.match(result.stdout, /^warning: bundle contains 5 files \(threshold 3\)/m);
+ assert.match(result.stdout, /^warning: directory holds more than 1 files/m);
+
+ const json = parseInventoryJson(result.stdout);
+ assert.equal(json.files, 5);
+ assert.ok(json.warnings.length >= 2);
+});
+
+test("inventory flags Mach-O files outside the expected locations", async (t) => {
+ const root = await tempRoot(t, "pi-desktop-bundle-misplaced-");
+ const release = join(root, "release");
+ const app = appFixturePath(release);
+ await writeMachO(join(app, "Contents", "Resources", "tools", "odd-binary"), 128);
+
+ const result = runInventory([app]);
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.match(result.stdout, /^mach-o: 1 \(dylib: 0, node: 0, framework binaries: 0\)$/m);
+ assert.match(
+ result.stdout,
+ /^warning: Mach-O outside Contents\/MacOS, Contents\/Frameworks, Contents\/Resources\/bin or a nested \.app: Contents\/Resources\/tools\/odd-binary$/m,
+ );
+ assert.match(
+ result.stdout,
+ /^signing-candidates: 1 \(mach-o 1 \+ nested-bundles 0 \+ binary-resources 0\)$/m,
+ );
+});
diff --git a/apps/desktop/test/macos-signing-watchdog.test.mjs b/apps/desktop/test/macos-signing-watchdog.test.mjs
new file mode 100644
index 000000000..443704afe
--- /dev/null
+++ b/apps/desktop/test/macos-signing-watchdog.test.mjs
@@ -0,0 +1,412 @@
+import assert from "node:assert/strict";
+import {
+ chmod,
+ mkdir,
+ mkdtemp,
+ readFile,
+ rm,
+ writeFile,
+} from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { spawn } from "node:child_process";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+
+const repoRoot = fileURLToPath(new URL("../../..", import.meta.url));
+const watchdogPath = join(repoRoot, "scripts", "macos-signing-watchdog.mjs");
+
+/** 20s guard so a regression can never hang the suite. */
+const WATCHDOG_GUARD_MS = 20_000;
+
+/**
+ * Run the watchdog and capture everything it printed. The environment is
+ * neutralized first: a caller's PI_SIGNING_* / GITHUB_STEP_SUMMARY must not
+ * change what the tests observe.
+ */
+function runWatchdog(args, { env = {}, cwd = repoRoot } = {}) {
+ const startedAt = Date.now();
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [watchdogPath, ...args], {
+ cwd,
+ env: {
+ ...process.env,
+ PI_SIGNING_TIMEOUT_SECONDS: "",
+ PI_SIGNING_STALL_SECONDS: "",
+ PI_SIGNING_HEARTBEAT_SECONDS: "",
+ PI_CODESIGN_LOG: "",
+ PI_CODESIGN_REAL: "",
+ GITHUB_STEP_SUMMARY: "",
+ ...env,
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (chunk) => {
+ stdout += chunk;
+ });
+ child.stderr.on("data", (chunk) => {
+ stderr += chunk;
+ });
+ const guard = setTimeout(() => child.kill("SIGKILL"), WATCHDOG_GUARD_MS);
+ child.on("error", (error) => {
+ clearTimeout(guard);
+ reject(error);
+ });
+ child.on("close", (status, signal) => {
+ clearTimeout(guard);
+ resolve({
+ status,
+ signal,
+ stdout,
+ stderr,
+ elapsedMs: Date.now() - startedAt,
+ });
+ });
+ });
+}
+
+async function makeTempDir(t) {
+ const root = await mkdtemp(join(tmpdir(), "pi-desktop-signing-watchdog-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ return root;
+}
+
+function summaryLines(stdout) {
+ return stdout.split("\n").filter((line) => line.startsWith("[sign] summary"));
+}
+
+/** The main summary line (the one carrying the counters). */
+function summaryLine(stdout) {
+ const line = summaryLines(stdout).find((entry) =>
+ entry.includes("codesign-calls="),
+ );
+ assert.ok(line, `no [sign] summary line in:\n${stdout}`);
+ return line;
+}
+
+function summaryNumber(stdout, name) {
+ const match = summaryLine(stdout).match(new RegExp(`${name}=([0-9.]+)`));
+ assert.ok(match, `no ${name}= in summary: ${summaryLine(stdout)}`);
+ return Number(match[1]);
+}
+
+test("forwards child output with a [sign] prefix and reports a clean exit", async () => {
+ const { status, stdout } = await runWatchdog([
+ "--label",
+ "clean",
+ "--",
+ "bash",
+ "-c",
+ 'echo "Walking... /tmp/PI-Desktop.app/Contents"; echo "notice: nothing to see"; echo "Signing... /tmp/PI-Desktop.app/Contents/MacOS/PI-Desktop"',
+ ]);
+
+ assert.equal(status, 0);
+ assert.match(stdout, /^\[sign\] /m);
+ assert.ok(stdout.includes("[sign] notice: nothing to see"));
+ assert.match(summaryLine(stdout), /label=clean /);
+ assert.match(summaryLine(stdout), /exit=0 /);
+});
+
+test("passes a non-zero child exit code through to the caller", async () => {
+ const { status, stdout } = await runWatchdog([
+ "--label",
+ "failing",
+ "--",
+ "bash",
+ "-c",
+ "exit 7",
+ ]);
+
+ assert.equal(status, 7);
+ assert.match(summaryLine(stdout), /exit=7 /);
+});
+
+test("a silent signing stage produces a stall dump without failing the run", async () => {
+ const { status, stdout, elapsedMs } = await runWatchdog([
+ "--label",
+ "stall",
+ "--stall-seconds",
+ "2",
+ "--heartbeat-seconds",
+ "1",
+ "--timeout-seconds",
+ "30",
+ "--",
+ "bash",
+ "-c",
+ 'echo "Signing... /tmp/x/Electron Framework"; sleep 6',
+ ]);
+
+ assert.equal(status, 0, "a stall must not fail the run");
+ assert.match(stdout, /\[sign\] STALL: no output for \d+s/);
+ assert.match(stdout, /last file: \/tmp\/x\/Electron Framework/);
+ assert.match(stdout, /\[sign\] STALL: recent output:/);
+ assert.ok(elapsedMs < 20_000, `watchdog took ${elapsedMs}ms`);
+});
+
+test("a hard timeout kills the process group, dumps diagnostics and exits 124", async () => {
+ const { status, stdout, elapsedMs } = await runWatchdog([
+ "--label",
+ "timeout",
+ "--timeout-seconds",
+ "2",
+ "--stall-seconds",
+ "60",
+ "--heartbeat-seconds",
+ "60",
+ "--",
+ "bash",
+ "-c",
+ 'echo "Signing... /tmp/x/Foo"; sleep 30',
+ ]);
+
+ assert.equal(status, 124);
+ assert.match(stdout, /\[sign\] TIMEOUT after 2s/);
+ assert.match(stdout, /last file: \/tmp\/x\/Foo/);
+ assert.match(stdout, /\[sign\] STALL: recent output:/);
+ assert.match(stdout, /\[sign\] STALL: processes:/);
+ assert.match(stdout, /\[sign\] STALL: codesign log tail:/);
+ assert.match(summaryLine(stdout), /exit=124 /);
+ assert.ok(elapsedMs < 10_000, `timeout took ${elapsedMs}ms`);
+});
+
+test("redacts a short certificate password even below the length guard", async () => {
+ // The certificate password is the one value builder-util itself may print
+ // unredacted, so it must be redacted at any length.
+ const shortPassword = "pw12";
+ const { status, stdout } = await runWatchdog(
+ [
+ "--label",
+ "short-secret",
+ "--",
+ "bash",
+ "-c",
+ 'echo "set-key-partition-list -s -k $CSC_KEY_PASSWORD /tmp/x.keychain"',
+ ],
+ { env: { CSC_KEY_PASSWORD: shortPassword } },
+ );
+
+ assert.equal(status, 0);
+ assert.ok(
+ !stdout.includes(shortPassword),
+ `a short certificate password leaked: ${stdout}`,
+ );
+ assert.match(stdout, /\[redacted\]/);
+});
+
+test("redacts secrets printed by the child and by codesign-style arguments", async () => {
+ const cscKeyPassword = "sentinel-csc-key-password-abcdef";
+ const appSpecificPassword = "sentinel-apple-app-password-abcdef";
+ const cscLink = "sentinel-csc-link-abcdef";
+ const appleId = "[email protected]";
+ const argumentPassword = "sentinel-argument-password";
+
+ const { status, stdout, stderr } = await runWatchdog(
+ [
+ "--label",
+ "redaction",
+ "--",
+ "bash",
+ "-c",
+ 'echo "CSC_KEY_PASSWORD=$CSC_KEY_PASSWORD"; echo "APPLE_APP_SPECIFIC_PASSWORD=$APPLE_APP_SPECIFIC_PASSWORD"; echo "CSC_LINK=$CSC_LINK"; echo "APPLE_ID=$APPLE_ID"; echo "codesign --password sentinel-argument-password --keychain-password sentinel-keychain-password /tmp/whatever"; echo "executing file=/usr/bin/security args=set-key-partition-list -S apple-tool:,apple: -s -k sentinel-keychain-flag-password /tmp/x.keychain"; echo "stderr $CSC_KEY_PASSWORD" >&2',
+ ],
+ {
+ env: {
+ CSC_KEY_PASSWORD: cscKeyPassword,
+ APPLE_APP_SPECIFIC_PASSWORD: appSpecificPassword,
+ CSC_LINK: cscLink,
+ APPLE_ID: appleId,
+ },
+ },
+ );
+
+ assert.equal(status, 0);
+ const combined = `${stdout}${stderr}`;
+ for (const secret of [
+ cscKeyPassword,
+ appSpecificPassword,
+ cscLink,
+ appleId,
+ argumentPassword,
+ "sentinel-keychain-password",
+ // `security set-key-partition-list -k <p12 password>` is how
+ // electron-builder unlocks the imported certificate, and `-k` is absent
+ // from builder-util's own sensitive-stem list.
+ "sentinel-keychain-flag-password",
+ ]) {
+ assert.ok(
+ !combined.includes(secret),
+ `secret leaked into the watchdog output: ${secret}`,
+ );
+ }
+ assert.ok(combined.includes("[redacted]"));
+ assert.match(combined, /--password \[redacted\]/);
+ assert.match(combined, /-k \[redacted\]/);
+ assert.match(stderr, /^\[sign\] stderr \[redacted\]$/m);
+});
+
+test(
+ "the injected codesign shim times calls and the summary classifies them",
+ { skip: process.platform !== "darwin" ? "the codesign shim is macOS-only" : false },
+ async (t) => {
+ const root = await makeTempDir(t);
+ const fakeBin = join(root, "fakebin");
+ await mkdir(fakeBin, { recursive: true });
+ await writeFile(
+ join(fakeBin, "codesign"),
+ '#!/bin/bash\nsleep 0.3\nexit 0\n',
+ );
+ await chmod(join(fakeBin, "codesign"), 0o755);
+ const codesignLog = join(root, "codesign-timing.log");
+
+ const { status, stdout } = await runWatchdog(
+ [
+ "--label",
+ "shim",
+ "--codesign-log",
+ codesignLog,
+ "--",
+ "bash",
+ "-c",
+ "codesign --display --verify /tmp/whatever",
+ ],
+ { env: { PATH: `${fakeBin}:${process.env.PATH}` } },
+ );
+
+ assert.equal(status, 0, stdout);
+ const records = (await readFile(codesignLog, "utf8"))
+ .split("\n")
+ .filter((line) => line !== "")
+ .map((line) => line.split("\t"));
+ assert.equal(records.length, 2, `expected one start/end pair: ${records}`);
+ const [start, end] = records;
+ assert.equal(start[0], "start");
+ assert.equal(end[0], "end");
+ assert.equal(start[2], end[2], "start and end must share the shim pid");
+ assert.equal(start[3], "--display --verify /tmp/whatever");
+ assert.equal(end[3], "0");
+ assert.ok(Number(end[1]) >= Number(start[1]));
+
+ assert.equal(summaryNumber(stdout, "codesign-calls"), 1);
+ const categories = summaryLines(stdout).find((line) =>
+ line.includes("codesign-categories"),
+ );
+ assert.ok(categories, `no categories line in:\n${stdout}`);
+ assert.match(categories, /verify=1\/[0-9]+\.[0-9]s/);
+ assert.ok(summaryNumber(stdout, "p50") > 0, summaryLine(stdout));
+ assert.ok(summaryNumber(stdout, "max") > 0, summaryLine(stdout));
+ assert.match(stdout, /\[sign\] summary slowest: \/tmp\/whatever /);
+ },
+);
+
+test(
+ "a failing codesign call is reported as a failure, not as a silent retry",
+ { skip: process.platform !== "darwin" ? "the codesign shim is macOS-only" : false },
+ async (t) => {
+ const root = await makeTempDir(t);
+ const fakeBin = join(root, "fakebin");
+ await mkdir(fakeBin, { recursive: true });
+ await writeFile(join(fakeBin, "codesign"), "#!/bin/bash\nexit 70\n");
+ await chmod(join(fakeBin, "codesign"), 0o755);
+
+ const { status, stdout } = await runWatchdog(
+ [
+ "--label",
+ "failing-codesign",
+ "--codesign-log",
+ join(root, "codesign-timing.log"),
+ "--",
+ "bash",
+ "-c",
+ "codesign --force --sign identity /tmp/failing-target || true",
+ ],
+ { env: { PATH: `${fakeBin}:${process.env.PATH}` } },
+ );
+
+ assert.equal(status, 0, stdout);
+ // electron-builder retries a failing pass up to three times without saying
+ // so; the failure count is the only signal that it happened.
+ assert.match(
+ stdout,
+ /\[sign\] summary failures: 1 codesign calls exited non-zero/,
+ );
+ },
+);
+
+test("--no-codesign-shim runs the command untouched and reports zero calls", async (t) => {
+ const root = await makeTempDir(t);
+ const codesignLog = join(root, "unused-codesign-timing.log");
+
+ const { status, stdout } = await runWatchdog([
+ "--label",
+ "no-shim",
+ "--no-codesign-shim",
+ "--codesign-log",
+ codesignLog,
+ "--",
+ "bash",
+ "-c",
+ 'echo "PI_CODESIGN_LOG=${PI_CODESIGN_LOG:-unset}"; echo "PI_CODESIGN_REAL=${PI_CODESIGN_REAL:-unset}"',
+ ]);
+
+ assert.equal(status, 0);
+ assert.match(stdout, /codesign-shim=off/);
+ assert.ok(stdout.includes("PI_CODESIGN_LOG=unset"));
+ assert.ok(stdout.includes("PI_CODESIGN_REAL=unset"));
+ assert.equal(summaryNumber(stdout, "codesign-calls"), 0);
+ await assert.rejects(readFile(codesignLog, "utf8"));
+});
+
+test("a missing -- separator is a usage error", async () => {
+ const withoutSeparator = await runWatchdog(["echo", "hi"]);
+ assert.equal(withoutSeparator.status, 2);
+ assert.match(withoutSeparator.stderr, /Usage: node scripts\/macos-signing-watchdog\.mjs/);
+ assert.ok(withoutSeparator.stderr.includes("-- <command>"));
+
+ const withoutCommand = await runWatchdog([]);
+ assert.equal(withoutCommand.status, 2);
+ assert.match(withoutCommand.stderr, /Usage: node scripts\/macos-signing-watchdog\.mjs/);
+});
+
+test("appends a markdown summary to GITHUB_STEP_SUMMARY", async (t) => {
+ const root = await makeTempDir(t);
+ const stepSummary = join(root, "step-summary.md");
+
+ const { status } = await runWatchdog(
+ ["--label", "gh-summary", "--", "bash", "-c", "echo building"],
+ { env: { GITHUB_STEP_SUMMARY: stepSummary } },
+ );
+
+ assert.equal(status, 0);
+ const markdown = await readFile(stepSummary, "utf8");
+ assert.ok(markdown.includes("gh-summary"), markdown);
+ assert.match(markdown, /\| elapsed \| [0-9]+\.[0-9]s \|/);
+});
+
+test("recognizes signing phases from the builder output in order", async () => {
+ const script = [
+ 'console.log("Walking... /tmp/PI-Desktop.app/Contents");',
+ 'console.log("Signing... /tmp/PI-Desktop.app/Contents/MacOS/PI-Desktop");',
+ 'console.log("notarizing using notarytool");',
+ ].join("\n");
+
+ const { status, stdout } = await runWatchdog([
+ "--label",
+ "phases",
+ "--",
+ process.execPath,
+ "-e",
+ script,
+ ]);
+
+ assert.equal(status, 0, stdout);
+ const phases = stdout
+ .split("\n")
+ .filter((line) => line.startsWith("[sign] phase:"))
+ .map((line) => line.slice("[sign] phase: ".length));
+ assert.deepEqual(phases, ["walking", "signing:PI-Desktop", "notarizing"]);
+});
diff --git a/docs/spec/06-delivery/06-release-runbook.md b/docs/spec/06-delivery/06-release-runbook.md
index 59edd7f95..a2585e095 100644
--- a/docs/spec/06-delivery/06-release-runbook.md
+++ b/docs/spec/06-delivery/06-release-runbook.md
@@ -237,7 +237,6 @@ then checks the identity, code-signing integrity (including
tickets before any artifact upload. The per-architecture `latest-mac.yml` files
are renamed before upload; the publish job merges them into one feed after
downloading both artifacts.
-the publish job merges them into one feed after downloading both artifacts.
The shared electron-builder configuration applies the architecture-labelled
pattern at the macOS platform level for ZIPs and overrides it at the DMG target
@@ -330,6 +329,77 @@ base64 -i developer-id-application.p12 | pbcopy
On Linux use `base64 -w0 developer-id-application.p12`. Files that must never
enter git: `*.p12`, `*.cer`, `*.p8`, `*.mobileprovision`.
+### 4.6 macOS signing observability and timeouts
+
+`electron-builder` prints one line before signing — `signing
+file=release/mac-arm64/PI-Desktop.app platform=darwin type=distribution
+identityName=...` — and then nothing until the phase is over. Three mechanisms
+hide in that gap, and the macOS lanes now expose all three:
+
+| Point in the phase | What happens | How it is visible |
+|---|---|---|
+| Walk | `@electron/osx-sign` walks `PI-Desktop.app/Contents` and collects every Mach-O file plus nested `.app` and `.framework` bundles | `DEBUG=electron-osx-sign*` prints `Walking... <dir>`; `scripts/macos-bundle-inventory.mjs` prints the same bundle's counts right after packaging |
+| Per-file signing | `codesign --force --sign <identity> --timestamp --entitlements ... <file>` runs serially, deepest file first, the app bundle last | `DEBUG=electron-osx-sign*` prints `Signing... <file>` and `Executing... <file> codesign ...`; the codesign shim times every invocation. If a keychain ever refuses to hand the key to a wrapped `codesign`, `PI_SIGNING_NO_CODESIGN_SHIM=1` runs the phase without the shim |
+| Silent retry | A failing pass is retried up to three more times with a 5s/10s/15s backoff and no log line | The watchdog's `codesign-calls` and `failures` lines expose repeated passes |
+| App notarization | `@electron/notarize` zips the app, uploads it, and waits for Apple's queue (`mac.notarize=true`) | `DEBUG=electron-notarize*` prints `zipping application to`, `attempting to upload file to Apple`, `notarization success`, then electron-builder prints `notarization successful` |
+| DMG notarization | The DMG carries its own signature, so the next step submits it again with `xcrun notarytool submit --wait` | The same watchdog keeps that wait observable and bounded |
+
+`scripts/macos-signing-watchdog.mjs` wraps both long phases. It forwards every
+child line with a `[sign] ` prefix and keeps the child's exit code, so the
+failure semantics of the lane do not change. stdout and stderr are forwarded as
+two independent streams, so their relative order can differ from a direct run,
+and the child receives no stdin. It prints a heartbeat while the
+child is silent (elapsed time, phase, last file, active codesign target), dumps
+diagnostics when the phase produces no output and no codesign activity for
+`PI_SIGNING_STALL_SECONDS` (the last file, the `ps` state of the signing
+processes, the codesign log tail), and reports per-file codesign timings — call
+count, total, p50, p95, maximum, and the slowest files — in a `[sign] summary`
+block. The knobs:
+
+| Setting | Default | Effect |
+|---|---|---|
+| `PI_SIGNING_TIMEOUT_SECONDS` | 2400 (CI: 1800 packaging, 1200 DMG) | Hard limit for the wrapped phase: diagnostics are dumped, the process group is killed, and the step exits 124 instead of hanging |
+| `PI_SIGNING_STALL_SECONDS` | 300 | Silence with no codesign activity for this long triggers one diagnostics dump; the phase keeps running, because Apple's notarization queue is a legitimate wait |
+| `PI_SIGNING_HEARTBEAT_SECONDS` | 60 | Heartbeat interval while the child produces no output |
+| `DEBUG` | `electron-osx-sign*,electron-notarize*` | Namespaces that expose walking, per-file signing, and notarization progress |
+
+`DEBUG` lists only the two namespaces that sanitize their own command lines,
+because `electron-builder`'s namespace is not safe here: builder-util prints
+every spawned command through a stem list that does not cover
+`security set-key-partition-list -k <p12 password>`. On top of that the watchdog
+redacts the values of `CSC_KEY_PASSWORD` and `APPLE_APP_SPECIFIC_PASSWORD` at any
+length, the values of `CSC_LINK` and `APPLE_ID`, and any `--password` or `-k`
+argument, from everything it emits — including the diagnostics, whose process
+view prints `comm` only and never `argv`, and the summary, which carries counts
+and redacted target paths. GitHub additionally masks every value that comes from
+a secret.
+
+Measured on the maintainer machine, one macOS arm64 bundle needs 93 `codesign`
+invocations (91 signing, 1 verification, 1 entitlement display) and about 49s of
+`codesign` wall time; only 16 of those files are Mach-O code and 5 are nested
+bundles. `@electron/osx-sign` also signs binary resources — 33 `.pak` files plus
+`.nib`, `.dat`, `.bin`, `.png`, `.icns`, and `app.asar` — because its walk
+selects every file that looks binary, not only Mach-O. Excluding exactly those
+data files with `mac.signIgnore` would remove roughly three quarters of the
+calls, but it changes what the release artifacts carry and needs a notarized
+release to validate, so it is deliberately not enabled.
+
+`scripts/macos-signing-diagnostics.sh` records the runner baseline before the
+certificate is imported: system version, `codesign --version`, keychain
+identities/list/default, `xcrun --find notarytool`, and the reachability and
+latency of `http://timestamp.apple.com/ts01`. The Developer ID identity is
+expected to be absent at that point, because electron-builder imports it from
+`CSC_LINK` while packaging; only `--require-identity` makes a missing identity
+fatal.
+
+Signer status: `@electron/[email protected]` is pinned exactly by
+`[email protected]` and no override applies to it. Its
+`signApplication()` awaits one `codesign` per file; it has no batch or parallel
+path and no option or environment variable that enables one. A faster signer
+therefore needs the `mac.sign` replacement hook, which is a rewrite rather than
+a configuration switch, so the lane keeps the pinned signer and the diagnostics
+above.
+
## 5. Verification gates
Unsigned debug artifacts (`workflow_dispatch` with `sign_macos: false`) are
diff --git a/docs/zh-CN/spec/06-delivery/06-release-runbook.md b/docs/zh-CN/spec/06-delivery/06-release-runbook.md
index 55f1cdc63..55f982545 100644
--- a/docs/zh-CN/spec/06-delivery/06-release-runbook.md
+++ b/docs/zh-CN/spec/06-delivery/06-release-runbook.md
@@ -273,6 +273,62 @@ base64 -i developer-id-application.p12 | pbcopy
Linux 使用 `base64 -w0 developer-id-application.p12`。绝不能进入 git 的文件:
`*.p12`、`*.cer`、`*.p8`、`*.mobileprovision`。
+### 4.6 macOS 签名可观测性与超时
+
+`electron-builder` 在开始签名前只打印一行 —— `signing
+file=release/mac-arm64/PI-Desktop.app platform=darwin type=distribution
+identityName=...` —— 之后直到该阶段结束都没有任何输出。这段时间里隐藏了三种机制,
+现在 macOS 通道把它们全部暴露出来:
+
+| 阶段位置 | 发生什么 | 现在如何可见 |
+|---|---|---|
+| 遍历 | `@electron/osx-sign` 遍历 `PI-Desktop.app/Contents`,收集所有 Mach-O 文件以及嵌套的 `.app` 与 `.framework` 包 | `DEBUG=electron-osx-sign*` 打印 `Walking... <dir>`;`scripts/macos-bundle-inventory.mjs` 在打包结束后打印同一个包的数量 |
+| 逐文件签名 | `codesign --force --sign <identity> --timestamp --entitlements ... <file>` 串行执行,最深的文件优先,应用包最后签 | `DEBUG=electron-osx-sign*` 打印 `Signing... <file>` 与 `Executing... <file> codesign ...`;codesign shim 记录每次调用的耗时。若钥匙串拒绝把私钥交给被包裹的 `codesign`,可设置 `PI_SIGNING_NO_CODESIGN_SHIM=1` 在不使用 shim 的情况下运行该阶段 |
+| 静默重试 | 一轮签名失败后最多再重试三次,退避 5s/10s/15s,且没有任何日志行 | 看门狗汇总中的 `codesign-calls` 与 `failures` 行会暴露重复的整轮签名 |
+| 应用公证 | `@electron/notarize` 打包 zip、上传并等待 Apple 队列(`mac.notarize=true`) | `DEBUG=electron-notarize*` 打印 `zipping application to`、`attempting to upload file to Apple`、`notarization success`,随后 electron-builder 打印 `notarization successful` |
+| DMG 公证 | DMG 有自己的签名,因此下一步会用 `xcrun notarytool submit --wait` 再提交一次 | 同一个看门狗让该等待过程可见并且有上限 |
+
+`scripts/macos-signing-watchdog.mjs` 包裹这两个长时间阶段。它给子进程的每一行加上
+`[sign] ` 前缀后转发,并保留子进程退出码,因此通道的失败语义不变;stdout 与 stderr 作为
+两条独立流转发,二者相对顺序可能与直接运行不同,子进程也不会获得 stdin。子进程静默时它打印心跳
+(已用时间、阶段、最后处理的文件、当前活动的 codesign 目标);当阶段在
+`PI_SIGNING_STALL_SECONDS` 内既无输出也无 codesign 活动时,它输出一次诊断(最后处理的
+文件、签名相关进程的 `ps` 状态、codesign 日志尾部);并在 `[sign] summary` 块中给出逐文件
+codesign 耗时 —— 调用次数、总耗时、p50、p95、最大值以及最慢的几个文件。可调项:
+
+| 设置 | 默认值 | 作用 |
+|---|---|---|
+| `PI_SIGNING_TIMEOUT_SECONDS` | 2400(CI:打包 1800,DMG 1200) | 被包裹阶段的硬上限:输出诊断、杀掉进程组,并以 124 退出而不是继续挂起 |
+| `PI_SIGNING_STALL_SECONDS` | 300 | 无 codesign 活动的静默持续这么长时间就触发一次诊断输出;阶段继续运行,因为等待 Apple 公证队列是合法等待 |
+| `PI_SIGNING_HEARTBEAT_SECONDS` | 60 | 子进程无输出时的心跳间隔 |
+| `DEBUG` | `electron-osx-sign*,electron-notarize*` | 暴露遍历、逐文件签名与公证进度的命名空间 |
+
+`DEBUG` 只列出两个会自行清洗命令行的命名空间,因为 `electron-builder` 的命名空间在这里
+并不安全:builder-util 打印每条外部命令时所用的敏感词表并不覆盖
+`security set-key-partition-list -k <p12 密码>`。在此之上,看门狗会把
+`CSC_KEY_PASSWORD`、`APPLE_APP_SPECIFIC_PASSWORD` 的取值(不限长度)、`CSC_LINK` 与
+`APPLE_ID` 的取值,以及任何 `--password` 或 `-k` 参数替换为 `[redacted]` —— 包括诊断
+输出(进程视图只打印 `comm`,绝不打印 `argv`)与汇总(只有计数与已脱敏的目标路径)。
+GitHub 本身也会屏蔽所有来自 secret 的值。
+
+在维护者机器上实测:一个 macOS arm64 包需要 93 次 `codesign` 调用(91 次签名、
+1 次校验、1 次 entitlement 显示),`codesign` 墙钟时间约 49s;其中只有 16 个文件是 Mach-O
+代码、5 个是嵌套包。`@electron/osx-sign` 还会给二进制资源签名 —— 33 个 `.pak`,以及
+`.nib`、`.dat`、`.bin`、`.png`、`.icns`、`app.asar` —— 因为它的遍历会选中所有"看起来是
+二进制"的文件,而不只是 Mach-O。用 `mac.signIgnore` 精确排除这些数据文件可以去掉约四分之三
+的调用,但这会改变发布工件所携带的内容,且需要一次真实公证发布来验证,因此这里有意不启用。
+
+`scripts/macos-signing-diagnostics.sh` 在证书导入之前记录 runner 基线:系统版本、
+`codesign --version`、钥匙串身份/列表/默认钥匙串、`xcrun --find notarytool`,以及
+`http://timestamp.apple.com/ts01` 的可达性与延迟。此时 Developer ID 身份理应不存在,
+因为 electron-builder 在打包过程中才从 `CSC_LINK` 导入;只有 `--require-identity`
+才会在缺少身份时判定失败。
+
+签名器现状:`@electron/[email protected]` 由 `[email protected]` 精确锁定,且没有任何
+override 作用于它。它的 `signApplication()` 对每个文件 `await` 一次 `codesign`;没有批量或
+并行路径,也没有任何选项或环境变量可以开启并发。因此更快的签名器只能通过 `mac.sign`
+替换钩子实现,那是重写而不是配置开关;所以该通道继续使用锁定的签名器并保留上述诊断。
+
## 5. 验证门
未签名调试产物(`workflow_dispatch` 且 `sign_macos: false`)不视为通过 Gatekeeper。标签发布必须通过以下签名、公证和装订检查,否则工作流失败。
diff --git a/scripts/README.md b/scripts/README.md
index 17f2d1952..e54305203 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -23,8 +23,11 @@ disagrees, so a green `check:release-docs` is a precondition, not a substitute.
| Script | Alias | Purpose |
|---|---|---|
| `notarize-and-staple-macos-release-dmg.sh` | `scripts/notarize-and-staple-macos-release-dmg.sh [release-dir]` | Submit the single DMG a native macOS job produced to Apple's notary service (`xcrun notarytool submit --wait`), require `status: Accepted`, then attach and validate the ticket (`xcrun stapler staple` / `validate`); run by the Release workflow when `sign_macos` is set. electron-builder only notarizes the `.app`, so the DMG needs this separate submission |
-| `staple-macos-release-dmg.sh` | `scripts/staple-macos-release-dmg.sh [release-dir]` | Attach Apple's notarization ticket (`xcrun stapler staple`) to the single DMG a native macOS job produced; run by the Release workflow when `sign_macos` is set |
| `verify-macos-release.sh` | `scripts/verify-macos-release.sh [release-dir]` | Fail unless the one `PI-Desktop.app` and DMG under the release directory are Developer ID-signed, notarized, and stapled; run by the Release workflow after stapling |
+| `macos-signing-diagnostics.sh` | `scripts/macos-signing-diagnostics.sh [--require-identity]` | Print the non-secret signing baseline before packaging (system, `codesign`, keychain identities/list/default, Xcode notary tools, Apple timestamp reachability). Informational by default, because the Developer ID identity is imported from `CSC_LINK` during packaging; `--require-identity` makes a missing Developer ID fatal |
+| `macos-bundle-inventory.mjs` | `node scripts/macos-bundle-inventory.mjs <app-or-release-dir>` | Count what the signing phase has to touch: entries, Mach-O binaries, `.dylib`/`.node`/frameworks/nested bundles, per-directory cost, and the largest binaries (`signing-candidates`). Informational; run after every macOS package build |
+| `macos-signing-watchdog.mjs` | `node scripts/macos-signing-watchdog.mjs [options] -- <command>` | Run a long silent phase (`electron-builder` signing, `notarytool submit --wait`) with a heartbeat, phase tracking, stall diagnostics (last file, `ps` state, codesign log tail), per-file codesign timings, and a hard timeout that fails instead of hanging; it forwards the child output and exit code unchanged and redacts `CSC_KEY_PASSWORD`/`APPLE_APP_SPECIFIC_PASSWORD`/`CSC_LINK` values plus `--password` arguments |
+| `macos-codesign-shim.sh` | used by `macos-signing-watchdog.mjs` | PATH shim that timestamps every `codesign` invocation and then executes the real `codesign`; inert unless `PI_CODESIGN_LOG` is set |
| `export-linux-asar.mjs` | `node scripts/export-linux-asar.mjs` | Copy the Linux `linux-unpacked/resources/app.asar` into the versioned release asset used for system-Electron repackaging |
| `check-linux-host-glibc.mjs` | `node scripts/check-linux-host-glibc.mjs [bin]` | Fail a Linux host-core binary whose needed glibc is above 2.35 |
| `make-icon.py` | `python3 scripts/make-icon.py` | Derive the package PNG, the macOS tray template, and the iconset/ICNS from the canonical PNG |
diff --git a/scripts/macos-bundle-inventory.mjs b/scripts/macos-bundle-inventory.mjs
new file mode 100644
index 000000000..81fcf2619
--- /dev/null
+++ b/scripts/macos-bundle-inventory.mjs
@@ -0,0 +1,556 @@
+#!/usr/bin/env node
+// Inventory the payload that @electron/osx-sign is about to sign.
+//
+// Why this exists: osx-sign walks the whole `PI-Desktop.app` and runs one
+// `codesign --sign ... --force --timestamp --entitlements ...` per signing
+// candidate, strictly serially. "How long will signing take?" is therefore a
+// function of how many candidates and bytes the bundle contains, and of which
+// of them sit in unexpected places. This script answers that from the built
+// artifact, before anything is signed.
+//
+// What counts as a candidate: @electron/[email protected] calls
+// `getFilePathIfBinary()` (isbinaryfile content detection) for *every* file it
+// walks, so it signs far more than the Mach-O files and nested bundles: any
+// resource that merely looks binary gets its own `codesign` call too. One real
+// signed PI-Desktop.app produced 91 invocations distributed over extensions
+// `.pak` 33, extensionless 24, `.dylib` 12, `.app` 5, `.framework` 4, `.nib` 3,
+// `.dat` 3, `.bin` 3, `.png` 2, `.asar` 1, `.icns` 1. Counting just Mach-O
+// files and nested bundles understates that work by roughly 4x, which is why
+// `binary-resources` exists and why `signing-candidates` includes it.
+//
+// Usage:
+// node scripts/macos-bundle-inventory.mjs <path> [--json] [--top <n>]
+//
+// <path> is either a `*.app` directory or the electron-builder release
+// directory, which must contain exactly one `*.app` one level down (for
+// example `release/mac-arm64/PI-Desktop.app`). `--json` appends one
+// machine-readable line prefixed with `inventory-json: `; `--top <n>` sets
+// how many entries the `top-level-cost` and `slowest-likely` lines list
+// (default 5).
+//
+// Byte accounting: every size is the sum of `st_size` (the file's logical
+// length, not on-disk block usage) of the regular files below that directory.
+// Directory symlinks are never followed: osx-sign walks real directories, and
+// not following them keeps every directory counted exactly once and makes
+// symlink cycles harmless. Symlinks are counted separately from files.
+
+// Binary sniffing: `binary-resources` counts regular files that are not Mach-O
+// and whose first 8 KiB contain a NUL byte. That approximates the isbinaryfile
+// content heuristic osx-sign relies on to decide whether a non-Mach-O file is
+// signed; it is not byte-identical to it (isbinaryfile also weighs UTF BOMs and
+// byte scoring), so treat it as a close lower bound rather than an exact count.
+// `.dylib` and `.node` files already have their own counters and are excluded
+// here so they are never counted twice.
+//
+// Thresholds (overridable so tests and unusually large bundles do not have to
+// create thousands of files):
+// PI_DESKTOP_INVENTORY_MAX_FILES default 2000 (whole bundle)
+// PI_DESKTOP_INVENTORY_MAX_DIR_FILES default 500 (single directory)
+//
+// Exit status: 0 for a completed inventory, 1 for a bad path or bad usage.
+// Warnings never change the exit status.
+
+import fs from "node:fs";
+import path from "node:path";
+
+const USAGE =
+ "usage: node scripts/macos-bundle-inventory.mjs <path> [--json] [--top <n>]";
+
+const DEFAULT_TOP = 5;
+const MAX_LISTED_WARNINGS = 10;
+
+const RESOURCE_DIRECTORIES = [
+ "agent-runtime",
+ "plugins",
+ "skills",
+ "models.dev",
+ "bin",
+];
+
+// Magic numbers of a Mach-O header, read as a big-endian uint32:
+// 32/64-bit big-endian, 32/64-bit little-endian, fat and fat64 big-endian, and
+// the byte-reversed (little-endian) fat variants.
+const MACH_O_MAGICS = new Set([
+ 0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe, 0xcafebabe, 0xcafebabf,
+ 0xbebafeca, 0xbfbafeca,
+]);
+
+// How many leading bytes are sampled when deciding whether a non-Mach-O file
+// merely looks binary.
+const BINARY_SNIFF_BYTES = 8192;
+
+// Extensions that already have a dedicated counter above, and therefore must
+// not be counted again as `binary-resources`.
+const EXTENSION_COUNTED_BINARIES = [".dylib", ".node"];
+
+// Locations where a Mach-O file is expected. Anything else is reported, because
+// it either bloats signing or hides a binary that should not ship.
+const EXPECTED_MACH_O_PREFIXES = [
+ "Contents/MacOS/",
+ "Contents/Frameworks/",
+ "Contents/Resources/bin/",
+];
+
+const warnings = [];
+
+function emitWarning(message) {
+ warnings.push(message);
+}
+
+function flushWarnings() {
+ for (const message of warnings) {
+ process.stdout.write(`warning: ${message}\n`);
+ }
+}
+
+function fail(message) {
+ process.stderr.write(`error: ${message}\n`);
+ process.exit(1);
+}
+
+function positiveInteger(value, fallback) {
+ const parsed = Number.parseInt(value ?? "", 10);
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
+}
+
+function parseArguments(argv) {
+ let target = null;
+ let json = false;
+ let top = DEFAULT_TOP;
+
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index];
+ if (argument === "--json") {
+ json = true;
+ } else if (argument === "--top") {
+ const value = argv[index + 1];
+ if (value === undefined || !/^\d+$/.test(value) || Number(value) < 1) {
+ fail(`--top requires a positive integer (${USAGE})`);
+ }
+ top = Number(value);
+ index += 1;
+ } else if (argument === "--help" || argument === "-h") {
+ process.stdout.write(`${USAGE}\n`);
+ process.exit(0);
+ } else if (argument.startsWith("-") && argument !== "-") {
+ fail(`unknown option: ${argument} (${USAGE})`);
+ } else if (target === null) {
+ target = argument;
+ } else {
+ fail(`unexpected argument: ${argument} (${USAGE})`);
+ }
+ }
+
+ if (target === null) {
+ fail(USAGE);
+ }
+ return { target, json, top };
+}
+
+/**
+ * Read a file's leading bytes once and classify it. The first four bytes decide
+ * Mach-O membership; for everything else the first 8 KiB decide whether the file
+ * merely looks binary, which is what makes osx-sign sign it (see the header).
+ * Unreadable files classify as neither, and are reported by the walker instead.
+ */
+function sniffFile(absolutePath) {
+ let descriptor;
+ try {
+ descriptor = fs.openSync(absolutePath, "r");
+ const header = Buffer.alloc(4);
+ if (
+ fs.readSync(descriptor, header, 0, 4, 0) === 4 &&
+ MACH_O_MAGICS.has(header.readUInt32BE(0))
+ ) {
+ return { machO: true, binary: true };
+ }
+ const sample = Buffer.alloc(BINARY_SNIFF_BYTES);
+ const read = fs.readSync(descriptor, sample, 0, BINARY_SNIFF_BYTES, 0);
+ return { machO: false, binary: sample.subarray(0, read).includes(0) };
+ } catch {
+ return { machO: false, binary: false };
+ } finally {
+ if (descriptor !== undefined) {
+ try {
+ fs.closeSync(descriptor);
+ } catch {
+ // The file is only sniffed; a close failure changes nothing.
+ }
+ }
+ }
+}
+
+/** True for extensions that already have a dedicated counter. */
+function isCountedByExtension(name) {
+ return EXTENSION_COUNTED_BINARIES.some((extension) =>
+ name.endsWith(extension),
+ );
+}
+
+function isDirectory(absolutePath) {
+ try {
+ return fs.statSync(absolutePath).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+function directoriesIn(absoluteDirectory) {
+ let names;
+ try {
+ names = fs.readdirSync(absoluteDirectory);
+ } catch {
+ return [];
+ }
+ const result = [];
+ for (const name of names) {
+ const candidate = path.join(absoluteDirectory, name);
+ if (isDirectory(candidate)) {
+ result.push(candidate);
+ }
+ }
+ return result;
+}
+
+function appBundlesIn(absoluteDirectory) {
+ return directoriesIn(absoluteDirectory).filter((candidate) =>
+ candidate.endsWith(".app"),
+ );
+}
+
+/**
+ * Resolve the single `.app` bundle to inspect. A release directory holds it one
+ * level down (`release/mac-arm64/PI-Desktop.app`); a build directory may hold it
+ * directly, so both levels are searched. Anything other than exactly one match
+ * fails: silently inventorying the wrong bundle is worse than not running.
+ */
+function resolveBundle(target) {
+ const resolved = path.resolve(target);
+ let stats;
+ try {
+ stats = fs.statSync(resolved);
+ } catch {
+ fail(`path does not exist: ${resolved}`);
+ }
+ if (!stats.isDirectory()) {
+ fail(`not a directory: ${resolved}`);
+ }
+ if (path.basename(resolved).endsWith(".app")) {
+ return resolved;
+ }
+
+ const candidates = [...appBundlesIn(resolved)];
+ for (const directory of directoriesIn(resolved)) {
+ candidates.push(...appBundlesIn(directory));
+ }
+ if (candidates.length !== 1) {
+ fail(
+ `expected exactly one *.app bundle under ${resolved} (found ${candidates.length})`,
+ );
+ }
+ return candidates[0];
+}
+
+/**
+ * Walk the bundle once. Directory symlinks are not followed (see the header),
+ * so a symlink cycle cannot loop or double count.
+ */
+function walkBundle(root) {
+ const files = [];
+ const directories = [];
+ const symlinks = [];
+ const pending = [{ absolute: root, relative: "" }];
+
+ while (pending.length > 0) {
+ const current = pending.pop();
+ let names;
+ try {
+ names = fs.readdirSync(current.absolute);
+ } catch (error) {
+ emitWarning(
+ `cannot read directory ${current.relative || "<bundle root>"}: ${error.code ?? error.message}`,
+ );
+ continue;
+ }
+
+ for (const name of names) {
+ const absolute = path.join(current.absolute, name);
+ const relative =
+ current.relative === "" ? name : `${current.relative}/${name}`;
+ let stats;
+ try {
+ stats = fs.lstatSync(absolute);
+ } catch (error) {
+ emitWarning(`cannot stat ${relative}: ${error.code ?? error.message}`);
+ continue;
+ }
+
+ if (stats.isSymbolicLink()) {
+ symlinks.push({ absolute, relative });
+ } else if (stats.isDirectory()) {
+ directories.push({ absolute, relative, name });
+ pending.push({ absolute, relative });
+ } else {
+ const sniffed = stats.isFile()
+ ? sniffFile(absolute)
+ : { machO: false, binary: false };
+ files.push({
+ absolute,
+ relative,
+ name,
+ bytes: stats.size,
+ mode: stats.mode,
+ machO: sniffed.machO,
+ binary: sniffed.binary,
+ });
+ }
+ }
+ }
+
+ return { files, directories, symlinks };
+}
+
+/** Directory part of a file's path, relative to the bundle root. */
+function directorySegments(relative) {
+ const segments = relative.split("/");
+ segments.pop();
+ return segments;
+}
+
+function isInsideFramework(relative) {
+ return directorySegments(relative).some((segment) =>
+ segment.endsWith(".framework"),
+ );
+}
+
+function isInsideNestedApp(relative) {
+ return directorySegments(relative).some((segment) =>
+ segment.endsWith(".app"),
+ );
+}
+
+function hasExpectedMachOLocation(relative) {
+ if (EXPECTED_MACH_O_PREFIXES.some((prefix) => relative.startsWith(prefix))) {
+ return true;
+ }
+ // A nested bundle owns its own layout, so anything inside it is expected.
+ return isInsideNestedApp(relative);
+}
+
+/** `{ files, bytes }` for one resource directory, or `null` when it is absent. */
+function summarizeResourceDirectory(appDirectory, files, name) {
+ const absolute = path.join(appDirectory, "Contents", "Resources", name);
+ if (!isDirectory(absolute)) {
+ return null;
+ }
+ const prefix = `Contents/Resources/${name}/`;
+ let count = 0;
+ let bytes = 0;
+ for (const file of files) {
+ if (file.relative.startsWith(prefix)) {
+ count += 1;
+ bytes += file.bytes;
+ }
+ }
+ return { files: count, bytes };
+}
+
+/** Sum of `st_size` per direct child directory of `Contents`, largest first. */
+function summarizeTopLevelCost(files) {
+ const cost = new Map();
+ for (const file of files) {
+ const segments = file.relative.split("/");
+ if (segments[0] !== "Contents" || segments.length < 3) {
+ continue;
+ }
+ const key = `Contents/${segments[1]}`;
+ cost.set(key, (cost.get(key) ?? 0) + file.bytes);
+ }
+ return [...cost.entries()]
+ .map(([entryPath, bytes]) => ({ path: entryPath, bytes }))
+ .sort((left, right) => right.bytes - left.bytes || left.path.localeCompare(right.path));
+}
+
+function reportCrowdedDirectories(files, maxDirectoryFiles) {
+ const filesPerDirectory = new Map();
+ for (const file of files) {
+ const directory = directorySegments(file.relative).join("/");
+ filesPerDirectory.set(
+ directory,
+ (filesPerDirectory.get(directory) ?? 0) + 1,
+ );
+ }
+ const crowded = [...filesPerDirectory.entries()]
+ .filter(([, count]) => count > maxDirectoryFiles)
+ .sort((left, right) => right[1] - left[1]);
+ reportCapped(
+ `directory holds more than ${maxDirectoryFiles} files`,
+ crowded.map(
+ ([directory, count]) => `${directory || "<bundle root>"} (${count} files)`,
+ ),
+ );
+}
+
+function reportCapped(headline, items) {
+ for (const item of items.slice(0, MAX_LISTED_WARNINGS)) {
+ emitWarning(`${headline}: ${item}`);
+ }
+ if (items.length > MAX_LISTED_WARNINGS) {
+ emitWarning(
+ `${headline}: ${items.length - MAX_LISTED_WARNINGS} more not listed`,
+ );
+ }
+}
+
+function formatResourceSummary(summary) {
+ return RESOURCE_DIRECTORIES.map((name) => {
+ const entry = summary[name];
+ return entry === null ? `${name}=<missing>` : `${name}=${entry.files}/${entry.bytes}`;
+ }).join(", ");
+}
+
+function run() {
+ const { target, json, top } = parseArguments(process.argv.slice(2));
+ const bundle = resolveBundle(target);
+ const maxFiles = positiveInteger(
+ process.env.PI_DESKTOP_INVENTORY_MAX_FILES,
+ 2000,
+ );
+ const maxDirectoryFiles = positiveInteger(
+ process.env.PI_DESKTOP_INVENTORY_MAX_DIR_FILES,
+ 500,
+ );
+
+ const { files, directories, symlinks } = walkBundle(bundle);
+
+ const machOFiles = files.filter((file) => file.machO);
+ const dylib = files.filter((file) => file.name.endsWith(".dylib")).length;
+ const nodeModules = files.filter((file) => file.name.endsWith(".node")).length;
+ const frameworks = directories.filter((directory) =>
+ directory.name.endsWith(".framework"),
+ ).length;
+ const nestedApps = directories.filter((directory) =>
+ directory.name.endsWith(".app"),
+ ).length;
+ const frameworkBinaries = machOFiles.filter((file) =>
+ isInsideFramework(file.relative),
+ ).length;
+ // Resource files that are not Mach-O but look binary, so osx-sign gives each
+ // of them its own `codesign` call. `.dylib`/`.node` are excluded: they are
+ // already reported by their own counters.
+ const binaryResources = files.filter(
+ (file) => file.binary && !file.machO && !isCountedByExtension(file.name),
+ ).length;
+ const executableScripts = files.filter(
+ (file) => !file.machO && (file.mode & 0o111) !== 0,
+ ).length;
+ const executableMachO = machOFiles.filter(
+ (file) => (file.mode & 0o111) !== 0,
+ ).length;
+ // osx-sign signs every nested bundle and every file isbinaryfile calls binary:
+ // the Mach-O files and the binary-looking resources alike.
+ const signingCandidates = machOFiles.length + nestedApps + binaryResources;
+
+ const resources = {};
+ for (const name of RESOURCE_DIRECTORIES) {
+ resources[name] = summarizeResourceDirectory(bundle, files, name);
+ }
+ const topLevelCost = summarizeTopLevelCost(files);
+ const slowestLikely = [...machOFiles]
+ .sort((left, right) => right.bytes - left.bytes)
+ .slice(0, top)
+ .map((file) => ({ path: file.relative, bytes: file.bytes }));
+
+ if (files.length > maxFiles) {
+ emitWarning(
+ `bundle contains ${files.length} files (threshold ${maxFiles}); osx-sign inspects every entry.`,
+ );
+ }
+ reportCrowdedDirectories(files, maxDirectoryFiles);
+ reportCapped(
+ "non-Mach-O regular file in Contents/Resources/bin",
+ files
+ .filter(
+ (file) =>
+ file.relative.startsWith("Contents/Resources/bin/") && !file.machO,
+ )
+ .map((file) => file.relative),
+ );
+ reportCapped(
+ "Mach-O outside Contents/MacOS, Contents/Frameworks, Contents/Resources/bin or a nested .app",
+ machOFiles
+ .filter((file) => !hasExpectedMachOLocation(file.relative))
+ .map((file) => file.relative),
+ );
+
+ process.stdout.write(
+ `==> ${path.basename(bundle)} inventory: ${bundle}\n`,
+ );
+ process.stdout.write(
+ `entries: ${files.length + directories.length + symlinks.length} (files: ${files.length}, directories: ${directories.length}, symlinks: ${symlinks.length})\n`,
+ );
+ process.stdout.write(
+ `mach-o: ${machOFiles.length} (dylib: ${dylib}, node: ${nodeModules}, framework binaries: ${frameworkBinaries})\n`,
+ );
+ process.stdout.write(`binary-resources: ${binaryResources}\n`);
+ process.stdout.write(
+ `bundles: frameworks=${frameworks} nested-apps=${nestedApps}\n`,
+ );
+ process.stdout.write(
+ `executables: script=${executableScripts} mach-o=${executableMachO}\n`,
+ );
+ process.stdout.write(`resources: ${formatResourceSummary(resources)}\n`);
+ process.stdout.write(
+ `top-level-cost: ${
+ topLevelCost.length === 0
+ ? "<none>"
+ : topLevelCost
+ .slice(0, top)
+ .map((entry) => `${entry.path}=${entry.bytes}`)
+ .join(", ")
+ }\n`,
+ );
+ process.stdout.write(
+ `signing-candidates: ${signingCandidates} (mach-o ${machOFiles.length} + nested-bundles ${nestedApps} + binary-resources ${binaryResources})\n`,
+ );
+ process.stdout.write(
+ `slowest-likely: ${
+ slowestLikely.length === 0
+ ? "<none>"
+ : slowestLikely
+ .map((entry) => `${entry.path} (${entry.bytes} bytes)`)
+ .join(", ")
+ }\n`,
+ );
+
+ flushWarnings();
+
+ if (json) {
+ const payload = {
+ bundle,
+ bundleName: path.basename(bundle),
+ entries: files.length + directories.length + symlinks.length,
+ files: files.length,
+ directories: directories.length,
+ symlinks: symlinks.length,
+ machO: machOFiles.length,
+ binaryResources,
+ dylib,
+ nodeModules,
+ frameworkBinaries,
+ frameworks,
+ nestedApps,
+ executableScripts,
+ executableMachO,
+ machOOutsideFramework: machOFiles.length - frameworkBinaries,
+ signingCandidates,
+ resources,
+ topLevelCost: topLevelCost.slice(0, top),
+ slowestLikely,
+ warnings,
+ };
+ process.stdout.write(`inventory-json: ${JSON.stringify(payload)}\n`);
+ }
+}
+
+run();
diff --git a/scripts/macos-codesign-shim.sh b/scripts/macos-codesign-shim.sh
new file mode 100755
index 000000000..0ee9d60d2
--- /dev/null
+++ b/scripts/macos-codesign-shim.sh
@@ -0,0 +1,100 @@
+#!/bin/bash
+#
+# macOS `codesign` timing shim.
+#
+# Why this exists: @electron/osx-sign signs a bundle by invoking `codesign` once
+# per file, strictly serially, and prints nothing per file unless
+# `DEBUG=electron-osx-sign*` is set (that debug stream is enormous). When signing
+# looks like it hung - the electron-builder output stops after
+# `• signing file=... identifyName=...` - the only cheap way to see which file
+# is being worked on, and that `builder-util` is silently retrying a failed call,
+# is to time the calls ourselves.
+#
+# This script is meant to be injected in front of the real `codesign` through
+# PATH (see scripts/macos-signing-watchdog.mjs). It appends tab separated
+# start/end records to $PI_CODESIGN_LOG and then behaves exactly like the real
+# tool: stdout, stderr and the exit status pass through untouched, and with the
+# log unset it does nothing but one `exec`.
+#
+# Environment:
+# PI_CODESIGN_LOG Append timing records here. Unset or empty disables the
+# shim completely (single exec, no log I/O, no overhead).
+# PI_CODESIGN_REAL Absolute path of the real codesign
+# (default: /usr/bin/codesign).
+#
+# Never prints its arguments: `--keychain <path>` would be noise and
+# `--password <value>` would be a secret. Credential-looking values are replaced
+# with [redacted] before they reach the log file.
+
+set -u
+
+PI_CODESIGN_REAL_PATH="${PI_CODESIGN_REAL:-/usr/bin/codesign}"
+PI_CODESIGN_LOG_PATH="${PI_CODESIGN_LOG:-}"
+
+if [ -z "$PI_CODESIGN_LOG_PATH" ]; then
+ exec "$PI_CODESIGN_REAL_PATH" "$@"
+fi
+
+# Wall clock seconds with millisecond resolution. `perl` ships with macOS, but
+# the shim must keep working (with second resolution) when it is unavailable, so
+# every fallback is checked and none of them may fail the call.
+pi_now() {
+ local value=""
+ if command -v perl >/dev/null 2>&1; then
+ value="$(perl -MTime::HiRes=time -e 'printf "%.3f\n", time' 2>/dev/null)" || value=""
+ case "$value" in
+ [0-9]*.[0-9]*) printf '%s\n' "$value"; return 0 ;;
+ esac
+ fi
+ if command -v date >/dev/null 2>&1; then
+ value="$(date +%s 2>/dev/null)" || value=""
+ case "$value" in
+ [0-9]*) printf '%s\n' "$value"; return 0 ;;
+ esac
+ fi
+ printf '%s\n' "${SECONDS:-0}"
+}
+
+pi_log() {
+ # Never let a broken or unwritable log path disturb codesign: stderr is
+ # silenced before the file is opened, so even the redirection error is
+ # swallowed instead of leaking into the build output.
+ printf '%s\t%s\t%s\t%s\n' "$1" "$2" "$3" "$4" 2>/dev/null >> "$PI_CODESIGN_LOG_PATH" || true
+}
+
+# Join argv with single spaces, drop newlines/tabs (they would forge log lines)
+# and redact credential-looking values.
+pi_redacted_args() {
+ local joined="" first=1 arg value redact_next=0
+ for arg in "$@"; do
+ value="$arg"
+ if [ "$redact_next" -eq 1 ]; then
+ value="[redacted]"
+ redact_next=0
+ else
+ case "$arg" in
+ --password | --keychain-password | -p) redact_next=1 ;;
+ --password=* | --keychain-password=*) value="${arg%%=*}=[redacted]" ;;
+ esac
+ fi
+ value="${value//$'\n'/ }"
+ value="${value//$'\r'/ }"
+ value="${value//$'\t'/ }"
+ if [ "$first" -eq 1 ]; then
+ joined="$value"
+ first=0
+ else
+ joined="$joined $value"
+ fi
+ done
+ printf '%s' "$joined"
+}
+
+pi_log "start" "$(pi_now)" "$$" "$(pi_redacted_args "$@")"
+
+"$PI_CODESIGN_REAL_PATH" "$@"
+PI_CODESIGN_STATUS=$?
+
+pi_log "end" "$(pi_now)" "$$" "$PI_CODESIGN_STATUS"
+
+exit "$PI_CODESIGN_STATUS"
diff --git a/scripts/macos-signing-diagnostics.sh b/scripts/macos-signing-diagnostics.sh
new file mode 100755
index 000000000..278839533
--- /dev/null
+++ b/scripts/macos-signing-diagnostics.sh
@@ -0,0 +1,220 @@
+#!/usr/bin/env bash
+# Record a non-sensitive snapshot of the macOS code-signing environment before
+# electron-builder starts packaging.
+#
+# Why this exists: @electron/osx-sign walks the whole `PI-Desktop.app` and runs
+# one `codesign --sign <identity> --force --timestamp --entitlements ...` per
+# Mach-O file and per nested bundle, strictly serially. When a release signing
+# step stalls, every interesting question is environmental: is a usable
+# Developer ID identity in this keychain at all, which keychains are searched,
+# is the Xcode toolchain complete, and can every `codesign` call reach Apple's
+# timestamp service. Recording that baseline next to the build keeps the answer
+# in the job log instead of in a rerun.
+#
+# Usage: scripts/macos-signing-diagnostics.sh [--require-identity]
+#
+# Environment:
+# MAC_SIGNING_IDENTITY bare common name ("XingYu Liu (DUV63RKYTW)") or the
+# full certificate label
+# ("Developer ID Application: XingYu Liu (DUV63RKYTW)").
+#
+# Exit status:
+# 0 snapshot printed. A missing certificate is only a warning by default:
+# the runner has no identity until electron-builder imports CSC_LINK.
+# 1 not running on macOS, or --require-identity was passed and this keychain
+# has no matching Developer ID identity.
+#
+# Secret handling: this script never prints the values of CSC_LINK,
+# CSC_KEY_PASSWORD, APPLE_ID, APPLE_APP_SPECIFIC_PASSWORD or APPLE_TEAM_ID, and
+# it never dumps `env`. Every line produced by an external command is piped
+# through `redact`, which rewrites those values (when set and at least 6
+# characters long) to `[redacted]`. A value containing a newline cannot be
+# represented as a sed pattern, so the snapshot suppresses command output
+# instead of risking a leak.
+
+set -euo pipefail
+
+REQUIRE_IDENTITY=false
+for arg in "$@"; do
+ case "$arg" in
+ --require-identity) REQUIRE_IDENTITY=true ;;
+ *)
+ echo "error: unknown argument: $arg" >&2
+ echo "usage: scripts/macos-signing-diagnostics.sh [--require-identity]" >&2
+ exit 1
+ ;;
+ esac
+done
+
+# Accepts either the bare common name or the full certificate label, matching
+# scripts/verify-macos-release.sh.
+IDENTITY_NAME="${MAC_SIGNING_IDENTITY:-XingYu Liu (DUV63RKYTW)}"
+IDENTITY_NAME="${IDENTITY_NAME#Developer ID Application: }"
+EXPECTED_IDENTITY="Developer ID Application: ${IDENTITY_NAME}"
+
+if [[ "$(uname -s 2>/dev/null || true)" != "Darwin" ]]; then
+ echo "error: macOS signing diagnostics must run on macOS." >&2
+ exit 1
+fi
+
+# ---------------------------------------------------------------------------
+# Redaction
+# ---------------------------------------------------------------------------
+
+REDACT_NAMES=(CSC_LINK CSC_KEY_PASSWORD APPLE_ID APPLE_APP_SPECIFIC_PASSWORD APPLE_TEAM_ID)
+REDACT_SED=""
+REDACT_UNSAFE=false
+
+for redact_name in "${REDACT_NAMES[@]}"; do
+ redact_value="${!redact_name:-}"
+ # Short values would match unrelated text, so they are not used as patterns.
+ if (( ${#redact_value} < 6 )); then
+ continue
+ fi
+ if [[ "$redact_value" == *$'\n'* ]]; then
+ REDACT_UNSAFE=true
+ continue
+ fi
+ # Escape backslashes first, then every BRE metacharacter plus the delimiter,
+ # so an arbitrary secret can be used as a literal sed pattern.
+ redact_pattern="$(printf '%s' "$redact_value" | sed -e 's/\\/\\\\/g' -e 's/[/.[*^$]/\\&/g')"
+ REDACT_SED="${REDACT_SED}s/${redact_pattern}/[redacted]/g"$'\n'
+done
+
+# Rewrite secret values in stdin to [redacted].
+redact() {
+ if [[ "$REDACT_UNSAFE" == "true" ]]; then
+ echo "[output suppressed: a secret value could not be redacted]"
+ return 0
+ fi
+ if [[ -z "$REDACT_SED" ]]; then
+ cat
+ return 0
+ fi
+ sed -e "$REDACT_SED"
+}
+
+# Echo one block of already-captured command output with secrets redacted. A
+# redaction failure suppresses the block instead of printing it raw.
+echo_redacted() {
+ local text="$1"
+ if [[ -z "$text" ]]; then
+ return 0
+ fi
+ if ! printf '%s\n' "$text" | redact; then
+ echo "warning: could not redact command output; suppressing it."
+ fi
+ return 0
+}
+
+# Run a command and echo its combined output, redacted. A missing or failing
+# command only warns: this step must never break the release build.
+echo_command_output() {
+ local command_name="$1"
+ shift
+ if ! command -v "$command_name" >/dev/null 2>&1; then
+ echo "warning: $command_name unavailable"
+ return 0
+ fi
+ local output status
+ output="$("$command_name" "$@" 2>&1)" && status=0 || status=$?
+ echo_redacted "$output"
+ if [[ "$status" -ne 0 ]]; then
+ echo "warning: $command_name $* exited with status $status"
+ fi
+ return 0
+}
+
+# ---------------------------------------------------------------------------
+# 1. System
+# ---------------------------------------------------------------------------
+
+echo "==> System"
+echo_command_output sw_vers
+echo_command_output uname -a
+echo_command_output uname -m
+
+# ---------------------------------------------------------------------------
+# 2. codesign
+# ---------------------------------------------------------------------------
+
+echo "==> codesign"
+echo_command_output which codesign
+CODESIGN_VERSION_STATUS=0
+CODESIGN_VERSION_OUTPUT="$(codesign --version 2>&1)" || CODESIGN_VERSION_STATUS=$?
+echo_redacted "$CODESIGN_VERSION_OUTPUT"
+if [[ "$CODESIGN_VERSION_STATUS" -ne 0 ]]; then
+ echo "warning: codesign --version exited with status $CODESIGN_VERSION_STATUS; some codesign builds only print their usage here."
+fi
+
+# ---------------------------------------------------------------------------
+# 3. Code signing identities (only the output of find-identity is printed; no
+# certificate or private key material is ever read or dumped)
+# ---------------------------------------------------------------------------
+
+echo "==> Code signing identities (security find-identity -v -p codesigning)"
+IDENTITY_OUTPUT=""
+if command -v security >/dev/null 2>&1; then
+ IDENTITY_STATUS=0
+ IDENTITY_OUTPUT="$(security find-identity -v -p codesigning 2>&1)" || IDENTITY_STATUS=$?
+ echo_redacted "$IDENTITY_OUTPUT"
+ if [[ "$IDENTITY_STATUS" -ne 0 ]]; then
+ echo "warning: security find-identity exited with status $IDENTITY_STATUS"
+ fi
+else
+ echo "warning: security unavailable"
+fi
+
+# ---------------------------------------------------------------------------
+# 4. Keychains
+# ---------------------------------------------------------------------------
+
+echo "==> Keychain"
+echo_command_output security list-keychains
+echo_command_output security default-keychain
+
+# ---------------------------------------------------------------------------
+# 5. Xcode toolchain
+# ---------------------------------------------------------------------------
+
+echo "==> Xcode toolchain"
+echo_command_output xcrun --find notarytool
+echo_command_output xcrun --find stapler
+
+# ---------------------------------------------------------------------------
+# 6. Apple timestamp service
+# `--timestamp` makes every single codesign invocation depend on this
+# endpoint, so a slow or unreachable service is a prime suspect for a stalled
+# signing phase. A failure here is informational only.
+# ---------------------------------------------------------------------------
+
+echo "==> Apple timestamp service (http://timestamp.apple.com/ts01)"
+if command -v curl >/dev/null 2>&1; then
+ CURL_STATUS=0
+ CURL_OUTPUT="$(curl -s -o /dev/null --max-time 10 -w '%{http_code} %{time_total}\n' http://timestamp.apple.com/ts01 2>&1)" || CURL_STATUS=$?
+ echo_redacted "$CURL_OUTPUT"
+ if [[ "$CURL_STATUS" -ne 0 ]]; then
+ echo "warning: Apple timestamp service probe failed (curl exit $CURL_STATUS); codesign --timestamp may be slow or fail."
+ fi
+else
+ echo "warning: curl unavailable; cannot probe the Apple timestamp service."
+fi
+
+# ---------------------------------------------------------------------------
+# 7. Conclusion
+# ---------------------------------------------------------------------------
+
+echo "==> Signing identity"
+if [[ -n "$IDENTITY_OUTPUT" && "$IDENTITY_OUTPUT" == *"$EXPECTED_IDENTITY"* ]]; then
+ echo "==> Developer ID identity available: ${EXPECTED_IDENTITY}"
+ IDENTITY_LINE="$(printf '%s\n' "$IDENTITY_OUTPUT" | grep -F -- "$EXPECTED_IDENTITY" | head -n 1 || true)"
+ echo_redacted "$IDENTITY_LINE"
+else
+ echo "warning: Developer ID Application: ${IDENTITY_NAME} is not available in the current keychain (electron-builder imports CSC_LINK during packaging)."
+ if [[ "$REQUIRE_IDENTITY" == "true" ]]; then
+ echo "error: Developer ID Application: ${IDENTITY_NAME} is not available in this keychain." >&2
+ exit 1
+ fi
+fi
+
+echo "==> macOS signing diagnostics complete"
diff --git a/scripts/macos-signing-watchdog.mjs b/scripts/macos-signing-watchdog.mjs
new file mode 100644
index 000000000..6abbf3080
--- /dev/null
+++ b/scripts/macos-signing-watchdog.mjs
@@ -0,0 +1,849 @@
+#!/usr/bin/env node
+/**
+ * macOS signing watchdog.
+ *
+ * Why this exists: `electron-builder --mac` prints one line
+ * (`• signing file=... platform=darwin type=distribution identityName=...`) and
+ * then goes silent for a long time. Three real reasons, all invisible in the
+ * default output:
+ *
+ * 1. @electron/osx-sign signs serially, one `codesign` call per file, and only
+ * logs per file with `DEBUG=electron-osx-sign*`.
+ * 2. When any `codesign` call fails, builder-util retries the whole round
+ * three times (5s/10s/15s) without printing anything.
+ * 3. With `mac.notarize=true`, @electron/notarize zips the app, uploads it and
+ * waits for Apple's queue - visible only with `DEBUG=electron-notarize*`.
+ *
+ * This wrapper gives that stage a back channel:
+ *
+ * - every child line is forwarded live with a `[sign] ` prefix (redacted),
+ * - `codesign` is wrapped by scripts/macos-codesign-shim.sh so each call is
+ * timed through $PI_CODESIGN_LOG (see --codesign-log),
+ * - a heartbeat reports phase/idle time/active codesign while output is
+ * silent, plus a bounded stall diagnostic dump,
+ * - a hard timeout terminates the whole process group and exits 124,
+ * - a summary with codesign call counts, percentiles and slowest files is
+ * printed on every exit path and appended to $GITHUB_STEP_SUMMARY.
+ *
+ * Usage:
+ * node scripts/macos-signing-watchdog.mjs [options] -- <command> [args...]
+ *
+ * Nothing here fails on a stall: waiting on Apple's notary queue is a legal,
+ * silent, multi-minute wait.
+ */
+
+import { execFileSync, spawn, spawnSync } from "node:child_process";
+import {
+ appendFileSync,
+ chmodSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { constants as osConstants, tmpdir } from "node:os";
+import { basename, dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const SHIM_SOURCE_PATH = fileURLToPath(
+ new URL("./macos-codesign-shim.sh", import.meta.url),
+);
+const DEFAULT_CODESIGN_LOG = join(
+ tmpdir(),
+ `pi-desktop-codesign-timing-${process.pid}.log`,
+);
+const DEFAULT_TIMEOUT_SECONDS = 2400;
+const DEFAULT_STALL_SECONDS = 300;
+const DEFAULT_HEARTBEAT_SECONDS = 60;
+
+/**
+ * Env values that must never reach the log, even if the child echoes them.
+ * Password values are redacted at any length; the certificate blob and the
+ * Apple ID keep a length guard so a short, innocuous value cannot rewrite
+ * unrelated log text.
+ */
+const REDACT_ENV_KEYS = ["CSC_LINK", "APPLE_ID"];
+const REDACT_ALWAYS_ENV_KEYS = [
+ "CSC_KEY_PASSWORD",
+ "APPLE_APP_SPECIFIC_PASSWORD",
+];
+/**
+ * `-k` is in the list because `security set-key-partition-list ... -k <p12
+ * password>` is how electron-builder unlocks the imported certificate, and
+ * builder-util's own `executing` debug line does not redact that stem. The
+ * cost is that an unrelated `-k <keychain path>` is redacted too.
+ */
+const REDACT_FLAG_PATTERN =
+ /(--password|--keychain-password|--app-specific-password|-p|-k)\s+\S+/g;
+const REDACT_FLAG_VALUE_PATTERN =
+ /(-k|--password|--keychain-password|--app-specific-password)=\S+/g;
+
+/** Only these processes are reported in a diagnostic dump (never their argv). */
+const DIAGNOSTIC_COMMANDS = new Set([
+ "codesign",
+ "security",
+ "notarytool",
+ "stapler",
+ "xcrun",
+ "electron-builder",
+ "node",
+]);
+
+const RECENT_OUTPUT_LINES = 20;
+const CODESIGN_LOG_TAIL_LINES = 10;
+const MAX_STALL_DUMPS = 3;
+const SLOWEST_LIMIT = 5;
+/** Rate limit so the watchdog never turns into a high frequency poller. */
+const HEARTBEAT_MIN_INTERVAL_MS = 10_000;
+const KILL_GRACE_MS = 10_000;
+const SIGKILL_SETTLE_MS = 1000;
+
+class UsageError extends Error {}
+
+function usage() {
+ return [
+ "Usage: node scripts/macos-signing-watchdog.mjs [options] -- <command> [args...]",
+ "",
+ "Options:",
+ " --label <name> Label used in the summary (default: basename of the command).",
+ " --timeout-seconds <n> Hard timeout in seconds (default: 2400, env PI_SIGNING_TIMEOUT_SECONDS).",
+ " --stall-seconds <n> Silence that counts as a stall, in seconds (default: 300, env PI_SIGNING_STALL_SECONDS).",
+ " --heartbeat-seconds <n> Heartbeat interval while output is silent (default: 60, env PI_SIGNING_HEARTBEAT_SECONDS).",
+ " --codesign-log <path> codesign timing log (default: $TMPDIR/pi-desktop-codesign-timing.log).",
+ " --summary-file <path> Also write the summary lines to this file.",
+ " --no-codesign-shim Do not inject the codesign timing shim (env PI_SIGNING_NO_CODESIGN_SHIM).",
+ "",
+ "Everything after `--` is the command to run; its stdout/stderr is forwarded line by line.",
+ ].join("\n");
+}
+
+function numberFromEnv(name, fallback) {
+ const raw = process.env[name];
+ if (typeof raw !== "string" || raw.trim() === "") return fallback;
+ const value = Number(raw);
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function isEnabledEnv(name) {
+ const raw = process.env[name];
+ if (typeof raw !== "string") return false;
+ return ["1", "true", "yes", "on"].includes(raw.trim().toLowerCase());
+}
+
+function parsePositiveNumber(flag, raw) {
+ const value = Number(raw);
+ if (!Number.isFinite(value) || value <= 0) {
+ throw new UsageError(`${flag} expects a positive number, got: ${raw}`);
+ }
+ return value;
+}
+
+function parseArgv(argv) {
+ const options = {
+ label: "",
+ timeoutSeconds: numberFromEnv(
+ "PI_SIGNING_TIMEOUT_SECONDS",
+ DEFAULT_TIMEOUT_SECONDS,
+ ),
+ stallSeconds: numberFromEnv(
+ "PI_SIGNING_STALL_SECONDS",
+ DEFAULT_STALL_SECONDS,
+ ),
+ heartbeatSeconds: numberFromEnv(
+ "PI_SIGNING_HEARTBEAT_SECONDS",
+ DEFAULT_HEARTBEAT_SECONDS,
+ ),
+ codesignLog: DEFAULT_CODESIGN_LOG,
+ summaryFile: "",
+ // The shim only adds timing; `PI_SIGNING_NO_CODESIGN_SHIM=1` is the
+ // rollback switch if a keychain ever refuses to hand the key to a
+ // wrapped codesign invocation.
+ codesignShim: !isEnabledEnv("PI_SIGNING_NO_CODESIGN_SHIM"),
+ command: [],
+ };
+
+ let index = 0;
+ for (; index < argv.length; index += 1) {
+ const arg = argv[index];
+ if (arg === "--") {
+ index += 1;
+ break;
+ }
+ const nextValue = () => {
+ index += 1;
+ const value = argv[index];
+ if (value === undefined) {
+ throw new UsageError(`${arg} requires a value`);
+ }
+ return value;
+ };
+ switch (arg) {
+ case "--label":
+ options.label = nextValue();
+ break;
+ case "--timeout-seconds":
+ options.timeoutSeconds = parsePositiveNumber(arg, nextValue());
+ break;
+ case "--stall-seconds":
+ options.stallSeconds = parsePositiveNumber(arg, nextValue());
+ break;
+ case "--heartbeat-seconds":
+ options.heartbeatSeconds = parsePositiveNumber(arg, nextValue());
+ break;
+ case "--codesign-log":
+ options.codesignLog = nextValue();
+ break;
+ case "--summary-file":
+ options.summaryFile = nextValue();
+ break;
+ case "--no-codesign-shim":
+ options.codesignShim = false;
+ break;
+ default:
+ throw new UsageError(
+ arg.startsWith("-")
+ ? `unknown option: ${arg}`
+ : `expected "--" before the command, got: ${arg}`,
+ );
+ }
+ }
+
+ options.command = argv.slice(index);
+ if (options.command.length === 0) {
+ throw new UsageError('no command given, expected "-- <command> [args...]"');
+ }
+ if (options.label === "") options.label = basename(options.command[0]);
+ return options;
+}
+
+/**
+ * Remove credentials from anything the watchdog prints. Output found in the
+ * child's output is untrusted, so both known secret env values (length >= 6, to
+ * avoid mangling short harmless values) and flag/value shapes are replaced.
+ */
+function redact(text) {
+ let out = String(text);
+ for (const key of REDACT_ALWAYS_ENV_KEYS) {
+ const value = process.env[key];
+ if (typeof value === "string" && value.length > 0) {
+ out = out.split(value).join("[redacted]");
+ }
+ }
+ for (const key of REDACT_ENV_KEYS) {
+ const value = process.env[key];
+ if (typeof value === "string" && value.length >= 6) {
+ out = out.split(value).join("[redacted]");
+ }
+ }
+ out = out.replace(REDACT_FLAG_PATTERN, (_match, flag) => `${flag} [redacted]`);
+ out = out.replace(
+ REDACT_FLAG_VALUE_PATTERN,
+ (_match, flag) => `${flag}=[redacted]`,
+ );
+ return out;
+}
+
+function resolveRealCodesign(pathValue) {
+ try {
+ const result = spawnSync("bash", ["-c", "command -v codesign"], {
+ encoding: "utf8",
+ env: { ...process.env, PATH: pathValue },
+ });
+ const candidates = (result.stdout ?? "")
+ .split("\n")
+ .map((line) => line.trim())
+ .filter(Boolean);
+ const candidate = candidates[candidates.length - 1];
+ if (typeof candidate === "string" && candidate.startsWith("/")) {
+ return candidate;
+ }
+ } catch {
+ // Fall through to the system default.
+ }
+ return "/usr/bin/codesign";
+}
+
+/**
+ * Line splitter that keeps partial lines buffered so a child killed mid-line
+ * still flushes its remainder on exit ('end' or an explicit flush()).
+ */
+function createLineReader(stream, onLine) {
+ let buffer = "";
+ stream.setEncoding("utf8");
+ stream.on("data", (chunk) => {
+ buffer += chunk;
+ let newline = buffer.indexOf("\n");
+ while (newline !== -1) {
+ const line = buffer.slice(0, newline);
+ buffer = buffer.slice(newline + 1);
+ onLine(line.replace(/\r$/, ""));
+ newline = buffer.indexOf("\n");
+ }
+ });
+ stream.on("end", () => {
+ if (buffer.length > 0) {
+ onLine(buffer.replace(/\r$/, ""));
+ buffer = "";
+ }
+ });
+ stream.on("error", () => {});
+ return {
+ flush() {
+ if (buffer.length > 0) {
+ onLine(buffer.replace(/\r$/, ""));
+ buffer = "";
+ }
+ },
+ };
+}
+
+/**
+ * Parse the shim log. Records are tab separated:
+ * start <unix-seconds.ms> <pid> <space joined args>
+ * end <unix-seconds.ms> <pid> <exit code>
+ * Calls are paired FIFO per pid; anything left over is still running (or was
+ * killed), which is exactly what the stall diagnostic and the summary need.
+ */
+function readCodesignLog(logPath) {
+ const calls = [];
+ const active = [];
+ let raw = "";
+ try {
+ raw = readFileSync(logPath, "utf8");
+ } catch {
+ return { calls, active, failures: 0 };
+ }
+
+ const pending = new Map();
+ for (const line of raw.split("\n")) {
+ if (line === "") continue;
+ const parts = line.split("\t");
+ if (parts[0] === "start" && parts.length >= 4) {
+ const startedAt = Number(parts[1]);
+ const pid = parts[2];
+ const args = parts.slice(3).join("\t");
+ const queue = pending.get(pid) ?? [];
+ queue.push({
+ pid,
+ startedAt: Number.isFinite(startedAt) ? startedAt : 0,
+ args,
+ exitCode: null,
+ });
+ pending.set(pid, queue);
+ continue;
+ }
+ if (parts[0] === "end" && parts.length >= 4) {
+ const endedAt = Number(parts[1]);
+ const queue = pending.get(parts[2]);
+ if (!queue || queue.length === 0) continue;
+ const call = queue.shift();
+ const duration =
+ Number.isFinite(endedAt) && Number.isFinite(call.startedAt)
+ ? Math.max(0, endedAt - call.startedAt)
+ : 0;
+ calls.push({
+ pid: call.pid,
+ args: call.args,
+ exitCode: Number(parts[3]),
+ duration,
+ category: categorizeCodesign(call.args),
+ target: codesignTarget(call.args),
+ });
+ }
+ }
+
+ for (const queue of pending.values()) {
+ for (const call of queue) active.push(call);
+ }
+ active.sort((a, b) => a.startedAt - b.startedAt);
+
+ const failures =
+ active.length + calls.filter((call) => call.exitCode !== 0).length;
+ return { calls, active, failures };
+}
+
+function categorizeCodesign(args) {
+ if (/(^|\s)--verify(\s|$)/.test(args)) return "verify";
+ if (/(^|\s)--display(\s|$)/.test(args)) return "display";
+ if (/(^|\s)--sign(\s|$)/.test(args)) return "sign";
+ return "other";
+}
+
+/** codesign takes its target as the last bare argument. */
+function codesignTarget(args) {
+ const tokens = args.split(" ").filter(Boolean);
+ for (let index = tokens.length - 1; index >= 0; index -= 1) {
+ if (!tokens[index].startsWith("-")) return tokens[index];
+ }
+ return args === "" ? "<unknown>" : args;
+}
+
+function percentile(sortedDurations, percent) {
+ if (sortedDurations.length === 0) return 0;
+ const rank = Math.ceil((percent / 100) * sortedDurations.length);
+ const index = Math.min(
+ sortedDurations.length - 1,
+ Math.max(0, rank - 1),
+ );
+ return sortedDurations[index];
+}
+
+function seconds(value) {
+ return `${value.toFixed(1)}s`;
+}
+
+function truncate(value, limit) {
+ return value.length <= limit ? value : `${value.slice(0, limit - 1)}…`;
+}
+
+function signalNumber(signal) {
+ const number = osConstants.signals?.[signal];
+ return typeof number === "number" ? number : 0;
+}
+
+function run() {
+ let options;
+ try {
+ options = parseArgv(process.argv.slice(2));
+ } catch (error) {
+ if (error instanceof UsageError) {
+ process.stderr.write(`macos-signing-watchdog: ${error.message}\n\n${usage()}\n`);
+ process.exitCode = 2;
+ return;
+ }
+ throw error;
+ }
+ const startedAt = Date.now();
+ const state = {
+ phase: "starting",
+ lastFile: "",
+ recent: [],
+ lastOutputAt: startedAt,
+ lastHeartbeatAt: 0,
+ lastStallAt: 0,
+ stallCount: 0,
+ timedOut: false,
+ spawnError: null,
+ };
+
+ const isDarwin = process.platform === "darwin";
+ const useShim = options.codesignShim && isDarwin;
+ let shimRoot = "";
+ let childEnv = { ...process.env };
+
+ let shimActive = false;
+ if (useShim) {
+ try {
+ const realCodesign = resolveRealCodesign(process.env.PATH ?? "");
+ shimRoot = mkdtempSync(join(tmpdir(), "pi-desktop-signing-watchdog-"));
+ const shimDir = join(shimRoot, "bin");
+ mkdirSync(shimDir, { recursive: true });
+ const shimPath = join(shimDir, "codesign");
+ writeFileSync(shimPath, readFileSync(SHIM_SOURCE_PATH));
+ chmodSync(shimPath, 0o755);
+ mkdirSync(dirname(options.codesignLog), { recursive: true });
+ // Start from an empty log so a previous run cannot pollute the summary.
+ writeFileSync(options.codesignLog, "");
+ childEnv = {
+ ...childEnv,
+ PATH: `${shimDir}:${process.env.PATH ?? ""}`,
+ PI_CODESIGN_LOG: options.codesignLog,
+ PI_CODESIGN_REAL: realCodesign,
+ };
+ shimActive = true;
+ } catch (error) {
+ // Timing data is diagnostics: losing it must not fail the release.
+ shimRoot = "";
+ process.stderr.write(
+ `[sign] warning: codesign timing shim disabled (${redact(error.message)})\n`,
+ );
+ }
+ }
+
+ process.stdout.write(
+ `[sign] watchdog label=${options.label} timeout=${options.timeoutSeconds}s stall=${options.stallSeconds}s heartbeat=${options.heartbeatSeconds}s codesign-shim=${shimActive ? "on" : "off"}\n`,
+ );
+ process.stdout.write(
+ `[sign] watchdog command: ${redact(options.command.map((part) => (/\s/.test(part) ? JSON.stringify(part) : part)).join(" "))}\n`,
+ );
+
+ const heartbeatIntervalMs = Math.max(
+ options.heartbeatSeconds * 1000,
+ HEARTBEAT_MIN_INTERVAL_MS,
+ );
+ const stallIntervalMs = options.stallSeconds * 1000;
+ // Never poll faster than 500ms and never slower than 10s: the heartbeat rate
+ // limit and a stall dump both need a timely tick.
+ const tickIntervalMs = Math.max(
+ 500,
+ Math.min(
+ HEARTBEAT_MIN_INTERVAL_MS,
+ heartbeatIntervalMs,
+ Math.max(stallIntervalMs, 500),
+ ),
+ );
+ const heartbeatDueMs = Math.max(0, heartbeatIntervalMs - tickIntervalMs);
+ const readShimState = () =>
+ useShim
+ ? readCodesignLog(options.codesignLog)
+ : { calls: [], active: [], failures: 0 };
+
+ function activeCodesign() {
+ const { active } = readShimState();
+ if (active.length === 0) return null;
+ const latest = active[active.length - 1];
+ return {
+ pid: latest.pid,
+ startedAt: latest.startedAt * 1000,
+ args: latest.args,
+ target: codesignTarget(latest.args),
+ };
+ }
+
+ function targetName(active) {
+ const target = state.lastFile || active?.target || "";
+ return target === "" ? "none" : basename(target);
+ }
+
+ function detectPhase(line) {
+ if (line.includes("Walking...")) return "walking";
+ const signing = line.match(/Signing\.\.\.\s+(.+?)\s*$/);
+ if (signing) {
+ state.lastFile = signing[1];
+ return `signing:${basename(signing[1])}`;
+ }
+ if (/Executing\.\.\./.test(line)) return "codesign";
+ if (line.includes("Verifying...")) return "verifying";
+ if (line.includes("signing file=")) return "packaging-sign";
+ if (/notarization successful/i.test(line)) return "notarized";
+ if (
+ line.includes("notarizing using notarytool") ||
+ line.includes("starting notarize process") ||
+ line.includes("attempting to upload file to Apple") ||
+ line.includes("zipping application to")
+ ) {
+ return "notarizing";
+ }
+ return null;
+ }
+
+ function handleLine(rawLine, sink) {
+ const line = rawLine.replace(/\r$/, "");
+ state.lastOutputAt = Date.now();
+ state.lastStallAt = 0;
+ const phase = detectPhase(line);
+ if (phase !== null && phase !== state.phase) {
+ state.phase = phase;
+ sink.write(`[sign] phase: ${redact(phase)}\n`);
+ }
+ const safe = redact(line);
+ state.recent.push(safe);
+ if (state.recent.length > RECENT_OUTPUT_LINES) state.recent.shift();
+ sink.write(`[sign] ${safe}\n`);
+ }
+
+ function processSnapshot() {
+ try {
+ const raw = execFileSync("ps", ["-Ao", "pid=,etime=,comm="], {
+ encoding: "utf8",
+ });
+ const rows = [];
+ for (const line of raw.split("\n")) {
+ const match = line.match(/^\s*(\d+)\s+(\S+)\s+(.*\S)\s*$/);
+ if (!match) continue;
+ const [, pid, etime, comm] = match;
+ if (!DIAGNOSTIC_COMMANDS.has(basename(comm))) continue;
+ rows.push(`${pid} ${etime} ${comm}`);
+ }
+ return rows;
+ } catch {
+ return [];
+ }
+ }
+
+ function codesignLogTail() {
+ if (!useShim) return [];
+ try {
+ const raw = readFileSync(options.codesignLog, "utf8");
+ return raw
+ .split("\n")
+ .filter((line) => line !== "")
+ .slice(-CODESIGN_LOG_TAIL_LINES)
+ .map((line) => redact(line));
+ } catch {
+ return [];
+ }
+ }
+
+ // The dump is reused verbatim by the timeout path.
+ function writeDiagnostics() {
+ const lines = [];
+ lines.push("[sign] STALL: recent output:");
+ if (state.recent.length === 0) {
+ lines.push("[sign] <none>");
+ } else {
+ for (const line of state.recent) lines.push(`[sign] ${line}`);
+ }
+ lines.push("[sign] STALL: processes:");
+ const processes = processSnapshot();
+ if (processes.length === 0) {
+ lines.push("[sign] <none>");
+ } else {
+ for (const row of processes) lines.push(`[sign] ${row}`);
+ }
+ lines.push("[sign] STALL: codesign log tail:");
+ const tail = codesignLogTail();
+ if (tail.length === 0) {
+ lines.push("[sign] <none>");
+ } else {
+ for (const row of tail) lines.push(`[sign] ${row}`);
+ }
+ process.stdout.write(`${lines.join("\n")}\n`);
+ }
+
+ function onTick() {
+ const now = Date.now();
+ const idleMs = now - state.lastOutputAt;
+ const active = activeCodesign();
+
+ // One tick of slack: the heartbeat is polled, and the tick that lands just
+ // before the interval boundary must not skip a whole period. The 10s rate
+ // limit below still keeps the print rate bounded.
+ if (
+ idleMs >= heartbeatDueMs &&
+ now - state.lastHeartbeatAt >= HEARTBEAT_MIN_INTERVAL_MS
+ ) {
+ state.lastHeartbeatAt = now;
+ const activeStartedAt = active === null ? 0 : active.startedAt;
+ const activeElapsed =
+ active === null
+ ? 0
+ : Math.max(0, Math.floor((now - activeStartedAt) / 1000));
+ process.stdout.write(
+ `[sign] heartbeat elapsed=${Math.floor((now - startedAt) / 1000)}s phase=${state.phase} idle=${Math.floor(idleMs / 1000)}s active-codesign=${active === null ? "none" : active.pid} active-elapsed=${activeElapsed}s target=${targetName(active)}\n`,
+ );
+ }
+
+ if (idleMs < stallIntervalMs) return;
+ if (active !== null) return;
+ if (state.stallCount >= MAX_STALL_DUMPS) return;
+ if (now - state.lastStallAt < stallIntervalMs) return;
+ state.lastStallAt = now;
+ state.stallCount += 1;
+ process.stdout.write(
+ `[sign] STALL: no output for ${Math.floor(idleMs / 1000)}s (phase=${state.phase}); last file: ${state.lastFile === "" ? "unknown" : state.lastFile}\n`,
+ );
+ writeDiagnostics();
+ }
+
+ function killChildGroup(signal) {
+ const pid = child.pid;
+ if (pid === undefined) return;
+ try {
+ process.kill(-pid, signal);
+ return;
+ } catch {
+ try {
+ child.kill(signal);
+ } catch {
+ // Already gone.
+ }
+ }
+ }
+
+ let finished = false;
+ let tickTimer = null;
+ let timeoutTimer = null;
+ let killTimer = null;
+ let settleTimer = null;
+
+ function writeSummary(exitCode) {
+ const elapsedSeconds = (Date.now() - startedAt) / 1000;
+ const { calls, failures } = readShimState();
+ const durations = calls
+ .map((call) => call.duration)
+ .sort((a, b) => a - b);
+ const totalCodesignSeconds = calls.reduce(
+ (sum, call) => sum + call.duration,
+ 0,
+ );
+ const categories = {
+ sign: { count: 0, seconds: 0 },
+ verify: { count: 0, seconds: 0 },
+ display: { count: 0, seconds: 0 },
+ other: { count: 0, seconds: 0 },
+ };
+ for (const call of calls) {
+ const bucket = categories[call.category];
+ bucket.count += 1;
+ bucket.seconds += call.duration;
+ }
+ const slowest = [...calls]
+ .sort((a, b) => b.duration - a.duration)
+ .slice(0, SLOWEST_LIMIT);
+
+ const lines = [];
+ lines.push(
+ `[sign] summary label=${options.label} exit=${exitCode} elapsed=${seconds(elapsedSeconds)} codesign-calls=${calls.length} codesign-total=${seconds(totalCodesignSeconds)} p50=${seconds(percentile(durations, 50))} p95=${seconds(percentile(durations, 95))} max=${seconds(percentile(durations, 100))}`,
+ );
+ lines.push(
+ `[sign] summary codesign-categories: sign=${categories.sign.count}/${seconds(categories.sign.seconds)} verify=${categories.verify.count}/${seconds(categories.verify.seconds)} display=${categories.display.count}/${seconds(categories.display.seconds)} other=${categories.other.count}/${seconds(categories.other.seconds)}`,
+ );
+ lines.push(
+ `[sign] summary slowest: ${
+ slowest.length === 0
+ ? "<none>"
+ : slowest
+ .map(
+ (call) =>
+ `${truncate(redact(call.target), 160)} ${seconds(call.duration)}`,
+ )
+ .join(" ")
+ }`,
+ );
+ if (failures > 0) {
+ lines.push(
+ `[sign] summary failures: ${failures} codesign calls exited non-zero`,
+ );
+ }
+
+ const output = `${lines.join("\n")}\n`;
+ process.stdout.write(output);
+
+ if (options.summaryFile !== "") {
+ try {
+ writeFileSync(options.summaryFile, output);
+ } catch (error) {
+ process.stderr.write(
+ `[sign] error: cannot write summary file: ${redact(error.message)}\n`,
+ );
+ }
+ }
+
+ const stepSummary = process.env.GITHUB_STEP_SUMMARY;
+ if (typeof stepSummary === "string" && stepSummary !== "") {
+ const markdown = [
+ `## macOS signing: ${options.label}`,
+ "",
+ "| metric | value |",
+ "| --- | --- |",
+ `| exit | ${exitCode} |`,
+ `| elapsed | ${seconds(elapsedSeconds)} |`,
+ `| codesign calls | ${calls.length} |`,
+ `| codesign total | ${seconds(totalCodesignSeconds)} |`,
+ `| codesign p50 | ${seconds(percentile(durations, 50))} |`,
+ `| codesign p95 | ${seconds(percentile(durations, 95))} |`,
+ `| codesign max | ${seconds(percentile(durations, 100))} |`,
+ `| codesign failures | ${failures} |`,
+ `| codesign slowest | ${slowest.length === 0 ? "<none>" : truncate(redact(slowest.map((call) => call.target).join(", ")), 400)} |`,
+ "",
+ ].join("\n");
+ try {
+ appendFileSync(stepSummary, markdown);
+ } catch (error) {
+ process.stderr.write(
+ `[sign] error: cannot append to GITHUB_STEP_SUMMARY: ${redact(error.message)}\n`,
+ );
+ }
+ }
+ }
+
+ function finishOnce(exitCode, signal) {
+ if (finished) return;
+ finished = true;
+ if (tickTimer !== null) clearInterval(tickTimer);
+ if (timeoutTimer !== null) clearTimeout(timeoutTimer);
+ if (killTimer !== null) clearTimeout(killTimer);
+ if (settleTimer !== null) clearTimeout(settleTimer);
+ tickTimer = null;
+ timeoutTimer = null;
+ killTimer = null;
+ settleTimer = null;
+
+ for (const reader of readers) reader.flush();
+
+ let code;
+ if (state.timedOut) {
+ code = 124;
+ } else if (typeof exitCode === "number") {
+ code = exitCode;
+ } else if (typeof signal === "string" && signal !== "") {
+ code = 128 + signalNumber(signal);
+ } else {
+ code = state.spawnError === null ? 1 : 127;
+ }
+
+ writeSummary(code);
+
+ if (shimRoot !== "") {
+ try {
+ rmSync(shimRoot, { recursive: true, force: true });
+ } catch {
+ // Best effort: a leftover temp directory is harmless.
+ }
+ }
+
+ process.exitCode = code;
+ }
+
+ function onTimeout() {
+ if (finished) return;
+ state.timedOut = true;
+ process.stdout.write(
+ `[sign] TIMEOUT after ${options.timeoutSeconds}s (phase=${state.phase}, last file: ${state.lastFile === "" ? "unknown" : state.lastFile})\n`,
+ );
+ // Same diagnostic dump as a stall, so the stuck stage is still on record.
+ writeDiagnostics();
+ killChildGroup("SIGTERM");
+ killTimer = setTimeout(() => {
+ killChildGroup("SIGKILL");
+ settleTimer = setTimeout(() => {
+ child.stdout?.destroy();
+ child.stderr?.destroy();
+ finishOnce(124, null);
+ }, SIGKILL_SETTLE_MS);
+ }, KILL_GRACE_MS);
+ }
+
+ const child = spawn(options.command[0], options.command.slice(1), {
+ env: childEnv,
+ cwd: process.cwd(),
+ stdio: ["ignore", "pipe", "pipe"],
+ // Own process group so a timeout can terminate codesign children too.
+ detached: true,
+ });
+
+ const readers = [
+ child.stdout === null
+ ? null
+ : createLineReader(child.stdout, (line) => handleLine(line, process.stdout)),
+ child.stderr === null
+ ? null
+ : createLineReader(child.stderr, (line) => handleLine(line, process.stderr)),
+ ].filter((reader) => reader !== null);
+
+ tickTimer = setInterval(onTick, tickIntervalMs);
+ timeoutTimer = setTimeout(onTimeout, options.timeoutSeconds * 1000);
+
+ child.on("error", (error) => {
+ state.spawnError = error;
+ process.stderr.write(
+ `[sign] error: cannot start ${redact(options.command[0])}: ${redact(error.message)}\n`,
+ );
+ finishOnce(null, null);
+ });
+
+ child.on("close", (code, signal) => {
+ finishOnce(code, signal);
+ });
+
+ const forwardSignal = (signal) => {
+ killChildGroup(signal);
+ finishOnce(null, signal);
+ };
+ process.on("SIGINT", () => forwardSignal("SIGINT"));
+ process.on("SIGTERM", () => forwardSignal("SIGTERM"));
+}
+
+run();
diff --git a/scripts/release-macos.sh b/scripts/release-macos.sh
index 590ab9539..26e4a8e34 100755
--- a/scripts/release-macos.sh
+++ b/scripts/release-macos.sh
@@ -12,6 +12,15 @@
# APPLE_TEAM_ID Apple Developer Team ID (must be DUV63RKYTW)
# MAC_ARCH optional `arm64` or `x64`; must match the host
#
+# Observability: the packaging command runs under
+# scripts/macos-signing-watchdog.mjs, which enables the per-file signing trace
+# (DEBUG=electron-osx-sign*) and the notarization progress
+# (DEBUG=electron-notarize*), prints a heartbeat while electron-builder is
+# silent, dumps diagnostics when the signing phase stalls, bounds the phase
+# with a hard timeout, and reports per-file codesign timings. The
+# `signing PI-Desktop.app` line electron-builder emits is otherwise the last
+# thing the log shows for minutes, because nested signing, silent full
+# retries, and Apple's notarization queue all happen without output.
# See docs/spec/06-delivery/06-release-runbook.md for the full runbook.
set -euo pipefail
@@ -67,14 +76,35 @@ cargo build -p host-core --release
echo "==> Building workspace packages"
pnpm -r --filter '!@pi-desktop/desktop' build
-echo "==> Building + packaging desktop (signed, $MAC_ARCH)"
+echo "==> Bundling the agent-runtime sidecar"
+pnpm --filter @pi-desktop/agent-runtime bundle
+
+echo "==> Building the desktop bundles"
pnpm --filter @pi-desktop/desktop exec electron-vite build
-pnpm --filter @pi-desktop/desktop exec electron-builder --mac "--${MAC_ARCH}" \
- -c.mac.identity="${MAC_SIGNING_IDENTITY}" \
+
+echo "==> Packaging the desktop (Developer ID signed + notarized, $MAC_ARCH)"
+# `--publish never` keeps a local checkout from publishing to GitHub; the
+# Release workflow owns publication. The watchdog is transparent: it forwards
+# every line, keeps the child's exit code, and only fails on its own timeout.
+# `electron-builder` is intentionally absent from DEBUG: builder-util's
+# `executing` line prints every spawned command with only its own stem list
+# redacted, which leaves `security set-key-partition-list -k <p12 password>`
+# in clear text on a terminal or in a log file.
+DEBUG="${DEBUG:-electron-osx-sign*,electron-notarize*}" \
+ node scripts/macos-signing-watchdog.mjs --label "release-macos-${MAC_ARCH}" -- \
+ pnpm --filter @pi-desktop/desktop exec electron-builder --mac "--${MAC_ARCH}" \
+ --publish never \
+ -c.mac.identity="${MAC_SIGNING_IDENTITY}" \
+ -c.mac.forceCodeSigning=true \
+ -c.mac.notarize=true
+
+echo "==> Analyzing the packaged app bundle"
+node scripts/macos-bundle-inventory.mjs apps/desktop/release
+
+echo "==> Notarizing and stapling the DMG"
scripts/notarize-and-staple-macos-release-dmg.sh apps/desktop/release
-scripts/verify-macos-release.sh apps/desktop/release
-scripts/staple-macos-release-dmg.sh apps/desktop/release
+echo "==> Verifying the signed and notarized release"
scripts/verify-macos-release.sh apps/desktop/release
echo "==> Done. Artifacts in apps/desktop/release/"