Skip to content

A full-featured download manager.

feat(safari): ship signed desktop bootstrap and upgrade registration (#2271)

Dr_rOot0db6923da428
diff --git a/.gitattributes b/.gitattributes
index 1802590a..03f72abb 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -17,3 +17,6 @@ scripts/before-build-use-staged-dependencies.mjs text eol=lf
scripts/native-binary-target.mjs text eol=lf
scripts/release-signing-input.mjs text eol=lf
scripts/verify-electron-package.mjs text eol=lf
+scripts/sign-macos.mjs text eol=lf
+build/entitlements.safari.plist text eol=lf
+build/app.motrix.safari.bootstrap.plist text eol=lf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 00c48d5b..4f4b93e3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -456,6 +456,12 @@ jobs:
src/core/plugin/finalize/finalize-nfs-recovery.integration.test.ts
--reporter=verbose
+ - name: Test and build Safari desktop helpers
+ if: matrix.platform == 'darwin'
+ run: |
+ swift test --package-path packages/safari-bootstrap
+ pnpm run build:safari-bootstrap -- --arch ${{ matrix.arch }} --test
+
# SQLite integration tests above use Node. Switch native modules to the
# packaged Electron ABI only after those tests have finished.
- name: Build Electron application
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index c821d39e..bec4731c 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -255,6 +255,12 @@ jobs:
src/core/plugin/finalize/finalize-smb-recovery.integration.test.ts
--reporter=verbose
+ - name: Test and build Safari desktop helpers
+ if: matrix.platform == 'darwin'
+ run: |
+ swift test --package-path packages/safari-bootstrap
+ pnpm run build:safari-bootstrap -- --arch ${{ matrix.arch }} --test
+
# SQLite integration tests above use Node. Rebuild for Electron before
# staging, so the packaged native dependency retains the correct ABI.
- name: Build Electron application
@@ -891,7 +897,7 @@ jobs:
EXPECTED_COMMIT: ${{ github.sha }}
EXPECTED_PLATFORM: ${{ matrix.platform }}
# Updated only after reviewing the verifier source itself.
- VERIFIER_SHA256: 05d56166dedb2b862fca79659db59ae55bf31b2e761f5a3194482618e0e7a076
+ VERIFIER_SHA256: ac73a236208b8c5d0ca156f558d39812b86d00031f69ac886a50b4b88a5b0fa7
run: |
const crypto = require('node:crypto')
const fs = require('node:fs')
diff --git a/build/app.motrix.safari.bootstrap.plist b/build/app.motrix.safari.bootstrap.plist
new file mode 100644
index 00000000..57a4026d
--- /dev/null
+++ b/build/app.motrix.safari.bootstrap.plist
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+<key>Label</key><string>app.motrix.safari.bootstrap</string>
+<key>BundleProgram</key><string>Contents/Library/LaunchServices/MotrixSafariBootstrap</string>
+<key>MachServices</key><dict>
+<key>7VMB56CA56.app.motrix.shared.bootstrap</key><true/>
+<key>7VMB56CA56.app.motrix.shared.registration</key><true/>
+</dict>
+<key>ProcessType</key><string>Interactive</string>
+</dict></plist>
diff --git a/build/entitlements.safari.plist b/build/entitlements.safari.plist
new file mode 100644
index 00000000..119e9323
--- /dev/null
+++ b/build/entitlements.safari.plist
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+<key>com.apple.security.application-groups</key>
+<array><string>7VMB56CA56.app.motrix.shared</string></array>
+</dict></plist>
diff --git a/electron-builder.json b/electron-builder.json
index 2dfe829c..6f15afbd 100644
--- a/electron-builder.json
+++ b/electron-builder.json
@@ -109,6 +109,21 @@
"extendInfo": {
"NSLocalNetworkUsageDescription": "Motrix uses the local network for UPnP port mapping and discovering download peers."
},
+ "sign": "./scripts/sign-macos.mjs",
+ "extraFiles": [
+ {
+ "from": "packages/safari-bootstrap/dist/darwin-${arch}/MotrixSafariBootstrap",
+ "to": "Library/LaunchServices/MotrixSafariBootstrap"
+ },
+ {
+ "from": "packages/safari-bootstrap/dist/darwin-${arch}/MotrixSafariRegistrar",
+ "to": "MacOS/MotrixSafariRegistrar"
+ },
+ {
+ "from": "build/app.motrix.safari.bootstrap.plist",
+ "to": "Library/LaunchAgents/app.motrix.safari.bootstrap.plist"
+ }
+ ],
"target": ["dmg", "zip"],
"extraResources": [
{ "from": "./extra/aria2.conf", "to": "./extra/aria2.conf" },
diff --git a/electron-builder.signing.json b/electron-builder.signing.json
index cc8d7527..4cc06a36 100644
--- a/electron-builder.signing.json
+++ b/electron-builder.signing.json
@@ -107,6 +107,21 @@
"extendInfo": {
"NSLocalNetworkUsageDescription": "Motrix uses the local network for UPnP port mapping and discovering download peers."
},
+ "sign": "./scripts/sign-macos.mjs",
+ "extraFiles": [
+ {
+ "from": "packages/safari-bootstrap/dist/darwin-${arch}/MotrixSafariBootstrap",
+ "to": "Library/LaunchServices/MotrixSafariBootstrap"
+ },
+ {
+ "from": "packages/safari-bootstrap/dist/darwin-${arch}/MotrixSafariRegistrar",
+ "to": "MacOS/MotrixSafariRegistrar"
+ },
+ {
+ "from": "signing-build-resources/app.motrix.safari.bootstrap.plist",
+ "to": "Library/LaunchAgents/app.motrix.safari.bootstrap.plist"
+ }
+ ],
"target": ["dmg", "zip"],
"extraResources": [
{ "from": "./extra/aria2.conf", "to": "./extra/aria2.conf" },
diff --git a/package.json b/package.json
index d5313caa..20134709 100644
--- a/package.json
+++ b/package.json
@@ -37,7 +37,7 @@
"generate:bridge-vectors": "node scripts/generate-bridge-pairing-vectors.mjs docs/bridge-pairing-protocol-vectors.json",
"package:flatpak-native-host": "node packages/native-host/package-flatpak-companion.mjs",
"build:snap:prepare": "node scripts/prepare-snap-project.mjs",
- "build:mac-arm64": "pnpm run build:builtin && pnpm run build:native-host -- --platform darwin --arch arm64 && pnpm run build:finalize-fs -- --platform darwin --arch arm64 && pnpm run build:electron",
+ "build:mac-arm64": "pnpm run build:builtin && pnpm run build:native-host -- --platform darwin --arch arm64 && pnpm run build:finalize-fs -- --platform darwin --arch arm64 && pnpm run build:safari-bootstrap -- --arch arm64 && pnpm run build:electron",
"prestart:server": "node scripts/ensure-native-abi.mjs node",
"start:server": "MOTRIX_SKIP_ELECTRON_REBUILD=1 node dist/server/index.mjs",
"check:boundaries": "node scripts/check-boundaries.mjs",
@@ -84,7 +84,8 @@
"rebuild:for-electron": "electron-rebuild --force --only better-sqlite3",
"pack:mac": "pnpm run check:third-party-notices && pnpm run build:mac-arm64 && pnpm run stage:electron -- --platform darwin --arch arm64 && CSC_IDENTITY_AUTO_DISCOVERY=false pnpm exec electron-builder --mac --arm64 -c.mac.target=dir && codesign --force --deep --sign - release/mac-arm64/Motrix.app",
"dist:mac": "pnpm run check:third-party-notices && pnpm run build:mac-arm64 && pnpm run stage:electron -- --platform darwin --arch arm64 && CSC_IDENTITY_AUTO_DISCOVERY=false pnpm exec electron-builder --mac --arm64 --publish never",
- "release:mac": "pnpm run check:third-party-notices && pnpm run build:mac-arm64 && pnpm run stage:electron -- --platform darwin --arch arm64 && pnpm exec electron-builder --mac --arm64 --publish never"
+ "release:mac": "pnpm run check:third-party-notices && pnpm run build:mac-arm64 && pnpm run stage:electron -- --platform darwin --arch arm64 && pnpm exec electron-builder --mac --arm64 --publish never",
+ "build:safari-bootstrap": "node packages/safari-bootstrap/build.mjs"
},
"devDependencies": {
"@biomejs/biome": "^2.5.14",
diff --git a/packages/native-host/include/motrix_safari_bootstrap.h b/packages/native-host/include/motrix_safari_bootstrap.h
index 05990277..5ef6ca52 100644
--- a/packages/native-host/include/motrix_safari_bootstrap.h
+++ b/packages/native-host/include/motrix_safari_bootstrap.h
@@ -7,4 +7,14 @@
* A zero return value means invalid buffers or an unavailable response. */
size_t motrix_safari_bootstrap_v1(const uint8_t *request, size_t request_len,
uint8_t *response, size_t response_capacity);
+/* Private desktop result. JSON remains protocol v1. bridge_not_running is 1
+ * only when discovery found no live bridge; nonce refusal is terminal (0).
+ * Invalid buffers return {0, 0}. The v1 buffer safety contract also applies. */
+typedef struct {
+ size_t response_len;
+ uint8_t bridge_not_running;
+} MotrixSafariBootstrapResult;
+MotrixSafariBootstrapResult motrix_safari_bootstrap_v2(
+ const uint8_t *request, size_t request_len,
+ uint8_t *response, size_t response_capacity);
#endif
diff --git a/packages/native-host/src/resolve.rs b/packages/native-host/src/resolve.rs
index 4d8989f5..9ec93f04 100644
--- a/packages/native-host/src/resolve.rs
+++ b/packages/native-host/src/resolve.rs
@@ -92,6 +92,23 @@ pub trait ResolveDeps {
fn sleep(&mut self, duration: Duration);
}
+/// Discovery-only failures retain whether a live bridge refused nonce issuance.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum ProbeError {
+ NotRunning,
+ NonceUnavailable,
+}
+
+pub fn probe_endpoint<D: ResolveDeps>(deps: &mut D) -> Result<ResolvedEndpoint, ProbeError> {
+ let endpoint = deps.read_endpoint().ok_or(ProbeError::NotRunning)?;
+ if !deps.probe_liveness(endpoint.port, PROBE_TIMEOUT) {
+ return Err(ProbeError::NotRunning);
+ }
+ deps.fetch_nonce(endpoint.port, PROBE_TIMEOUT)
+ .map(|nonce| ResolvedEndpoint { endpoint, nonce })
+ .ok_or(ProbeError::NonceUnavailable)
+}
+
/// Resolves the recorded endpoint, launching Motrix first when the caller
/// allows it and the bridge is not already up.
///
@@ -115,13 +132,10 @@ pub fn resolve_endpoint<D: ResolveDeps>(
allow_launch: bool,
deps: &mut D,
) -> Result<ResolvedEndpoint, ResolveError> {
- if let Some(endpoint) = deps.read_endpoint()
- && deps.probe_liveness(endpoint.port, PROBE_TIMEOUT)
- {
- return deps
- .fetch_nonce(endpoint.port, PROBE_TIMEOUT)
- .map(|nonce| ResolvedEndpoint { endpoint, nonce })
- .ok_or(ResolveError::NotRunning);
+ match probe_endpoint(deps) {
+ Ok(resolved) => return Ok(resolved),
+ Err(ProbeError::NonceUnavailable) => return Err(ResolveError::NotRunning),
+ Err(ProbeError::NotRunning) => {}
}
if !allow_launch {
diff --git a/packages/native-host/src/safari_bootstrap.rs b/packages/native-host/src/safari_bootstrap.rs
index a2b87b4d..2046471b 100644
--- a/packages/native-host/src/safari_bootstrap.rs
+++ b/packages/native-host/src/safari_bootstrap.rs
@@ -10,7 +10,9 @@ use serde::Deserialize;
use serde_json::{Value, json};
use crate::canonical::base64url_decode;
-use crate::resolve::{ResolveDeps, ResolveError, ResolveResult, resolve_endpoint};
+use crate::resolve::{
+ ProbeError, ResolveDeps, ResolveError, ResolveResult, probe_endpoint, resolve_endpoint,
+};
use crate::runtime::SystemResolveDeps;
use crate::ticket::{TICKET_LIFETIME_SECONDS, TicketInputs, mint_ticket};
use crate::user_data::{native_host_bridge_data_dir, native_host_user_data_dir};
@@ -31,7 +33,13 @@ fn error(code: &str) -> Value {
json!({"error": code, "protocolVersion": 1})
}
-fn resolve<D: ResolveDeps>(request: &[u8], deps: &mut D, now: Option<u64>) -> Value {
+fn resolve<D: ResolveDeps>(
+ request: &[u8],
+ deps: &mut D,
+ now: Option<u64>,
+ bridge_not_running: &mut bool,
+) -> Value {
+ *bridge_not_running = false;
let Ok(request) = serde_json::from_slice::<Request>(request) else {
return error("invalid-request");
};
@@ -43,11 +51,22 @@ fn resolve<D: ResolveDeps>(request: &[u8], deps: &mut D, now: Option<u64>) -> Va
if request.action != "bootstrap" || request.protocol_version != 1 {
return error("invalid-request");
}
- let resolved = match resolve_endpoint(request.allow_launch, deps) {
- Ok(resolved) => resolved,
- Err(ResolveError::NotRunning) => return error("bootstrap-unavailable"),
- Err(ResolveError::NotInstalled | ResolveError::LaunchFailed) => {
- return error("launch-denied");
+ let resolved = if request.allow_launch {
+ // Preserve the original v1 ABI's explicit launch behavior.
+ match resolve_endpoint(true, deps) {
+ Ok(resolved) => resolved,
+ Err(ResolveError::NotRunning) => return error("bootstrap-unavailable"),
+ Err(ResolveError::NotInstalled | ResolveError::LaunchFailed) => {
+ return error("launch-denied");
+ }
+ }
+ } else {
+ match probe_endpoint(deps) {
+ Ok(resolved) => resolved,
+ Err(reason) => {
+ *bridge_not_running = reason == ProbeError::NotRunning;
+ return error("bootstrap-unavailable");
+ }
}
};
// Missing owner-checked attestation material must never create an identity.
@@ -96,13 +115,38 @@ pub unsafe extern "C" fn motrix_safari_bootstrap_v1(
response: *mut u8,
response_capacity: usize,
) -> usize {
+ // SAFETY: the caller provides the same buffer contract as the v2 entry point.
+ unsafe { motrix_safari_bootstrap_v2(request, request_len, response, response_capacity) }
+ .response_len
+}
+
+/// Private desktop ABI metadata; the JSON/XPC response stays at protocol v1.
+#[repr(C)]
+#[derive(Default)]
+pub struct SafariBootstrapResult {
+ pub response_len: usize,
+ pub bridge_not_running: u8,
+}
+
+/// Resolve one request, preserving whether discovery found no running bridge.
+/// Only that state permits the Swift desktop owner to launch or poll again.
+///
+/// # Safety
+/// The input/output buffers must satisfy the same contract as `motrix_safari_bootstrap_v1`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn motrix_safari_bootstrap_v2(
+ request: *const u8,
+ request_len: usize,
+ response: *mut u8,
+ response_capacity: usize,
+) -> SafariBootstrapResult {
if request.is_null()
|| response.is_null()
|| request_len == 0
|| request_len > MAX_BYTES
|| response_capacity < MAX_BYTES
{
- return 0;
+ return SafariBootstrapResult::default();
}
// SAFETY: the embedding service owns separate, valid buffers per the ABI.
let request = unsafe { std::slice::from_raw_parts(request, request_len) };
@@ -113,16 +157,20 @@ pub unsafe extern "C" fn motrix_safari_bootstrap_v1(
.duration_since(UNIX_EPOCH)
.ok()
.map(|time| time.as_secs());
- let result = resolve(request, &mut deps, now);
+ let mut bridge_not_running = false;
+ let result = resolve(request, &mut deps, now, &mut bridge_not_running);
let Ok(bytes) = serde_json::to_vec(&result) else {
- return 0;
+ return SafariBootstrapResult::default();
};
if bytes.len() > MAX_BYTES {
- return 0;
+ return SafariBootstrapResult::default();
}
// SAFETY: output has sufficient capacity and does not alias the input.
unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), response, bytes.len()) };
- bytes.len()
+ SafariBootstrapResult {
+ response_len: bytes.len(),
+ bridge_not_running: u8::from(bridge_not_running),
+ }
}
#[cfg(test)]
@@ -136,6 +184,7 @@ mod tests {
endpoint: Option<EndpointFile>,
nonce_calls: usize,
launch_calls: usize,
+ nonce_available: bool,
}
impl ResolveDeps for Deps {
fn read_endpoint(&mut self) -> Option<EndpointFile> {
@@ -146,7 +195,7 @@ mod tests {
}
fn fetch_nonce(&mut self, _: u16, _: Duration) -> Option<String> {
self.nonce_calls += 1;
- Some("nonce".into())
+ self.nonce_available.then(|| "nonce".into())
}
fn launch(&mut self) -> bool {
self.launch_calls += 1;
@@ -168,13 +217,41 @@ mod tests {
}),
nonce_calls: 0,
launch_calls: 0,
+ nonce_available: true,
}
}
fn request() -> Value {
json!({"action":"bootstrap", "protocolVersion":1, "bindingPub":base64url_encode(&[7;32]), "allowLaunch":false})
}
fn call(request: Value, deps: &mut Deps) -> Value {
- resolve(&serde_json::to_vec(&request).unwrap(), deps, Some(1000))
+ resolve(
+ &serde_json::to_vec(&request).unwrap(),
+ deps,
+ Some(1000),
+ &mut false,
+ )
+ }
+
+ #[test]
+ fn nonce_refusal_is_terminal_while_missing_bridge_allows_wake() {
+ for missing in [false, true] {
+ let mut deps = deps();
+ deps.nonce_available = false;
+ if missing {
+ deps.endpoint = None;
+ }
+ let mut bridge_not_running = false;
+ let result = resolve(
+ &serde_json::to_vec(&request()).unwrap(),
+ &mut deps,
+ Some(1000),
+ &mut bridge_not_running,
+ );
+ assert_eq!(result, error("bootstrap-unavailable"));
+ assert_eq!(bridge_not_running, missing);
+ assert_eq!(deps.nonce_calls, usize::from(!missing));
+ assert_eq!(deps.launch_calls, 0);
+ }
}
#[test]
diff --git a/packages/safari-bootstrap/.gitignore b/packages/safari-bootstrap/.gitignore
new file mode 100644
index 00000000..803ca219
--- /dev/null
+++ b/packages/safari-bootstrap/.gitignore
@@ -0,0 +1,2 @@
+/.build/
+/dist/
diff --git a/packages/safari-bootstrap/Executables/BootstrapServiceMain.swift b/packages/safari-bootstrap/Executables/BootstrapServiceMain.swift
new file mode 100644
index 00000000..06f69d39
--- /dev/null
+++ b/packages/safari-bootstrap/Executables/BootstrapServiceMain.swift
@@ -0,0 +1,33 @@
+import Foundation
+import os
+
+@main
+enum BootstrapServiceMain {
+ static func main() {
+ let logger = Logger(subsystem: "app.motrix.safari.bootstrap", category: "service")
+ do {
+ // Generated constants are part of this signed executable, never runtime input.
+ let resolver = NativeBootstrapResolver()
+ let desktop = BootstrapDesktopResolver()
+ let configuration = try signedBootstrapConfiguration()
+ let service = try BootstrapIPCService(configuration: configuration) { request in
+ let result = try await desktop.resolve(allowLaunch: request.allowLaunch) {
+ try await resolver.resolve(request)
+ } launch: {
+ try await BootstrapDesktopLauncher.launch(configuration: configuration)
+ }
+ // Neither the request, nonce, ticket nor local token enters diagnostics.
+ logger.notice("Authenticated bootstrap request completed")
+ return result
+ }
+ let registration = try BootstrapRegistrationService(configuration: configuration)
+ registration.activate()
+ service.activate()
+ logger.notice("Signed bootstrap service activated")
+ withExtendedLifetime((service, registration)) { dispatchMain() }
+ } catch {
+ logger.error("Bootstrap service identity validation failed")
+ exit(EXIT_FAILURE)
+ }
+ }
+}
diff --git a/packages/safari-bootstrap/Executables/DesktopBootstrapRegistrar.swift b/packages/safari-bootstrap/Executables/DesktopBootstrapRegistrar.swift
new file mode 100644
index 00000000..b0b00649
--- /dev/null
+++ b/packages/safari-bootstrap/Executables/DesktopBootstrapRegistrar.swift
@@ -0,0 +1,75 @@
+import Foundation
+import Security
+import ServiceManagement
+import os
+
+/// Invoked by the desktop shell from Contents/MacOS, never a web message.
+@main
+enum DesktopBootstrapRegistrar {
+ static func verifyCode(at url: URL, requirement: String) throws {
+ var code: SecStaticCode?
+ guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess,
+ let code,
+ SecStaticCodeCheckValidity(code, [], try BootstrapIPCConfiguration.compileRequirement(requirement)) == errSecSuccess
+ else { throw BootstrapIPCError.untrustedProcess }
+ }
+
+ static func statusName(_ status: SMAppService.Status) -> String {
+ switch status {
+ case .notRegistered: "not-registered"
+ case .enabled: "enabled"
+ case .requiresApproval: "requires-approval"
+ case .notFound: "not-found"
+ @unknown default: "unknown"
+ }
+ }
+
+ static func main() async {
+ let logger = Logger(subsystem: "app.motrix.safari.registration", category: "service-management")
+ do {
+ guard CommandLine.arguments.count == 2,
+ ["--status", "--register", "--unregister"].contains(CommandLine.arguments[1]),
+ Bundle.main.bundleIdentifier == "app.motrix.native"
+ else { throw BootstrapIPCError.invalidRequest }
+ let configuration = try signedBootstrapConfiguration()
+ let registrarConfiguration = try BootstrapIPCConfiguration(
+ teamIdentifier: configuration.teamIdentifier,
+ clientBundleIdentifier: configuration.clientBundleIdentifier,
+ serviceBundleIdentifier: "app.motrix.safari.registration",
+ appGroupIdentifier: configuration.appGroupIdentifier
+ )
+ try registrarConfiguration.validateCurrentService()
+ let bundle = Bundle.main.bundleURL
+ try verifyCode(at: bundle, requirement:
+ "anchor apple generic and certificate leaf[subject.OU] = \"\(configuration.teamIdentifier)\" and identifier \"app.motrix.native\"")
+ try verifyCode(at: bundle.appendingPathComponent("Contents/Library/LaunchServices/MotrixSafariBootstrap"),
+ requirement: configuration.serviceSigningRequirement)
+ let plistName = "app.motrix.safari.bootstrap.plist"
+ let plist = bundle.appendingPathComponent("Contents/Library/LaunchAgents/\(plistName)")
+ guard FileManager.default.fileExists(atPath: plist.path) else { throw BootstrapIPCError.invalidConfiguration }
+ let service = SMAppService.agent(plistName: plistName)
+ var status = statusName(service.status)
+ switch CommandLine.arguments[1] {
+ case "--register":
+ let expected = try BootstrapRegistrationIdentity.expected(at:
+ bundle.appendingPathComponent("Contents/Library/LaunchServices/MotrixSafariBootstrap"))
+ status = try await BootstrapRegistrationReconciler.reconcile(
+ status: { statusName(service.status) },
+ matches: { await BootstrapRegistrationProbe().matches(configuration: configuration, expected: expected) },
+ unregister: { try await service.unregister() },
+ register: { try service.register() }
+ )
+ case "--unregister":
+ if service.status != .notRegistered && service.status != .notFound { try await service.unregister() }
+ status = statusName(service.status)
+ default: break
+ }
+ let result = try JSONSerialization.data(withJSONObject: ["protocolVersion": 1, "status": status])
+ FileHandle.standardOutput.write(result + Data([10]))
+ } catch {
+ logger.error("Bootstrap registration command failed: \((error as NSError).code, privacy: .public)")
+ FileHandle.standardError.write(Data("bootstrap-registration-failed\n".utf8))
+ exit(EXIT_FAILURE)
+ }
+ }
+}
diff --git a/packages/safari-bootstrap/Native/NativeBootstrapResolver.swift b/packages/safari-bootstrap/Native/NativeBootstrapResolver.swift
new file mode 100644
index 00000000..4203040e
--- /dev/null
+++ b/packages/safari-bootstrap/Native/NativeBootstrapResolver.swift
@@ -0,0 +1,34 @@
+import Foundation
+
+/// The C ABI is linked statically; no subprocess, argv identity, or dynamic library is accepted.
+actor NativeBootstrapResolver {
+ private let queue = DispatchQueue(label: "app.motrix.safari.rust-bootstrap")
+
+ func resolve(_ request: BootstrapIPCRequest) async throws -> BootstrapDesktopProbe {
+ try Task.checkCancellation()
+ let input = try JSONSerialization.data(withJSONObject: [
+ "action": "bootstrap", "protocolVersion": 1,
+ "bindingPub": request.bindingPublicKey, "allowLaunch": false,
+ ])
+ return await withCheckedContinuation { continuation in
+ queue.async {
+ var output = [UInt8](repeating: 0, count: 16 * 1024)
+ let written = input.withUnsafeBytes { inputBuffer in
+ output.withUnsafeMutableBufferPointer { outputBuffer in
+ motrix_safari_bootstrap_v2(
+ inputBuffer.bindMemory(to: UInt8.self).baseAddress, inputBuffer.count,
+ outputBuffer.baseAddress, outputBuffer.count
+ )
+ }
+ }
+ guard written.response_len > 0, written.response_len <= output.count else {
+ continuation.resume(returning: .response(BootstrapIPCCodec.unavailable))
+ return
+ }
+ let result: BootstrapDesktopProbe = written.bridge_not_running == 1
+ ? .notRunning : .response(Data(output.prefix(written.response_len)))
+ continuation.resume(returning: result)
+ }
+ }
+ }
+}
diff --git a/packages/safari-bootstrap/Package.swift b/packages/safari-bootstrap/Package.swift
new file mode 100644
index 00000000..71ee0c4c
--- /dev/null
+++ b/packages/safari-bootstrap/Package.swift
@@ -0,0 +1,12 @@
+// swift-tools-version: 6.0
+import PackageDescription
+
+let package = Package(
+ name: "MotrixSafariBootstrap",
+ platforms: [.macOS(.v13)],
+ products: [.library(name: "SafariNativeIPC", targets: ["SafariNativeIPC"])],
+ targets: [
+ .target(name: "SafariNativeIPC"),
+ .testTarget(name: "SafariNativeIPCTests", dependencies: ["SafariNativeIPC"]),
+ ]
+)
diff --git a/packages/safari-bootstrap/README.md b/packages/safari-bootstrap/README.md
new file mode 100644
index 00000000..f1989edb
--- /dev/null
+++ b/packages/safari-bootstrap/README.md
@@ -0,0 +1,99 @@
+# Safari desktop bootstrap
+
+This package belongs to **Motrix.app**, not the independently distributed Safari
+extension container. Its original IPC implementation comes from
+[motrix-extension](https://github.com/motrixapp/motrix-extension/tree/4dc7d53abc048705a2edcebe2b327ec7b713032f/native/safari)
+(MIT, Copyright 2026-present Dr_rOot). The desktop owns this implementation and
+its release cadence; the existing Safari bootstrap wire interface remains v1.
+
+## Build and distribution
+
+On macOS with Xcode and the matching Rust target installed:
+
+```sh
+pnpm run build:safari-bootstrap -- --arch arm64 --test
+pnpm run build:safari-bootstrap -- --arch x64
+swift test --package-path packages/safari-bootstrap
+```
+
+Builds need no certificate or adjacent checkout. They produce two unsigned
+executables in `dist/darwin-<arch>/`. Electron Builder embeds them at:
+
+- `Contents/Library/LaunchServices/MotrixSafariBootstrap`
+- `Contents/MacOS/MotrixSafariRegistrar`
+- `Contents/Library/LaunchAgents/app.motrix.safari.bootstrap.plist`
+
+The existing CI and release macOS matrices build each architecture separately.
+`--test` runs eight loopback integration cases on the runner's native architecture,
+linking the production Swift adapter and Rust library. These cover successful,
+rate-limited (429), unavailable (503), cold-start and passive discovery paths.
+The private v2 C ABI preserves whether discovery found a running bridge; a live
+bridge refusing a nonce terminates the request without wake-up or retry. The
+existing v1 ABI and extension-facing JSON/XPC protocol remain compatible.
+The isolated signing job receives binaries as data and hash-pinned signing
+policy, not Swift/Rust source or a build hook. `scripts/sign-macos.mjs` runs with
+the existing pinned Electron Builder dependency closure and Developer ID
+certificate. Only the two exact helper paths receive the App Group entitlement;
+Electron retains its existing per-file signing policy. Signing checks the fixed
+Team, identifiers and exact helper entitlements before the complete app enters
+the existing notarization, stapling, DMG/ZIP and updater publication gates.
+
+`configuration.json`, the two build plists, and the signing policy pin the
+production Team and group. The group uses macOS's Team-prefixed convention;
+there is no new CI secret or private provisioning profile in this package.
+See Apple's [app group guidance](https://developer.apple.com/documentation/xcode/accessing-app-group-containers).
+Changing the Team requires coordinated changes to the independently signed
+Safari extension and these reviewed distribution inputs.
+
+## Registration and upgrades
+
+The packaged desktop verifies its own signature and same-Team registrar before
+invoking `--register`. The registrar verifies the bundled helper, then asks the
+running service for its signed executable location and code-directory hash over
+a separate, read-only `.registration` Mach endpoint. This endpoint accepts only
+the same-user, same-Team signed registrar with the expected App Group. The
+Safari `.bootstrap` endpoint retains its extension-only identity requirement.
+Neither interface accepts an application path supplied by JavaScript.
+
+A matching service is left running, including during a Safari cold launch.
+An absent, unresponsive or mismatched service is reconciled through
+`SMAppService`: unregister the old registration when enabled, register the
+current bundle, then verify its running identity. At most two registration
+cycles bound recovery attempts. Registration failures are reported as failures,
+not `enabled`.
+`requires-approval` is preserved; the app never overrides the user's disabled
+background-item choice. `--status` reports the OS registration state only;
+`--register` additionally verifies the owner. `--unregister` removes this service
+without deleting an app or its user data.
+
+Every changed signed build must use a fresh `CFBundleVersion`. Both the unsigned
+build and isolated signing jobs already use `github.run_number.github.run_attempt.0`.
+In migration testing, macOS retained the old launch constraint when Development
+and Developer ID copies reused a build number; retries alone did not repair it.
+Using a new build number allowed the new signed copy to take ownership. Local
+signed rebuilds must also advance their build number.
+
+After installing/updating, open the intended Motrix.app once. This is what
+establishes ownership on the user's Mac; CI cannot register a service for that
+user. Explicitly launching another signed copy can intentionally change the
+registered owner. Merely downloading a new app does not update registration.
+The helper launches only its verified containing desktop bundle, and pairing
+still requires MBP1 authentication against the discovered running instance.
+
+## Release acceptance
+
+CI checks Swift IPC/registration policy, both architectures, embedded locations,
+fixed LaunchAgent contents, signing-input tampering and finalized package layout.
+Before promotion, verify on a real Mac:
+
+1. Install and launch the signed build, and approve the background item if macOS
+ requests it. Query its registrar and confirm registration succeeds.
+2. Quit Motrix, request connection in Safari, and verify the current installed
+ app starts, the engine is ready, and engine diagnostics run.
+3. Upgrade an already registered build, then repeat cold launch and paired
+ reconnection. Cover relocation and migration from a Development-signed copy.
+4. Disable the background item and confirm launching Motrix does not silently
+ re-enable it. Re-enable it explicitly before continuing testing.
+
+Never delete the database or pairing credentials to repair an old launch target.
+Unsigned/ad-hoc development builds cannot establish this production trust chain.
diff --git a/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapDesktopLauncher.swift b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapDesktopLauncher.swift
new file mode 100644
index 00000000..f21f9d02
--- /dev/null
+++ b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapDesktopLauncher.swift
@@ -0,0 +1,98 @@
+import AppKit
+import Foundation
+import Security
+
+/// Launch only the verified desktop bundle containing this running service.
+enum BootstrapDesktopLauncher {
+ static func containingDesktop(executable: URL) throws -> URL {
+ let service = executable.resolvingSymlinksInPath()
+ let services = service.deletingLastPathComponent()
+ let library = services.deletingLastPathComponent()
+ let contents = library.deletingLastPathComponent()
+ let app = contents.deletingLastPathComponent()
+ guard service.lastPathComponent == "MotrixSafariBootstrap",
+ services.lastPathComponent == "LaunchServices",
+ library.lastPathComponent == "Library",
+ contents.lastPathComponent == "Contents",
+ app.pathExtension == "app"
+ else { throw BootstrapIPCError.untrustedProcess }
+ return app
+ }
+
+ @MainActor
+ static func launch(configuration: BootstrapIPCConfiguration) async throws {
+ try Task.checkCancellation()
+ try configuration.validateCurrentService()
+ var current: SecCode?
+ var currentStatic: SecStaticCode?
+ var information: CFDictionary?
+ guard SecCodeCopySelf([], &current) == errSecSuccess, let current,
+ SecCodeCopyStaticCode(current, [], &currentStatic) == errSecSuccess, let currentStatic,
+ SecCodeCopySigningInformation(currentStatic, [], &information) == errSecSuccess,
+ let dictionary = information as? [String: Any],
+ let executable = dictionary[kSecCodeInfoMainExecutable as String] as? URL
+ else { throw BootstrapIPCError.untrustedProcess }
+ let app = try containingDesktop(executable: executable)
+ let requirement = try BootstrapIPCConfiguration.compileRequirement(
+ "anchor apple generic and certificate leaf[subject.OU] = \"\(configuration.teamIdentifier)\" and identifier \"app.motrix.native\""
+ )
+ var code: SecStaticCode?
+ guard SecStaticCodeCreateWithPath(app as CFURL, [], &code) == errSecSuccess,
+ let code, SecStaticCodeCheckValidity(code, [], requirement) == errSecSuccess
+ else { throw BootstrapIPCError.untrustedProcess }
+ try Task.checkCancellation()
+ let options = NSWorkspace.OpenConfiguration()
+ options.activates = false
+ _ = try await NSWorkspace.shared.openApplication(at: app, configuration: options)
+ }
+}
+
+/// Private classification from the Rust ABI; never added to the extension's wire response.
+enum BootstrapDesktopProbe: Sendable {
+ case notRunning
+ case response(Data)
+
+ var response: Data {
+ switch self {
+ case .notRunning: BootstrapIPCCodec.unavailable
+ case .response(let data): data
+ }
+ }
+}
+
+/// Keep the native Rust resolver discovery-only; the signed host owns wake-up.
+actor BootstrapDesktopResolver {
+ private var busy = false
+ private let timeout: Duration
+ private let interval: Duration
+
+ init(timeout: Duration = .seconds(10), interval: Duration = .milliseconds(250)) {
+ self.timeout = timeout
+ self.interval = interval
+ }
+
+ func resolve(
+ allowLaunch: Bool,
+ probe: @Sendable () async throws -> BootstrapDesktopProbe,
+ launch: @Sendable () async throws -> Void
+ ) async throws -> Data {
+ guard !busy else { return BootstrapIPCCodec.unavailable }
+ try Task.checkCancellation()
+ busy = true
+ defer { busy = false }
+ let result = try await probe()
+ guard allowLaunch, case .notRunning = result else { return result.response }
+ try Task.checkCancellation()
+ do { try await launch() }
+ catch is CancellationError { throw CancellationError() }
+ catch { return Data("{\"error\":\"launch-denied\",\"protocolVersion\":1}".utf8) }
+ let deadline = ContinuousClock.now.advanced(by: timeout)
+ repeat {
+ try Task.checkCancellation()
+ let response = try await probe()
+ if case .response(let data) = response { return data }
+ try await Task.sleep(for: interval)
+ } while ContinuousClock.now < deadline
+ return BootstrapIPCCodec.unavailable
+ }
+}
diff --git a/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapIPCClient.swift b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapIPCClient.swift
new file mode 100644
index 00000000..e88bc6ac
--- /dev/null
+++ b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapIPCClient.swift
@@ -0,0 +1,155 @@
+import Foundation
+
+/// Keep this interface small: Foundation permits only the declared Data values on the wire.
+@objc(MotrixSafariBootstrapIPC)
+protocol BootstrapIPCRemote {
+ func authenticate(reply: @escaping @Sendable () -> Void)
+ func bootstrap(_ request: Data, reply: @escaping @Sendable (Data) -> Void)
+}
+
+public struct BootstrapIPCClient: Sendable {
+ private let makeConnection: @Sendable () -> NSXPCConnection
+ private let serviceRequirement: String
+ private let timeout: TimeInterval
+
+ public init(configuration: BootstrapIPCConfiguration, timeout: TimeInterval = 18) throws {
+ try Self.validateTimeout(timeout)
+ try configuration.validateCurrentClient()
+ let serviceName = configuration.machServiceName
+ makeConnection = { NSXPCConnection(machServiceName: serviceName) }
+ serviceRequirement = configuration.serviceSigningRequirement
+ self.timeout = timeout
+ }
+
+ /// Every call uses a fresh connection and invalidates it on every terminal path.
+ public func bootstrap(_ data: Data) async throws -> Data {
+ let request = try BootstrapIPCRequest(data: data)
+ let operation = BootstrapIPCOperation(
+ connection: makeConnection(), requirement: serviceRequirement,
+ requestData: data, request: request, timeout: timeout
+ )
+ return try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { operation.start($0) }
+ } onCancel: {
+ operation.cancel()
+ }
+ }
+
+ static func validateTimeout(_ timeout: TimeInterval) throws {
+ guard timeout.isFinite, timeout > 0, timeout <= 20 else {
+ throw BootstrapIPCError.invalidConfiguration
+ }
+ }
+
+ #if DEBUG
+ /// Available only to @testable clients of debug builds, never a production configuration switch.
+ init(testEndpoint: NSXPCListenerEndpoint, serviceRequirement: String, timeout: TimeInterval) throws {
+ try Self.validateTimeout(timeout)
+ _ = try BootstrapIPCConfiguration.compileRequirement(serviceRequirement)
+ let endpoint = TestEndpoint(value: testEndpoint)
+ makeConnection = { NSXPCConnection(listenerEndpoint: endpoint.value) }
+ self.serviceRequirement = serviceRequirement
+ self.timeout = timeout
+ }
+
+ private struct TestEndpoint: @unchecked Sendable {
+ let value: NSXPCListenerEndpoint
+ }
+ #endif
+}
+
+/// All completion paths share one serial queue, including cancellation before start.
+private final class BootstrapIPCOperation: @unchecked Sendable {
+ private let queue = DispatchQueue(label: "app.motrix.safari.bootstrap-request")
+ private var connection: NSXPCConnection?
+ private var proxy: (any BootstrapIPCRemote)?
+ private let requirement: String
+ private let requestData: Data
+ private let request: BootstrapIPCRequest
+ private let timeout: TimeInterval
+ private var continuation: CheckedContinuation<Data, any Error>?
+ private var result: Result<Data, BootstrapIPCError>?
+ private var timer: DispatchSourceTimer?
+ private var sentBootstrap = false
+
+ init(connection: NSXPCConnection, requirement: String, requestData: Data,
+ request: BootstrapIPCRequest, timeout: TimeInterval) {
+ self.connection = connection
+ self.requirement = requirement
+ self.requestData = requestData
+ self.request = request
+ self.timeout = timeout
+ }
+
+ func start(_ continuation: CheckedContinuation<Data, any Error>) {
+ queue.async { [self] in
+ if let result {
+ continuation.resume(with: result.mapError { $0 as any Error })
+ return
+ }
+ self.continuation = continuation
+ guard let connection else {
+ finish(.failure(.unavailable))
+ return
+ }
+ connection.remoteObjectInterface = NSXPCInterface(with: BootstrapIPCRemote.self)
+ connection.setCodeSigningRequirement(requirement)
+ connection.interruptionHandler = { [weak self] in self?.complete(.failure(.unavailable)) }
+ connection.invalidationHandler = { [weak self] in self?.complete(.failure(.unavailable)) }
+ let timer = DispatchSource.makeTimerSource(queue: queue)
+ timer.schedule(deadline: .now() + timeout)
+ timer.setEventHandler { [weak self] in self?.finish(.failure(.timedOut)) }
+ self.timer = timer
+ timer.resume()
+ connection.resume()
+ guard let proxy = connection.remoteObjectProxyWithErrorHandler({ [weak self] _ in
+ self?.complete(.failure(.unavailable))
+ }) as? BootstrapIPCRemote else {
+ finish(.failure(.unavailable))
+ return
+ }
+ self.proxy = proxy
+ // Foundation checks incoming messages, not the first outgoing request.
+ // Authenticate an empty reply before sending even a public binding key.
+ proxy.authenticate { [weak self] in self?.authenticated() }
+ }
+ }
+
+ private func authenticated() {
+ queue.async { [self] in
+ guard result == nil, !sentBootstrap, let proxy else { return }
+ sentBootstrap = true
+ proxy.bootstrap(requestData) { [weak self] response in
+ guard let self else { return }
+ do {
+ try BootstrapIPCCodec.validateResponse(response, for: request)
+ complete(.success(response))
+ } catch {
+ complete(.failure(.invalidResponse))
+ }
+ }
+ }
+ }
+
+ func cancel() { complete(.failure(.cancelled)) }
+
+ private func complete(_ result: Result<Data, BootstrapIPCError>) {
+ queue.async { [self] in finish(result) }
+ }
+
+ private func finish(_ result: Result<Data, BootstrapIPCError>) {
+ guard self.result == nil else { return }
+ self.result = result
+ timer?.setEventHandler {}
+ timer?.cancel()
+ timer = nil
+ proxy = nil
+ connection?.interruptionHandler = nil
+ connection?.invalidationHandler = nil
+ connection?.invalidate()
+ connection = nil
+ let continuation = self.continuation
+ self.continuation = nil
+ continuation?.resume(with: result.mapError { $0 as any Error })
+ }
+}
diff --git a/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapIPCCodec.swift b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapIPCCodec.swift
new file mode 100644
index 00000000..5a775b99
--- /dev/null
+++ b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapIPCCodec.swift
@@ -0,0 +1,95 @@
+import Foundation
+
+/// A resolver receives only a validated bootstrap request, without a claimed identity.
+public struct BootstrapIPCRequest: Sendable, Equatable {
+ public let bindingPublicKey: String
+ public let allowLaunch: Bool
+
+ public init(data: Data) throws {
+ let object = try BootstrapIPCCodec.object(data, response: false)
+ guard Set(object.keys) == ["action", "protocolVersion", "bindingPub", "allowLaunch"],
+ object["action"] as? String == "bootstrap",
+ BootstrapIPCCodec.integer(object["protocolVersion"], in: 1...1),
+ let key = object["bindingPub"] as? String,
+ BootstrapIPCCodec.isCanonicalKey(key),
+ let launch = object["allowLaunch"] as? NSNumber,
+ CFGetTypeID(launch) == CFBooleanGetTypeID()
+ else { throw BootstrapIPCError.invalidRequest }
+ bindingPublicKey = key
+ allowLaunch = launch.boolValue
+ }
+}
+
+/// The service and client independently enforce the same bounded wire contract.
+enum BootstrapIPCCodec {
+ static let maximumMessageBytes = 16 * 1024
+ static let unavailable = Data("{\"error\":\"bootstrap-unavailable\",\"protocolVersion\":1}".utf8)
+ static let invalidRequest = Data("{\"error\":\"invalid-request\",\"protocolVersion\":1}".utf8)
+ static let timeout = Data("{\"error\":\"ipc-timeout\",\"protocolVersion\":1}".utf8)
+ static let invalidResponse = Data("{\"error\":\"invalid-response\",\"protocolVersion\":1}".utf8)
+
+ static func validateResponse(_ data: Data, for request: BootstrapIPCRequest) throws {
+ let object = try object(data, response: true)
+ if Set(object.keys) == ["error", "protocolVersion"] {
+ guard integer(object["protocolVersion"], in: 1...1),
+ let error = object["error"] as? String,
+ ["bootstrap-unavailable", "invalid-request", "message-too-large", "ipc-timeout",
+ "ipc-unavailable", "invalid-response", "launch-denied"].contains(error)
+ else { throw BootstrapIPCError.invalidResponse }
+ return
+ }
+ let required: Set<String> = ["action", "protocolVersion", "port", "nonce"]
+ guard Set(object.keys) == required || Set(object.keys) == required.union(["nmTicket"]),
+ object["action"] as? String == "requestPair",
+ integer(object["protocolVersion"], in: 1...1),
+ integer(object["port"], in: 1...65535),
+ object["nonce"] is NSNull || boundedASCII(object["nonce"], maximum: 512)
+ else { throw BootstrapIPCError.invalidResponse }
+ if let ticket = object["nmTicket"] {
+ guard let ticket = ticket as? [String: Any],
+ Set(ticket.keys) == ["v", "purpose", "protocolVersion", "serverGeneration", "browser",
+ "callerId", "exp", "bindingPub", "mac"],
+ integer(ticket["v"], in: 1...1),
+ ticket["purpose"] as? String == "mbp1-attestation",
+ integer(ticket["protocolVersion"], in: 1...1),
+ boundedASCII(ticket["serverGeneration"], maximum: 256),
+ ticket["browser"] as? String == "safari",
+ boundedASCII(ticket["callerId"], maximum: 255),
+ integer(ticket["exp"], in: 0...9007199254740991),
+ ticket["bindingPub"] as? String == request.bindingPublicKey,
+ let mac = ticket["mac"] as? String, isCanonicalKey(mac)
+ else { throw BootstrapIPCError.invalidResponse }
+ }
+ }
+
+ static func object(_ data: Data, response: Bool) throws -> [String: Any] {
+ guard data.count <= maximumMessageBytes else { throw BootstrapIPCError.messageTooLarge }
+ guard let object = try? JSONSerialization.jsonObject(with: data),
+ let dictionary = object as? [String: Any]
+ else { throw response ? BootstrapIPCError.invalidResponse : BootstrapIPCError.invalidRequest }
+ return dictionary
+ }
+
+ static func integer(_ value: Any?, in range: ClosedRange<Double>) -> Bool {
+ guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else { return false }
+ let value = number.doubleValue
+ return value.isFinite && value.rounded(.towardZero) == value && range.contains(value)
+ }
+
+ private static func boundedASCII(_ value: Any?, maximum: Int) -> Bool {
+ guard let text = value as? String, !text.isEmpty, text.utf8.count <= maximum else { return false }
+ return text.utf8.allSatisfy { (32...126).contains($0) }
+ }
+
+ static func isCanonicalKey(_ value: String) -> Bool {
+ guard value.utf8.count == 43,
+ value.utf8.allSatisfy({ (65...90).contains($0) || (97...122).contains($0)
+ || (48...57).contains($0) || $0 == 45 || $0 == 95 })
+ else { return false }
+ let padded = value.replacingOccurrences(of: "-", with: "+")
+ .replacingOccurrences(of: "_", with: "/") + "="
+ guard let bytes = Data(base64Encoded: padded), bytes.count == 32 else { return false }
+ return bytes.base64EncodedString().replacingOccurrences(of: "+", with: "-")
+ .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") == value
+ }
+}
diff --git a/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapIPCConfiguration.swift b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapIPCConfiguration.swift
new file mode 100644
index 00000000..291b184d
--- /dev/null
+++ b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapIPCConfiguration.swift
@@ -0,0 +1,101 @@
+import Foundation
+import Security
+
+public enum BootstrapIPCError: Error, Sendable, Equatable {
+ case invalidConfiguration
+ case untrustedProcess
+ case invalidRequest
+ case messageTooLarge
+ case invalidResponse
+ case unavailable
+ case timedOut
+ case cancelled
+}
+
+/// Production identity is explicit; there is no unsigned or bundle-ID-only mode.
+public struct BootstrapIPCConfiguration: Sendable {
+ public let teamIdentifier: String
+ public let clientBundleIdentifier: String
+ public let serviceBundleIdentifier: String
+ public let appGroupIdentifier: String
+ public let machServiceName: String
+ public let clientSigningRequirement: String
+ public let serviceSigningRequirement: String
+
+ public init(
+ teamIdentifier: String,
+ clientBundleIdentifier: String,
+ serviceBundleIdentifier: String,
+ appGroupIdentifier: String
+ ) throws {
+ guard teamIdentifier.utf8.count == 10,
+ teamIdentifier.utf8.allSatisfy({ (65...90).contains($0) || (48...57).contains($0) }),
+ Self.isBundleIdentifier(clientBundleIdentifier),
+ Self.isBundleIdentifier(serviceBundleIdentifier),
+ appGroupIdentifier.hasPrefix(teamIdentifier + "."),
+ Self.isBundleIdentifier(String(appGroupIdentifier.dropFirst(11))),
+ (appGroupIdentifier + ".bootstrap").utf8.count <= 127
+ else { throw BootstrapIPCError.invalidConfiguration }
+
+ let clientRequirement = Self.requirement(team: teamIdentifier, identifier: clientBundleIdentifier, group: appGroupIdentifier)
+ let serviceRequirement = Self.requirement(team: teamIdentifier, identifier: serviceBundleIdentifier, group: appGroupIdentifier)
+ _ = try Self.compileRequirement(clientRequirement)
+ _ = try Self.compileRequirement(serviceRequirement)
+ self.teamIdentifier = teamIdentifier
+ self.clientBundleIdentifier = clientBundleIdentifier
+ self.serviceBundleIdentifier = serviceBundleIdentifier
+ self.appGroupIdentifier = appGroupIdentifier
+ machServiceName = appGroupIdentifier + ".bootstrap"
+ clientSigningRequirement = clientRequirement
+ serviceSigningRequirement = serviceRequirement
+ }
+
+ /// Checks the running process, never a mutable executable path supplied by a caller.
+ public func validateCurrentClient() throws {
+ try validateCurrentProcess(requirement: clientSigningRequirement)
+ }
+
+ public func validateCurrentService() throws {
+ try validateCurrentProcess(requirement: serviceSigningRequirement)
+ }
+
+ private func validateCurrentProcess(requirement: String) throws {
+ var currentCode: SecCode?
+ guard SecCodeCopySelf([], &currentCode) == errSecSuccess,
+ let currentCode,
+ SecCodeCheckValidity(currentCode, [], try Self.compileRequirement(requirement)) == errSecSuccess,
+ let task = SecTaskCreateFromSelf(nil),
+ let groups = SecTaskCopyValueForEntitlement(
+ task, "com.apple.security.application-groups" as CFString, nil
+ ) as? [String], groups.contains(appGroupIdentifier)
+ else { throw BootstrapIPCError.untrustedProcess }
+ }
+
+ static func compileRequirement(_ string: String) throws -> SecRequirement {
+ var requirement: SecRequirement?
+ guard SecRequirementCreateWithString(string as CFString, [], &requirement) == errSecSuccess,
+ let requirement
+ else { throw BootstrapIPCError.invalidConfiguration }
+ return requirement
+ }
+
+ private static func requirement(team: String, identifier: String, group: String) -> String {
+ "anchor apple generic and certificate leaf[subject.OU] = \"\(team)\" and identifier \"\(identifier)\""
+ + " and entitlement[\"com.apple.security.application-groups\"] = \"\(group)\""
+ }
+
+ private static func isBundleIdentifier(_ value: String) -> Bool {
+ guard value.utf8.count <= 255 else { return false }
+ let components = value.split(separator: ".", omittingEmptySubsequences: false)
+ return components.count >= 2 && components.allSatisfy { component in
+ guard let first = component.utf8.first,
+ isAlphaNumeric(first), let last = component.utf8.last, isAlphaNumeric(last)
+ else { return false }
+ return component.utf8.allSatisfy { isAlphaNumeric($0) || $0 == 45 }
+ }
+ }
+
+ private static func isAlphaNumeric(_ byte: UInt8) -> Bool {
+ (65...90).contains(byte) || (97...122).contains(byte) || (48...57).contains(byte)
+ }
+}
diff --git a/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapIPCService.swift b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapIPCService.swift
new file mode 100644
index 00000000..827f91d5
--- /dev/null
+++ b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapIPCService.swift
@@ -0,0 +1,174 @@
+import Foundation
+
+/// Implemented by the signed native host. No resolver, launch behavior, or endpoint access is implicit.
+public typealias BootstrapIPCResolver = @Sendable (BootstrapIPCRequest) async throws -> Data
+
+public final class BootstrapIPCService: NSObject, NSXPCListenerDelegate, @unchecked Sendable {
+ private let listener: NSXPCListener
+ private let resolver: BootstrapIPCResolver
+ private let timeout: TimeInterval
+ private let expectedUserID: uid_t
+ private let lock = NSLock()
+ private var connections: [UUID: NSXPCConnection] = [:]
+ private var stopped = false
+
+ public init(
+ configuration: BootstrapIPCConfiguration,
+ timeout: TimeInterval = 18,
+ resolver: BootstrapIPCResolver? = nil
+ ) throws {
+ try BootstrapIPCClient.validateTimeout(timeout)
+ try configuration.validateCurrentService()
+ listener = NSXPCListener(machServiceName: configuration.machServiceName)
+ self.resolver = resolver ?? { _ in BootstrapIPCCodec.unavailable }
+ self.timeout = timeout
+ expectedUserID = geteuid()
+ super.init()
+ listener.setConnectionCodeSigningRequirement(configuration.clientSigningRequirement)
+ listener.delegate = self
+ }
+
+ public func activate() {
+ lock.lock()
+ defer { lock.unlock() }
+ guard !stopped else { return }
+ listener.activate()
+ }
+
+ /// Call when the native host exits; outstanding clients receive invalidation.
+ public func invalidate() {
+ lock.lock()
+ stopped = true
+ let active = Array(connections.values)
+ connections.removeAll()
+ lock.unlock()
+ listener.invalidate()
+ active.forEach { $0.invalidate() }
+ }
+
+ deinit { invalidate() }
+
+ public func listener(_ listener: NSXPCListener, shouldAcceptNewConnection connection: NSXPCConnection) -> Bool {
+ guard listener === self.listener, connection.effectiveUserIdentifier == expectedUserID else { return false }
+ lock.lock()
+ defer { lock.unlock() }
+ guard !stopped else { return false }
+ let id = UUID()
+ let session = BootstrapIPCSession(resolver: resolver, timeout: timeout)
+ connection.exportedInterface = NSXPCInterface(with: BootstrapIPCRemote.self)
+ connection.exportedObject = session
+ connection.invalidationHandler = { [weak self, session] in
+ session.cancel()
+ self?.removeConnection(id)
+ }
+ connection.interruptionHandler = { [weak connection, session] in
+ session.cancel()
+ connection?.invalidate()
+ }
+ connections[id] = connection
+ connection.resume()
+ return true
+ }
+
+ private func removeConnection(_ id: UUID) {
+ lock.lock()
+ connections.removeValue(forKey: id)
+ lock.unlock()
+ }
+
+ #if DEBUG
+ init(testClientRequirement: String, expectedUserID: uid_t = geteuid(), timeout: TimeInterval = 1,
+ resolver: @escaping BootstrapIPCResolver = { _ in BootstrapIPCCodec.unavailable }) throws {
+ try BootstrapIPCClient.validateTimeout(timeout)
+ _ = try BootstrapIPCConfiguration.compileRequirement(testClientRequirement)
+ listener = NSXPCListener.anonymous()
+ self.resolver = resolver
+ self.timeout = timeout
+ self.expectedUserID = expectedUserID
+ super.init()
+ listener.setConnectionCodeSigningRequirement(testClientRequirement)
+ listener.delegate = self
+ }
+
+ var testEndpoint: NSXPCListenerEndpoint { listener.endpoint }
+
+ var testActiveConnectionCount: Int {
+ lock.lock()
+ defer { lock.unlock() }
+ return connections.count
+ }
+ #endif
+}
+
+/// A connection is deliberately single-use, matching the bootstrap handoff lifecycle.
+private final class BootstrapIPCSession: NSObject, BootstrapIPCRemote, @unchecked Sendable {
+ private let resolver: BootstrapIPCResolver
+ private let timeout: TimeInterval
+ private let queue = DispatchQueue(label: "app.motrix.safari.bootstrap-session")
+ private var used = false
+ private var completed = false
+ private var reply: (@Sendable (Data) -> Void)?
+ private var task: Task<Void, Never>?
+ private var timer: DispatchSourceTimer?
+
+ init(resolver: @escaping BootstrapIPCResolver, timeout: TimeInterval) {
+ self.resolver = resolver
+ self.timeout = timeout
+ }
+
+ func authenticate(reply: @escaping @Sendable () -> Void) {
+ reply()
+ }
+
+ func bootstrap(_ data: Data, reply: @escaping @Sendable (Data) -> Void) {
+ queue.async { [self] in
+ guard !used, !completed else {
+ reply(BootstrapIPCCodec.invalidRequest)
+ return
+ }
+ used = true
+ self.reply = reply
+ let request: BootstrapIPCRequest
+ do { request = try BootstrapIPCRequest(data: data) }
+ catch {
+ finish(BootstrapIPCCodec.invalidRequest)
+ return
+ }
+ let timer = DispatchSource.makeTimerSource(queue: queue)
+ timer.schedule(deadline: .now() + timeout)
+ timer.setEventHandler { [weak self] in self?.finish(BootstrapIPCCodec.timeout) }
+ self.timer = timer
+ timer.resume()
+ task = Task { [weak self, resolver] in
+ let response: Data
+ do {
+ let result = try await resolver(request)
+ do {
+ try BootstrapIPCCodec.validateResponse(result, for: request)
+ response = result
+ } catch { response = BootstrapIPCCodec.invalidResponse }
+ } catch { response = BootstrapIPCCodec.unavailable }
+ self?.complete(response)
+ }
+ }
+ }
+
+ func cancel() { complete(nil) }
+
+ private func complete(_ response: Data?) {
+ queue.async { [self] in finish(response) }
+ }
+
+ private func finish(_ response: Data?) {
+ guard !completed else { return }
+ completed = true
+ timer?.setEventHandler {}
+ timer?.cancel()
+ timer = nil
+ task?.cancel()
+ task = nil
+ let reply = self.reply
+ self.reply = nil
+ if let response { reply?(response) }
+ }
+}
diff --git a/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapRegistrationProbe.swift b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapRegistrationProbe.swift
new file mode 100644
index 00000000..4f631a93
--- /dev/null
+++ b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapRegistrationProbe.swift
@@ -0,0 +1,136 @@
+import Foundation
+import Security
+
+/// A separate, read-only interface: only the signed registrar can ask which code owns registration.
+@objc(MotrixSafariRegistrationProbe)
+protocol BootstrapRegistrationRemote {
+ func identity(reply: @escaping @Sendable (Data) -> Void)
+}
+
+struct BootstrapRegistrationIdentity: Codable, Equatable, Sendable {
+ let executable: String
+ let cdHash: Data
+
+ static func read(code: SecStaticCode) throws -> Self {
+ var information: CFDictionary?
+ guard SecCodeCopySigningInformation(code, [], &information) == errSecSuccess,
+ let data = information as? [String: Any],
+ let executable = data[kSecCodeInfoMainExecutable as String] as? URL,
+ let hash = data[kSecCodeInfoUnique as String] as? Data
+ else { throw BootstrapIPCError.untrustedProcess }
+ return Self(executable: executable.resolvingSymlinksInPath().path, cdHash: hash)
+ }
+
+ static func current() throws -> Self {
+ var code: SecCode?
+ var staticCode: SecStaticCode?
+ guard SecCodeCopySelf([], &code) == errSecSuccess, let code,
+ SecCodeCopyStaticCode(code, [], &staticCode) == errSecSuccess, let staticCode
+ else { throw BootstrapIPCError.untrustedProcess }
+ return try read(code: staticCode)
+ }
+
+ static func expected(at url: URL) throws -> Self {
+ var code: SecStaticCode?
+ guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess, let code
+ else { throw BootstrapIPCError.untrustedProcess }
+ return try read(code: code)
+ }
+}
+
+final class BootstrapRegistrationService: NSObject, NSXPCListenerDelegate, BootstrapRegistrationRemote {
+ private let listener: NSXPCListener
+ private let payload: Data
+
+ init(configuration: BootstrapIPCConfiguration) throws {
+ try configuration.validateCurrentService()
+ payload = try JSONEncoder().encode(BootstrapRegistrationIdentity.current())
+ let registrar = try BootstrapIPCConfiguration(
+ teamIdentifier: configuration.teamIdentifier,
+ clientBundleIdentifier: "app.motrix.safari.registration",
+ serviceBundleIdentifier: configuration.serviceBundleIdentifier,
+ appGroupIdentifier: configuration.appGroupIdentifier
+ )
+ listener = NSXPCListener(machServiceName: configuration.appGroupIdentifier + ".registration")
+ super.init()
+ listener.setConnectionCodeSigningRequirement(registrar.clientSigningRequirement)
+ listener.delegate = self
+ }
+
+ #if DEBUG
+ init(testClientRequirement: String, payload: Data) {
+ self.payload = payload
+ listener = NSXPCListener.anonymous()
+ super.init()
+ listener.setConnectionCodeSigningRequirement(testClientRequirement)
+ listener.delegate = self
+ }
+ var testEndpoint: NSXPCListenerEndpoint { listener.endpoint }
+ #endif
+
+ func activate() { listener.activate() }
+ deinit { listener.invalidate() }
+
+ func listener(_ listener: NSXPCListener, shouldAcceptNewConnection connection: NSXPCConnection) -> Bool {
+ guard listener === self.listener, connection.effectiveUserIdentifier == geteuid() else { return false }
+ connection.exportedInterface = NSXPCInterface(with: BootstrapRegistrationRemote.self)
+ connection.exportedObject = self
+ connection.resume()
+ return true
+ }
+
+ func identity(reply: @escaping @Sendable (Data) -> Void) { reply(payload) }
+}
+
+/// No request data or credentials are sent. The incoming reply must satisfy the service signature.
+final class BootstrapRegistrationProbe: @unchecked Sendable {
+ private let lock = NSLock()
+ private var continuation: CheckedContinuation<Bool, Never>?
+ private var connection: NSXPCConnection?
+
+ func matches(configuration: BootstrapIPCConfiguration, expected: BootstrapRegistrationIdentity) async -> Bool {
+ await matches(
+ connection: NSXPCConnection(machServiceName: configuration.appGroupIdentifier + ".registration"),
+ requirement: configuration.serviceSigningRequirement, expected: expected)
+ }
+
+ #if DEBUG
+ func testMatches(endpoint: NSXPCListenerEndpoint, requirement: String, expected: BootstrapRegistrationIdentity) async -> Bool {
+ await matches(connection: NSXPCConnection(listenerEndpoint: endpoint), requirement: requirement, expected: expected)
+ }
+ #endif
+
+ private func matches(connection: NSXPCConnection, requirement: String, expected: BootstrapRegistrationIdentity) async -> Bool {
+ await withCheckedContinuation { continuation in
+ lock.lock()
+ self.continuation = continuation
+ self.connection = connection
+ lock.unlock()
+ connection.remoteObjectInterface = NSXPCInterface(with: BootstrapRegistrationRemote.self)
+ connection.setCodeSigningRequirement(requirement)
+ connection.invalidationHandler = { [weak self] in self?.finish(false) }
+ connection.interruptionHandler = { [weak self] in self?.finish(false) }
+ connection.resume()
+ DispatchQueue.global().asyncAfter(deadline: .now() + 2) { [self] in finish(false) }
+ let proxy = connection.remoteObjectProxyWithErrorHandler { [weak self] _ in self?.finish(false) }
+ guard let remote = proxy as? BootstrapRegistrationRemote else { finish(false); return }
+ remote.identity { [weak self] data in
+ let matches = data.count <= 8192 && (try? JSONDecoder().decode(BootstrapRegistrationIdentity.self, from: data)) == expected
+ self?.finish(matches)
+ }
+ }
+ }
+
+ private func finish(_ result: Bool) {
+ lock.lock()
+ let continuation = self.continuation
+ self.continuation = nil
+ let connection = self.connection
+ self.connection = nil
+ lock.unlock()
+ connection?.invalidationHandler = nil
+ connection?.interruptionHandler = nil
+ connection?.invalidate()
+ continuation?.resume(returning: result)
+ }
+}
diff --git a/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapRegistrationReconciler.swift b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapRegistrationReconciler.swift
new file mode 100644
index 00000000..5d4a2fc9
--- /dev/null
+++ b/packages/safari-bootstrap/Sources/SafariNativeIPC/BootstrapRegistrationReconciler.swift
@@ -0,0 +1,26 @@
+/// Rebind only stale registrations; never undo a user's disabled background-item choice.
+enum BootstrapRegistrationReconciler {
+ @MainActor
+ static func reconcile(
+ status: () -> String,
+ matches: () async -> Bool,
+ unregister: () async throws -> Void,
+ register: () throws -> Void
+ ) async throws -> String {
+ if status() == "requires-approval" { return "requires-approval" }
+ if status() == "enabled", await matches() { return "enabled" }
+ // Retry a stale registration once, then report failure instead of looping indefinitely.
+ for _ in 0..<2 {
+ switch status() {
+ case "requires-approval": return "requires-approval"
+ case "enabled": try await unregister()
+ case "not-registered", "not-found": break
+ default: return "failed"
+ }
+ try register()
+ if status() == "requires-approval" { return "requires-approval" }
+ if status() == "enabled", await matches() { return "enabled" }
+ }
+ return "failed"
+ }
+}
diff --git a/packages/safari-bootstrap/Tests/FFI/BootstrapProbe.swift b/packages/safari-bootstrap/Tests/FFI/BootstrapProbe.swift
new file mode 100644
index 00000000..3ae9cd63
--- /dev/null
+++ b/packages/safari-bootstrap/Tests/FFI/BootstrapProbe.swift
@@ -0,0 +1,28 @@
+import Foundation
+
+private actor LaunchCounter {
+ var count = 0
+ func launch() { count += 1 }
+}
+
+/// Links the production Swift adapter and Rust library; launch is the only simulated operation.
+@main enum BootstrapProbe {
+ static func main() async throws {
+ let allowLaunch = CommandLine.arguments.dropFirst().first != "passive"
+ let input = try JSONSerialization.data(withJSONObject: [
+ "action": "bootstrap", "protocolVersion": 1,
+ "bindingPub": String(repeating: "A", count: 43), "allowLaunch": allowLaunch,
+ ])
+ let request = try BootstrapIPCRequest(data: input)
+ let native = NativeBootstrapResolver()
+ let launches = LaunchCounter()
+ let response = try await BootstrapDesktopResolver().resolve(allowLaunch: allowLaunch) {
+ try await native.resolve(request)
+ } launch: { await launches.launch() }
+ let result = try JSONSerialization.data(withJSONObject: [
+ "response": try JSONSerialization.jsonObject(with: response),
+ "launches": await launches.count,
+ ])
+ FileHandle.standardOutput.write(result + Data([10]))
+ }
+}
diff --git a/packages/safari-bootstrap/Tests/SafariNativeIPCTests/BootstrapDesktopResolverTests.swift b/packages/safari-bootstrap/Tests/SafariNativeIPCTests/BootstrapDesktopResolverTests.swift
new file mode 100644
index 00000000..5fa9091f
--- /dev/null
+++ b/packages/safari-bootstrap/Tests/SafariNativeIPCTests/BootstrapDesktopResolverTests.swift
@@ -0,0 +1,130 @@
+import Foundation
+import XCTest
+@testable import SafariNativeIPC
+
+private actor ResolverFixture {
+ var probes = 0
+ var launches = 0
+ let availableAfter: Int
+ let launchFails: Bool
+ let ready = Data("{\"action\":\"requestPair\",\"protocolVersion\":1,\"port\":16800,\"nonce\":null}".utf8)
+
+ init(availableAfter: Int, launchFails: Bool = false) {
+ self.availableAfter = availableAfter
+ self.launchFails = launchFails
+ }
+
+ func probe() -> BootstrapDesktopProbe {
+ probes += 1
+ return probes > availableAfter ? .response(ready) : .notRunning
+ }
+
+ func launch() throws {
+ launches += 1
+ if launchFails { throw BootstrapIPCError.untrustedProcess }
+ }
+}
+
+final class BootstrapDesktopResolverTests: XCTestCase, @unchecked Sendable {
+ func testLaunchPathIsTheContainingDesktopOnly() throws {
+ let path = "/tmp/Motrix.app/Contents/Library/LaunchServices/MotrixSafariBootstrap"
+ let actual = try BootstrapDesktopLauncher.containingDesktop(executable: URL(fileURLWithPath: path))
+ XCTAssertEqual(actual.path, URL(fileURLWithPath: "/tmp/Motrix.app").resolvingSymlinksInPath().path)
+ for invalid in [
+ "/tmp/Motrix.app/Contents/MacOS/MotrixSafariBootstrap",
+ "/tmp/Motrix.app/Contents/Library/LaunchServices/OtherService",
+ "/tmp/Motrix/Contents/Library/LaunchServices/MotrixSafariBootstrap",
+ ] {
+ XCTAssertThrowsError(try BootstrapDesktopLauncher.containingDesktop(executable: URL(fileURLWithPath: invalid)))
+ }
+ }
+
+ func testPassiveProbeNeverLaunchesOrPolls() async throws {
+ let fixture = ResolverFixture(availableAfter: 3)
+ let result = try await BootstrapDesktopResolver().resolve(allowLaunch: false) {
+ await fixture.probe()
+ } launch: { try await fixture.launch() }
+ XCTAssertEqual(result, BootstrapIPCCodec.unavailable)
+ let counts = await (fixture.probes, fixture.launches)
+ XCTAssertEqual(counts.0, 1)
+ XCTAssertEqual(counts.1, 0)
+ }
+
+ func testRunningDesktopDoesNotLaunchAgain() async throws {
+ let fixture = ResolverFixture(availableAfter: 0)
+ let result = try await BootstrapDesktopResolver().resolve(allowLaunch: true) {
+ await fixture.probe()
+ } launch: { try await fixture.launch() }
+ XCTAssertEqual(result, fixture.ready)
+ let launches = await fixture.launches
+ XCTAssertEqual(launches, 0)
+ }
+
+ func testExplicitWakeLaunchesOnceAndReturnsFreshHandoff() async throws {
+ let fixture = ResolverFixture(availableAfter: 2)
+ let resolver = BootstrapDesktopResolver(timeout: .seconds(1), interval: .milliseconds(1))
+ let result = try await resolver.resolve(allowLaunch: true) {
+ await fixture.probe()
+ } launch: { try await fixture.launch() }
+ XCTAssertEqual(result, fixture.ready)
+ let counts = await (fixture.probes, fixture.launches)
+ XCTAssertEqual(counts.0, 3)
+ XCTAssertEqual(counts.1, 1)
+ }
+
+ func testRejectedHostFailsClosedWithoutPolling() async throws {
+ let fixture = ResolverFixture(availableAfter: 2, launchFails: true)
+ let result = try await BootstrapDesktopResolver().resolve(allowLaunch: true) {
+ await fixture.probe()
+ } launch: { try await fixture.launch() }
+ let error = try BootstrapIPCCodec.object(result, response: true)["error"] as? String
+ XCTAssertEqual(error, "launch-denied")
+ let probes = await fixture.probes
+ XCTAssertEqual(probes, 1)
+ }
+
+ func testDeadlineStopsPolling() async throws {
+ let fixture = ResolverFixture(availableAfter: .max)
+ let result = try await BootstrapDesktopResolver(timeout: .milliseconds(5), interval: .milliseconds(1))
+ .resolve(allowLaunch: true) { await fixture.probe() } launch: { try await fixture.launch() }
+ XCTAssertEqual(result, BootstrapIPCCodec.unavailable)
+ let launches = await fixture.launches
+ XCTAssertEqual(launches, 1)
+ }
+
+ func testLiveBridgeFailureNeverLaunchesOrRetries() async throws {
+ let fixture = ResolverFixture(availableAfter: 0)
+ let result = try await BootstrapDesktopResolver().resolve(allowLaunch: true) {
+ _ = await fixture.probe()
+ return .response(BootstrapIPCCodec.unavailable)
+ } launch: { try await fixture.launch() }
+ XCTAssertEqual(result, BootstrapIPCCodec.unavailable)
+ let counts = await (fixture.probes, fixture.launches)
+ XCTAssertEqual(counts.0, 1)
+ XCTAssertEqual(counts.1, 0)
+ }
+
+ func testNonceRefusalAfterColdLaunchStopsPolling() async throws {
+ let fixture = ResolverFixture(availableAfter: 1)
+ let result = try await BootstrapDesktopResolver().resolve(allowLaunch: true) {
+ let probe = await fixture.probe()
+ if case .notRunning = probe { return .notRunning }
+ return .response(BootstrapIPCCodec.unavailable)
+ } launch: { try await fixture.launch() }
+ XCTAssertEqual(result, BootstrapIPCCodec.unavailable)
+ let counts = await (fixture.probes, fixture.launches)
+ XCTAssertEqual(counts.0, 2)
+ XCTAssertEqual(counts.1, 1)
+ }
+
+ func testMalformedDiscoveryNeverTriggersLaunch() async throws {
+ let fixture = ResolverFixture(availableAfter: 0)
+ let malformed = Data("{\"error\":\"bootstrap-unavailable\",\"protocolVersion\":true}".utf8)
+ let result = try await BootstrapDesktopResolver().resolve(allowLaunch: true) {
+ .response(malformed)
+ } launch: { try await fixture.launch() }
+ XCTAssertEqual(result, malformed)
+ let launches = await fixture.launches
+ XCTAssertEqual(launches, 0)
+ }
+}
diff --git a/packages/safari-bootstrap/Tests/SafariNativeIPCTests/BootstrapIPCCodecTests.swift b/packages/safari-bootstrap/Tests/SafariNativeIPCTests/BootstrapIPCCodecTests.swift
new file mode 100644
index 00000000..58db4aa7
--- /dev/null
+++ b/packages/safari-bootstrap/Tests/SafariNativeIPCTests/BootstrapIPCCodecTests.swift
@@ -0,0 +1,157 @@
+import Foundation
+import XCTest
+@testable import SafariNativeIPC
+
+final class BootstrapIPCCodecTests: XCTestCase {
+ let key = String(repeating: "A", count: 43)
+
+ var request: [String: Any] {
+ ["action": "bootstrap", "protocolVersion": 1, "bindingPub": key, "allowLaunch": false]
+ }
+
+ var response: [String: Any] {
+ ["action": "requestPair", "protocolVersion": 1, "port": 16800, "nonce": "nonce"]
+ }
+
+ func encode(_ object: Any) throws -> Data {
+ try JSONSerialization.data(withJSONObject: object, options: [.fragmentsAllowed, .withoutEscapingSlashes])
+ }
+
+ func testConfigurationDerivesConstrainedServiceAndSigningRequirements() throws {
+ let configuration = try BootstrapIPCConfiguration(
+ teamIdentifier: "ABCDEFGHIJ", clientBundleIdentifier: "app.motrix.extension",
+ serviceBundleIdentifier: "app.motrix.bootstrap", appGroupIdentifier: "ABCDEFGHIJ.app.motrix"
+ )
+ XCTAssertEqual(configuration.machServiceName, "ABCDEFGHIJ.app.motrix.bootstrap")
+ XCTAssertEqual(configuration.clientSigningRequirement,
+ "anchor apple generic and certificate leaf[subject.OU] = \"ABCDEFGHIJ\" and identifier \"app.motrix.extension\" and entitlement[\"com.apple.security.application-groups\"] = \"ABCDEFGHIJ.app.motrix\"")
+ XCTAssertEqual(configuration.serviceSigningRequirement,
+ "anchor apple generic and certificate leaf[subject.OU] = \"ABCDEFGHIJ\" and identifier \"app.motrix.bootstrap\" and entitlement[\"com.apple.security.application-groups\"] = \"ABCDEFGHIJ.app.motrix\"")
+ XCTAssertThrowsError(try configuration.validateCurrentClient())
+ XCTAssertThrowsError(try BootstrapIPCClient(configuration: configuration))
+ XCTAssertThrowsError(try BootstrapIPCService(configuration: configuration))
+ }
+
+ func testConfigurationRejectsMissingIdentityInjectionAndUnrelatedGroup() {
+ let valid = ["ABCDEFGHIJ", "app.motrix.extension", "app.motrix.bootstrap", "ABCDEFGHIJ.app.motrix"]
+ for index in valid.indices {
+ for invalid in ["", " ", "anything\" or true", "app..motrix", "../app"] {
+ var inputs = valid
+ inputs[index] = invalid
+ XCTAssertThrowsError(try BootstrapIPCConfiguration(
+ teamIdentifier: inputs[0], clientBundleIdentifier: inputs[1],
+ serviceBundleIdentifier: inputs[2], appGroupIdentifier: inputs[3]
+ ))
+ }
+ }
+ for group in ["OTHERTEAM1.app.motrix", "group.app.motrix", "ABCDEFGHIJ." + String(repeating: "a", count: 120) + ".x"] {
+ XCTAssertThrowsError(try BootstrapIPCConfiguration(
+ teamIdentifier: valid[0], clientBundleIdentifier: valid[1],
+ serviceBundleIdentifier: valid[2], appGroupIdentifier: group
+ ))
+ }
+ for timeout in [Double.nan, Double.infinity, 0, -1, 21] {
+ XCTAssertThrowsError(try BootstrapIPCClient.validateTimeout(timeout))
+ }
+ }
+
+ func testRequestHasExactFieldsCanonicalPublicKeyAndBooleanFlag() throws {
+ let parsed = try BootstrapIPCRequest(data: encode(request))
+ XCTAssertEqual(parsed.bindingPublicKey, key)
+ XCTAssertFalse(parsed.allowLaunch)
+ for field in request.keys {
+ var malformed = request
+ malformed.removeValue(forKey: field)
+ XCTAssertThrowsError(try BootstrapIPCRequest(data: encode(malformed)))
+ }
+ for (field, values) in [
+ ("bindingPub", ["", String(repeating: "A", count: 42) + "B", key + "=", 42] as [Any]),
+ ("allowLaunch", [0, 1, "true", NSNull()] as [Any]),
+ ("protocolVersion", [true, 0, 2, "1", 1.5] as [Any]),
+ ("action", ["start", "ping", NSNull()] as [Any]),
+ ] {
+ for value in values {
+ var malformed = request
+ malformed[field] = value
+ XCTAssertThrowsError(try BootstrapIPCRequest(data: encode(malformed)))
+ }
+ }
+ var malformed = request
+ malformed["callerId"] = "spoofed"
+ XCTAssertThrowsError(try BootstrapIPCRequest(data: encode(malformed)))
+ }
+
+ func testWireSizeAndJSONShapeAreCheckedBeforeParsing() throws {
+ let encoded = try encode(request)
+ let exactlyLimit = encoded + Data(repeating: 32, count: 16384 - encoded.count)
+ XCTAssertNoThrow(try BootstrapIPCRequest(data: exactlyLimit))
+ XCTAssertThrowsError(try BootstrapIPCRequest(data: exactlyLimit + Data([32]))) { error in
+ XCTAssertEqual(error as? BootstrapIPCError, .messageTooLarge)
+ }
+ for data in [Data(), Data("[]".utf8), Data("null".utf8), Data("true".utf8), Data([0xff])] {
+ XCTAssertThrowsError(try BootstrapIPCRequest(data: data))
+ }
+ }
+
+ func testSuccessAndFixedErrorsNeverExposeEndpointFields() throws {
+ let request = try BootstrapIPCRequest(data: encode(request))
+ XCTAssertNoThrow(try BootstrapIPCCodec.validateResponse(encode(response), for: request))
+ var nullNonce = response
+ nullNonce["nonce"] = NSNull()
+ XCTAssertNoThrow(try BootstrapIPCCodec.validateResponse(encode(nullNonce), for: request))
+ XCTAssertNoThrow(try BootstrapIPCCodec.validateResponse(BootstrapIPCCodec.unavailable, for: request))
+ for extra in ["token", "generation", "endpoint", "message", "debug"] {
+ var malformed = response
+ malformed[extra] = "secret"
+ XCTAssertThrowsError(try BootstrapIPCCodec.validateResponse(encode(malformed), for: request))
+ }
+ for error in ["secret error text", "", "unsupported-version"] {
+ XCTAssertThrowsError(try BootstrapIPCCodec.validateResponse(
+ encode(["error": error, "protocolVersion": 1]), for: request
+ ))
+ }
+ for field in response.keys {
+ var malformed = response
+ malformed.removeValue(forKey: field)
+ XCTAssertThrowsError(try BootstrapIPCCodec.validateResponse(encode(malformed), for: request))
+ }
+ }
+
+ func testResponseRejectsInvalidPortVersionNonceAndOversize() throws {
+ let request = try BootstrapIPCRequest(data: encode(request))
+ for (field, values) in [
+ ("port", [0, -1, 65536, 1.5, true, "16800"] as [Any]),
+ ("protocolVersion", [true, 2, "1"] as [Any]),
+ ("nonce", ["", String(repeating: "a", count: 513), "line\nbreak", 12, []] as [Any]),
+ ("nmTicket", [NSNull(), "ticket", [], [:]] as [Any]),
+ ] {
+ for value in values {
+ var malformed = response
+ malformed[field] = value
+ XCTAssertThrowsError(try BootstrapIPCCodec.validateResponse(encode(malformed), for: request))
+ }
+ }
+ XCTAssertThrowsError(try BootstrapIPCCodec.validateResponse(Data(repeating: 32, count: 16385), for: request))
+ }
+
+ func testTicketShapePreservesOnlyProtocolFieldsAndRequestBinding() throws {
+ let request = try BootstrapIPCRequest(data: encode(request))
+ let ticket: [String: Any] = [
+ "v": 1, "purpose": "mbp1-attestation", "protocolVersion": 1,
+ "serverGeneration": "generation", "browser": "safari", "callerId": "app.motrix.extension",
+ "exp": 1800000000, "bindingPub": key, "mac": key,
+ ]
+ var response = response
+ response["nmTicket"] = ticket
+ XCTAssertNoThrow(try BootstrapIPCCodec.validateResponse(encode(response), for: request))
+ for (field, value): (String, Any) in [
+ ("token", "secret"), ("browser", "chrome"), ("purpose", "other"),
+ ("bindingPub", String(repeating: "B", count: 43)), ("exp", true), ("mac", "x"),
+ ] {
+ var malformed = ticket
+ malformed[field] = value
+ response["nmTicket"] = malformed
+ XCTAssertThrowsError(try BootstrapIPCCodec.validateResponse(encode(response), for: request))
+ }
+ }
+}
diff --git a/packages/safari-bootstrap/Tests/SafariNativeIPCTests/BootstrapIPCIntegrationTests.swift b/packages/safari-bootstrap/Tests/SafariNativeIPCTests/BootstrapIPCIntegrationTests.swift
new file mode 100644
index 00000000..4255512c
--- /dev/null
+++ b/packages/safari-bootstrap/Tests/SafariNativeIPCTests/BootstrapIPCIntegrationTests.swift
@@ -0,0 +1,236 @@
+import Foundation
+import Security
+import XCTest
+@testable import SafariNativeIPC
+
+/// These use actual NSXPC connections, with both peers constrained to this signed test executable.
+final class BootstrapIPCIntegrationTests: XCTestCase, @unchecked Sendable {
+ private let request = Data("{\"action\":\"bootstrap\",\"protocolVersion\":1,\"bindingPub\":\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"allowLaunch\":false}".utf8)
+ private let success = Data("{\"action\":\"requestPair\",\"protocolVersion\":1,\"port\":16800,\"nonce\":null}".utf8)
+
+ private func currentRequirement() throws -> String {
+ var dynamicCode: SecCode?
+ var staticCode: SecStaticCode?
+ var requirement: SecRequirement?
+ var string: CFString?
+ guard SecCodeCopySelf([], &dynamicCode) == errSecSuccess, let dynamicCode,
+ SecCodeCopyStaticCode(dynamicCode, [], &staticCode) == errSecSuccess, let staticCode,
+ SecCodeCopyDesignatedRequirement(staticCode, [], &requirement) == errSecSuccess, let requirement,
+ SecRequirementCopyString(requirement, [], &string) == errSecSuccess, let string
+ else { throw BootstrapIPCError.untrustedProcess }
+ XCTAssertEqual(SecCodeCheckValidity(dynamicCode, [], requirement), errSecSuccess)
+ return string as String
+ }
+
+ private func client(_ service: BootstrapIPCService, requirement: String, timeout: TimeInterval = 1) throws -> BootstrapIPCClient {
+ try BootstrapIPCClient(testEndpoint: service.testEndpoint, serviceRequirement: requirement, timeout: timeout)
+ }
+
+ private func assertConnectionsReleased(_ service: BootstrapIPCService) async throws {
+ for _ in 0..<50 {
+ if service.testActiveConnectionCount == 0 { return }
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ XCTAssertEqual(service.testActiveConnectionCount, 0)
+ }
+
+ func testRegistrationIdentityUsesAuthenticatedXPC() async throws {
+ let requirement = try currentRequirement()
+ let expected = try BootstrapRegistrationIdentity.current()
+ let payload = try JSONEncoder().encode(expected)
+ let service = BootstrapRegistrationService(testClientRequirement: requirement, payload: payload)
+ service.activate()
+ let matched = await BootstrapRegistrationProbe().testMatches(endpoint: service.testEndpoint, requirement: requirement, expected: expected)
+ XCTAssertTrue(matched)
+ let wrongCode = BootstrapRegistrationIdentity(executable: expected.executable, cdHash: Data([0]))
+ let wrongMatch = await BootstrapRegistrationProbe().testMatches(endpoint: service.testEndpoint, requirement: requirement, expected: wrongCode)
+ XCTAssertFalse(wrongMatch)
+ }
+
+ func testRegistrationIdentityRejectsUntrustedPeersAndMalformedPayload() async throws {
+ let requirement = try currentRequirement()
+ let wrong = "(\(requirement)) and identifier \"wrong.peer\""
+ let expected = try BootstrapRegistrationIdentity.current()
+ for (clientRequirement, serviceRequirement, payload) in [
+ (wrong, requirement, try JSONEncoder().encode(expected)),
+ (requirement, wrong, try JSONEncoder().encode(expected)),
+ (requirement, requirement, Data("invalid".utf8)),
+ (requirement, requirement, Data(repeating: 65, count: 8193)),
+ ] {
+ let service = BootstrapRegistrationService(testClientRequirement: clientRequirement, payload: payload)
+ service.activate()
+ let matched = await BootstrapRegistrationProbe().testMatches(endpoint: service.testEndpoint, requirement: serviceRequirement, expected: expected)
+ XCTAssertFalse(matched)
+ }
+ }
+
+ func testActualXPCRoundTripUsesBothSigningRequirementsAndReleasesConnection() async throws {
+ let requirement = try currentRequirement()
+ let expected = success
+ let service = try BootstrapIPCService(testClientRequirement: requirement) { request in
+ XCTAssertFalse(request.allowLaunch)
+ XCTAssertEqual(request.bindingPublicKey, String(repeating: "A", count: 43))
+ return expected
+ }
+ service.activate()
+ defer { service.invalidate() }
+ let response = try await client(service, requirement: requirement).bootstrap(request)
+ XCTAssertEqual(response, expected)
+ try await assertConnectionsReleased(service)
+ }
+
+ func testDefaultResolverIsUnavailableOverActualXPC() async throws {
+ let requirement = try currentRequirement()
+ let service = try BootstrapIPCService(testClientRequirement: requirement)
+ service.activate()
+ defer { service.invalidate() }
+ let response = try await client(service, requirement: requirement).bootstrap(request)
+ XCTAssertEqual(response, BootstrapIPCCodec.unavailable)
+ try await assertConnectionsReleased(service)
+ }
+
+ func testListenerRejectsWrongClientSigningRequirement() async throws {
+ let requirement = try currentRequirement()
+ let service = try BootstrapIPCService(testClientRequirement: "(\(requirement)) and identifier \"wrong.peer\"") { _ in
+ XCTFail("An untrusted caller reached the resolver")
+ return BootstrapIPCCodec.unavailable
+ }
+ service.activate()
+ defer { service.invalidate() }
+ do {
+ _ = try await client(service, requirement: requirement).bootstrap(request)
+ XCTFail("Wrong client signature was accepted")
+ } catch { XCTAssertEqual(error as? BootstrapIPCError, .unavailable) }
+ XCTAssertEqual(service.testActiveConnectionCount, 0)
+ }
+
+ func testClientRejectsWrongServiceSigningRequirement() async throws {
+ let requirement = try currentRequirement()
+ let service = try BootstrapIPCService(testClientRequirement: requirement) { _ in
+ XCTFail("A request was delivered to a service with the wrong signature")
+ return BootstrapIPCCodec.unavailable
+ }
+ service.activate()
+ defer { service.invalidate() }
+ do {
+ _ = try await client(service, requirement: "(\(requirement)) and identifier \"wrong.peer\"").bootstrap(request)
+ XCTFail("Wrong service signature was accepted")
+ } catch { XCTAssertEqual(error as? BootstrapIPCError, .unavailable) }
+ try await assertConnectionsReleased(service)
+ }
+
+ func testListenerRejectsDifferentEffectiveUser() async throws {
+ let requirement = try currentRequirement()
+ let service = try BootstrapIPCService(testClientRequirement: requirement, expectedUserID: geteuid() + 1)
+ service.activate()
+ defer { service.invalidate() }
+ do {
+ _ = try await client(service, requirement: requirement).bootstrap(request)
+ XCTFail("Wrong user was accepted")
+ } catch { XCTAssertEqual(error as? BootstrapIPCError, .unavailable) }
+ XCTAssertEqual(service.testActiveConnectionCount, 0)
+ }
+
+ func testBothPeersRejectMissingRequiredAppGroupBeforeBootstrapDelivery() async throws {
+ let requirement = try currentRequirement()
+ let missingGroup = "(\(requirement)) and entitlement[\"com.apple.security.application-groups\"] = \"TESTONLY00.app.motrix.missing\""
+ for rejectClient in [true, false] {
+ let service = try BootstrapIPCService(testClientRequirement: rejectClient ? missingGroup : requirement) { _ in
+ XCTFail("A peer without the required App Group reached bootstrap")
+ return BootstrapIPCCodec.unavailable
+ }
+ service.activate()
+ defer { service.invalidate() }
+ do {
+ _ = try await client(service, requirement: rejectClient ? requirement : missingGroup).bootstrap(request)
+ XCTFail("A peer without the required App Group was accepted")
+ } catch { XCTAssertEqual(error as? BootstrapIPCError, .unavailable) }
+ try await assertConnectionsReleased(service)
+ }
+ }
+
+ func testInvalidResolverResponseIsReplacedWithoutLeakingSecrets() async throws {
+ let requirement = try currentRequirement()
+ let service = try BootstrapIPCService(testClientRequirement: requirement) { _ in
+ Data("{\"token\":\"secret\",\"generation\":\"secret\"}".utf8)
+ }
+ service.activate()
+ defer { service.invalidate() }
+ let response = try await client(service, requirement: requirement).bootstrap(request)
+ XCTAssertEqual(response, BootstrapIPCCodec.invalidResponse)
+ try await assertConnectionsReleased(service)
+ }
+
+ func testClientTimeoutCancelsAndReleasesConnection() async throws {
+ let requirement = try currentRequirement()
+ let service = try BootstrapIPCService(testClientRequirement: requirement) { _ in
+ try await Task.sleep(for: .seconds(5))
+ return BootstrapIPCCodec.unavailable
+ }
+ service.activate()
+ defer { service.invalidate() }
+ do {
+ _ = try await client(service, requirement: requirement, timeout: 0.05).bootstrap(request)
+ XCTFail("A stalled resolver escaped the client timeout")
+ } catch { XCTAssertEqual(error as? BootstrapIPCError, .timedOut) }
+ try await assertConnectionsReleased(service)
+ }
+
+ func testServiceTimeoutRepliesOnceAndCancelsResolver() async throws {
+ let requirement = try currentRequirement()
+ let service = try BootstrapIPCService(testClientRequirement: requirement, timeout: 0.03) { _ in
+ try await Task.sleep(for: .seconds(5))
+ return BootstrapIPCCodec.unavailable
+ }
+ service.activate()
+ defer { service.invalidate() }
+ let response = try await client(service, requirement: requirement).bootstrap(request)
+ XCTAssertEqual(response, BootstrapIPCCodec.timeout)
+ try await assertConnectionsReleased(service)
+ }
+
+ func testCancellationAndServiceInvalidationSettleOutstandingCalls() async throws {
+ let requirement = try currentRequirement()
+ let service = try BootstrapIPCService(testClientRequirement: requirement) { _ in
+ try await Task.sleep(for: .seconds(5))
+ return BootstrapIPCCodec.unavailable
+ }
+ service.activate()
+ defer { service.invalidate() }
+ let client = try client(service, requirement: requirement)
+ let request = request
+ let cancelled = Task { try await client.bootstrap(request) }
+ cancelled.cancel()
+ do {
+ _ = try await cancelled.value
+ XCTFail("Cancelled operation succeeded")
+ } catch { XCTAssertEqual(error as? BootstrapIPCError, .cancelled) }
+ let disconnected = Task { try await client.bootstrap(request) }
+ try await Task.sleep(for: .milliseconds(30))
+ service.invalidate()
+ do {
+ _ = try await disconnected.value
+ XCTFail("Invalidated connection succeeded")
+ } catch { XCTAssertEqual(error as? BootstrapIPCError, .unavailable) }
+ try await assertConnectionsReleased(service)
+ }
+
+ func testReplyTimeoutRacesDoNotDoubleResumeAndReleaseEveryConnection() async throws {
+ let requirement = try currentRequirement()
+ let expected = success
+ let service = try BootstrapIPCService(testClientRequirement: requirement, timeout: 0.02) { _ in
+ try await Task.sleep(for: .milliseconds(20))
+ return expected
+ }
+ service.activate()
+ defer { service.invalidate() }
+ let client = try client(service, requirement: requirement, timeout: 0.02)
+ for _ in 0..<20 {
+ do {
+ let response = try await client.bootstrap(request)
+ XCTAssertTrue(response == expected || response == BootstrapIPCCodec.timeout)
+ } catch { XCTAssertEqual(error as? BootstrapIPCError, .timedOut) }
+ }
+ try await assertConnectionsReleased(service)
+ }
+}
diff --git a/packages/safari-bootstrap/Tests/SafariNativeIPCTests/BootstrapRegistrationTests.swift b/packages/safari-bootstrap/Tests/SafariNativeIPCTests/BootstrapRegistrationTests.swift
new file mode 100644
index 00000000..beb50404
--- /dev/null
+++ b/packages/safari-bootstrap/Tests/SafariNativeIPCTests/BootstrapRegistrationTests.swift
@@ -0,0 +1,64 @@
+import Foundation
+import XCTest
+@testable import SafariNativeIPC
+
+final class BootstrapRegistrationTests: XCTestCase {
+ @MainActor
+ func testMatchingOwnerDoesNotInterruptColdLaunch() async throws {
+ var mutations = 0
+ let result = try await BootstrapRegistrationReconciler.reconcile(
+ status: { "enabled" }, matches: { true },
+ unregister: { mutations += 1 }, register: { mutations += 1 })
+ XCTAssertEqual(result, "enabled")
+ XCTAssertEqual(mutations, 0)
+ }
+
+ @MainActor
+ func testStaleOwnerRebindsAndVerifiesBeforeReportingEnabled() async throws {
+ var state = "enabled"
+ var registrations = 0
+ var removals = 0
+ let result = try await BootstrapRegistrationReconciler.reconcile(
+ status: { state }, matches: { registrations == 2 },
+ unregister: { removals += 1; state = "not-registered" },
+ register: { registrations += 1; state = "enabled" })
+ XCTAssertEqual(result, "enabled")
+ XCTAssertEqual(registrations, 2)
+ XCTAssertEqual(removals, 2)
+ }
+
+ @MainActor
+ func testUserDisabledServiceIsNeverReenabled() async throws {
+ var mutations = 0
+ let result = try await BootstrapRegistrationReconciler.reconcile(
+ status: { "requires-approval" }, matches: { XCTFail("must not probe"); return false },
+ unregister: { mutations += 1 }, register: { mutations += 1 })
+ XCTAssertEqual(result, "requires-approval")
+ XCTAssertEqual(mutations, 0)
+ }
+
+ @MainActor
+ func testFailedOwnerVerificationIsBounded() async throws {
+ var registrations = 0
+ let result = try await BootstrapRegistrationReconciler.reconcile(
+ status: { "enabled" }, matches: { false }, unregister: {},
+ register: { registrations += 1 })
+ XCTAssertEqual(result, "failed")
+ XCTAssertEqual(registrations, 2)
+ }
+
+ @MainActor
+ func testApprovalRequiredAfterRegistrationStopsRepair() async throws {
+ var state = "not-registered"
+ let result = try await BootstrapRegistrationReconciler.reconcile(
+ status: { state }, matches: { XCTFail("must not probe disabled service"); return false },
+ unregister: { XCTFail("not registered") }, register: { state = "requires-approval" })
+ XCTAssertEqual(result, "requires-approval")
+ }
+
+ func testIdentityIncludesBothCanonicalExecutableAndCodeHash() {
+ let identity = BootstrapRegistrationIdentity(executable: "/Applications/Motrix.app/helper", cdHash: Data([1]))
+ XCTAssertNotEqual(identity, BootstrapRegistrationIdentity(executable: "/tmp/Motrix.app/helper", cdHash: Data([1])))
+ XCTAssertNotEqual(identity, BootstrapRegistrationIdentity(executable: identity.executable, cdHash: Data([2])))
+ }
+}
diff --git a/packages/safari-bootstrap/build.mjs b/packages/safari-bootstrap/build.mjs
new file mode 100644
index 00000000..f4882f6a
--- /dev/null
+++ b/packages/safari-bootstrap/build.mjs
@@ -0,0 +1,123 @@
+import { spawnSync } from 'node:child_process'
+import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { parseArgs } from 'node:util'
+import { testBootstrapIntegration } from './test-integration.mjs'
+
+const { values } = parseArgs({
+ args: process.argv.slice(2).filter((arg) => arg !== '--'),
+ options: { arch: { type: 'string' }, test: { type: 'boolean' } },
+})
+const arch = values.arch ?? process.arch
+if (process.platform !== 'darwin' || !['arm64', 'x64'].includes(arch)) {
+ throw new Error('Safari bootstrap requires macOS and --arch arm64 or x64')
+}
+const root = fileURLToPath(new URL('../../', import.meta.url))
+const source = join(root, 'packages/safari-bootstrap')
+const output = join(source, 'dist', `darwin-${arch}`)
+const intermediate = join(source, '.build', arch)
+mkdirSync(output, { recursive: true })
+mkdirSync(intermediate, { recursive: true })
+const configuration = JSON.parse(
+ readFileSync(join(source, 'configuration.json'), 'utf8')
+)
+const generated = join(intermediate, 'SignedConfiguration.swift')
+writeFileSync(
+ generated,
+ `func signedBootstrapConfiguration() throws -> BootstrapIPCConfiguration {
+ try BootstrapIPCConfiguration(
+ teamIdentifier: ${JSON.stringify(configuration.teamIdentifier)},
+ clientBundleIdentifier: ${JSON.stringify(configuration.clientBundleIdentifier)},
+ serviceBundleIdentifier: ${JSON.stringify(configuration.serviceBundleIdentifier)},
+ appGroupIdentifier: ${JSON.stringify(configuration.appGroupIdentifier)}
+ )
+}
+`
+)
+function run(command, args) {
+ const result = spawnSync(command, args, {
+ cwd: root,
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'inherit'],
+ })
+ if (result.error || result.status !== 0) throw new Error(`${command} failed`)
+ return result.stdout.trim()
+}
+const cpu = arch === 'arm64' ? 'aarch64' : 'x86_64'
+const target = `${cpu}-apple-darwin`
+const rustOutput = join(intermediate, 'rust')
+run('cargo', [
+ 'rustc',
+ '--manifest-path',
+ 'packages/native-host/Cargo.toml',
+ '--locked',
+ '--release',
+ '--lib',
+ '--features',
+ 'safari-bootstrap',
+ '--crate-type',
+ 'staticlib',
+ '--target',
+ target,
+ '--target-dir',
+ rustOutput,
+])
+const sdk = run('/usr/bin/xcrun', ['--sdk', 'macosx', '--show-sdk-path'])
+const ipc = join(source, 'Sources/SafariNativeIPC')
+const common = [
+ 'swiftc',
+ '-O',
+ '-swift-version',
+ '6',
+ '-parse-as-library',
+ '-target',
+ `${arch === 'x64' ? 'x86_64' : arch}-apple-macos13.0`,
+ '-sdk',
+ sdk,
+ '-module-cache-path',
+ join(intermediate, 'swift-module-cache'),
+ ...readdirSync(ipc)
+ .filter((name) => name.endsWith('.swift'))
+ .sort()
+ .map((name) => join(ipc, name)),
+ generated,
+ '-framework',
+ 'Security',
+]
+run('/usr/bin/xcrun', [
+ ...common,
+ '-import-objc-header',
+ join(root, 'packages/native-host/include/motrix_safari_bootstrap.h'),
+ join(source, 'Native/NativeBootstrapResolver.swift'),
+ join(source, 'Executables/BootstrapServiceMain.swift'),
+ join(rustOutput, target, 'release/libmotrix_native_host.a'),
+ '-o',
+ join(output, 'MotrixSafariBootstrap'),
+])
+run('/usr/bin/xcrun', [
+ ...common,
+ join(source, 'Executables/DesktopBootstrapRegistrar.swift'),
+ '-framework',
+ 'ServiceManagement',
+ '-o',
+ join(output, 'MotrixSafariRegistrar'),
+])
+console.log(`Built unsigned Safari desktop helpers for ${arch}`)
+
+if (values.test) {
+ if (arch !== process.arch)
+ throw new Error('Integration tests require the runner architecture')
+ const probe = join(intermediate, 'bootstrap-probe')
+ run('/usr/bin/xcrun', [
+ ...common,
+ '-import-objc-header',
+ join(root, 'packages/native-host/include/motrix_safari_bootstrap.h'),
+ join(source, 'Native/NativeBootstrapResolver.swift'),
+ join(source, 'Tests/FFI/BootstrapProbe.swift'),
+ join(rustOutput, target, 'release/libmotrix_native_host.a'),
+ '-o',
+ probe,
+ ])
+ await testBootstrapIntegration(probe)
+}
diff --git a/packages/safari-bootstrap/configuration.json b/packages/safari-bootstrap/configuration.json
new file mode 100644
index 00000000..58da0068
--- /dev/null
+++ b/packages/safari-bootstrap/configuration.json
@@ -0,0 +1,6 @@
+{
+ "teamIdentifier": "7VMB56CA56",
+ "clientBundleIdentifier": "app.motrix.safari.extension",
+ "serviceBundleIdentifier": "app.motrix.safari.bootstrap",
+ "appGroupIdentifier": "7VMB56CA56.app.motrix.shared"
+}
diff --git a/packages/safari-bootstrap/test-integration.mjs b/packages/safari-bootstrap/test-integration.mjs
new file mode 100644
index 00000000..ef3a0ce1
--- /dev/null
+++ b/packages/safari-bootstrap/test-integration.mjs
@@ -0,0 +1,121 @@
+import assert from 'node:assert/strict'
+import { spawn } from 'node:child_process'
+import { once } from 'node:events'
+import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { createServer } from 'node:http'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+function runProbe(executable, mode, directory) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(executable, [mode], {
+ env: { ...process.env, MOTRIX_BRIDGE_DATA_DIR: directory },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ signal: AbortSignal.timeout(8_000),
+ })
+ let output = ''
+ let diagnostic = ''
+ child.stdout.setEncoding('utf8').on('data', (data) => {
+ output += data
+ })
+ child.stderr.setEncoding('utf8').on('data', (data) => {
+ diagnostic += data
+ })
+ child.on('error', reject)
+ child.on('close', (code) => {
+ if (code !== 0)
+ return reject(new Error(`Bootstrap fixture failed: ${diagnostic}`))
+ try {
+ resolve(JSON.parse(output))
+ } catch (error) {
+ reject(error)
+ }
+ })
+ })
+}
+
+export async function testBootstrapIntegration(executable) {
+ for (const scenario of [
+ { name: 'running-success', status: 200 },
+ { name: 'running-rate-limit', status: 429 },
+ { name: 'running-unavailable', status: 503 },
+ { name: 'cold-success', status: 200, cold: true },
+ { name: 'cold-rate-limit', status: 429, cold: true },
+ { name: 'cold-unavailable', status: 503, cold: true },
+ { name: 'passive-rate-limit', status: 429, passive: true },
+ { name: 'passive-offline', status: 503, passive: true, cold: true },
+ ]) {
+ const directory = await mkdtemp(join(tmpdir(), 'motrix-safari-ffi-'))
+ const counts = { discovery: 0, nonce: 0 }
+ const server = createServer((request, response) => {
+ let status = 404
+ let body = {}
+ if (request.method === 'GET' && request.url === '/discovery') {
+ counts.discovery += 1
+ status = scenario.cold && counts.discovery === 1 ? 503 : 200
+ body = {
+ app: 'motrix-bridge',
+ apiVersion: 1,
+ instanceId: 'ffi-fixture',
+ appVersion: '2.0.0',
+ }
+ } else if (request.method === 'POST' && request.url === '/nonce') {
+ counts.nonce += 1
+ status =
+ request.headers['x-motrix-bridge'] === '1' ? scenario.status : 400
+ body = { nonce: 'ffi-fixture-nonce-0123456789' }
+ }
+ const data = JSON.stringify(body)
+ response.writeHead(status, {
+ 'Content-Type': 'application/json',
+ 'Content-Length': Buffer.byteLength(data),
+ })
+ response.end(data)
+ })
+ try {
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ const port = server.address().port
+ const endpoint = join(directory, 'endpoint.json')
+ await writeFile(endpoint, JSON.stringify({ port }), { mode: 0o600 })
+ await chmod(endpoint, 0o600)
+ const result = await runProbe(
+ executable,
+ scenario.passive ? 'passive' : 'wake',
+ directory
+ )
+ const passiveOffline = Boolean(scenario.passive && scenario.cold)
+ assert.deepEqual(
+ counts,
+ {
+ discovery: scenario.cold && !scenario.passive ? 2 : 1,
+ nonce: passiveOffline ? 0 : 1,
+ },
+ scenario.name
+ )
+ assert.equal(
+ result.launches,
+ scenario.cold && !scenario.passive ? 1 : 0,
+ scenario.name
+ )
+ assert.deepEqual(
+ result.response,
+ scenario.status === 200
+ ? {
+ action: 'requestPair',
+ protocolVersion: 1,
+ port,
+ nonce: 'ffi-fixture-nonce-0123456789',
+ }
+ : { error: 'bootstrap-unavailable', protocolVersion: 1 },
+ scenario.name
+ )
+ console.log(`Safari Swift/Rust integration passed: ${scenario.name}`)
+ } finally {
+ server.closeAllConnections()
+ if (server.listening)
+ await new Promise((resolve) => server.close(resolve))
+ await rm(directory, { recursive: true, force: true })
+ }
+ }
+}
diff --git a/scripts/release-signing-input.mjs b/scripts/release-signing-input.mjs
index 41bc4f3e..f0478677 100644
--- a/scripts/release-signing-input.mjs
+++ b/scripts/release-signing-input.mjs
@@ -34,8 +34,14 @@ export const SIGNING_ARCHIVE_LIMITS = Object.freeze({
})
const TRUSTED_INPUT_SHA256 = Object.freeze({
+ 'signing-build-resources/app.motrix.safari.bootstrap.plist':
+ '27ad50100646b2696fd7a0cab8d5ce1f391730069350f6e3d76ace376e0ef696',
+ 'signing-build-resources/entitlements.safari.plist':
+ '9d8cee581ad890260639ec94839844cbd12abf3396131604b32820bf28328c4d',
+ 'scripts/sign-macos.mjs':
+ 'e5109fd4ef90aaaac74bc91b1b9470f163d61cff32ec241ce5b216318849375d',
'electron-builder.signing.json':
- 'fb261dd746182ba6e374af6b5955a6f77d71f4aeb343485d0f69ee4e62bdd3d3',
+ 'da0d66babef56e80e725fd62b7b7b659571809d01e0f4383f28f6623a21962aa',
'signing-build-resources/256x256.png':
'044d3b64a14aa512ca41469372d1ad630557daaeb2cb4e709d34f2d3c57d4c3b',
'signing-build-resources/background.tiff':
@@ -69,7 +75,7 @@ const TRUSTED_INPUT_SHA256 = Object.freeze({
'scripts/native-binary-target.mjs':
'6f0a42eecf729eb6de2df28b5d7449993590e494deb4e309b99c367094045797',
'scripts/verify-electron-package.mjs':
- 'ec160ddfa929242155e38d3e0cfdd752ca748a16a84c71eefd39d5b0cbfb9e8a',
+ '83e7a924c43b70def9440dc8561d9c0aa5dd15dc6044b24f3436215eb92e345c',
})
// Use electron-builder's default resource names so the restricted config can
@@ -84,6 +90,15 @@ const SOURCE_MAPPINGS = [
['THIRD_PARTY_NOTICES.md', 'THIRD_PARTY_NOTICES.md'],
['THIRD_PARTY_NOTICES.zh-CN.md', 'THIRD_PARTY_NOTICES.zh-CN.md'],
['build/legal', 'build/legal'],
+ ['scripts/sign-macos.mjs', 'scripts/sign-macos.mjs'],
+ [
+ 'build/entitlements.safari.plist',
+ 'signing-build-resources/entitlements.safari.plist',
+ ],
+ [
+ 'build/app.motrix.safari.bootstrap.plist',
+ 'signing-build-resources/app.motrix.safari.bootstrap.plist',
+ ],
['build/256x256.png', 'signing-build-resources/256x256.png'],
['build/background.tiff', 'signing-build-resources/background.tiff'],
[
@@ -161,6 +176,7 @@ function isAllowedSigningDataPath(relativePath) {
'signing-policy/installer.nsh',
'signing-tool/package.json',
'signing-tool/package-lock.json',
+ 'scripts/sign-macos.mjs',
'scripts/before-build-use-staged-dependencies.mjs',
'scripts/electron-package-size-budgets.json',
'scripts/electron-package-utils.mjs',
@@ -176,6 +192,7 @@ function isAllowedSigningDataPath(relativePath) {
'extra/',
'packages/finalize-fs/dist/',
'packages/native-host/dist/',
+ 'packages/safari-bootstrap/dist/',
'signing-build-resources/',
'size-reports/',
].some((prefix) => relativePath.startsWith(prefix))
@@ -218,6 +235,7 @@ function isAllowedSigningDirectory(relativePath) {
'extra',
'packages/finalize-fs/dist',
'packages/native-host/dist',
+ 'packages/safari-bootstrap/dist',
]
const flatRoots = [
'signing-build-resources',
@@ -245,6 +263,8 @@ function isAllowedSigningBuildResource(relativePath) {
'signing-build-resources/256x256.png',
'signing-build-resources/background.tiff',
'signing-build-resources/entitlements.mac.plist',
+ 'signing-build-resources/entitlements.safari.plist',
+ 'signing-build-resources/app.motrix.safari.bootstrap.plist',
'signing-build-resources/icon.icns',
'signing-build-resources/icon.ico',
'signing-build-resources/torrent.icns',
@@ -583,6 +603,12 @@ export async function createSigningInput(options) {
const targetKey = `${options.platform}-${options.arch}`
for (const [sourcePath, destinationPath] of [
...SOURCE_MAPPINGS,
+ ...(options.platform === 'darwin'
+ ? ['MotrixSafariBootstrap', 'MotrixSafariRegistrar'].map((name) => {
+ const file = `packages/safari-bootstrap/dist/darwin-${options.arch}/${name}`
+ return [file, file]
+ })
+ : []),
[
targetResource(options.platform, options.arch),
targetResource(options.platform, options.arch),
@@ -708,7 +734,7 @@ async function verifyRestrictedConfig(input) {
config.nsis?.customNsisBinary !== null ||
config.nsis?.customNsisResources !== null ||
config.toolsets?.nsis !== undefined ||
- config.mac?.sign !== undefined ||
+ config.mac?.sign !== './scripts/sign-macos.mjs' ||
config.win?.signtoolOptions?.sign !== undefined
) {
throw new Error('restricted signing config is not self-contained')
diff --git a/scripts/sign-macos.mjs b/scripts/sign-macos.mjs
new file mode 100644
index 00000000..e2568bcc
--- /dev/null
+++ b/scripts/sign-macos.mjs
@@ -0,0 +1,86 @@
+import { execFileSync } from 'node:child_process'
+import { createRequire } from 'node:module'
+import path from 'node:path'
+
+const TEAM = '7VMB56CA56'
+const GROUP = `${TEAM}.app.motrix.shared`
+const HELPERS = {
+ 'Contents/MacOS/MotrixSafariRegistrar': 'app.motrix.safari.registration',
+ 'Contents/Library/LaunchServices/MotrixSafariBootstrap':
+ 'app.motrix.safari.bootstrap',
+}
+
+export function safariSignOptions(app, file, entitlements, fallback) {
+ const identifier =
+ HELPERS[
+ path
+ .relative(path.resolve(app), path.resolve(file))
+ .split(path.sep)
+ .join('/')
+ ]
+ if (!identifier) return fallback?.(file) ?? {}
+ return {
+ entitlements,
+ hardenedRuntime: true,
+ requirements: `=designated => anchor apple generic and certificate leaf[subject.OU] = "${TEAM}" and identifier "${identifier}"`,
+ additionalArguments: ['--identifier', identifier],
+ }
+}
+
+// Invoked only by electron-builder after identity selection. Resolve dependencies
+// from its isolated, lockfile-pinned runtime, never from the unsigned app payload.
+export default async function sign(options, packager) {
+ const require = createRequire(
+ process.env.ELECTRON_BUILDER_CLI || import.meta.url
+ )
+ const {
+ sign: signElectron,
+ } = require('app-builder-lib/out/codeSign/macCodeSign.js')
+ const entitlements = path.join(
+ packager.info.projectDir,
+ process.env.ELECTRON_BUILDER_CLI ? 'signing-build-resources' : 'build',
+ 'entitlements.safari.plist'
+ )
+ await signElectron({
+ ...options,
+ optionsForFile: (file) =>
+ safariSignOptions(
+ options.app,
+ file,
+ entitlements,
+ options.optionsForFile
+ ),
+ })
+ // Check fixed identity and privileges before electron-builder submits for notarization.
+ for (const [relative, identifier] of Object.entries(HELPERS)) {
+ const file = path.join(options.app, relative)
+ execFileSync(
+ '/usr/bin/codesign',
+ [
+ '--verify',
+ '--strict',
+ '-R',
+ `=anchor apple generic and certificate leaf[subject.OU] = "${TEAM}" and identifier "${identifier}" and entitlement["com.apple.security.application-groups"] = "${GROUP}"`,
+ file,
+ ],
+ { stdio: 'pipe' }
+ )
+ const xml = execFileSync(
+ '/usr/bin/codesign',
+ ['-d', '--entitlements', '-', '--xml', file],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }
+ )
+ const actual = JSON.parse(
+ execFileSync('/usr/bin/plutil', ['-convert', 'json', '-o', '-', '-'], {
+ input: xml,
+ encoding: 'utf8',
+ })
+ )
+ if (
+ JSON.stringify(actual) !==
+ JSON.stringify({ 'com.apple.security.application-groups': [GROUP] })
+ ) {
+ throw new Error('Safari helper has unexpected entitlements')
+ }
+ }
+}
diff --git a/scripts/verify-electron-package.mjs b/scripts/verify-electron-package.mjs
index 2ea5153c..6d7e0701 100644
--- a/scripts/verify-electron-package.mjs
+++ b/scripts/verify-electron-package.mjs
@@ -544,6 +544,42 @@ export async function verifyElectronPackage(options) {
return 'single external resvg WASM matches stage'
})
+ await check('safari-desktop-helpers', async () => {
+ if (target.platform !== 'darwin') return 'not applicable'
+ for (const relative of [
+ 'MacOS/MotrixSafariRegistrar',
+ 'Library/LaunchServices/MotrixSafariBootstrap',
+ ]) {
+ const file = path.join(resources, '..', relative)
+ const info = await lstat(file)
+ if (
+ !info.isFile() ||
+ !nativeTargetMatches(
+ detectNativeBinaryTarget(await readFile(file)),
+ 'darwin',
+ target.arch,
+ false
+ )
+ ) {
+ throw new Error(`invalid Safari helper: ${relative}`)
+ }
+ await access(file, constants.X_OK)
+ }
+ const plist = path.join(
+ resources,
+ '../Library/LaunchAgents/app.motrix.safari.bootstrap.plist'
+ )
+ if (!(await lstat(plist)).isFile())
+ throw new Error('invalid Safari LaunchAgent')
+ const digest = sha256(await readFile(plist))
+ if (
+ digest !==
+ '27ad50100646b2696fd7a0cab8d5ce1f391730069350f6e3d76ace376e0ef696'
+ )
+ throw new Error('unexpected Safari LaunchAgent configuration')
+ return 'Safari helper architecture and LaunchAgent verified'
+ })
+
await check('external-resources', async () => {
const hostName =
target.platform === 'win32'
diff --git a/src/main/bridge/safari-bootstrap-registration.ts b/src/main/bridge/safari-bootstrap-registration.ts
index b2a4c1c1..a8bfd42d 100644
--- a/src/main/bridge/safari-bootstrap-registration.ts
+++ b/src/main/bridge/safari-bootstrap-registration.ts
@@ -53,7 +53,7 @@ export async function registerSafariBootstrap(
(async (file, args) =>
execute(file, [...args], {
encoding: 'utf8',
- timeout: 10_000,
+ timeout: 25_000,
maxBuffer: 32 * 1024,
windowsHide: true,
}))
diff --git a/tests/scripts/release-signing-input.test.ts b/tests/scripts/release-signing-input.test.ts
index 722a5645..8cac5804 100644
--- a/tests/scripts/release-signing-input.test.ts
+++ b/tests/scripts/release-signing-input.test.ts
@@ -29,6 +29,9 @@ const COMMIT = 'a'.repeat(40)
const temporaryDirectories: string[] = []
const HASH_PINNED_TEXT_SOURCES = [
'electron-builder.signing.json',
+ 'scripts/sign-macos.mjs',
+ 'build/entitlements.safari.plist',
+ 'build/app.motrix.safari.bootstrap.plist',
'build/entitlements.mac.plist',
'build/installer.nsh',
'scripts/release-signing-tool/package.json',
@@ -41,6 +44,15 @@ const HASH_PINNED_TEXT_SOURCES = [
'scripts/verify-electron-package.mjs',
] as const
const TRUSTED_FIXTURES = [
+ ['scripts/sign-macos.mjs', 'scripts/sign-macos.mjs'],
+ [
+ 'build/entitlements.safari.plist',
+ 'signing-build-resources/entitlements.safari.plist',
+ ],
+ [
+ 'build/app.motrix.safari.bootstrap.plist',
+ 'signing-build-resources/app.motrix.safari.bootstrap.plist',
+ ],
['electron-builder.signing.json', 'electron-builder.signing.json'],
['build/256x256.png', 'signing-build-resources/256x256.png'],
['build/background.tiff', 'signing-build-resources/background.tiff'],
@@ -349,6 +361,23 @@ describe('isolated release signing input', () => {
)
})
+ it.each([
+ 'scripts/sign-macos.mjs',
+ 'signing-build-resources/entitlements.safari.plist',
+ 'signing-build-resources/app.motrix.safari.bootstrap.plist',
+ ])(
+ 'rejects tampered Safari signing policy despite a rewritten manifest: %s',
+ async (relative) => {
+ const directory = await createFixture()
+ const file = path.join(directory, relative)
+ await writeFile(file, `${await readFile(file, 'utf8')}\n`)
+ await refreshManifest(directory)
+ await expect(verify(directory)).rejects.toThrow(
+ /trusted signing input digest mismatch/
+ )
+ }
+ )
+
it('rejects a staged-dependency hook whose digest changed', async () => {
const directory = await createFixture()
const hookPath = path.join(
diff --git a/tests/scripts/safari-desktop-package.test.ts b/tests/scripts/safari-desktop-package.test.ts
new file mode 100644
index 00000000..62341019
--- /dev/null
+++ b/tests/scripts/safari-desktop-package.test.ts
@@ -0,0 +1,86 @@
+import { readFileSync } from 'node:fs'
+import path from 'node:path'
+import { describe, expect, it } from 'vitest'
+// @ts-expect-error -- release signing hook is JavaScript
+import { safariSignOptions } from '../../scripts/sign-macos.mjs'
+
+describe('Safari desktop distribution', () => {
+ it('gives only the exact helper paths their dedicated entitlements and identifiers', () => {
+ const app = '/Applications/Motrix.app'
+ const fallback = () => ({
+ entitlements: 'electron.plist',
+ hardenedRuntime: true,
+ })
+ for (const [relative, identifier] of [
+ [
+ 'Contents/MacOS/MotrixSafariRegistrar',
+ 'app.motrix.safari.registration',
+ ],
+ [
+ 'Contents/Library/LaunchServices/MotrixSafariBootstrap',
+ 'app.motrix.safari.bootstrap',
+ ],
+ ]) {
+ const result = safariSignOptions(
+ app,
+ path.join(app, relative!),
+ 'safari.plist',
+ fallback
+ )
+ expect(result.entitlements).toBe('safari.plist')
+ expect(result.additionalArguments).toEqual(['--identifier', identifier])
+ expect(result.requirements).toContain('7VMB56CA56')
+ expect(result.hardenedRuntime).toBe(true)
+ }
+ for (const file of [
+ app,
+ `${app}/Contents/MacOS/Motrix`,
+ '/tmp/MotrixSafariBootstrap',
+ `${app}/Contents/Resources/MotrixSafariBootstrap`,
+ ]) {
+ expect(safariSignOptions(app, file, 'safari.plist', fallback)).toEqual(
+ fallback()
+ )
+ }
+ })
+
+ it('gives unsigned and signed release builds the same per-attempt bundle version', () => {
+ const workflow = readFileSync('.github/workflows/release.yml', 'utf8')
+ const versions = workflow.match(/-c\.mac\.bundleVersion=[^\r\n ]+/g)
+ // Match complete expressions because GitHub expressions contain spaces.
+ expect(versions).toHaveLength(2)
+ expect(
+ workflow.split(
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: literal GitHub Actions expression
+ '-c.mac.bundleVersion=${{ github.run_number }}.${{ github.run_attempt }}.0'
+ )
+ ).toHaveLength(3)
+ })
+
+ it('embeds desktop helpers in both unsigned and isolated signing packages', () => {
+ for (const name of [
+ 'electron-builder.json',
+ 'electron-builder.signing.json',
+ ]) {
+ const config = JSON.parse(readFileSync(name, 'utf8'))
+ expect(config.mac.sign).toBe('./scripts/sign-macos.mjs')
+ expect(
+ config.mac.extraFiles.map((file: { to: string }) => file.to)
+ ).toEqual([
+ 'Library/LaunchServices/MotrixSafariBootstrap',
+ 'MacOS/MotrixSafariRegistrar',
+ 'Library/LaunchAgents/app.motrix.safari.bootstrap.plist',
+ ])
+ }
+ for (const name of ['ci.yml', 'release.yml']) {
+ const workflow = readFileSync(`.github/workflows/${name}`, 'utf8')
+ expect(workflow).toContain(
+ 'swift test --package-path packages/safari-bootstrap'
+ )
+ expect(workflow).toContain(
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: literal GitHub Actions expression
+ 'pnpm run build:safari-bootstrap -- --arch ${{ matrix.arch }} --test'
+ )
+ }
+ })
+})
diff --git a/tests/scripts/verify-electron-package.test.ts b/tests/scripts/verify-electron-package.test.ts
index 8ea191d6..b1b67de7 100644
--- a/tests/scripts/verify-electron-package.test.ts
+++ b/tests/scripts/verify-electron-package.test.ts
@@ -245,6 +245,21 @@ async function createFixture(
await chmod(host, 0o755)
await chmod(finalize, 0o755)
await chmod(engine, 0o755)
+ if (target.platform === 'darwin') {
+ for (const relative of [
+ 'Contents/MacOS/MotrixSafariRegistrar',
+ 'Contents/Library/LaunchServices/MotrixSafariBootstrap',
+ ]) {
+ await chmod(await write(appDir, relative, executable), 0o755)
+ }
+ await write(
+ appDir,
+ 'Contents/Library/LaunchAgents/app.motrix.safari.bootstrap.plist',
+ await readFile(
+ path.join(process.cwd(), 'build/app.motrix.safari.bootstrap.plist')
+ )
+ )
+ }
for (const relativePath of LEGAL)
await write(resources, relativePath, relativePath)
await writeJson(
@@ -303,6 +318,17 @@ function failedCheck(report: Awaited<ReturnType<typeof verify>>, id: string) {
}
describe('post-package Electron verification', () => {
+ it.each([
+ 'Contents/MacOS/MotrixSafariRegistrar',
+ 'Contents/Library/LaunchServices/MotrixSafariBootstrap',
+ 'Contents/Library/LaunchAgents/app.motrix.safari.bootstrap.plist',
+ ])('rejects missing or tampered Safari payload: %s', async (relative) => {
+ const fixture = await createFixture()
+ await writeFile(path.join(fixture.appDir, relative), 'untrusted')
+ const report = await verify(fixture)
+ expect(report.passed).toBe(false)
+ })
+
it('normalizes Windows ASAR listings to portable archive paths', () => {
expect(
normalizeArchiveEntry(