| 1 | import Combine |
| 2 | import CryptoKit |
| 3 | import Foundation |
| 4 | import Observation |
| 5 | import RastrilloApple |
| 6 | |
| 7 | /// The kit owns identity, team choice and session renewal. Equipo turns |
| 8 | /// that session into its existing device bearer and keeps it in DeviceAccounts. |
| 9 | @MainActor @Observable |
| 10 | public final class EquipoOficinaID { |
| 11 | public let model: OficinaIDModel |
| 12 | public private(set) var error: String? |
| 13 | public private(set) var busy = false |
| 14 | public private(set) var account: DeviceAccount? |
| 15 | public var suspended = false |
| 16 | @ObservationIgnored var onAccount: ((DeviceAccount, EquipoTransport, SignInLifetime) -> Void)? |
| 17 | @ObservationIgnored var onLeave: (() -> Void)? |
| 18 | @ObservationIgnored private var watch: AnyCancellable? |
| 19 | @ObservationIgnored private var registration: (state: OficinaSignedIn, lifetime: SignInLifetime, id: UUID, task: Task<Void, Never>)? |
| 20 | @ObservationIgnored public private(set) var cleanup: Task<Void, Never>? |
| 21 | @ObservationIgnored private var renewal: (id: UUID, task: Task<Void, Never>)? |
| 22 | private let accounts: DeviceAccounts |
| 23 | private let makeTransport: @Sendable (URL) -> EquipoTransport |
| 24 | private let label: () -> String |
| 25 | private let now: @Sendable () -> Date |
| 26 | private var started = false |
| 27 | private var lifetime: SignInLifetime? |
| 28 | private var selected: String? |
| 29 | private var lastRejection: Date? |
| 30 | private var identityID: String? |
| 31 | |
| 32 | nonisolated public static let configuration = OficinaIDConfiguration(app: "equipo", appName: "Equipo") |
| 33 | nonisolated public static var appGroup: String { |
| 34 | #if os(macOS) |
| 35 | "9U4A84C4WK.works.oficina" |
| 36 | #else |
| 37 | "group.works.oficina" |
| 38 | #endif |
| 39 | } |
| 40 | |
| 41 | public init(model: OficinaIDModel, accounts: DeviceAccounts, |
| 42 | makeTransport: @escaping @Sendable (URL) -> EquipoTransport, |
| 43 | now: @escaping @Sendable () -> Date = Date.init, label: @escaping () -> String) { |
| 44 | self.model = model; self.accounts = accounts; self.makeTransport = makeTransport |
| 45 | self.now = now; self.label = label |
| 46 | lifetime = accounts.lifetimes.current |
| 47 | watch = model.$step.sink { [weak self] step in |
| 48 | self?.stepChanged(step) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | public func start() async { |
| 53 | guard !started else { return } |
| 54 | started = true |
| 55 | if suspended { model.suspendStraightIn() } |
| 56 | let lifetime = accounts.lifetimes.current |
| 57 | await model.start() |
| 58 | guard lifetime.isActive else { return } |
| 59 | // Another app may have signed this identity out while Equipo was |
| 60 | // closed. A successful negative lookup removes its background bearer; |
| 61 | // an unreadable Keychain leaves it alone. |
| 62 | for saved in accounts.all() { |
| 63 | if let identity = saved.oficinaIdentity, (try? model.store.hasIdentity(identity)) == false { |
| 64 | try? accounts.commit(.remove(saved), lifetime: lifetime) |
| 65 | Task { await self.revoke(saved) } |
| 66 | } |
| 67 | } |
| 68 | await model.refreshTeams() |
| 69 | guard lifetime.isActive else { return } |
| 70 | await synchronize() |
| 71 | } |
| 72 | |
| 73 | private func stepChanged(_ step: OficinaIDModel.Step) { |
| 74 | // @Published delivers before step is set. Invalidate synchronously, |
| 75 | // then read the new step in a task. A late device answer cannot revive it. |
| 76 | let previousIdentity = identityID |
| 77 | identityID = model.identity?.id |
| 78 | if identityID == nil, previousIdentity != nil { forget() } |
| 79 | switch step { |
| 80 | case .signedIn(let state): |
| 81 | guard !suspended else { return } |
| 82 | let selection = state.identity.id + "|" + state.team.sqid + "|" + state.origin.absoluteString |
| 83 | if selected != nil && selected != selection || lifetime?.isActive != true || lifetime !== accounts.lifetimes.current { |
| 84 | onLeave?() |
| 85 | lifetime?.end() |
| 86 | registration?.task.cancel(); registration = nil |
| 87 | renewal?.task.cancel(); renewal = nil |
| 88 | lastRejection = nil; busy = false |
| 89 | lifetime = accounts.lifetimes.begin() |
| 90 | } |
| 91 | selected = selection |
| 92 | guard let lifetime else { return } |
| 93 | Task { [weak self] in |
| 94 | guard lifetime.isActive else { return } |
| 95 | await self?.synchronize() |
| 96 | } |
| 97 | case .loading, .unavailable: break // Keep the conversation over an outage. |
| 98 | default: |
| 99 | if selected != nil { |
| 100 | onLeave?() |
| 101 | lifetime?.end(); lifetime = nil; selected = nil |
| 102 | account = nil |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | /// Also called after model actions, so their callers can await the bridge. |
| 108 | public func synchronize() async { |
| 109 | guard !suspended, let lifetime, lifetime.isActive, case .signedIn(let state) = model.step else { return } |
| 110 | if let registration, registration.state == state, registration.lifetime === lifetime { |
| 111 | await registration.task.value; return |
| 112 | } |
| 113 | let id = UUID() |
| 114 | let waiting = Task { [weak self] in |
| 115 | guard let self else { return } |
| 116 | await self.register(state, lifetime: lifetime) |
| 117 | } |
| 118 | registration = (state, lifetime, id, waiting) |
| 119 | await waiting.value |
| 120 | if registration?.id == id { registration = nil } |
| 121 | } |
| 122 | |
| 123 | private func register(_ state: OficinaSignedIn, lifetime: SignInLifetime) async { |
| 124 | let hash = Self.hash(state.session.value) |
| 125 | if let saved = accounts.all().first(where: { |
| 126 | $0.origin == state.origin && $0.oficinaIdentity == state.identity.id && $0.oficinaTeam == state.team.sqid |
| 127 | && $0.oficinaSessionHash == hash && $0.isUsable(now: now()) |
| 128 | }) { |
| 129 | guard current(state, lifetime: lifetime) else { return } |
| 130 | install(saved, lifetime: lifetime) |
| 131 | return |
| 132 | } |
| 133 | busy = true; error = nil |
| 134 | defer { if self.lifetime === lifetime { busy = false } } |
| 135 | // Fresh Curve25519 signing key, exactly as pairing creates one. |
| 136 | var next = DeviceAccount.new(origin: state.origin, label: label()) |
| 137 | next.oficinaIdentity = state.identity.id |
| 138 | next.oficinaTeam = state.team.sqid |
| 139 | next.oficinaSessionHash = hash |
| 140 | next.teamName = state.team.name |
| 141 | let previous = accounts.all().first { $0.origin == state.origin } |
| 142 | do { |
| 143 | try lifetime.check() |
| 144 | let body = try EquipoJSON.encoder.encode(["public_key": try next.publicKey(), "label": next.label]) |
| 145 | let transport = makeTransport(state.origin) |
| 146 | next.credential = try await EquipoClient(transport: transport, token: nil).send( |
| 147 | APIRequest("POST", "/auth/devices/native", body: body, nativeSession: state.session)) |
| 148 | guard current(state, lifetime: lifetime) else { await revoke(next); return } |
| 149 | do { try accounts.commit(.save(next), lifetime: lifetime) } |
| 150 | catch { await revoke(next); throw error } |
| 151 | install(next, lifetime: lifetime) |
| 152 | if let previous, previous.credential?.id != next.credential?.id { |
| 153 | Task { await self.revoke(previous) } |
| 154 | } |
| 155 | } catch { |
| 156 | guard current(state, lifetime: lifetime) else { return } |
| 157 | self.error = String(localized: "oficina.device_failed", bundle: .module) |
| 158 | if let api = error as? EquipoAPIError, api.status == 401 || api.status == 403, |
| 159 | lastRejection.map({ now().timeIntervalSince($0) >= 60 }) ?? true { |
| 160 | lastRejection = now() |
| 161 | await model.refreshTeams(maxAge: 0) |
| 162 | guard current(state, lifetime: lifetime) else { return } |
| 163 | await model.sessionRejected() |
| 164 | // A new kit session gets a new registration. Never await our |
| 165 | // own in-flight registration when Home left the step unchanged. |
| 166 | if lifetime.isActive, model.step != .signedIn(state) { await synchronize() } |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | private func current(_ state: OficinaSignedIn, lifetime: SignInLifetime) -> Bool { |
| 172 | !suspended && lifetime.isActive && self.lifetime === lifetime && model.step == .signedIn(state) |
| 173 | } |
| 174 | |
| 175 | private func install(_ next: DeviceAccount, lifetime: SignInLifetime) { |
| 176 | guard lifetime.isActive else { return } |
| 177 | error = nil |
| 178 | guard account != next else { return } |
| 179 | account = next |
| 180 | let origin = next.origin, identity = next.oficinaIdentity, team = next.oficinaTeam |
| 181 | let transport = EquipoRenewingTransport(inner: makeTransport(origin), lifetime: lifetime, credential: { [weak self] in |
| 182 | guard let self, lifetime.isActive, self.lifetime === lifetime, !self.suspended, self.model.identity?.id == identity, |
| 183 | let current = self.account, current.origin == origin, current.oficinaTeam == team else { return nil } |
| 184 | return current.credential?.token |
| 185 | }, rejected: { [weak self] in |
| 186 | guard lifetime.isActive else { return } |
| 187 | await self?.rejected() |
| 188 | }) |
| 189 | onAccount?(next, transport, lifetime) |
| 190 | } |
| 191 | |
| 192 | public func renewIfNeeded() async { |
| 193 | guard !suspended, let lifetime, lifetime.isActive else { return } |
| 194 | if let renewal { await renewal.task.value; return } |
| 195 | let id = UUID() |
| 196 | let task = Task { |
| 197 | guard lifetime.isActive else { return } |
| 198 | if case .unavailable = model.step { await model.retry() } |
| 199 | else { await model.renewIfNeeded() } |
| 200 | guard lifetime.isActive else { return } |
| 201 | await synchronize() |
| 202 | } |
| 203 | renewal = (id, task) |
| 204 | await task.value |
| 205 | if renewal?.id == id { renewal = nil } |
| 206 | } |
| 207 | |
| 208 | /// Coalesced and limited to once a minute within the same sign-in. |
| 209 | func rejected() async { |
| 210 | guard !suspended, let lifetime, lifetime.isActive else { return } |
| 211 | if let renewal { await renewal.task.value; return } |
| 212 | if let lastRejection, now().timeIntervalSince(lastRejection) < 60 { return } |
| 213 | lastRejection = now() |
| 214 | let id = UUID() |
| 215 | let task = Task { |
| 216 | guard lifetime.isActive else { return } |
| 217 | await model.refreshTeams(maxAge: 0) |
| 218 | guard lifetime.isActive else { return } |
| 219 | if case .unavailable = model.step { await model.retry() } |
| 220 | else { await model.sessionRejected() } |
| 221 | guard lifetime.isActive else { return } |
| 222 | await synchronize() |
| 223 | } |
| 224 | renewal = (id, task) |
| 225 | await task.value |
| 226 | if renewal?.id == id { renewal = nil } |
| 227 | } |
| 228 | |
| 229 | /// Leave Equipo's native account locally before any network cleanup. |
| 230 | /// The kit may also reach this through Use another or another app's sign-out. |
| 231 | /// Saved native bearers can predate this bridge's first synchronization. |
| 232 | /// Remove all of them, while leaving pairing-made accounts alone. |
| 233 | private func forget() { |
| 234 | registration?.task.cancel(); registration = nil |
| 235 | renewal?.task.cancel(); renewal = nil |
| 236 | let removalLifetime = accounts.lifetimes.current |
| 237 | let old = accounts.all().filter { $0.oficinaIdentity != nil } |
| 238 | for account in old { try? accounts.commit(.remove(account), lifetime: removalLifetime) } |
| 239 | lifetime?.end(); lifetime = nil; selected = nil |
| 240 | busy = false |
| 241 | account = nil; error = nil; lastRejection = nil |
| 242 | onLeave?() |
| 243 | if !old.isEmpty { |
| 244 | let previousCleanup = cleanup |
| 245 | cleanup = Task { |
| 246 | await previousCleanup?.value |
| 247 | for account in old { await self.revoke(account) } |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | /// The app removes the conversation while this lifetime still owns its |
| 253 | /// persistence. Forget first; ending the token closes the write gate. |
| 254 | func sessionEnded(lifetime: SignInLifetime) { |
| 255 | guard self.lifetime === lifetime, lifetime.isActive else { return } |
| 256 | forget() |
| 257 | } |
| 258 | |
| 259 | public func signOut() { |
| 260 | identityID = nil |
| 261 | forget() |
| 262 | lifetime?.end(); lifetime = nil; selected = nil |
| 263 | model.signOut() |
| 264 | } |
| 265 | |
| 266 | public func pause() { |
| 267 | suspended = true |
| 268 | identityID = nil |
| 269 | forget() |
| 270 | lifetime?.end(); lifetime = nil; selected = nil |
| 271 | registration?.task.cancel(); registration = nil |
| 272 | renewal?.task.cancel(); renewal = nil |
| 273 | model.suspendStraightIn() |
| 274 | account = nil; busy = false; lastRejection = nil |
| 275 | } |
| 276 | |
| 277 | public func resume() async { |
| 278 | suspended = false |
| 279 | let lifetime = accounts.lifetimes.begin() |
| 280 | self.lifetime = lifetime |
| 281 | try? accounts.commit(.route("oficina"), lifetime: lifetime) |
| 282 | await model.resumeStraightIn() |
| 283 | guard lifetime.isActive else { return } |
| 284 | await synchronize() |
| 285 | } |
| 286 | |
| 287 | private func revoke(_ account: DeviceAccount) async { |
| 288 | await DeviceRevocation.revoke(account, transport: makeTransport(account.origin)) |
| 289 | } |
| 290 | |
| 291 | private static func hash(_ value: String) -> String { Base64URL.encode(Data(SHA256.hash(data: Data(value.utf8)))) } |
| 292 | } |
| 293 | |