Cotton code
87 lines · 4.8 KB · SwiftRaw
// Google's consent page in the system's sign-in sheet, not in Safari (Days CONTRACT §13: "ASWebAuthenticationSession// or Safari, never an embedded web view"). In Safari the person was left on the Worker's "You can close this page"// with Days behind; in the sheet, Google's answer comes back to Days by itself.//// Google sends the browser to the Worker's callback (`https://<server>/v1/google/callback?code&state`). Days holds// webcredentials for that host (`.entitlements/CottonDays.entitlements`, the host's apple-app-site-association), so// the sheet hands that address to Days instead of loading it, and Days asks it itself: the Worker spends the state,// trades the code and keeps the grant exactly as when the browser asked it. Nothing new on the Worker.//// Where the sheet cannot catch the address (a host whose association iOS has not fetched), the// Worker's page loads inside the sheet and connects as before; closing the sheet reads Google again either way.import AuthenticationServicesimport Foundationimport UIKit@MainActorfinal class DaysGoogleSignIn: NSObject, ASWebAuthenticationPresentationContextProviding {    /// How Google's page ended, as Days says it.    enum Ended: Equatable {        /// The Worker kept the grant; Days reads Google again and shows the account.        case connected        /// The Worker's own words for what went wrong ("Calendar access was not ticked on Google's page…").        case refused(String)        /// The sheet was closed before Google answered, or it loaded the Worker's page itself.        case closed    }    private var session: ASWebAuthenticationSession?    /// The callback the consent page names (`redirect_uri`), when it is an https address the sheet can catch.    nonisolated static func callback(of page: URL) -> (host: String, path: String)? {        guard let redirect = URLComponents(url: page, resolvingAgainstBaseURL: false)?                .queryItems?.first(where: { $0.name == "redirect_uri" })?.value,              let parts = URLComponents(string: redirect), parts.scheme == "https",              let host = parts.host, !host.isEmpty, !parts.path.isEmpty else { return nil }        return (host, parts.path)    }    /// Opens `page` in the sign-in sheet; nil when this phone or page cannot use the sheet (open it in Safari).    func open(_ page: URL) async -> Ended? {        guard let back = Self.callback(of: page) else { return nil }        let caught: URL? = await withCheckedContinuation { done in            let sheet = ASWebAuthenticationSession(url: page, callback: .https(host: back.host, path: back.path)) { url, _ in                done.resume(returning: url)            }            sheet.presentationContextProvider = self            session = sheet            if !sheet.start() { done.resume(returning: nil) }        }        session = nil        guard let caught else { return .closed }        return await Self.answer(caught)    }    /// Asks the Worker's callback as the browser would have, and reads its page: the title says whether it connected.    nonisolated static func answer(_ callback: URL) async -> Ended {        var ask = URLRequest(url: callback)        ask.httpShouldHandleCookies = false        ask.timeoutInterval = 30        guard let (body, _) = try? await URLSession(configuration: .ephemeral).data(for: ask),              let page = String(data: body, encoding: .utf8) else { return .closed }        return read(page)    }    /// The Worker's callback page (`apps/business/src/google.ts` `said`): `<title>` then one `<p>`.    nonisolated static func read(_ page: String) -> Ended {        func between(_ open: String, _ close: String) -> String? {            guard let a = page.range(of: open), let b = page.range(of: close, range: a.upperBound..<page.endIndex) else { return nil }            return String(page[a.upperBound..<b.lowerBound])        }        let title = between("<title>", "</title>").map(unescape) ?? ""        if title == "Google Calendar is connected" { return .connected }        let line = between("<p>", "</p>").map(unescape) ?? title        return line.isEmpty ? .closed : .refused(line)    }    nonisolated private static func unescape(_ s: String) -> String {        s.replacingOccurrences(of: "&lt;", with: "<").replacingOccurrences(of: "&gt;", with: ">")            .replacingOccurrences(of: "&quot;", with: "\"").replacingOccurrences(of: "&#39;", with: "'")            .replacingOccurrences(of: "&amp;", with: "&")    }    func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {        let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }        return scenes.flatMap(\.windows).first(where: \.isKeyWindow) ?? scenes.first.map { UIWindow(windowScene: $0) } ?? UIWindow()    }}