import Combine import Foundation import RastrilloApple /// How Docs signs in, as the person last chose it. Oficina ID is the primary /// way (spec 2026-11-14-oficina-id-native §9, slice A); "Other ways to sign /// in…" keeps the server address and browser approval for self-hosted /// servers and local accounts (§11). public enum DocsSignInRoute: String, Sendable { case oficinaID = "oficina-id" case server /// The `UserDefaults` key the choice is kept under. public static let key = "docs.signin.route" /// The route to show. Nothing chosen yet means Oficina ID, except for /// someone already signed in the old way: their per-app sessions keep /// working until an Oficina ID replaces them (spec Appendix C). An /// Oficina ID sign-in chooses `.oficinaID` for good. On `.server` the /// app suspends the kit's straight in (spec §9, rule 0). public static func resolve(stored: String, hasServerAccounts: Bool) -> DocsSignInRoute { if let chosen = DocsSignInRoute(rawValue: stored) { return chosen } return hasServerAccounts ? .server : .oficinaID } } /// Docs' half of Oficina ID: the kit's model, and the team sessions it mints /// turned into the transports Docs' workspaces use. /// /// A workspace is keyed by `(identity, team)`, never by a session: a session /// is re-minted after 24 hours and on a 401, and the workspace, its offline /// store and its outbox must carry on through that. So the transport is a /// supplier that reads the latest session for its account on every request. /// /// Nothing here is read-then-written from a view's body or init (Docs /// 0.1.7/0.1.8 hung at launch that way, 84d1008): `mounted`, `sessions` and /// `signIns` change only from the model's step publisher, and `start`, /// `routeChanged` and `useAnother` run from a `.task`, an `.onChange` or a /// button. @MainActor public final class DocsOficinaSession: ObservableObject { public let model: OficinaIDModel private var sessions: [String: (session: NativeSession, client: NativeHTTP)] = [:] private var lastRejection: [String: Date] = [:] private var lastRefusal: Date? /// A re-mint in flight (a day-old session's, or a refused one's): never /// two at once, and a refusal that lands meanwhile waits for it. private var renewal: Task? private var started = false private var watch: AnyCancellable? private let now: () -> Date nonisolated public static let configuration = OficinaIDConfiguration(app: "docs", appName: "Docs") /// The team the workspace shows. It is the signed-in team, and it stays /// while Oficina ID cannot mint that team a new session (spec §11): a /// 401 with Home unreachable must not unmount an open editor. Docs then /// shows the "Can't reach Oficina ID" line over the workspace instead. /// nil once the identity signs out, or the model moves to another team's /// question (not on it, choose, …). @Published public private(set) var mounted: OficinaSignedIn? /// Counts sign-ins a person made here: an identity chosen, a code or /// passkey, a team picked, a retry. Going straight in at launch (the /// last team, or the one Oficina ID on the device) is not one, so it /// never changes Docs' sign-in route. @Published public private(set) var signIns = 0 /// "Teams": the workspace's button for Docs' team picker. public static var teamsTitle: String { NSLocalizedString("native.oficinaid.teams", bundle: DocsResources.bundle, comment: "") } /// The App Group that holds the identity order and last-used team: team /// prefixed on the Mac, where it needs no profile, and the registered /// `group.works.oficina` on iOS (rastrillo/native APPLE.md). nonisolated public static var appGroup: String { #if os(macOS) "9U4A84C4WK.works.oficina" #else "group.works.oficina" #endif } /// The real wiring: the shared keychain group, Docs' own group, the App /// Group, Home over HTTPS and the platform's passkey sheet. public static func live() -> DocsOficinaSession { DocsOficinaSession(model: .live(configuration: configuration, appGroup: appGroup)) } public init(model: OficinaIDModel, now: @escaping () -> Date = Date.init) { self.model = model self.now = now watch = model.$step.sink { [weak self] step in self?.stepChanged(step) } } /// Reads the store once per launch, however many windows ask, then /// refreshes the team list (spec §9: at launch). With one Oficina ID on /// the device the kit goes straight in (Paul, 2026-11-19). `serverRoute` /// is Docs' own sign-in being the route: nothing goes straight in then /// (rule 0). public func start(serverRoute: Bool = false) async { guard !started else { return } started = true if serverRoute { model.suspendStraightIn() } await model.start() await model.refreshTeams() } /// The route changed, by the person or by itself (the last server /// account signed out, say): straight in is suspended exactly while /// Docs' own sign-in is the route, and resumes when it stops being /// (spec §9, rule 0). Signed in, neither disturbs the session. Call it /// from `.onChange(of: route)`, never from a body. public func routeChanged(to route: DocsSignInRoute) async { switch route { case .server: model.suspendStraightIn() case .oficinaID: await model.resumeStraightIn() } } /// "Use another Oficina ID" from the account menu: only while signed in /// (over an outage the team stays mounted, but there is no dialog to /// ask with), and only when `canLeave` (no document window of the /// identity open). The kit then asks (`oficinaReplaceConfirmation`), and /// the window re-checks Docs' guards while it does. Returns whether it /// asked. @discardableResult public func useAnother(identity: String, canLeave: Bool) -> Bool { guard case .signedIn(let state) = model.step, state.identity.id == identity, canLeave else { return false } model.useAnother() return true } /// "Use another Oficina ID" as the account menu asks it: Docs' guards /// first, then the kit's confirmation. A document window of the /// identity open, or changes of any of its teams unsent, refuse it /// before anything is shown, so the confirmation is never put up only /// to be withdrawn, and can't be confirmed while the outbox is still /// being checked (#130, finding 1). `openDocuments` is asked again once /// that check is done. Returns why it was refused; nil once the kit asks /// (or nothing can be asked: not signed in to `identity`). public func requestUseAnother(identity: String, openDocuments: @MainActor () -> Bool) async -> DocsLeaveBlock? { if let block = await DocsLeaveBlock.check(identity: identity, openDocuments: openDocuments()) { return block } if openDocuments() { return .openDocuments } useAnother(identity: identity, canLeave: true) return nil } /// The team picker opened: refresh if the list is five minutes old. public func pickerOpened() async { await model.refreshTeams() } /// An instance answered 403: the person may have left the team, or been /// given another, so the list is fetched again, at most once a minute. func refused() async { if let last = lastRefusal, now().timeIntervalSince(last) < 60 { return } lastRefusal = now() await model.refreshTeams(maxAge: 0) } /// The team session in use, if the model has one. public var signedIn: OficinaSignedIn? { if case .signedIn(let state) = model.step { return state } return nil } /// The account Docs files an Oficina ID team under: its offline store, /// outbox and windows. Stable for the life of the identity on this /// device, whatever session the team holds. public static func accountID(_ state: OficinaSignedIn) -> String { accountID(identity: state.identity.id, team: state.team.sqid) } /// The team name a document window of `account` shows in its subtitle /// (spec D7): the signed-in team's, or another team of the same identity /// from the teams cache, read each time so a renamed team shows its new /// name. nil for a server account or a team this device has not seen. public func teamName(forAccount account: String) -> String? { guard let state = mounted ?? signedIn else { return nil } if Self.accountID(state) == account { return state.team.name } return model.store.teams(state.identity.id)?.teams .first { Self.accountID(identity: state.identity.id, team: $0.sqid) == account }?.name } /// Who "(you)" is in the Share panel for a window of `account`: the /// identity's label (an email, or the name the person gave it). nil for /// a server account. public func identityLabel(forAccount account: String) -> String? { guard let state = mounted ?? signedIn, DocsOficinaSession.account(account, belongsTo: state.identity.id) else { return nil } return state.identity.label } nonisolated public static func accountID(identity: String, team: String) -> String { prefix + component(identity) + "." + component(team) } nonisolated static let prefix = "oficina-id." /// An account ID names a directory and a keychain item, so each part is /// used as it is only when it is base64url-safe (as Home's identity IDs /// and sqids are). Anything else, a "." or "/" above all, is encoded, /// marked by a "~" no plain part can contain. nonisolated static func component(_ text: String) -> String { let plain = !text.isEmpty && text.unicodeScalars.allSatisfy { ("a"..."z").contains($0) || ("A"..."Z").contains($0) || ("0"..."9").contains($0) || $0 == "-" || $0 == "_" } return plain ? text : "~" + Base64URL.encode(Data(text.utf8)) } /// Whether `account` is one of `identity`'s teams: signing out of an /// identity ends all of them. nonisolated public static func account(_ account: String, belongsTo identity: String) -> Bool { account.hasPrefix(prefix + component(identity) + ".") } /// Whether `account` is an Oficina ID team's, as against a server /// account's (a UUID). nonisolated public static func isOficinaAccount(_ account: String) -> Bool { account.hasPrefix(prefix) } /// The client for `account`'s latest session, or nil once the identity /// has signed out. One client per session, so requests share a /// URLSession instead of making one each. public func client(for account: String) -> NativeHTTP? { sessions[account]?.client } /// What a workspace for `account` asks on every request. A 401 from it /// re-mints the session silently (spec §7); a request after sign-out /// gets no transport, and fails as `.unauthorized`. public func transport(for account: String) -> @MainActor () -> NativeTransport? { { [weak self] in guard let self, let current = self.sessions[account] else { return nil } return self.watch(current.client, account: account, session: current.session.value) } } /// `inner`, sending with `account`'s `session`, watched for refusals. A /// refusal says which session it was sent with, so one that comes back /// after another request's re-mint is not taken for the new session's. func watch(_ inner: NativeTransport, account: String, session: String) -> DocsSessionWatch { DocsSessionWatch(inner: inner, rejected: { [weak self] in Task { @MainActor in await self?.rejected(account, sentWith: session) } }, refused: { [weak self] in Task { @MainActor in await self?.refused() } }) } /// Re-mints a session older than 24 hours; call when a scene comes back. public func renewIfNeeded() async { guard renewal == nil else { return } await renew { [model] in await model.renewIfNeeded() } } private func renew(_ body: @escaping @MainActor () async -> Void) async { // Cleared inside the task, so whoever awaits it finds none in flight. let task = Task { @MainActor [weak self] in await body(); self?.renewal = nil } renewal = task await task.value } /// The instance refused the session `session` (nil: whichever is /// current). Only the team in use can be re-minted (another team's would /// mean switching to it), and at most once a minute per account, so an /// instance that keeps refusing cannot set off a loop of assertions. /// /// A refusal of a session already replaced, by another request's re-mint /// that finished first, re-mints nothing: the write sent on the old /// cookie may have stopped the account's outbox after the new session /// restarted it, so it is restarted again (#130, finding 4). func rejected(_ account: String, sentWith session: String? = nil) async { if let renewal { await renewal.value } if let session, let current = sessions[account]?.session.value, current != session { await DocsOfflineAccount.sessionReplaced(account) return } guard let state = signedIn, Self.accountID(state) == account, renewal == nil else { return } if let last = lastRejection[account], now().timeIntervalSince(last) < 60 { return } lastRejection[account] = now() await renew { [model] in await model.sessionRejected() } } /// Called as the step is about to change (`@Published` publishes before /// the property is set), so `model.step` is still the previous one. private func stepChanged(_ step: OficinaIDModel.Step) { let previous = model.step switch step { case .signedIn(let state): mounted = state if case .signedIn = previous {} else if previous != .loading { signIns += 1 } case .unavailable(let team) where mounted?.team.sqid == team.sqid && model.identity?.id == mounted?.identity.id: break default: mounted = nil } if case .signedIn(let state) = step { let account = Self.accountID(state) let previous = sessions[account]?.session if previous?.value != state.session.value { sessions[account] = (state.session, state.client()) // A workspace whose outbox stopped on the old session's 401 // sends again with the new one. if previous != nil { DocsOfflineAccount.sessionRestored(account) } } // Sessions of the identity's other teams stay, so their document // windows keep working; another identity's never do. sessions = sessions.filter { Self.account($0.key, belongsTo: state.identity.id) } } else if model.identity == nil { sessions.removeAll() lastRejection.removeAll() } } } /// Why Docs won't sign out, switch team or replace the Oficina ID just now, /// in a line the person sees instead of a button that silently does nothing. public enum DocsLeaveBlock: Equatable, Sendable { /// Changes on this device are still to be sent, in this window or in any /// team of the identity (an outbox left by a crash included). case sending /// A document window of one of the identity's teams is open (Mac). case openDocuments public var message: String { NSLocalizedString(self == .sending ? "native.leave.sending" : "native.leave.openDocuments", bundle: DocsResources.bundle, comment: "") } /// The identity-wide guard: open document windows first, then anything /// this window or any of the identity's teams has not sent. @MainActor public static func check(identity: String, openDocuments: Bool, unsentHere: Bool = false) async -> DocsLeaveBlock? { if openDocuments { return .openDocuments } if unsentHere { return .sending } return await DocsOfflineAccount.hasUnsent(identity: identity) ? .sending : nil } } /// A transport that tells Docs when the instance refuses its session: a 401, /// or the 303 to sign-in that `NativeClientError` also reads as an ended /// session; and when it refuses a request, a 403. Everything else passes /// through untouched. /// /// Docs' session guards answer a non-GET request whose session has ended /// (none, unknown, revoked, or a native session past its seven days) with /// 403 "signed out" (rastrillo sessions.Require, and Docs' identity guard: /// internal/docs/identity.go, sessionEndedBody), not 401. Read as a refused /// request, a window open past the session's seven days whose first request /// is a write would never re-mint, and its outbox would hold the change as /// access lost. That one 403 is an ended session, re-minted and surfaced as /// the 401 it means; internal/docs/native_contract_test.go pins the bytes. struct DocsSessionWatch: NativeTransport { let inner: NativeTransport let rejected: @Sendable () -> Void /// A 403: refused this request, not the session. Docs refreshes the team /// list on it (spec §9). var refused: @Sendable () -> Void = {} var origin: URL { inner.origin } /// The session guards' refusal, byte for byte (`http.Error` adds the newline). static let signedOut = Data("signed out\n".utf8) func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { let reply = try await inner.responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes) if reply.status == 403, reply.data == Self.signedOut { rejected() return NativeResponse(data: reply.data, status: 401, headers: reply.headers) } if reply.status == 401 || reply.status == 303 { rejected() } if reply.status == 403 { refused() } return reply } func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { do { try await inner.stream(path, onOpen: onOpen, onLine: onLine) } catch NativeClientError.unauthorized { rejected(); throw NativeClientError.unauthorized } } func download(_ path: String, to destination: URL) async throws { do { try await inner.download(path, to: destination) } catch NativeClientError.unauthorized { rejected(); throw NativeClientError.unauthorized } } } #if os(macOS) import Security /// The launch gate (spec §13, "Mac launch"): the final signed artifact must /// launch and read the shared group before any Sparkle publish, because a /// build killed at launch cannot update itself. Run the app's executable /// with `--oficina-id-launch-check`: macOS checks the embedded profile /// against the entitlements as it starts the process. This then checks the /// signed entitlements (keychain groups in order, the App Group, the /// associated domain) and reads, never writes, both keychain groups. It /// prints what it found and exits 0 only if all of it works. It prints /// counts, never an identity or a session. public enum DocsOficinaLaunchCheck { public static let argument = "--oficina-id-launch-check" public static func run() -> (passed: Bool, lines: [String]) { var lines: [String] = [], passed = true func check(_ name: String, _ body: () throws -> String) { do { lines.append("ok \(name): \(try body())") } catch { passed = false; lines.append("FAIL \(name): \(error)") } } let own = OficinaKeychainStore.appGroup(for: DocsOficinaSession.configuration.app) check("keychain-access-groups") { let groups = entitlement("keychain-access-groups") // A query that names no group lands in the first: it must be Docs' own. guard groups.first == own, groups.contains(OficinaKeychainStore.sharedGroup) else { throw LaunchCheckError("expected [\(own), \(OficinaKeychainStore.sharedGroup)], got \(groups)") } return groups.joined(separator: ", ") } check("shared group \(OficinaKeychainStore.sharedGroup)") { // The store Docs' onboarding reads at launch, records decoded. let store = OficinaIDStore(shared: OficinaKeychainStore(accessGroup: OficinaKeychainStore.sharedGroup), appPrivate: OficinaKeychainStore(accessGroup: own), group: UserDefaults(suiteName: DocsOficinaSession.appGroup) ?? .standard) return "readable, \(try store.identities().count) identities" + " (\(store.unreadableIdentities().count) only a newer app can read)" } check("Docs' group \(own)") { "readable, \(try OficinaKeychainStore(accessGroup: own).accounts(service: "works.oficina.id.session").count) sessions" } // On a Mac, containerURL answers for any app group, granted or not, // so the entitlement itself is what proves the grant. check("App Group \(DocsOficinaSession.appGroup)") { let groups = entitlement("com.apple.security.application-groups") guard groups.contains(DocsOficinaSession.appGroup) else { throw LaunchCheckError("not granted: com.apple.security.application-groups is \(groups)") } guard UserDefaults(suiteName: DocsOficinaSession.appGroup) != nil else { throw LaunchCheckError("no defaults suite") } return "granted" } check("associated domains") { let domains = entitlement("com.apple.developer.associated-domains") guard domains.contains("webcredentials:id.oficina.works") else { throw LaunchCheckError("got \(domains)") } return domains.joined(separator: ", ") } return (passed, lines) } /// A string-array entitlement of this process, as signed. static func entitlement(_ key: String) -> [String] { guard let task = SecTaskCreateFromSelf(nil) else { return [] } return SecTaskCopyValueForEntitlement(task, key as CFString, nil) as? [String] ?? [] } struct LaunchCheckError: Error, CustomStringConvertible { let description: String init(_ description: String) { self.description = description } } } #endif