Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Authentication/AuthService.swift3// Description: Signing in (passkey, device linking) and out; session refresh.4import Foundation56public extension Data {7 init?(base64URL s: String) {8 var b = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")9 while b.count % 4 != 0 { b.append("=") }10 self.init(base64Encoded: b)11 }12 var base64URL: String { base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") }13}1415public struct PasskeyChallenge: Sendable {16 public let challengeID: String17 public let challenge: Data18 public let relyingParty: String19}2021/// Signing in and out. Two ways in, both ending with a session of this app's own, kept in the Keychain:22/// - a passkey, through AuthenticationServices (the app layer shows the system sheet and hands the assertion back);23/// - device linking: the app shows a code, a browser that is already signed in approves it.24public struct AuthService: Sendable {25 public let api: APIClient26 public init(api: APIClient) { self.api = api }2728 /// Checks the stored session against the cluster and refreshes the account's details and the CSRF token.29 @discardableResult30 public func refresh() async throws -> Account {31 guard var c = api.currentCredential else { throw APIError.unauthenticated }32 let s: WireSession = try await api.get("auth/session")33 guard s.authenticated, let u = s.user, let csrf = s.csrfToken else { api.noteUnauthenticated(); throw APIError.unauthenticated }34 c.csrfToken = csrf35 c.account = Account(id: u.id, email: u.email, displayName: u.displayName, role: u.role, isOwner: u.isOwner)36 try api.adopt(c)37 return c.account38 }3940 private func adopt(token: String, csrf: String, expiresAt: Date?) async throws -> Account {41 try api.adopt(Credential(serverURL: api.baseURL, sessionToken: token, csrfToken: csrf,42 account: Account(id: "", email: "", displayName: "", role: "listener", isOwner: false), expiresAt: expiresAt))43 do { return try await refresh() } catch { api.forgetCredential(); throw error }44 }4546 // MARK: Device linking4748 public func startDeviceLink() async throws -> WireDeviceStart {49 try await api.send("POST", "auth/device/start", json: ["deviceName": Host.current().localizedName ?? "Mac"], authenticated: false)50 }5152 /// One poll. Returns nil while the request is still waiting for approval.53 public func pollDeviceLink(_ start: WireDeviceStart) async throws -> Account? {54 let r: WireDevicePoll = try await api.send("POST", "auth/device/poll", json: ["deviceCode": start.deviceCode], authenticated: false)55 guard r.status == "approved", let token = r.sessionToken, let csrf = r.csrfToken else { return nil }56 return try await adopt(token: token, csrf: csrf, expiresAt: r.expiresAt)57 }5859 /// Polls until the request is approved, refused, expired or the task is cancelled.60 public func awaitDeviceLink(_ start: WireDeviceStart) async throws -> Account {61 let deadline = Date().addingTimeInterval(TimeInterval(start.expiresIn))62 while Date() < deadline {63 try Task.checkCancellation()64 do { if let account = try await pollDeviceLink(start) { return account } }65 catch APIError.offline { /* keep waiting: the network may come back before the code expires */ }66 try await Task.sleep(nanoseconds: UInt64(max(1, start.interval)) * 1_000_000_000)67 }68 throw APIError.http(status: 410, code: "expired", message: "The pairing request has expired")69 }7071 // MARK: Passkeys7273 public func passkeyChallenge() async throws -> PasskeyChallenge {74 struct R: Decodable { struct O: Decodable { var challenge: String; var rpId: String? }; var challengeId: String; var options: O }75 let r: R = try await api.send("POST", "auth/login/options", authenticated: false)76 guard let challenge = Data(base64URL: r.options.challenge) else { throw APIError.invalidResponse }77 return PasskeyChallenge(challengeID: r.challengeId, challenge: challenge, relyingParty: r.options.rpId ?? api.baseURL.host ?? "")78 }7980 /// Sends the assertion produced by the system. The cluster verifies it exactly as it does for a browser.81 public func passkeyVerify(_ ch: PasskeyChallenge, credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userHandle: Data?) async throws -> Account {82 var response: [String: Any] = ["clientDataJSON": clientDataJSON.base64URL, "authenticatorData": authenticatorData.base64URL, "signature": signature.base64URL]83 if let userHandle { response["userHandle"] = userHandle.base64URL }84 let assertion: [String: Any] = ["id": credentialID.base64URL, "rawId": credentialID.base64URL, "type": "public-key", "response": response,85 "clientExtensionResults": [String: Any](), "authenticatorAttachment": "platform"]86 let body = try JSONSerialization.data(withJSONObject: ["challengeId": ch.challengeID, "response": assertion])87 let (_, http) = try await api.exchange("POST", "auth/login/verify", body: body, authenticated: false)88 // The session arrives as a cookie; the app keeps the token itself (no shared cookie storage).89 let fields = http.allHeaderFields.reduce(into: [String: String]()) { $0[String(describing: $1.key)] = String(describing: $1.value) }90 guard let token = HTTPCookie.cookies(withResponseHeaderFields: fields, for: api.baseURL).first(where: { $0.name == APIClient.cookieName })?.value, !token.isEmpty91 else { throw APIError.invalidResponse }92 return try await adopt(token: token, csrf: "", expiresAt: Date().addingTimeInterval(30 * 86400))93 }9495 /// Ends the session on the cluster when it can be reached, and always forgets it locally. Downloaded files are untouched.96 public func signOut() async {97 let _: WireOK? = try? await api.send("POST", "auth/logout")98 api.forgetCredential()99 }100}101