Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Install: show when the signature expires, and renew it without rebuilding
LNPANDY26a8b86f6d2a
diff --git a/frontend/Sources/NSPortBuilder/AppSignature.swift b/frontend/Sources/NSPortBuilder/AppSignature.swiftnew file mode 100644index 00000000..540552ca--- /dev/null+++ b/frontend/Sources/NSPortBuilder/AppSignature.swift@@ -0,0 +1,65 @@+import Foundation++/// The provisioning profile an installed app was signed with, and when it expires: a free Apple ID's profile lasts 7+/// days, so a game installed with one stops starting unless the same app is signed again. The launcher can only tell+/// when to re-sign if it reads that date from the app the signature is in.+///+/// An App Store or paid-team profile lives a year, so the date is usually far away and nothing is shown as urgent.+enum AppSignature {+ static let profileName = "embedded.mobileprovision"++ /// `ExpirationDate` of the app's embedded.mobileprovision, read through `security cms -D` (the profile is a+ /// CMS-wrapped property list); nil when the app carries no profile or it cannot be read.+ static func expiration(ofApp app: String) -> Date? {+ let profile = app + "/" + profileName+ guard FileManager.default.fileExists(atPath: profile) else { return nil }+ let p = Process(), out = Pipe()+ p.executableURL = URL(fileURLWithPath: "/usr/bin/security")+ p.arguments = ["cms", "-D", "-i", profile]+ p.standardOutput = out+ p.standardError = FileHandle.nullDevice+ guard (try? p.run()) != nil else { return nil }+ let data = out.fileHandleForReading.readDataToEndOfFile()+ p.waitUntilExit()+ guard p.terminationStatus == 0 else { return nil }+ return expiration(fromProfile: data)+ }++ /// The profile plist's ExpirationDate. Split out so the parse is tested without a signed app.+ static func expiration(fromProfile data: Data) -> Date? {+ guard let plist = (try? PropertyListSerialization.propertyList(from: data, options: [], format: nil)) as? [String: Any]+ else { return nil }+ return plist["ExpirationDate"] as? Date+ }++ /// Whole days from today to the date, counted in calendar days (0 = today, negative = past): the day the profile+ /// stops working is the day iOS refuses to start the app, not 24 hours after the last start.+ static func daysLeft(to date: Date, now: Date = Date()) -> Int {+ let calendar = Calendar(identifier: .gregorian)+ return calendar.dateComponents([.day], from: calendar.startOfDay(for: now), to: calendar.startOfDay(for: date)).day ?? 0+ }++ /// Two days or fewer: re-sign before the next game session rather than after the game stops starting.+ static func isUrgent(_ date: Date, now: Date = Date()) -> Bool { daysLeft(to: date, now: now) <= 2 }++ /// The hero's line: the date and the days left, in the app's language.+ static func describe(_ date: Date, _ t: (String) -> String, now: Date = Date(), locale: Locale = .current) -> String {+ let formatter = DateFormatter()+ formatter.dateStyle = .medium+ formatter.timeStyle = .none+ formatter.locale = locale+ let day = formatter.string(from: date)+ let days = daysLeft(to: date, now: now)+ if days < 0 { return String(format: t("dev.expiryPast"), day, -days) }+ if days == 0 { return String(format: t("dev.expiryToday"), day) }+ return String(format: t("dev.expiry"), day, days)+ }++ /// The compact form beside a game's status ("3 days left", "expired"): a card has no room for the date.+ static func short(_ date: Date, _ t: (String) -> String, now: Date = Date()) -> String {+ let days = daysLeft(to: date, now: now)+ if days < 0 { return t("dev.expiryExpiredShort") }+ if days == 0 { return t("dev.expiryTodayShort") }+ return String(format: t("dev.expiryShort"), days)+ }+}diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex e41360fc..7506c701 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -1748,13 +1748,165 @@ final class BuildModel: ObservableObject {}}- private func finishInstall(_ failure: String?) {+ private func finishInstall(_ failure: String?, note: String? = nil) {running = falsedone = failure == nil- doneNote = failure ?? String(format: t("dev.installed"), deviceName(installDevice))+ doneNote = failure ?? note ?? String(format: t("dev.installed"), deviceName(installDevice))cleanupStaging()}+ /// Reinstall the signed app that is already in derived data, without unpacking, signing or packing again: the+ /// device keeps the app's Documents (game data and saves), as the bundle ID does not change. A reinstall that+ /// fails on an expired signature says so in devicectl's words; signing again is not this button's job.+ func reinstallOnDevice(then: (() -> Void)? = nil) {+ let device = installedOn, app = installedAppPath+ guard !device.isEmpty, !app.isEmpty else { then?(); return }+ guard FileManager.default.fileExists(atPath: app) else {+ doneNote = String(format: t("dev.reinstallMissing"), shortPath(app))+ then?(); return+ }+ running = true+ runTool(id: 1004, name: String(format: t("dev.reinstallStage"), deviceName(device)),+ Self.reinstallCommand(xcrun: xcrunPath, device: device, app: app), step: Self.installStep) { error in+ if let error {+ // The app is still on the device: a failed reinstall is a note, not a failed build+ self.running = false+ self.doneNote = String(format: self.t("dev.reinstallFailed"), error)+ } else {+ self.finishInstall(nil, note: String(format: self.t("dev.reinstalled"), self.deviceName(device)))+ }+ then?()+ }+ }++ nonisolated static func reinstallCommand(xcrun: String, device: String, app: String) -> [String] {+ [xcrun, "devicectl", "device", "install", "app", "--device", device, app]+ }++ /// Renew an installed app's signature (a free Apple ID's profile lasts 7 days). The same xcodebuild parameters as+ /// the install, run on the cached project and derived data: Xcode reuses the compiled products and only signs+ /// again, then devicectl installs the app over itself. PRODUCT_BUNDLE_IDENTIFIER is the installed app's own, so the+ /// device keeps that app's Documents (game data, saves); a retry under another identifier would lose them.+ func resignOnDevice(app: String, device: String, then: (() -> Void)? = nil) {+ guard !device.isEmpty, !app.isEmpty else { then?(); return }+ guard !signingTeam.isEmpty else {+ doneNote = t("dev.resignNoTeam")+ then?(); return+ }+ guard let bundle = NSDictionary(contentsOfFile: app + "/Info.plist")?["CFBundleIdentifier"] as? String else {+ doneNote = String(format: t("dev.noProject"), shortPath(app + "/Info.plist"))+ then?(); return+ }+ guard let paths = Self.buildPaths(ofApp: app), FileManager.default.fileExists(atPath: paths.project) else {+ doneNote = String(format: t("dev.resignNoProject"), shortPath(Self.buildPaths(ofApp: app)?.project ?? app))+ then?(); return+ }+ let xcrun = xcrunPath, team = signingTeam, name = deviceName(device)+ DispatchQueue.global(qos: .userInitiated).async {+ let scheme = Self.scheme(of: paths.project, xcrun: xcrun)+ DispatchQueue.main.async {+ guard let scheme else {+ self.doneNote = String(format: self.t("dev.noProject"), self.shortPath(paths.project))+ then?(); return+ }+ self.running = true+ self.runTool(id: 1006, name: String(format: self.t("dev.resignStage"), name),+ Self.resignCommand(xcrun: xcrun, project: paths.project, scheme: scheme, device: device,+ derived: paths.derived, team: team, bundle: bundle), step: Self.xcodeStep) { error in+ if let error, !error.isEmpty {+ self.running = false+ self.doneNote = String(format: self.t("dev.resignFailed"), error)+ then?(); return+ }+ self.runTool(id: 1007, name: String(format: self.t("dev.installStage"), name),+ Self.reinstallCommand(xcrun: xcrun, device: device, app: app), step: Self.installStep) { installError in+ self.running = false+ if let installError {+ self.doneNote = String(format: self.t("dev.installFailed"), installError)+ } else {+ self.installedOn = device+ self.installedAppPath = app+ self.doneNote = String(format: self.t("dev.resigned"), name)+ }+ then?()+ }+ }+ }+ }+ }++ /// The xcodebuild parameters of a re-sign: signAndInstall's, plus the installed app's own identifier. The same+ /// derived data is what keeps Xcode from rebuilding the game's code.+ nonisolated static func resignCommand(xcrun: String, project: String, scheme: String, device: String, derived: String,+ team: String, bundle: String) -> [String] {+ [xcrun, "xcodebuild", "-project", project, "-scheme", scheme, "-configuration", "Release",+ "-destination", "id=\(device)", "-derivedDataPath", derived, "-allowProvisioningUpdates",+ "DEVELOPMENT_TEAM=\(team)", "DM_COPY_ROMFS=NO", "PRODUCT_BUNDLE_IDENTIFIER=\(bundle)", "build"]+ }++ /// The cached project and derived data an installed app came from, from the app's own path+ /// (<work>/xcode-derived-data/Build/Products/Release-iphoneos/DmIOS.app): a re-sign must run there to reuse them.+ nonisolated static func buildPaths(ofApp app: String) -> (project: String, derived: String)? {+ guard let marker = app.range(of: "/Build/Products/") else { return nil }+ let derived = String(app[..<marker.lowerBound])+ let work = (derived as NSString).deletingLastPathComponent+ return (work + "/xcode/DmIOS.xcodeproj", derived)+ }++ /// Ask where to write the .ipa, then pack the signed app there.+ func saveIPAPanel() {+ let p = NSSavePanel()+ p.title = t("dev.saveIPATitle")+ p.allowedFileTypes = ["ipa"]+ p.nameFieldStringValue = defaultIPAName()+ p.canCreateDirectories = true+ guard p.runModal() == .OK, let url = p.url else { return }+ saveIPA(to: url)+ }++ /// The signed app as an .ipa (Payload/<name>.app, the layout iOS and the sideloaders install): useful while the+ /// signature lasts, and the thing to re-sign when it expires. The game data is not in it — it stays in the app's+ /// Documents (romfs.img), as a normal iOS build has it.+ func saveIPA(to url: URL, then: (() -> Void)? = nil) {+ let app = installedAppPath, fm = FileManager.default+ guard !app.isEmpty, fm.fileExists(atPath: app) else {+ doneNote = String(format: t("dev.saveNeedsApp"), shortPath(app))+ then?(); return+ }+ let stage = fm.temporaryDirectory.appendingPathComponent("nspb-ipa-" + UUID().uuidString)+ let payload = stage.appendingPathComponent("Payload")+ do {+ try fm.createDirectory(at: payload, withIntermediateDirectories: true)+ try fm.copyItem(atPath: app, toPath: payload.appendingPathComponent((app as NSString).lastPathComponent).path)+ } catch {+ try? fm.removeItem(at: stage)+ doneNote = String(format: t("dev.saveFailed"), error.localizedDescription)+ then?(); return+ }+ running = true+ runTool(id: 1005, name: t("dev.saveStage"), Self.ipaCommand(payload: payload.path, ipa: url.path), step: { _ in nil }) { error in+ try? fm.removeItem(at: stage)+ self.running = false+ self.doneNote = error.map { String(format: self.t("dev.saveFailed"), $0) }+ ?? String(format: self.t("dev.savedIPA"), self.shortPath(url.path))+ then?()+ }+ }++ /// ditto writes the archive the way Finder's "compress" does; the IPA's root must be Payload/, and --norsrc keeps+ /// __MACOSX out (the signature itself lives in _CodeSignature inside the app).+ nonisolated static func ipaCommand(payload: String, ipa: String) -> [String] {+ ["/usr/bin/ditto", "-c", "-k", "--norsrc", "--keepParent", payload, ipa]+ }++ /// The name the save panel offers: the app's display name, so two games' IPAs do not collide. A slash or colon in a+ /// game's name would split the file name or show as a folder in Finder.+ func defaultIPAName() -> String {+ let plist = NSDictionary(contentsOfFile: installedAppPath + "/Info.plist")+ let name = (plist?["CFBundleDisplayName"] as? String) ?? (plist?["CFBundleExecutable"] as? String) ?? "DmIOS"+ return name.replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: ":", with: "_") + ".ipa"+ }+/// The game's folder (romfs.img, aoc/) into the installed app's Documents, where main.m looks for this game's files first.nonisolated static func archiveCopy(xcrun: String, device: String, bundle: String, archive: String, titleID: String) -> [String] {[xcrun, "devicectl", "device", "copy", "to", "--device", device, "--source", archive,diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex 6e844631..e4bee4cb 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -44,6 +44,8 @@ struct ContentView: View {@StateObject private var row = RowScroller()@StateObject private var toolsAge: ToolsAge@State private var buildCommit = "" // the checkout's commit when the running build started (ToolsAge)+ @State private var signatureExpiry: [UUID: Date] = [:] // installed apps' provisioning-profile expiry, per game+ @State private var resignNote: String? // the last re-sign's outcome, shown under the hero's expiry lineprivate var performStartupChecks: Boolprivate let onRunSetup: (() -> Void)? // Settings' "Run setup again"; the root view supplies itprivate let qaManage: (open: Bool, ring: Bool) // visual QA: the Manage menu open at launch, with the controller's focus ring or without@@ -106,6 +108,7 @@ struct ContentView: View {manageOpenFor = library.selected?.id}refreshArtwork()+ readSignatures()if performStartupChecks { library.discover(); fetchArtwork(); m.refreshDevices(); checkTools() }if performStartupChecks {m.checkDeps()@@ -122,11 +125,13 @@ struct ContentView: View {}.onChange(of: library.games) { _ inrefreshArtwork()+ readSignatures()if performStartupChecks { fetchArtwork() }}.onChange(of: m.repoPath) { _ in refreshArtwork(); if performStartupChecks { checkTools() } }// A clone, pull or update check has finished (the automatic pull at launch among them): the checkout may have moved.onReceive(m.$repoBusy.removeDuplicates().dropFirst()) { busy in if !busy && performStartupChecks { checkTools() } }+ .onChange(of: library.selectedID) { _ in resignNote = nil } // the last re-sign's note belongs to its game.onReceive(m.$running.removeDuplicates()) { running inif running && activeBuildID == nil { activeBuildID = library.rememberInputs(m) }if running && activeBuildID != nil { // the tools this build runs: a pull waits for the build (pullRepo, autoPull)@@ -379,6 +384,31 @@ struct ContentView: View {.anchorPreference(key: ManageAnchorKey.self, value: .bounds) { $0 }.padTarget("hero.manage", scope: "main", radius: 12) { manageOpenFor = game.id }}+ // A free Apple ID's provisioning profile lasts 7 days: say when this app's runs out, and renew it here.+ if game.onDevice, let expiry = signatureExpiry[game.id] {+ HStack(spacing: 10) {+ Image(systemName: "checkmark.seal").font(.system(size: 12))+ .foregroundStyle(LauncherPalette.cream.opacity(0.7))+ Text(AppSignature.describe(expiry, m.t)).font(.manrope(12.5))+ .foregroundStyle(AppSignature.isUrgent(expiry) ? LauncherPalette.building : .secondary)+ if AppSignature.isUrgent(expiry) {+ Button { resign(game) } label: {+ Text(m.t("dev.resign")).font(.manrope(12, .semibold))+ .foregroundStyle(LauncherPalette.cream)+ .padding(.horizontal, 10).padding(.vertical, 4)+ .overlay(Capsule().strokeBorder(LauncherPalette.cream.opacity(0.35)))+ .contentShape(Capsule())+ }+ .buttonStyle(.plain).disabled(m.running)+ .help(m.t("dev.resignHelp"))+ .padTarget("hero.resign", scope: "main", radius: 12) { if !m.running { resign(game) } }+ }+ }+ }+ if let resignNote {+ Text(resignNote).font(.manrope(12)).foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }}.padding(.horizontal, 34).padding(.bottom, 34)}@@ -485,6 +515,14 @@ struct ContentView: View {.font(.manrope(prominent ? 13 : 12)).foregroundStyle(.secondary).lineLimit(1).help(m.t("library.olderToolsHelp"))}+ // A free Apple ID's profile lasts 7 days: the card says when it runs out, the hero offers to renew it.+ if !building, let expiry = signatureExpiry[game.id] {+ Text("· " + AppSignature.short(expiry, m.t))+ .font(.manrope(prominent ? 13 : 12))+ .foregroundStyle(AppSignature.isUrgent(expiry) ? LauncherPalette.building : .secondary)+ .lineLimit(1)+ .help(AppSignature.describe(expiry, m.t))+ }}.accessibilityElement(children: .combine)}@@ -686,6 +724,27 @@ struct ContentView: View {} catch { launchError = error.localizedDescription }}+ /// The installed apps' profile expiries, read in the background: `security cms` per app, so not in a view body.+ private func readSignatures() {+ let apps = library.games.filter(\.onDevice).map { ($0.id, $0.iosAppPath) }+ guard !apps.isEmpty else { signatureExpiry = [:]; return }+ DispatchQueue.global(qos: .utility).async {+ var found: [UUID: Date] = [:]+ for (id, path) in apps { if let date = AppSignature.expiration(ofApp: path) { found[id] = date } }+ DispatchQueue.main.async { signatureExpiry = found }+ }+ }++ /// Sign the installed app again for another 7 days (a free Apple ID's profile), then install it: the game's code+ /// is not rebuilt, and its Documents stay.+ private func resign(_ game: LibraryGame) {+ resignNote = nil+ m.resignOnDevice(app: game.iosAppPath, device: game.installedDevice) {+ resignNote = m.doneNote+ signatureExpiry[game.id] = AppSignature.expiration(ofApp: game.iosAppPath)+ }+ }+private func recordBuild() {guard m.done, let id = activeBuildID else { return }if m.target == "mac-app" { library.recordCompletedApp(path: m.macAppPath, commit: buildCommit, for: id) }diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex c7fe38f4..35ad73e6 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -204,6 +204,31 @@ enum L10n {"dev.signFailed": ("\u{7b7e}\u{540d}\u{5931}\u{8d25}\u{ff1a}%@", "Signing failed: %@"),"dev.installFailed": ("\u{5b89}\u{88c5}\u{5931}\u{8d25}\u{ff1a}%@", "Installing failed: %@"),"dev.noProject": ("\u{6ca1}\u{6709}\u{627e}\u{5230}\u{ff1a}%@", "Not found: %@"),+ "dev.reinstall": ("重装", "Reinstall"),+ "dev.reinstallStage": ("重装到 %@", "Reinstalling on %@"),+ "dev.reinstalled": ("已重新安装到 %@(游戏数据保留)", "Reinstalled on %@ (the game data is kept)"),+ "dev.reinstallFailed": ("重装失败:%@(签名已过期时请重新签名并安装)", "Reinstalling failed: %@ (if the signature has expired, sign and install again)"),+ "dev.reinstallMissing": ("找不到已签名的 App:%@(请重新构建)", "The signed app is not there: %@ (build again)"),+ "dev.signedApp": ("已签名的 App", "Signed app"),+ "dev.saveIPA": ("保存 IPA…", "Save IPA…"),+ "dev.saveIPATitle": ("保存已签名的 IPA", "Save the signed IPA"),+ "dev.saveStage": ("打包 IPA", "Packing the IPA"),+ "dev.savedIPA": ("已保存 IPA:%@", "Saved the IPA: %@"),+ "dev.saveFailed": ("保存 IPA 失败:%@(请检查目标位置的可用空间和写入权限)", "Saving the IPA failed: %@ (check free space and write permission at the destination)"),+ "dev.saveNeedsApp": ("没有可打包的已签名 App:%@(请重新构建)", "No signed app to pack: %@ (build again)"),+ "dev.expiry": ("签名到期:%@(剩 %d 天)", "Signature expires: %@ (%d days left)"),+ "dev.expiryToday": ("签名今天到期(%@)", "Signature expires today (%@)"),+ "dev.expiryPast": ("签名已过期(%@,%d 天前)", "Signature expired %@ (%d days ago)"),+ "dev.expiryShort": ("签名剩 %d 天", "%d days of signature left"),+ "dev.expiryTodayShort": ("签名今天到期", "signature expires today"),+ "dev.expiryExpiredShort": ("签名已过期", "signature expired"),+ "dev.resign": ("续签", "Re-sign"),+ "dev.resignHelp": ("用缓存工程重新签名并安装:不重新编译游戏,App 数据(存档、游戏数据)保留", "Sign and install again from the cached project: no rebuild, and the app's data (saves, game data) is kept"),+ "dev.resignStage": ("续签并安装到 %@", "Re-signing for %@"),+ "dev.resigned": ("已续签并安装到 %@", "Re-signed and installed on %@"),+ "dev.resignFailed": ("续签失败:%@(请在 Xcode → 设置 → 账户 → Manage Certificates 检查证书,或确认网络)", "Re-signing failed: %@ (check the certificate in Xcode → Settings → Accounts → Manage Certificates, or the network)"),+ "dev.resignNoProject": ("找不到缓存的 Xcode 工程:%@(请重新构建一次)", "The cached Xcode project is not there: %@ (build once more)"),+ "dev.resignNoTeam": ("续签需要签名团队:请选择签名团队后再试。", "Re-signing needs a signing team: pick one first."),"prog.eta": ("\u{8fd8}\u{5269} %@", "%@ left"),"activity.mac": ("\u{6b63}\u{5728}\u{6784}\u{5efa} Mac \u{7248}", "Mac build in progress"),"activity.ios": ("\u{6b63}\u{5728}\u{6784}\u{5efa} iPhone \u{7248}", "iPhone build in progress"),diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swiftindex 622b8e57..37c730e0 100644--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift@@ -367,7 +367,7 @@ final class LibraryTests: XCTestCase {print('error: "iOS Team Provisioning Profile" cannot be registered to your development team', flush=True)sys.exit(1)app = pathlib.Path(a[a.index('-derivedDataPath') + 1]) / 'Build/Products/Release-iphoneos/DmIOS.app'- app.mkdir(parents=True)+ app.mkdir(parents=True, exist_ok=True) # a re-sign rebuilds over the app the install left therewith (app / 'Info.plist').open('wb') as f: plistlib.dump({'CFBundleIdentifier': 'org.nxnative.test'}, f)print('CodeSign ' + str(app), flush=True)elif a[:3] == ['devicectl', 'device', 'install']:@@ -436,6 +436,134 @@ final class LibraryTests: XCTestCase {XCTAssertTrue(try String(contentsOf: calls, encoding: .utf8).contains("devicectl device process launch --device 00008150-AAAA org.nxnative.test"))}+ /// A deleted app comes back without unpacking, signing or packing anything again: the signed app already in+ /// derived data is installed as it is, and the device keeps the game data (the bundle ID does not change).+ @MainActor func testReinstallInstallsTheSignedAppWithoutBuildingAgain() throws {+ let (model, _, calls, _) = try runInstallFlow(transfer: true)+ let app = model.installedAppPath+ let buildsBefore = try String(contentsOf: calls, encoding: .utf8).split(separator: "\n").filter { $0.hasPrefix("xcodebuild") }.count+ let done = expectation(description: "Reinstalled")+ model.reinstallOnDevice { done.fulfill() }+ wait(for: [done], timeout: 20)+ let log = try String(contentsOf: calls, encoding: .utf8).split(separator: "\n").map(String.init)+ XCTAssertEqual(log.filter { $0.hasPrefix("devicectl device install app") }.count, 2)+ XCTAssertEqual(log.last { $0.hasPrefix("devicectl device install app") }, "devicectl device install app --device 00008150-AAAA \(app)")+ XCTAssertEqual(log.filter { $0.hasPrefix("xcodebuild") }.count, buildsBefore) // no second build+ XCTAssertEqual(log.filter { $0.hasPrefix("romfs_image") }.count, 1) // the game files are not re-packed+ XCTAssertEqual(model.stages.last?.id, 1004)+ XCTAssertEqual(model.stages.last?.state, .done)+ XCTAssertEqual(model.doneNote, String(format: model.t("dev.reinstalled"), "iPhone"))+ XCTAssertFalse(model.running)+ }++ /// The saved package is an ordinary IPA — Payload/DmIOS.app/… at the archive's root, no __MACOSX — so a+ /// sideloader or another Mac installs it while the signature lasts, without building the game again.+ @MainActor func testSaveIPAWritesAnOrdinaryPayloadArchive() throws {+ let (model, _, _, _) = try runInstallFlow(transfer: true)+ XCTAssertEqual(model.defaultIPAName(), "DmIOS.ipa")+ let ipa = temporary.appendingPathComponent("Test Game.ipa")+ let saved = expectation(description: "Saved the IPA")+ model.saveIPA(to: ipa) { saved.fulfill() }+ wait(for: [saved], timeout: 30)+ XCTAssertTrue(FileManager.default.fileExists(atPath: ipa.path))+ let unzip = Process(), out = Pipe()+ unzip.executableURL = URL(fileURLWithPath: "/usr/bin/unzip")+ unzip.arguments = ["-l", ipa.path]+ unzip.standardOutput = out+ try unzip.run(); unzip.waitUntilExit()+ let listing = String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)+ XCTAssertEqual(unzip.terminationStatus, 0, listing)+ XCTAssertTrue(listing.contains("Payload/DmIOS.app/Info.plist"), listing)+ XCTAssertFalse(listing.contains("__MACOSX"), listing)+ XCTAssertEqual(model.doneNote, String(format: model.t("dev.savedIPA"), model.shortPath(ipa.path)))+ XCTAssertFalse(model.running)+ }++ /// Both actions name what is missing instead of doing nothing, and a failed reinstall is a note on the installed+ /// app, not a failed build (the app is still on the device).+ @MainActor func testReinstallAndSaveReportAMissingSignedApp() throws {+ let (model, _, _, _) = try runInstallFlow(transfer: true)+ try FileManager.default.removeItem(atPath: model.installedAppPath)+ var reported = expectation(description: "Reinstall says what is missing")+ model.reinstallOnDevice { reported.fulfill() }+ wait(for: [reported], timeout: 10)+ XCTAssertEqual(model.doneNote, String(format: model.t("dev.reinstallMissing"), model.shortPath(model.installedAppPath)))+ XCTAssertTrue(model.done)+ reported = expectation(description: "Save says what is missing")+ let ipa = temporary.appendingPathComponent("missing.ipa")+ model.saveIPA(to: ipa) { reported.fulfill() }+ wait(for: [reported], timeout: 10)+ XCTAssertEqual(model.doneNote, String(format: model.t("dev.saveNeedsApp"), model.shortPath(model.installedAppPath)))+ XCTAssertFalse(FileManager.default.fileExists(atPath: ipa.path))+ }++ /// The save panel's name comes from the app, with the separators a game name can carry replaced: a slash would make+ /// a subfolder, a colon shows as a folder in Finder.+ @MainActor func testTheIPANameComesFromTheDisplayNameWithoutPathSeparators() throws {+ let app = temporary.appendingPathComponent("DmIOS.app")+ try FileManager.default.createDirectory(at: app, withIntermediateDirectories: true)+ let info: [String: Any] = ["CFBundleDisplayName": "Zelda: Echoes/of Wisdom"]+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)+ .write(to: app.appendingPathComponent("Info.plist"))+ let model = BuildModel()+ model.installedAppPath = app.path+ XCTAssertEqual(model.defaultIPAName(), "Zelda_ Echoes_of Wisdom.ipa")+ }++ /// The two commands the actions build: a plain devicectl install of the cached app, and ditto's Payload archive.+ func testTheReinstallAndIPARecipes() {+ XCTAssertEqual(BuildModel.reinstallCommand(xcrun: "/x", device: "D", app: "/a/DmIOS.app"),+ ["/x", "devicectl", "device", "install", "app", "--device", "D", "/a/DmIOS.app"])+ XCTAssertEqual(BuildModel.ipaCommand(payload: "/t/Payload", ipa: "/o/Game.ipa"),+ ["/usr/bin/ditto", "-c", "-k", "--norsrc", "--keepParent", "/t/Payload", "/o/Game.ipa"])+ }++ /// A re-sign is the install's xcodebuild line (same project, derived data, team) plus the installed app's own bundle+ /// ID, so Xcode reuses the compiled game and the device keeps the app's Documents; then the app is installed again,+ /// with no second romfs pack.+ @MainActor func testResignSignsAgainAndInstallsWithoutRepacking() throws {+ let (model, _, calls, _) = try runInstallFlow(transfer: true)+ let app = model.installedAppPath+ let done = expectation(description: "Re-signed")+ model.resignOnDevice(app: app, device: "00008150-AAAA") { done.fulfill() }+ wait(for: [done], timeout: 30)+ let log = try String(contentsOf: calls, encoding: .utf8).split(separator: "\n").map(String.init)+ let resign = try XCTUnwrap(log.last { $0.hasPrefix("xcodebuild -project") })+ for part in ["-derivedDataPath \(temporary.path)/\(titleID)_build/xcode-derived-data", "-allowProvisioningUpdates",+ "DEVELOPMENT_TEAM=TEAM123456", "DM_COPY_ROMFS=NO", "PRODUCT_BUNDLE_IDENTIFIER=org.nxnative.test", "build"] {+ XCTAssertTrue(resign.contains(part), part)+ }+ XCTAssertEqual(log.filter { $0.hasPrefix("xcodebuild -project") }.count, 3) // the install's two signs, then this one+ XCTAssertEqual(log.filter { $0.hasPrefix("romfs_image") }.count, 1) // the game files are not packed again+ XCTAssertEqual(log.last { $0.hasPrefix("devicectl device install app") },+ "devicectl device install app --device 00008150-AAAA \(app)")+ XCTAssertEqual(model.doneNote, String(format: model.t("dev.resigned"), "iPhone"))+ XCTAssertFalse(model.running)+ }++ /// A re-sign that cannot work says what to do: a missing cached project, or no signing team chosen.+ @MainActor func testResignReportsAMissingProjectOrTeam() throws {+ let (model, _, _, _) = try runInstallFlow(transfer: true)+ let savedTeam = UserDefaults.standard.string(forKey: "signingTeam")+ defer { UserDefaults.standard.set(savedTeam, forKey: "signingTeam") }+ // An app with a bundle ID but no project beside it: the cached build was moved or removed.+ let orphan = temporary.appendingPathComponent("orphan/xcode-derived-data/Build/Products/Release-iphoneos/DmIOS.app")+ try FileManager.default.createDirectory(at: orphan, withIntermediateDirectories: true)+ try PropertyListSerialization.data(fromPropertyList: ["CFBundleIdentifier": bundleID], format: .xml, options: 0)+ .write(to: orphan.appendingPathComponent("Info.plist"))+ var reported = expectation(description: "Missing project reported")+ model.resignOnDevice(app: orphan.path, device: "00008150-AAAA") { reported.fulfill() }+ wait(for: [reported], timeout: 10)+ XCTAssertEqual(model.doneNote, String(format: model.t("dev.resignNoProject"),+ model.shortPath(temporary.path + "/orphan/xcode/DmIOS.xcodeproj")))+ model.signingTeam = ""+ reported = expectation(description: "Missing team reported")+ model.resignOnDevice(app: model.installedAppPath, device: "00008150-AAAA") { reported.fulfill() }+ wait(for: [reported], timeout: 10)+ XCTAssertEqual(model.doneNote, model.t("dev.resignNoTeam"))+ XCTAssertFalse(model.running)+ }+func testCorruptLibraryIsReportedWithoutOverwritingIt() throws {let file = temporary.appendingPathComponent("library.json")let data = Data("broken JSON".utf8)diff --git a/frontend/Tests/NSPortBuilderTests/SignatureTests.swift b/frontend/Tests/NSPortBuilderTests/SignatureTests.swiftnew file mode 100644index 00000000..49970e7d--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/SignatureTests.swift@@ -0,0 +1,87 @@+import XCTest+@testable import NSPortBuilder++/// The provisioning-profile expiry a free Apple ID's install has to show (7 days), and the re-sign command that renews+/// it: parsing, the day count, the wording, and the xcodebuild parameters (the install's, plus the app's own bundle ID).+final class SignatureTests: XCTestCase {+ private func profile(expires: Date?) throws -> Data {+ var plist: [String: Any] = ["Name": "iOS Team Provisioning Profile: org.nxnative.test", "TeamIdentifier": ["TEAM123456"]]+ if let expires { plist["ExpirationDate"] = expires }+ return try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)+ }++ func testTheProfilePlistYieldsItsExpirationDate() throws {+ let date = Date(timeIntervalSince1970: 1_790_000_000)+ XCTAssertEqual(AppSignature.expiration(fromProfile: try profile(expires: date)), date)+ XCTAssertNil(AppSignature.expiration(fromProfile: try profile(expires: nil)))+ XCTAssertNil(AppSignature.expiration(fromProfile: Data("not a plist".utf8)))+ }++ /// The app without a profile (a Mac app, or an app the launcher did not build) has no date rather than an error.+ func testAnAppWithoutAProfileHasNoExpiry() throws {+ let app = FileManager.default.temporaryDirectory.appendingPathComponent("no-profile-\(UUID().uuidString).app")+ try FileManager.default.createDirectory(at: app, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: app) }+ XCTAssertNil(AppSignature.expiration(ofApp: app.path))+ }++ /// Whole calendar days: the day the profile stops working is the day iOS refuses to start the app.+ func testDaysLeftAreCalendarDays() throws {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = .current+ let now = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 10, day: 29, hour: 23, minute: 30)))+ let tomorrowMorning = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 10, day: 30, hour: 1)))+ let inThree = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 11, day: 1, hour: 9)))+ let yesterday = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 10, day: 28, hour: 9)))+ XCTAssertEqual(AppSignature.daysLeft(to: tomorrowMorning, now: now), 1)+ XCTAssertEqual(AppSignature.daysLeft(to: inThree, now: now), 3)+ XCTAssertEqual(AppSignature.daysLeft(to: yesterday, now: now), -1)+ XCTAssertEqual(AppSignature.daysLeft(to: now, now: now), 0)+ }++ func testTwoDaysOrFewerIsUrgent() throws {+ let now = Date()+ let day: TimeInterval = 24 * 3600+ XCTAssertTrue(AppSignature.isUrgent(now.addingTimeInterval(2 * day), now: now))+ XCTAssertFalse(AppSignature.isUrgent(now.addingTimeInterval(6 * day), now: now))+ }++ /// The hero's wording, in both languages, for a future, today's and a past date.+ func testTheExpiryWording() throws {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = .current+ let now = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 10, day: 29, hour: 12)))+ let inThree = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 11, day: 1, hour: 9)))+ let yesterday = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 10, day: 28, hour: 9)))+ let yesterdayText = AppSignature.describe(yesterday, { L10n.string($0, .en) }, now: now, locale: Locale(identifier: "en_US"))+ XCTAssertTrue(yesterdayText.contains("expired"), yesterdayText)+ let future = AppSignature.describe(inThree, { L10n.string($0, .en) }, now: now, locale: Locale(identifier: "en_US"))+ XCTAssertTrue(future.contains("3 days left"), future)+ let today = AppSignature.describe(now, { L10n.string($0, .en) }, now: now, locale: Locale(identifier: "en_US"))+ XCTAssertTrue(today.contains("today"), today)+ let zh = AppSignature.describe(inThree, { L10n.string($0, .zh) }, now: now, locale: Locale(identifier: "zh_CN"))+ XCTAssertTrue(zh.contains("剩 3 天"), zh)+ XCTAssertEqual(AppSignature.short(inThree, { L10n.string($0, .en) }, now: now), "3 days of signature left")+ XCTAssertEqual(AppSignature.short(yesterday, { L10n.string($0, .en) }, now: now), "signature expired")+ }++ /// The re-sign is the install's xcodebuild line plus the installed app's own bundle ID: the same derived data makes+ /// Xcode reuse the compiled game, and the identifier keeps the app's Documents.+ func testTheResignCommandMatchesTheInstallPlusTheBundleID() {+ let command = BuildModel.resignCommand(xcrun: "/x", project: "/w/xcode/DmIOS.xcodeproj", scheme: "Test (0100)",+ device: "UDID", derived: "/w/xcode-derived-data", team: "TEAM123456",+ bundle: "org.nxnative.test")+ XCTAssertEqual(command, ["/x", "xcodebuild", "-project", "/w/xcode/DmIOS.xcodeproj", "-scheme", "Test (0100)",+ "-configuration", "Release", "-destination", "id=UDID", "-derivedDataPath", "/w/xcode-derived-data",+ "-allowProvisioningUpdates", "DEVELOPMENT_TEAM=TEAM123456", "DM_COPY_ROMFS=NO",+ "PRODUCT_BUNDLE_IDENTIFIER=org.nxnative.test", "build"])+ }++ /// An installed app's path names its work folder, and with it the project and derived data a re-sign must reuse.+ func testBuildPathsComeFromTheInstalledApp() {+ let paths = BuildModel.buildPaths(ofApp: "/Users/x/0100_build/xcode-derived-data/Build/Products/Release-iphoneos/DmIOS.app")+ XCTAssertEqual(paths?.project, "/Users/x/0100_build/xcode/DmIOS.xcodeproj")+ XCTAssertEqual(paths?.derived, "/Users/x/0100_build/xcode-derived-data")+ XCTAssertNil(BuildModel.buildPaths(ofApp: "/elsewhere/DmIOS.app"))+ }+}