Skip to content

Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit

feat(installer): add a small native DMG installer and updater

tememumtaza025c46339753
diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml
index 285a56f..502ed52 100644
--- a/.github/workflows/app.yml
+++ b/.github/workflows/app.yml
@@ -146,10 +146,14 @@ jobs:
- name: Run the checks that need the built app
run: make ci-checks-built
+ - name: Package the native installer
+ run: make native-installer
+
- name: Package the app bundle
run: |
mkdir -p out/artifact
ditto -c -k --keepParent out/Bridgeplay.app out/artifact/Bridgeplay.zip
+ cp out/Bridgeplay-Installer.dmg out/artifact/
- name: Upload the app bundle
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
diff --git a/Makefile b/Makefile
index d3fb076..dcb0fc0 100644
--- a/Makefile
+++ b/Makefile
@@ -798,6 +798,8 @@ app: app-payload $(ICON_CAR)
"$(APP_BUNDLE)/Contents/MacOS/BridgeplayApp"
cp -R "$$(swift build --package-path app -c release --show-bin-path)/BridgeplayApp_BridgeplayApp.bundle" \
"$(APP_BUNDLE)/Contents/Resources/"
+ cp -R "$$(swift build --package-path app -c release --show-bin-path)/BridgeplayApp_BridgeplayUI.bundle" \
+ "$(APP_BUNDLE)/Contents/Resources/"
cp -R "$(APP_BUNDLE)/Contents/Resources/BridgeplayApp_BridgeplayApp.bundle/Contents/Resources/"*.lproj \
"$(APP_BUNDLE)/Contents/Resources/"
cp "$(ICON_DIR)/Assets.car" "$(ICON_DIR)/$(ICON_NAME).icns" \
@@ -889,7 +891,7 @@ CI_CHECKS := mincheck l10ncheck \
activatecheck compatcheck compatsvc-check shortcutcheck launch-shell envcheck \
buildcheck settingscheck routecheck bridgecheck gamedrivecheck launchercheck \
seedcheck gamefixescheck padcheck np-native-tests native-shim-tests \
- app-tests game-host-check dualsense-check steam-rumble-check
+ app-tests native-installercheck game-host-check dualsense-check steam-rumble-check
# app.yml runs the checks that need the built app in its build job and the rest in a
# parallel job; both lists together are CI_CHECKS.
@@ -909,3 +911,11 @@ ci-checks:
done; \
if [ -n "$$failed" ]; then echo "==> ci-checks failed:$$failed" >&2; exit 1; fi; \
echo "==> ci-checks: all $(words $(CI_CHECKS)) checks passed"
+
+.PHONY: native-installer native-installercheck
+native-installer:
+ sh scripts/package-native-installer.sh
+
+native-installercheck:
+ sh scripts/test-native-installer.sh
+ sh scripts/test-installer-cleanup.sh
diff --git a/NOTICE b/NOTICE
index e32767c..c4f44f7 100644
--- a/NOTICE
+++ b/NOTICE
@@ -139,7 +139,7 @@ MIT licensed, see
https://github.com/sparkle-project/Sparkle/blob/2.10.0/LICENSE
The app's interface uses the Geist and Unbounded typefaces, bundled in
-app/Sources/BridgeplayApp/Resources/Fonts/ under the SIL Open Font License 1.1
+app/Sources/BridgeplayUI/Resources/Fonts/ under the SIL Open Font License 1.1
(OFL-Geist.txt, OFL-Unbounded.txt there). Game covers shown in the app are read
from the user's own Steam library cache or Steam's CDN at run time; none ship
with Bridgeplay.
diff --git a/app/Package.swift b/app/Package.swift
index 4fe3a8b..04471de 100644
--- a/app/Package.swift
+++ b/app/Package.swift
@@ -22,11 +22,10 @@ let package = Package(
targets: [
.executableTarget(
name: "BridgeplayApp",
- dependencies: [.product(name: "Sparkle", package: "Sparkle")],
+ dependencies: [.product(name: "Sparkle", package: "Sparkle"), "BridgeplayUI"],
path: "Sources/BridgeplayApp",
resources: (hasPayload ? [.copy("Resources/payload")] : []) + [
.process("Resources/Localization"),
- .copy("Resources/Fonts"),
.copy("Resources/payload.manifest"),
.copy("Resources/valve-packages.manifest"),
.copy("Resources/detour2.bin"),
@@ -75,5 +74,29 @@ let package = Package(
dependencies: ["BridgeplayApp"],
path: testsPath
),
- ] : [])
+ ] : []) + [
+ .target(
+ name: "BridgeplayUI",
+ path: "Sources/BridgeplayUI",
+ resources: [.copy("Resources/Fonts")],
+ swiftSettings: [.swiftLanguageMode(.v6)]
+ ),
+ .target(
+ name: "BridgeplayInstallerCore",
+ path: "Sources/BridgeplayInstallerCore",
+ swiftSettings: [.swiftLanguageMode(.v6)]
+ ),
+ .executableTarget(
+ name: "BridgeplayInstaller",
+ dependencies: ["BridgeplayUI", "BridgeplayInstallerCore"],
+ path: "Sources/BridgeplayInstaller",
+ resources: [.process("Resources/Localization")],
+ swiftSettings: [.swiftLanguageMode(.v6)]
+ ),
+ .testTarget(
+ name: "BridgeplayInstallerCoreTests",
+ dependencies: ["BridgeplayInstallerCore"],
+ path: "Tests/BridgeplayInstallerCoreTests"
+ ),
+ ]
)
diff --git a/app/Sources/BridgeplayApp/Views/GuideView.swift b/app/Sources/BridgeplayApp/Views/GuideView.swift
index 102a0e3..06f86a2 100644
--- a/app/Sources/BridgeplayApp/Views/GuideView.swift
+++ b/app/Sources/BridgeplayApp/Views/GuideView.swift
@@ -1,4 +1,5 @@
import SwiftUI
+import BridgeplayUI
// How to reach a game's Bridgeplay settings in Steam, and what every one of them does. The
// pictures are drawings of Steam's own screens in Steam's colours (like the ones on
diff --git a/app/Sources/BridgeplayApp/Views/PlayReportCard.swift b/app/Sources/BridgeplayApp/Views/PlayReportCard.swift
index 0f1e675..acb9ee6 100644
--- a/app/Sources/BridgeplayApp/Views/PlayReportCard.swift
+++ b/app/Sources/BridgeplayApp/Views/PlayReportCard.swift
@@ -1,4 +1,5 @@
import SwiftUI
+import BridgeplayUI
// Asks how the last game session ran. Smooth sends at once; Has Issues and Didn't Run first
// offer an optional note on what went wrong.
diff --git a/app/Sources/BridgeplayApp/Views/RootView.swift b/app/Sources/BridgeplayApp/Views/RootView.swift
index 3077dda..a4913fb 100644
--- a/app/Sources/BridgeplayApp/Views/RootView.swift
+++ b/app/Sources/BridgeplayApp/Views/RootView.swift
@@ -1,4 +1,5 @@
import SwiftUI
+import BridgeplayUI
enum Pane: String, CaseIterable, Identifiable, Hashable {
case status
diff --git a/app/Sources/BridgeplayApp/Views/SetupArt.swift b/app/Sources/BridgeplayApp/Views/SetupArt.swift
index bd6d22f..e726c6b 100644
--- a/app/Sources/BridgeplayApp/Views/SetupArt.swift
+++ b/app/Sources/BridgeplayApp/Views/SetupArt.swift
@@ -1,5 +1,6 @@
import AppKit
import SwiftUI
+import BridgeplayUI
// The Setup Assistant's art rail, in bridgeplay.dev's motifs: an aurora of the brand gradient
// over a faint grid, the hero line, and one illustration per step (the checker's scan line,
diff --git a/app/Sources/BridgeplayApp/Views/SetupAssistantView.swift b/app/Sources/BridgeplayApp/Views/SetupAssistantView.swift
index e53d5b8..c8e1884 100644
--- a/app/Sources/BridgeplayApp/Views/SetupAssistantView.swift
+++ b/app/Sources/BridgeplayApp/Views/SetupAssistantView.swift
@@ -1,5 +1,6 @@
import SwiftUI
import UniformTypeIdentifiers
+import BridgeplayUI
// First-run Setup Assistant. Built from the Status page's own pieces (a grouped Form of
// StatusRows with StatusTone dots and StatusActions) so it reads as part of the same app.
@@ -73,7 +74,7 @@ struct SetupAssistantView: View {
VStack(alignment: .leading, spacing: 14) {
content
if let message = model.message {
- Card {
+ SetupCard {
WizardRow(row: StatusRow(title: String(localized: "Something went wrong"), value: message, tone: .bad))
}
}
@@ -156,19 +157,19 @@ struct SetupAssistantView: View {
private var macStep: some View {
StepHeader(step: model.step, title: "Check your Mac",
detail: "Bridgeplay runs Windows games from your Steam library. First, a few quick checks.")
- Card {
+ SetupCard {
checked(0, StatusRow(title: String(localized: "Apple silicon"),
value: model.appleSilicon ? SetupChecks.chipName : String(localized: "Bridgeplay doesn't run on Intel Macs."),
tone: model.appleSilicon ? .ok : .bad))
- Hairline()
+ SetupHairline()
checked(1, StatusRow(title: String(localized: "macOS \(SetupChecks.minimumMacOS) or later"),
value: model.macOSSupported ? SetupChecks.macOSDisplay : String(localized: "\(SetupChecks.macOSDisplay). Update macOS first."),
tone: model.macOSSupported ? .ok : .bad))
- Hairline()
+ SetupHairline()
checked(2, StatusRow(title: String(localized: "Free space"),
value: model.freeBytes.map { String(localized: "\(ByteCountFormatter.string(fromByteCount: $0, countStyle: .file)) available, 3 GB needed") },
tone: model.hasSpace ? .ok : .bad))
- Hairline()
+ SetupHairline()
checked(3, StatusRow(title: String(localized: "Rosetta 2"),
value: model.rosettaInstalled ? String(localized: "Installed.") : String(localized: "Apple's translator for Windows games. Asks for your Mac password."),
tone: model.rosettaInstalled ? .ok : .warning,
@@ -182,7 +183,7 @@ struct SetupAssistantView: View {
private var graphicsStep: some View {
StepHeader(step: model.step, title: "Add Apple's game graphics",
detail: "Apple's Game Porting Toolkit includes D3DMetal, which runs DirectX 11 and 12 games on Metal, with MetalFX upscaling. It's free, but only Apple can hand it out, so you download it once with your Apple Account.")
- Card {
+ SetupCard {
if let gptk = model.gptk {
WizardRow(row: StatusRow(title: String(localized: "Game Porting Toolkit"),
value: String(localized: "Ready from \(gptk.libRoot.path(percentEncoded: false))."),
@@ -193,7 +194,7 @@ struct SetupAssistantView: View {
action: StatusAction(label: String(localized: "Open Apple Downloads")) {
NSWorkspace.shared.open(URL(string: "https://developer.apple.com/download/all/?q=Game%20Porting%20Toolkit")!)
}), number: 1)
- Hairline()
+ SetupHairline()
if let image = model.gptkImages.first {
WizardRow(row: StatusRow(title: String(localized: "Use the one in Downloads"),
value: image.lastPathComponent,
@@ -226,19 +227,19 @@ struct SetupAssistantView: View {
private var steamStep: some View {
StepHeader(step: model.step, title: "Sign in to Steam",
detail: "Sign in with your account in Steam. Bridgeplay continues on its own once you're in.")
- Card {
+ SetupCard {
checked(0, StatusRow(title: String(localized: "Steam"),
value: model.steamInstalled ? SupportPaths.Steam.app.path(percentEncoded: false) : String(localized: "Not installed."),
tone: model.steamInstalled ? .ok : .warning,
action: model.steamInstalled ? nil : StatusAction(
label: String(localized: "Install Steam"), isProminent: true, isEnabled: !model.isWorking
) { Task { await model.installSteam() } }))
- Hairline()
+ SetupHairline()
checked(1, StatusRow(title: String(localized: "Steam account"),
value: model.signedIn ? String(localized: "Signed in.") : String(localized: "Waiting for you to sign in. Bridgeplay never sees your password."),
tone: model.signedIn ? .ok : .info,
action: model.signedIn || !model.steamInstalled ? nil : StatusAction(label: String(localized: "Open Steam"), isProminent: true) { model.openSteam() }))
- Hairline()
+ SetupHairline()
checked(2, trustRow)
}
}
@@ -273,9 +274,9 @@ struct SetupAssistantView: View {
if model.tasks.contains(where: { $0.state != .done }) {
approvals
}
- Card {
+ SetupCard {
ForEach(Array(model.tasks.enumerated()), id: \.element.id) { index, task in
- if index > 0 { Hairline() }
+ if index > 0 { SetupHairline() }
WizardRow(row: StatusRow(title: task.title, value: value(of: task), tone: tone(of: task)),
pending: task.state == .running)
.animation(Self.rowSpring, value: task.state)
@@ -294,7 +295,7 @@ struct SetupAssistantView: View {
}
.padding(.horizontal, 2)
if model.needsAppManagement {
- Card {
+ SetupCard {
WizardRow(row: StatusRow(title: String(localized: "App Management"),
value: String(localized: "Turn on Bridgeplay in Privacy & Security › App Management. Setup continues by itself once it's on."),
tone: .warning,
@@ -311,12 +312,12 @@ struct SetupAssistantView: View {
// can change. App Management can ask too.
@ViewBuilder
private var approvals: some View {
- Card {
+ SetupCard {
if model.trust == .done {
WizardRow(row: StatusRow(title: String(localized: "Confirm the Steam update"),
value: String(localized: "macOS asks for your Mac password once, so Steam keeps working with Bridgeplay. Type it and choose Always Allow, and it won't ask again."),
tone: .info))
- Hairline()
+ SetupHairline()
}
WizardRow(row: StatusRow(title: String(localized: "Allow Bridgeplay in App Management"),
value: String(localized: "If macOS shows the switch, turn it on. Setup carries on by itself."),
@@ -329,15 +330,15 @@ struct SetupAssistantView: View {
StepHeader(step: model.step, title: "You're all set",
detail: "Open Steam, install a Windows game and press Play. Status, Prefixes and Prefix Backups in this window change engines, fix a game or undo everything.",
emphasized: true)
- Card {
+ SetupCard {
checked(0, StatusRow(title: String(localized: "Bridgeplay"), value: String(localized: "Installed into Steam."), tone: .ok))
- Hairline()
+ SetupHairline()
checked(1, StatusRow(title: String(localized: "WineCX Engine"), value: String(localized: "Steam's default for Windows games."), tone: .ok))
- Hairline()
+ SetupHairline()
checked(2, StatusRow(title: String(localized: "Game Porting Toolkit"),
value: model.gptk == nil ? String(localized: "Skipped. Games use DXMT; add it later from Status.") : String(localized: "Linked."),
tone: model.gptk == nil ? .neutral : .ok))
- Hairline()
+ SetupHairline()
checked(3, StatusRow(title: String(localized: "Controllers"),
value: String(localized: "The first time a game uses a controller, macOS asks to let Steam use Input Monitoring. Click Allow. If you missed it, turn on Steam in Input Monitoring."),
tone: .info,
@@ -348,12 +349,12 @@ struct SetupAssistantView: View {
.foregroundStyle(BP.fg)
.padding(.horizontal, 2)
.padding(.top, 8)
- Card {
+ SetupCard {
WizardRow(row: StatusRow(title: String(localized: "Metal HUD"),
value: String(localized: "Shows frame rate and GPU details in a corner while you play."),
toggle: Binding(get: { model.metalHUD }, set: { model.setGameDefault(.metalHUD, $0) })),
symbol: "gauge.with.dots.needle.33percent")
- Hairline()
+ SetupHairline()
WizardRow(row: StatusRow(title: String(localized: "High Resolution"),
value: String(localized: "Sharper on Retina displays, but games run slower."),
toggle: Binding(get: { model.highResolution }, set: { model.setGameDefault(.highResolution, $0) })),
@@ -507,23 +508,6 @@ private struct StepHeader: View {
}
}
-// .tile on the site: one raised panel, hairline border, small radius.
-private struct Card<Content: View>: View {
- @ViewBuilder let content: Content
-
- var body: some View {
- VStack(spacing: 0) { content }
- .background(BP.raise, in: RoundedRectangle(cornerRadius: BP.radius, style: .continuous))
- .overlay(RoundedRectangle(cornerRadius: BP.radius, style: .continuous).strokeBorder(BP.line, lineWidth: 1))
- }
-}
-
-private struct Hairline: View {
- var body: some View {
- Rectangle().fill(BP.line).frame(height: 1).padding(.leading, 54)
- }
-}
-
// A StatusRow's content in the wizard's style: a tone badge, the title and value, and pill
// buttons on the right.
private struct WizardRow: View {
diff --git a/app/Sources/BridgeplayApp/Views/StatusHero.swift b/app/Sources/BridgeplayApp/Views/StatusHero.swift
index 8a626c2..f77373b 100644
--- a/app/Sources/BridgeplayApp/Views/StatusHero.swift
+++ b/app/Sources/BridgeplayApp/Views/StatusHero.swift
@@ -1,4 +1,5 @@
import SwiftUI
+import BridgeplayUI
// The top of the Status page: the landing page's aurora behind one plain answer to "can I
// play?", with the engine, graphics and Steam state as chips underneath.
diff --git a/app/Sources/BridgeplayApp/Views/StatusView.swift b/app/Sources/BridgeplayApp/Views/StatusView.swift
index 885860f..d78a23e 100644
--- a/app/Sources/BridgeplayApp/Views/StatusView.swift
+++ b/app/Sources/BridgeplayApp/Views/StatusView.swift
@@ -1,4 +1,5 @@
// 'Status' view, see SystemStatus for actual logic
+import BridgeplayUI
import SwiftUI
diff --git a/app/Sources/BridgeplayInstaller/InstallerApp.swift b/app/Sources/BridgeplayInstaller/InstallerApp.swift
new file mode 100644
index 0000000..efeb58b
--- /dev/null
+++ b/app/Sources/BridgeplayInstaller/InstallerApp.swift
@@ -0,0 +1,105 @@
+import AppKit
+import SwiftUI
+import BridgeplayUI
+
+@main
+struct InstallerLaunch {
+ @MainActor
+ static func main() {
+ if InstallerCleanup.runIfRequested() { return }
+ if let index = CommandLine.arguments.firstIndex(of: "--icon"),
+ CommandLine.arguments.indices.contains(index + 1) {
+ InstallerScreenshot.icon(to: URL(fileURLWithPath: CommandLine.arguments[index + 1]))
+ return
+ }
+ if let index = CommandLine.arguments.firstIndex(of: "--screenshot"),
+ CommandLine.arguments.indices.contains(index + 1) {
+ InstallerScreenshot.render(to: URL(fileURLWithPath: CommandLine.arguments[index + 1]))
+ return
+ }
+ BridgeplayInstallerApp.main()
+ }
+}
+
+struct BridgeplayInstallerApp: App {
+ @NSApplicationDelegateAdaptor(InstallerDelegate.self) private var delegate
+ @State private var model = InstallerModel()
+
+ var body: some Scene {
+ Window("Bridgeplay Installer", id: "installer") {
+ InstallerView(model: model)
+ .onAppear { delegate.model = model }
+ .task { await model.check() }
+ .onDisappear { model.cancel() }
+ }
+ .windowResizability(.contentSize)
+ .defaultSize(width: 780, height: 580)
+ .commands {
+ CommandGroup(replacing: .newItem) {}
+ }
+ }
+}
+
+func tr(_ value: String.LocalizationValue) -> String {
+ String(localized: value, bundle: InstallerResources.bundle)
+}
+
+@MainActor
+private enum InstallerScreenshot {
+ static func icon(to output: URL) {
+ _ = NSApplication.shared
+ let host = NSHostingView(rootView: BridgeplayMark(size: 512).frame(width: 512, height: 512))
+ host.frame = NSRect(x: 0, y: 0, width: 512, height: 512)
+ host.layoutSubtreeIfNeeded()
+ guard let rep = host.bitmapImageRepForCachingDisplay(in: host.bounds) else { exit(1) }
+ host.cacheDisplay(in: host.bounds, to: rep)
+ guard let png = rep.representation(using: .png, properties: [:]) else { exit(1) }
+ do { try png.write(to: output) } catch { exit(1) }
+ }
+
+ static func render(to output: URL) {
+ _ = NSApplication.shared
+ let model = InstallerModel(preview: InstallerModel.previewArgument ?? "review")
+ let host = NSHostingView(rootView: InstallerView(model: model))
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 780, height: 580),
+ styleMask: [.borderless], backing: .buffered, defer: false)
+ window.contentView = host
+ window.appearance = NSAppearance(named: .darkAqua)
+ window.setFrameOrigin(NSPoint(x: -20_000, y: -20_000))
+ window.orderFrontRegardless()
+ RunLoop.main.run(until: Date().addingTimeInterval(0.5))
+ host.layoutSubtreeIfNeeded()
+ guard let rep = host.bitmapImageRepForCachingDisplay(in: host.bounds) else { exit(1) }
+ host.cacheDisplay(in: host.bounds, to: rep)
+ do {
+ try FileManager.default.createDirectory(at: output.deletingLastPathComponent(), withIntermediateDirectories: true)
+ guard let png = rep.representation(using: .png, properties: [:]) else { exit(1) }
+ try png.write(to: output)
+ } catch {
+ FileHandle.standardError.write(Data("\(error)\n".utf8))
+ exit(1)
+ }
+ window.orderOut(nil)
+ }
+}
+
+@MainActor
+final class InstallerDelegate: NSObject, NSApplicationDelegate {
+ var model: InstallerModel?
+ func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
+ guard model?.stage != .installing else { return .terminateCancel }
+ model?.cancel()
+ return .terminateNow
+ }
+ func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
+}
+
+enum InstallerResources {
+ static var bundle: Bundle {
+ if let resources = Bundle.main.resourceURL,
+ let packaged = Bundle(url: resources.appendingPathComponent("BridgeplayApp_BridgeplayInstaller.bundle")) {
+ return packaged
+ }
+ return .module
+ }
+}
diff --git a/app/Sources/BridgeplayInstaller/InstallerCleanup.swift b/app/Sources/BridgeplayInstaller/InstallerCleanup.swift
new file mode 100644
index 0000000..34b8f44
--- /dev/null
+++ b/app/Sources/BridgeplayInstaller/InstallerCleanup.swift
@@ -0,0 +1,136 @@
+import AppKit
+import Foundation
+import Darwin
+
+@MainActor
+enum InstallerCleanup {
+ struct Source: Codable, Equatable {
+ let image: URL
+ let device: String
+ let inode: UInt64
+ let filesystem: Int32
+ }
+
+ static func source() throws -> Source? {
+ guard let executable = Bundle.main.executableURL else { return nil }
+ return try source(containing: executable, info: diskImages())
+ }
+
+ static func source(containing executable: URL, info: Data) throws -> Source? {
+ let plist = try PropertyListSerialization.propertyList(from: info, format: nil)
+ guard let images = (plist as? [String: Any])?["images"] as? [[String: Any]] else { return nil }
+ let executablePath = executable.resolvingSymlinksInPath().path
+ for item in images {
+ guard let path = item["image-path"] as? String,
+ let entities = item["system-entities"] as? [[String: Any]] else { continue }
+ for entity in entities {
+ guard let mount = entity["mount-point"] as? String,
+ let device = entity["dev-entry"] as? String,
+ mount != "/", executablePath.hasPrefix(mount + "/"),
+ device.range(of: #"^/dev/disk[0-9]+(s[0-9]+)*$"#, options: .regularExpression) != nil else { continue }
+ let image = URL(fileURLWithPath: path)
+ guard image.pathExtension.lowercased() == "dmg", let identity = identity(image) else { continue }
+ return Source(image: image, device: device, inode: identity.st_ino, filesystem: identity.st_dev)
+ }
+ }
+ return nil
+ }
+
+ static func schedule(_ source: Source) throws {
+ guard let executable = Bundle.main.executableURL,
+ let current = try self.source(), current == source else {
+ throw CocoaError(.fileReadUnknown)
+ }
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent("bridgeplay-cleanup-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ do {
+ let helper = folder.appendingPathComponent("BridgeplayCleanup")
+ try FileManager.default.copyItem(at: executable, to: helper)
+ let resources = InstallerResources.bundle.bundleURL
+ try FileManager.default.copyItem(at: resources, to: folder.appendingPathComponent(resources.lastPathComponent))
+ let process = Process()
+ process.currentDirectoryURL = folder
+ process.executableURL = helper
+ process.arguments = ["--cleanup", try JSONEncoder().encode(source).base64EncodedString(), String(getpid())]
+ try process.run()
+ } catch {
+ try? FileManager.default.removeItem(at: folder)
+ throw error
+ }
+ }
+
+ static func runIfRequested() -> Bool {
+ let args = CommandLine.arguments
+ guard args.count > 1, args[1] == "--cleanup" else { return false }
+ guard args.count == 4, args[2].count < 16_384,
+ let bytes = Data(base64Encoded: args[2]),
+ let source = try? JSONDecoder().decode(Source.self, from: bytes),
+ let parent = Int32(args[3]), parent > 1 else { return true }
+ let ownDirectory = Bundle.main.executableURL?.deletingLastPathComponent()
+ defer {
+ if let ownDirectory,
+ ownDirectory.lastPathComponent.hasPrefix("bridgeplay-cleanup-"),
+ ownDirectory.deletingLastPathComponent().standardizedFileURL == FileManager.default.temporaryDirectory.standardizedFileURL {
+ try? FileManager.default.removeItem(at: ownDirectory)
+ }
+ }
+ do {
+ for _ in 0..<300 {
+ if kill(parent, 0) != 0 { break }
+ Thread.sleep(forTimeInterval: 0.2)
+ }
+ guard kill(parent, 0) != 0 else { throw CocoaError(.fileWriteFileExists) }
+ guard let before = identity(source.image), before.st_ino == source.inode,
+ before.st_dev == source.filesystem else { throw CocoaError(.fileReadUnknown) }
+ let info = try diskImages()
+ guard mounted(source, info: info) else { throw CocoaError(.fileReadUnknown) }
+ try run("/usr/bin/hdiutil", ["detach", source.device])
+ guard let after = identity(source.image), after.st_ino == source.inode,
+ after.st_dev == source.filesystem else { throw CocoaError(.fileReadUnknown) }
+ try FileManager.default.trashItem(at: source.image, resultingItemURL: nil)
+ } catch {
+ _ = NSApplication.shared
+ let alert = NSAlert()
+ alert.messageText = tr("Installer cleanup could not finish")
+ alert.informativeText = tr("Bridgeplay is installed. You can eject the installer and move its DMG to Trash in Finder.") + "\n\n" + error.localizedDescription
+ alert.addButton(withTitle: tr("OK"))
+ alert.runModal()
+ }
+ return true
+ }
+
+ private static func mounted(_ source: Source, info: Data) -> Bool {
+ guard let plist = try? PropertyListSerialization.propertyList(from: info, format: nil),
+ let images = (plist as? [String: Any])?["images"] as? [[String: Any]] else { return false }
+ return images.contains { item in
+ guard let path = item["image-path"] as? String,
+ URL(fileURLWithPath: path) == source.image,
+ let entities = item["system-entities"] as? [[String: Any]] else { return false }
+ return entities.contains { ($0["dev-entry"] as? String) == source.device && $0["mount-point"] != nil }
+ }
+ }
+
+ private static func identity(_ url: URL) -> stat? {
+ var info = stat()
+ guard url.isFileURL, url.pathExtension.lowercased() == "dmg",
+ lstat(url.path, &info) == 0, info.st_mode & S_IFMT == S_IFREG else { return nil }
+ return info
+ }
+
+ private static func diskImages() throws -> Data { try run("/usr/bin/hdiutil", ["info", "-plist"]) }
+
+ @discardableResult
+ private static func run(_ executable: String, _ args: [String]) throws -> Data {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: executable)
+ process.arguments = args
+ let pipe = Pipe()
+ process.standardOutput = pipe
+ process.standardError = FileHandle.nullDevice
+ try process.run()
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ guard process.terminationStatus == 0 else { throw CocoaError(.fileWriteUnknown) }
+ return data
+ }
+}
diff --git a/app/Sources/BridgeplayInstaller/InstallerMessage.swift b/app/Sources/BridgeplayInstaller/InstallerMessage.swift
new file mode 100644
index 0000000..df4aa91
--- /dev/null
+++ b/app/Sources/BridgeplayInstaller/InstallerMessage.swift
@@ -0,0 +1,25 @@
+import Foundation
+import BridgeplayInstallerCore
+
+enum InstallerMessage {
+ static func describe(_ error: Error) -> String {
+ guard let error = error as? InstallerError else { return error.localizedDescription }
+ switch error {
+ case .invalidRelease: return tr("The release information is invalid. Try again later.")
+ case .networkFailure: return tr("Could not reach the release server. Check your connection and try again.")
+ case .invalidDestination: return tr("The application location is not safe to update.")
+ case .archiveTooLarge, .invalidArchiveLength: return tr("The download is incomplete or has an unexpected size. Try again.")
+ case .signatureMismatch: return tr("The download could not be verified. Your installed application has been kept.")
+ case .writeFailure: return tr("The download could not be saved. Check available space and folder permissions.")
+ case .unsupportedSystem: return tr("This release requires a newer macOS version or an Apple silicon Mac.")
+ case .invalidInstallation: return tr("The existing application could not be read. Check the application in Finder before trying again.")
+ case .otherAppInstalled: return tr("Another application already uses the install location. Move it in Finder before trying again.")
+ case .downgrade: return tr("A newer Bridgeplay build is already installed. It has been kept.")
+ case .alreadyCurrent: return tr("This Bridgeplay version is already installed. Check again to continue.")
+ case .appIsRunning: return tr("Quit Bridgeplay and its updater, then try again.")
+ case .installLocked: return tr("Another installation is in progress, or the installer lock cannot be accessed. Try again after it finishes.")
+ case .appValidation: return tr("The downloaded application did not pass validation. Your installed application has been kept.")
+ case .replacementFailure: return tr("The application could not be replaced. Check the app and its previous-version backup in Applications before trying again.")
+ }
+ }
+}
diff --git a/app/Sources/BridgeplayInstaller/InstallerModel.swift b/app/Sources/BridgeplayInstaller/InstallerModel.swift
new file mode 100644
index 0000000..1ed16ac
--- /dev/null
+++ b/app/Sources/BridgeplayInstaller/InstallerModel.swift
@@ -0,0 +1,166 @@
+import AppKit
+import Foundation
+import Observation
+import BridgeplayInstallerCore
+
+@MainActor
+@Observable
+final class InstallerModel {
+ enum Stage: Int { case checking, review, downloading, installing, done, failed }
+ var stage: Stage = .checking
+ var version = ""
+ var installedVersion: String?
+ var isCurrent = false
+ var progress: Double?
+ var received: Int64 = 0
+ var total: Int64?
+ var failure: String?
+ var openBridgeplay = true
+ var removeInstaller = true
+ var finishing = false
+ let preview: String?
+ private var release: InstallerRelease?
+ private var operation: Task<Void, Never>?
+ private let service: InstallerService
+ var destination: URL { service.destination }
+ private(set) var cleanupSource: InstallerCleanup.Source?
+
+ static var previewArgument: String? {
+ let args = CommandLine.arguments
+ guard let index = args.firstIndex(of: "--preview"), args.indices.contains(index + 1) else { return nil }
+ return args[index + 1]
+ }
+
+ private static var destinationArgument: URL {
+ #if DEBUG
+ let args = CommandLine.arguments
+ if let index = args.firstIndex(of: "--test-destination"), args.indices.contains(index + 1) {
+ let value = URL(fileURLWithPath: args[index + 1]).standardizedFileURL
+ let temp = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().path
+ if value.lastPathComponent == "Bridgeplay.app",
+ value.deletingLastPathComponent().resolvingSymlinksInPath().path.hasPrefix(temp + "/") { return value }
+ fatalError("Test destination must be Bridgeplay.app inside the temporary directory.")
+ }
+ #endif
+ return URL(fileURLWithPath: "/Applications/Bridgeplay.app")
+ }
+
+ init(preview: String? = InstallerModel.previewArgument) {
+ self.preview = preview
+ self.service = InstallerService(destination: Self.destinationArgument)
+ if let preview {
+ version = "3.4.1"
+ switch preview {
+ case "update": installedVersion = "3.3.0"; stage = .review
+ case "current": installedVersion = version; isCurrent = true; stage = .done
+ case "download": stage = .downloading; received = 31_659_404; total = 79_148_511; progress = 0.4
+ case "install": stage = .installing
+ case "done": stage = .done
+ case "error": stage = .failed; failure = tr("The download could not be verified. Your installed application has been kept.")
+ default: stage = .review
+ }
+ } else {
+ cleanupSource = try? InstallerCleanup.source()
+ }
+ }
+
+ var busy: Bool { stage == .checking || stage == .downloading || stage == .installing || finishing }
+ var updating: Bool { installedVersion != nil }
+ var step: Int {
+ switch stage { case .checking: 0; case .review, .failed: 1; case .downloading, .installing: 2; case .done: 3 }
+ }
+
+ func check() async {
+ guard preview == nil else { return }
+ stage = .checking
+ failure = nil
+ do {
+ let service = self.service
+ try await Task.detached(priority: .userInitiated) { try service.recoverIfNeeded() }.value
+ try Task.checkCancellation()
+ let fetched = try await InstallerRelease.latest()
+ try Task.checkCancellation()
+ release = fetched
+ version = fetched.shortVersion
+ total = fetched.archiveLength
+ let state = try service.state(for: fetched)
+ switch state {
+ case .notInstalled: installedVersion = nil; stage = .review
+ case .updateAvailable(_, let current, _): installedVersion = current; stage = .review
+ case .upToDate(_, let current): installedVersion = current; version = current; isCurrent = true; stage = .done
+ }
+ } catch is CancellationError {
+ stage = .review
+ } catch { fail(error) }
+ }
+
+ func start() {
+ guard operation == nil, let release, preview == nil else { return }
+ operation = Task {
+ defer { operation = nil }
+ stage = .downloading
+ failure = nil
+ received = 0
+ progress = nil
+ let work = FileManager.default.temporaryDirectory.appendingPathComponent("bridgeplay-install-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: work) }
+ do {
+ try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)
+ let archive = try await release.download(to: work) { [weak self] value in
+ Task { @MainActor in
+ guard let self, self.stage == .downloading else { return }
+ self.received = value.received
+ self.total = value.total
+ self.progress = value.total.flatMap { $0 > 0 ? Double(value.received) / Double($0) : nil }
+ }
+ }
+ try Task.checkCancellation()
+ stage = .installing
+ progress = nil
+ let service = self.service
+ _ = try await Task.detached(priority: .userInitiated) {
+ try service.install(release: release, archive: archive)
+ }.value
+ stage = .done
+ } catch is CancellationError {
+ stage = .review
+ } catch { fail(error) }
+ }
+ }
+
+ func cancel() {
+ guard stage != .installing else { return }
+ operation?.cancel()
+ }
+
+ func retry() {
+ guard !busy else { return }
+ operation = Task { await check(); operation = nil }
+ }
+
+ func finish() {
+ guard preview == nil, stage == .done, !finishing else { return }
+ finishing = true
+ if openBridgeplay {
+ let config = NSWorkspace.OpenConfiguration()
+ NSWorkspace.shared.openApplication(at: destination, configuration: config) { _, error in
+ Task { @MainActor in
+ if let error { self.failure = error.localizedDescription; self.finishing = false }
+ else { self.finishCleanup() }
+ }
+ }
+ } else { finishCleanup() }
+ }
+
+ private func finishCleanup() {
+ do {
+ if removeInstaller, let cleanupSource { try InstallerCleanup.schedule(cleanupSource) }
+ NSApplication.shared.terminate(nil)
+ } catch { failure = error.localizedDescription; finishing = false }
+ }
+
+ private func fail(_ error: Error) {
+ failure = InstallerMessage.describe(error)
+ stage = .failed
+ }
+}
diff --git a/app/Sources/BridgeplayInstaller/InstallerView.swift b/app/Sources/BridgeplayInstaller/InstallerView.swift
new file mode 100644
index 0000000..89589d7
--- /dev/null
+++ b/app/Sources/BridgeplayInstaller/InstallerView.swift
@@ -0,0 +1,215 @@
+import SwiftUI
+import BridgeplayUI
+
+struct InstallerView: View {
+ @Bindable var model: InstallerModel
+
+ private var title: String {
+ switch model.stage {
+ case .checking: tr("Check your installation")
+ case .review: model.updating ? tr("Update Bridgeplay") : tr("Install Bridgeplay")
+ case .downloading: tr("Downloading Bridgeplay")
+ case .installing: tr("Installing Bridgeplay")
+ case .done: model.isCurrent ? tr("Bridgeplay is up to date") : tr("Bridgeplay is ready")
+ case .failed: tr("Installation could not continue")
+ }
+ }
+
+ var body: some View {
+ HStack(spacing: 0) {
+ rail.frame(width: 240)
+ Rectangle().fill(BP.line).frame(width: 1)
+ VStack(spacing: 0) {
+ steps.padding(.horizontal, 28).padding(.top, 26).padding(.bottom, 4)
+ ScrollView {
+ VStack(alignment: .leading, spacing: 18) {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(tr("Bridgeplay Installer")).font(BP.sans(11, .semibold))
+ .tracking(0.9).textCase(.uppercase).foregroundStyle(BP.fg3)
+ Text(title).font(BP.sans(28, .semibold)).tracking(-0.9)
+ Text(detail).font(BP.sans(14)).foregroundStyle(BP.fg2)
+ .lineSpacing(2).fixedSize(horizontal: false, vertical: true)
+ }
+ content
+ if let failure = model.failure {
+ SetupCard {
+ Label {
+ VStack(alignment: .leading, spacing: 5) {
+ Text(tr("Something went wrong")).font(BP.sans(13, .semibold))
+ Text(failure).font(BP.sans(12)).foregroundStyle(BP.fg2)
+ .textSelection(.enabled)
+ }
+ } icon: { Image(systemName: "exclamationmark.circle").foregroundStyle(BP.orange) }
+ .padding(16).frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+ }
+ .padding(.horizontal, 28).padding(.top, 20).padding(.bottom, 24)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .scrollIndicators(.never)
+ Rectangle().fill(BP.line).frame(height: 1)
+ footer.padding(.horizontal, 24).padding(.vertical, 14)
+ }
+ }
+ .frame(width: 780, height: 580)
+ .background(BP.bg).foregroundStyle(BP.fg)
+ .environment(\.colorScheme, .dark).tint(BP.blue)
+ .onChange(of: model.stage) {
+ for window in NSApplication.shared.windows {
+ window.standardWindowButton(.closeButton)?.isEnabled = model.stage != .installing
+ }
+ }
+ }
+
+ private var detail: String {
+ switch model.stage {
+ case .checking: tr("Checking the latest release and the application on this Mac.")
+ case .review: tr("The application goes in Applications. Your settings, game prefixes and saves are kept.")
+ case .downloading: tr("Only the application is downloaded here. Its signature is checked before installation.")
+ case .installing: tr("Verifying and replacing the application. Please keep the installer open.")
+ case .done: tr("Open Bridgeplay to continue setup or check its Status page for component updates. Engine and graphics downloads are handled there.")
+ case .failed: tr("Review the details below, then try again. The installer does not remove your game data.")
+ }
+ }
+
+ private var rail: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 9) {
+ BridgeplayMark(size: 22)
+ Text(verbatim: "Bridgeplay").font(BP.display(13)).foregroundStyle(BP.iridescent)
+ }
+ .padding(22)
+ Spacer()
+ BridgeplayMark(size: 136).frame(maxWidth: .infinity)
+ Spacer()
+ VStack(alignment: .leading, spacing: 2) {
+ Text(tr("Windows games.")).foregroundStyle(BP.fg)
+ Text(tr("In your Mac's Steam.")).foregroundStyle(BP.iridescent)
+ }
+ .font(BP.sans(19, .semibold)).tracking(-0.5).padding(24)
+ }
+ .background(BP.bg)
+ }
+
+ private var steps: some View {
+ let names = [tr("Check"), tr("Review"), tr("Install"), tr("Finish")]
+ return VStack(spacing: 8) {
+ ZStack {
+ HStack(spacing: 6) {
+ ForEach(0..<4) { _ in Capsule().fill(BP.raise2) }
+ }
+ BP.iridescent.mask {
+ HStack(spacing: 6) {
+ ForEach(0..<4) { index in Capsule().fill(index <= model.step ? Color.white : .clear) }
+ }
+ }
+ }.frame(height: 3)
+ HStack(spacing: 6) {
+ ForEach(0..<4) { index in
+ Text(names[index]).font(BP.sans(11, index == model.step ? .semibold : .medium))
+ .foregroundStyle(index == model.step ? BP.fg : BP.fg3)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+ }
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(names[model.step])
+ }
+
+ @ViewBuilder
+ private var content: some View {
+ switch model.stage {
+ case .checking:
+ ProgressView().controlSize(.small).frame(maxWidth: .infinity).padding(24)
+ case .review:
+ SetupCard {
+ row(tr("Version"), value: model.version, icon: "arrow.down.circle")
+ if let installed = model.installedVersion {
+ SetupHairline()
+ row(tr("Installed"), value: installed, icon: "checkmark.circle")
+ }
+ SetupHairline()
+ row(tr("Location"), value: model.destination.path, icon: "folder")
+ if let total = model.total {
+ SetupHairline()
+ row(tr("Download"), value: bytes(total), icon: "network")
+ }
+ }
+ Text(tr("Close Bridgeplay before updating. Steam setup and any required permissions are handled by Bridgeplay after installation."))
+ .font(BP.sans(12)).foregroundStyle(BP.fg3).fixedSize(horizontal: false, vertical: true)
+ case .downloading, .installing:
+ SetupCard {
+ VStack(alignment: .leading, spacing: 14) {
+ HStack(spacing: 10) {
+ ProgressView().controlSize(.small)
+ Text(model.stage == .downloading ? tr("Downloading") : tr("Verifying and installing"))
+ .font(BP.sans(13, .semibold))
+ }
+ if model.stage == .downloading {
+ if let value = model.progress {
+ ProgressView(value: min(max(value, 0), 1)).tint(BP.blue)
+ } else { ProgressView().progressViewStyle(.linear).tint(BP.blue) }
+ Text(model.total.map { "\(bytes(model.received)) / \(bytes($0))" } ?? bytes(model.received))
+ .font(BP.sans(12)).monospacedDigit().foregroundStyle(BP.fg2)
+ }
+ }
+ .padding(18).frame(maxWidth: .infinity, alignment: .leading)
+ }
+ case .done:
+ SetupCard {
+ row(tr("Version"), value: model.version, icon: "checkmark.circle.fill")
+ SetupHairline()
+ row(tr("Game data"), value: tr("Kept in place"), icon: "externaldrive")
+ }
+ Toggle(tr("Open Bridgeplay"), isOn: $model.openBridgeplay).font(BP.sans(13))
+ Toggle(tr("Eject installer and move DMG to Trash"), isOn: $model.removeInstaller)
+ .font(BP.sans(13)).disabled(model.cleanupSource == nil)
+ if model.cleanupSource == nil {
+ Text(tr("The source DMG could not be identified. You can eject it and move it to Trash in Finder."))
+ .font(BP.sans(12)).foregroundStyle(BP.fg3).fixedSize(horizontal: false, vertical: true)
+ }
+ case .failed: EmptyView()
+ }
+ }
+
+ private func row(_ label: String, value: String, icon: String) -> some View {
+ HStack(alignment: .top, spacing: 12) {
+ Image(systemName: icon).foregroundStyle(BP.blue).frame(width: 20)
+ VStack(alignment: .leading, spacing: 4) {
+ Text(label).font(BP.sans(13, .semibold))
+ Text(value).font(BP.sans(12)).foregroundStyle(BP.fg2).textSelection(.enabled)
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(16).frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ private var footer: some View {
+ HStack {
+ if model.stage != .installing && model.stage != .done {
+ Button(tr("Cancel")) {
+ model.cancel()
+ if model.preview == nil { NSApplication.shared.terminate(nil) }
+ }
+ .buttonStyle(.pillPlain).keyboardShortcut(.cancelAction)
+ }
+ Spacer()
+ switch model.stage {
+ case .review:
+ Button(model.updating ? tr("Update") : tr("Install")) { model.start() }
+ .buttonStyle(.pillLarge).keyboardShortcut(.defaultAction)
+ case .failed:
+ Button(tr("Try Again")) { model.retry() }.buttonStyle(.pillLarge).keyboardShortcut(.defaultAction)
+ case .done:
+ Button(tr("Finish")) { model.finish() }.buttonStyle(.pillLarge)
+ .disabled(model.finishing).keyboardShortcut(.defaultAction)
+ default: EmptyView()
+ }
+ }
+ }
+
+ private func bytes(_ value: Int64) -> String {
+ ByteCountFormatter.string(fromByteCount: value, countStyle: .file)
+ }
+}
diff --git a/app/Sources/BridgeplayInstaller/Resources/Localization/Localizable.xcstrings b/app/Sources/BridgeplayInstaller/Resources/Localization/Localizable.xcstrings
new file mode 100644
index 0000000..f0c1873
--- /dev/null
+++ b/app/Sources/BridgeplayInstaller/Resources/Localization/Localizable.xcstrings
@@ -0,0 +1,969 @@
+{
+ "sourceLanguage": "en",
+ "strings": {
+ "Bridgeplay Installer": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Installatore Bridgeplay"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Program Installer Bridgeplay"
+ }
+ }
+ }
+ },
+ "Bridgeplay is installed. You can eject the installer and move its DMG to Trash in Finder.": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Bridgeplay è installato. Puoi espellere il programma di installazione e spostare il DMG nel Cestino dal Finder."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Bridgeplay 已安装。你可以在 Finder 中推出安装器并将 DMG 移到废纸篓。"
+ }
+ }
+ }
+ },
+ "Bridgeplay is ready": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Bridgeplay è pronto"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Bridgeplay 已就绪"
+ }
+ }
+ }
+ },
+ "Bridgeplay is up to date": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Bridgeplay è aggiornato"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Bridgeplay 已是最新版本"
+ }
+ }
+ }
+ },
+ "Cancel": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Annulla"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "取消"
+ }
+ }
+ }
+ },
+ "Check": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Verifica"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "检查"
+ }
+ }
+ }
+ },
+ "Check your installation": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Controlla l'installazione"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "检查安装状态"
+ }
+ }
+ }
+ },
+ "Checking the latest release and the application on this Mac.": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Controllo l'ultima versione e l'applicazione su questo Mac."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "正在检查最新版本以及这台 Mac 上的应用程序。"
+ }
+ }
+ }
+ },
+ "Close Bridgeplay before updating. Steam setup and any required permissions are handled by Bridgeplay after installation.": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Chiudi Bridgeplay prima di aggiornare. Dopo l'installazione, Bridgeplay configurerà Steam e richiederà le autorizzazioni necessarie."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "更新前请先退出 Bridgeplay。安装后,Bridgeplay 会配置 Steam 并请求所需权限。"
+ }
+ }
+ }
+ },
+ "Download": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Download"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "下载"
+ }
+ }
+ }
+ },
+ "Downloading": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Download in corso"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "正在下载"
+ }
+ }
+ }
+ },
+ "Downloading Bridgeplay": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Download di Bridgeplay"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "正在下载 Bridgeplay"
+ }
+ }
+ }
+ },
+ "Eject installer and move DMG to Trash": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Espelli il programma di installazione e sposta il DMG nel Cestino"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "推出安装器并将 DMG 移到废纸篓"
+ }
+ }
+ }
+ },
+ "Finish": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Fine"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "完成"
+ }
+ }
+ }
+ },
+ "Game data": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Dati di gioco"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "游戏数据"
+ }
+ }
+ }
+ },
+ "In your Mac's Steam.": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nel tuo Steam sul Mac."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "在 Mac 的 Steam 中畅玩。"
+ }
+ }
+ }
+ },
+ "Install": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Installa"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "安装"
+ }
+ }
+ }
+ },
+ "Install Bridgeplay": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Installa Bridgeplay"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "安装 Bridgeplay"
+ }
+ }
+ }
+ },
+ "Installation could not continue": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Impossibile continuare l'installazione"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "无法继续安装"
+ }
+ }
+ }
+ },
+ "Installed": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Installato"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "已安装版本"
+ }
+ }
+ }
+ },
+ "Installer cleanup could not finish": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Impossibile completare la pulizia del programma di installazione"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "无法完成安装器清理"
+ }
+ }
+ }
+ },
+ "Installing Bridgeplay": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Installazione di Bridgeplay"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "正在安装 Bridgeplay"
+ }
+ }
+ }
+ },
+ "Kept in place": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Conservati"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "已保留"
+ }
+ }
+ }
+ },
+ "Location": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Posizione"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "位置"
+ }
+ }
+ }
+ },
+ "OK": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "OK"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "好"
+ }
+ }
+ }
+ },
+ "Only the application is downloaded here. Its signature is checked before installation.": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Qui viene scaricata solo l'applicazione. La firma viene verificata prima dell'installazione."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "此处只会下载应用程序,并在安装前验证其签名。"
+ }
+ }
+ }
+ },
+ "Open Bridgeplay": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Apri Bridgeplay"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "打开 Bridgeplay"
+ }
+ }
+ }
+ },
+ "Open Bridgeplay to continue setup or check its Status page for component updates. Engine and graphics downloads are handled there.": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Apri Bridgeplay per continuare la configurazione o controllare gli aggiornamenti dei componenti nella pagina Stato. Da lì puoi scaricare motore e grafica."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "打开 Bridgeplay 继续设置,或在“状态”页面检查组件更新。你可以在那里下载引擎和图形组件。"
+ }
+ }
+ }
+ },
+ "Review": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Riepilogo"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "确认"
+ }
+ }
+ }
+ },
+ "Review the details below, then try again. The installer does not remove your game data.": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Controlla i dettagli qui sotto e riprova. Il programma di installazione non rimuove i dati di gioco."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "请查看下方详情后重试。安装器不会删除你的游戏数据。"
+ }
+ }
+ }
+ },
+ "Something went wrong": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Si è verificato un problema"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "出了点问题"
+ }
+ }
+ }
+ },
+ "The application goes in Applications. Your settings, game prefixes and saves are kept.": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "L'applicazione viene installata in Applicazioni. Le impostazioni, i prefissi di gioco e i salvataggi vengono mantenuti."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "应用程序将安装到“应用程序”文件夹。你的设置、游戏前缀和存档都会保留。"
+ }
+ }
+ }
+ },
+ "The download could not be verified. Your installed application has been kept.": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Impossibile verificare il download. L'applicazione installata è stata conservata."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "无法验证下载文件。已保留当前安装的应用程序。"
+ }
+ }
+ }
+ },
+ "The source DMG could not be identified. You can eject it and move it to Trash in Finder.": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Impossibile identificare il DMG di origine. Puoi espellerlo e spostarlo nel Cestino dal Finder."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "无法识别来源 DMG。你可以在 Finder 中将其推出并移到废纸篓。"
+ }
+ }
+ }
+ },
+ "Try Again": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Riprova"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "重试"
+ }
+ }
+ }
+ },
+ "Update": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aggiorna"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "更新"
+ }
+ }
+ }
+ },
+ "Update Bridgeplay": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aggiorna Bridgeplay"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "更新 Bridgeplay"
+ }
+ }
+ }
+ },
+ "Verifying and installing": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Verifica e installazione"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "正在验证并安装"
+ }
+ }
+ }
+ },
+ "Verifying and replacing the application. Please keep the installer open.": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Verifica e sostituzione dell'applicazione. Tieni aperto il programma di installazione."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "正在验证并替换应用程序。请保持安装器打开。"
+ }
+ }
+ }
+ },
+ "Version": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Versione"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "版本"
+ }
+ }
+ }
+ },
+ "Windows games.": {
+ "localizations": {
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Giochi Windows."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "畅玩 Windows 游戏。"
+ }
+ }
+ }
+ },
+ "The release information is invalid. Try again later.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "The release information is invalid. Try again later."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le informazioni sulla versione non sono valide. Riprova più tardi."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "版本信息无效。请稍后重试。"
+ }
+ }
+ }
+ },
+ "Could not reach the release server. Check your connection and try again.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Could not reach the release server. Check your connection and try again."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Impossibile raggiungere il server delle versioni. Controlla la connessione e riprova."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "无法连接到版本服务器。请检查网络连接后重试。"
+ }
+ }
+ }
+ },
+ "The application location is not safe to update.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "The application location is not safe to update."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Il percorso dell’applicazione non può essere aggiornato in sicurezza."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "无法安全更新此应用位置。"
+ }
+ }
+ }
+ },
+ "The download is incomplete or has an unexpected size. Try again.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "The download is incomplete or has an unexpected size. Try again."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Il download è incompleto o ha dimensioni inattese. Riprova."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "下载不完整或大小不符合预期。请重试。"
+ }
+ }
+ }
+ },
+ "The download could not be saved. Check available space and folder permissions.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "The download could not be saved. Check available space and folder permissions."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Impossibile salvare il download. Controlla lo spazio disponibile e i permessi della cartella."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "无法保存下载内容。请检查可用空间和文件夹权限。"
+ }
+ }
+ }
+ },
+ "This release requires a newer macOS version or an Apple silicon Mac.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This release requires a newer macOS version or an Apple silicon Mac."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Questa versione richiede una versione più recente di macOS o un Mac con chip Apple."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "此版本需要更新的 macOS 或搭载 Apple 芯片的 Mac。"
+ }
+ }
+ }
+ },
+ "The existing application could not be read. Check the application in Finder before trying again.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "The existing application could not be read. Check the application in Finder before trying again."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Impossibile leggere l’applicazione esistente. Controllala nel Finder prima di riprovare."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "无法读取现有应用。请在访达中检查该应用后重试。"
+ }
+ }
+ }
+ },
+ "Another application already uses the install location. Move it in Finder before trying again.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Another application already uses the install location. Move it in Finder before trying again."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Un’altra applicazione occupa già il percorso di installazione. Spostala nel Finder prima di riprovare."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "安装位置已有其他应用。请在访达中将其移走后重试。"
+ }
+ }
+ }
+ },
+ "A newer Bridgeplay build is already installed. It has been kept.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "A newer Bridgeplay build is already installed. It has been kept."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "È già installata una build più recente di Bridgeplay. È stata mantenuta."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "已安装更新的 Bridgeplay 构建版本,现有版本已保留。"
+ }
+ }
+ }
+ },
+ "This Bridgeplay version is already installed. Check again to continue.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This Bridgeplay version is already installed. Check again to continue."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Questa versione di Bridgeplay è già installata. Controlla di nuovo per continuare."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "此 Bridgeplay 版本已安装。请重新检查以继续。"
+ }
+ }
+ }
+ },
+ "Quit Bridgeplay and its updater, then try again.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Quit Bridgeplay and its updater, then try again."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Chiudi Bridgeplay e il suo programma di aggiornamento, poi riprova."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "请退出 Bridgeplay 及其更新程序后重试。"
+ }
+ }
+ }
+ },
+ "Another installation is in progress, or the installer lock cannot be accessed. Try again after it finishes.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Another installation is in progress, or the installer lock cannot be accessed. Try again after it finishes."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "È in corso un’altra installazione o non è possibile accedere al blocco del programma di installazione. Riprova al termine."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "另一个安装正在进行,或无法访问安装锁。请在安装结束后重试。"
+ }
+ }
+ }
+ },
+ "The downloaded application did not pass validation. Your installed application has been kept.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "The downloaded application did not pass validation. Your installed application has been kept."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "L’applicazione scaricata non ha superato la verifica. L’applicazione installata è stata mantenuta."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "下载的应用未通过验证。现有应用已保留。"
+ }
+ }
+ }
+ },
+ "The application could not be replaced. Check the app and its previous-version backup in Applications before trying again.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "The application could not be replaced. Check the app and its previous-version backup in Applications before trying again."
+ }
+ },
+ "it": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Impossibile sostituire l’applicazione. Controlla l’app e il backup della versione precedente in Applicazioni prima di riprovare."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "无法替换应用。请在“应用程序”中检查应用及其旧版本备份后重试。"
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/app/Sources/BridgeplayInstallerCore/InstallerRelease.swift b/app/Sources/BridgeplayInstallerCore/InstallerRelease.swift
new file mode 100644
index 0000000..6dbf27e
--- /dev/null
+++ b/app/Sources/BridgeplayInstallerCore/InstallerRelease.swift
@@ -0,0 +1,378 @@
+import CryptoKit
+import Foundation
+
+public struct InstallerDownloadProgress: Sendable, Equatable {
+ public let received: Int64
+ public let total: Int64?
+
+ public init(received: Int64, total: Int64?) {
+ self.received = received
+ self.total = total
+ }
+}
+
+/// A Bridgeplay release whose archive is authenticated by the public key shipped in the app.
+public struct InstallerRelease: Sendable, Equatable {
+ public static let appcastURL = URL(
+ string: "https://github.com/raymondchins/Bridgeplay/releases/latest/download/appcast.xml"
+ )!
+
+ public let build: Int
+ public let shortVersion: String
+ public let minimumOS: String
+ public let archiveURL: URL
+ public let archiveLength: Int64
+ public let signature: Data
+ let verificationKey: Data
+
+ public init(
+ build: Int,
+ shortVersion: String,
+ minimumOS: String,
+ archiveURL: URL,
+ archiveLength: Int64,
+ signature: Data
+ ) throws {
+ try self.init(
+ build: build,
+ shortVersion: shortVersion,
+ minimumOS: minimumOS,
+ archiveURL: archiveURL,
+ archiveLength: archiveLength,
+ signature: signature,
+ verificationKey: Data(base64Encoded: Self.encodedSigningKey)!
+ )
+ }
+
+ init(
+ build: Int,
+ shortVersion: String,
+ minimumOS: String,
+ archiveURL: URL,
+ archiveLength: Int64,
+ signature: Data,
+ verificationKey: Data
+ ) throws {
+ guard build > 0, Self.isVersion(shortVersion), Self.isVersion(minimumOS),
+ archiveLength > 0, archiveLength <= Self.maximumArchiveLength,
+ signature.count == 64, verificationKey.count == 32, Self.isReleaseArchive(archiveURL) else {
+ throw InstallerError.invalidRelease
+ }
+ self.build = build
+ self.shortVersion = shortVersion
+ self.minimumOS = minimumOS
+ self.archiveURL = archiveURL
+ self.archiveLength = archiveLength
+ self.signature = signature
+ self.verificationKey = verificationKey
+ }
+
+ /// Parse the first release in Bridgeplay's Sparkle feed.
+ public static func parse(appcast: Data) throws -> InstallerRelease {
+ let reader = AppcastReader()
+ let parser = XMLParser(data: appcast)
+ parser.delegate = reader
+ parser.shouldResolveExternalEntities = false
+ let sourceText = String(data: appcast, encoding: .utf8) ?? ""
+ guard appcast.count <= 256_000,
+ !sourceText.localizedCaseInsensitiveContains("<!DOCTYPE"),
+ !sourceText.localizedCaseInsensitiveContains("<!ENTITY"),
+ parser.parse(), let attributes = reader.enclosure,
+ let buildText = reader.build, let shortVersion = reader.shortVersion,
+ let minimumOS = reader.minimumOS, reader.hardwareRequirements == "arm64" else {
+ throw InstallerError.invalidRelease
+ }
+
+ guard buildText.utf8.allSatisfy({ (48...57).contains($0) }), let build = Int(buildText),
+ let lengthText = attributes["length"],
+ lengthText.utf8.allSatisfy({ (48...57).contains($0) }), let length = Int64(lengthText),
+ let signatureText = attributes["sparkle:edSignature"],
+ let signature = Data(base64Encoded: signatureText),
+ let urlText = attributes["url"], let url = URL(string: urlText) else {
+ throw InstallerError.invalidRelease
+ }
+
+ return try InstallerRelease(
+ build: build,
+ shortVersion: shortVersion,
+ minimumOS: minimumOS,
+ archiveURL: url,
+ archiveLength: length,
+ signature: signature
+ )
+ }
+
+ public static func latest(
+ from appcastURL: URL = appcastURL,
+ session: URLSession = .shared
+ ) async throws -> InstallerRelease {
+ guard Self.isAppcastURL(appcastURL) else { throw InstallerError.invalidRelease }
+ var request = URLRequest(url: appcastURL)
+ request.timeoutInterval = 30
+ let bytes: URLSession.AsyncBytes
+ let response: URLResponse
+ do {
+ (bytes, response) = try await session.bytes(for: request)
+ } catch {
+ throw InstallerError.networkFailure(error.localizedDescription)
+ }
+ guard let http = response as? HTTPURLResponse, http.statusCode == 200,
+ let finalURL = http.url, Self.isGitHubResponseURL(finalURL) else {
+ throw InstallerError.invalidRelease
+ }
+ var data = Data()
+ for try await byte in bytes {
+ guard data.count < 256_000 else { throw InstallerError.invalidRelease }
+ data.append(byte)
+ }
+ return try parse(appcast: data)
+ }
+
+ /// Stream the signed archive to temporary memory, verify it, then write it to disk.
+ /// The destination is created only after the complete archive passes its EdDSA check.
+ public func download(
+ to destination: URL,
+ session: URLSession = .shared,
+ progress: @Sendable (InstallerDownloadProgress) -> Void = { _ in }
+ ) async throws -> URL {
+ guard destination.isFileURL else { throw InstallerError.invalidDestination }
+ let archiveURL = destination.appending(path: "Bridgeplay.zip")
+ var request = URLRequest(url: self.archiveURL)
+ request.timeoutInterval = 60
+
+ let bytes: URLSession.AsyncBytes
+ let response: URLResponse
+ do {
+ (bytes, response) = try await session.bytes(for: request)
+ } catch is CancellationError {
+ throw CancellationError()
+ } catch {
+ throw InstallerError.networkFailure(error.localizedDescription)
+ }
+
+ guard let http = response as? HTTPURLResponse, http.statusCode == 200,
+ let finalURL = http.url, Self.isArchiveResponseURL(finalURL) else {
+ throw InstallerError.invalidRelease
+ }
+ let expected = response.expectedContentLength > 0 ? response.expectedContentLength : nil
+ if let expected, expected > Self.maximumArchiveLength {
+ throw InstallerError.archiveTooLarge
+ }
+
+ var archive = Data()
+ archive.reserveCapacity(Int(min(expected ?? archiveLength, Self.maximumArchiveLength)))
+ var received: Int64 = 0
+ for try await byte in bytes {
+ try Task.checkCancellation()
+ received += 1
+ guard received <= Self.maximumArchiveLength,
+ received <= archiveLength,
+ expected.map({ received <= $0 }) ?? true else {
+ throw InstallerError.invalidArchiveLength
+ }
+ archive.append(byte)
+ if received.isMultiple(of: 256 * 1024) {
+ progress(InstallerDownloadProgress(received: received, total: expected ?? archiveLength))
+ }
+ }
+
+ guard received == archiveLength, expected.map({ $0 == received }) ?? true else {
+ throw InstallerError.invalidArchiveLength
+ }
+ try Self.verify(archive, signature: signature, publicKey: verificationKey)
+ try Task.checkCancellation()
+
+ do {
+ try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)
+ try archive.write(to: archiveURL, options: .atomic)
+ } catch {
+ try? FileManager.default.removeItem(at: archiveURL)
+ throw InstallerError.writeFailure(error.localizedDescription)
+ }
+ progress(InstallerDownloadProgress(received: received, total: expected ?? archiveLength))
+ return archiveURL
+ }
+
+ func verifyArchive(at url: URL) throws {
+ let values = try url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
+ guard values.isRegularFile == true, let fileSize = values.fileSize,
+ Int64(fileSize) == archiveLength,
+ fileSize <= Self.maximumArchiveLength else {
+ throw InstallerError.invalidArchiveLength
+ }
+ let archive = try Data(contentsOf: url, options: .mappedIfSafe)
+ try Self.verify(archive, signature: signature, publicKey: verificationKey)
+ }
+
+ static let maximumArchiveLength: Int64 = 1_073_741_824
+
+ static let encodedSigningKey = "KrO6vVqAJozBSnfrLuyhBU/Kfhg8klI8ftl7CQ2sV98="
+
+ static func verify(_ data: Data, signature: Data, publicKey: Data) throws {
+ do {
+ let key = try Curve25519.Signing.PublicKey(rawRepresentation: publicKey)
+ guard key.isValidSignature(signature, for: data) else { throw InstallerError.signatureMismatch }
+ } catch let error as InstallerError {
+ throw error
+ } catch {
+ throw InstallerError.invalidRelease
+ }
+ }
+
+ static func isReleaseArchive(_ url: URL) -> Bool {
+ guard url.scheme == "https", url.user == nil, url.password == nil,
+ url.query == nil, url.fragment == nil, url.host == "github.com",
+ url.port == nil || url.port == 443 else { return false }
+ return url.path.hasPrefix("/raymondchins/Bridgeplay/releases/download/")
+ && url.lastPathComponent == "Bridgeplay.zip"
+ }
+
+ private static func isAppcastURL(_ url: URL) -> Bool {
+ url.scheme == "https" && url.host == "github.com" && (url.port == nil || url.port == 443)
+ && url.user == nil && url.password == nil
+ && url.query == nil && url.fragment == nil
+ && url.path == "/raymondchins/Bridgeplay/releases/latest/download/appcast.xml"
+ }
+
+ private static func isGitHubResponseURL(_ url: URL) -> Bool {
+ guard url.scheme == "https", url.user == nil, url.password == nil,
+ url.port == nil || url.port == 443 else { return false }
+ guard let host = url.host?.lowercased() else { return false }
+ return host == "github.com" || host == "release-assets.githubusercontent.com"
+ || host.hasSuffix(".githubusercontent.com")
+ }
+
+ private static func isArchiveResponseURL(_ url: URL) -> Bool {
+ isGitHubResponseURL(url)
+ }
+
+ private static func isVersion(_ text: String) -> Bool {
+ let components = text.split(separator: ".", omittingEmptySubsequences: false)
+ return (2...3).contains(components.count)
+ && components.allSatisfy {
+ !$0.isEmpty && UInt64($0) != nil
+ && $0.utf8.allSatisfy { (48...57).contains($0) }
+ }
+ }
+}
+
+private final class AppcastReader: NSObject, XMLParserDelegate {
+ private(set) var enclosure: [String: String]?
+ private(set) var build: String?
+ private(set) var shortVersion: String?
+ private(set) var minimumOS: String?
+ private(set) var hardwareRequirements: String?
+ private var readingItem = false
+ private var sawItem = false
+ private var capturedElement: String?
+ private var capturedText = ""
+
+ func parser(
+ _ parser: XMLParser,
+ didStartElement elementName: String,
+ namespaceURI: String?,
+ qualifiedName qName: String?,
+ attributes attributeDict: [String: String] = [:]
+ ) {
+ if elementName == "item", !sawItem {
+ sawItem = true
+ readingItem = true
+ return
+ }
+ guard readingItem else { return }
+ if elementName == "enclosure", enclosure == nil {
+ enclosure = attributeDict
+ }
+ if ["sparkle:version", "sparkle:shortVersionString", "sparkle:minimumSystemVersion",
+ "sparkle:hardwareRequirements"].contains(elementName) {
+ capturedElement = elementName
+ capturedText = ""
+ }
+ }
+
+ func parser(_ parser: XMLParser, foundCharacters string: String) {
+ guard capturedElement != nil else { return }
+ capturedText += string
+ if capturedText.utf8.count > 128 { parser.abortParsing() }
+ }
+
+ func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) {
+ guard capturedElement != nil, let text = String(data: CDATABlock, encoding: .utf8) else { return }
+ capturedText += text
+ if capturedText.utf8.count > 128 { parser.abortParsing() }
+ }
+
+ func parser(
+ _ parser: XMLParser,
+ didEndElement elementName: String,
+ namespaceURI: String?,
+ qualifiedName qName: String?
+ ) {
+ guard readingItem else { return }
+ if elementName == capturedElement {
+ let value = capturedText.trimmingCharacters(in: .whitespacesAndNewlines)
+ switch elementName {
+ case "sparkle:version": build = value
+ case "sparkle:shortVersionString": shortVersion = value
+ case "sparkle:minimumSystemVersion": minimumOS = value
+ case "sparkle:hardwareRequirements": hardwareRequirements = value
+ default: break
+ }
+ capturedElement = nil
+ capturedText = ""
+ }
+ if elementName == "item" { readingItem = false }
+ }
+}
+
+public enum InstallerError: LocalizedError, Sendable {
+ case invalidRelease
+ case networkFailure(String)
+ case invalidDestination
+ case archiveTooLarge
+ case invalidArchiveLength
+ case signatureMismatch
+ case writeFailure(String)
+ case unsupportedSystem(minimum: String)
+ case invalidInstallation(String)
+ case otherAppInstalled(String)
+ case downgrade(current: Int, offered: Int)
+ case alreadyCurrent
+ case appIsRunning
+ case installLocked
+ case appValidation(String)
+ case replacementFailure(String)
+
+ public var errorDescription: String? {
+ switch self {
+ case .invalidRelease: "The Bridgeplay release information could not be verified."
+ case .networkFailure(let detail): "Bridgeplay could not reach its release server. \(detail)"
+ case .invalidDestination: "Choose a local folder for Bridgeplay."
+ case .archiveTooLarge: "The Bridgeplay download is larger than expected."
+ case .invalidArchiveLength: "The Bridgeplay download is incomplete or has an unexpected size."
+ case .signatureMismatch: "The Bridgeplay download did not pass its signature check."
+ case .writeFailure(let detail): "The verified Bridgeplay download could not be saved. \(detail)"
+ case .unsupportedSystem(let minimum): "This Bridgeplay release needs macOS \(minimum) or later."
+ case .invalidInstallation(let detail): "The Bridgeplay installation could not be read. \(detail)"
+ case .otherAppInstalled(let name): "Another app is already at the install location (\(name)). Choose another location or move it first."
+ case .downgrade(let current, let offered): "Bridgeplay \(offered) is older than the installed build \(current)."
+ case .alreadyCurrent: "This Bridgeplay version is already installed."
+ case .appIsRunning: "Quit Bridgeplay before installing its update, then try again."
+ case .installLocked: "Another Bridgeplay installation is in progress. Finish it before trying again."
+ case .appValidation(let detail): "The downloaded Bridgeplay app could not be validated. \(detail)"
+ case .replacementFailure(let detail): "Bridgeplay could not replace the existing app. \(detail)"
+ }
+ }
+}
+
+func compareVersions(_ lhs: String, _ rhs: String) -> ComparisonResult {
+ let left = lhs.split(separator: ".").compactMap { UInt64($0) }
+ let right = rhs.split(separator: ".").compactMap { UInt64($0) }
+ for index in 0..<max(left.count, right.count) {
+ let a = index < left.count ? left[index] : 0
+ let b = index < right.count ? right[index] : 0
+ if a < b { return .orderedAscending }
+ if a > b { return .orderedDescending }
+ }
+ return .orderedSame
+}
diff --git a/app/Sources/BridgeplayInstallerCore/InstallerService.swift b/app/Sources/BridgeplayInstallerCore/InstallerService.swift
new file mode 100644
index 0000000..ab2b937
--- /dev/null
+++ b/app/Sources/BridgeplayInstallerCore/InstallerService.swift
@@ -0,0 +1,347 @@
+import Darwin
+import Foundation
+
+public enum InstallationState: Sendable, Equatable {
+ case notInstalled
+ case updateAvailable(currentBuild: Int, currentVersion: String, release: InstallerRelease)
+ case upToDate(build: Int, version: String)
+}
+
+/// Detects and safely replaces the Bridgeplay app bundle. Game setup stays in the app.
+public struct InstallerService: Sendable {
+ public static let bundleIdentifier = "com.bridgeplay.Bridgeplay"
+ public static let applicationName = "Bridgeplay.app"
+
+ public let destination: URL
+ private let ensureAppIsClosed: @Sendable () throws -> Void
+
+ public init(destination: URL = URL(fileURLWithPath: "/Applications/Bridgeplay.app", isDirectory: true)) {
+ self.init(destination: destination, ensureAppIsClosed: { try Self.requireAppIsClosed() })
+ }
+
+ init(
+ destination: URL,
+ ensureAppIsClosed: @escaping @Sendable () throws -> Void
+ ) {
+ self.destination = destination
+ self.ensureAppIsClosed = ensureAppIsClosed
+ }
+
+ public func state(for release: InstallerRelease) throws -> InstallationState {
+ try recoverIfNeeded()
+ try Self.checkSystem(release)
+ let target = transactionDestination
+ guard try Self.pathExistsWithoutSymlink(target) else { return .notInstalled }
+ let current = try Self.readBundle(at: target)
+ guard current.identifier == Self.bundleIdentifier else {
+ throw InstallerError.otherAppInstalled(current.identifier)
+ }
+ guard release.build >= current.build else {
+ throw InstallerError.downgrade(current: current.build, offered: release.build)
+ }
+ if release.build == current.build {
+ guard release.shortVersion == current.version else {
+ throw InstallerError.invalidInstallation("Its version number does not match its build number.")
+ }
+ return .upToDate(build: current.build, version: current.version)
+ }
+ return .updateAvailable(
+ currentBuild: current.build, currentVersion: current.version, release: release
+ )
+ }
+
+ /// Restore a verified previous app after an interrupted replacement, without network access.
+ public func recoverIfNeeded() throws {
+ guard destination.isFileURL, destination.lastPathComponent == Self.applicationName else {
+ throw InstallerError.invalidDestination
+ }
+ let target = transactionDestination
+ let parent = target.deletingLastPathComponent()
+ let backup = Self.backupURL(in: parent)
+ guard try !Self.pathExistsWithoutSymlink(target),
+ try Self.pathExistsWithoutSymlink(backup) else { return }
+
+ let lock = try InstallLock(parent: parent)
+ defer { lock.release() }
+ try ensureAppIsClosed()
+
+ // Recheck after acquiring the cross-process lock.
+ guard try !Self.pathExistsWithoutSymlink(target),
+ try Self.pathExistsWithoutSymlink(backup) else { return }
+ let previous = try Self.readBundle(at: backup)
+ guard previous.identifier == Self.bundleIdentifier else {
+ throw InstallerError.invalidInstallation("The saved recovery app has a different bundle identifier.")
+ }
+ try Self.verifyInstalledSignature(at: backup)
+ do { try FileManager.default.moveItem(at: backup, to: target) }
+ catch { throw InstallerError.replacementFailure("The saved copy could not be restored. \(error.localizedDescription)") }
+ }
+
+ /// Verify, stage and install a release archive. The prior app is restored if replacement fails.
+ @discardableResult
+ public func install(release: InstallerRelease, archive: URL) throws -> URL {
+ try Self.checkSystem(release)
+ guard archive.isFileURL, destination.isFileURL,
+ destination.lastPathComponent == Self.applicationName else {
+ throw InstallerError.invalidDestination
+ }
+ try release.verifyArchive(at: archive)
+
+ let fileManager = FileManager.default
+ let target = transactionDestination
+ let parent = target.deletingLastPathComponent()
+ let stage = parent.appending(path: ".BridgeplayInstaller-\(UUID().uuidString)", directoryHint: .isDirectory)
+ let payload = stage.appending(path: "payload", directoryHint: .isDirectory)
+ let stagedApp = payload.appending(path: Self.applicationName, directoryHint: .isDirectory)
+ let backup = Self.backupURL(in: parent)
+ defer { try? fileManager.removeItem(at: stage) }
+
+ do {
+ try fileManager.createDirectory(at: payload, withIntermediateDirectories: true)
+ } catch {
+ throw InstallerError.writeFailure(error.localizedDescription)
+ }
+
+ try Self.extract(archive, into: payload)
+ let entries = try fileManager.contentsOfDirectory(atPath: payload.path)
+ guard entries == [Self.applicationName] else { throw InstallerError.appValidation("The archive does not contain a single Bridgeplay app.") }
+ try Self.validateBundle(at: stagedApp, expectedBuild: release.build, expectedVersion: release.shortVersion)
+
+ // Coordinate concurrent installers and the installed app immediately before mutation.
+ let lock = try InstallLock(parent: parent)
+ defer { lock.release() }
+ try ensureAppIsClosed()
+
+ var destinationExists = try Self.pathExistsWithoutSymlink(destination)
+ var backupExists = try Self.pathExistsWithoutSymlink(backup)
+
+ // Recover an interrupted replacement before considering a new one. The backup is
+ // retained across successful installs so this also recovers a later disk failure.
+ if !destinationExists, backupExists {
+ let previous = try Self.readBundle(at: backup)
+ guard previous.identifier == Self.bundleIdentifier else {
+ throw InstallerError.invalidInstallation("The saved recovery app has a different bundle identifier.")
+ }
+ try Self.verifyInstalledSignature(at: backup)
+ do { try fileManager.moveItem(at: backup, to: target) }
+ catch { throw InstallerError.replacementFailure("The saved copy could not be restored. \(error.localizedDescription)") }
+ destinationExists = true
+ backupExists = false
+ }
+
+ if destinationExists {
+ let current = try Self.readBundle(at: destination)
+ guard current.identifier == Self.bundleIdentifier else {
+ throw InstallerError.otherAppInstalled(current.identifier)
+ }
+ guard release.build > current.build else {
+ if release.build == current.build { throw InstallerError.alreadyCurrent }
+ throw InstallerError.downgrade(current: current.build, offered: release.build)
+ }
+ }
+
+ if backupExists {
+ let previous = try Self.readBundle(at: backup)
+ guard previous.identifier == Self.bundleIdentifier else {
+ throw InstallerError.invalidInstallation("A different app is occupying the saved recovery location.")
+ }
+ try Self.verifyInstalledSignature(at: backup)
+ do { try fileManager.removeItem(at: backup) }
+ catch { throw InstallerError.writeFailure(error.localizedDescription) }
+ }
+
+ do {
+ if destinationExists { try fileManager.moveItem(at: target, to: backup) }
+ try fileManager.moveItem(at: stagedApp, to: target)
+ } catch {
+ var rollbackDetail = ""
+ if fileManager.fileExists(atPath: backup.path), !fileManager.fileExists(atPath: target.path) {
+ do {
+ try fileManager.moveItem(at: backup, to: target)
+ rollbackDetail = " The previous app was restored."
+ } catch {
+ rollbackDetail = " The previous app remains at \(backup.path): \(error.localizedDescription)"
+ }
+ }
+ throw InstallerError.replacementFailure("\(error.localizedDescription)\(rollbackDetail)")
+ }
+
+ // Keep one verified previous app for recovery if the next launch fails.
+ return destination
+ }
+
+ /// Resolve symlinked ancestors once, while preserving the final path component for lstat.
+ /// This avoids operations through aliases such as macOS's /tmp -> /private/tmp.
+ private var transactionDestination: URL {
+ let normalized = destination.standardizedFileURL
+ let parent = normalized.deletingLastPathComponent().resolvingSymlinksInPath().standardizedFileURL
+ return parent.appending(path: normalized.lastPathComponent, directoryHint: .isDirectory)
+ }
+
+ private static func checkSystem(_ release: InstallerRelease) throws {
+ let version = ProcessInfo.processInfo.operatingSystemVersion
+ let current = [version.majorVersion, version.minorVersion, version.patchVersion]
+ .map(String.init).joined(separator: ".")
+ if compareVersions(current, release.minimumOS) == .orderedAscending {
+ throw InstallerError.unsupportedSystem(minimum: release.minimumOS)
+ }
+ #if arch(arm64)
+ // Supported hardware for Bridgeplay.
+ #else
+ throw InstallerError.unsupportedSystem(minimum: "Apple silicon")
+ #endif
+ }
+
+ private static func readBundle(at url: URL) throws -> BundleInfo {
+ guard try pathExistsWithoutSymlink(url) else {
+ throw InstallerError.invalidInstallation("The app bundle does not exist.")
+ }
+ var status = stat()
+ guard lstat(url.path, &status) == 0, (status.st_mode & S_IFMT) == S_IFDIR else {
+ throw InstallerError.invalidInstallation("The app bundle is not a regular directory.")
+ }
+ let infoURL = url.appending(path: "Contents/Info.plist")
+ let info: [String: Any]
+ do {
+ let data = try Data(contentsOf: infoURL)
+ guard let plist = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else {
+ throw InstallerError.invalidInstallation("Its Info.plist is malformed.")
+ }
+ info = plist
+ } catch let error as InstallerError {
+ throw error
+ } catch {
+ throw InstallerError.invalidInstallation(error.localizedDescription)
+ }
+ guard let identifier = info["CFBundleIdentifier"] as? String,
+ let version = info["CFBundleShortVersionString"] as? String,
+ let buildText = info["CFBundleVersion"] as? String,
+ buildText.utf8.allSatisfy({ (48...57).contains($0) }), let build = Int(buildText),
+ let executable = info["CFBundleExecutable"] as? String,
+ !executable.isEmpty, executable != ".", executable != "..",
+ !executable.contains("/"), !executable.contains("\\") else {
+ throw InstallerError.invalidInstallation("Its app identity or version is missing.")
+ }
+ let executableURL = url.appending(path: "Contents/MacOS/\(executable)")
+ let executableValues = try? executableURL.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .isExecutableKey])
+ guard executableValues?.isRegularFile == true,
+ executableValues?.isSymbolicLink != true,
+ executableValues?.isExecutable == true else {
+ throw InstallerError.invalidInstallation("Its app executable is missing or unsafe.")
+ }
+ return BundleInfo(identifier: identifier, version: version, build: build)
+ }
+
+ private static func validateBundle(at url: URL, expectedBuild: Int, expectedVersion: String) throws {
+ let info = try readBundle(at: url)
+ guard info.identifier == bundleIdentifier else { throw InstallerError.appValidation("The app has a different bundle identifier.") }
+ guard info.build == expectedBuild, info.version == expectedVersion else {
+ throw InstallerError.appValidation("The app version does not match the authenticated release information.")
+ }
+ try verifyInstalledSignature(at: url)
+ }
+
+ private static func verifyInstalledSignature(at url: URL) throws {
+ try run("/usr/bin/codesign", ["--verify", "--strict", "--deep", url.path], failure: InstallerError.appValidation("Its code signature is invalid."))
+ }
+
+ private static func pathExistsWithoutSymlink(_ url: URL) throws -> Bool {
+ var status = stat()
+ if lstat(url.path, &status) != 0 {
+ if errno == ENOENT { return false }
+ throw InstallerError.invalidDestination
+ }
+ guard (status.st_mode & S_IFMT) != S_IFLNK else {
+ throw InstallerError.invalidDestination
+ }
+ return true
+ }
+
+ private static func backupURL(in parent: URL) -> URL {
+ parent.appending(path: ".Bridgeplay.app.previous", directoryHint: .isDirectory)
+ }
+
+ private static func extract(_ archive: URL, into directory: URL) throws {
+ try run("/usr/bin/ditto", ["-x", "-k", archive.path, directory.path], failure: InstallerError.appValidation("The app archive could not be extracted."))
+ }
+
+ private static func requireAppIsClosed() throws {
+ for name in ["BridgeplayApp", "Autoupdate"] {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/pgrep")
+ process.arguments = ["-x", name]
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ do { try process.run() }
+ catch { throw InstallerError.appIsRunning }
+ process.waitUntilExit()
+ if process.terminationStatus == 0 { throw InstallerError.appIsRunning }
+ }
+ }
+
+ private static func run(_ executable: String, _ arguments: [String], failure: InstallerError) throws {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: executable)
+ process.arguments = arguments
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ do { try process.run() }
+ catch { throw failure }
+ process.waitUntilExit()
+ guard process.terminationStatus == 0 else { throw failure }
+ }
+
+ private struct BundleInfo {
+ let identifier: String
+ let version: String
+ let build: Int
+ }
+}
+
+private final class InstallLock {
+ private let descriptor: Int32
+
+ init(parent: URL) throws {
+ let path = parent.appending(path: ".Bridgeplay.app.install.lock").path
+ var fd = open(path, O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
+ let created = fd >= 0
+ if created, fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0 {
+ close(fd)
+ throw InstallerError.installLocked
+ }
+ if !created, errno == EEXIST {
+ // Other macOS accounts can take the exclusive advisory lock through a read-only fd.
+ // A brief retry covers the creator's interval between O_EXCL and fchmod(0644).
+ for _ in 0..<10 {
+ fd = open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC)
+ if fd < 0, errno == EACCES || errno == EPERM {
+ fd = open(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)
+ }
+ if fd >= 0 { break }
+ guard errno == EACCES || errno == EPERM else { break }
+ usleep(10_000)
+ }
+ }
+ guard fd >= 0 else { throw InstallerError.installLocked }
+ var status = stat()
+ guard fstat(fd, &status) == 0, (status.st_mode & S_IFMT) == S_IFREG,
+ status.st_nlink == 1 else {
+ close(fd)
+ throw InstallerError.installLocked
+ }
+ if status.st_uid == geteuid(), fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0 {
+ close(fd)
+ throw InstallerError.installLocked
+ }
+ guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {
+ close(fd)
+ throw InstallerError.installLocked
+ }
+ descriptor = fd
+ }
+
+ func release() {
+ flock(descriptor, LOCK_UN)
+ close(descriptor)
+ }
+}
diff --git a/app/Sources/BridgeplayApp/Views/BridgeplayTheme.swift b/app/Sources/BridgeplayUI/BridgeplayTheme.swift
similarity index 63%
rename from app/Sources/BridgeplayApp/Views/BridgeplayTheme.swift
rename to app/Sources/BridgeplayUI/BridgeplayTheme.swift
index 29cfa64..a5ce0f1 100644
--- a/app/Sources/BridgeplayApp/Views/BridgeplayTheme.swift
+++ b/app/Sources/BridgeplayUI/BridgeplayTheme.swift
@@ -4,37 +4,37 @@ import SwiftUI
// The look of bridgeplay.dev (styles.css :root) for the app's own surfaces: black canvas,
// near-white type in Geist, hairline borders, small radii, and the violet-blue-pink
// gradient kept for emphasis only (progress, the last step, one word of a headline).
-enum BP {
- static let bg = Color(hex: 0x000000)
- static let raise = Color(hex: 0x0D0D0F)
- static let raise2 = Color(hex: 0x161618)
- static let fg = Color(hex: 0xF5F5F7)
- static let fg2 = Color(hex: 0xA1A1A6)
- static let fg3 = Color(hex: 0x86868B)
- static let line = Color.white.opacity(0.08)
- static let lineStrong = Color.white.opacity(0.18)
- static let violet = Color(hex: 0x8B7BFF)
- static let blue = Color(hex: 0x4FB3FF)
- static let pink = Color(hex: 0xFF7AC6)
- static let green = Color(hex: 0x30D158)
- static let orange = Color(hex: 0xFF9F0A)
- static let red = Color(hex: 0xFF453A)
-
- static let iridescent = LinearGradient(colors: [violet, blue, pink], startPoint: .leading, endPoint: .trailing)
- static let iridescentDiagonal = LinearGradient(colors: [violet, blue, pink], startPoint: .topLeading, endPoint: .bottomTrailing)
-
- static let radius: CGFloat = 12
- static let controlRadius: CGFloat = 8
+public enum BP {
+ public static let bg = Color(hex: 0x000000)
+ public static let raise = Color(hex: 0x0D0D0F)
+ public static let raise2 = Color(hex: 0x161618)
+ public static let fg = Color(hex: 0xF5F5F7)
+ public static let fg2 = Color(hex: 0xA1A1A6)
+ public static let fg3 = Color(hex: 0x86868B)
+ public static let line = Color.white.opacity(0.08)
+ public static let lineStrong = Color.white.opacity(0.18)
+ public static let violet = Color(hex: 0x8B7BFF)
+ public static let blue = Color(hex: 0x4FB3FF)
+ public static let pink = Color(hex: 0xFF7AC6)
+ public static let green = Color(hex: 0x30D158)
+ public static let orange = Color(hex: 0xFF9F0A)
+ public static let red = Color(hex: 0xFF453A)
+
+ public static let iridescent = LinearGradient(colors: [violet, blue, pink], startPoint: .leading, endPoint: .trailing)
+ public static let iridescentDiagonal = LinearGradient(colors: [violet, blue, pink], startPoint: .topLeading, endPoint: .bottomTrailing)
+
+ public static let radius: CGFloat = 12
+ public static let controlRadius: CGFloat = 8
// cubic-bezier(0.16, 1, 0.3, 1), the site's --ease-out.
- static let easeOut = Animation.timingCurve(0.16, 1, 0.3, 1, duration: 0.5)
+ public static let easeOut = Animation.timingCurve(0.16, 1, 0.3, 1, duration: 0.5)
- static func sans(_ size: CGFloat, _ weight: Font.Weight = .regular) -> Font {
+ public static func sans(_ size: CGFloat, _ weight: Font.Weight = .regular) -> Font {
registerFonts()
return .custom("Geist", size: size).weight(weight)
}
- static func display(_ size: CGFloat) -> Font {
+ public static func display(_ size: CGFloat) -> Font {
registerFonts()
return .custom("Unbounded", size: size).weight(.semibold)
}
@@ -42,17 +42,22 @@ enum BP {
// Process-scoped, so nothing is installed on the Mac. Missing glyphs (Chinese) fall
// back to the system font.
private static let registered: Void = {
+ let resources = Bundle.main.resourceURL.flatMap { resourceURL in
+ Bundle(url: resourceURL.appendingPathComponent(
+ "BridgeplayApp_BridgeplayUI.bundle", isDirectory: true
+ ))
+ } ?? .module
for name in ["geist", "unbounded"] {
- guard let url = Bundle.module.url(forResource: name, withExtension: "woff2", subdirectory: "Fonts") else { continue }
+ guard let url = resources.url(forResource: name, withExtension: "woff2", subdirectory: "Fonts") else { continue }
CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)
}
}()
- static func registerFonts() { _ = registered }
+ public static func registerFonts() { _ = registered }
}
extension Color {
- init(hex: UInt32) {
+ public init(hex: UInt32) {
self.init(.sRGB,
red: Double((hex >> 16) & 0xFF) / 255,
green: Double((hex >> 8) & 0xFF) / 255,
@@ -62,14 +67,19 @@ extension Color {
// .pill on the site: white with black text, fully round. The secondary kind is a
// hairline capsule in the foreground colour.
-struct PillButtonStyle: ButtonStyle {
- enum Kind { case primary, secondary, plain }
- var kind: Kind = .primary
- var large = false
+public struct PillButtonStyle: ButtonStyle {
+ public enum Kind { case primary, secondary, plain }
+ public var kind: Kind = .primary
+ public var large = false
+
+ public init(kind: Kind = .primary, large: Bool = false) {
+ self.kind = kind
+ self.large = large
+ }
@Environment(\.isEnabled) private var isEnabled
- func makeBody(configuration: Configuration) -> some View {
+ public func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(BP.sans(large ? 14 : 13, .semibold))
.tracking(-0.15)
@@ -103,22 +113,26 @@ struct PillButtonStyle: ButtonStyle {
}
extension ButtonStyle where Self == PillButtonStyle {
- static var pill: PillButtonStyle { PillButtonStyle() }
- static var pillLarge: PillButtonStyle { PillButtonStyle(large: true) }
- static var pillSecondary: PillButtonStyle { PillButtonStyle(kind: .secondary) }
- static var pillSecondaryLarge: PillButtonStyle { PillButtonStyle(kind: .secondary, large: true) }
- static var pillPlain: PillButtonStyle { PillButtonStyle(kind: .plain, large: true) }
+ public static var pill: PillButtonStyle { PillButtonStyle() }
+ public static var pillLarge: PillButtonStyle { PillButtonStyle(large: true) }
+ public static var pillSecondary: PillButtonStyle { PillButtonStyle(kind: .secondary) }
+ public static var pillSecondaryLarge: PillButtonStyle { PillButtonStyle(kind: .secondary, large: true) }
+ public static var pillPlain: PillButtonStyle { PillButtonStyle(kind: .plain, large: true) }
}
// The Bridgeplay mark (helpers/icon/bridgeplay-mark.svg) as shapes in a 24-unit box, so the
// art can draw it in stroke by stroke: the deck and towers, the suspension cable, and the
// cable's reflection.
-enum BridgePart { case deck, cable, echo }
+public enum BridgePart: Sendable { case deck, cable, echo }
+
+public struct BridgeShape: Shape {
+ public let part: BridgePart
-struct BridgeShape: Shape {
- let part: BridgePart
+ public init(part: BridgePart) {
+ self.part = part
+ }
- func path(in rect: CGRect) -> Path {
+ public func path(in rect: CGRect) -> Path {
let s = min(rect.width, rect.height) / 24
func p(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
CGPoint(x: rect.minX + (2.4 + x * 0.8) * s, y: rect.minY + (2.4 + y * 0.8) * s)
@@ -148,7 +162,7 @@ struct BridgeShape: Shape {
}
// Stroke widths from the SVG, scaled to a mark drawn `size` points wide.
- static func width(_ part: BridgePart, size: CGFloat) -> CGFloat {
+ public static func width(_ part: BridgePart, size: CGFloat) -> CGFloat {
let unit = size / 24 * 0.8
switch part {
case .deck: return 1.8 * unit
@@ -159,10 +173,14 @@ struct BridgeShape: Shape {
}
// The mark drawn flat on its black tile, as in the nav bar and favicon.
-struct BridgeplayMark: View {
- var size: CGFloat = 22
+public struct BridgeplayMark: View {
+ public var size: CGFloat = 22
+
+ public init(size: CGFloat = 22) {
+ self.size = size
+ }
- var body: some View {
+ public var body: some View {
ZStack {
BridgeShape(part: .deck)
.stroke(BP.fg, style: StrokeStyle(lineWidth: BridgeShape.width(.deck, size: size), lineCap: .round))
diff --git a/app/Sources/BridgeplayApp/Resources/Fonts/OFL-Geist.txt b/app/Sources/BridgeplayUI/Resources/Fonts/OFL-Geist.txt
similarity index 100%
rename from app/Sources/BridgeplayApp/Resources/Fonts/OFL-Geist.txt
rename to app/Sources/BridgeplayUI/Resources/Fonts/OFL-Geist.txt
diff --git a/app/Sources/BridgeplayApp/Resources/Fonts/OFL-Unbounded.txt b/app/Sources/BridgeplayUI/Resources/Fonts/OFL-Unbounded.txt
similarity index 100%
rename from app/Sources/BridgeplayApp/Resources/Fonts/OFL-Unbounded.txt
rename to app/Sources/BridgeplayUI/Resources/Fonts/OFL-Unbounded.txt
diff --git a/app/Sources/BridgeplayApp/Resources/Fonts/geist.woff2 b/app/Sources/BridgeplayUI/Resources/Fonts/geist.woff2
similarity index 100%
rename from app/Sources/BridgeplayApp/Resources/Fonts/geist.woff2
rename to app/Sources/BridgeplayUI/Resources/Fonts/geist.woff2
diff --git a/app/Sources/BridgeplayApp/Resources/Fonts/unbounded.woff2 b/app/Sources/BridgeplayUI/Resources/Fonts/unbounded.woff2
similarity index 100%
rename from app/Sources/BridgeplayApp/Resources/Fonts/unbounded.woff2
rename to app/Sources/BridgeplayUI/Resources/Fonts/unbounded.woff2
diff --git a/app/Sources/BridgeplayUI/SetupCard.swift b/app/Sources/BridgeplayUI/SetupCard.swift
new file mode 100644
index 0000000..57ad6b6
--- /dev/null
+++ b/app/Sources/BridgeplayUI/SetupCard.swift
@@ -0,0 +1,24 @@
+import SwiftUI
+
+// The setup wizard's raised panel and divider, shared with the installer wizard.
+public struct SetupCard<Content: View>: View {
+ private let content: Content
+
+ public init(@ViewBuilder content: () -> Content) {
+ self.content = content()
+ }
+
+ public var body: some View {
+ VStack(spacing: 0) { content }
+ .background(BP.raise, in: RoundedRectangle(cornerRadius: BP.radius, style: .continuous))
+ .overlay(RoundedRectangle(cornerRadius: BP.radius, style: .continuous).strokeBorder(BP.line, lineWidth: 1))
+ }
+}
+
+public struct SetupHairline: View {
+ public init() {}
+
+ public var body: some View {
+ Rectangle().fill(BP.line).frame(height: 1).padding(.leading, 54)
+ }
+}
diff --git a/app/Tests/BridgeplayInstallerCoreTests/InstallerReleaseTests.swift b/app/Tests/BridgeplayInstallerCoreTests/InstallerReleaseTests.swift
new file mode 100644
index 0000000..6025022
--- /dev/null
+++ b/app/Tests/BridgeplayInstallerCoreTests/InstallerReleaseTests.swift
@@ -0,0 +1,173 @@
+import Foundation
+import CryptoKit
+import Testing
+@testable import BridgeplayInstallerCore
+
+@Suite("Installer release validation")
+struct InstallerReleaseTests {
+ private let validURL = URL(string: "https://github.com/raymondchins/Bridgeplay/releases/download/v3.5.0/Bridgeplay.zip")!
+ private let signature = Data(repeating: 0xA5, count: 64)
+
+ private func release(
+ url: URL? = nil,
+ length: Int64 = 1234,
+ signature: Data? = nil,
+ build: Int = 35,
+ version: String = "3.5.0",
+ minimumOS: String = "26.0"
+ ) throws -> InstallerRelease {
+ try InstallerRelease(
+ build: build,
+ shortVersion: version,
+ minimumOS: minimumOS,
+ archiveURL: url ?? validURL,
+ archiveLength: length,
+ signature: signature ?? self.signature
+ )
+ }
+
+ private func appcast(
+ url: String = "https://github.com/raymondchins/Bridgeplay/releases/download/v3.5.0/Bridgeplay.zip",
+ length: String = "1234",
+ build: String = "35",
+ version: String = "3.5.0",
+ minimumOS: String = "26.0",
+ signature: String = Data(repeating: 0xA5, count: 64).base64EncodedString(),
+ hardware: String? = "arm64"
+ ) -> Data {
+ let xml = """
+ <?xml version="1.0" standalone="yes"?>
+ <rss xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle" version="2.0">
+ <channel><item>
+ <sparkle:version>\(build)</sparkle:version>
+ <sparkle:shortVersionString>\(version)</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>\(minimumOS)</sparkle:minimumSystemVersion>
+ \(hardware.map { "<sparkle:hardwareRequirements>\($0)</sparkle:hardwareRequirements>" } ?? "")
+ <enclosure url="\(url)" length="\(length)" type="application/octet-stream"
+ sparkle:edSignature="\(signature)" />
+ </item></channel>
+ </rss>
+ """
+ return Data(xml.utf8)
+ }
+
+ @Test func parsesCurrentFeedFields() throws {
+ let value = try InstallerRelease.parse(appcast: appcast())
+ #expect(value.build == 35)
+ #expect(value.shortVersion == "3.5.0")
+ #expect(value.minimumOS == "26.0")
+ #expect(value.archiveLength == 1234)
+ #expect(value.archiveURL == validURL)
+ #expect(value.signature.count == 64)
+ }
+
+ @Test(arguments: [
+ "http://github.com/raymondchins/Bridgeplay/releases/download/v3.5.0/Bridgeplay.zip",
+ "https://github.com.attacker.invalid/raymondchins/Bridgeplay/releases/download/v3.5.0/Bridgeplay.zip",
+ "https://attacker.invalid/raymondchins/Bridgeplay/releases/download/v3.5.0/Bridgeplay.zip",
+ "https://github.com/raymondchins/Bridgeplay/releases/download/v3.5.0/Other.zip",
+ "https://[email protected]/raymondchins/Bridgeplay/releases/download/v3.5.0/Bridgeplay.zip",
+ "https://github.com/raymondchins/Bridgeplay/releases/download/v3.5.0/Bridgeplay.zip?redirect=attacker.invalid",
+ "https://github.com:444/raymondchins/Bridgeplay/releases/download/v3.5.0/Bridgeplay.zip",
+ ])
+ func rejectsUntrustedArchiveURL(_ input: String) throws {
+ let url = try #require(URL(string: input))
+ #expect(throws: InstallerError.self) {
+ try release(url: url)
+ }
+ }
+
+ @Test func rejectsInvalidLengthsBuildVersionsAndSignatures() {
+ #expect(throws: InstallerError.self) { try release(length: 0) }
+ #expect(throws: InstallerError.self) { try release(length: 1_073_741_825) }
+ #expect(throws: InstallerError.self) { try release(build: 0) }
+ #expect(throws: InstallerError.self) { try release(version: "3.5.release") }
+ #expect(throws: InstallerError.self) { try release(minimumOS: "26") }
+ #expect(throws: InstallerError.self) { try release(minimumOS: "26.0.1.2") }
+ #expect(throws: InstallerError.self) { try release(signature: Data(repeating: 0, count: 63)) }
+ }
+
+ @Test func acceptsTwoOrThreeNumericOSVersionComponents() throws {
+ #expect(try release(minimumOS: "26.0").minimumOS == "26.0")
+ #expect(try release(minimumOS: "26.0.1").minimumOS == "26.0.1")
+ }
+
+ @Test func rejectsMalformedOrUnsafeAppcast() {
+ #expect(throws: InstallerError.self) { try InstallerRelease.parse(appcast: Data("not XML".utf8)) }
+ #expect(throws: InstallerError.self) {
+ try InstallerRelease.parse(appcast: Data("<!DOCTYPE rss [<!ENTITY x SYSTEM 'file:///etc/passwd'>]><rss>&x;</rss>".utf8))
+ }
+ #expect(throws: InstallerError.self) { try InstallerRelease.parse(appcast: appcast(url: "https://evil.example/app.zip")) }
+ #expect(throws: InstallerError.self) { try InstallerRelease.parse(appcast: appcast(length: "-1")) }
+ #expect(throws: InstallerError.self) { try InstallerRelease.parse(appcast: appcast(build: "35junk")) }
+ #expect(throws: InstallerError.self) { try InstallerRelease.parse(appcast: appcast(version: "not-a-version")) }
+ #expect(throws: InstallerError.self) { try InstallerRelease.parse(appcast: appcast(minimumOS: "26.0.1.2.3")) }
+ #expect(throws: InstallerError.self) { try InstallerRelease.parse(appcast: appcast(signature: "!!!")) }
+ #expect(throws: InstallerError.self) { try InstallerRelease.parse(appcast: appcast(hardware: "x86_64")) }
+ }
+
+ @Test func requiresAppleSiliconHardwareRequirement() {
+ #expect(throws: InstallerError.self) {
+ try InstallerRelease.parse(appcast: appcast(hardware: nil))
+ }
+ }
+
+ @Test func rejectsAppcastURLOutsidePinnedFeed() async {
+ let wrong = URL(string: "https://attacker.invalid/releases/latest/download/appcast.xml")!
+ await #expect(throws: InstallerError.self) { try await InstallerRelease.latest(from: wrong) }
+ }
+
+ @Test(arguments: [
+ "https://github.com/raymondchins/Bridgeplay/releases/download/appcast.xml",
+ "https://github.com:444/raymondchins/Bridgeplay/releases/latest/download/appcast.xml",
+ ])
+ func rejectsUntrustedAppcastPath(_ input: String) async throws {
+ let url = try #require(URL(string: input))
+ await #expect(throws: InstallerError.self) { try await InstallerRelease.latest(from: url) }
+ }
+
+ @Test func rejectsArchiveBytesWithWrongLengthBeforeTrustingSignature() throws {
+ let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString, directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let file = directory.appending(path: "archive.zip")
+ try Data(repeating: 0, count: 12).write(to: file)
+ #expect(throws: InstallerError.self) { try release().verifyArchive(at: file) }
+ }
+
+ @Test func rejectsTamperedArchiveUsingPinnedProductionKey() throws {
+ let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString, directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let file = directory.appending(path: "archive.zip")
+ try Data(repeating: 0x42, count: 1234).write(to: file)
+ do {
+ try release().verifyArchive(at: file)
+ Issue.record("The archive must not pass with an unrelated signature.")
+ } catch let error as InstallerError {
+ guard case .signatureMismatch = error else {
+ Issue.record("Expected signatureMismatch, received \(error).")
+ return
+ }
+ }
+ }
+
+ @Test func acceptsBytesSignedByTheCorrespondingTestKeyAndRejectsTampering() throws {
+ let key = Curve25519.Signing.PrivateKey()
+ let signedBytes = Data("test archive contents".utf8)
+ let signature = try key.signature(for: signedBytes)
+
+ try InstallerRelease.verify(signedBytes, signature: signature, publicKey: key.publicKey.rawRepresentation)
+
+ do {
+ try InstallerRelease.verify(Data("tampered archive contents".utf8), signature: signature,
+ publicKey: key.publicKey.rawRepresentation)
+ Issue.record("Changing one signed archive must fail signature verification.")
+ } catch let error as InstallerError {
+ guard case .signatureMismatch = error else {
+ Issue.record("Expected signatureMismatch, received \(error).")
+ return
+ }
+ }
+ }
+}
diff --git a/app/Tests/BridgeplayInstallerCoreTests/InstallerServiceTests.swift b/app/Tests/BridgeplayInstallerCoreTests/InstallerServiceTests.swift
new file mode 100644
index 0000000..1adde0d
--- /dev/null
+++ b/app/Tests/BridgeplayInstallerCoreTests/InstallerServiceTests.swift
@@ -0,0 +1,461 @@
+import Darwin
+import Foundation
+import CryptoKit
+import Testing
+@testable import BridgeplayInstallerCore
+
+@Suite("Installer installation detection")
+struct InstallerServiceTests {
+ private let signature = Data(repeating: 0xA5, count: 64)
+ private let archiveURL = URL(string: "https://github.com/raymondchins/Bridgeplay/releases/download/v3.5.0/Bridgeplay.zip")!
+
+ private func temporaryDirectory() throws -> URL {
+ let directory = FileManager.default.temporaryDirectory.appending(path: "BridgeplayInstallerTests-\(UUID())", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ return directory
+ }
+
+ private func service(at destination: URL, gate: @escaping @Sendable () throws -> Void = {}) -> InstallerService {
+ InstallerService(destination: destination, ensureAppIsClosed: gate)
+ }
+
+ private func writeApp(at url: URL, identifier: String = InstallerService.bundleIdentifier,
+ version: String = "3.4.1", build: String = "34") throws {
+ let info: [String: Any] = [
+ "CFBundleIdentifier": identifier,
+ "CFBundleShortVersionString": version,
+ "CFBundleVersion": build,
+ "CFBundleExecutable": "BridgeplayApp",
+ ]
+ let infoURL = url.appending(path: "Contents/Info.plist")
+ try FileManager.default.createDirectory(at: infoURL.deletingLastPathComponent(), withIntermediateDirectories: true)
+ let data = try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)
+ try data.write(to: infoURL)
+ let executable = url.appending(path: "Contents/MacOS/BridgeplayApp")
+ try FileManager.default.createDirectory(at: executable.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("#!/bin/sh\nexit 0\n".utf8).write(to: executable)
+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path)
+ }
+
+ private func writeSignedApp(at url: URL, version: String, build: String) throws {
+ try writeApp(at: url, version: version, build: build)
+ let executable = url.appending(path: "Contents/MacOS/BridgeplayApp")
+ try FileManager.default.removeItem(at: executable)
+ try FileManager.default.copyItem(at: URL(fileURLWithPath: "/usr/bin/true"), to: executable)
+ try run("/usr/bin/codesign", ["--force", "--sign", "-", "--deep", url.path])
+ try run("/usr/bin/codesign", ["--verify", "--strict", "--deep", url.path])
+ }
+
+ private func installedBuild(at url: URL) throws -> String? {
+ let data = try Data(contentsOf: url.appending(path: "Contents/Info.plist"))
+ let propertyList = try PropertyListSerialization.propertyList(from: data, format: nil)
+ return (propertyList as? [String: Any])?["CFBundleVersion"] as? String
+ }
+
+ private func release(build: Int = 35, version: String = "3.5.0", minimumOS: String = "26.0",
+ signature: Data? = nil, key: Curve25519.Signing.PrivateKey? = nil) throws -> InstallerRelease {
+ try InstallerRelease(build: build, shortVersion: version, minimumOS: minimumOS,
+ archiveURL: archiveURL, archiveLength: 1234,
+ signature: signature ?? self.signature,
+ verificationKey: key?.publicKey.rawRepresentation ?? Data(repeating: 0, count: 32))
+ }
+
+ private func makeSignedArchive(in root: URL, build: String, version: String,
+ key: Curve25519.Signing.PrivateKey) throws -> (InstallerRelease, URL) {
+ let app = root.appending(path: "source/Bridgeplay.app", directoryHint: .isDirectory)
+ try writeSignedApp(at: app, version: version, build: build)
+
+ let archive = root.appending(path: "Bridgeplay.zip")
+ try run("/usr/bin/ditto", ["-c", "-k", "--keepParent", app.path, archive.path])
+ let data = try Data(contentsOf: archive)
+ let signature = try key.signature(for: data)
+ let release = try InstallerRelease(
+ build: Int(build)!, shortVersion: version, minimumOS: "26.0", archiveURL: archiveURL,
+ archiveLength: Int64(data.count), signature: signature,
+ verificationKey: key.publicKey.rawRepresentation
+ )
+ return (release, archive)
+ }
+
+ private func run(_ executable: String, _ arguments: [String]) throws {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: executable)
+ process.arguments = arguments
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ try process.run()
+ process.waitUntilExit()
+ #expect(process.terminationStatus == 0)
+ }
+
+ @Test func detectsFreshInstallWithoutMutation() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let destination = root.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ let state = try service(at: destination).state(for: release())
+ #expect(state == .notInstalled)
+ #expect(!FileManager.default.fileExists(atPath: destination.path))
+ }
+
+ @Test func identifiesAnAvailableUpdateAndKeepsUnrelatedDataUntouched() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let destination = root.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination)
+ let save = root.appending(path: "save.dat")
+ let config = root.appending(path: "default.conf")
+ try Data("save".utf8).write(to: save)
+ try Data("user override".utf8).write(to: config)
+ let state = try service(at: destination).state(for: release())
+ guard case .updateAvailable(let build, let version, _) = state else {
+ Issue.record("Expected an available update; received \(state).")
+ return
+ }
+ #expect(build == 34)
+ #expect(version == "3.4.1")
+ #expect(try Data(contentsOf: save) == Data("save".utf8))
+ #expect(try Data(contentsOf: config) == Data("user override".utf8))
+ }
+
+ @Test func treatsSameBuildAndVersionAsCurrent() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let destination = root.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination, version: "3.5.0", build: "35")
+ #expect(try service(at: destination).state(for: release()) == .upToDate(build: 35, version: "3.5.0"))
+ }
+
+ @Test func rejectsDowngradesAndInconsistentInstalledVersion() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let destination = root.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination, version: "3.6.0", build: "36")
+ do {
+ _ = try service(at: destination).state(for: release())
+ Issue.record("An older release must not replace a newer installed build.")
+ } catch let error as InstallerError {
+ guard case .downgrade(current: 36, offered: 35) = error else {
+ Issue.record("Expected downgrade, received \(error).")
+ return
+ }
+ }
+ try writeApp(at: destination, version: "3.5.1", build: "35")
+ do {
+ _ = try service(at: destination).state(for: release())
+ Issue.record("A version/build mismatch must not be reported as current.")
+ } catch let error as InstallerError {
+ guard case .invalidInstallation = error else {
+ Issue.record("Expected invalidInstallation, received \(error).")
+ return
+ }
+ }
+ }
+
+ @Test func refusesAnUnrelatedApplicationAtDestination() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let destination = root.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination, identifier: "com.example.other")
+ do {
+ _ = try service(at: destination).state(for: release())
+ Issue.record("An unrelated app at the destination must be preserved.")
+ } catch let error as InstallerError {
+ guard case .otherAppInstalled("com.example.other") = error else {
+ Issue.record("Expected otherAppInstalled, received \(error).")
+ return
+ }
+ }
+ #expect(FileManager.default.fileExists(atPath: destination.appending(path: "Contents/Info.plist").path))
+ }
+
+ @Test func refusesSymbolicLinkAtDestination() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let target = root.appending(path: "real-app", directoryHint: .isDirectory)
+ try writeApp(at: target)
+ let destination = root.appending(path: "Bridgeplay.app")
+ try FileManager.default.createSymbolicLink(at: destination, withDestinationURL: target)
+ do {
+ _ = try service(at: destination).state(for: release())
+ Issue.record("The install target must not follow a symbolic link.")
+ } catch let error as InstallerError {
+ guard case .invalidDestination = error else {
+ Issue.record("Expected invalidInstallation, received \(error).")
+ return
+ }
+ }
+ #expect(FileManager.default.fileExists(atPath: target.appending(path: "Contents/Info.plist").path))
+ }
+
+ @Test func refusesDanglingSymbolicLinkAtDestination() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let target = root.appending(path: "missing-app", directoryHint: .isDirectory)
+ let destination = root.appending(path: "Bridgeplay.app")
+ try FileManager.default.createSymbolicLink(at: destination, withDestinationURL: target)
+
+ #expect(throws: InstallerError.self) {
+ try service(at: destination).state(for: release())
+ }
+ #expect(try FileManager.default.destinationOfSymbolicLink(atPath: destination.path) == target.path)
+ }
+
+ @Test func rejectsUnsupportedSystemBeforeTouchingDestination() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let destination = root.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ #expect(throws: InstallerError.self) {
+ try service(at: destination).state(for: release(minimumOS: "99.0"))
+ }
+ #expect(!FileManager.default.fileExists(atPath: destination.path))
+ }
+
+ @Test func installsSignedArchiveIntoAnIsolatedDirectoryAndPreservesSiblingData() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let key = Curve25519.Signing.PrivateKey()
+ let (release, archive) = try makeSignedArchive(in: root, build: "35", version: "3.5.0", key: key)
+ let save = root.appending(path: "saves/slot.sav")
+ let config = root.appending(path: "Application Support/bridgeplay/gamefixes/default.conf")
+ try FileManager.default.createDirectory(at: save.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: config.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("save survives".utf8).write(to: save)
+ try Data("user settings survive".utf8).write(to: config)
+
+ let destination = root.appending(path: "Applications/Bridgeplay.app", directoryHint: .isDirectory)
+ let installed = try service(at: destination).install(release: release, archive: archive)
+ #expect(installed == destination)
+ #expect(try service(at: destination).state(for: release) == .upToDate(build: 35, version: "3.5.0"))
+ #expect(try Data(contentsOf: save) == Data("save survives".utf8))
+ #expect(try Data(contentsOf: config) == Data("user settings survive".utf8))
+ #expect(!FileManager.default.fileExists(atPath: root.appending(path: "Applications/.Bridgeplay.app.previous").path))
+ }
+
+ @Test func validatesBeforeReplacingAnExistingApp() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let key = Curve25519.Signing.PrivateKey()
+ let (release, archive) = try makeSignedArchive(in: root, build: "35", version: "3.5.0", key: key)
+ let destination = root.appending(path: "Applications/Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination, version: "3.4.1", build: "34")
+ let oldData = try Data(contentsOf: destination.appending(path: "Contents/Info.plist"))
+
+ var tampered = try Data(contentsOf: archive)
+ tampered[tampered.startIndex] ^= 0x1
+ try tampered.write(to: archive)
+ do {
+ try service(at: destination).install(release: release, archive: archive)
+ Issue.record("A changed archive must be rejected before the installed app is moved.")
+ } catch let error as InstallerError {
+ guard case .signatureMismatch = error else {
+ Issue.record("Expected signatureMismatch, received \(error).")
+ return
+ }
+ }
+
+ #expect(try Data(contentsOf: destination.appending(path: "Contents/Info.plist")) == oldData)
+ #expect(!FileManager.default.fileExists(atPath: root.appending(path: "Applications/.Bridgeplay.app.previous").path))
+ }
+
+ @Test func rejectsWrongSignedBundleAndKeepsExistingInstallation() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let key = Curve25519.Signing.PrivateKey()
+ let (release, archive) = try makeSignedArchive(in: root, build: "36", version: "3.6.0", key: key)
+ let destination = root.appending(path: "Applications/Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination, version: "3.4.1", build: "34")
+ let oldData = try Data(contentsOf: destination.appending(path: "Contents/Info.plist"))
+ let expectedRelease = try InstallerRelease(
+ build: 35, shortVersion: "3.5.0", minimumOS: "26.0", archiveURL: archiveURL,
+ archiveLength: release.archiveLength, signature: release.signature,
+ verificationKey: key.publicKey.rawRepresentation
+ )
+
+ do {
+ try service(at: destination).install(release: expectedRelease, archive: archive)
+ Issue.record("A validly signed app with a mismatching build/version must be rejected.")
+ } catch let error as InstallerError {
+ guard case .appValidation = error else {
+ Issue.record("Expected appValidation, received \(error).")
+ return
+ }
+ }
+ #expect(try Data(contentsOf: destination.appending(path: "Contents/Info.plist")) == oldData)
+ }
+
+ @Test func successfulUpdateRetainsVerifiedPreviousAppAndPersistentLockFile() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let key = Curve25519.Signing.PrivateKey()
+ let (release, archive) = try makeSignedArchive(in: root, build: "35", version: "3.5.0", key: key)
+ let destination = root.appending(path: "Applications/Bridgeplay.app", directoryHint: .isDirectory)
+ try writeSignedApp(at: destination, version: "3.4.1", build: "34")
+ let save = root.appending(path: "saves/slot.sav")
+ try FileManager.default.createDirectory(at: save.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("keep this save".utf8).write(to: save)
+
+ try service(at: destination).install(release: release, archive: archive)
+
+ let parent = root.appending(path: "Applications", directoryHint: .isDirectory)
+ let backup = parent.appending(path: ".Bridgeplay.app.previous", directoryHint: .isDirectory)
+ let lockURL = parent.appending(path: ".Bridgeplay.app.install.lock")
+ #expect(try installedBuild(at: destination) == "35")
+ #expect(try installedBuild(at: backup) == "34")
+ #expect(FileManager.default.fileExists(atPath: lockURL.path))
+ let lockMode = try FileManager.default.attributesOfItem(atPath: lockURL.path)[.posixPermissions] as? NSNumber
+ #expect(lockMode?.intValue == 0o644)
+ #expect(try Data(contentsOf: save) == Data("keep this save".utf8))
+ }
+
+ @Test func recoversPreviousBundleBeforeUpdatingAndPreservesUserData() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let key = Curve25519.Signing.PrivateKey()
+ let (release, archive) = try makeSignedArchive(in: root, build: "35", version: "3.5.0", key: key)
+ let parent = root.appending(path: "Applications", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true)
+ let destination = parent.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ let backup = parent.appending(path: ".Bridgeplay.app.previous", directoryHint: .isDirectory)
+ try writeSignedApp(at: backup, version: "3.4.1", build: "34")
+ let save = root.appending(path: "saves/slot.sav")
+ try FileManager.default.createDirectory(at: save.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("recovery must keep saves".utf8).write(to: save)
+
+ try service(at: destination).recoverIfNeeded()
+
+ guard case .updateAvailable(let build, let version, _) = try service(at: destination).state(for: release) else {
+ Issue.record("Recovery must restore the previous Bridgeplay build without installing the offered release.")
+ return
+ }
+ #expect(build == 34)
+ #expect(version == "3.4.1")
+ #expect(try installedBuild(at: destination) == "34")
+ #expect(!FileManager.default.fileExists(atPath: backup.path))
+ #expect(try Data(contentsOf: save) == Data("recovery must keep saves".utf8))
+ }
+
+ @Test func rejectsInstallWhileAnotherProcessHoldsPersistentLock() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let key = Curve25519.Signing.PrivateKey()
+ let (release, archive) = try makeSignedArchive(in: root, build: "35", version: "3.5.0", key: key)
+ let destination = root.appending(path: "Applications/Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination, version: "3.4.1", build: "34")
+ let oldInfo = try Data(contentsOf: destination.appending(path: "Contents/Info.plist"))
+ let lockURL = root.appending(path: "Applications/.Bridgeplay.app.install.lock")
+ let lockPath = lockURL.path
+ let creatorDescriptor = open(lockPath, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
+ #expect(creatorDescriptor >= 0)
+ guard creatorDescriptor >= 0 else { return }
+ close(creatorDescriptor)
+ try FileManager.default.setAttributes([.posixPermissions: 0o444], ofItemAtPath: lockPath)
+ let descriptor = open(lockPath, O_RDONLY | O_NOFOLLOW)
+ #expect(descriptor >= 0)
+ guard descriptor >= 0 else { return }
+ defer {
+ flock(descriptor, LOCK_UN)
+ close(descriptor)
+ }
+ #expect(flock(descriptor, LOCK_EX | LOCK_NB) == 0)
+
+ do {
+ try service(at: destination).install(release: release, archive: archive)
+ Issue.record("An installer must not proceed while another installer holds the lock.")
+ } catch let error as InstallerError {
+ guard case .installLocked = error else {
+ Issue.record("Expected installLocked, received \(error).")
+ return
+ }
+ }
+
+ #expect(try Data(contentsOf: destination.appending(path: "Contents/Info.plist")) == oldInfo)
+ #expect(FileManager.default.fileExists(atPath: lockPath))
+ }
+
+ @Test func readOnlyDestinationDoesNotDeleteInstalledAppOrUserData() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: root.path) }
+ defer { try? FileManager.default.removeItem(at: root) }
+ let key = Curve25519.Signing.PrivateKey()
+ let (release, archive) = try makeSignedArchive(in: root, build: "35", version: "3.5.0", key: key)
+ let parent = root.appending(path: "readonly", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true)
+ let destination = parent.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination, version: "3.4.1", build: "34")
+ let oldInfo = try Data(contentsOf: destination.appending(path: "Contents/Info.plist"))
+ let save = root.appending(path: "save.dat")
+ try Data("unchanged".utf8).write(to: save)
+ try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: parent.path)
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: parent.path) }
+
+ do {
+ try service(at: destination).install(release: release, archive: archive)
+ Issue.record("A read-only install parent must reject replacement.")
+ } catch let error as InstallerError {
+ guard case .writeFailure = error else {
+ Issue.record("Expected writeFailure, received \(error).")
+ return
+ }
+ }
+
+ #expect(try Data(contentsOf: destination.appending(path: "Contents/Info.plist")) == oldInfo)
+ #expect(try Data(contentsOf: save) == Data("unchanged".utf8))
+ }
+
+ @Test func injectedProcessGatePreventsAnyInstallMutation() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let key = Curve25519.Signing.PrivateKey()
+ let (release, archive) = try makeSignedArchive(in: root, build: "35", version: "3.5.0", key: key)
+ let destination = root.appending(path: "Applications/Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination, version: "3.4.1", build: "34")
+ let oldInfo = try Data(contentsOf: destination.appending(path: "Contents/Info.plist"))
+
+ do {
+ try service(at: destination, gate: { throw InstallerError.appIsRunning })
+ .install(release: release, archive: archive)
+ Issue.record("The process gate must prevent app replacement.")
+ } catch let error as InstallerError {
+ guard case .appIsRunning = error else {
+ Issue.record("Expected appIsRunning, received \(error).")
+ return
+ }
+ }
+
+ #expect(try Data(contentsOf: destination.appending(path: "Contents/Info.plist")) == oldInfo)
+ #expect(!FileManager.default.fileExists(atPath: root.appending(path: "Applications/.Bridgeplay.app.previous").path))
+ }
+
+ @Test func restoresOriginalAppIfStagedBundleDisappearsDuringReplacement() throws {
+ let root = try temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let key = Curve25519.Signing.PrivateKey()
+ let (release, archive) = try makeSignedArchive(in: root, build: "35", version: "3.5.0", key: key)
+ let parent = root.appending(path: "Applications", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true)
+ let destination = parent.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeSignedApp(at: destination, version: "3.4.1", build: "34")
+ let oldInfo = try Data(contentsOf: destination.appending(path: "Contents/Info.plist"))
+ let service = InstallerService(destination: destination, ensureAppIsClosed: {
+ let stages = try FileManager.default.contentsOfDirectory(at: parent, includingPropertiesForKeys: nil)
+ .filter { $0.lastPathComponent.hasPrefix(".BridgeplayInstaller-") }
+ guard let stagedApp = stages.first?.appending(path: "payload/Bridgeplay.app") else {
+ throw InstallerError.appValidation("The staged app fixture is missing.")
+ }
+ try FileManager.default.removeItem(at: stagedApp)
+ })
+
+ do {
+ try service.install(release: release, archive: archive)
+ Issue.record("A vanished staged app must fail and restore the previous install.")
+ } catch let error as InstallerError {
+ guard case .replacementFailure = error else {
+ Issue.record("Expected replacementFailure, received \(error).")
+ return
+ }
+ }
+
+ #expect(try Data(contentsOf: destination.appending(path: "Contents/Info.plist")) == oldInfo)
+ #expect(!FileManager.default.fileExists(atPath: parent.appending(path: ".Bridgeplay.app.previous").path))
+ }
+}
diff --git a/docs/NATIVE-INSTALLER.md b/docs/NATIVE-INSTALLER.md
new file mode 100644
index 0000000..9a936eb
--- /dev/null
+++ b/docs/NATIVE-INSTALLER.md
@@ -0,0 +1,85 @@
+# Native installer DMG
+
+The native installer is an optional small bootstrap for a new installation or an app
+update. It downloads the existing Bridgeplay release, verifies its Sparkle EdDSA signature
+before extraction, and installs the app in `/Applications/Bridgeplay.app`. It does not
+bundle Wine, GPTK, or the product's payload. Discussion: [issue #17](https://github.com/raymondchins/Bridgeplay/issues/17).
+
+## Build
+
+```sh
+make native-installer
+```
+
+This builds the `BridgeplayInstaller` SwiftPM product for arm64, copies its two resource
+bundles and font license files, compiles installer translations, renders the existing
+Bridgeplay mark as the icon, signs the app and packages `out/Bridgeplay-Installer.dmg`.
+The default is an ad hoc local build. `BRIDGEPLAY_SIGN_IDENTITY` selects the maintainer's
+signing identity. The default size budget is 5 MiB; a larger artifact fails packaging.
+`BRIDGEPLAY_INSTALLER_MAX_BYTES` can override the budget for a deliberate size review.
+
+CI also packages the DMG as a build artifact and runs `native-installercheck`.
+The bootstrap can be built separately from the full app/Wine toolchain. Follow
+[BUILD-LOCAL.md](BUILD-LOCAL.md) for the product build, which still requires Xcode.
+Creating an ad hoc DMG does not provide Developer ID signing or notarization. Test a
+quarantined browser download before claiming a frictionless public installation.
+
+## Behavior
+
+The wizard checks the release and installed app, then offers Install or Update. An already
+current app requires no download. A newer installed build is kept; the installer refuses a
+downgrade. A different application or unsafe destination is not replaced.
+
+The app archive is authenticated with the same public key as the installed app's Sparkle
+updater. The app's identity, build, version and code signature are checked before replacement.
+The installer stages on the destination volume, coordinates through a persistent lock,
+refuses an active Bridgeplay/updater process, and keeps the prior app in the hidden
+`.Bridgeplay.app.previous` sibling for recovery. An interrupted replacement is recovered
+locally before release discovery, including when the network is unavailable. Unexpected
+backup contents are preserved and reported instead of deleted.
+
+Prefixes, saves, Steam libraries, support folders and user configuration are not rewritten
+by the bootstrap. Opening the installed app continues its existing Setup Assistant or
+Status/update flow. Engine/graphics downloads and Steam setup remain the app's responsibility;
+the existing Apple toolkit download/import path is preserved. This DMG does not replace the
+existing bundled ZIP installer or alter Sparkle's update feed.
+
+On Finish, users may open Bridgeplay and eject/move the source DMG to Trash. Cleanup is
+available only when the exact source image is identified from `hdiutil` metadata. A copied
+helper outside the mounted volume waits for the installer to exit, rechecks image identity,
+ejects and uses macOS Trash. Cleanup failures preserve the image and show a message. No
+permanent deletion is used for the downloaded DMG.
+
+## Verification
+
+Run the focused installer core tests with the full app tests on the supported Xcode:
+
+```sh
+make app-tests
+make scriptcheck runcheck native-installercheck
+```
+
+`scripts/test-native-installer.sh` runs an additional standalone smoke suite against the
+production core sources without depending on the full app test bundle. It uses generated
+signing keys and temporary app roots, leaving installed apps and game data alone.
+
+For visual review, the executable supports deterministic, non-mutating preview states:
+
+```sh
+app/.build/debug/BridgeplayInstaller --preview update --screenshot /tmp/installer-update.png
+```
+
+For an isolated GUI test, a debug build also accepts `--test-destination` with a
+`Bridgeplay.app` path inside the macOS temporary directory. Release builds always use
+Applications. Do not open the installed test app unless you intend to exercise real setup.
+
+States are `review`, `update`, `download`, `install`, `done`, `current`, and `error`.
+Preview screenshots establish appearance; they do not establish install/update success.
+
+Before public rollout, exercise a fresh install, older/current/newer app, real component
+setup, offline/retry, rejected signatures, low disk/permission failures, concurrent
+install/update, interrupted replacement, multiple macOS users, external/case-sensitive
+volumes, supported OS versions, all locales, keyboard/VoiceOver, and cleanup enabled/disabled.
+Record the actual packaged size and separate local ad hoc verification from maintainer-signed
+release validation. The contributor writes the PR description personally per CONTRIBUTING.md;
+release publishing and keys remain with the maintainer.
diff --git a/installer/tests/native-installer-cleanup-smoke.swift b/installer/tests/native-installer-cleanup-smoke.swift
new file mode 100644
index 0000000..512596e
--- /dev/null
+++ b/installer/tests/native-installer-cleanup-smoke.swift
@@ -0,0 +1,45 @@
+import AppKit
+import Foundation
+
+func tr(_ value: String.LocalizationValue) -> String { String(localized: value) }
+enum InstallerResources { static let bundle = Bundle.main }
+
+@main
+struct CleanupSmoke {
+ @MainActor
+ static func main() throws {
+ let fm = FileManager.default
+ let root = fm.temporaryDirectory.appendingPathComponent("bridgeplay-cleanup-tests-\(UUID().uuidString)")
+ try fm.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? fm.removeItem(at: root) }
+ let image = root.appendingPathComponent("Installer.dmg")
+ try Data("test image identity".utf8).write(to: image)
+ let executable = URL(fileURLWithPath: "/Volumes/Test Installer/Bridgeplay Installer.app/Contents/MacOS/BridgeplayInstaller")
+ func info(image: URL, mount: String = "/Volumes/Test Installer", device: String = "/dev/disk123s1") throws -> Data {
+ try PropertyListSerialization.data(fromPropertyList: ["images": [
+ ["image-path": image.path, "system-entities": [["mount-point": mount, "dev-entry": device]]]
+ ]], format: .xml, options: 0)
+ }
+ var passed = 0
+ func expect(_ condition: Bool, _ message: String) throws {
+ guard condition else { throw NSError(domain: message, code: 1) }
+ passed += 1
+ print("PASS \(message)")
+ }
+ let source = try InstallerCleanup.source(containing: executable, info: info(image: image))
+ try expect(source?.image == image, "exact source image from disk metadata")
+ try expect(source?.device == "/dev/disk123s1", "exact mounted device")
+ let decoy = URL(fileURLWithPath: "/Volumes/Test Installer-other/App")
+ try expect(try InstallerCleanup.source(containing: decoy, info: info(image: image)) == nil, "mount prefix boundary")
+ try expect(try InstallerCleanup.source(containing: executable, info: info(image: image, device: "/tmp/fake")) == nil, "unsafe device rejected")
+ try expect(try InstallerCleanup.source(containing: executable, info: info(image: image, mount: "/")) == nil, "root mount rejected")
+ let link = root.appendingPathComponent("link.dmg")
+ try fm.createSymbolicLink(at: link, withDestinationURL: image)
+ try expect(try InstallerCleanup.source(containing: executable, info: info(image: link)) == nil, "symlink image rejected")
+ let other = root.appendingPathComponent("file.txt")
+ try Data().write(to: other)
+ try expect(try InstallerCleanup.source(containing: executable, info: info(image: other)) == nil, "unrelated source file preserved")
+ try expect(try InstallerCleanup.source(containing: executable, info: info(image: root.appendingPathComponent("missing.dmg"))) == nil, "missing source preserved")
+ print("Cleanup smoke: \(passed) checks passed; no mounted image or Trash modified.")
+ }
+}
diff --git a/installer/tests/native-installer-core-smoke.swift b/installer/tests/native-installer-core-smoke.swift
new file mode 100644
index 0000000..4230037
--- /dev/null
+++ b/installer/tests/native-installer-core-smoke.swift
@@ -0,0 +1,498 @@
+import CryptoKit
+import Darwin
+import Foundation
+
+@main
+struct NativeInstallerCoreSmoke {
+ private static let archiveURL = URL(
+ string: "https://github.com/raymondchins/Bridgeplay/releases/download/v3.5.0/Bridgeplay.zip"
+ )!
+
+ static func main() {
+ do {
+ try run()
+ } catch {
+ fputs("FAIL: \(error)\n", stderr)
+ exit(EXIT_FAILURE)
+ }
+ }
+
+ private static func run() throws {
+ guard CommandLine.arguments.count == 2 else {
+ throw SmokeFailure("Pass one temporary work directory.")
+ }
+ let root = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+
+ try testAppcastValidation()
+ print("PASS appcast fields, URL, size, version, hardware, and XML validation")
+
+ let key = Curve25519.Signing.PrivateKey()
+ let bytes = Data("signed fixture".utf8)
+ let signature = try key.signature(for: bytes)
+ try InstallerRelease.verify(bytes, signature: signature, publicKey: key.publicKey.rawRepresentation)
+ try expectInstallerError("tampered signature") {
+ try InstallerRelease.verify(Data("tampered fixture".utf8), signature: signature,
+ publicKey: key.publicKey.rawRepresentation)
+ } matches: {
+ if case .signatureMismatch = $0 { return true }
+ return false
+ }
+ print("PASS Ed25519 signature accepts authentic bytes and rejects tampering")
+
+ let (release35, archive35) = try makeSignedArchive(in: root, build: "35", version: "3.5.0", key: key)
+ try testDetectionAndInstall(release: release35, archive: archive35, key: key, root: root)
+ try testRejectedReplacement(release: release35, archive: archive35, root: root)
+ try testLockAndReadonlyLock(release: release35, archive: archive35, root: root)
+ try testReadonlyParent(release: release35, archive: archive35, root: root)
+ try testProcessGate(release: release35, archive: archive35, root: root)
+ try testRollback(release: release35, archive: archive35, root: root)
+ try testBackupRecovery(release: release35, root: root)
+ try testDanglingSymlink(root: root)
+
+ print("PASS isolated fresh install, update detection, user-data preservation, backup recovery, rollback, lock, and destination checks")
+ print("PASS all native installer core smoke checks")
+ }
+
+ private static func testAppcastValidation() throws {
+ let signature = Data(repeating: 0xA5, count: 64).base64EncodedString()
+ let valid = appcast(signature: signature, minimumOS: "26.0.1")
+ let release = try InstallerRelease.parse(appcast: valid)
+ try require(release.build == 35 && release.shortVersion == "3.5.0", "parsed build and release version")
+ try require(release.minimumOS == "26.0.1", "three-component minimum OS version")
+ try require(release.archiveLength == 512 && release.archiveURL == archiveURL, "archive metadata")
+
+ _ = try InstallerRelease.parse(appcast: appcast(signature: signature, minimumOS: "26.0"))
+ try expectInstallerError("wrong archive host") {
+ _ = try InstallerRelease.parse(appcast: appcast(signature: signature,
+ archive: "https://github.com.attacker.invalid/raymondchins/Bridgeplay/releases/download/v3.5.0/Bridgeplay.zip"))
+ }
+ try expectInstallerError("wrong archive path") {
+ _ = try InstallerRelease.parse(appcast: appcast(signature: signature,
+ archive: "https://github.com/raymondchins/Bridgeplay/releases/download/v3.5.0/Other.zip"))
+ }
+ try expectInstallerError("oversized archive length") {
+ _ = try InstallerRelease.parse(appcast: appcast(signature: signature, length: "1073741825"))
+ }
+ try expectInstallerError("invalid version") {
+ _ = try InstallerRelease.parse(appcast: appcast(signature: signature, version: "3.release"))
+ }
+ try expectInstallerError("four-component OS version") {
+ _ = try InstallerRelease.parse(appcast: appcast(signature: signature, minimumOS: "26.0.1.1"))
+ }
+ try expectInstallerError("wrong hardware") {
+ _ = try InstallerRelease.parse(appcast: appcast(signature: signature, hardware: "x86_64"))
+ }
+ try expectInstallerError("missing hardware") {
+ _ = try InstallerRelease.parse(appcast: appcast(signature: signature, hardware: nil))
+ }
+ try expectInstallerError("DTD") {
+ _ = try InstallerRelease.parse(appcast: Data("<!DOCTYPE rss [<!ENTITY x SYSTEM 'file:///etc/passwd'>]><rss>&x;</rss>".utf8))
+ }
+ try expectInstallerError("oversized feed") {
+ _ = try InstallerRelease.parse(appcast: Data(repeating: 0x20, count: 256_001))
+ }
+ }
+
+ private static func appcast(
+ signature: String,
+ minimumOS: String = "26.0",
+ archive: String = "https://github.com/raymondchins/Bridgeplay/releases/download/v3.5.0/Bridgeplay.zip",
+ length: String = "512",
+ version: String = "3.5.0",
+ hardware: String? = "arm64"
+ ) -> Data {
+ let hardwareElement = hardware.map { "<sparkle:hardwareRequirements>\($0)</sparkle:hardwareRequirements>" } ?? ""
+ let xml = """
+ <?xml version="1.0" standalone="yes"?>
+ <rss xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle" version="2.0">
+ <channel><item>
+ <sparkle:version>35</sparkle:version>
+ <sparkle:shortVersionString>\(version)</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>\(minimumOS)</sparkle:minimumSystemVersion>
+ \(hardwareElement)
+ <enclosure url="\(archive)" length="\(length)" type="application/octet-stream"
+ sparkle:edSignature="\(signature)" />
+ </item></channel>
+ </rss>
+ """
+ return Data(xml.utf8)
+ }
+
+ private static func testDetectionAndInstall(
+ release: InstallerRelease,
+ archive: URL,
+ key: Curve25519.Signing.PrivateKey,
+ root: URL
+ ) throws {
+ let directory = root.appending(path: "install-flow", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let destination = directory.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ let service = InstallerService(destination: destination, ensureAppIsClosed: {})
+ try require(try service.state(for: release) == .notInstalled, "new-install detection")
+
+ let save = directory.appending(path: "saves/slot.sav")
+ let config = directory.appending(path: "Application Support/bridgeplay/gamefixes/default.conf")
+ try FileManager.default.createDirectory(at: save.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: config.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("save survives".utf8).write(to: save)
+ try Data("user config survives".utf8).write(to: config)
+
+ try service.install(release: release, archive: archive)
+ try require(try service.state(for: release) == .upToDate(build: 35, version: "3.5.0"), "installed version is current")
+ try require(try Data(contentsOf: save) == Data("save survives".utf8), "save remains untouched")
+ try require(try Data(contentsOf: config) == Data("user config survives".utf8), "config remains untouched")
+ let lockMode = try FileManager.default.attributesOfItem(
+ atPath: directory.appending(path: ".Bridgeplay.app.install.lock").path
+ )[.posixPermissions] as? NSNumber
+ try require(lockMode?.intValue == 0o644, "persistent lock is readable by other macOS accounts")
+
+ let updateDirectory = root.appending(path: "update-flow", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: updateDirectory, withIntermediateDirectories: true)
+ let updateDestination = updateDirectory.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeSignedApp(at: updateDestination, version: "3.4.1", build: "34")
+ let updateService = InstallerService(destination: updateDestination, ensureAppIsClosed: {})
+ guard case .updateAvailable(let currentBuild, let currentVersion, _) = try updateService.state(for: release) else {
+ throw SmokeFailure("Existing Bridgeplay did not report an available update.")
+ }
+ try require(currentBuild == 34 && currentVersion == "3.4.1", "update detection")
+
+ let olderRelease = try makeRelease(build: 33, version: "3.3.0", archive: archive, key: key)
+ try expectInstallerError("downgrade") {
+ _ = try updateService.state(for: olderRelease)
+ } matches: {
+ if case .downgrade(current: 34, offered: 33) = $0 { return true }
+ return false
+ }
+ let unsupported = try makeRelease(build: 35, version: "3.5.0", minimumOS: "99.0", archive: archive, key: key)
+ try expectInstallerError("minimum OS") {
+ _ = try updateService.state(for: unsupported)
+ } matches: {
+ if case .unsupportedSystem(minimum: "99.0") = $0 { return true }
+ return false
+ }
+
+ try updateService.install(release: release, archive: archive)
+ let previousApp = updateDirectory.appending(path: ".Bridgeplay.app.previous", directoryHint: .isDirectory)
+ try require(try installedBuild(at: updateDestination) == "35", "update installs offered build")
+ try require(try installedBuild(at: previousApp) == "34", "update retains previous signed build")
+
+ let unrelatedDirectory = root.appending(path: "unrelated-app", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: unrelatedDirectory, withIntermediateDirectories: true)
+ let unrelated = unrelatedDirectory.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: unrelated, identifier: "com.example.other", version: "1.0", build: "1")
+ let unrelatedService = InstallerService(destination: unrelated, ensureAppIsClosed: {})
+ try expectInstallerError("unrelated app") {
+ _ = try unrelatedService.state(for: release)
+ } matches: {
+ if case .otherAppInstalled("com.example.other") = $0 { return true }
+ return false
+ }
+ }
+
+ private static func testRejectedReplacement(release: InstallerRelease, archive: URL, root: URL) throws {
+ let directory = root.appending(path: "reject-replacement", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let destination = directory.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination, version: "3.4.1", build: "34")
+ let originalInfo = try Data(contentsOf: destination.appending(path: "Contents/Info.plist"))
+ let tampered = directory.appending(path: "tampered.zip")
+ var bytes = try Data(contentsOf: archive)
+ bytes[bytes.startIndex] ^= 0x1
+ try bytes.write(to: tampered)
+
+ let service = InstallerService(destination: destination, ensureAppIsClosed: {})
+ try expectInstallerError("tampered archive replacement") {
+ try service.install(release: release, archive: tampered)
+ } matches: {
+ if case .signatureMismatch = $0 { return true }
+ return false
+ }
+ try require(try Data(contentsOf: destination.appending(path: "Contents/Info.plist")) == originalInfo,
+ "signature failure leaves prior app intact")
+ }
+
+ private static func testLockAndReadonlyLock(release: InstallerRelease, archive: URL, root: URL) throws {
+ let directory = root.appending(path: "locked-install", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let destination = directory.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination, version: "3.4.1", build: "34")
+ let originalInfo = try Data(contentsOf: destination.appending(path: "Contents/Info.plist"))
+ let lockURL = directory.appending(path: ".Bridgeplay.app.install.lock")
+ let fd = open(lockURL.path, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)
+ guard fd >= 0 else { throw SmokeFailure("Could not create lock fixture: \(String(cString: strerror(errno)))") }
+ defer {
+ flock(fd, LOCK_UN)
+ close(fd)
+ }
+ try require(flock(fd, LOCK_EX | LOCK_NB) == 0, "fixture obtains install lock")
+ let service = InstallerService(destination: destination, ensureAppIsClosed: {})
+ try expectInstallerError("concurrent installer lock") {
+ try service.install(release: release, archive: archive)
+ } matches: {
+ if case .installLocked = $0 { return true }
+ return false
+ }
+ try require(try Data(contentsOf: destination.appending(path: "Contents/Info.plist")) == originalInfo,
+ "locked install leaves prior app intact")
+
+ let readonlyDirectory = root.appending(path: "readonly-lock", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: readonlyDirectory, withIntermediateDirectories: true)
+ let readonlyDestination = readonlyDirectory.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: readonlyDestination, version: "3.4.1", build: "34")
+ let readonlyLock = readonlyDirectory.appending(path: ".Bridgeplay.app.install.lock")
+ try Data().write(to: readonlyLock)
+ try FileManager.default.setAttributes([.posixPermissions: 0o444], ofItemAtPath: readonlyLock.path)
+ let readonlyFD = open(readonlyLock.path, O_RDONLY | O_NOFOLLOW)
+ guard readonlyFD >= 0 else { throw SmokeFailure("Could not open shared lock read-only.") }
+ defer {
+ flock(readonlyFD, LOCK_UN)
+ close(readonlyFD)
+ }
+ try require(flock(readonlyFD, LOCK_EX | LOCK_NB) == 0, "another macOS account can hold an exclusive read-only lock")
+ let readonlyInfo = try Data(contentsOf: readonlyDestination.appending(path: "Contents/Info.plist"))
+ let readonlyService = InstallerService(destination: readonlyDestination, ensureAppIsClosed: {})
+ try expectInstallerError("read-only persistent lock") {
+ try readonlyService.install(release: release, archive: archive)
+ } matches: {
+ if case .installLocked = $0 { return true }
+ return false
+ }
+ try require(try Data(contentsOf: readonlyDestination.appending(path: "Contents/Info.plist")) == readonlyInfo,
+ "read-only lock leaves prior app intact")
+ }
+
+ private static func testReadonlyParent(release: InstallerRelease, archive: URL, root: URL) throws {
+ guard geteuid() != 0 else {
+ print("SKIP read-only parent: smoke runner is root and bypasses POSIX write permissions")
+ return
+ }
+ let directory = root.appending(path: "readonly-parent", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let destination = directory.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination, version: "3.4.1", build: "34")
+ let originalInfo = try Data(contentsOf: destination.appending(path: "Contents/Info.plist"))
+ let save = root.appending(path: "readonly-save.dat")
+ try Data("untouched".utf8).write(to: save)
+ try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: directory.path)
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: directory.path) }
+
+ let service = InstallerService(destination: destination, ensureAppIsClosed: {})
+ try expectInstallerError("read-only install parent") {
+ try service.install(release: release, archive: archive)
+ } matches: {
+ if case .writeFailure = $0 { return true }
+ return false
+ }
+ try require(try Data(contentsOf: destination.appending(path: "Contents/Info.plist")) == originalInfo,
+ "read-only parent leaves prior app intact")
+ try require(try Data(contentsOf: save) == Data("untouched".utf8), "read-only install leaves save intact")
+ }
+
+ private static func testProcessGate(release: InstallerRelease, archive: URL, root: URL) throws {
+ let directory = root.appending(path: "running-app", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let destination = directory.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeApp(at: destination, version: "3.4.1", build: "34")
+ let originalInfo = try Data(contentsOf: destination.appending(path: "Contents/Info.plist"))
+ let service = InstallerService(destination: destination, ensureAppIsClosed: {
+ throw InstallerError.appIsRunning
+ })
+ try expectInstallerError("running app process gate") {
+ try service.install(release: release, archive: archive)
+ } matches: {
+ if case .appIsRunning = $0 { return true }
+ return false
+ }
+ try require(try Data(contentsOf: destination.appending(path: "Contents/Info.plist")) == originalInfo,
+ "process gate leaves prior app intact")
+ }
+
+ private static func testRollback(release: InstallerRelease, archive: URL, root: URL) throws {
+ let directory = root.appending(path: "rollback", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let destination = directory.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ try writeSignedApp(at: destination, version: "3.4.1", build: "34")
+ let originalInfo = try Data(contentsOf: destination.appending(path: "Contents/Info.plist"))
+ let service = InstallerService(destination: destination, ensureAppIsClosed: {
+ let stage = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)
+ .first { $0.lastPathComponent.hasPrefix(".BridgeplayInstaller-") }
+ guard let stagedApp = stage?.appending(path: "payload/Bridgeplay.app") else {
+ throw SmokeFailure("Validated staging directory was not found.")
+ }
+ try FileManager.default.removeItem(at: stagedApp)
+ })
+ try expectInstallerError("replacement rollback") {
+ try service.install(release: release, archive: archive)
+ } matches: {
+ if case .replacementFailure = $0 { return true }
+ return false
+ }
+ try require(try Data(contentsOf: destination.appending(path: "Contents/Info.plist")) == originalInfo,
+ "failed replacement restores previous app")
+ try require(!FileManager.default.fileExists(atPath: directory.appending(path: ".Bridgeplay.app.previous").path),
+ "rollback consumes recovery backup only after restoring it")
+ }
+
+ private static func testBackupRecovery(release: InstallerRelease, root: URL) throws {
+ let directory = root.appending(path: "backup-recovery", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let destination = directory.appending(path: "Bridgeplay.app", directoryHint: .isDirectory)
+ let backup = directory.appending(path: ".Bridgeplay.app.previous", directoryHint: .isDirectory)
+ try writeSignedApp(at: backup, version: "3.4.1", build: "34")
+ let save = directory.appending(path: "saves/slot.sav")
+ try FileManager.default.createDirectory(at: save.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("survive backup recovery".utf8).write(to: save)
+ let service = InstallerService(destination: destination, ensureAppIsClosed: {})
+ try service.recoverIfNeeded()
+ guard case .updateAvailable(let build, let version, _) = try service.state(for: release) else {
+ throw SmokeFailure("Recovery must restore the previous app without installing the offered release.")
+ }
+ try require(build == 34 && version == "3.4.1", "recovered prior build detected as update available")
+ try require(try installedBuild(at: destination) == "34", "recovered previous app is restored")
+ try require(!FileManager.default.fileExists(atPath: backup.path), "restored backup path is cleared")
+ try require(try Data(contentsOf: save) == Data("survive backup recovery".utf8), "backup recovery preserves save")
+ }
+
+ private static func testDanglingSymlink(root: URL) throws {
+ let directory = root.appending(path: "dangling-symlink", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let destination = directory.appending(path: "Bridgeplay.app")
+ let target = directory.appending(path: "target-does-not-exist")
+ try FileManager.default.createSymbolicLink(at: destination, withDestinationURL: target)
+ let release = try InstallerRelease(
+ build: 35,
+ shortVersion: "3.5.0",
+ minimumOS: "1.0",
+ archiveURL: archiveURL,
+ archiveLength: 1,
+ signature: Data(repeating: 0, count: 64)
+ )
+ let service = InstallerService(destination: destination, ensureAppIsClosed: {})
+ try expectInstallerError("dangling destination symlink") {
+ _ = try service.state(for: release)
+ } matches: {
+ if case .invalidDestination = $0 { return true }
+ return false
+ }
+ try require(try FileManager.default.destinationOfSymbolicLink(atPath: destination.path) == target.path,
+ "dangling destination link remains untouched")
+ }
+
+ private static func makeSignedArchive(
+ in root: URL,
+ build: String,
+ version: String,
+ key: Curve25519.Signing.PrivateKey
+ ) throws -> (InstallerRelease, URL) {
+ let source = root.appending(path: "source-\(build)/Bridgeplay.app", directoryHint: .isDirectory)
+ try writeSignedApp(at: source, version: version, build: build)
+ let archive = root.appending(path: "Bridgeplay-\(build).zip")
+ try run("/usr/bin/ditto", ["-c", "-k", "--keepParent", source.path, archive.path])
+ let bytes = try Data(contentsOf: archive)
+ let release = try InstallerRelease(
+ build: Int(build)!,
+ shortVersion: version,
+ minimumOS: "1.0",
+ archiveURL: archiveURL,
+ archiveLength: Int64(bytes.count),
+ signature: try key.signature(for: bytes),
+ verificationKey: key.publicKey.rawRepresentation
+ )
+ return (release, archive)
+ }
+
+ private static func makeRelease(
+ build: Int,
+ version: String,
+ minimumOS: String = "1.0",
+ archive: URL,
+ key: Curve25519.Signing.PrivateKey
+ ) throws -> InstallerRelease {
+ let bytes = try Data(contentsOf: archive)
+ return try InstallerRelease(
+ build: build,
+ shortVersion: version,
+ minimumOS: minimumOS,
+ archiveURL: archiveURL,
+ archiveLength: Int64(bytes.count),
+ signature: try key.signature(for: bytes),
+ verificationKey: key.publicKey.rawRepresentation
+ )
+ }
+
+ private static func writeApp(
+ at url: URL,
+ identifier: String = InstallerService.bundleIdentifier,
+ version: String,
+ build: String
+ ) throws {
+ let info: [String: Any] = [
+ "CFBundleIdentifier": identifier,
+ "CFBundleShortVersionString": version,
+ "CFBundleVersion": build,
+ "CFBundleExecutable": "BridgeplayApp",
+ ]
+ let infoURL = url.appending(path: "Contents/Info.plist")
+ try FileManager.default.createDirectory(at: infoURL.deletingLastPathComponent(), withIntermediateDirectories: true)
+ let data = try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)
+ try data.write(to: infoURL)
+ let executable = url.appending(path: "Contents/MacOS/BridgeplayApp")
+ try FileManager.default.createDirectory(at: executable.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("#!/bin/sh\nexit 0\n".utf8).write(to: executable)
+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path)
+ }
+
+ private static func writeSignedApp(at url: URL, version: String, build: String) throws {
+ try writeApp(at: url, version: version, build: build)
+ let executable = url.appending(path: "Contents/MacOS/BridgeplayApp")
+ try FileManager.default.removeItem(at: executable)
+ try FileManager.default.copyItem(at: URL(fileURLWithPath: "/usr/bin/true"), to: executable)
+ try run("/usr/bin/codesign", ["--force", "--sign", "-", "--deep", url.path])
+ try run("/usr/bin/codesign", ["--verify", "--strict", "--deep", url.path])
+ }
+
+ private static func installedBuild(at url: URL) throws -> String? {
+ let data = try Data(contentsOf: url.appending(path: "Contents/Info.plist"))
+ let propertyList = try PropertyListSerialization.propertyList(from: data, format: nil)
+ return (propertyList as? [String: Any])?["CFBundleVersion"] as? String
+ }
+
+ private static func run(_ executable: String, _ arguments: [String]) throws {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: executable)
+ process.arguments = arguments
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ try process.run()
+ process.waitUntilExit()
+ guard process.terminationStatus == 0 else {
+ throw SmokeFailure("\(executable) exited with status \(process.terminationStatus).")
+ }
+ }
+
+ private static func expectInstallerError(
+ _ name: String,
+ operation: () throws -> Void,
+ matches: (InstallerError) -> Bool = { _ in true }
+ ) throws {
+ do {
+ try operation()
+ throw SmokeFailure("Expected \(name) to fail.")
+ } catch let error as InstallerError {
+ guard matches(error) else { throw SmokeFailure("Unexpected error for \(name): \(error.localizedDescription)") }
+ }
+ }
+
+ private static func require(_ condition: @autoclosure () throws -> Bool, _ message: String) throws {
+ guard try condition() else { throw SmokeFailure("Assertion failed: \(message)") }
+ }
+}
+
+private struct SmokeFailure: Error, CustomStringConvertible {
+ let message: String
+
+ init(_ message: String) { self.message = message }
+
+ var description: String { message }
+}
diff --git a/scripts/package-native-installer.sh b/scripts/package-native-installer.sh
new file mode 100755
index 0000000..d47d178
--- /dev/null
+++ b/scripts/package-native-installer.sh
@@ -0,0 +1,85 @@
+#!/bin/sh
+# Build a small native bootstrap DMG without Wine, GPTK or the product payload.
+set -eu
+repo=$(cd "$(dirname "$0")/.." && pwd)
+cd "$repo"
+identity=${BRIDGEPLAY_SIGN_IDENTITY:--}
+configuration=${CONFIGURATION:-release}
+out="$repo/out/native-installer"
+app="$out/Bridgeplay Installer.app"
+dmg="$repo/out/Bridgeplay-Installer.dmg"
+
+swift build --package-path app -c "$configuration" --product BridgeplayInstaller --arch arm64
+bin=$(swift build --package-path app -c "$configuration" --show-bin-path --arch arm64)
+[ -x "$bin/BridgeplayInstaller" ] || { echo 'Installer executable missing' >&2; exit 1; }
+mkdir -p "$out"
+stage=$(mktemp -d "$out/.package.XXXXXX")
+trap 'rm -rf "$stage"' EXIT HUP INT TERM
+bundle="$stage/Bridgeplay Installer.app"
+mkdir -p "$bundle/Contents/MacOS" "$bundle/Contents/Resources"
+cp "$bin/BridgeplayInstaller" "$bundle/Contents/MacOS/BridgeplayInstaller"
+for resource in BridgeplayApp_BridgeplayUI.bundle BridgeplayApp_BridgeplayInstaller.bundle; do
+ ditto "$bin/$resource" "$bundle/Contents/Resources/$resource"
+done
+python3 - "$repo/app/Sources/BridgeplayInstaller/Resources/Localization/Localizable.xcstrings" "$bundle/Contents/Resources/BridgeplayApp_BridgeplayInstaller.bundle" <<'PYTHON'
+import json
+import pathlib
+import sys
+catalog = json.loads(pathlib.Path(sys.argv[1]).read_text())
+bundle = pathlib.Path(sys.argv[2])
+root = bundle / "Contents" / "Resources" if (bundle / "Contents" / "Resources").is_dir() else bundle
+for language in ("en", "it", "zh-Hans"):
+ folder = root / (language + ".lproj")
+ folder.mkdir(exist_ok=True)
+ values = []
+ for key, entry in sorted(catalog["strings"].items()):
+ value = key if language == "en" else entry["localizations"][language]["stringUnit"]["value"]
+ values.append(json.dumps(key, ensure_ascii=False) + " = " + json.dumps(value, ensure_ascii=False) + ";")
+ (folder / "Localizable.strings").write_text("\n".join(values) + "\n", encoding="utf-16")
+(root / "Localizable.xcstrings").unlink(missing_ok=True)
+PYTHON
+"$bin/BridgeplayInstaller" --icon "$stage/icon.png"
+mkdir "$stage/Bridgeplay.iconset"
+for points in 16 32 128 256 512; do
+ sips -z "$points" "$points" "$stage/icon.png" --out "$stage/Bridgeplay.iconset/icon_${points}x${points}.png" >/dev/null
+ pixels=$((points * 2))
+ sips -z "$pixels" "$pixels" "$stage/icon.png" --out "$stage/Bridgeplay.iconset/icon_${points}x${points}@2x.png" >/dev/null
+done
+iconutil -c icns "$stage/Bridgeplay.iconset" -o "$bundle/Contents/Resources/Bridgeplay.icns"
+rm -rf "$stage/icon.png" "$stage/Bridgeplay.iconset"
+cat > "$bundle/Contents/Info.plist" <<'PLIST'
+<?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>CFBundleIdentifier</key><string>com.bridgeplay.Installer</string>
+<key>CFBundleName</key><string>Bridgeplay Installer</string>
+<key>CFBundleDisplayName</key><string>Bridgeplay Installer</string>
+<key>CFBundleExecutable</key><string>BridgeplayInstaller</string>
+<key>CFBundleIconFile</key><string>Bridgeplay</string>
+<key>CFBundlePackageType</key><string>APPL</string>
+<key>CFBundleShortVersionString</key><string>1.0</string>
+<key>CFBundleVersion</key><string>1</string>
+<key>LSMinimumSystemVersion</key><string>26.0</string>
+<key>LSApplicationCategoryType</key><string>public.app-category.utilities</string>
+<key>NSHighResolutionCapable</key><true/>
+<key>NSPrincipalClass</key><string>NSApplication</string>
+<key>CFBundleLocalizations</key><array><string>en</string><string>it</string><string>zh-Hans</string></array>
+<key>NSDownloadsFolderUsageDescription</key><string>Moves this installer disk image to Trash after you choose Finish.</string>
+</dict></plist>
+PLIST
+cp LICENSE "$bundle/Contents/Resources/LICENSE"
+codesign --force --sign "$identity" "$bundle"
+codesign --verify --strict --deep "$bundle"
+# Only replace previous local packaging outputs after a complete bundle is available.
+rm -rf "$app"
+ditto "$bundle" "$app"
+hdiutil create -quiet -volname 'Bridgeplay Installer' -srcfolder "$stage" -format UDZO -ov "$dmg"
+codesign --force --sign "$identity" "$dmg"
+size=$(stat -f '%z' "$dmg")
+limit=${BRIDGEPLAY_INSTALLER_MAX_BYTES:-5242880}
+if [ "$size" -gt "$limit" ]; then
+ echo "Installer DMG exceeds size budget: $size > $limit bytes" >&2
+ exit 1
+fi
+printf 'DMG: %s\nSize: %s bytes (budget %s)\n' "$dmg" "$size" "$limit"
+shasum -a 256 "$dmg"
diff --git a/scripts/test-installer-cleanup.sh b/scripts/test-installer-cleanup.sh
new file mode 100755
index 0000000..17330b8
--- /dev/null
+++ b/scripts/test-installer-cleanup.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+# Exercise source-DMG identification without ejecting or trashing user files.
+set -eu
+repo=$(cd "$(dirname "$0")/.." && pwd)
+work=$(mktemp -d "${TMPDIR:-/tmp}/bridgeplay-cleanup-tests.XXXXXX")
+trap 'rm -rf "$work"' EXIT HUP INT TERM
+swiftc -parse-as-library -swift-version 6 \
+ "$repo/app/Sources/BridgeplayInstaller/InstallerCleanup.swift" \
+ "$repo/installer/tests/native-installer-cleanup-smoke.swift" \
+ -o "$work/cleanup-tests"
+"$work/cleanup-tests"
diff --git a/scripts/test-native-installer.sh b/scripts/test-native-installer.sh
new file mode 100755
index 0000000..c804629
--- /dev/null
+++ b/scripts/test-native-installer.sh
@@ -0,0 +1,19 @@
+#!/bin/sh
+set -eu
+
+if [ "$(uname -s)" != "Darwin" ]; then
+ echo "This smoke test requires macOS." >&2
+ exit 2
+fi
+
+repo_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
+work_dir=$(mktemp -d "${TMPDIR:-/tmp}/bridgeplay-installer.XXXXXX")
+trap 'rm -rf "$work_dir"' EXIT HUP INT TERM
+
+xcrun --find swiftc >/dev/null
+xcrun swiftc -swift-version 6 \
+ "$repo_root"/app/Sources/BridgeplayInstallerCore/*.swift \
+ "$repo_root"/installer/tests/native-installer-core-smoke.swift \
+ -o "$work_dir/native-installer-core-smoke"
+
+"$work_dir/native-installer-core-smoke" "$work_dir/fixtures"