import Foundation /// Authority for one sign-in, shared by every task it starts. Renewal keeps /// the same lifetime; sign-out, switching accounts and cancellation end it. @MainActor public final class SignInLifetime { public private(set) var isActive = true public func end() { isActive = false } func check() throws { guard isActive else { throw CancellationError() } } } /// One current sign-in across pairing and Oficina ID. A stale task cannot /// acquire a replacement token; only an explicit sign-in transition begins one. @MainActor public final class SignInLifetimes { public private(set) var current = SignInLifetime() @discardableResult public func begin() -> SignInLifetime { current.end() current = SignInLifetime() return current } func require(_ lifetime: SignInLifetime) throws { try lifetime.check() guard current === lifetime else { throw CancellationError() } } } /// Engine traffic is confined to its original lifetime, including clients /// retained by views, retries and push registration after the session leaves. struct LifetimeTransport: EquipoTransport { let inner: EquipoTransport let lifetime: SignInLifetime var origin: URL { inner.origin } func send(_ request: APIRequest) async throws -> APIResponse { try await lifetime.check() let response = try await inner.send(request) try await lifetime.check() return response } func lines(_ request: APIRequest) async throws -> AsyncThrowingStream { try await lifetime.check() let stream = try await inner.lines(request) try await lifetime.check() return AsyncThrowingStream { continuation in let task = Task { do { for try await line in stream { try await lifetime.check() continuation.yield(line) } continuation.finish() } catch { continuation.finish(throwing: error) } } continuation.onTermination = { _ in task.cancel() } } } } /// The only traffic allowed after a lifetime ends: best-effort revocation /// with the abandoned credential itself. Never consults a current bearer. enum DeviceRevocation { static func revoke(_ account: DeviceAccount, transport: EquipoTransport) async { let client = EquipoClient(transport: transport, token: account.credential?.token) if let id = account.credential?.id, let page = try? await client.devices(), let device = page.items.first(where: { $0.id == id }) { _ = try? await client.revokeDevice(id, EquipoClient.empty(ifMatch: device.revision)) } } }