import Foundation import CoreFoundation /// The page-facing API is window.iosapp.postMessage(action, JSON.stringify(params)). enum ActivityBridgeScript { static let handlerName = "iosapp" static let source = source(privacyURL: nil) static func source(privacyURL: URL?) -> String { let value = try! JSONSerialization.data(withJSONObject: privacyURL?.absoluteString ?? "", options: [.fragmentsAllowed]) let encoded = String(decoding: value, as: UTF8.self) return """ (() => { const bridge = Object.freeze({ privacyURL: \(encoded), postMessage(action, params) { window.webkit.messageHandlers.iosapp.postMessage({action, params: params ?? '{}'}); } }); Object.defineProperty(window, 'iosapp', {value: bridge, configurable: true}); })(); """ } } enum ActivityBridgeCommand: Equatable { case close(SurveySubmission?) case openWindow(URL) case facebook(FacebookEvent) enum DecodeError: String, Error { case invalidMessage, missingAction, missingParams, oversizedParams, invalidJSON case invalidURL, unsupportedAction, invalidValue, invalidCurrency } static func parse(_ body: Any) -> Self? { try? decode(body) } static func decode(_ body: Any) throws -> Self { guard let message = body as? [String: Any] else { throw DecodeError.invalidMessage } guard let action = message["action"] as? String else { throw DecodeError.missingAction } let params: [String: Any] if let json = message["params"] as? String { guard json.utf8.count <= 16_384 else { throw DecodeError.oversizedParams } guard let data = json.data(using: .utf8), let decoded = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw DecodeError.invalidJSON } params = decoded } else if let object = message["params"] as? [String: Any] { params = object } else { throw DecodeError.missingParams } if action == "close" { if let submitted = params["submitted"] { guard let flag = submitted as? NSNumber, CFGetTypeID(flag) == CFBooleanGetTypeID() else { throw DecodeError.invalidMessage } } if params["submitted"] as? Bool == true { guard let answers = params["answers"] as? [NSNumber], answers.count == 4, answers.allSatisfy({ CFGetTypeID($0) != CFBooleanGetTypeID() && [1.0, 2.0].contains($0.doubleValue) }), let feedback = params["feedback"] as? String, feedback.count <= 2000 else { throw DecodeError.invalidMessage } return .close(SurveySubmission(answers: answers.map(\.intValue), feedback: feedback)) } return .close(nil) } if action == "openWindow" { guard let raw = params["url"] as? String, let url = ActivityURL.parse(raw) else { throw DecodeError.invalidURL } return .openWindow(url) } do { let event = try FacebookEvent(action: action, params: params) return .facebook(event) } catch FacebookEvent.ValidationError.unsupportedAction { throw DecodeError.unsupportedAction } catch FacebookEvent.ValidationError.invalidCurrency { throw DecodeError.invalidCurrency } catch { throw DecodeError.invalidValue } } } @MainActor final class ActivityBridge { enum Result: Equatable { case ignored, closed, externalURLRequested, facebook(FacebookTracking.LogResult) } private let pageURL: URL private let close: (SurveySubmission?) -> Void private let openExternalURL: (URL) -> Void private let tracking: FacebookTracking init(pageURL: URL, tracking: FacebookTracking, close: @escaping (SurveySubmission?) -> Void = { _ in }, openExternalURL: @escaping (URL) -> Void) { self.pageURL = pageURL; self.tracking = tracking; self.openExternalURL = openExternalURL self.close = close } @discardableResult func receive(_ body: Any, from sourceURL: URL?, isMainFrame: Bool) -> Result { guard isMainFrame, let sourceURL, Self.sameOrigin(pageURL, sourceURL), let command = ActivityBridgeCommand.parse(body) else { return .ignored } switch command { case .close(let submission): close(submission) return .closed case .openWindow(let url): openExternalURL(url) return .externalURLRequested case .facebook(let event): let result = tracking.logFBEvent(action: event.action.rawValue, params: event.parameters) return .facebook(result) } } private static func sameOrigin(_ lhs: URL, _ rhs: URL) -> Bool { func port(_ url: URL) -> Int { url.port ?? (url.scheme?.lowercased() == "https" ? 443 : 80) } return lhs.scheme?.lowercased() == rhs.scheme?.lowercased() && lhs.host?.lowercased() == rhs.host?.lowercased() && port(lhs) == port(rhs) } }