oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2
3/// Authority for one sign-in, shared by every task it starts. Renewal keeps
4/// the same lifetime; sign-out, switching accounts and cancellation end it.
5@MainActor public final class SignInLifetime {
6 public private(set) var isActive = true
7 public func end() { isActive = false }
8 func check() throws { guard isActive else { throw CancellationError() } }
9}
10
11/// One current sign-in across pairing and Oficina ID. A stale task cannot
12/// acquire a replacement token; only an explicit sign-in transition begins one.
13@MainActor public final class SignInLifetimes {
14 public private(set) var current = SignInLifetime()
15 @discardableResult public func begin() -> SignInLifetime {
16 current.end()
17 current = SignInLifetime()
18 return current
19 }
20 func require(_ lifetime: SignInLifetime) throws {
21 try lifetime.check()
22 guard current === lifetime else { throw CancellationError() }
23 }
24}
25
26/// Engine traffic is confined to its original lifetime, including clients
27/// retained by views, retries and push registration after the session leaves.
28struct LifetimeTransport: EquipoTransport {
29 let inner: EquipoTransport
30 let lifetime: SignInLifetime
31 var origin: URL { inner.origin }
32 func send(_ request: APIRequest) async throws -> APIResponse {
33 try await lifetime.check()
34 let response = try await inner.send(request)
35 try await lifetime.check()
36 return response
37 }
38 func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> {
39 try await lifetime.check()
40 let stream = try await inner.lines(request)
41 try await lifetime.check()
42 return AsyncThrowingStream { continuation in
43 let task = Task {
44 do {
45 for try await line in stream {
46 try await lifetime.check()
47 continuation.yield(line)
48 }
49 continuation.finish()
50 } catch { continuation.finish(throwing: error) }
51 }
52 continuation.onTermination = { _ in task.cancel() }
53 }
54 }
55}
56
57/// The only traffic allowed after a lifetime ends: best-effort revocation
58/// with the abandoned credential itself. Never consults a current bearer.
59enum DeviceRevocation {
60 static func revoke(_ account: DeviceAccount, transport: EquipoTransport) async {
61 let client = EquipoClient(transport: transport, token: account.credential?.token)
62 if let id = account.credential?.id, let page = try? await client.devices(),
63 let device = page.items.first(where: { $0.id == id }) {
64 _ = try? await client.revokeDevice(id, EquipoClient.empty(ifMatch: device.revision))
65 }
66 }
67}
68