import CryptoKit import Foundation import Observation /// Pairing a device with a team (equipo-v1.md, "Sign in a device"): ask for /// a challenge, show its code, open the team in the browser, and poll the /// exchange until the person approves this device there. /// /// One proof per challenge. Every poll resends it unchanged, nonce /// included: the server keeps no idempotency record for exchange, answers /// 409 while it waits, and returns the saved credential for the same nonce /// if a success was lost on the way back. @MainActor @Observable public final class PairingModel { public enum Step: Equatable, Sendable { case enterTeam case requesting case waiting(code: String, verification: URL, expires: Date) case approved(teamName: String) case expired case failed(String) } public private(set) var step: Step = .enterTeam public private(set) var account: DeviceAccount? private let accounts: DeviceAccounts private let makeTransport: @Sendable (URL) -> EquipoTransport private let sleep: @Sendable (Duration) async throws -> Void private let now: @Sendable () -> Date private var task: Task? private(set) var lifetime: SignInLifetime? private var pendingAccount: DeviceAccount? private var retiring: Set = [] public private(set) var cleanup: Task? /// The floor the API sets; the server enforces it too. public static let minimumInterval: Duration = .seconds(5) public init(accounts: DeviceAccounts, makeTransport: @escaping @Sendable (URL) -> EquipoTransport = { URLSessionTransport(origin: $0) }, sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, now: @escaping @Sendable () -> Date = { Date() }) { self.accounts = accounts; self.makeTransport = makeTransport; self.sleep = sleep; self.now = now } /// Turns what a person types into the team's origin: a host or a URL, /// nothing after the host. https only, except plain http to this /// machine's loopback address for a local Equipo (README, "Local startup"). public static func origin(from typed: String) -> URL? { var text = typed.trimmingCharacters(in: .whitespacesAndNewlines) guard !text.isEmpty else { return nil } if !text.contains("://") { text = "https://" + text } guard let url = URL(string: text), let scheme = url.scheme?.lowercased(), let host = url.host?.lowercased(), !host.isEmpty, url.user == nil else { return nil } guard scheme == "https" || (scheme == "http" && isLoopback(host)) else { return nil } // The default port is the same place as none: the server's links leave it out. let port = url.port == (scheme == "https" ? 443 : 80) ? nil : url.port var c = URLComponents(); c.scheme = scheme; c.host = host; c.port = port return c.url } static func isLoopback(_ host: String) -> Bool { host == "127.0.0.1" || host == "localhost" || host == "::1" } /// The browser page must belong to the team itself. static func verificationIsTrusted(_ url: URL, origin: URL) -> Bool { url.scheme == origin.scheme && url.host?.lowercased() == origin.host?.lowercased() && url.port == origin.port } public func start(origin: URL, label: String) { let lifetime = begin() task = Task { await run(origin: origin, label: label, lifetime: lifetime) } } private func begin() -> SignInLifetime { cancel() let lifetime = accounts.lifetimes.begin() self.lifetime = lifetime return lifetime } /// Transfers this exact lifetime to the conversation without ending it. func handoff() -> SignInLifetime? { guard let lifetime, lifetime.isActive else { return nil } self.lifetime = nil; pendingAccount = nil; task = nil return lifetime } public func cancel() { if let lifetime { if let pendingAccount { try? accounts.commit(.remove(pendingAccount), lifetime: lifetime) retire(pendingAccount) } lifetime.end() } task?.cancel(); task = nil; lifetime = nil pendingAccount = nil; account = nil; step = .enterTeam } func run(origin: URL, label: String) async { await run(origin: origin, label: label, lifetime: begin()) } private func run(origin: URL, label: String, lifetime: SignInLifetime) async { guard lifetime.isActive else { return } step = .requesting var account = accounts.all().first { $0.origin == origin && $0.credential == nil } ?? .new(origin: origin, label: label) pendingAccount = account do { try accounts.commit(.save(account), lifetime: lifetime) let client = EquipoClient(transport: makeTransport(origin), token: nil) let begin = try PendingWrite.json(["public_key": try account.publicKey(), "label": label]) let challenge: DeviceChallenge = try await retrying(lifetime: lifetime) { try await client.beginDevice(begin) } try lifetime.check() guard let verification = URL(string: challenge.verificationUri), Self.verificationIsTrusted(verification, origin: origin) else { throw PairingError.badChallenge } step = .waiting(code: challenge.userCode, verification: verification, expires: challenge.expiresAt) let proof = try PendingWrite.json(DeviceProof.body(for: challenge, key: try account.signingKey(), nonce: DeviceProof.nonce())) var interval = max(Self.minimumInterval, .seconds(challenge.pollIntervalSeconds)) while lifetime.isActive && !Task.isCancelled { if now() >= challenge.expiresAt { step = .expired; return } try await sleep(interval) try lifetime.check() do { // Decode a late minted credential before checking the // lifetime so it can be revoked with its own bearer. account.credential = try await client.exchangeDevice(proof) guard lifetime.isActive else { retire(account); return } do { try accounts.commit(.save(account), lifetime: lifetime) } catch { retire(account); throw error } pendingAccount = account self.account = account let transport = LifetimeTransport(inner: makeTransport(origin), lifetime: lifetime) let me = try? await EquipoClient(transport: transport, token: account.credential?.token).me() guard lifetime.isActive else { retire(account); return } if let me { account.teamName = me.teamName; account.address = me.person.address try accounts.commit(.save(account), lifetime: lifetime) pendingAccount = account self.account = account } step = .approved(teamName: account.teamName ?? origin.host ?? "") return } catch let error as EquipoAPIError { try lifetime.check() switch error.code { case "authorization_pending": continue case "slow_down": interval += .seconds(5) case "device_expired": step = .expired; return default: if error == .offline { continue } throw error } } } } catch is CancellationError { return } catch let error as EquipoAPIError { guard lifetime.isActive else { return } step = .failed(Self.describe(error)) } catch { guard lifetime.isActive else { return } step = .failed(String(localized: "pairing.failed", bundle: .module)) } } private func retrying(lifetime: SignInLifetime, _ attempt: @Sendable () async throws -> T) async throws -> T { var tries = 0 while true { try lifetime.check() do { return try await attempt() } catch EquipoAPIError.offline where tries < 2 { try lifetime.check() tries += 1; try await sleep(.seconds(2)) } } } private func retire(_ account: DeviceAccount) { guard account.credential != nil, retiring.insert(account.keySeed).inserted else { return } let transport = makeTransport(account.origin) cleanup = Task { await DeviceRevocation.revoke(account, transport: transport) } } static func describe(_ error: EquipoAPIError) -> String { switch error { case .offline: return String(localized: "pairing.offline", bundle: .module) case .badOrigin: return String(localized: "pairing.bad_team", bundle: .module) default: if error.status == 404 { return String(localized: "pairing.not_equipo", bundle: .module) } if error.code == "slow_down" { return String(localized: "pairing.slow_down", bundle: .module) } return String(localized: "pairing.failed", bundle: .module) } } }