diff --git a/.gitignore b/.gitignore index 6fcd120..5e1ed4a 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,8 @@ Payload/ *.ipa xcuserdata/ Vendor/ +.build/ +.swiftpm/ +.xtool/ +xtool/ +ZSignKit/zsign diff --git a/Package.resolved b/Package.resolved new file mode 100644 index 0000000..3bf60f1 --- /dev/null +++ b/Package.resolved @@ -0,0 +1,24 @@ +{ + "originHash" : "2ddc169d24521f3d7ddd90d7fff886e8620fdaca652be305ae39d00b83eee3d7", + "pins" : [ + { + "identity" : "openssl", + "kind" : "remoteSourceControl", + "location" : "https://github.com/krzyzanowskim/OpenSSL.git", + "state" : { + "revision" : "0a6149bff4fb00921ce0ec1811f726b166638095", + "version" : "3.6.5000" + } + }, + { + "identity" : "zipfoundation", + "kind" : "remoteSourceControl", + "location" : "https://github.com/weichsel/ZIPFoundation.git", + "state" : { + "revision" : "22787ffb59de99e5dc1fbfe80b19c97a904ad48d", + "version" : "0.9.20" + } + } + ], + "version" : 3 +} diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..a75ffb9 --- /dev/null +++ b/Package.swift @@ -0,0 +1,57 @@ +// swift-tools-version: 6.0 +import PackageDescription + +// For local builds with xtool (`xtool dev build`). The release IPA is still built +// from project.yml by GitHub Actions. Run Scripts/fetch-dependencies.sh first, +// it puts zsign (ZSignKit/zsign) and the OpenSSL headers in place. +let zsignCSettings: [CSetting] = [ + .define("SWIFTIPA_HAS_ZSIGN", to: "1"), + .headerSearchPath("zsign"), + .headerSearchPath("zsign/common"), + .headerSearchPath("../Vendor/openssl-include"), +] +let zsignCXXSettings: [CXXSetting] = [ + .define("SWIFTIPA_HAS_ZSIGN", to: "1"), + .headerSearchPath("zsign"), + .headerSearchPath("zsign/common"), + .headerSearchPath("../Vendor/openssl-include"), +] + +let package = Package( + name: "SwiftIPA", + platforms: [.iOS(.v16)], + products: [.library(name: "SwiftIPA", targets: ["SwiftIPA"])], + dependencies: [ + .package(url: "https://github.com/weichsel/ZIPFoundation.git", exact: "0.9.20"), + .package(url: "https://github.com/krzyzanowskim/OpenSSL.git", exact: "3.6.5000"), + ], + targets: [ + .target( + name: "ZSignKit", + dependencies: [.product(name: "OpenSSL", package: "OpenSSL")], + path: "ZSignKit", + exclude: [ + "zsign/zsign.cpp", + "zsign/certcheck.cpp", + "zsign/certcheck.h", + "zsign/metadata.cpp", + "zsign/metadata.h", + "zsign/third-party", + "zsign/common/archive.cpp", + "zsign/common/archive.h", + ], + publicHeadersPath: "include", + cSettings: zsignCSettings, + cxxSettings: zsignCXXSettings, + linkerSettings: [.linkedLibrary("z")] + ), + .target( + name: "SwiftIPA", + dependencies: ["ZSignKit", .product(name: "ZIPFoundation", package: "ZIPFoundation")], + path: "SwiftIPA", + exclude: ["Resources", "Signing/ZSign"] + ), + ], + swiftLanguageModes: [.v5], + cxxLanguageStandard: .cxx17 +) diff --git a/README.md b/README.md index 86719ee..bcafa53 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ There's no account and no tracking. The app only goes online when you ask it to: ## Features - Change the bundle ID, name, version, build, minimum iOS version, icon and entitlements, or take the bundle ID straight from your certificate's provisioning profile +- The imported IPA stays untouched. Signing always starts from it, so signing again with other settings doesn't stack changes, and you can export the original any time - Re-signing the same app with the same certificate and settings is almost instant, because the result gets cached - Fast Packaging (on by default) skips compressing the signed IPA, so signing big apps takes a fraction of the time - Sign several apps in one go @@ -22,6 +23,9 @@ There's no account and no tracking. The app only goes online when you ask it to: - Remove extensions, the Watch app or the embedded profile, force file sharing, and a few more tweaks like that - Add AltStore or ESign sources and pull apps from them - See when a certificate is about to expire, with a reminder a few days before +- Adding a certificate checks the .p12 password and that the .p12 belongs to the provisioning profile +- If signing fails, Show Log has zsign's full output to copy or share +- Sort the library by name, size, or when an app was added or signed - Look inside an IPA before signing it (architectures, encryption, linked libraries, extensions) - Six color themes, English and German - Report bugs from Settings → Bugs & Issues, which opens a prefilled issue on GitHub @@ -66,14 +70,24 @@ xcodegen generate open SwiftIPA.xcodeproj ``` -The fetch script downloads zsign and the OpenSSL headers into `Vendor/`, which isn't checked in. The app talks to zsign through one small Objective-C++ file (`Signing/ZSign/ZSignBridge.mm`), everything else is Swift and SwiftUI. +The fetch script downloads zsign and the OpenSSL headers into `Vendor/`, which isn't checked in. Both are pinned to fixed versions in the script. The app talks to zsign through one small Objective-C++ file (`ZSignKit/ZSignBridge.mm`), everything else is Swift and SwiftUI. + +### With xtool (Linux or macOS) + +With [xtool](https://xtool.sh) and its Darwin SDK set up: + +```bash +./Scripts/xtool-build.sh # unsigned IPA in xtool/SwiftIPA.ipa +./Scripts/xtool-build.sh install # build, sign and install on the connected iPhone +``` + +This uses `Package.swift` and `xtool.yml`. Release builds still come from `project.yml` on GitHub Actions. The xtool build has no German strings yet, because the String Catalog can't be compiled outside Xcode. ## Known issues -- `.deb` tweaks only work if they're gzip-compressed. For `xz` or `zstd` ones, extract the `.dylib` and import that instead. +- `.deb` tweaks work with gzip and xz compression. For `zstd` or `bzip2` ones, extract the `.dylib` and import that instead. - Installing needs api.palera.in to be reachable. If it's down, use Export IPA for now. - Revoked certificates are only detected through the profile and expiry date, the app doesn't ask Apple directly. -- The Share Sheet extension is English only. - No special iPad layout yet. Found a bug or have an idea? Open an issue, I read all of them. diff --git a/Scripts/fetch-dependencies.sh b/Scripts/fetch-dependencies.sh index 4ae5151..f7ac254 100755 --- a/Scripts/fetch-dependencies.sh +++ b/Scripts/fetch-dependencies.sh @@ -5,21 +5,28 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" VENDOR="$ROOT/Vendor" ZSIGN_DIR="$VENDOR/zsign" ZSIGN_REPO="https://github.com/zhlynn/zsign.git" -ZSIGN_REF="${ZSIGN_REF:-master}" +# Pinned so a change on zsign's master can't break the build or signing unnoticed. +# To update: set a newer commit here, build, sign a few apps, then commit. +ZSIGN_REF="${ZSIGN_REF:-9299685bab7ef99827e06e5dfda93af747386590}" OPENSSL_INCLUDE_DIR="$VENDOR/openssl-include/openssl" -OPENSSL_RELEASE_API="https://api.github.com/repos/krzyzanowskim/OpenSSL/releases/latest" +# Must match the OpenSSL package version in project.yml and Package.swift. +OPENSSL_TAG="${OPENSSL_TAG:-3.6.5000}" +OPENSSL_RELEASE_API="https://api.github.com/repos/krzyzanowskim/OpenSSL/releases/tags/$OPENSSL_TAG" mkdir -p "$VENDOR" -if [ -d "$ZSIGN_DIR/.git" ]; then - echo "==> Updating zsign" - git -C "$ZSIGN_DIR" fetch --depth 1 origin "$ZSIGN_REF" - git -C "$ZSIGN_DIR" checkout -q FETCH_HEAD -else +if [ ! -d "$ZSIGN_DIR/.git" ]; then echo "==> Cloning zsign" rm -rf "$ZSIGN_DIR" - git clone --depth 1 --branch "$ZSIGN_REF" "$ZSIGN_REPO" "$ZSIGN_DIR" + git init -q "$ZSIGN_DIR" + git -C "$ZSIGN_DIR" remote add origin "$ZSIGN_REPO" fi +echo "==> Checking out zsign $ZSIGN_REF" +git -C "$ZSIGN_DIR" fetch -q --depth 1 origin "$ZSIGN_REF" +git -C "$ZSIGN_DIR" checkout -q FETCH_HEAD + +# The SwiftPM/xtool build (Package.swift) expects zsign's sources here. +ln -sfn ../Vendor/zsign/src "$ROOT/ZSignKit/zsign" echo "==> Checking the sources SwiftIPA expects" for file in src/bundle.cpp src/bundle.h src/openssl.cpp src/openssl.h src/macho.cpp src/macho.h src/archo.cpp src/archo.h src/signing.cpp src/signing.h src/common/common.h src/common/mach-o.h; do @@ -72,5 +79,5 @@ cp "$HEADERS_SRC"/*.h "$OPENSSL_INCLUDE_DIR/" echo echo "Done. Now run:" -echo " xcodegen generate" -echo " open SwiftIPA.xcodeproj" +echo " xcodegen generate && open SwiftIPA.xcodeproj (Xcode)" +echo " Scripts/xtool-build.sh (xtool, e.g. on Linux)" diff --git a/Scripts/xtool-build.sh b/Scripts/xtool-build.sh new file mode 100755 index 0000000..d72a085 --- /dev/null +++ b/Scripts/xtool-build.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Local build with xtool (https://xtool.sh), e.g. on Linux. +# Scripts/xtool-build.sh unsigned IPA in xtool/SwiftIPA.ipa +# Scripts/xtool-build.sh install build, sign and install on the connected iPhone (xtool dev) +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +if [ ! -f Vendor/zsign/src/bundle.cpp ] || [ ! -d Vendor/openssl-include/openssl ]; then + ./Scripts/fetch-dependencies.sh +fi +ln -sfn ../Vendor/zsign/src ZSignKit/zsign + +export PKG_CONFIG_PATH="$ROOT/Support/pkgconfig" + +if [ "${1:-}" = "install" ]; then + exec xtool dev +fi +xtool dev build --ipa "$@" diff --git a/ShareExtension/Info.plist b/ShareExtension/Info.plist deleted file mode 100644 index 6631ffa..0000000 --- a/ShareExtension/Info.plist +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/ShareExtension/ShareViewController.swift b/ShareExtension/ShareViewController.swift deleted file mode 100644 index b49a4f2..0000000 --- a/ShareExtension/ShareViewController.swift +++ /dev/null @@ -1,113 +0,0 @@ -import UIKit -import SwiftUI - -final class ShareViewController: UIViewController { - override func viewDidLoad() { - super.viewDidLoad() - view.backgroundColor = .black - presentStatus() - extractAttachments { [weak self] items in - DispatchQueue.main.async { - self?.finish(with: items) - } - } - } - - private func presentStatus() { - let hosting = UIHostingController(rootView: ShareStatusView()) - addChild(hosting) - hosting.view.frame = view.bounds - hosting.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] - view.addSubview(hosting.view) - hosting.didMove(toParent: self) - } - - private func finish(with items: [InboxStore.Item]) { - guard !items.isEmpty else { - let error = NSError(domain: "com.xsxs18.SwiftIPA.ShareExtension", code: -1) - extensionContext?.cancelRequest(withError: error) - return - } - InboxStore.queue(items) - guard let url = URL(string: "swiftipa://import") else { - extensionContext?.completeRequest(returningItems: nil) - return - } - extensionContext?.open(url) { [weak self] _ in - self?.extensionContext?.completeRequest(returningItems: nil) - } - } - - private func extractAttachments(completion: @escaping ([InboxStore.Item]) -> Void) { - guard let extensionItems = extensionContext?.inputItems as? [NSExtensionItem] else { - completion([]) - return - } - let providers = extensionItems.compactMap { $0.attachments }.flatMap { $0 } - guard !providers.isEmpty else { - completion([]) - return - } - - let resultsLock = NSLock() - var results: [InboxStore.Item] = [] - let group = DispatchGroup() - - for provider in providers { - group.enter() - loadFile(from: provider) { item in - if let item { - resultsLock.lock() - results.append(item) - resultsLock.unlock() - } - group.leave() - } - } - - group.notify(queue: .main) { - completion(results) - } - } - - private func loadFile(from provider: NSItemProvider, completion: @escaping (InboxStore.Item?) -> Void) { - let identifiers = provider.registeredTypeIdentifiers - guard !identifiers.isEmpty else { - completion(nil) - return - } - tryLoad(from: provider, identifiers: identifiers, index: 0, completion: completion) - } - - private func tryLoad(from provider: NSItemProvider, identifiers: [String], index: Int, completion: @escaping (InboxStore.Item?) -> Void) { - guard index < identifiers.count else { - completion(nil) - return - } - provider.loadFileRepresentation(forTypeIdentifier: identifiers[index]) { [weak self] url, error in - guard let self else { return } - guard let url, error == nil, url.pathExtension.lowercased() == "ipa" else { - self.tryLoad(from: provider, identifiers: identifiers, index: index + 1, completion: completion) - return - } - guard let data = try? Data(contentsOf: url) else { - self.tryLoad(from: provider, identifiers: identifiers, index: index + 1, completion: completion) - return - } - completion(InboxStore.Item(suggestedName: url.lastPathComponent, data: data)) - } - } -} - -private struct ShareStatusView: View { - var body: some View { - VStack(spacing: SISpacing.md) { - ProgressView() - .tint(SIColor.accent) - Text("Sending to SwiftIPA…") - .foregroundStyle(SIColor.textPrimary) - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .background(SIColor.background) - } -} diff --git a/Support/pkgconfig/zlib.pc b/Support/pkgconfig/zlib.pc new file mode 100644 index 0000000..b16927a --- /dev/null +++ b/Support/pkgconfig/zlib.pc @@ -0,0 +1,8 @@ +# ZIPFoundation asks pkg-config for zlib when the build host isn't an Apple +# platform (xtool on Linux). The host's zlib.pc would add -L/usr/lib64, which +# breaks the iOS link, so this one only links the SDK's libz. +Name: zlib +Description: zlib from the iOS SDK +Version: 1.2.12 +Libs: -lz +Cflags: diff --git a/Support/xtool-Info.plist b/Support/xtool-Info.plist new file mode 100644 index 0000000..24cf9b3 --- /dev/null +++ b/Support/xtool-Info.plist @@ -0,0 +1,109 @@ + + + + + CFBundleDisplayName + SwiftIPA + CFBundleDocumentTypes + + + CFBundleTypeName + iOS App Archive + CFBundleTypeRole + Editor + LSHandlerRank + Alternate + LSItemContentTypes + + com.apple.itunes.ipa + com.xsxs18.SwiftIPA.ipa + com.xsxs18.SwiftIPA.tipa + + + + CFBundleLocalizations + + en + de + + CFBundleShortVersionString + 1.8.0 + CFBundleURLTypes + + + CFBundleURLName + com.xsxs18.SwiftIPA + CFBundleURLSchemes + + swiftipa + + + + CFBundleVersion + 0 + LSSupportsOpeningDocumentsInPlace + + NSAppTransportSecurity + + NSAllowsLocalNetworking + + + NSLocalNetworkUsageDescription + SwiftIPA runs a local server on your device so iOS can install the app you just signed. + UIBackgroundModes + + fetch + + UIFileSharingEnabled + + UILaunchScreen + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UTImportedTypeDeclarations + + + UTTypeConformsTo + + public.data + public.content + com.apple.itunes.ipa + + UTTypeDescription + iOS App Archive + UTTypeIdentifier + com.xsxs18.SwiftIPA.ipa + UTTypeTagSpecification + + public.filename-extension + + ipa + + + + + UTTypeConformsTo + + public.data + public.content + com.apple.itunes.ipa + + UTTypeDescription + iOS App Archive + UTTypeIdentifier + com.xsxs18.SwiftIPA.tipa + UTTypeTagSpecification + + public.filename-extension + + tipa + + + + + + diff --git a/SwiftIPA/Models/AppEntry.swift b/SwiftIPA/Models/AppEntry.swift index 427c257..f104aac 100644 --- a/SwiftIPA/Models/AppEntry.swift +++ b/SwiftIPA/Models/AppEntry.swift @@ -7,7 +7,11 @@ struct AppEntry: Identifiable, Codable, Hashable { var version: String var build: String var minimumOSVersion: String + /// The IPA as imported. Before 1.8 signing overwrote it, so for apps signed + /// with an older version it may already be a signed build. var fileName: String + /// The signed build, next to the original. + var signedFileName: String? var iconFileName: String? var byteSize: Int64 var importedAt: Date @@ -25,6 +29,7 @@ struct AppEntry: Identifiable, Codable, Hashable { build: String = "1", minimumOSVersion: String = "", fileName: String, + signedFileName: String? = nil, iconFileName: String? = nil, byteSize: Int64 = 0, importedAt: Date = Date(), @@ -41,6 +46,7 @@ struct AppEntry: Identifiable, Codable, Hashable { self.build = build self.minimumOSVersion = minimumOSVersion self.fileName = fileName + self.signedFileName = signedFileName self.iconFileName = iconFileName self.byteSize = byteSize self.importedAt = importedAt @@ -53,6 +59,9 @@ struct AppEntry: Identifiable, Codable, Hashable { var isSigned: Bool { signedAt != nil } + /// The imported IPA is still there untouched (not the case for apps signed before 1.8). + var hasOriginal: Bool { signedFileName != nil || signedAt == nil } + var displaySize: String { ByteCountFormatter.string(fromByteCount: byteSize, countStyle: .file) } diff --git a/SwiftIPA/Resources/Localizable.xcstrings b/SwiftIPA/Resources/Localizable.xcstrings index 68412f9..17682ea 100644 --- a/SwiftIPA/Resources/Localizable.xcstrings +++ b/SwiftIPA/Resources/Localizable.xcstrings @@ -3290,6 +3290,126 @@ } } } + }, + "Signing Log": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Signier-Log" + } + } + } + }, + "Show Log": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Log anzeigen" + } + } + } + }, + "Copy Log": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Log kopieren" + } + } + } + }, + "zsign didn't print anything.": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "zsign hat nichts ausgegeben." + } + } + } + }, + "Export Original IPA": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Original-IPA exportieren" + } + } + } + }, + "Original IPA": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Original-IPA" + } + } + } + }, + "Recently Added": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Zuletzt hinzugefügt" + } + } + } + }, + "Recently Signed": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Zuletzt signiert" + } + } + } + }, + "Size": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Größe" + } + } + } + }, + "Sort By": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Sortieren nach" + } + } + } + }, + "The install was cancelled.": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Installation wurde abgebrochen." + } + } + } + }, + "This .p12 certificate isn't part of the provisioning profile. Apps signed with this pair won't install. Pick the profile that belongs to this certificate.": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Dieses .p12-Zertifikat gehört nicht zum Provisioning-Profil. Damit signierte Apps lassen sich nicht installieren. Wähle das Profil, das zu diesem Zertifikat gehört." + } + } + } } }, "version": "1.0" diff --git a/SwiftIPA/Services/AppLibraryStore.swift b/SwiftIPA/Services/AppLibraryStore.swift index 0e2d969..8a18ec4 100644 --- a/SwiftIPA/Services/AppLibraryStore.swift +++ b/SwiftIPA/Services/AppLibraryStore.swift @@ -18,10 +18,22 @@ final class AppLibraryStore: ObservableObject { apps = load() } + /// The IPA to install or export: the signed build if there is one. func ipaURL(for entry: AppEntry) -> URL { + if let signed = entry.signedFileName { return folder.appendingPathComponent(signed) } + return originalIPAURL(for: entry) + } + + /// The IPA as it was imported. Signing always starts from this one, so + /// signing again doesn't pile changes (suffixes, tweaks) on top of the last build. + func originalIPAURL(for entry: AppEntry) -> URL { folder.appendingPathComponent(entry.fileName) } + private func files(of entry: AppEntry) -> [URL] { + [entry.fileName, entry.signedFileName, entry.iconFileName].compactMap { $0 }.map { folder.appendingPathComponent($0) } + } + func iconURL(for entry: AppEntry) -> URL? { guard let name = entry.iconFileName else { return nil } return folder.appendingPathComponent(name) @@ -53,17 +65,31 @@ final class AppLibraryStore: ObservableObject { let destination = folder.appendingPathComponent(fileName) try fileManager.copyItem(at: sourceURL, to: destination) - let extracted = try IPAService.extract(ipaURL: destination) - defer { extracted.cleanUp() } - let metadata = try IPAService.metadata(from: extracted) + let inspection: (metadata: AppMetadata, icon: Data?) + do { + inspection = try IPAService.inspectArchive(at: destination) + } catch { + // Don't leave a broken copy behind in the library folder. + try? fileManager.removeItem(at: destination) + throw error + } + let metadata = inspection.metadata var iconFileName: String? - if let iconData = IPAService.extractIcon(from: extracted) { + if let iconData = inspection.icon { let name = "\(id.uuidString)-icon.png" try? iconData.write(to: folder.appendingPathComponent(name)) iconFileName = name } + // Files opened from other apps get copied into Documents/Inbox, which + // would otherwise keep a second copy of every shared IPA. + let inbox = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + .appendingPathComponent("Inbox", isDirectory: true).standardizedFileURL.path + if sourceURL.standardizedFileURL.path.hasPrefix(inbox + "/") { + try? fileManager.removeItem(at: sourceURL) + } + let size = (try? fileManager.attributesOfItem(atPath: destination.path)[.size] as? Int64) ?? 0 return AppEntry( @@ -84,7 +110,10 @@ final class AppLibraryStore: ObservableObject { /// `bundleIdentifier` is the ID the app was actually signed with. It's nil /// when the result came from the cache, then it gets worked out again here. func markSigned(_ entryID: UUID, signedIPAURL: URL, bundleIdentifier: String?, options: SigningOptions, certificateID: UUID) async throws { - guard let destination = await MainActor.run(body: { apps.first(where: { $0.id == entryID }).map(ipaURL) }) else { return } + guard let entry = await MainActor.run(body: { apps.first(where: { $0.id == entryID }) }) else { return } + // The signed build goes next to the original, which stays as it was imported. + let signedFileName = entry.hasOriginal ? "\(entry.id.uuidString)-signed.ipa" : entry.fileName + let destination = folder.appendingPathComponent(signedFileName) try await Task.detached(priority: .userInitiated) { try FileManager.default.replaceItem(at: destination, withItemAt: signedIPAURL) @@ -94,6 +123,7 @@ final class AppLibraryStore: ObservableObject { await MainActor.run { guard let index = apps.firstIndex(where: { $0.id == entryID }) else { return } + if apps[index].hasOriginal { apps[index].signedFileName = signedFileName } apps[index].byteSize = size apps[index].signedAt = Date() apps[index].certificateID = certificateID @@ -113,10 +143,7 @@ final class AppLibraryStore: ObservableObject { } func remove(_ entry: AppEntry) { - try? FileManager.default.removeItem(at: ipaURL(for: entry)) - if let iconURL = iconURL(for: entry) { - try? FileManager.default.removeItem(at: iconURL) - } + for url in files(of: entry) { try? FileManager.default.removeItem(at: url) } withAnimation(.easeOut(duration: 0.25)) { apps.removeAll { $0.id == entry.id } } @@ -125,10 +152,7 @@ final class AppLibraryStore: ObservableObject { func removeAll(where predicate: (AppEntry) -> Bool) { for entry in apps where predicate(entry) { - try? FileManager.default.removeItem(at: ipaURL(for: entry)) - if let iconURL = iconURL(for: entry) { - try? FileManager.default.removeItem(at: iconURL) - } + for url in files(of: entry) { try? FileManager.default.removeItem(at: url) } } withAnimation(.easeOut(duration: 0.25)) { apps.removeAll(where: predicate) diff --git a/SwiftIPA/Services/CertificateService.swift b/SwiftIPA/Services/CertificateService.swift index 8800ff1..207d144 100644 --- a/SwiftIPA/Services/CertificateService.swift +++ b/SwiftIPA/Services/CertificateService.swift @@ -1,4 +1,7 @@ import Foundation +#if canImport(ZSignKit) +import ZSignKit // xtool/SwiftPM build; Xcode uses the bridging header +#endif import Security struct ProvisioningProfileInfo { @@ -12,6 +15,8 @@ struct ProvisioningProfileInfo { var entitlements: [String: Any] var supportsUnrestrictedEntitlements: Bool var applicationIdentifier: String? + /// DER data of the certificates the profile was made for. + var developerCertificates: [Data] = [] /// The profile's App ID without the team prefix, e.g. `com.example.app` or `*`. var bundleIdentifier: String? { @@ -28,12 +33,15 @@ struct P12Info { var subjectCommonName: String? var expirationDate: Date? var issuedDate: Date? + /// DER data of the signing certificate. + var certificateData: Data } enum CertificateServiceError: LocalizedError { case cannotReadProfile case wrongPassword case cannotReadP12 + case profileMismatch var errorDescription: String? { switch self { @@ -43,6 +51,8 @@ enum CertificateServiceError: LocalizedError { return String(localized: "That password doesn't unlock this .p12 file.") case .cannotReadP12: return String(localized: "Couldn't read this .p12 certificate file.") + case .profileMismatch: + return String(localized: "This .p12 certificate isn't part of the provisioning profile. Apps signed with this pair won't install. Pick the profile that belongs to this certificate.") } } } @@ -73,7 +83,8 @@ enum CertificateService { deviceCount: (plist["ProvisionedDevices"] as? [String])?.count, entitlements: entitlements, supportsUnrestrictedEntitlements: unrestricted, - applicationIdentifier: entitlements["application-identifier"] as? String + applicationIdentifier: entitlements["application-identifier"] as? String, + developerCertificates: (plist["DeveloperCertificates"] as? [Data]) ?? [] ) } @@ -111,7 +122,8 @@ enum CertificateService { return P12Info( subjectCommonName: commonName as String?, expirationDate: notAfter, - issuedDate: notBefore + issuedDate: notBefore, + certificateData: certificateData ) } } diff --git a/SwiftIPA/Services/CertificateStore.swift b/SwiftIPA/Services/CertificateStore.swift index cc39bfe..b3dae62 100644 --- a/SwiftIPA/Services/CertificateStore.swift +++ b/SwiftIPA/Services/CertificateStore.swift @@ -85,19 +85,34 @@ final class CertificateStore: ObservableObject { let p12Destination = folder.appendingPathComponent(p12FileName) let provisionDestination = folder.appendingPathComponent(provisionFileName) - try fileManager.copyItem(at: p12SourceURL, to: p12Destination) - try fileManager.copyItem(at: provisionSourceURL, to: provisionDestination) + let profileInfo: ProvisioningProfileInfo + let p12Info: P12Info + do { + try fileManager.copyItem(at: p12SourceURL, to: p12Destination) + try fileManager.copyItem(at: provisionSourceURL, to: provisionDestination) + profileInfo = try CertificateService.inspectProvisioningProfile(at: provisionDestination) + // A wrong password used to be accepted here and only failed later, while signing. + p12Info = try CertificateService.inspectP12(at: p12Destination, password: password) + if !profileInfo.developerCertificates.isEmpty, + !profileInfo.developerCertificates.contains(p12Info.certificateData) { + throw CertificateServiceError.profileMismatch + } + } catch { + try? fileManager.removeItem(at: p12Destination) + try? fileManager.removeItem(at: provisionDestination) + throw error + } - let profileInfo = try CertificateService.inspectProvisioningProfile(at: provisionDestination) - let p12Info = try? CertificateService.inspectP12(at: p12Destination, password: password) + // The certificate can run out before the profile does. + let expiry = [profileInfo.expirationDate, p12Info.expirationDate].compactMap { $0 }.min() var certificate = SigningCertificate( id: id, name: name, teamName: profileInfo.teamName, teamIdentifier: profileInfo.teamIdentifier, - issuedAt: p12Info?.issuedDate, - expiresAt: profileInfo.expirationDate, + issuedAt: p12Info.issuedDate, + expiresAt: expiry, p12FileName: p12FileName, provisionFileName: provisionFileName, provisionedDeviceCount: profileInfo.deviceCount, @@ -158,10 +173,15 @@ final class CertificateStore: ObservableObject { } func refreshHealth(for certificate: SigningCertificate) async { - guard let index = certificates.firstIndex(where: { $0.id == certificate.id }) else { return } if let profileInfo = try? CertificateService.inspectProvisioningProfile(at: provisionURL(for: certificate)) { + let p12Expiry = password(for: certificate) + .flatMap { try? CertificateService.inspectP12(at: p12URL(for: certificate), password: $0) }? + .expirationDate + let expiry = [profileInfo.expirationDate, p12Expiry].compactMap { $0 }.min() await MainActor.run { - certificates[index].expiresAt = profileInfo.expirationDate + // Look the index up here, the list may have changed while the profile was read. + guard let index = certificates.firstIndex(where: { $0.id == certificate.id }) else { return } + certificates[index].expiresAt = expiry certificates[index].teamName = profileInfo.teamName certificates[index].provisionedDeviceCount = profileInfo.deviceCount certificates[index].lastRevocationCheck = Date() diff --git a/SwiftIPA/Services/InstallServer.swift b/SwiftIPA/Services/InstallServer.swift index 9d2e230..f44421d 100644 --- a/SwiftIPA/Services/InstallServer.swift +++ b/SwiftIPA/Services/InstallServer.swift @@ -65,6 +65,9 @@ final class InstallServer { private var host = "127.0.0.1" private var port: UInt16 = 8442 private var currentMode: InstallMode = .secureDirect + /// Random path segment, so nobody else on the network can guess where the IPA is served. + private var token = UUID().uuidString.lowercased() + private var stopWork: DispatchWorkItem? private let queue = DispatchQueue(label: "com.xsxs18.SwiftIPA.InstallServer") private init() {} @@ -86,6 +89,7 @@ final class InstallServer { self.scheme = mode.useSecureConnection ? "https" : "http" self.port = mode.useSecureConnection ? 8443 : 8442 self.currentMode = mode + self.token = UUID().uuidString.lowercased() self.host = preferLoopback ? "127.0.0.1" : (Self.wifiIPAddress() ?? "127.0.0.1") @@ -121,12 +125,18 @@ final class InstallServer { guard !alreadyResumed else { return } switch state { + case .waiting(let error): + // E.g. the port is still taken. Waiting here would leave the install stuck on "Preparing". + newListener.cancel() + continuation.resume(throwing: InstallServerError.listenerFailed(error.localizedDescription)) + case .cancelled: + continuation.resume(throwing: InstallServerError.listenerFailed(String(localized: "The install was cancelled."))) case .ready: switch mode.presentationStyle { case .direct: continuation.resume(returning: InstallLink(url: URL(string: self.itmsServicesLink)!, presentationStyle: .direct)) case .webView: - let pageURL = "\(self.scheme)://\(self.host):\(self.port)/install" + let pageURL = "\(self.scheme)://\(self.host):\(self.port)/\(self.token)/install" continuation.resume(returning: InstallLink(url: URL(string: pageURL)!, presentationStyle: .webView)) } case .failed(let error): @@ -142,10 +152,24 @@ final class InstallServer { } func stop() { + stopWork?.cancel() + stopWork = nil listener?.cancel() listener = nil } + /// iOS fetches the IPA once. Keep serving for a bit in case it retries, then close the port. + private func scheduleStop(after seconds: TimeInterval) { + // listener and stopWork are only touched on the main queue. + DispatchQueue.main.async { [weak self] in + guard let self else { return } + let work = DispatchWorkItem { [weak self] in self?.stop() } + self.stopWork?.cancel() + self.stopWork = work + DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: work) + } + } + private func handle(_ connection: NWConnection) { connection.start(queue: queue) readRequest(connection: connection, buffer: Data()) @@ -176,12 +200,13 @@ final class InstallServer { private func respond(to requestLine: String, on connection: NWConnection) { let parts = requestLine.split(separator: " ") let path = parts.count > 1 ? String(parts[1]) : "/" + let prefix = "/\(token)" - if path.hasPrefix("/manifest.plist") { + if path.hasPrefix(prefix + "/manifest.plist") { sendManifest(on: connection) - } else if path.hasPrefix("/app.ipa") { + } else if path.hasPrefix(prefix + "/app.ipa") { sendIPA(on: connection) - } else if path.hasPrefix("/install") { + } else if path.hasPrefix(prefix + "/install") { sendInstallPage(on: connection) } else { let body = "Not Found".data(using: .utf8)! @@ -192,9 +217,9 @@ final class InstallServer { private var manifestSourceURL: URL { switch currentMode { case .secureDirect: - return URL(string: "\(scheme)://\(host):\(port)/manifest.plist")! + return URL(string: "\(scheme)://\(host):\(port)/\(token)/manifest.plist")! case .externalManifest: - let payloadURL = "\(scheme)://\(host):\(port)/app.ipa" + let payloadURL = "\(scheme)://\(host):\(port)/\(token)/app.ipa" var components = URLComponents(string: "https://api.palera.in/genPlist")! components.queryItems = [ URLQueryItem(name: "bundleid", value: bundleIdentifier), @@ -238,7 +263,7 @@ final class InstallServer { "assets": [ [ "kind": "software-package", - "url": "\(scheme)://\(host):\(port)/app.ipa" + "url": "\(scheme)://\(host):\(port)/\(token)/app.ipa" ] ], "metadata": [ @@ -277,6 +302,7 @@ final class InstallServer { try? handle.close() connection.cancel() report(.installing) + scheduleStop(after: 60) return } let newSent = sent + Int64(chunk.count) @@ -318,15 +344,16 @@ final class InstallServer { var pointer: UnsafeMutablePointer? = firstInterface while let interface = pointer { defer { pointer = interface.pointee.ifa_next } - let family = interface.pointee.ifa_addr.pointee.sa_family - guard family == UInt8(AF_INET) else { continue } + // Some interfaces have no address at all, reading through it would crash. + guard let socketAddress = interface.pointee.ifa_addr else { continue } + guard socketAddress.pointee.sa_family == UInt8(AF_INET) else { continue } let name = String(cString: interface.pointee.ifa_name) guard name == "en0" else { continue } var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST)) getnameinfo( - interface.pointee.ifa_addr, - socklen_t(interface.pointee.ifa_addr.pointee.sa_len), + socketAddress, + socklen_t(socketAddress.pointee.sa_len), &hostBuffer, socklen_t(hostBuffer.count), nil, diff --git a/SwiftIPA/Services/LocalServerIdentity.swift b/SwiftIPA/Services/LocalServerIdentity.swift index 35e87a5..1d091b3 100644 --- a/SwiftIPA/Services/LocalServerIdentity.swift +++ b/SwiftIPA/Services/LocalServerIdentity.swift @@ -1,4 +1,7 @@ import Foundation +#if canImport(ZSignKit) +import ZSignKit // xtool/SwiftPM build; Xcode uses the bridging header +#endif import Security import Network @@ -24,7 +27,19 @@ enum LocalServerIdentity { } static func ensureIdentity() throws -> (identity: SecIdentity, certificate: SecCertificate, password: String) { - let password = existingPassword() ?? newPassword() + do { + return try loadOrCreateIdentity() + } catch { + // The password lives in the keychain (this device only) and the .p12 in + // Documents. After restoring a backup to another phone they no longer + // match, so start over with a new identity instead of failing every time. + try? FileManager.default.removeItem(at: p12URL) + return try loadOrCreateIdentity(forceNewPassword: true) + } + } + + private static func loadOrCreateIdentity(forceNewPassword: Bool = false) throws -> (identity: SecIdentity, certificate: SecCertificate, password: String) { + let password = (forceNewPassword ? nil : existingPassword()) ?? newPassword() if !FileManager.default.fileExists(atPath: p12URL.path) { var errorMessage: NSString? diff --git a/SwiftIPA/Shared/InboxStore.swift b/SwiftIPA/Shared/InboxStore.swift deleted file mode 100644 index 26b52fa..0000000 --- a/SwiftIPA/Shared/InboxStore.swift +++ /dev/null @@ -1,63 +0,0 @@ -import Foundation -import UIKit - -enum InboxStore { - struct Item { - let suggestedName: String - let data: Data - } - - private static let itemType = "com.xsxs18.swiftipa.inbox-item" - - static func queue(_ items: [Item]) { - UIPasteboard.general.items = items.compactMap { item in - guard let nameData = item.suggestedName.data(using: .utf8), nameData.count <= UInt32.max else { return nil } - var payload = encodedUInt32(UInt32(nameData.count)) - payload.append(nameData) - payload.append(item.data) - return [itemType: payload] - } - } - - static func takePending() -> [Item] { - guard UIPasteboard.general.contains(pasteboardTypes: [itemType]) else { return [] } - var remaining: [[String: Any]] = [] - var results: [Item] = [] - for entry in UIPasteboard.general.items { - if let payload = entry[itemType] as? Data, let item = decode(payload) { - results.append(item) - } else { - remaining.append(entry) - } - } - if !results.isEmpty { - UIPasteboard.general.items = remaining - } - return results - } - - private static func encodedUInt32(_ value: UInt32) -> Data { - Data([ - UInt8((value >> 24) & 0xFF), - UInt8((value >> 16) & 0xFF), - UInt8((value >> 8) & 0xFF), - UInt8(value & 0xFF) - ]) - } - - private static func decodeUInt32(_ data: Data) -> UInt32 { - data.reduce(UInt32(0)) { ($0 << 8) | UInt32($1) } - } - - private static func decode(_ payload: Data) -> Item? { - guard payload.count >= 4 else { return nil } - var cursor = payload.startIndex - let nameLength = Int(decodeUInt32(payload[cursor..<(cursor + 4)])) - cursor += 4 - guard cursor + nameLength <= payload.endIndex else { return nil } - guard let name = String(data: payload[cursor..<(cursor + nameLength)], encoding: .utf8) else { return nil } - cursor += nameLength - let fileData = payload[cursor...] - return Item(suggestedName: name, data: Data(fileData)) - } -} diff --git a/SwiftIPA/Shared/ProgressReportingDownloader.swift b/SwiftIPA/Shared/ProgressReportingDownloader.swift index 9f82975..b2b0256 100644 --- a/SwiftIPA/Shared/ProgressReportingDownloader.swift +++ b/SwiftIPA/Shared/ProgressReportingDownloader.swift @@ -4,20 +4,46 @@ final class ProgressReportingDownloader: NSObject, URLSessionDownloadDelegate { private var continuation: CheckedContinuation? private let onProgress: (Double?, Int64) -> Void private var session: URLSession? + private var task: URLSessionDownloadTask? + private let lock = NSLock() init(onProgress: @escaping (Double?, Int64) -> Void) { self.onProgress = onProgress } func download(from url: URL) async throws -> URL { - try await withCheckedThrowingContinuation { continuation in - self.continuation = continuation - let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil) - self.session = session - session.downloadTask(with: url).resume() + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + lock.lock() + self.continuation = continuation + // The session keeps its delegate (self) alive until it's invalidated in finish(_:). + let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil) + self.session = session + let task = session.downloadTask(with: url) + self.task = task + lock.unlock() + task.resume() + } + } onCancel: { + lock.lock() + let task = self.task + lock.unlock() + task?.cancel() } } + private func finish(_ result: Result) { + lock.lock() + let continuation = self.continuation + self.continuation = nil + let session = self.session + self.session = nil + self.task = nil + lock.unlock() + session?.finishTasksAndInvalidate() + continuation?.resume(with: result) + } + func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, @@ -31,24 +57,20 @@ final class ProgressReportingDownloader: NSObject, URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { guard let httpResponse = downloadTask.response as? HTTPURLResponse, httpResponse.statusCode == 200 else { - continuation?.resume(throwing: RepositoryServiceError.invalidResponse) - continuation = nil + finish(.failure(RepositoryServiceError.invalidResponse)) return } let destination = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).ipa") do { - try FileManager.default.replaceItem(at: destination, withItemAt: location) - continuation?.resume(returning: destination) + // The downloaded file is deleted as soon as this method returns, so move it now. + try FileManager.default.moveItem(at: location, to: destination) + finish(.success(destination)) } catch { - continuation?.resume(throwing: error) + finish(.failure(error)) } - continuation = nil } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - if let error { - continuation?.resume(throwing: error) - continuation = nil - } + if let error { finish(.failure(error)) } } } diff --git a/SwiftIPA/Signing/IPAService.swift b/SwiftIPA/Signing/IPAService.swift index cbe4763..d9d5558 100644 --- a/SwiftIPA/Signing/IPAService.swift +++ b/SwiftIPA/Signing/IPAService.swift @@ -91,79 +91,123 @@ enum IPAService { guard let plist = InfoPlistPatcher.read(at: extracted.infoPlistURL) else { throw IPAServiceError.noInfoPlist } - - let name = (plist["CFBundleDisplayName"] as? String) ?? (plist["CFBundleName"] as? String) ?? extracted.appFolder.deletingPathExtension().lastPathComponent - let bundleID = (plist["CFBundleIdentifier"] as? String) ?? "" - let version = (plist["CFBundleShortVersionString"] as? String) ?? "1.0" - let build = (plist["CFBundleVersion"] as? String) ?? "1" - let minimumOS = (plist["MinimumOSVersion"] as? String) ?? "" - - var schemes: [String] = [] - if let urlTypes = plist["CFBundleURLTypes"] as? [[String: Any]] { - for entry in urlTypes { - if let names = entry["CFBundleURLSchemes"] as? [String] { - schemes.append(contentsOf: names) - } - } - } - let fileManager = FileManager.default let watchExists = fileManager.fileExists(atPath: extracted.appFolder.appendingPathComponent("Watch").path) let pluginsFolder = extracted.appFolder.appendingPathComponent("PlugIns") let plugins = (try? fileManager.contentsOfDirectory(atPath: pluginsFolder.path)) ?? [] + return metadata( + fromPlist: plist, + fallbackName: extracted.appFolder.deletingPathExtension().lastPathComponent, + hasWatchApp: watchExists, + plugins: plugins + ) + } + private static func metadata(fromPlist plist: [String: Any], fallbackName: String, hasWatchApp: Bool, plugins: [String]) -> AppMetadata { + let name = (plist["CFBundleDisplayName"] as? String) ?? (plist["CFBundleName"] as? String) ?? fallbackName + var schemes: [String] = [] + for entry in (plist["CFBundleURLTypes"] as? [[String: Any]]) ?? [] { + schemes.append(contentsOf: (entry["CFBundleURLSchemes"] as? [String]) ?? []) + } return AppMetadata( name: name, - bundleIdentifier: bundleID, - version: version, - build: build, - minimumOSVersion: minimumOS, + bundleIdentifier: (plist["CFBundleIdentifier"] as? String) ?? "", + version: (plist["CFBundleShortVersionString"] as? String) ?? "1.0", + build: (plist["CFBundleVersion"] as? String) ?? "1", + minimumOSVersion: (plist["MinimumOSVersion"] as? String) ?? "", urlSchemes: schemes, - hasWatchApp: watchExists, + hasWatchApp: hasWatchApp, plugins: plugins ) } - static func extractIcon(from extracted: ExtractedApp) -> Data? { - guard let plist = InfoPlistPatcher.read(at: extracted.infoPlistURL) else { return nil } - let icons = plist["CFBundleIcons"] as? [String: Any] - let primary = icons?["CFBundlePrimaryIcon"] as? [String: Any] - let files = (primary?["CFBundleIconFiles"] as? [String]) ?? [] + /// Reads the metadata and icon straight from the archive instead of + /// unpacking it, so importing a big IPA doesn't need its size again in free + /// space. `verifyChecksums` reads every file once to check its CRC, which + /// catches a broken download here instead of after signing. + static func inspectArchive(at ipaURL: URL, verifyChecksums: Bool = true) throws -> (metadata: AppMetadata, icon: Data?) { + let archive: Archive + do { + archive = try Archive(url: ipaURL, accessMode: .read) + } catch { + throw IPAServiceError.notAnIPA + } - let fileManager = FileManager.default - let candidates = (try? fileManager.contentsOfDirectory(atPath: extracted.appFolder.path)) ?? [] - - var bestURL: URL? - var bestSize = -1 - - for base in files { - for candidate in candidates where candidate.hasPrefix(base) && candidate.hasSuffix(".png") { - let url = extracted.appFolder.appendingPathComponent(candidate) - if let image = UIImage(contentsOfFile: url.path) { - let size = Int(image.size.width * image.size.height) - if size > bestSize { - bestSize = size - bestURL = url - } - } + var appPrefix: String? + var appFolderName = "" + for entry in archive where entry.type == .file { + let parts = entry.path.split(separator: "/", omittingEmptySubsequences: false) + if parts.count == 3, parts[0] == "Payload", parts[1].hasSuffix(".app"), parts[2] == "Info.plist" { + appFolderName = String(parts[1]) + appPrefix = "Payload/\(appFolderName)/" + break } } + guard let appPrefix, let plistEntry = archive[appPrefix + "Info.plist"] else { + throw IPAServiceError.noAppBundleFound + } + guard let plistData = try? readEntry(plistEntry, in: archive), + let plist = try? PropertyListSerialization.propertyList(from: plistData, format: nil) as? [String: Any] else { + throw IPAServiceError.noInfoPlist + } - if bestURL == nil { - for candidate in candidates where candidate.lowercased().contains("appicon") && candidate.hasSuffix(".png") { - let url = extracted.appFolder.appendingPathComponent(candidate) - if let image = UIImage(contentsOfFile: url.path) { - let size = Int(image.size.width * image.size.height) - if size > bestSize { - bestSize = size - bestURL = url - } + var hasWatchApp = false + var plugins = Set() + var rootFiles: [String: Entry] = [:] + for entry in archive { + if verifyChecksums, entry.type == .file { + let checksum: CRC32 + do { + checksum = try archive.extract(entry, skipCRC32: false) { _ in } + } catch { + throw IPAServiceError.extractionFailed } + if checksum != entry.checksum { throw IPAServiceError.extractionFailed } } + guard entry.path.hasPrefix(appPrefix) else { continue } + let inner = entry.path.dropFirst(appPrefix.count) + if inner.hasPrefix("Watch/") { hasWatchApp = true } + if inner.hasPrefix("PlugIns/") { + let name = inner.dropFirst("PlugIns/".count).split(separator: "/").first.map(String.init) + if let name, name.hasSuffix(".appex") { plugins.insert(name) } + } + if entry.type == .file, !inner.contains("/") { rootFiles[String(inner)] = entry } } - guard let iconURL = bestURL else { return nil } - return try? Data(contentsOf: iconURL) + let metadata = metadata( + fromPlist: plist, + fallbackName: (appFolderName as NSString).deletingPathExtension, + hasWatchApp: hasWatchApp, + plugins: plugins.sorted() + ) + let icon = bestIcon(plist: plist, candidates: rootFiles.keys.sorted()) { name in + rootFiles[name].flatMap { try? readEntry($0, in: archive) } + } + return (metadata, icon) + } + + private static func readEntry(_ entry: Entry, in archive: Archive) throws -> Data { + var data = Data() + _ = try archive.extract(entry, skipCRC32: true) { data.append($0) } + return data + } + + /// The biggest PNG named like the app's icon files, or any "AppIcon" PNG. + private static func bestIcon(plist: [String: Any], candidates: [String], load: (String) -> Data?) -> Data? { + let icons = plist["CFBundleIcons"] as? [String: Any] + let primary = icons?["CFBundlePrimaryIcon"] as? [String: Any] + let iconFiles = (primary?["CFBundleIconFiles"] as? [String]) ?? [] + let pngs = candidates.filter { $0.lowercased().hasSuffix(".png") } + var named = pngs.filter { name in iconFiles.contains { name.hasPrefix($0) } } + if named.isEmpty { named = pngs.filter { $0.lowercased().contains("appicon") } } + + var best: (data: Data, pixels: Int)? + for name in named { + guard let data = load(name), let image = UIImage(data: data) else { continue } + let pixels = Int(image.size.width * image.scale * image.size.height * image.scale) + if pixels > (best?.pixels ?? -1) { best = (data, pixels) } + } + return best?.data } /// `compress: false` stores files without deflate. The IPA gets bigger but diff --git a/SwiftIPA/Signing/SigningCache.swift b/SwiftIPA/Signing/SigningCache.swift index ea02fea..fd23731 100644 --- a/SwiftIPA/Signing/SigningCache.swift +++ b/SwiftIPA/Signing/SigningCache.swift @@ -5,6 +5,8 @@ struct SigningCacheEntry: Codable { var ipaFileName: String var createdAt: Date var byteSize: Int64 + /// The bundle ID the cached build was signed with. Missing in entries from before 1.8. + var bundleIdentifier: String? } final class SigningCache { @@ -26,7 +28,7 @@ final class SigningCache { FileHashing.sha256(of: "\(sourceHash)|\(optionsFingerprint)|\(certificateFingerprint)") } - func cachedIPA(for key: String) -> URL? { + func cachedIPA(for key: String) -> (url: URL, bundleIdentifier: String?)? { queue.sync { var index = readIndex() guard let entry = index[key] else { return nil } @@ -36,11 +38,11 @@ final class SigningCache { writeIndex(index) return nil } - return fileURL + return (fileURL, entry.bundleIdentifier) } } - func store(key: String, ipaURL: URL) { + func store(key: String, ipaURL: URL, bundleIdentifier: String?) { queue.sync { var index = readIndex() let fileName = "\(key).ipa" @@ -48,7 +50,7 @@ final class SigningCache { guard (try? FileManager.default.replaceItem(at: destination, withItemAt: ipaURL)) != nil else { return } let size = (try? FileManager.default.attributesOfItem(atPath: destination.path)[.size] as? Int64) ?? 0 - index[key] = SigningCacheEntry(key: key, ipaFileName: fileName, createdAt: Date(), byteSize: size) + index[key] = SigningCacheEntry(key: key, ipaFileName: fileName, createdAt: Date(), byteSize: size, bundleIdentifier: bundleIdentifier) writeIndex(index) evictIfNeeded(index: &index) } diff --git a/SwiftIPA/Signing/SigningEngine.swift b/SwiftIPA/Signing/SigningEngine.swift index b1a1b64..1f76ec3 100644 --- a/SwiftIPA/Signing/SigningEngine.swift +++ b/SwiftIPA/Signing/SigningEngine.swift @@ -25,8 +25,13 @@ actor SigningEngine { private let cache = SigningCache.shared + /// The heavy steps take turns on this actor anyway, but every running job + /// keeps its unpacked IPA on disk while it waits. With many jobs that could + /// fill up the device, two at a time is enough. + private static let maxConcurrentJobs = 2 + func run(jobs: [SigningJob]) async { - let concurrency = max(1, min(ProcessInfo.processInfo.activeProcessorCount, jobs.count)) + let concurrency = max(1, min(Self.maxConcurrentJobs, jobs.count)) await withTaskGroup(of: Void.self) { group in var iterator = jobs.makeIterator() var launched = 0 @@ -60,7 +65,11 @@ actor SigningEngine { ) try? FileManager.default.removeItem(at: result.url) } catch { - await MainActor.run { job.status = .failed(error.localizedDescription) } + let log = (error as? ZSignEngineError)?.log + await MainActor.run { + job.log = log + job.status = .failed(error.localizedDescription) + } } } @@ -82,19 +91,19 @@ actor SigningEngine { let certificateBundleID = CertificateStore.shared.profileBundleIdentifier(forCertificateID: certificate.id) var cacheKey: String? - if job.options.useCache, + // A random suffix is supposed to be new every time, a cached build would repeat the old one. + if job.options.useCache, job.options.bundleIdentifierRule != .randomSuffix, let sourceHash = FileHashing.cachedSHA256(of: job.sourceIPAURL), - let optionsData = try? JSONEncoder().encode(job.options) { - let optionsFingerprint = FileHashing.sha256(of: String(data: optionsData, encoding: .utf8) ?? "") + let optionsFingerprint = Self.fingerprint(of: job.options) { let certFingerprint = (FileHashing.cachedSHA256(of: p12URL) ?? "") + (FileHashing.cachedSHA256(of: provisionURL) ?? "") let key = cache.key(sourceHash: sourceHash, optionsFingerprint: optionsFingerprint, certificateFingerprint: certFingerprint) cacheKey = key if let cached = cache.cachedIPA(for: key) { await MainActor.run { job.status = .cached } let tempCopy = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).ipa") - try FileManager.default.replaceItem(at: tempCopy, withItemAt: cached) + try FileManager.default.replaceItem(at: tempCopy, withItemAt: cached.url) await MainActor.run { job.status = .done(0) } - return (tempCopy, nil) + return (tempCopy, cached.bundleIdentifier) } } @@ -160,7 +169,7 @@ actor SigningEngine { try IPAService.repack(extracted: extracted, to: output, compress: !job.options.fastPackaging) if let cacheKey { - cache.store(key: cacheKey, ipaURL: output) + cache.store(key: cacheKey, ipaURL: output, bundleIdentifier: resolvedBundleID) } let elapsed = Date().timeIntervalSince(started) @@ -168,6 +177,29 @@ actor SigningEngine { return (output, resolvedBundleID) } + /// Everything about the options that changes the signed app: the options + /// themselves (with sorted keys, so the same options always give the same + /// text) plus the contents of the tweaks and the custom icon, which can be + /// replaced without the options changing. + private static func fingerprint(of options: SigningOptions) -> String? { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + guard let optionsData = try? encoder.encode(options) else { return nil } + var parts = [String(decoding: optionsData, as: UTF8.self)] + let store = DylibLibraryStore.shared + for id in options.injectedDylibIDs { + guard let dylib = store.dylibs.first(where: { $0.id == id }) else { continue } + parts.append("tweak \(id.uuidString) \(FileHashing.cachedSHA256(of: store.url(for: dylib)) ?? "-")") + } + if let provider = store.substrateProvider, !options.injectedDylibIDs.isEmpty { + parts.append("substrate \(FileHashing.cachedSHA256(of: store.url(for: provider)) ?? "-")") + } + if let iconPath = options.customIconPath { + parts.append("icon \(FileHashing.cachedSHA256(of: URL(fileURLWithPath: iconPath)) ?? "-")") + } + return FileHashing.sha256(of: parts.joined(separator: "\n")) + } + /// Returns the files zsign should inject. Tweaks built for a jailbreak link /// CydiaSubstrate from a path that doesn't exist in a sideloaded app, so a /// copy of each such tweak is pointed at the substrate provider from the diff --git a/SwiftIPA/Signing/SigningJob.swift b/SwiftIPA/Signing/SigningJob.swift index 0dd8e20..c4ef6ad 100644 --- a/SwiftIPA/Signing/SigningJob.swift +++ b/SwiftIPA/Signing/SigningJob.swift @@ -27,6 +27,8 @@ final class SigningJob: Identifiable, ObservableObject { let certificateID: UUID @Published var status: SigningJobStatus = .queued + /// zsign's output when signing failed, shown under "Show Log". + @Published var log: String? init(appEntryID: UUID, sourceIPAURL: URL, displayName: String, options: SigningOptions, certificateID: UUID) { self.appEntryID = appEntryID diff --git a/SwiftIPA/Signing/ZSignEngine.swift b/SwiftIPA/Signing/ZSignEngine.swift index 396f5c5..81ce3ae 100644 --- a/SwiftIPA/Signing/ZSignEngine.swift +++ b/SwiftIPA/Signing/ZSignEngine.swift @@ -1,20 +1,31 @@ import Foundation +#if canImport(ZSignKit) +import ZSignKit // xtool/SwiftPM build; Xcode uses the bridging header +#endif enum ZSignEngineError: LocalizedError { case engineUnavailable - case invalidCertificate(String) - case signingFailed(String) + case invalidCertificate(String, log: String?) + case signingFailed(String, log: String?) var errorDescription: String? { switch self { case .engineUnavailable: return String(localized: "The signing engine isn't built into this copy of SwiftIPA. Run Scripts/fetch-dependencies.sh, then rebuild in Xcode.") - case .invalidCertificate(let message): + case .invalidCertificate(let message, _): return message - case .signingFailed(let message): + case .signingFailed(let message, _): return message } } + + /// What zsign printed, for the log view after a failed sign. + var log: String? { + switch self { + case .engineUnavailable: return nil + case .invalidCertificate(_, let log), .signingFailed(_, let log): return log + } + } } struct ZSignOutcome { @@ -74,11 +85,11 @@ enum ZSignEngine { case .success: return ZSignOutcome(duration: result.duration) case .invalidCertificate: - throw ZSignEngineError.invalidCertificate(result.message ?? String(localized: "Invalid certificate.")) + throw ZSignEngineError.invalidCertificate(result.message ?? String(localized: "Invalid certificate."), log: result.log) case .engineUnavailable: throw ZSignEngineError.engineUnavailable default: - throw ZSignEngineError.signingFailed(result.message ?? String(localized: "Signing failed.")) + throw ZSignEngineError.signingFailed(result.message ?? String(localized: "Signing failed."), log: result.log) } } } diff --git a/SwiftIPA/Views/Library/AppDetailView.swift b/SwiftIPA/Views/Library/AppDetailView.swift index 77e9240..bc1d2bc 100644 --- a/SwiftIPA/Views/Library/AppDetailView.swift +++ b/SwiftIPA/Views/Library/AppDetailView.swift @@ -7,6 +7,7 @@ struct AppDetailView: View { @State private var showingInspector = false @State private var showingRename = false @State private var showingShareSheet = false + @State private var showingOriginalShareSheet = false @State private var showingInstall = false @State private var inspectionError: String? @Environment(\.dismiss) private var dismiss @@ -69,6 +70,14 @@ struct AppDetailView: View { Label("Export IPA", systemImage: "square.and.arrow.up") } + if entry.isSigned && entry.hasOriginal { + Button { + showingOriginalShareSheet = true + } label: { + Label("Export Original IPA", systemImage: "doc.zipper") + } + } + Button { inspect(entry) } label: { @@ -100,6 +109,9 @@ struct AppDetailView: View { if let certificate = CertificateStore.shared.certificate(withID: entry.certificateID) { LabeledContent("Certificate", value: certificate.name) } + if entry.hasOriginal { + LabeledContent("Original IPA", value: originalSize(for: entry)) + } } } } @@ -122,6 +134,9 @@ struct AppDetailView: View { .sheet(isPresented: $showingShareSheet) { ShareSheet(items: [library.ipaURL(for: entry)]) } + .sheet(isPresented: $showingOriginalShareSheet) { + ShareSheet(items: [library.originalIPAURL(for: entry)]) + } .overlay(alignment: .bottom) { if showingInstall { InstallStatusPill(entryID: entry.id) { @@ -140,6 +155,12 @@ struct AppDetailView: View { @State private var inspectionReport: InspectionReport? + private func originalSize(for entry: AppEntry) -> String { + let path = library.originalIPAURL(for: entry).path + let bytes = (try? FileManager.default.attributesOfItem(atPath: path)[.size] as? Int64) ?? 0 + return ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file) + } + private func inspect(_ entry: AppEntry) { do { inspectionReport = try InspectorService.inspect(ipaURL: library.ipaURL(for: entry)) diff --git a/SwiftIPA/Views/Library/LibraryView.swift b/SwiftIPA/Views/Library/LibraryView.swift index 43b90a8..b28201c 100644 --- a/SwiftIPA/Views/Library/LibraryView.swift +++ b/SwiftIPA/Views/Library/LibraryView.swift @@ -1,6 +1,38 @@ import SwiftUI import UniformTypeIdentifiers +enum LibrarySortOrder: String, CaseIterable, Identifiable { + case recentlyAdded + case recentlySigned + case name + case size + + var id: String { rawValue } + + var title: LocalizedStringKey { + switch self { + case .recentlyAdded: return "Recently Added" + case .recentlySigned: return "Recently Signed" + case .name: return "Name" + case .size: return "Size" + } + } + + func sorted(_ apps: [AppEntry]) -> [AppEntry] { + switch self { + case .recentlyAdded: + return apps.sorted { $0.importedAt > $1.importedAt } + case .recentlySigned: + // Unsigned apps last, newest import first among them. + return apps.sorted { ($0.signedAt ?? .distantPast, $0.importedAt) > ($1.signedAt ?? .distantPast, $1.importedAt) } + case .name: + return apps.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } + case .size: + return apps.sorted { $0.byteSize > $1.byteSize } + } + } +} + struct LibraryView: View { @ObservedObject private var library = AppLibraryStore.shared @State private var searchText = "" @@ -12,10 +44,12 @@ struct LibraryView: View { @State private var importError: String? @State private var isImporting = false @State private var importingCount = 0 + @AppStorage("SwiftIPA.librarySortOrder") private var sortOrder: LibrarySortOrder = .recentlyAdded private var filteredApps: [AppEntry] { - guard !searchText.isEmpty else { return library.apps } - return library.apps.filter { + let apps = sortOrder.sorted(library.apps) + guard !searchText.isEmpty else { return apps } + return apps.filter { $0.name.localizedCaseInsensitiveContains(searchText) || $0.bundleIdentifier.localizedCaseInsensitiveContains(searchText) } @@ -53,6 +87,18 @@ struct LibraryView: View { Button("Sign All") { showingBatchSheet = true } .disabled(selection.isEmpty) } else { + if library.apps.count > 1 { + Menu { + Picker("Sort By", selection: $sortOrder) { + ForEach(LibrarySortOrder.allCases) { order in + Text(order.title).tag(order) + } + } + } label: { + Image(systemName: "arrow.up.arrow.down") + } + .accessibilityLabel(Text("Sort By")) + } Menu { Button { showingImporter = true diff --git a/SwiftIPA/Views/Signing/BatchQueueView.swift b/SwiftIPA/Views/Signing/BatchQueueView.swift index a0e145f..5b5c42b 100644 --- a/SwiftIPA/Views/Signing/BatchQueueView.swift +++ b/SwiftIPA/Views/Signing/BatchQueueView.swift @@ -72,7 +72,9 @@ struct BatchQueueView: View { private func start() { guard let certificateID else { return } - let options = presetID.flatMap { id in presetStore.presets.first { $0.id == id }?.options } ?? SigningOptions() + // Without a preset, use the default signing options from Settings like a single sign does. + let options = presetID.flatMap { id in presetStore.presets.first { $0.id == id }?.options } + ?? DefaultSigningOptionsStore.shared.options jobs = entryIDs.compactMap { id -> SigningJob? in guard let entry = library.apps.first(where: { $0.id == id }) else { return nil } @@ -82,7 +84,7 @@ struct BatchQueueView: View { if entryOptions.build.isEmpty { entryOptions.build = entry.build } return SigningJob( appEntryID: entry.id, - sourceIPAURL: library.ipaURL(for: entry), + sourceIPAURL: library.originalIPAURL(for: entry), displayName: entry.name, options: entryOptions, certificateID: certificateID @@ -101,6 +103,7 @@ struct BatchQueueView: View { private struct BatchJobRow: View { @ObservedObject var job: SigningJob + @State private var showingLog = false var body: some View { HStack { @@ -109,7 +112,16 @@ private struct BatchJobRow: View { statusView .transition(.opacity.combined(with: .scale(scale: 0.9))) } + .contentShape(Rectangle()) + .onTapGesture { + if case .failed = job.status { showingLog = true } + } .animation(.easeOut(duration: 0.2), value: job.status) + .sheet(isPresented: $showingLog) { + if case .failed(let message) = job.status { + SigningLogView(title: job.displayName, message: message, log: job.log ?? "") + } + } } @ViewBuilder @@ -124,7 +136,11 @@ private struct BatchJobRow: View { case .done(let seconds): StatusBadge(text: seconds < 0.05 ? String(localized: "Instant") : String(format: "%.1fs", seconds), color: SIColor.success) case .failed: - StatusBadge(text: String(localized: "Failed"), color: SIColor.danger) + HStack(spacing: 4) { + StatusBadge(text: String(localized: "Failed"), color: SIColor.danger) + // Tap the row for the message and zsign's log. + Image(systemName: "info.circle").foregroundStyle(SIColor.danger) + } } } } diff --git a/SwiftIPA/Views/Signing/SigningLogView.swift b/SwiftIPA/Views/Signing/SigningLogView.swift new file mode 100644 index 0000000..73de54d --- /dev/null +++ b/SwiftIPA/Views/Signing/SigningLogView.swift @@ -0,0 +1,52 @@ +import SwiftUI + +/// zsign's output after a failed sign, to copy into a bug report. +struct SigningLogView: View { + let title: String + let message: String + let log: String + @Environment(\.dismiss) private var dismiss + @State private var copied = false + + private var report: String { + "\(title)\n\(message)\n\n\(log)" + } + + var body: some View { + NavigationStack { + ScrollView { + VStack(alignment: .leading, spacing: SISpacing.md) { + Text(message) + .font(SIFont.headline) + .foregroundStyle(SIColor.danger) + Text(log.isEmpty ? String(localized: "zsign didn't print anything.") : log) + .font(.system(.footnote, design: .monospaced)) + .foregroundStyle(SIColor.textPrimary) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + } + .padding(SISpacing.md) + } + .siScreen() + .navigationTitle("Signing Log") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Done") { dismiss() } + } + ToolbarItemGroup(placement: .primaryAction) { + Button { + UIPasteboard.general.string = report + copied = true + } label: { + Image(systemName: copied ? "checkmark" : "doc.on.doc") + } + .accessibilityLabel(Text("Copy Log")) + ShareLink(item: report) { + Image(systemName: "square.and.arrow.up") + } + } + } + } + } +} diff --git a/SwiftIPA/Views/Signing/SigningSheetView.swift b/SwiftIPA/Views/Signing/SigningSheetView.swift index 8d05611..6875680 100644 --- a/SwiftIPA/Views/Signing/SigningSheetView.swift +++ b/SwiftIPA/Views/Signing/SigningSheetView.swift @@ -16,6 +16,8 @@ struct SigningSheetView: View { @State private var isSigning = false @State private var jobStatus: SigningJobStatus = .queued @State private var errorMessage: String? + @State private var failureLog: String? + @State private var showingLog = false @State private var showingSavePreset = false @State private var presetName = "" @State private var pickedIconItem: PhotosPickerItem? @@ -73,6 +75,9 @@ struct SigningSheetView: View { loadPickedIcon(newItem) } .alert("Signing Failed", isPresented: Binding(get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } })) { + if failureLog != nil { + Button("Show Log") { showingLog = true } + } Button("OK") { errorMessage = nil } } message: { Text(errorMessage ?? "") @@ -82,6 +87,9 @@ struct SigningSheetView: View { } message: { Text(iconImportError ?? "") } + .sheet(isPresented: $showingLog) { + SigningLogView(title: entry?.name ?? "", message: errorMessage ?? String(localized: "Signing failed."), log: failureLog ?? "") + } .sheet(isPresented: $showingSavePreset) { NameInputSheet(title: String(localized: "Save Preset"), placeholder: String(localized: "Preset name"), text: "", confirmTitle: String(localized: "Save")) { name in presetStore.save(name: name, certificateID: certificateID, options: options) @@ -322,7 +330,7 @@ struct SigningSheetView: View { let job = SigningJob( appEntryID: entry.id, - sourceIPAURL: library.ipaURL(for: entry), + sourceIPAURL: library.originalIPAURL(for: entry), displayName: entry.name, options: options, certificateID: certificateID @@ -338,6 +346,7 @@ struct SigningSheetView: View { await MainActor.run { isSigning = false if case .failed(let message) = job.status { + failureLog = job.log errorMessage = message } else { let shouldInstall = options.installAfterSigning diff --git a/SwiftIPA/Views/Sources/SourceDetailView.swift b/SwiftIPA/Views/Sources/SourceDetailView.swift index 1fb4862..08ca2fa 100644 --- a/SwiftIPA/Views/Sources/SourceDetailView.swift +++ b/SwiftIPA/Views/Sources/SourceDetailView.swift @@ -60,8 +60,9 @@ struct SourceDetailView: View { downloadedBytes = bytesWritten } } + // Also when the import fails, otherwise the download stays in tmp. + defer { try? FileManager.default.removeItem(at: url) } let entry = try await AppLibraryStore.shared.importIPA(at: url, sourceName: source?.name) - try? FileManager.default.removeItem(at: url) await MainActor.run { downloadingID = nil signEntryID = entry.id diff --git a/SwiftIPA/Signing/ZSign/ZSignBridge.mm b/ZSignKit/ZSignBridge.mm similarity index 90% rename from SwiftIPA/Signing/ZSign/ZSignBridge.mm rename to ZSignKit/ZSignBridge.mm index a2ea2e3..bdaa0cf 100644 --- a/SwiftIPA/Signing/ZSign/ZSignBridge.mm +++ b/ZSignKit/ZSignBridge.mm @@ -29,6 +29,7 @@ + (nullable NSDate *)dateFromCertificateData:(NSData *)certificateData notAfter: #if SWIFTIPA_HAS_ZSIGN + (NSString *)captureStdoutDuringBlock:(void (^)(void))block; + (nullable NSString *)lastErrorLineFromCapturedOutput:(NSString *)output; ++ (NSString *)plainTextFromCapturedOutput:(NSString *)output; #endif @end @@ -87,6 +88,13 @@ + (nullable NSString *)lastErrorLineFromCapturedOutput:(NSString *)output { } return trimmed.length > 0 ? trimmed : nil; } + ++ (NSString *)plainTextFromCapturedOutput:(NSString *)output { + if (output.length == 0) return @""; + NSRegularExpression *colors = [NSRegularExpression regularExpressionWithPattern:@"\x1b\\[[0-9;]*m" options:0 error:nil]; + NSString *plain = colors ? [colors stringByReplacingMatchesInString:output options:0 range:NSMakeRange(0, output.length) withTemplate:@""] : output; + return [plain stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; +} #endif + (BOOL)isEngineAvailable { @@ -101,6 +109,15 @@ + (ZSignResult *)signAppFolderAtPath:(NSString *)folderPath options:(ZSignOption ZSignResult *result = [ZSignResult new]; #if SWIFTIPA_HAS_ZSIGN + // zsign prints to stdout, which captureStdoutDuringBlock redirects for the + // whole process. Two signs at once would swap each other's pipes and the + // second reader would wait forever. SigningEngine already runs one at a + // time, this keeps any other caller from doing it. + static NSLock *signLock; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ signLock = [NSLock new]; }); + [signLock lock]; + CFTimeInterval started = CACurrentMediaTime(); __block bool prepared = false; @@ -155,7 +172,10 @@ + (ZSignResult *)signAppFolderAtPath:(NSString *)folderPath options:(ZSignOption ); }]; + [signLock unlock]; + result.duration = CACurrentMediaTime() - started; + result.log = [self plainTextFromCapturedOutput:capturedOutput]; NSString *detail = [self lastErrorLineFromCapturedOutput:capturedOutput]; if (!prepared) { diff --git a/SwiftIPA/Signing/ZSign/ZSignBridge.h b/ZSignKit/include/ZSignBridge.h similarity index 95% rename from SwiftIPA/Signing/ZSign/ZSignBridge.h rename to ZSignKit/include/ZSignBridge.h index f764e39..f5feb77 100644 --- a/SwiftIPA/Signing/ZSign/ZSignBridge.h +++ b/ZSignKit/include/ZSignBridge.h @@ -13,6 +13,8 @@ typedef NS_ENUM(NSInteger, ZSignResultCode) { @interface ZSignResult : NSObject @property (nonatomic, assign) ZSignResultCode code; @property (nonatomic, copy, nullable) NSString *message; +/// Everything zsign printed while signing, without color codes. +@property (nonatomic, copy, nullable) NSString *log; @property (nonatomic, assign) NSTimeInterval duration; @end diff --git a/project.yml b/project.yml index a05b53a..53e8c05 100644 --- a/project.yml +++ b/project.yml @@ -8,10 +8,11 @@ options: packages: ZIPFoundation: url: https://github.com/weichsel/ZIPFoundation.git - from: 0.9.19 + exactVersion: 0.9.20 + # Keep in sync with OPENSSL_TAG in Scripts/fetch-dependencies.sh (headers) and Package.resolved. OpenSSL: url: https://github.com/krzyzanowskim/OpenSSL.git - from: 3.3.2000 + exactVersion: 3.6.5000 settings: base: SWIFT_VERSION: "5.0" @@ -25,6 +26,8 @@ targets: platform: iOS sources: - path: SwiftIPA + - path: ZSignKit/ZSignBridge.mm + - path: ZSignKit/include - path: Vendor/zsign/src optional: true excludes: @@ -37,6 +40,7 @@ targets: - "**/metadata.h" - "third-party/**" - "**/common_win32.h" + # The xtool build reads the same keys from Support/xtool-Info.plist, keep both in sync. info: path: SwiftIPA/Resources/Info.plist properties: @@ -67,7 +71,7 @@ targets: UIFileSharingEnabled: true LSSupportsOpeningDocumentsInPlace: true CFBundleVersion: "0" - CFBundleShortVersionString: "1.7.2" + CFBundleShortVersionString: "1.8.0" CFBundleLocalizations: - en - de @@ -91,6 +95,7 @@ targets: - $(SRCROOT)/Vendor/zsign/src - $(SRCROOT)/Vendor/zsign/src/common - $(SRCROOT)/Vendor/openssl-include + - $(SRCROOT)/ZSignKit/include GCC_PREPROCESSOR_DEFINITIONS: - $(inherited) - SWIFTIPA_HAS_ZSIGN=1 diff --git a/xtool.yml b/xtool.yml new file mode 100644 index 0000000..b57bf45 --- /dev/null +++ b/xtool.yml @@ -0,0 +1,5 @@ +version: 1 +bundleID: com.xsxs18.SwiftIPA +infoPath: Support/xtool-Info.plist +iconPath: SwiftIPA/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png +skipLSP: true