import Combine import Foundation import Observation import RastrilloApple /// Base's session on this device: Oficina ID through the kit, and once /// signed in, the client, the member, Home and Ask. /// /// - Oficina ID is the kit's `OficinaIDModel` (app "base"): straight in /// when another Oficina app holds the ID, the kit's onboarding otherwise. /// `OficinaApp.base` arrives with the kit's next pin; until then the /// onboarding draws in the kit's default appearance. /// - The client keeps one transport for the whole session and swaps the /// kit's session under it when the kit mints a new one (a 401's /// `sessionRejected()`, a stale one renewed on foreground), so Ask's /// stream and writes never hold an ended cookie. /// - Coming forward: `renewIfNeeded()`, then Home and Ask read afresh and /// Ask listens again (Task 12 adds renewing Ask's own key first). @MainActor @Observable public final class BaseSession { public static let configuration = OficinaIDConfiguration(app: "base", appName: "Base") public static var appGroup: String { #if os(iOS) "group.works.oficina" #else "9U4A84C4WK.works.oficina" #endif } public let oficina: OficinaIDModel public private(set) var signedIn: OficinaSignedIn? public private(set) var client: BaseClient? public private(set) var ask: AskModel? public private(set) var me: Me? public private(set) var home: HomeData? @ObservationIgnored public private(set) var askSetup: AskSetup? @ObservationIgnored private var transport: SwappableTransport? @ObservationIgnored private var watching: AnyCancellable? /// Where the person's Disconnect is kept, per account. let defaults: UserDefaults public init(oficina: OficinaIDModel, defaults: UserDefaults = .standard) { self.oficina = oficina self.defaults = defaults watching = oficina.$step.sink { [weak self] step in Task { @MainActor in self?.stepChanged(step) } } } public static func live() -> BaseSession { BaseSession(oficina: .live(configuration: configuration, appGroup: appGroup)) } /// The kit moved: signed in (perhaps with a fresh session), or out. func stepChanged(_ step: OficinaIDModel.Step) { // Loading is the kit reading its store, not a sign-out. if step == .loading { return } guard case .signedIn(let state) = step else { if let left = account { end() forgetDisconnectIfGone(left.identity) } return } if let previous = account, previous.identity != state.identity.id { forgetDisconnectIfGone(previous.identity) } begin(identity: state.identity.id, origin: state.origin, transport: CapabilityTransport(state.client()), state: state) } /// Who the session is for: an identity at a Base. Anything that /// started for one account publishes nothing once the account changes. struct Account: Equatable { let identity: String; let origin: URL } @ObservationIgnored private(set) var account: Account? /// Bumped whenever the account changes or ends: work started under an /// older generation publishes nothing. @ObservationIgnored private(set) var generation = 0 @ObservationIgnored private(set) var refreshing: Task? /// Ask's set-up running on its own (a state or a write said reconnect): /// the session owns it, and cancels it on sign-out and in the background. @ObservationIgnored private(set) var settingUp: Task? func startSetup() { guard let askSetup, settingUp == nil else { return } settingUp = Task { [weak self] in _ = await askSetup.runIfNeeded() self?.settingUp = nil } } /// An Oficina ID assertion addressed to `audience` (Equipo): the kit's. @ObservationIgnored lazy var assertion: @MainActor (URL) async throws -> (assertion: String, verifier: String) = { [oficina] audience in try await oficina.assertion(for: audience) } /// Base refused the session: the kit mints a new one silently. @ObservationIgnored lazy var rejected: @MainActor () async -> Void = { [oficina] in await oficina.sessionRejected() } /// Signed in as `identity` at `origin`. The same account again (the kit /// renewed its session) swaps the session under the client; another /// account starts afresh, and nothing of the old one lands. func begin(identity: String, origin: URL, transport http: NativeTransport, state: OficinaSignedIn? = nil) { let next = Account(identity: identity, origin: origin) if let transport, account == next { transport.swap(http) signedIn = state return } end() let epoch = generation let swappable = SwappableTransport(http) // A 401 is only this account's to act on while it is still the one. let client = BaseClient(transport: swappable) { [weak self] in guard let self, await self.generation == epoch else { return } await self.rejected() } account = next transport = swappable self.client = client signedIn = state let ask = AskModel(client: client) let setup = AskSetup(client: client, ask: ask, assertion: { [weak self] equipo in guard let self, self.generation == epoch else { throw CancellationError() } return try await self.assertion(equipo) }, fallbackEquipo: { [weak self] in self?.me?.equipoOrigin }) setup.isCurrent = { [weak self] in self?.generation == epoch } // Both read and write the flag of the account this set-up belongs // to, and only while it is still the one signed in: a gone // account's set-up is held off and writes nothing. setup.heldOff = { [weak self, weak ask] in guard let self, self.generation == epoch else { return true } // Base's word wins, and the device's cache follows it. if let said = ask?.disconnected { if self.disconnected(next) != said { self.setDisconnected(said, for: next) } return said } return self.disconnected(next) } setup.onDisconnected = { [weak self] in guard let self, self.generation == epoch else { return } self.setDisconnected(true, for: next) } ask.onNeedsSetup = { [weak self] in guard let self, self.generation == epoch else { return } self.startSetup() } self.ask = ask askSetup = setup refreshing = Task { await self.refresh() } } /// Signed out, or about to be someone else: the old account's work is /// cancelled and anything still in flight lands on nothing. func end() { generation += 1 refreshing?.cancel() refreshing = nil settingUp?.cancel() settingUp = nil ask?.dispose() ask = nil; askSetup = nil; client = nil; transport = nil; account = nil signedIn = nil; me = nil; home = nil } /// Reads the member, Home and Ask afresh, for the account it started /// under only. public func refresh() async { guard let client else { return } let epoch = generation async let me = try? client.me() async let home = try? client.home() await ask?.resume() let (newMe, newHome) = await (me, home) guard generation == epoch, !Task.isCancelled else { return } if let newMe { self.me = newMe } if let newHome { self.home = newHome } // Ask set up (or renewed) with Oficina ID, if it wants it. await askSetup?.runIfNeeded() } /// Set it up (the person pressed the button): now, whatever the minute. public func setUpAsk() async { // The person's own: whatever set-up is in flight gives way to it. settingUp?.cancel() settingUp = nil askSetup?.invalidate() askDisconnected = false await askSetup?.runIfNeeded(force: true) } /// The app came forward. public func foreground() async { await oficina.renewIfNeeded() await refresh() } /// The app went away: Ask stops listening. public func background() { settingUp?.cancel() settingUp = nil ask?.pause() } /// The session's transport, for what loads from Base's origin (icons). public var iconTransport: NativeTransport? { transport } /// The member's Appearance: shown at once, kept on the web too. A /// failure puts the old one back. public func setAppearance(_ appearance: BaseAppearance) async { guard let client, var me else { return } let epoch = generation let before = me.appearance me.appearance = appearance self.me = me do { try await client.setAppearance(appearance) } catch { if generation == epoch { self.me?.appearance = before } } } /// The person disconnected Ask on this account (Settings' Disconnect). /// It sticks, across launches: no set-up runs by itself until they set /// Ask up again or sign in afresh. var askDisconnected: Bool { get { account.map(disconnected) ?? false } set { if let account { setDisconnected(newValue, for: account) } } } func disconnected(_ account: Account) -> Bool { defaults.bool(forKey: Self.disconnectedKey(account)) } func setDisconnected(_ value: Bool, for account: Account) { defaults.set(value, forKey: Self.disconnectedKey(account)) } static func disconnectedKey(_ account: Account) -> String { "askDisconnected:\(account.identity)@\(account.origin.absoluteString)" } /// The identity has left this device (a sign-out here, in another /// Oficina app, or Home ending its grant): its Disconnect goes for every /// team, so the next sign-in is a fresh one. A team switch or a /// relaunch keeps it: the identity is still here. func forgetDisconnectIfGone(_ identity: String) { guard (try? oficina.store.hasIdentity(identity)) != true else { return } let prefix = "askDisconnected:\(identity)@" for key in defaults.dictionaryRepresentation().keys where key.hasPrefix(prefix) { defaults.removeObject(forKey: key) } } /// Settings' Disconnect for Ask, then Ask as it is now. It stops any /// set-up running, and keeps one from running again by itself. public func disconnectAsk() async { guard let client else { return } let before = askDisconnected askDisconnected = true settingUp?.cancel() settingUp = nil askSetup?.invalidate() let epoch = generation do { try await client.disconnectAsk() } catch { // Nothing was disconnected (offline, a 502): as Base says, the // flag stays as it was, and renewal goes on. guard generation == epoch else { return } askDisconnected = before return } guard generation == epoch else { return } await ask?.load() } /// The teams this Oficina ID is in, for Switch team. /// /// The kit refreshes its cache when it's older than a minute; nil means /// it didn't (fresh already, a refresh already running, or a failure), /// never "no teams", so the cache for this identity is the answer then. /// Signed out or someone else meanwhile: none. public func teams() async -> [OficinaTeam] { guard let asked = account else { return [] } let fresh = await oficina.refreshTeams(maxAge: 60) guard account == asked else { return [] } return fresh ?? oficina.store.teams(asked.identity)?.teams ?? [] } /// Switch team: the kit opens the other team's Base. public func switchTo(_ team: OficinaTeam) async { await oficina.choose(team) } /// Sign out (confirmed by the caller): the kit's sign-out of this /// Oficina ID, everywhere on this device. public func signOut() { // The kit's step change clears Disconnect for every team of the // identity (forgetDisconnectIfGone), whoever signed it out. oficina.signOut() } } /// A transport whose session can be replaced under the requests that use /// it: each request goes to whichever `NativeHTTP` is current when it starts. final class SwappableTransport: NativeTransport, @unchecked Sendable { private let lock = NSLock() private var inner: NativeTransport init(_ inner: NativeTransport) { self.inner = inner } func swap(_ next: NativeTransport) { lock.withLock { inner = next } } private var current: NativeTransport { lock.withLock { inner } } var origin: URL { current.origin } func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { try await current.responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes) } func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { try await current.stream(path, onOpen: onOpen, onLine: onLine) } func download(_ path: String, to destination: URL) async throws { try await current.download(path, to: destination) } } /// Says what this app draws on its Ask reads, `/ask/state` and /// `/ask/events` (docs/api/base-native-v1.md, "What the app can draw"): /// `client_caps=lookup_answers`, a query parameter, since the kit's /// NativeHTTP sets no header of its own. Base counts it as /// `Base-Client-Capabilities`. Every other request goes as it is. final class CapabilityTransport: NativeTransport, @unchecked Sendable { /// What this build draws, comma-separated. static let capabilities = "lookup_answers" private let inner: NativeTransport init(_ inner: NativeTransport) { self.inner = inner } /// path with the capabilities added, if it is one of Ask's reads. static func path(_ path: String) -> String { let bare = path.split(separator: "?", maxSplits: 1).first.map(String.init) ?? path guard bare == "/ask/state" || bare == "/ask/events" else { return path } return path + (path.contains("?") ? "&" : "?") + "client_caps=" + capabilities } var origin: URL { inner.origin } func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { try await inner.responseDetails(method == "GET" ? Self.path(path) : path, method: method, body: body, contentType: contentType, maxBytes: maxBytes) } func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { try await inner.stream(Self.path(path), onOpen: onOpen, onLine: onLine) } func download(_ path: String, to destination: URL) async throws { try await inner.download(path, to: destination) } }