oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1import Combine
2import Foundation
3import RastrilloApple
4
5/// How Docs signs in, as the person last chose it. Oficina ID is the primary
6/// way (spec 2026-11-14-oficina-id-native §9, slice A); "Other ways to sign
7/// in…" keeps the server address and browser approval for self-hosted
8/// servers and local accounts (§11).
9public enum DocsSignInRoute: 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 = "docs.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 per-app sessions keep
18 /// working until an Oficina ID replaces them (spec Appendix C). An
19 /// Oficina ID sign-in chooses `.oficinaID` for good. On `.server` the
20 /// app suspends the kit's straight in (spec §9, rule 0).
21 public static func resolve(stored: String, hasServerAccounts: Bool) -> DocsSignInRoute {
22 if let chosen = DocsSignInRoute(rawValue: stored) { return chosen }
23 return hasServerAccounts ? .server : .oficinaID
24 }
25}
26
27/// Docs' half of Oficina ID: the kit's model, and the team sessions it mints
28/// turned into the transports Docs' 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 workspace, its offline
32/// store and its outbox must carry on through that. So the transport is a
33/// supplier that reads the latest session for its 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, 84d1008): `mounted`, `sessions` and
37/// `signIns` change only from the model's step publisher, and `start`,
38/// `routeChanged` and `useAnother` run from a `.task`, an `.onChange` or a
39/// button.
40@MainActor public final class DocsOficinaSession: ObservableObject {
41 public let model: OficinaIDModel
42 private var sessions: [String: (session: NativeSession, client: NativeHTTP)] = [:]
43 private var lastRejection: [String: Date] = [:]
44 private var lastRefusal: Date?
45 /// A re-mint in flight (a day-old session's, or a refused one's): never
46 /// two at once, and a refusal that lands meanwhile waits for it.
47 private var renewal: Task<Void, Never>?
48 private var started = false
49 private var watch: AnyCancellable?
50 private let now: () -> Date
51
52 nonisolated public static let configuration = OficinaIDConfiguration(app: "docs", appName: "Docs")
53
54 /// The team the workspace shows. It is the signed-in team, and it stays
55 /// while Oficina ID cannot mint that team a new session (spec §11): a
56 /// 401 with Home unreachable must not unmount an open editor. Docs then
57 /// shows the "Can't reach Oficina ID" line over the workspace instead.
58 /// nil once the identity signs out, or the model moves to another team's
59 /// question (not on it, choose, …).
60 @Published public private(set) var mounted: OficinaSignedIn?
61
62 /// Counts sign-ins a person made here: an identity chosen, a code or
63 /// passkey, a team picked, a retry. Going straight in at launch (the
64 /// last team, or the one Oficina ID on the device) is not one, so it
65 /// never changes Docs' sign-in route.
66 @Published public private(set) var signIns = 0
67
68 /// "Teams": the workspace's button for Docs' team picker.
69 public static var teamsTitle: String {
70 NSLocalizedString("native.oficinaid.teams", bundle: DocsResources.bundle, comment: "")
71 }
72
73 /// The App Group that holds the identity order and last-used team: team
74 /// prefixed on the Mac, where it needs no profile, and the registered
75 /// `group.works.oficina` on iOS (rastrillo/native APPLE.md).
76 nonisolated public static var appGroup: String {
77 #if os(macOS)
78 "9U4A84C4WK.works.oficina"
79 #else
80 "group.works.oficina"
81 #endif
82 }
83
84 /// The real wiring: the shared keychain group, Docs' own group, the App
85 /// Group, Home over HTTPS and the platform's passkey sheet.
86 public static func live() -> DocsOficinaSession {
87 DocsOficinaSession(model: .live(configuration: configuration, appGroup: appGroup))
88 }
89
90 public init(model: OficinaIDModel, now: @escaping () -> Date = Date.init) {
91 self.model = model
92 self.now = now
93 watch = model.$step.sink { [weak self] step in self?.stepChanged(step) }
94 }
95
96 /// Reads the store once per launch, however many windows ask, then
97 /// refreshes the team list (spec §9: at launch). With one Oficina ID on
98 /// the device the kit goes straight in (Paul, 2026-11-19). `serverRoute`
99 /// is Docs' own sign-in being the route: nothing goes straight in then
100 /// (rule 0).
101 public func start(serverRoute: Bool = false) async {
102 guard !started else { return }
103 started = true
104 if serverRoute { model.suspendStraightIn() }
105 await model.start()
106 await model.refreshTeams()
107 }
108
109 /// The route changed, by the person or by itself (the last server
110 /// account signed out, say): straight in is suspended exactly while
111 /// Docs' own sign-in is the route, and resumes when it stops being
112 /// (spec §9, rule 0). Signed in, neither disturbs the session. Call it
113 /// from `.onChange(of: route)`, never from a body.
114 public func routeChanged(to route: DocsSignInRoute) async {
115 switch route {
116 case .server: model.suspendStraightIn()
117 case .oficinaID: await model.resumeStraightIn()
118 }
119 }
120
121 /// "Use another Oficina ID" from the account menu: only while signed in
122 /// (over an outage the team stays mounted, but there is no dialog to
123 /// ask with), and only when `canLeave` (no document window of the
124 /// identity open). The kit then asks (`oficinaReplaceConfirmation`), and
125 /// the window re-checks Docs' guards while it does. Returns whether it
126 /// asked.
127 @discardableResult
128 public func useAnother(identity: String, canLeave: Bool) -> Bool {
129 guard case .signedIn(let state) = model.step, state.identity.id == identity, canLeave else { return false }
130 model.useAnother()
131 return true
132 }
133
134 /// "Use another Oficina ID" as the account menu asks it: Docs' guards
135 /// first, then the kit's confirmation. A document window of the
136 /// identity open, or changes of any of its teams unsent, refuse it
137 /// before anything is shown, so the confirmation is never put up only
138 /// to be withdrawn, and can't be confirmed while the outbox is still
139 /// being checked (#130, finding 1). `openDocuments` is asked again once
140 /// that check is done. Returns why it was refused; nil once the kit asks
141 /// (or nothing can be asked: not signed in to `identity`).
142 public func requestUseAnother(identity: String, openDocuments: @MainActor () -> Bool) async -> DocsLeaveBlock? {
143 if let block = await DocsLeaveBlock.check(identity: identity, openDocuments: openDocuments()) { return block }
144 if openDocuments() { return .openDocuments }
145 useAnother(identity: identity, canLeave: true)
146 return nil
147 }
148
149 /// The team picker opened: refresh if the list is five minutes old.
150 public func pickerOpened() async { await model.refreshTeams() }
151
152 /// An instance answered 403: the person may have left the team, or been
153 /// given another, so the list is fetched again, at most once a minute.
154 func refused() async {
155 if let last = lastRefusal, now().timeIntervalSince(last) < 60 { return }
156 lastRefusal = now()
157 await model.refreshTeams(maxAge: 0)
158 }
159
160 /// The team session in use, if the model has one.
161 public var signedIn: OficinaSignedIn? {
162 if case .signedIn(let state) = model.step { return state }
163 return nil
164 }
165
166 /// The account Docs files an Oficina ID team under: its offline store,
167 /// outbox and windows. Stable for the life of the identity on this
168 /// device, whatever session the team holds.
169 public static func accountID(_ state: OficinaSignedIn) -> String {
170 accountID(identity: state.identity.id, team: state.team.sqid)
171 }
172
173 /// The team name a document window of `account` shows in its subtitle
174 /// (spec D7): the signed-in team's, or another team of the same identity
175 /// from the teams cache, read each time so a renamed team shows its new
176 /// name. nil for a server account or a team this device has not seen.
177 public func teamName(forAccount account: String) -> String? {
178 guard let state = mounted ?? signedIn else { return nil }
179 if Self.accountID(state) == account { return state.team.name }
180 return model.store.teams(state.identity.id)?.teams
181 .first { Self.accountID(identity: state.identity.id, team: $0.sqid) == account }?.name
182 }
183
184 /// Who "(you)" is in the Share panel for a window of `account`: the
185 /// identity's label (an email, or the name the person gave it). nil for
186 /// a server account.
187 public func identityLabel(forAccount account: String) -> String? {
188 guard let state = mounted ?? signedIn, DocsOficinaSession.account(account, belongsTo: state.identity.id) else { return nil }
189 return state.identity.label
190 }
191
192 nonisolated public static func accountID(identity: String, team: String) -> String {
193 prefix + component(identity) + "." + component(team)
194 }
195
196 nonisolated static let prefix = "oficina-id."
197
198 /// An account ID names a directory and a keychain item, so each part is
199 /// used as it is only when it is base64url-safe (as Home's identity IDs
200 /// and sqids are). Anything else, a "." or "/" above all, is encoded,
201 /// marked by a "~" no plain part can contain.
202 nonisolated static func component(_ text: String) -> String {
203 let plain = !text.isEmpty && text.unicodeScalars.allSatisfy {
204 ("a"..."z").contains($0) || ("A"..."Z").contains($0) || ("0"..."9").contains($0) || $0 == "-" || $0 == "_"
205 }
206 return plain ? text : "~" + Base64URL.encode(Data(text.utf8))
207 }
208
209 /// Whether `account` is one of `identity`'s teams: signing out of an
210 /// identity ends all of them.
211 nonisolated public static func account(_ account: String, belongsTo identity: String) -> Bool {
212 account.hasPrefix(prefix + component(identity) + ".")
213 }
214
215 /// Whether `account` is an Oficina ID team's, as against a server
216 /// account's (a UUID).
217 nonisolated public static func isOficinaAccount(_ account: String) -> Bool { account.hasPrefix(prefix) }
218
219 /// The client for `account`'s latest session, or nil once the identity
220 /// has signed out. One client per session, so requests share a
221 /// URLSession instead of making one each.
222 public func client(for account: String) -> NativeHTTP? { sessions[account]?.client }
223
224 /// What a workspace for `account` asks on every request. A 401 from it
225 /// re-mints the session silently (spec §7); a request after sign-out
226 /// gets no transport, and fails as `.unauthorized`.
227 public func transport(for account: String) -> @MainActor () -> NativeTransport? {
228 { [weak self] in
229 guard let self, let current = self.sessions[account] else { return nil }
230 return self.watch(current.client, account: account, session: current.session.value)
231 }
232 }
233
234 /// `inner`, sending with `account`'s `session`, watched for refusals. A
235 /// refusal says which session it was sent with, so one that comes back
236 /// after another request's re-mint is not taken for the new session's.
237 func watch(_ inner: NativeTransport, account: String, session: String) -> DocsSessionWatch {
238 DocsSessionWatch(inner: inner, rejected: { [weak self] in
239 Task { @MainActor in await self?.rejected(account, sentWith: session) }
240 }, refused: { [weak self] in
241 Task { @MainActor in await self?.refused() }
242 })
243 }
244
245 /// Re-mints a session older than 24 hours; call when a scene comes back.
246 public func renewIfNeeded() async {
247 guard renewal == nil else { return }
248 await renew { [model] in await model.renewIfNeeded() }
249 }
250
251 private func renew(_ body: @escaping @MainActor () async -> Void) async {
252 // Cleared inside the task, so whoever awaits it finds none in flight.
253 let task = Task { @MainActor [weak self] in await body(); self?.renewal = nil }
254 renewal = task
255 await task.value
256 }
257
258 /// The instance refused the session `session` (nil: whichever is
259 /// current). Only the team in use can be re-minted (another team's would
260 /// mean switching to it), and at most once a minute per account, so an
261 /// instance that keeps refusing cannot set off a loop of assertions.
262 ///
263 /// A refusal of a session already replaced, by another request's re-mint
264 /// that finished first, re-mints nothing: the write sent on the old
265 /// cookie may have stopped the account's outbox after the new session
266 /// restarted it, so it is restarted again (#130, finding 4).
267 func rejected(_ account: String, sentWith session: String? = nil) async {
268 if let renewal { await renewal.value }
269 if let session, let current = sessions[account]?.session.value, current != session {
270 await DocsOfflineAccount.sessionReplaced(account)
271 return
272 }
273 guard let state = signedIn, Self.accountID(state) == account, renewal == nil else { return }
274 if let last = lastRejection[account], now().timeIntervalSince(last) < 60 { return }
275 lastRejection[account] = now()
276 await renew { [model] in await model.sessionRejected() }
277 }
278
279 /// Called as the step is about to change (`@Published` publishes before
280 /// the property is set), so `model.step` is still the previous one.
281 private func stepChanged(_ step: OficinaIDModel.Step) {
282 let previous = model.step
283 switch step {
284 case .signedIn(let state):
285 mounted = state
286 if case .signedIn = previous {} else if previous != .loading { signIns += 1 }
287 case .unavailable(let team) where mounted?.team.sqid == team.sqid && model.identity?.id == mounted?.identity.id:
288 break
289 default:
290 mounted = nil
291 }
292 if case .signedIn(let state) = step {
293 let account = Self.accountID(state)
294 let previous = sessions[account]?.session
295 if previous?.value != state.session.value {
296 sessions[account] = (state.session, state.client())
297 // A workspace whose outbox stopped on the old session's 401
298 // sends again with the new one.
299 if previous != nil { DocsOfflineAccount.sessionRestored(account) }
300 }
301 // Sessions of the identity's other teams stay, so their document
302 // windows keep working; another identity's never do.
303 sessions = sessions.filter { Self.account($0.key, belongsTo: state.identity.id) }
304 } else if model.identity == nil {
305 sessions.removeAll()
306 lastRejection.removeAll()
307 }
308 }
309}
310
311/// Why Docs won't sign out, switch team or replace the Oficina ID just now,
312/// in a line the person sees instead of a button that silently does nothing.
313public enum DocsLeaveBlock: Equatable, Sendable {
314 /// Changes on this device are still to be sent, in this window or in any
315 /// team of the identity (an outbox left by a crash included).
316 case sending
317 /// A document window of one of the identity's teams is open (Mac).
318 case openDocuments
319
320 public var message: String {
321 NSLocalizedString(self == .sending ? "native.leave.sending" : "native.leave.openDocuments",
322 bundle: DocsResources.bundle, comment: "")
323 }
324
325 /// The identity-wide guard: open document windows first, then anything
326 /// this window or any of the identity's teams has not sent.
327 @MainActor public static func check(identity: String, openDocuments: Bool, unsentHere: Bool = false) async -> DocsLeaveBlock? {
328 if openDocuments { return .openDocuments }
329 if unsentHere { return .sending }
330 return await DocsOfflineAccount.hasUnsent(identity: identity) ? .sending : nil
331 }
332}
333
334/// A transport that tells Docs when the instance refuses its session: a 401,
335/// or the 303 to sign-in that `NativeClientError` also reads as an ended
336/// session; and when it refuses a request, a 403. Everything else passes
337/// through untouched.
338///
339/// Docs' session guards answer a non-GET request whose session has ended
340/// (none, unknown, revoked, or a native session past its seven days) with
341/// 403 "signed out" (rastrillo sessions.Require, and Docs' identity guard:
342/// internal/docs/identity.go, sessionEndedBody), not 401. Read as a refused
343/// request, a window open past the session's seven days whose first request
344/// is a write would never re-mint, and its outbox would hold the change as
345/// access lost. That one 403 is an ended session, re-minted and surfaced as
346/// the 401 it means; internal/docs/native_contract_test.go pins the bytes.
347struct DocsSessionWatch: NativeTransport {
348 let inner: NativeTransport
349 let rejected: @Sendable () -> Void
350 /// A 403: refused this request, not the session. Docs refreshes the team
351 /// list on it (spec §9).
352 var refused: @Sendable () -> Void = {}
353
354 var origin: URL { inner.origin }
355
356 /// The session guards' refusal, byte for byte (`http.Error` adds the newline).
357 static let signedOut = Data("signed out\n".utf8)
358
359 func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse {
360 let reply = try await inner.responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes)
361 if reply.status == 403, reply.data == Self.signedOut {
362 rejected()
363 return NativeResponse(data: reply.data, status: 401, headers: reply.headers)
364 }
365 if reply.status == 401 || reply.status == 303 { rejected() }
366 if reply.status == 403 { refused() }
367 return reply
368 }
369
370 func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws {
371 do { try await inner.stream(path, onOpen: onOpen, onLine: onLine) }
372 catch NativeClientError.unauthorized { rejected(); throw NativeClientError.unauthorized }
373 }
374
375 func download(_ path: String, to destination: URL) async throws {
376 do { try await inner.download(path, to: destination) }
377 catch NativeClientError.unauthorized { rejected(); throw NativeClientError.unauthorized }
378 }
379}
380
381#if os(macOS)
382import Security
383
384/// The launch gate (spec §13, "Mac launch"): the final signed artifact must
385/// launch and read the shared group before any Sparkle publish, because a
386/// build killed at launch cannot update itself. Run the app's executable
387/// with `--oficina-id-launch-check`: macOS checks the embedded profile
388/// against the entitlements as it starts the process. This then checks the
389/// signed entitlements (keychain groups in order, the App Group, the
390/// associated domain) and reads, never writes, both keychain groups. It
391/// prints what it found and exits 0 only if all of it works. It prints
392/// counts, never an identity or a session.
393public enum DocsOficinaLaunchCheck {
394 public static let argument = "--oficina-id-launch-check"
395
396 public static func run() -> (passed: Bool, lines: [String]) {
397 var lines: [String] = [], passed = true
398 func check(_ name: String, _ body: () throws -> String) {
399 do { lines.append("ok \(name): \(try body())") }
400 catch { passed = false; lines.append("FAIL \(name): \(error)") }
401 }
402 let own = OficinaKeychainStore.appGroup(for: DocsOficinaSession.configuration.app)
403 check("keychain-access-groups") {
404 let groups = entitlement("keychain-access-groups")
405 // A query that names no group lands in the first: it must be Docs' own.
406 guard groups.first == own, groups.contains(OficinaKeychainStore.sharedGroup) else {
407 throw LaunchCheckError("expected [\(own), \(OficinaKeychainStore.sharedGroup)], got \(groups)")
408 }
409 return groups.joined(separator: ", ")
410 }
411 check("shared group \(OficinaKeychainStore.sharedGroup)") {
412 // The store Docs' onboarding reads at launch, records decoded.
413 let store = OficinaIDStore(shared: OficinaKeychainStore(accessGroup: OficinaKeychainStore.sharedGroup),
414 appPrivate: OficinaKeychainStore(accessGroup: own),
415 group: UserDefaults(suiteName: DocsOficinaSession.appGroup) ?? .standard)
416 return "readable, \(try store.identities().count) identities"
417 + " (\(store.unreadableIdentities().count) only a newer app can read)"
418 }
419 check("Docs' group \(own)") {
420 "readable, \(try OficinaKeychainStore(accessGroup: own).accounts(service: "works.oficina.id.session").count) sessions"
421 }
422 // On a Mac, containerURL answers for any app group, granted or not,
423 // so the entitlement itself is what proves the grant.
424 check("App Group \(DocsOficinaSession.appGroup)") {
425 let groups = entitlement("com.apple.security.application-groups")
426 guard groups.contains(DocsOficinaSession.appGroup) else {
427 throw LaunchCheckError("not granted: com.apple.security.application-groups is \(groups)")
428 }
429 guard UserDefaults(suiteName: DocsOficinaSession.appGroup) != nil else { throw LaunchCheckError("no defaults suite") }
430 return "granted"
431 }
432 check("associated domains") {
433 let domains = entitlement("com.apple.developer.associated-domains")
434 guard domains.contains("webcredentials:id.oficina.works") else { throw LaunchCheckError("got \(domains)") }
435 return domains.joined(separator: ", ")
436 }
437 return (passed, lines)
438 }
439
440 /// A string-array entitlement of this process, as signed.
441 static func entitlement(_ key: String) -> [String] {
442 guard let task = SecTaskCreateFromSelf(nil) else { return [] }
443 return SecTaskCopyValueForEntitlement(task, key as CFString, nil) as? [String] ?? []
444 }
445
446 struct LaunchCheckError: Error, CustomStringConvertible {
447 let description: String
448 init(_ description: String) { self.description = description }
449 }
450}
451#endif
452