| 1 | import Combine |
| 2 | import Foundation |
| 3 | import RastrilloApple |
| 4 | |
| 5 | /// How Sheets signs in, as the person last chose it. Oficina ID is the |
| 6 | /// primary way (Home spec 2026-11-14-oficina-id-native §9, slice A); "Other |
| 7 | /// ways to sign in…" keeps the server address and browser approval for |
| 8 | /// self-hosted servers and local accounts (§11). |
| 9 | public enum SheetsSignInRoute: String, Sendable { |
| 10 | case oficinaID = "oficina-id" |
| 11 | case server |
| 12 | |
| 13 | /// The `UserDefaults` key the choice is kept under. |
| 14 | public static let key = "sheets.signin.route" |
| 15 | |
| 16 | /// The route to show. Nothing chosen yet means Oficina ID, except for |
| 17 | /// someone already signed in the old way: their accounts keep working |
| 18 | /// until an Oficina ID replaces them (spec Appendix C). An Oficina ID |
| 19 | /// sign-in chooses `.oficinaID` for good. On `.server` the app suspends |
| 20 | /// the kit's straight in (spec §9, rule 0). |
| 21 | public static func resolve(stored: String, hasServerAccounts: Bool) -> SheetsSignInRoute { |
| 22 | if let chosen = SheetsSignInRoute(rawValue: stored) { return chosen } |
| 23 | return hasServerAccounts ? .server : .oficinaID |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | /// Sheets' half of Oficina ID: the kit's model, and the team sessions it |
| 28 | /// mints turned into the transport Sheets' workspaces use. |
| 29 | /// |
| 30 | /// A workspace is keyed by `(identity, team)`, never by a session: a session |
| 31 | /// is re-minted after 24 hours and on a 401, and the open workspace must |
| 32 | /// carry on through that, so its transport reads the latest session for its |
| 33 | /// account on every request. |
| 34 | /// |
| 35 | /// Nothing here is read-then-written from a view's body or init (Docs |
| 36 | /// 0.1.7/0.1.8 hung at launch that way, docs 84d1008): `mounted`, |
| 37 | /// `sessions` and `signIns` change only from the model's step publisher, |
| 38 | /// and `start()` runs from a `.task`. |
| 39 | @MainActor public final class SheetsOficinaSession: ObservableObject { |
| 40 | public let model: OficinaIDModel |
| 41 | private var sessions: [String: (session: NativeSession, client: NativeHTTP)] = [:] |
| 42 | private var lastRejection: [String: Date] = [:] |
| 43 | private var lastRefusal: Date? |
| 44 | private var renewing = false |
| 45 | private var started = false |
| 46 | private var watch: AnyCancellable? |
| 47 | private let now: () -> Date |
| 48 | |
| 49 | nonisolated public static let configuration = OficinaIDConfiguration(app: "sheets", appName: "Sheets") |
| 50 | |
| 51 | /// The team the workspace shows: the signed-in team, kept while Oficina |
| 52 | /// ID cannot mint it a new session (spec §11), so a 401 with Home |
| 53 | /// unreachable does not unmount an open sheet. nil once the identity |
| 54 | /// signs out or the model moves on to another team's question. |
| 55 | @Published public private(set) var mounted: OficinaSignedIn? |
| 56 | |
| 57 | /// Sign-ins a person made here (a code, a passkey, a team or identity |
| 58 | /// picked, a retry), as against a launch going straight in. Only these |
| 59 | /// choose the Oficina ID route for good. |
| 60 | @Published public private(set) var signIns = 0 |
| 61 | |
| 62 | /// The App Group holding identity order and last-used team: team-prefixed |
| 63 | /// on the Mac, the registered `group.works.oficina` on iOS. |
| 64 | nonisolated public static var appGroup: String { |
| 65 | #if os(macOS) |
| 66 | "9U4A84C4WK.works.oficina" |
| 67 | #else |
| 68 | "group.works.oficina" |
| 69 | #endif |
| 70 | } |
| 71 | |
| 72 | /// The real wiring: the shared keychain group, Sheets' own, the App |
| 73 | /// Group, Home over HTTPS and the platform's passkey sheet. |
| 74 | public static func live() -> SheetsOficinaSession { |
| 75 | SheetsOficinaSession(model: .live(configuration: configuration, appGroup: appGroup)) |
| 76 | } |
| 77 | |
| 78 | public init(model: OficinaIDModel, now: @escaping () -> Date = Date.init) { |
| 79 | self.model = model |
| 80 | self.now = now |
| 81 | watch = model.$step.sink { [weak self] step in self?.stepChanged(step) } |
| 82 | } |
| 83 | |
| 84 | /// Reads the store once per launch, however many windows ask, then |
| 85 | /// refreshes the team list (spec §9: at launch). `serverRoute` is the app's |
| 86 | /// own sign-in being the route: nothing goes straight in then (rule 0). |
| 87 | public func start(serverRoute: Bool = false) async { |
| 88 | guard !started else { return } |
| 89 | started = true |
| 90 | if serverRoute { model.suspendStraightIn() } |
| 91 | await model.start() |
| 92 | await model.refreshTeams() |
| 93 | } |
| 94 | |
| 95 | /// The route changed, by the person or by itself (the last server account |
| 96 | /// signed out, say): straight in is suspended exactly while the app's |
| 97 | /// own sign-in is the route, and resumes when it stops being (spec §9, |
| 98 | /// rule 0). Without this a route that flips on its own would leave |
| 99 | /// Welcome with straight in still suspended (Fable, sheets ded0f68). |
| 100 | public func routeChanged(to route: SheetsSignInRoute) async { |
| 101 | switch route { |
| 102 | case .server: model.suspendStraightIn() |
| 103 | case .oficinaID: await model.resumeStraightIn() |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | /// "Use another Oficina ID" from the account menu: only while signed in |
| 108 | /// (over an outage there is no dialog to ask with), and only when |
| 109 | /// `canLeave` (no document window of the identity open). Returns whether |
| 110 | /// it asked. |
| 111 | @discardableResult |
| 112 | public func useAnother(identity: String, canLeave: Bool) -> Bool { |
| 113 | guard case .signedIn(let state) = model.step, state.identity.id == identity, canLeave else { return false } |
| 114 | model.useAnother() |
| 115 | return true |
| 116 | } |
| 117 | |
| 118 | /// "Sign out of <label>", refused while a document window of the |
| 119 | /// identity is open. Returns whether it signed out. |
| 120 | @discardableResult |
| 121 | public func signOut(identity: String, canLeave: Bool) -> Bool { |
| 122 | guard model.identity?.id == identity, canLeave else { return false } |
| 123 | model.signOut() |
| 124 | return true |
| 125 | } |
| 126 | |
| 127 | /// The team picker opened: refresh if the list is five minutes old. |
| 128 | public func pickerOpened() async { await model.refreshTeams() } |
| 129 | |
| 130 | /// An instance answered 403: fetch the team list again, at most once a |
| 131 | /// minute (spec §9). |
| 132 | func refused() async { |
| 133 | if let last = lastRefusal, now().timeIntervalSince(last) < 60 { return } |
| 134 | lastRefusal = now() |
| 135 | await model.refreshTeams(maxAge: 0) |
| 136 | } |
| 137 | |
| 138 | /// The account Sheets files an Oficina ID team under (its windows and |
| 139 | /// recents): stable for the life of the identity on this device. |
| 140 | nonisolated public static func accountID(_ state: OficinaSignedIn) -> String { |
| 141 | accountID(identity: state.identity.id, team: state.team.sqid) |
| 142 | } |
| 143 | |
| 144 | nonisolated public static func accountID(identity: String, team: String) -> String { |
| 145 | prefix + component(identity) + "." + component(team) |
| 146 | } |
| 147 | |
| 148 | nonisolated static let prefix = "oficina-id." |
| 149 | |
| 150 | /// Each part is used as it is only when base64url-safe (as Home's |
| 151 | /// identity IDs and sqids are); anything else is encoded behind a "~". |
| 152 | nonisolated static func component(_ text: String) -> String { |
| 153 | let plain = !text.isEmpty && text.unicodeScalars.allSatisfy { |
| 154 | ("a"..."z").contains($0) || ("A"..."Z").contains($0) || ("0"..."9").contains($0) || $0 == "-" || $0 == "_" |
| 155 | } |
| 156 | return plain ? text : "~" + Base64URL.encode(Data(text.utf8)) |
| 157 | } |
| 158 | |
| 159 | /// Whether `account` is one of `identity`'s teams. |
| 160 | nonisolated public static func account(_ account: String, belongsTo identity: String) -> Bool { |
| 161 | account.hasPrefix(prefix + component(identity) + ".") |
| 162 | } |
| 163 | |
| 164 | /// The transport for `account`: its latest session on every request; a |
| 165 | /// 401 re-mints silently (spec §7), a 403 refreshes the teams; after |
| 166 | /// sign-out every request fails as `.unauthorized`. |
| 167 | public func transport(for account: String, origin: URL) -> SheetsOficinaTransport { |
| 168 | SheetsOficinaTransport(origin: origin, current: { [weak self] in self?.sessions[account]?.client as (any NativeTransport)? }, |
| 169 | rejected: { [weak self] in Task { @MainActor in await self?.rejected(account) } }, |
| 170 | refused: { [weak self] in Task { @MainActor in await self?.refused() } }) |
| 171 | } |
| 172 | |
| 173 | /// Re-mints a session older than 24 hours; call when a scene comes back. |
| 174 | public func renewIfNeeded() async { |
| 175 | guard !renewing else { return } |
| 176 | renewing = true |
| 177 | defer { renewing = false } |
| 178 | await model.renewIfNeeded() |
| 179 | } |
| 180 | |
| 181 | /// The instance refused the session: only the team in use is re-minted, |
| 182 | /// at most once a minute per account, so a refusing instance cannot set |
| 183 | /// off a loop of assertions. |
| 184 | func rejected(_ account: String) async { |
| 185 | guard case .signedIn(let state) = model.step, Self.accountID(state) == account, !renewing else { return } |
| 186 | if let last = lastRejection[account], now().timeIntervalSince(last) < 60 { return } |
| 187 | lastRejection[account] = now() |
| 188 | renewing = true |
| 189 | defer { renewing = false } |
| 190 | await model.sessionRejected() |
| 191 | } |
| 192 | |
| 193 | /// Called as the step is about to change (`@Published` publishes before |
| 194 | /// the property is set), so `model.step` is still the previous one. |
| 195 | private func stepChanged(_ step: OficinaIDModel.Step) { |
| 196 | let previous = model.step |
| 197 | switch step { |
| 198 | case .signedIn(let state): |
| 199 | mounted = state |
| 200 | if case .signedIn = previous {} else if previous != .loading { signIns += 1 } |
| 201 | case .unavailable(let team) where mounted?.team.sqid == team.sqid && model.identity?.id == mounted?.identity.id: |
| 202 | break |
| 203 | default: |
| 204 | mounted = nil |
| 205 | } |
| 206 | if case .signedIn(let state) = step { |
| 207 | let account = Self.accountID(state) |
| 208 | if sessions[account]?.session.value != state.session.value { |
| 209 | sessions[account] = (state.session, state.client()) |
| 210 | } |
| 211 | // The identity's other teams keep theirs (open document windows); |
| 212 | // another identity's never do. |
| 213 | sessions = sessions.filter { Self.account($0.key, belongsTo: state.identity.id) } |
| 214 | } else if model.identity == nil { |
| 215 | sessions.removeAll() |
| 216 | lastRejection.removeAll() |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | /// A workspace's transport for an Oficina ID team: the latest session's |
| 222 | /// client on every request, and word back when the instance refuses the |
| 223 | /// session (401, or the 303 to sign-in `NativeClientError` also reads as an |
| 224 | /// ended session) or a request (403). |
| 225 | /// |
| 226 | /// Sheets' session guards answer a non-GET request with an ended or refused |
| 227 | /// session as 403 "Sign in first." (home.go, team_access.go), not 401: read |
| 228 | /// as a refused request, a window open past the session's seven days whose |
| 229 | /// first request is a cell write would never re-mint. That one 403 is an |
| 230 | /// ended session, re-minted and surfaced as the 401 it means. |
| 231 | public struct SheetsOficinaTransport: NativeTransport { |
| 232 | public let origin: URL |
| 233 | let current: @MainActor @Sendable () -> (any NativeTransport)? |
| 234 | let rejected: @Sendable () -> Void |
| 235 | let refused: @Sendable () -> Void |
| 236 | |
| 237 | public init(origin: URL, current: @escaping @MainActor @Sendable () -> (any NativeTransport)?, |
| 238 | rejected: @escaping @Sendable () -> Void, refused: @escaping @Sendable () -> Void) { |
| 239 | self.origin = origin; self.current = current; self.rejected = rejected; self.refused = refused |
| 240 | } |
| 241 | |
| 242 | /// The session guards' refusal, byte for byte (`http.Error` adds the newline). |
| 243 | static let signInFirst = Data("Sign in first.\n".utf8) |
| 244 | |
| 245 | private func client() async throws -> any NativeTransport { |
| 246 | guard let client = await current() else { throw NativeClientError.unauthorized } |
| 247 | return client |
| 248 | } |
| 249 | |
| 250 | public func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| 251 | let reply = try await client().responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes) |
| 252 | if reply.status == 403, reply.data == Self.signInFirst { |
| 253 | rejected() |
| 254 | return NativeResponse(data: reply.data, status: 401, headers: reply.headers) |
| 255 | } |
| 256 | if reply.status == 401 || reply.status == 303 { rejected() } |
| 257 | if reply.status == 403 { refused() } |
| 258 | return reply |
| 259 | } |
| 260 | |
| 261 | public func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| 262 | do { try await client().stream(path, onOpen: onOpen, onLine: onLine) } |
| 263 | catch NativeClientError.unauthorized { rejected(); throw NativeClientError.unauthorized } |
| 264 | } |
| 265 | |
| 266 | public func download(_ path: String, to destination: URL) async throws { |
| 267 | do { try await client().download(path, to: destination) } |
| 268 | catch NativeClientError.unauthorized { rejected(); throw NativeClientError.unauthorized } |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | #if os(macOS) |
| 273 | import Security |
| 274 | |
| 275 | /// The launch gate (spec §13, "Mac launch"): the final signed artifact must |
| 276 | /// launch and read the shared group before any Sparkle publish, because a |
| 277 | /// build killed at launch cannot update itself. Run the app's executable |
| 278 | /// with `--oficina-id-launch-check`. It checks the signed entitlements and |
| 279 | /// reads, never writes, both keychain groups; it prints counts, never an |
| 280 | /// identity or a session, and exits 0 only if all of it works. |
| 281 | public enum SheetsOficinaLaunchCheck { |
| 282 | public static let argument = "--oficina-id-launch-check" |
| 283 | |
| 284 | public static func run() -> (passed: Bool, lines: [String]) { |
| 285 | var lines: [String] = [], passed = true |
| 286 | func check(_ name: String, _ body: () throws -> String) { |
| 287 | do { lines.append("ok \(name): \(try body())") } |
| 288 | catch { passed = false; lines.append("FAIL \(name): \(error)") } |
| 289 | } |
| 290 | let own = OficinaKeychainStore.appGroup(for: SheetsOficinaSession.configuration.app) |
| 291 | check("keychain-access-groups") { |
| 292 | let groups = entitlement("keychain-access-groups") |
| 293 | // A query that names no group lands in the first: it must be Sheets' own. |
| 294 | guard groups.first == own, groups.contains(OficinaKeychainStore.sharedGroup) else { |
| 295 | throw LaunchCheckError("expected [\(own), \(OficinaKeychainStore.sharedGroup)], got \(groups)") |
| 296 | } |
| 297 | return groups.joined(separator: ", ") |
| 298 | } |
| 299 | check("shared group \(OficinaKeychainStore.sharedGroup)") { |
| 300 | let store = OficinaIDStore(shared: OficinaKeychainStore(accessGroup: OficinaKeychainStore.sharedGroup), |
| 301 | appPrivate: OficinaKeychainStore(accessGroup: own), |
| 302 | group: UserDefaults(suiteName: SheetsOficinaSession.appGroup) ?? .standard) |
| 303 | return "readable, \(try store.identities().count) identities" |
| 304 | + " (\(store.unreadableIdentities().count) only a newer app can read)" |
| 305 | } |
| 306 | check("Sheets' group \(own)") { |
| 307 | "readable, \(try OficinaKeychainStore(accessGroup: own).accounts(service: "works.oficina.id.session").count) sessions" |
| 308 | } |
| 309 | // On a Mac, containerURL answers for any app group, granted or not, so |
| 310 | // the entitlement itself is what proves the grant. |
| 311 | check("App Group \(SheetsOficinaSession.appGroup)") { |
| 312 | let groups = entitlement("com.apple.security.application-groups") |
| 313 | guard groups.contains(SheetsOficinaSession.appGroup) else { |
| 314 | throw LaunchCheckError("not granted: com.apple.security.application-groups is \(groups)") |
| 315 | } |
| 316 | guard UserDefaults(suiteName: SheetsOficinaSession.appGroup) != nil else { throw LaunchCheckError("no defaults suite") } |
| 317 | return "granted" |
| 318 | } |
| 319 | check("associated domains") { |
| 320 | let domains = entitlement("com.apple.developer.associated-domains") |
| 321 | guard domains.contains("webcredentials:id.oficina.works") else { throw LaunchCheckError("got \(domains)") } |
| 322 | return domains.joined(separator: ", ") |
| 323 | } |
| 324 | return (passed, lines) |
| 325 | } |
| 326 | |
| 327 | /// A string-array entitlement of this process, as signed. |
| 328 | static func entitlement(_ key: String) -> [String] { |
| 329 | guard let task = SecTaskCreateFromSelf(nil) else { return [] } |
| 330 | return SecTaskCopyValueForEntitlement(task, key as CFString, nil) as? [String] ?? [] |
| 331 | } |
| 332 | |
| 333 | struct LaunchCheckError: Error, CustomStringConvertible { |
| 334 | let description: String |
| 335 | init(_ description: String) { self.description = description } |
| 336 | } |
| 337 | } |
| 338 | #endif |
| 339 | |