| 1 | import CryptoKit |
| 2 | import Foundation |
| 3 | import Observation |
| 4 | |
| 5 | /// Pairing a device with a team (equipo-v1.md, "Sign in a device"): ask for |
| 6 | /// a challenge, show its code, open the team in the browser, and poll the |
| 7 | /// exchange until the person approves this device there. |
| 8 | /// |
| 9 | /// One proof per challenge. Every poll resends it unchanged, nonce |
| 10 | /// included: the server keeps no idempotency record for exchange, answers |
| 11 | /// 409 while it waits, and returns the saved credential for the same nonce |
| 12 | /// if a success was lost on the way back. |
| 13 | @MainActor @Observable |
| 14 | public final class PairingModel { |
| 15 | public enum Step: Equatable, Sendable { |
| 16 | case enterTeam |
| 17 | case requesting |
| 18 | case waiting(code: String, verification: URL, expires: Date) |
| 19 | case approved(teamName: String) |
| 20 | case expired |
| 21 | case failed(String) |
| 22 | } |
| 23 | |
| 24 | public private(set) var step: Step = .enterTeam |
| 25 | public private(set) var account: DeviceAccount? |
| 26 | |
| 27 | private let accounts: DeviceAccounts |
| 28 | private let makeTransport: @Sendable (URL) -> EquipoTransport |
| 29 | private let sleep: @Sendable (Duration) async throws -> Void |
| 30 | private let now: @Sendable () -> Date |
| 31 | private var task: Task<Void, Never>? |
| 32 | private(set) var lifetime: SignInLifetime? |
| 33 | private var pendingAccount: DeviceAccount? |
| 34 | private var retiring: Set<Data> = [] |
| 35 | public private(set) var cleanup: Task<Void, Never>? |
| 36 | |
| 37 | /// The floor the API sets; the server enforces it too. |
| 38 | public static let minimumInterval: Duration = .seconds(5) |
| 39 | |
| 40 | public init(accounts: DeviceAccounts, |
| 41 | makeTransport: @escaping @Sendable (URL) -> EquipoTransport = { URLSessionTransport(origin: $0) }, |
| 42 | sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, |
| 43 | now: @escaping @Sendable () -> Date = { Date() }) { |
| 44 | self.accounts = accounts; self.makeTransport = makeTransport; self.sleep = sleep; self.now = now |
| 45 | } |
| 46 | |
| 47 | /// Turns what a person types into the team's origin: a host or a URL, |
| 48 | /// nothing after the host. https only, except plain http to this |
| 49 | /// machine's loopback address for a local Equipo (README, "Local startup"). |
| 50 | public static func origin(from typed: String) -> URL? { |
| 51 | var text = typed.trimmingCharacters(in: .whitespacesAndNewlines) |
| 52 | guard !text.isEmpty else { return nil } |
| 53 | if !text.contains("://") { text = "https://" + text } |
| 54 | guard let url = URL(string: text), let scheme = url.scheme?.lowercased(), let host = url.host?.lowercased(), !host.isEmpty, url.user == nil else { return nil } |
| 55 | guard scheme == "https" || (scheme == "http" && isLoopback(host)) else { return nil } |
| 56 | // The default port is the same place as none: the server's links leave it out. |
| 57 | let port = url.port == (scheme == "https" ? 443 : 80) ? nil : url.port |
| 58 | var c = URLComponents(); c.scheme = scheme; c.host = host; c.port = port |
| 59 | return c.url |
| 60 | } |
| 61 | static func isLoopback(_ host: String) -> Bool { host == "127.0.0.1" || host == "localhost" || host == "::1" } |
| 62 | |
| 63 | /// The browser page must belong to the team itself. |
| 64 | static func verificationIsTrusted(_ url: URL, origin: URL) -> Bool { |
| 65 | url.scheme == origin.scheme && url.host?.lowercased() == origin.host?.lowercased() && url.port == origin.port |
| 66 | } |
| 67 | |
| 68 | public func start(origin: URL, label: String) { |
| 69 | let lifetime = begin() |
| 70 | task = Task { await run(origin: origin, label: label, lifetime: lifetime) } |
| 71 | } |
| 72 | |
| 73 | private func begin() -> SignInLifetime { |
| 74 | cancel() |
| 75 | let lifetime = accounts.lifetimes.begin() |
| 76 | self.lifetime = lifetime |
| 77 | return lifetime |
| 78 | } |
| 79 | |
| 80 | /// Transfers this exact lifetime to the conversation without ending it. |
| 81 | func handoff() -> SignInLifetime? { |
| 82 | guard let lifetime, lifetime.isActive else { return nil } |
| 83 | self.lifetime = nil; pendingAccount = nil; task = nil |
| 84 | return lifetime |
| 85 | } |
| 86 | |
| 87 | public func cancel() { |
| 88 | if let lifetime { |
| 89 | if let pendingAccount { |
| 90 | try? accounts.commit(.remove(pendingAccount), lifetime: lifetime) |
| 91 | retire(pendingAccount) |
| 92 | } |
| 93 | lifetime.end() |
| 94 | } |
| 95 | task?.cancel(); task = nil; lifetime = nil |
| 96 | pendingAccount = nil; account = nil; step = .enterTeam |
| 97 | } |
| 98 | |
| 99 | func run(origin: URL, label: String) async { |
| 100 | await run(origin: origin, label: label, lifetime: begin()) |
| 101 | } |
| 102 | |
| 103 | private func run(origin: URL, label: String, lifetime: SignInLifetime) async { |
| 104 | guard lifetime.isActive else { return } |
| 105 | step = .requesting |
| 106 | var account = accounts.all().first { $0.origin == origin && $0.credential == nil } ?? .new(origin: origin, label: label) |
| 107 | pendingAccount = account |
| 108 | do { |
| 109 | try accounts.commit(.save(account), lifetime: lifetime) |
| 110 | let client = EquipoClient(transport: makeTransport(origin), token: nil) |
| 111 | let begin = try PendingWrite.json(["public_key": try account.publicKey(), "label": label]) |
| 112 | let challenge: DeviceChallenge = try await retrying(lifetime: lifetime) { try await client.beginDevice(begin) } |
| 113 | try lifetime.check() |
| 114 | guard let verification = URL(string: challenge.verificationUri), Self.verificationIsTrusted(verification, origin: origin) else { |
| 115 | throw PairingError.badChallenge |
| 116 | } |
| 117 | step = .waiting(code: challenge.userCode, verification: verification, expires: challenge.expiresAt) |
| 118 | let proof = try PendingWrite.json(DeviceProof.body(for: challenge, key: try account.signingKey(), nonce: DeviceProof.nonce())) |
| 119 | var interval = max(Self.minimumInterval, .seconds(challenge.pollIntervalSeconds)) |
| 120 | while lifetime.isActive && !Task.isCancelled { |
| 121 | if now() >= challenge.expiresAt { step = .expired; return } |
| 122 | try await sleep(interval) |
| 123 | try lifetime.check() |
| 124 | do { |
| 125 | // Decode a late minted credential before checking the |
| 126 | // lifetime so it can be revoked with its own bearer. |
| 127 | account.credential = try await client.exchangeDevice(proof) |
| 128 | guard lifetime.isActive else { retire(account); return } |
| 129 | do { try accounts.commit(.save(account), lifetime: lifetime) } |
| 130 | catch { retire(account); throw error } |
| 131 | pendingAccount = account |
| 132 | self.account = account |
| 133 | let transport = LifetimeTransport(inner: makeTransport(origin), lifetime: lifetime) |
| 134 | let me = try? await EquipoClient(transport: transport, token: account.credential?.token).me() |
| 135 | guard lifetime.isActive else { retire(account); return } |
| 136 | if let me { |
| 137 | account.teamName = me.teamName; account.address = me.person.address |
| 138 | try accounts.commit(.save(account), lifetime: lifetime) |
| 139 | pendingAccount = account |
| 140 | self.account = account |
| 141 | } |
| 142 | step = .approved(teamName: account.teamName ?? origin.host ?? "") |
| 143 | return |
| 144 | } catch let error as EquipoAPIError { |
| 145 | try lifetime.check() |
| 146 | switch error.code { |
| 147 | case "authorization_pending": continue |
| 148 | case "slow_down": interval += .seconds(5) |
| 149 | case "device_expired": step = .expired; return |
| 150 | default: |
| 151 | if error == .offline { continue } |
| 152 | throw error |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | } catch is CancellationError { |
| 157 | return |
| 158 | } catch let error as EquipoAPIError { |
| 159 | guard lifetime.isActive else { return } |
| 160 | step = .failed(Self.describe(error)) |
| 161 | } catch { |
| 162 | guard lifetime.isActive else { return } |
| 163 | step = .failed(String(localized: "pairing.failed", bundle: .module)) |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | private func retrying<T: Sendable>(lifetime: SignInLifetime, _ attempt: @Sendable () async throws -> T) async throws -> T { |
| 168 | var tries = 0 |
| 169 | while true { |
| 170 | try lifetime.check() |
| 171 | do { return try await attempt() } |
| 172 | catch EquipoAPIError.offline where tries < 2 { |
| 173 | try lifetime.check() |
| 174 | tries += 1; try await sleep(.seconds(2)) |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | private func retire(_ account: DeviceAccount) { |
| 180 | guard account.credential != nil, retiring.insert(account.keySeed).inserted else { return } |
| 181 | let transport = makeTransport(account.origin) |
| 182 | cleanup = Task { await DeviceRevocation.revoke(account, transport: transport) } |
| 183 | } |
| 184 | |
| 185 | static func describe(_ error: EquipoAPIError) -> String { |
| 186 | switch error { |
| 187 | case .offline: return String(localized: "pairing.offline", bundle: .module) |
| 188 | case .badOrigin: return String(localized: "pairing.bad_team", bundle: .module) |
| 189 | default: |
| 190 | if error.status == 404 { return String(localized: "pairing.not_equipo", bundle: .module) } |
| 191 | if error.code == "slow_down" { return String(localized: "pairing.slow_down", bundle: .module) } |
| 192 | return String(localized: "pairing.failed", bundle: .module) |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |