From 150a059888a91f03d70dae72d6cdacf83316ce3c Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 1 Aug 2026 09:57:24 -0700 Subject: [PATCH] fix(swift-ios): harden platform integrations --- .../App/Cloud/T3ConnectConfiguration.swift | 12 +- apps/swift-ios/App/NativeFeatureClient.swift | 15 ++- .../App/Platform/PlatformAgentAwareness.swift | 97 ++++++++++++-- .../App/Platform/PlatformCloudDelivery.swift | 13 +- .../App/Platform/PlatformDeepLinks.swift | 8 +- .../App/Platform/PlatformNotifications.swift | 16 +-- .../Extensions/Share/SharePayloadLoader.swift | 121 +++++++++++++++--- .../Share/ShareViewController.swift | 3 +- .../Extensions/Shared/ShareInbox.swift | 36 ++++-- .../Features/Settings/SettingsView.swift | 13 -- apps/swift-ios/README.md | 12 +- apps/swift-ios/Scripts/ci-test.sh | 14 +- apps/swift-ios/Scripts/install-device.sh | 73 ++++++++++- .../Scripts/resolve-device-udid.swift | 43 +++++++ .../Tests/CoreTests/T3ConnectDPoPTests.swift | 2 +- .../T3ConnectNativeCapabilityTests.swift | 40 ++++++ .../PlatformTests/PlatformDeepLinkTests.swift | 9 ++ 17 files changed, 421 insertions(+), 106 deletions(-) create mode 100644 apps/swift-ios/Scripts/resolve-device-udid.swift diff --git a/apps/swift-ios/App/Cloud/T3ConnectConfiguration.swift b/apps/swift-ios/App/Cloud/T3ConnectConfiguration.swift index 657692c4b1..88de0b30a4 100644 --- a/apps/swift-ios/App/Cloud/T3ConnectConfiguration.swift +++ b/apps/swift-ios/App/Cloud/T3ConnectConfiguration.swift @@ -70,13 +70,11 @@ public struct T3ConnectConfiguration: Equatable, Sendable { } components.query = nil components.fragment = nil - if components.path != "/" { - components.path = components.path.replacingOccurrences( - of: #"/+$"#, - with: "", - options: .regularExpression - ) - } + components.path = components.path.replacingOccurrences( + of: #"/+$"#, + with: "", + options: .regularExpression + ) return components.url ?? url } } diff --git a/apps/swift-ios/App/NativeFeatureClient.swift b/apps/swift-ios/App/NativeFeatureClient.swift index 18b16a6105..f267c0e80f 100644 --- a/apps/swift-ios/App/NativeFeatureClient.swift +++ b/apps/swift-ios/App/NativeFeatureClient.swift @@ -18,6 +18,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, { private let runtime: EnvironmentRuntime let t3ConnectController: T3ConnectController + private let hasMatchingT3ConnectController: Bool private let settingsStore: UserDefaults private let fallbackPollingInitialDelay: Duration private let fallbackPollingInterval: Duration @@ -89,16 +90,19 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, let controller: T3ConnectController if let t3ConnectController { controller = t3ConnectController - } else if let runtime, !runtime.supportsManagedAuthorization { + } else if let runtime { controller = T3ConnectController( resolution: .unavailable( - reason: "This client runtime was created without T3 Connect authorization." + reason: runtime.supportsManagedAuthorization + ? "This client runtime requires its matching T3 Connect controller." + : "This client runtime was created without T3 Connect authorization." ) ) } else { controller = T3ConnectController() } self.t3ConnectController = controller + hasMatchingT3ConnectController = t3ConnectController != nil || runtime == nil self.runtime = runtime ?? EnvironmentRuntime( managedAuthorization: T3ConnectRuntimeAuthorization(controller: controller) ) @@ -157,7 +161,6 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, connectionDetail: activeIsReachable ? nil : "That server is currently unreachable." ) latestSnapshot = snapshot - startAggregateRefresh(activeClient) return snapshot } @@ -183,6 +186,11 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, func connectT3Environment( _ credential: T3ConnectManagedEnvironmentCredential ) async throws { + guard hasMatchingT3ConnectController else { + throw T3ConnectRelayError.invalidConfiguration( + "This client runtime requires its matching T3 Connect controller." + ) + } guard runtime.supportsManagedAuthorization else { throw T3ConnectRelayError.invalidConfiguration( "This client runtime was created without T3 Connect authorization." @@ -297,6 +305,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, if let previousClient, previousClient !== newClient { await previousClient.disconnect() } + startAggregateRefresh(newClient) } private func clearActiveEnvironment(disconnectClient: Bool = true) async { diff --git a/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift b/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift index 4b30839759..b54057dae8 100644 --- a/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift +++ b/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift @@ -163,8 +163,18 @@ final class PlatformAgentAwarenessCoordinator { let enabled: Bool } + private struct Synchronization { + let signature: Signature + let aggregate: T3RelayAgentActivityAggregateState + let enabled: Bool + let now: Date + } + private var activityUpdateTask: Task? private var lastSignature: Signature? + private var inFlightSignature: Signature? + private var latestSynchronization: Synchronization? + private var synchronizationGeneration = 0 func synchronize(snapshot: FeatureSnapshot, liveActivitiesEnabled: Bool) { let now = Date.now @@ -178,8 +188,14 @@ final class PlatformAgentAwarenessCoordinator { rows: aggregate.activities, enabled: liveActivitiesEnabled ) - guard signature != lastSignature else { return } - lastSignature = signature + let synchronization = Synchronization( + signature: signature, + aggregate: aggregate, + enabled: liveActivitiesEnabled, + now: now + ) + latestSynchronization = synchronization + guard signature != lastSignature, signature != inFlightSignature else { return } let widgetSnapshot = T3TaskWidgetSnapshot( updatedAt: aggregate.updatedAt, @@ -190,13 +206,65 @@ final class PlatformAgentAwarenessCoordinator { WidgetCenter.shared.reloadTimelines(ofKind: "T3RecentTasksWidget") } + schedule(synchronization) + } + + /// Account sign-out removes any activity that may contain account-scoped + /// content, then restores the latest local projection without waiting for + /// an unrelated thread update. + func resetAndResynchronizeLiveActivity() { + lastSignature = nil + guard let latestSynchronization else { + activityUpdateTask?.cancel() + synchronizationGeneration &+= 1 + inFlightSignature = nil + activityUpdateTask = Task { @MainActor in + for activity in Activity.activities { + await activity.end(nil, dismissalPolicy: .immediate) + } + notifyActivityChanged() + } + return + } + schedule(latestSynchronization, endingExistingActivitiesFirst: true) + } + + private func schedule( + _ synchronization: Synchronization, + endingExistingActivitiesFirst: Bool = false + ) { activityUpdateTask?.cancel() - activityUpdateTask = Task { @MainActor in - await synchronizeLiveActivity( - aggregate: aggregate, - enabled: liveActivitiesEnabled, - now: now - ) + synchronizationGeneration &+= 1 + let generation = synchronizationGeneration + inFlightSignature = synchronization.signature + activityUpdateTask = Task { @MainActor [weak self] in + guard let self else { return } + do { + if endingExistingActivitiesFirst { + for activity in Activity.activities { + await activity.end(nil, dismissalPolicy: .immediate) + } + try Task.checkCancellation() + } + try await synchronizeLiveActivity( + aggregate: synchronization.aggregate, + enabled: synchronization.enabled, + now: synchronization.now + ) + try Task.checkCancellation() + guard synchronizationGeneration == generation, + inFlightSignature == synchronization.signature else { return } + lastSignature = synchronization.signature + inFlightSignature = nil + activityUpdateTask = nil + } catch { + guard synchronizationGeneration == generation, + inFlightSignature == synchronization.signature else { return } + // Keep the completed signature unchanged so the next identical + // snapshot retries a failed or cancelled ActivityKit operation. + inFlightSignature = nil + activityUpdateTask = nil + } } } @@ -204,21 +272,20 @@ final class PlatformAgentAwarenessCoordinator { aggregate: T3RelayAgentActivityAggregateState, enabled: Bool, now: Date - ) async { - guard !Task.isCancelled else { return } + ) async throws { + try Task.checkCancellation() let activities = Activity.activities guard enabled, ActivityAuthorizationInfo().areActivitiesEnabled else { for activity in activities { await activity.end(nil, dismissalPolicy: .immediate) } + try Task.checkCancellation() notifyActivityChanged() return } - guard let state = try? LiveActivityAttributes.ContentState(aggregate: aggregate) else { - return - } + let state = try LiveActivityAttributes.ContentState(aggregate: aggregate) let content = ActivityContent( state: state, staleDate: now.addingTimeInterval(10 * 60) @@ -231,6 +298,7 @@ final class PlatformAgentAwarenessCoordinator { dismissalPolicy: .after(now.addingTimeInterval(5 * 60)) ) } + try Task.checkCancellation() notifyActivityChanged() return } @@ -241,12 +309,13 @@ final class PlatformAgentAwarenessCoordinator { await duplicate.end(nil, dismissalPolicy: .immediate) } } else { - _ = try? Activity.request( + _ = try Activity.request( attributes: LiveActivityAttributes(), content: content, pushType: .token ) } + try Task.checkCancellation() notifyActivityChanged() } diff --git a/apps/swift-ios/App/Platform/PlatformCloudDelivery.swift b/apps/swift-ios/App/Platform/PlatformCloudDelivery.swift index a56e8051ef..9678f7a82a 100644 --- a/apps/swift-ios/App/Platform/PlatformCloudDelivery.swift +++ b/apps/swift-ios/App/Platform/PlatformCloudDelivery.swift @@ -150,7 +150,9 @@ final class PlatformCloudDeliveryCoordinator { guard !Task.isCancelled, let self else { return } if controller.account == nil { clearSuccessfulRegistrationCache() - endPrivateActivities() + pendingActivityTokens.removeAll() + PlatformAgentAwarenessCoordinator.shared + .resetAndResynchronizeLiveActivity() } refreshActivityTokenObservers() requestRegistration() @@ -323,15 +325,6 @@ final class PlatformCloudDeliveryCoordinator { defaults.removeObject(forKey: activityFingerprintKey) } - private func endPrivateActivities() { - pendingActivityTokens.removeAll() - Task { @MainActor in - for activity in Activity.activities { - await activity.end(nil, dismissalPolicy: .immediate) - } - } - } - private func currentRegistration(settings: FeatureSettings) -> T3ConnectDeviceRegistration { let version = Bundle.main.object( forInfoDictionaryKey: "CFBundleShortVersionString" diff --git a/apps/swift-ios/App/Platform/PlatformDeepLinks.swift b/apps/swift-ios/App/Platform/PlatformDeepLinks.swift index 69cb85a633..70caaade2b 100644 --- a/apps/swift-ios/App/Platform/PlatformDeepLinks.swift +++ b/apps/swift-ios/App/Platform/PlatformDeepLinks.swift @@ -105,15 +105,15 @@ enum PlatformDeepLinkParser { throw PlatformDeepLinkError.unsupportedURL } + guard let host = components.host?.lowercased(), trustedWebHosts.contains(host) else { + throw PlatformDeepLinkError.unsupportedURL + } + let segments = pathSegments(components.percentEncodedPath) if isConnectionRoute(segments: segments, query: query) { return try connectionRoute(url) } - guard let host = components.host?.lowercased(), trustedWebHosts.contains(host) else { - throw PlatformDeepLinkError.unsupportedURL - } - if let explicit = try? navigationRoute(segments: segments, query: query) { return explicit } diff --git a/apps/swift-ios/App/Platform/PlatformNotifications.swift b/apps/swift-ios/App/Platform/PlatformNotifications.swift index 6cf6fe5954..0ffd17f5e5 100644 --- a/apps/swift-ios/App/Platform/PlatformNotifications.swift +++ b/apps/swift-ios/App/Platform/PlatformNotifications.swift @@ -245,10 +245,6 @@ final class T3PlatformAppDelegate: NSObject, UIApplicationDelegate { ) -> Bool { PlatformBackgroundRefreshCoordinator.shared.register() PlatformNotificationService.shared.installDelegate() - if let payload = launchOptions?[.remoteNotification] as? [AnyHashable: Any], - let route = PlatformNotificationPayload.route(from: payload) { - PlatformRouteMailbox.shared.put(route) - } return true } @@ -271,16 +267,8 @@ final class T3PlatformAppDelegate: NSObject, UIApplicationDelegate { didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void ) { - guard let route = PlatformNotificationPayload.route(from: userInfo) else { - completionHandler(.noData) - return - } - PlatformRouteMailbox.shared.put(route) - NotificationCenter.default.post( - name: .platformRouteReceived, - object: nil, - userInfo: ["route": route] + completionHandler( + PlatformNotificationPayload.route(from: userInfo) == nil ? .noData : .newData ) - completionHandler(.newData) } } diff --git a/apps/swift-ios/Extensions/Share/SharePayloadLoader.swift b/apps/swift-ios/Extensions/Share/SharePayloadLoader.swift index 28ccb0c7e2..7c8b650e39 100644 --- a/apps/swift-ios/Extensions/Share/SharePayloadLoader.swift +++ b/apps/swift-ios/Extensions/Share/SharePayloadLoader.swift @@ -4,12 +4,15 @@ import UniformTypeIdentifiers struct T3LoadedSharePayload: Sendable { var textFragments: [String] var images: [T3PendingShareImage] + var warnings: [String] } enum T3SharePayloadLoader { static func load(from inputItems: [Any]) async -> T3LoadedSharePayload { var textFragments: [String] = [] var images: [T3PendingShareImage] = [] + var skippedOversizedImage = false + var skippedExcessImage = false for case let item as NSExtensionItem in inputItems { if let attributedText = item.attributedContentText?.string { @@ -17,19 +20,33 @@ enum T3SharePayloadLoader { } for provider in item.attachments ?? [] { - if images.count < T3IncomingShareStore.maximumImageCount, - let imageType = provider.registeredTypeIdentifiers.first(where: { - UTType($0)?.conforms(to: .image) == true - }), - let data = try? await loadData(from: provider, typeIdentifier: imageType) - { - images.append( - T3PendingShareImage( - data: data, - suggestedName: provider.suggestedName, + if let imageType = provider.registeredTypeIdentifiers.first(where: { + UTType($0)?.conforms(to: .image) == true + }) { + guard images.count < T3IncomingShareStore.maximumImageCount else { + skippedExcessImage = true + continue + } + do { + let staged = try await loadStagedImage( + from: provider, typeIdentifier: imageType ) - ) + images.append( + T3PendingShareImage( + stagedFileURL: staged.url, + byteCount: staged.byteCount, + suggestedName: provider.suggestedName, + typeIdentifier: imageType + ) + ) + } catch T3SharePayloadLoaderError.imageTooLarge { + skippedOversizedImage = true + } catch { + // An image provider is terminal even if it also vends a + // URL or text representation. Falling through would + // silently turn a rejected attachment into other input. + } continue } @@ -56,24 +73,86 @@ enum T3SharePayloadLoader { } } - return T3LoadedSharePayload(textFragments: textFragments, images: images) + var warnings: [String] = [] + if skippedOversizedImage { + warnings.append("One shared image exceeded the 10 MB attachment limit.") + } + if skippedExcessImage { + warnings.append( + "Only the first \(T3IncomingShareStore.maximumImageCount) shared images were attached." + ) + } + return T3LoadedSharePayload( + textFragments: textFragments, + images: images, + warnings: warnings + ) } - private static func loadData( + private static func loadStagedImage( from provider: NSItemProvider, typeIdentifier: String - ) async throws -> Data { + ) async throws -> (url: URL, byteCount: Int) { try await withCheckedThrowingContinuation { continuation in - provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, error in - if let data { - continuation.resume(returning: data) - } else { - continuation.resume(throwing: error ?? CocoaError(.fileReadUnknown)) + provider.loadFileRepresentation(forTypeIdentifier: typeIdentifier) { url, error in + do { + guard let url else { + throw error ?? CocoaError(.fileReadUnknown) + } + continuation.resume(returning: try stageImage(from: url)) + } catch { + continuation.resume(throwing: error) } } } } + /// The provider-owned URL expires when its callback returns. Stream it to + /// an extension-owned temporary file while enforcing the byte limit, so a + /// malicious or enormous provider never has to be materialized in memory. + private static func stageImage(from sourceURL: URL) throws -> (url: URL, byteCount: Int) { + let fileManager = FileManager.default + let stagingDirectory = fileManager.temporaryDirectory.appending( + path: "T3CodeShareStaging", + directoryHint: .isDirectory + ) + try fileManager.createDirectory( + at: stagingDirectory, + withIntermediateDirectories: true + ) + let stagedURL = stagingDirectory.appending( + path: UUID().uuidString.lowercased(), + directoryHint: .notDirectory + ) + guard fileManager.createFile(atPath: stagedURL.path, contents: nil) else { + throw CocoaError(.fileWriteUnknown) + } + + do { + let source = try FileHandle(forReadingFrom: sourceURL) + let destination = try FileHandle(forWritingTo: stagedURL) + defer { + try? source.close() + try? destination.close() + } + + var byteCount = 0 + while let chunk = try source.read(upToCount: 64 * 1_024), !chunk.isEmpty { + try Task.checkCancellation() + byteCount += chunk.count + guard byteCount <= T3IncomingShareStore.maximumImageBytes else { + throw T3SharePayloadLoaderError.imageTooLarge + } + try destination.write(contentsOf: chunk) + } + guard byteCount > 0 else { throw CocoaError(.fileReadCorruptFile) } + return (stagedURL, byteCount) + } catch { + try? fileManager.removeItem(at: stagedURL) + throw error + } + } + private static func loadItem( from provider: NSItemProvider, typeIdentifier: String @@ -109,3 +188,7 @@ enum T3SharePayloadLoader { return nil } } + +private enum T3SharePayloadLoaderError: Error { + case imageTooLarge +} diff --git a/apps/swift-ios/Extensions/Share/ShareViewController.swift b/apps/swift-ios/Extensions/Share/ShareViewController.swift index 149dfbb374..7d1d7a0389 100644 --- a/apps/swift-ios/Extensions/Share/ShareViewController.swift +++ b/apps/swift-ios/Extensions/Share/ShareViewController.swift @@ -15,7 +15,8 @@ final class T3ShareViewController: UIViewController { return try await Task.detached { try T3IncomingShareStore.write( textFragments: payload.textFragments, - images: payload.images + images: payload.images, + warnings: payload.warnings ) }.value }, diff --git a/apps/swift-ios/Extensions/Shared/ShareInbox.swift b/apps/swift-ios/Extensions/Shared/ShareInbox.swift index af6b51dc85..4b14aafe49 100644 --- a/apps/swift-ios/Extensions/Shared/ShareInbox.swift +++ b/apps/swift-ios/Extensions/Shared/ShareInbox.swift @@ -20,7 +20,8 @@ struct T3IncomingShareEnvelope: Codable, Hashable, Identifiable, Sendable { } struct T3PendingShareImage: Sendable { - var data: Data + var stagedFileURL: URL + var byteCount: Int var suggestedName: String? var typeIdentifier: String } @@ -50,19 +51,26 @@ enum T3IncomingShareStore { static func write( textFragments: [String], images: [T3PendingShareImage], + warnings initialWarnings: [String] = [], now: Date = Date(), id: String = UUID().uuidString.lowercased() ) throws -> T3IncomingShareEnvelope { guard let containerURL = T3SharedContainer.rootURL else { throw T3IncomingShareStoreError.appGroupUnavailable } + defer { + for image in images { + try? FileManager.default.removeItem(at: image.stagedFileURL) + } + } let normalizedText = deduplicatedText(textFragments) let itemDirectory = containerURL .appending(path: inboxRelativePath, directoryHint: .isDirectory) .appending(path: id, directoryHint: .isDirectory) - var warnings: [String] = [] + var warnings = initialWarnings var savedImages: [T3IncomingShareImage] = [] + var validOverflowCount = 0 do { try FileManager.default.createDirectory( @@ -70,32 +78,44 @@ enum T3IncomingShareStore { withIntermediateDirectories: true ) - for (index, image) in images.prefix(maximumImageCount).enumerated() { - guard !image.data.isEmpty, image.data.count <= maximumImageBytes else { + for image in images { + let values = try? image.stagedFileURL.resourceValues(forKeys: [ + .fileSizeKey, + .isRegularFileKey, + ]) + guard values?.isRegularFile == true, + let byteCount = values?.fileSize, + byteCount > 0, + byteCount <= maximumImageBytes, + byteCount == image.byteCount else { warnings.append("One shared image exceeded the 10 MB attachment limit.") continue } + guard savedImages.count < maximumImageCount else { + validOverflowCount += 1 + continue + } let attachmentID = UUID().uuidString.lowercased() let fileName = safeFileName( image.suggestedName, - fallback: "shared-image-\(index + 1).\(fileExtension(for: image.typeIdentifier))" + fallback: "shared-image-\(savedImages.count + 1).\(fileExtension(for: image.typeIdentifier))" ) let storedName = "\(attachmentID)-\(fileName)" let fileURL = itemDirectory.appending(path: storedName, directoryHint: .notDirectory) - try image.data.write(to: fileURL, options: .atomic) + try FileManager.default.copyItem(at: image.stagedFileURL, to: fileURL) savedImages.append( T3IncomingShareImage( id: attachmentID, fileName: fileName, typeIdentifier: image.typeIdentifier, relativePath: "\(inboxRelativePath)/\(id)/\(storedName)", - byteCount: image.data.count + byteCount: byteCount ) ) } - if images.count > maximumImageCount { + if validOverflowCount > 0 { warnings.append("Only the first \(maximumImageCount) shared images were attached.") } diff --git a/apps/swift-ios/Features/Settings/SettingsView.swift b/apps/swift-ios/Features/Settings/SettingsView.swift index 2d356bd76d..d4eedf96ca 100644 --- a/apps/swift-ios/Features/Settings/SettingsView.swift +++ b/apps/swift-ios/Features/Settings/SettingsView.swift @@ -310,19 +310,6 @@ public struct SettingsView: View { private func save() { isSaving = true Task { - if settings.notificationsEnabled, - !model.snapshot.settings.notificationsEnabled - { - let authorized = await PlatformNotificationService.shared.requestAuthorization() - if !authorized { - settings.notificationsEnabled = false - model.errorMessage = "Notifications are disabled in iOS Settings." - } - } else if !settings.notificationsEnabled, - model.snapshot.settings.notificationsEnabled - { - _ = await PlatformNotificationService.shared.synchronize(enabled: false) - } await model.saveSettings(settings) isSaving = false if model.snapshot.settings == settings { diff --git a/apps/swift-ios/README.md b/apps/swift-ios/README.md index bd921f8703..510cee96f8 100644 --- a/apps/swift-ios/README.md +++ b/apps/swift-ios/README.md @@ -97,7 +97,9 @@ entry point without duplicating the simulator-selection or signing policy. ## Install on a physical device Enable Developer Mode on the device, connect and trust the Mac, then find its -identifier with `xcrun devicectl list devices`. Xcode must be signed into an Apple +CoreDevice identifier or hardware UDID with +`xcrun devicectl list devices --columns UDID`. The script resolves either form to +the destination UDID expected by Xcode. Xcode must be signed into an Apple Developer account for the requested team. ```sh @@ -108,9 +110,11 @@ T3_SWIFT_DEVELOPMENT_TEAM="TEAMID1234" \ The script builds, provisions, installs, and launches the app. It accepts the T3 Connect build settings above as environment variables. Optional overrides are -`T3_SWIFT_BUNDLE_IDENTIFIER`, `T3_SWIFT_CONFIGURATION`, -`T3_SWIFT_DERIVED_DATA_PATH`, `T3_SWIFT_VERSION`, and -`T3_SWIFT_BUILD_NUMBER`. +`T3_SWIFT_CONFIGURATION`, `T3_SWIFT_DERIVED_DATA_PATH`, `T3_SWIFT_VERSION`, and +`T3_SWIFT_BUILD_NUMBER`. The app and extension bundle identifiers stay fixed so +automatic signing provisions their shared App Group consistently. Run with +`T3_SWIFT_VERIFY_BUNDLE_IDENTIFIERS_ONLY=1` to verify those settings without a +device build. ## Release checklist diff --git a/apps/swift-ios/Scripts/ci-test.sh b/apps/swift-ios/Scripts/ci-test.sh index dcc69cb476..c4422897d8 100755 --- a/apps/swift-ios/Scripts/ci-test.sh +++ b/apps/swift-ios/Scripts/ci-test.sh @@ -26,7 +26,19 @@ if [[ -z "${SIMULATOR_ID}" ]]; then # the newest installed iOS runtime without coupling CI to a device model. SIMULATOR_ID="$( xcrun simctl list devices available \ - | awk -F '[()]' '/^[[:space:]]+iPhone/ { candidate=$2 } END { print candidate }' + | awk ' + /^[[:space:]]+iPhone/ { + line = $0 + while (match(line, /\([[:xdigit:]-]+\)/)) { + value = substr(line, RSTART + 1, RLENGTH - 2) + if (value ~ /^[[:xdigit:]]{8}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{12}$/) { + candidate = value + } + line = substr(line, RSTART + RLENGTH) + } + } + END { print candidate } + ' )" fi diff --git a/apps/swift-ios/Scripts/install-device.sh b/apps/swift-ios/Scripts/install-device.sh index d2f8b2c12f..2f3c388387 100755 --- a/apps/swift-ios/Scripts/install-device.sh +++ b/apps/swift-ios/Scripts/install-device.sh @@ -7,7 +7,9 @@ APP_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" DEVICE_ID="${T3_SWIFT_DEVICE_ID:-${1:-}}" DEVELOPMENT_TEAM="${T3_SWIFT_DEVELOPMENT_TEAM:-${2:-}}" CONFIGURATION="${T3_SWIFT_CONFIGURATION:-Debug}" -BUNDLE_IDENTIFIER="${T3_SWIFT_BUNDLE_IDENTIFIER:-com.t3tools.t3code.swiftui}" +BUNDLE_IDENTIFIER="com.t3tools.t3code.swiftui" +WIDGET_BUNDLE_IDENTIFIER="${BUNDLE_IDENTIFIER}.widgets" +SHARE_BUNDLE_IDENTIFIER="${BUNDLE_IDENTIFIER}.sharing" DERIVED_DATA_PATH="${T3_SWIFT_DERIVED_DATA_PATH:-${APP_DIR}/.derivedData/device}" die() { @@ -19,11 +21,46 @@ require_cmd() { command -v "$1" >/dev/null 2>&1 || die "missing required command: $1" } +require_cmd awk +require_cmd mktemp +require_cmd plutil require_cmd xcodebuild require_cmd xcrun +[[ -z "${T3_SWIFT_BUNDLE_IDENTIFIER:-}" || "${T3_SWIFT_BUNDLE_IDENTIFIER}" == "${BUNDLE_IDENTIFIER}" ]] || die \ + "custom bundle identifiers are unsupported because this app and its extensions share a fixed App Group" + +bundle_identifier_for_target() { + local target="$1" + xcodebuild -showBuildSettings \ + -project "${APP_DIR}/T3Code.xcodeproj" \ + -target "${target}" \ + -configuration "${CONFIGURATION}" \ + | awk '$1 == "PRODUCT_BUNDLE_IDENTIFIER" && $2 == "=" { print $3; exit }' +} + +verify_bundle_identifiers() { + local host widgets share + host="$(bundle_identifier_for_target T3Code)" + widgets="$(bundle_identifier_for_target T3CodeWidgets)" + share="$(bundle_identifier_for_target T3CodeShare)" + [[ "${host}" == "${BUNDLE_IDENTIFIER}" ]] || die \ + "host bundle identifier resolved to '${host}'" + [[ "${widgets}" == "${WIDGET_BUNDLE_IDENTIFIER}" ]] || die \ + "widget bundle identifier resolved to '${widgets}'" + [[ "${share}" == "${SHARE_BUNDLE_IDENTIFIER}" ]] || die \ + "share bundle identifier resolved to '${share}'" + printf '[swift-ios-device] bundle identifiers: %s, %s, %s\n' \ + "${host}" "${widgets}" "${share}" +} + +if [[ "${T3_SWIFT_VERIFY_BUNDLE_IDENTIFIERS_ONLY:-0}" == "1" ]]; then + verify_bundle_identifiers + exit 0 +fi + [[ -n "${DEVICE_ID}" ]] || die \ - "set T3_SWIFT_DEVICE_ID to an identifier from 'xcrun devicectl list devices'" + "set T3_SWIFT_DEVICE_ID to a CoreDevice identifier or UDID from 'xcrun devicectl list devices --columns UDID'" [[ -n "${DEVELOPMENT_TEAM}" ]] || die \ "set T3_SWIFT_DEVELOPMENT_TEAM to your Apple Developer team ID" [[ "${CONFIGURATION}" == "Debug" || "${CONFIGURATION}" == "Release" ]] || die \ @@ -31,9 +68,15 @@ require_cmd xcrun build_settings=( "DEVELOPMENT_TEAM=${DEVELOPMENT_TEAM}" - "PRODUCT_BUNDLE_IDENTIFIER=${BUNDLE_IDENTIFIER}" ) +DEVICE_JSON="$(mktemp -t t3-swift-devices.XXXXXX)" +trap 'unlink "${DEVICE_JSON}" 2>/dev/null || true' EXIT +xcrun devicectl list devices --json-output "${DEVICE_JSON}" --quiet >/dev/null +DESTINATION_ID="$( + xcrun swift "${SCRIPT_DIR}/resolve-device-udid.swift" "${DEVICE_JSON}" "${DEVICE_ID}" +)" || die "could not resolve device '${DEVICE_ID}' to an Xcode destination UDID" + for key in \ T3CODE_CLERK_PUBLISHABLE_KEY \ T3CODE_CLERK_JWT_TEMPLATE \ @@ -51,12 +94,12 @@ if [[ -n "${T3_SWIFT_BUILD_NUMBER:-}" ]]; then build_settings+=("CURRENT_PROJECT_VERSION=${T3_SWIFT_BUILD_NUMBER}") fi -printf '[swift-ios-device] building %s for %s\n' "${BUNDLE_IDENTIFIER}" "${DEVICE_ID}" +printf '[swift-ios-device] building %s for %s\n' "${BUNDLE_IDENTIFIER}" "${DESTINATION_ID}" xcodebuild build \ -project "${APP_DIR}/T3Code.xcodeproj" \ -scheme T3Code \ -configuration "${CONFIGURATION}" \ - -destination "platform=iOS,id=${DEVICE_ID}" \ + -destination "platform=iOS,id=${DESTINATION_ID}" \ -derivedDataPath "${DERIVED_DATA_PATH}" \ -allowProvisioningUpdates \ "${build_settings[@]}" @@ -64,8 +107,24 @@ xcodebuild build \ APP_PATH="${DERIVED_DATA_PATH}/Build/Products/${CONFIGURATION}-iphoneos/T3Code.app" [[ -d "${APP_PATH}" ]] || die "built app was not found at ${APP_PATH}" +actual_host="$(plutil -extract CFBundleIdentifier raw -o - "${APP_PATH}/Info.plist")" +actual_widgets="$( + plutil -extract CFBundleIdentifier raw -o - \ + "${APP_PATH}/PlugIns/T3CodeWidgets.appex/Info.plist" +)" +actual_share="$( + plutil -extract CFBundleIdentifier raw -o - \ + "${APP_PATH}/PlugIns/T3CodeShare.appex/Info.plist" +)" +[[ "${actual_host}" == "${BUNDLE_IDENTIFIER}" ]] || die \ + "built host bundle identifier is '${actual_host}'" +[[ "${actual_widgets}" == "${WIDGET_BUNDLE_IDENTIFIER}" ]] || die \ + "built widget bundle identifier is '${actual_widgets}'" +[[ "${actual_share}" == "${SHARE_BUNDLE_IDENTIFIER}" ]] || die \ + "built share bundle identifier is '${actual_share}'" + printf '[swift-ios-device] installing %s\n' "${APP_PATH}" -xcrun devicectl device install app --device "${DEVICE_ID}" "${APP_PATH}" +xcrun devicectl device install app --device "${DESTINATION_ID}" "${APP_PATH}" printf '[swift-ios-device] launching %s\n' "${BUNDLE_IDENTIFIER}" -xcrun devicectl device process launch --device "${DEVICE_ID}" "${BUNDLE_IDENTIFIER}" +xcrun devicectl device process launch --device "${DESTINATION_ID}" "${BUNDLE_IDENTIFIER}" diff --git a/apps/swift-ios/Scripts/resolve-device-udid.swift b/apps/swift-ios/Scripts/resolve-device-udid.swift new file mode 100644 index 0000000000..308e17a87e --- /dev/null +++ b/apps/swift-ios/Scripts/resolve-device-udid.swift @@ -0,0 +1,43 @@ +import Foundation + +private struct DeviceList: Decodable { + struct Result: Decodable { + struct Device: Decodable { + struct HardwareProperties: Decodable { + let udid: String + } + + let identifier: String + let hardwareProperties: HardwareProperties + } + + let devices: [Device] + } + + let result: Result +} + +guard CommandLine.arguments.count == 3 else { + FileHandle.standardError.write(Data("usage: resolve-device-udid \n".utf8)) + exit(64) +} + +do { + let payload = try JSONDecoder().decode( + DeviceList.self, + from: Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[1])) + ) + let requested = CommandLine.arguments[2] + guard let device = payload.result.devices.first(where: { + $0.identifier.caseInsensitiveCompare(requested) == .orderedSame + || $0.hardwareProperties.udid.caseInsensitiveCompare(requested) == .orderedSame + }) else { + throw CocoaError(.fileNoSuchFile) + } + print(device.hardwareProperties.udid) +} catch { + FileHandle.standardError.write( + Data("Could not resolve that device identifier: \(error.localizedDescription)\n".utf8) + ) + exit(1) +} diff --git a/apps/swift-ios/Tests/CoreTests/T3ConnectDPoPTests.swift b/apps/swift-ios/Tests/CoreTests/T3ConnectDPoPTests.swift index 4c7450b4c8..b7afd77d14 100644 --- a/apps/swift-ios/Tests/CoreTests/T3ConnectDPoPTests.swift +++ b/apps/swift-ios/Tests/CoreTests/T3ConnectDPoPTests.swift @@ -88,7 +88,7 @@ final class T3ConnectDPoPTests: XCTestCase { return XCTFail("Expected available T3 Connect configuration") } XCTAssertEqual(configuration.clerkJWTTemplate, "relay-template") - XCTAssertEqual(configuration.relayHTTPURL.absoluteString, "https://relay.example/") + XCTAssertEqual(configuration.relayHTTPURL.absoluteString, "https://relay.example") } private func jsonObject(_ encoded: String) throws -> [String: Any] { diff --git a/apps/swift-ios/Tests/FeatureTests/T3ConnectNativeCapabilityTests.swift b/apps/swift-ios/Tests/FeatureTests/T3ConnectNativeCapabilityTests.swift index c8a8fd8944..d8dcd63e2a 100644 --- a/apps/swift-ios/Tests/FeatureTests/T3ConnectNativeCapabilityTests.swift +++ b/apps/swift-ios/Tests/FeatureTests/T3ConnectNativeCapabilityTests.swift @@ -154,6 +154,46 @@ final class T3ConnectNativeCapabilityTests: XCTestCase { } } + func testInjectedManagedRuntimeRequiresItsMatchingController() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("t3-connect-controller-mismatch-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: directory) } + let signer = try testSigner() + let transport = T3ConnectNativeHTTPTransport(descriptorEnvironmentID: "managed-1") + let runtimeController = T3ConnectController( + resolution: .unavailable(reason: "Authentication is injected by this test."), + transport: transport, + signer: signer + ) + let runtime = EnvironmentRuntime( + environmentStore: EnvironmentStore( + fileURL: directory.appendingPathComponent("environments.json") + ), + credentialStore: InMemoryCredentialStore(), + httpTransport: transport, + webSocketConnector: T3ConnectBlockingConnector(), + managedAuthorization: T3ConnectRuntimeAuthorization(controller: runtimeController) + ) + let client = NativeFeatureClient(runtime: runtime) + + XCTAssertEqual( + client.t3ConnectController.unavailableReason, + "This client runtime requires its matching T3 Connect controller." + ) + do { + try await client.connectT3Environment( + try await bootstrapCredential(signer: signer) + ) + XCTFail("A managed runtime accepted an unrelated controller") + } catch let error as T3ConnectRelayError { + guard case .invalidConfiguration = error else { + return XCTFail("Unexpected T3 Connect error: \(error)") + } + } + let requests = await transport.requests + XCTAssertTrue(requests.isEmpty) + } + private func testSigner() throws -> T3ConnectDPoPSigner { var scalar = Data(repeating: 0, count: 32) scalar[31] = 11 diff --git a/apps/swift-ios/Tests/PlatformTests/PlatformDeepLinkTests.swift b/apps/swift-ios/Tests/PlatformTests/PlatformDeepLinkTests.swift index 300bc9607f..0db247b710 100644 --- a/apps/swift-ios/Tests/PlatformTests/PlatformDeepLinkTests.swift +++ b/apps/swift-ios/Tests/PlatformTests/PlatformDeepLinkTests.swift @@ -54,6 +54,15 @@ struct PlatformDeepLinkTests { } } + @Test + func rejectsConnectionParametersFromUntrustedWebHosts() { + #expect(throws: PlatformDeepLinkError.unsupportedURL) { + try PlatformDeepLinkParser.parse( + "https://malicious.example/connect?endpoint=https%3A%2F%2Fattacker.example&token=x" + ) + } + } + @Test func routeURLsRoundTrip() throws { let routes: [PlatformRoute] = [