Oficina ID is Docs' sign-in (slice A); PlainAppNameCommands; a Settings window titled Docs; a launch check
Human
Prompt
3. Adopt the Oficina ID onboarding as the primary sign-in in Docs (Mac + iOS), keeping the existing server-address/browser sign-in under "Other ways to sign in…" per spec. One identity in slice A. Docs' team picker uses the kit's team list. Keep existing accounts working (migration per spec Appendix C: old per-app sessions remain until replaced). 4. Adopt PlainAppNameCommands (first in .commands), add "localizations" (Docs' 12 languages) to mac-updates.json, set the Settings window's navigationTitle to "Docs". 6. Build and run on this Mac: a Developer ID-signed Sparkle build with the profile embedded must launch (spec's launch gate) and the shared keychain must work
From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.
Summary
DocsOficinaSession wraps the kit's OficinaIDModel.live: one model per app, started once; workspaces are keyed oficina-id.<identity>.<team> and read their team's latest session on every request, so a 24-hour or 401 re-mint carries the offline store and outbox through (a 401 or 303 from the instance calls sessionRejected, at most once a minute per account; the drainer is restored after). DocsAccountWindow shows OficinaOnboardingView until signed in; Other ways to sign in… is the old NativeAccountsView/NativeSignInView with Sign in with Oficina ID beneath; DocsSignInRoute keeps anyone already signed in the old way on it until an Oficina ID replaces it (Appendix C). The toolbar's Accounts becomes Teams: DocsTeamPicker lists the kit's cached teams that have Docs, Other ways, and Sign out of <label> (guarded by unsent changes and open document windows of any of the identity's teams). The passkey nudge sits under the workspace; renewIfNeeded runs when a scene becomes active. Mac: PlainAppNameCommands first in .commands; Settings { DocsSettingsView } with .navigationTitle(Docs), the account and version. DocsMac --oficina-id-launch-check reads the entitlement order, both keychain groups and the App Group and exits 0 only if all work (spec §13 launch gate). Ten new strings in all twelve languages; the kit's own strings stay English until its review.Agent notes
Verified on this Mac (macOS 27): the Developer ID build with the profile embedded launches (taskgated-helper: allowing entitlements for works.oficina.docs due to provisioning profile) and its launch check passes; an ad hoc build fails it with -34018; a Developer ID probe signed as works.oficina.sheets wrote an identity to the shared group and the real Docs artifact read and decoded it, then the probe removed it. Not exercised: any network sign-in (Home's native endpoints are not deployed), real passkeys, iOS on a device.
21 files changed,
+1,000
−38
native/apple/Sources/DocsApp/DocsAccountWindow.swift+173 −31native/apple/Sources/DocsApp/DocsApp.swift+38 −3native/apple/Sources/DocsApp/DocsDocumentWindow.swift+1 −1native/apple/Sources/DocsApp/DocsWindows.swift+9 −0native/apple/Sources/DocsKit/DocsOfflineAccount.swift+3 −0native/apple/Sources/DocsKit/DocsOficinaID.swift+241 −0native/apple/Sources/DocsKit/DocsOficinaViews.swift+181 −0native/apple/Sources/DocsKit/DocsWorkspace.swift+21 −3native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings+12 −0native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings+12 −0native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings+12 −0native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings+12 −0native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings+12 −0native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings+12 −0native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings+12 −0native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings+12 −0native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings+12 −0native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings+12 −0native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings+12 −0native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings+12 −0native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift+189 −0
CI passed — run details
diff --git a/native/apple/Sources/DocsApp/DocsAccountWindow.swift b/native/apple/Sources/DocsApp/DocsAccountWindow.swift| index 472739f..80ba56c 100644 |
| --- a/native/apple/Sources/DocsApp/DocsAccountWindow.swift |
| +++ b/native/apple/Sources/DocsApp/DocsAccountWindow.swift |
| @@ -4,12 +4,37 @@ import SwiftUI |
| /// Each window owns its navigation and model lifetime. Switching an account in |
| /// one window must never discard another window's unconfirmed edits. |
| +/// |
| +/// Sign-in is Oficina ID first (spec 2026-11-14-oficina-id-native, slice A): |
| +/// the kit's onboarding until its model is signed in to a team, then that |
| +/// team's workspace. "Other ways to sign in…" is the server address and |
| +/// browser approval that came before, kept for self-hosted servers and local |
| +/// accounts; someone already signed in that way keeps those accounts until an |
| +/// Oficina ID replaces them (`DocsSignInRoute`). |
| struct DocsAccountWindow: View { |
| + let oficina: DocsOficinaSession |
| + @ObservedObject private var model: OficinaIDModel |
| @StateObject private var connection = NativeConnection(defaultServer: "https://docs.oficina.works") |
| + @AppStorage(DocsSignInRoute.key) private var storedRoute = "" |
| + @State private var pickingTeam = false |
| + @Environment(\.scenePhase) private var scenePhase |
| #if os(macOS) |
| @Bindable var windows: DocsWindows |
| @Environment(\.openWindow) private var openWindow |
| #endif |
| + |
| + #if os(macOS) |
| + init(oficina: DocsOficinaSession, windows: DocsWindows) { |
| + self.oficina = oficina; _model = ObservedObject(wrappedValue: oficina.model); _windows = Bindable(windows) |
| + } |
| + #else |
| + init(oficina: DocsOficinaSession) { self.oficina = oficina; _model = ObservedObject(wrappedValue: oficina.model) } |
| + #endif |
| + |
| + private var route: DocsSignInRoute { |
| + DocsSignInRoute.resolve(stored: storedRoute, hasServerAccounts: !connection.accounts.isEmpty) |
| + } |
| + |
| private func transport(for account: String?) -> @MainActor () -> NativeTransport? { |
| let connection = connection |
| return DocsAccountTransport.supplier(account: account, |
| @@ -19,41 +44,158 @@ struct DocsAccountWindow: View { |
| var body: some View { |
| Group { |
| - if let client = connection.client { |
| - #if os(macOS) |
| - if let account = connection.activeAccountID { |
| - DocsWorkspace(client: client, accountID: account, transport: transport(for: account), accounts: connection.showAccounts, signOut: { |
| - guard connection.activeAccountID == account, windows.canSignOut(account) else { return } |
| - windows.entries.removeAll { $0.account == account } |
| - connection.signOut() |
| - }, createDocument: { |
| - guard connection.activeAccountID == account else { return } |
| - let id = windows.reserveDraft(account: account, client: client) |
| - openWindow(id: "document", value: id) |
| - }, canSignOut: windows.canSignOut(account), createRequested: $windows.createRequested, accountsRequested: $windows.accountsRequested, openDocument: { document, title in |
| - guard connection.activeAccountID == account else { return } |
| - let id = windows.reserve(account: account, document: document, title: title, client: client) |
| - openWindow(id: "document", value: id) |
| - }, updateRecents: { documents in |
| - guard connection.activeAccountID == account else { return } |
| - windows.updateRecents(documents, account: account, client: client) |
| - }) |
| - .id(account) |
| - } |
| - #else |
| - DocsWorkspace(client: client, accountID: connection.activeAccountID, transport: transport(for: connection.activeAccountID), accounts: connection.showAccounts, signOut: connection.signOut) |
| - .id(connection.activeAccountID) |
| - #endif |
| - } else { |
| - NativeAccountsView("Docs", systemImage: "doc.text", connection: connection) |
| + switch route { |
| + case .oficinaID: |
| + if case .signedIn(let state) = model.step { oficinaWorkspace(state) } |
| + else { OficinaOnboardingView(model: model, otherWays: { storedRoute = DocsSignInRoute.server.rawValue }) } |
| + case .server: |
| + if let client = connection.client { serverWorkspace(client) } |
| + else { DocsOtherWaysView(connection: connection) { storedRoute = DocsSignInRoute.oficinaID.rawValue } } |
| } |
| - }.onOpenURL(perform: connection.handleOpenURL) |
| + } |
| + .onOpenURL(perform: connection.handleOpenURL) |
| + .task { await oficina.start() } |
| + // A sign-in with Oficina ID replaces the other ways for good (Appendix C). |
| + .onChange(of: oficina.signedIn?.identity.id, initial: true) { _, identity in |
| + if identity != nil { storedRoute = DocsSignInRoute.oficinaID.rawValue } |
| + } |
| + .onChange(of: scenePhase) { _, phase in |
| + if phase == .active { Task { await oficina.renewIfNeeded() } } |
| + } |
| #if os(macOS) |
| .onChange(of: windows.accountsRequested, initial: true) { _, requested in |
| - if requested && connection.client == nil { windows.accountsRequested = false } |
| + if requested && currentClient == nil { windows.accountsRequested = false } |
| + } |
| + .onChange(of: windows.signOutRequested, initial: true) { _, requested in |
| + if requested && currentClient == nil { windows.signOutRequested = false } |
| + } |
| + .focusedSceneValue(\.docsWindowAccount, currentAccount) |
| + .onChange(of: currentAccount, initial: true) { _, value in windows.activeAccount = value } |
| + .onChange(of: settingsAccount, initial: true) { _, value in windows.settingsAccount = value } |
| + #endif |
| + } |
| + |
| + private var currentAccount: String? { |
| + switch route { |
| + case .oficinaID: return oficina.signedIn.map(DocsOficinaSession.accountID) |
| + case .server: return connection.activeAccountID |
| + } |
| + } |
| + |
| + private var currentClient: NativeHTTP? { |
| + switch route { |
| + case .oficinaID: return oficina.signedIn.flatMap { oficina.client(for: DocsOficinaSession.accountID($0)) } |
| + case .server: return connection.client |
| + } |
| + } |
| + |
| + // MARK: Oficina ID |
| + |
| + @ViewBuilder private func oficinaWorkspace(_ state: OficinaSignedIn) -> some View { |
| + let account = DocsOficinaSession.accountID(state) |
| + let client = oficina.client(for: account) ?? state.client() |
| + #if os(macOS) |
| + let canLeave = !windows.entries.contains { DocsOficinaSession.account($0.account, belongsTo: state.identity.id) && $0.isOpen } |
| + DocsWorkspace(client: client, accountID: account, transport: oficina.transport(for: account), accounts: { pickingTeam = true }, signOut: { |
| + signOutOficinaID(state) |
| + }, createDocument: { |
| + guard currentAccount == account else { return } |
| + let id = windows.reserveDraft(account: account, client: client) |
| + openWindow(id: "document", value: id) |
| + }, canSignOut: canLeave, createRequested: $windows.createRequested, accountsRequested: $windows.accountsRequested, |
| + signOutRequested: $windows.signOutRequested, accountsLabel: teamsLabel, signOutLabel: OficinaIDText.text("signOut", state.identity.label), |
| + openDocument: { document, title in |
| + guard currentAccount == account else { return } |
| + let id = windows.reserve(account: account, document: document, title: title, client: client) |
| + openWindow(id: "document", value: id) |
| + }, updateRecents: { documents in |
| + guard currentAccount == account else { return } |
| + windows.updateRecents(documents, account: account, client: client) |
| + }) |
| + .id(account) |
| + .onAppear { windows.transports[account] = oficina.transport(for: account) } |
| + .safeAreaInset(edge: .bottom, spacing: 0) { passkeyNudge } |
| + .sheet(isPresented: $pickingTeam) { teamPicker(state, canLeave: canLeave) } |
| + #else |
| + DocsWorkspace(client: client, accountID: account, transport: oficina.transport(for: account), accounts: { pickingTeam = true }, |
| + signOut: { signOutOficinaID(state) }, accountsLabel: teamsLabel, |
| + signOutLabel: OficinaIDText.text("signOut", state.identity.label)) |
| + .id(account) |
| + .safeAreaInset(edge: .bottom, spacing: 0) { passkeyNudge } |
| + .sheet(isPresented: $pickingTeam) { teamPicker(state, canLeave: true) } |
| + #endif |
| + } |
| + |
| + private var teamsLabel: String { DocsOficinaSession.teamsTitle } |
| + |
| + @ViewBuilder private var passkeyNudge: some View { |
| + if model.offerPasskey { OficinaPasskeyNudge(model: model).padding(12) } |
| + } |
| + |
| + private func teamPicker(_ state: OficinaSignedIn, canLeave: Bool) -> some View { |
| + DocsTeamPicker(model: model, current: state, canLeave: canLeave, otherWays: { |
| + pickingTeam = false |
| + storedRoute = DocsSignInRoute.server.rawValue |
| + }, signOut: { |
| + pickingTeam = false |
| + signOutOficinaID(state) |
| + }, done: { pickingTeam = false }) |
| + } |
| + |
| + /// "Sign out of <label>": every team of the identity, on every Oficina app |
| + /// on this device (spec §10), after Docs' own guard: the workspace refuses |
| + /// while anything is unsent, and the Mac while a document window of any |
| + /// of the identity's teams is open. |
| + private func signOutOficinaID(_ state: OficinaSignedIn) { |
| + #if os(macOS) |
| + guard !windows.entries.contains(where: { DocsOficinaSession.account($0.account, belongsTo: state.identity.id) && $0.isOpen }) else { return } |
| + windows.entries.removeAll { DocsOficinaSession.account($0.account, belongsTo: state.identity.id) } |
| + windows.transports = windows.transports.filter { !DocsOficinaSession.account($0.key, belongsTo: state.identity.id) } |
| + #endif |
| + model.signOut() |
| + } |
| + |
| + // MARK: Other ways (server address) |
| + |
| + @ViewBuilder private func serverWorkspace(_ client: NativeHTTP) -> some View { |
| + #if os(macOS) |
| + if let account = connection.activeAccountID { |
| + DocsWorkspace(client: client, accountID: account, transport: transport(for: account), accounts: connection.showAccounts, signOut: { |
| + guard connection.activeAccountID == account, windows.canSignOut(account) else { return } |
| + windows.entries.removeAll { $0.account == account } |
| + connection.signOut() |
| + }, createDocument: { |
| + guard connection.activeAccountID == account else { return } |
| + let id = windows.reserveDraft(account: account, client: client) |
| + openWindow(id: "document", value: id) |
| + }, canSignOut: windows.canSignOut(account), createRequested: $windows.createRequested, accountsRequested: $windows.accountsRequested, |
| + signOutRequested: $windows.signOutRequested, openDocument: { document, title in |
| + guard connection.activeAccountID == account else { return } |
| + let id = windows.reserve(account: account, document: document, title: title, client: client) |
| + openWindow(id: "document", value: id) |
| + }, updateRecents: { documents in |
| + guard connection.activeAccountID == account else { return } |
| + windows.updateRecents(documents, account: account, client: client) |
| + }) |
| + .id(account) |
| } |
| - .focusedSceneValue(\.docsWindowAccount, connection.activeAccountID) |
| - .onChange(of: connection.activeAccountID, initial: true) { _, value in windows.activeAccount = value } |
| + #else |
| + DocsWorkspace(client: client, accountID: connection.activeAccountID, transport: transport(for: connection.activeAccountID), accounts: connection.showAccounts, signOut: connection.signOut) |
| + .id(connection.activeAccountID) |
| #endif |
| } |
| + |
| + #if os(macOS) |
| + private var settingsAccount: DocsSettingsView.Account { |
| + switch route { |
| + case .oficinaID: |
| + guard let state = oficina.signedIn else { return .none } |
| + return .oficinaID(identity: state.identity.label, team: state.team.name, teamLabel: state.team.label) |
| + case .server: |
| + guard let client = connection.client else { return .none } |
| + let name = connection.accounts.first { $0.id == connection.activeAccountID }?.name ?? "" |
| + return .server(name: name, host: client.origin.host ?? client.origin.absoluteString) |
| + } |
| + } |
| + #endif |
| } |
diff --git a/native/apple/Sources/DocsApp/DocsApp.swift b/native/apple/Sources/DocsApp/DocsApp.swift| index c529b74..9ebb74e 100644 |
| --- a/native/apple/Sources/DocsApp/DocsApp.swift |
| +++ b/native/apple/Sources/DocsApp/DocsApp.swift |
| @@ -12,15 +12,32 @@ import SwiftUI |
| @State private var windows = DocsWindows() |
| @NSApplicationDelegateAdaptor(DocsApplicationDelegate.self) private var appDelegate |
| #endif |
| + /// One Oficina ID model for the whole app (slice A: one identity), read |
| + /// from the keychain once at launch, whichever window asks first. |
| + @StateObject private var oficina = DocsOficinaSession.live() |
| /// Every bundled face is registered here, synchronously, before the |
| /// first window exists, so no text view ever lays out with a face |
| /// missing (polish-audit/fonts/NO-FOUT.md §7). |
| - init() { DocsFonts.register() } |
| + init() { |
| + #if os(macOS) |
| + // The launch gate: run the signed executable with this argument. |
| + if CommandLine.arguments.contains(DocsOficinaLaunchCheck.argument) { |
| + let result = DocsOficinaLaunchCheck.run() |
| + result.lines.forEach { print($0) } |
| + exit(result.passed ? 0 : 1) |
| + } |
| + #endif |
| + DocsFonts.register() |
| + } |
| var body: some Scene { |
| #if os(macOS) |
| - Window(docsMacString("Home"), id: "home") { DocsAccountWindow(windows: windows) } |
| + Window(docsMacString("Home"), id: "home") { DocsAccountWindow(oficina: oficina, windows: windows) } |
| .defaultSize(width: 1000, height: 760) |
| .commands { |
| + // First: About, Hide, Quit say "Docs", not the Finder name, and the |
| + // groups after it (Check for Updates, the Colophon) survive |
| + // (rastrillo/native docs/mac-updates.md). |
| + PlainAppNameCommands() |
| DocsWindowCommands(windows: windows) |
| DocsEditorCommands() |
| #if canImport(RastrilloMacUpdates) |
| @@ -36,8 +53,26 @@ import SwiftUI |
| // the typefaces' licences among it. |
| Window(DocsColophonView.title, id: "colophon") { DocsColophonView() } |
| .defaultSize(width: 680, height: 760) |
| + Settings { DocsSettingsWindow(windows: windows) } |
| #else |
| - WindowGroup { DocsAccountWindow() } |
| + WindowGroup { DocsAccountWindow(oficina: oficina) } |
| #endif |
| } |
| } |
| + |
| +#if os(macOS) |
| +/// Docs ▸ Settings… (⌘,): the home window's account and the version. Its |
| +/// buttons ask the home window, which holds the guards against stranding |
| +/// unsent changes. |
| +struct DocsSettingsWindow: View { |
| + let windows: DocsWindows |
| + @Environment(\.openWindow) private var openWindow |
| + var body: some View { |
| + DocsSettingsView(account: windows.settingsAccount, canSignOut: windows.canSignOut(windows.activeAccount), manage: { |
| + windows.accountsRequested = true; openWindow(id: "home") |
| + }, signOut: { |
| + windows.signOutRequested = true; openWindow(id: "home") |
| + }, signIn: { openWindow(id: "home") }) |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/DocsApp/DocsDocumentWindow.swift b/native/apple/Sources/DocsApp/DocsDocumentWindow.swift| index 941e00d..b5ce9e2 100644 |
| --- a/native/apple/Sources/DocsApp/DocsDocumentWindow.swift |
| +++ b/native/apple/Sources/DocsApp/DocsDocumentWindow.swift |
| @@ -8,7 +8,7 @@ struct DocsDocumentWindow: View { |
| @Environment(\.openWindow) private var openWindow |
| var body: some View { |
| if let entry = windows.entries.first(where: { $0.id == id }) { |
| - DocsWorkspace(client: entry.client, accountID: entry.account, signOut: {}, documentID: entry.document, newDocument: entry.isDraft, documentChanged: { document, title in windows.attach(entry.id, document: document, title: title) }) |
| + DocsWorkspace(client: entry.client, accountID: entry.account, transport: windows.transports[entry.account], signOut: {}, documentID: entry.document, newDocument: entry.isDraft, documentChanged: { document, title in windows.attach(entry.id, document: document, title: title) }) |
| .id(entry.id) |
| .focusedSceneValue(\.docsWindowAccount, entry.account) |
| .onAppear { windows.setOpen(entry.id, true) } |
diff --git a/native/apple/Sources/DocsApp/DocsWindows.swift b/native/apple/Sources/DocsApp/DocsWindows.swift| index 41a682d..59589fc 100644 |
| --- a/native/apple/Sources/DocsApp/DocsWindows.swift |
| +++ b/native/apple/Sources/DocsApp/DocsWindows.swift |
| @@ -20,6 +20,15 @@ import SwiftUI |
| var activeAccount: String? |
| var createRequested = false |
| var accountsRequested = false |
| + /// Settings' "Sign out", carried out by the home window's guard. |
| + var signOutRequested = false |
| + /// What Settings shows: the home window's account. |
| + var settingsAccount: DocsSettingsView.Account = .none |
| + /// Oficina ID accounts' transports, so a document window reads the |
| + /// latest session of its team (re-minted every 24 hours and on a 401) |
| + /// rather than the one it opened with. Server accounts have none: their |
| + /// windows keep the client they were opened with, as before. |
| + var transports: [String: @MainActor () -> NativeTransport?] = [:] |
| func reserve(account: String, document: String, title: String, client: NativeHTTP) -> UUID { |
| if let index = entries.firstIndex(where: { $0.account == account && $0.client.origin == client.origin && $0.document == document }) { |
| var entry = entries.remove(at: index) |
diff --git a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift| index b8faef2..630ccb6 100644 |
| --- a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift |
| +++ b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift |
| @@ -27,6 +27,9 @@ struct DocsOfflineMetadata: Codable { |
| let account = DocsOfflineAccount(store: store, accountID: id, connectivity: .shared, transport: transport ?? { fallback }) |
| accounts[id] = account; return account |
| } |
| + /// The account's session was replaced (Oficina ID re-minted it): an |
| + /// outbox that stopped on the old one's 401 sends again. |
| + static func sessionRestored(_ id: String) { accounts[id]?.drainer.sessionRestored() } |
| init(store: BlobStore, accountID: String, connectivity: NativeConnectivity, transport: @escaping @MainActor () -> NativeTransport?) { |
| self.store = store; outbox = Outbox(store: store, account: accountID) |
| replicaCache = DocsReplicaCache(store: store) |
diff --git a/native/apple/Sources/DocsKit/DocsOficinaID.swift b/native/apple/Sources/DocsKit/DocsOficinaID.swift| new file mode 100644 |
| index 0000000..7378956 |
| --- /dev/null |
| +++ b/native/apple/Sources/DocsKit/DocsOficinaID.swift |
| @@ -0,0 +1,241 @@ |
| +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. |
| + 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. |
| +@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 renewing = false |
| + private var started = false |
| + private var watch: AnyCancellable? |
| + private let now: () -> Date |
| + |
| + nonisolated public static let configuration = OficinaIDConfiguration(app: "docs", appName: "Docs") |
| + |
| + /// "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. |
| + public func start() async { |
| + guard !started else { return } |
| + started = true |
| + await model.start() |
| + } |
| + |
| + /// 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) |
| + } |
| + |
| + public static func accountID(identity: String, team: String) -> String { |
| + // Identity IDs and sqids are base64url and sqid characters, never ".". |
| + "oficina-id." + identity + "." + team |
| + } |
| + |
| + /// Whether `account` is one of `identity`'s teams: signing out of an |
| + /// identity ends all of them. |
| + public static func account(_ account: String, belongsTo identity: String) -> Bool { |
| + account.hasPrefix("oficina-id." + identity + ".") |
| + } |
| + |
| + /// 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 client = self.sessions[account]?.client else { return nil } |
| + return DocsSessionWatch(inner: client) { [weak self] in |
| + Task { @MainActor in await self?.rejected(account) } |
| + } |
| + } |
| + } |
| + |
| + /// Re-mints a session older than 24 hours; call when a scene comes back. |
| + public func renewIfNeeded() async { |
| + guard !renewing else { return } |
| + renewing = true |
| + defer { renewing = false } |
| + await model.renewIfNeeded() |
| + } |
| + |
| + /// The instance refused the session. 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. |
| + func rejected(_ account: String) async { |
| + guard let state = signedIn, Self.accountID(state) == account, !renewing else { return } |
| + if let last = lastRejection[account], now().timeIntervalSince(last) < 60 { return } |
| + lastRejection[account] = now() |
| + renewing = true |
| + defer { renewing = false } |
| + await model.sessionRejected() |
| + } |
| + |
| + private func stepChanged(_ step: OficinaIDModel.Step) { |
| + 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() |
| + } |
| + } |
| +} |
| + |
| +/// 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. Everything else passes through untouched. |
| +struct DocsSessionWatch: NativeTransport { |
| + let inner: NativeTransport |
| + let rejected: @Sendable () -> Void |
| + |
| + var origin: URL { inner.origin } |
| + |
| + 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 == 401 || reply.status == 303 { rejected() } |
| + 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, then this reads (and |
| +/// never writes) the two keychain groups and the App Group, 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 task = SecTaskCreateFromSelf(nil) |
| + let groups = task.flatMap { SecTaskCopyValueForEntitlement($0, "keychain-access-groups" as CFString, nil) } as? [String] ?? [] |
| + // 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" |
| + } |
| + check("App Group \(DocsOficinaSession.appGroup)") { |
| + guard FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: DocsOficinaSession.appGroup) != nil, |
| + UserDefaults(suiteName: DocsOficinaSession.appGroup) != nil else { throw LaunchCheckError("no container") } |
| + return "container available" |
| + } |
| + return (passed, lines) |
| + } |
| + |
| + struct LaunchCheckError: Error, CustomStringConvertible { |
| + let description: String |
| + init(_ description: String) { self.description = description } |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/DocsKit/DocsOficinaViews.swift b/native/apple/Sources/DocsKit/DocsOficinaViews.swift| new file mode 100644 |
| index 0000000..07bfd35 |
| --- /dev/null |
| +++ b/native/apple/Sources/DocsKit/DocsOficinaViews.swift |
| @@ -0,0 +1,181 @@ |
| +import RastrilloApple |
| +import SwiftUI |
| + |
| +/// Docs' team picker for an Oficina ID (spec §9): the kit's team list for |
| +/// the identity, from its team cache, filtered to teams that have Docs. The |
| +/// several-identities account menu is slice A2; this is one identity's teams. |
| +@MainActor public struct DocsTeamPicker: View { |
| + @ObservedObject private var model: OficinaIDModel |
| + private let current: OficinaSignedIn |
| + private let canLeave: Bool |
| + private let otherWays: () -> Void |
| + private let signOut: () -> Void |
| + private let done: () -> Void |
| + |
| + /// `canLeave` is false while the workspace has unsent changes or open |
| + /// document windows: switching team or signing out would strand them. |
| + public init(model: OficinaIDModel, current: OficinaSignedIn, canLeave: Bool, |
| + otherWays: @escaping () -> Void, signOut: @escaping () -> Void, done: @escaping () -> Void) { |
| + self.model = model; self.current = current; self.canLeave = canLeave |
| + self.otherWays = otherWays; self.signOut = signOut; self.done = done |
| + } |
| + |
| + /// The cached teams that have Docs, the current one always among them. |
| + public static func teams(_ cached: [OficinaTeam]?, current: OficinaTeam) -> [OficinaTeam] { |
| + var teams = (cached ?? []).filter { $0.origin(for: DocsOficinaSession.configuration.app) != nil } |
| + if !teams.contains(where: { $0.sqid == current.sqid }) { teams.append(current) } |
| + return teams.sorted { ($0.name.localizedLowercase, $0.sqid) < ($1.name.localizedLowercase, $1.sqid) } |
| + } |
| + |
| + private var teams: [OficinaTeam] { Self.teams(model.store.teams(current.identity.id)?.teams, current: current.team) } |
| + |
| + public var body: some View { |
| + NavigationStack { |
| + List { |
| + Section { |
| + OficinaIdentityRow(identity: current.identity, accent: .docs) |
| + } header: { Text(verbatim: "Oficina ID") } |
| + Section { |
| + ForEach(teams) { team in |
| + Button { choose(team) } label: { |
| + HStack(spacing: 8) { |
| + OficinaTeamRow(team: team) |
| + Image(systemName: "checkmark").foregroundStyle(OficinaPalette.accent(.docs)) |
| + .opacity(team.sqid == current.team.sqid ? 1 : 0).accessibilityHidden(true) |
| + } |
| + } |
| + .buttonStyle(.plain) |
| + .disabled(team.sqid != current.team.sqid && (!canLeave || model.busy)) |
| + .accessibilityAddTraits(team.sqid == current.team.sqid ? .isSelected : []) |
| + .accessibilityIdentifier("docs.team-\(team.label)") |
| + } |
| + } header: { Text("native.oficinaid.teams", bundle: DocsResources.bundle) } |
| + Section { |
| + Button(OficinaIDText.text("otherWays")) { otherWays() } |
| + .accessibilityIdentifier("docs.otherWays") |
| + Button(role: .destructive) { signOut() } label: { |
| + Text(verbatim: OficinaIDText.text("signOut", current.identity.label)) |
| + } |
| + .disabled(!canLeave) |
| + .accessibilityIdentifier("docs.oficinaid.signOut") |
| + } |
| + } |
| + .navigationTitle(Text("native.oficinaid.teams", bundle: DocsResources.bundle)) |
| + #if os(iOS) |
| + .navigationBarTitleDisplayMode(.inline) |
| + #endif |
| + .toolbar { |
| + ToolbarItem(placement: .confirmationAction) { |
| + Button { done() } label: { Text("native.done", bundle: DocsResources.bundle) } |
| + } |
| + } |
| + } |
| + .tint(OficinaPalette.accent(.docs)) |
| + #if os(macOS) |
| + .frame(minWidth: 420, idealWidth: 460, minHeight: 440, idealHeight: 520) |
| + #endif |
| + } |
| + |
| + private func choose(_ team: OficinaTeam) { |
| + done() |
| + guard team.sqid != current.team.sqid else { return } |
| + Task { await model.choose(team) } |
| + } |
| +} |
| + |
| +/// "Other ways to sign in…": the server address and browser approval that |
| +/// stay for self-hosted servers and local accounts (spec §11), with the way |
| +/// back to Oficina ID beneath. |
| +@MainActor public struct DocsOtherWaysView: View { |
| + @ObservedObject private var connection: NativeConnection |
| + private let oficinaID: () -> Void |
| + |
| + public init(connection: NativeConnection, oficinaID: @escaping () -> Void) { |
| + self.connection = connection; self.oficinaID = oficinaID |
| + } |
| + |
| + public var body: some View { |
| + NativeAccountsView("Docs", systemImage: "doc.text", connection: connection) |
| + .safeAreaInset(edge: .bottom, spacing: 0) { |
| + Button { connection.cancel(); oficinaID() } label: { |
| + Label { Text("native.oficinaid.signin", bundle: DocsResources.bundle) } icon: { Image(systemName: "person.crop.circle") } |
| + } |
| + .buttonStyle(.borderless) |
| + .accessibilityIdentifier("docs.oficinaid.signin") |
| + .padding(16) |
| + .frame(maxWidth: .infinity) |
| + } |
| + } |
| +} |
| + |
| +#if os(macOS) |
| +/// Docs ▸ Settings: who Docs is signed in as, and the version. SwiftUI would |
| +/// title the window "Oficina Docs Settings" from the display name; the plain |
| +/// name comes from the content's navigation title (rastrillo/native |
| +/// docs/mac-updates.md, "Not covered: the Settings window"). |
| +public struct DocsSettingsView: View { |
| + public enum Account: Equatable { |
| + case oficinaID(identity: String, team: String, teamLabel: String) |
| + case server(name: String, host: String) |
| + case none |
| + } |
| + |
| + private let account: Account |
| + private let canSignOut: Bool |
| + private let manage: () -> Void |
| + private let signOut: () -> Void |
| + private let signIn: () -> Void |
| + private let version: String |
| + |
| + public init(account: Account, canSignOut: Bool, version: String = DocsSettingsView.bundleVersion, |
| + manage: @escaping () -> Void, signOut: @escaping () -> Void, signIn: @escaping () -> Void) { |
| + self.account = account; self.canSignOut = canSignOut; self.version = version |
| + self.manage = manage; self.signOut = signOut; self.signIn = signIn |
| + } |
| + |
| + public static var bundleVersion: String { |
| + let info = Bundle.main.infoDictionary ?? [:] |
| + let short = info["CFBundleShortVersionString"] as? String ?? "0.1.0" |
| + return (info["CFBundleVersion"] as? String).map { "\(short) (\($0))" } ?? short |
| + } |
| + |
| + public var body: some View { |
| + Form { |
| + Section { |
| + switch account { |
| + case .oficinaID(let identity, let team, let teamLabel): |
| + LabeledContent { Text(verbatim: identity).textSelection(.enabled) } label: { Text(verbatim: "Oficina ID") } |
| + LabeledContent { Text(verbatim: "\(team) (\(teamLabel))") } label: { Text("native.settings.team", bundle: DocsResources.bundle) } |
| + HStack { |
| + Button { manage() } label: { Text("native.settings.changeTeam", bundle: DocsResources.bundle) } |
| + Spacer() |
| + Button(role: .destructive) { signOut() } label: { Text(verbatim: OficinaIDText.text("signOut", identity)) } |
| + .disabled(!canSignOut) |
| + } |
| + case .server(let name, let host): |
| + LabeledContent { Text(verbatim: name.isEmpty ? host : "\(name) (\(host))").textSelection(.enabled) } label: { |
| + Text("native.settings.server", bundle: DocsResources.bundle) |
| + } |
| + HStack { |
| + Button { manage() } label: { Text("native.settings.accounts", bundle: DocsResources.bundle) } |
| + Spacer() |
| + Button(role: .destructive) { signOut() } label: { Text("docs.signout.label", bundle: DocsResources.bundle) } |
| + .disabled(!canSignOut) |
| + } |
| + case .none: |
| + LabeledContent { Text("native.settings.signedOut", bundle: DocsResources.bundle) } label: { Text(verbatim: "Oficina ID") } |
| + Button { signIn() } label: { Text("native.settings.signIn", bundle: DocsResources.bundle) } |
| + } |
| + } header: { Text("native.settings.account", bundle: DocsResources.bundle) } |
| + Section { |
| + LabeledContent { Text(verbatim: version) } label: { Text("native.colophon.version", bundle: DocsResources.bundle) } |
| + } |
| + } |
| + .formStyle(.grouped) |
| + .frame(width: 480) |
| + .fixedSize(horizontal: false, vertical: true) |
| + .navigationTitle(Text("native.docs", bundle: DocsResources.bundle)) |
| + .tint(OficinaPalette.accent(.docs)) |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift| index 2559fcf..ad98569 100644 |
| --- a/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| +++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| @@ -21,6 +21,11 @@ import SwiftUI |
| private let updateRecents: (([(String, String)]) -> Void)? |
| private let canSignOut: Bool |
| @Binding private var accountsRequested: Bool |
| + @Binding private var signOutRequested: Bool |
| + /// Oficina ID's words for the account controls: "Teams" and |
| + /// "Sign out of <label>". nil keeps the server sign-in's own. |
| + private let accountsLabel: String? |
| + private let signOutLabel: String? |
| @Binding private var createRequested: Bool |
| private let documentID: String? |
| private let openDocument: ((String, String) -> Void)? |
| @@ -31,7 +36,8 @@ import SwiftUI |
| private let client: NativeHTTP |
| /// `transport` supplies the account's current session to the model on every |
| /// request; without one the model keeps `client` for its whole lifetime. |
| - public init(client: NativeHTTP, accountID: String? = nil, transport: (@MainActor () -> NativeTransport?)? = nil, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil) { |
| + public init(client: NativeHTTP, accountID: String? = nil, transport: (@MainActor () -> NativeTransport?)? = nil, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), signOutRequested: Binding<Bool> = .constant(false), accountsLabel: String? = nil, signOutLabel: String? = nil, openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil) { |
| + self._signOutRequested = signOutRequested; self.accountsLabel = accountsLabel; self.signOutLabel = signOutLabel |
| self.updateRecents = updateRecents; self.canSignOut = canSignOut; self._createRequested = createRequested; self._accountsRequested = accountsRequested; self.documentID = documentID; self.openDocument = openDocument |
| self.newDocument = newDocument; self.createDocument = createDocument; self.documentChanged = documentChanged |
| let offline = accountID.map { DocsOfflineAccount.account($0, origin: client.origin, fallback: client, transport: transport) } |
| @@ -51,14 +57,15 @@ import SwiftUI |
| .toolbar { |
| if let accounts { |
| ToolbarItem(placement: .navigation) { |
| - Button(docsMacString("Accounts"), systemImage: "chevron.backward", action: accounts).disabled(model.hasUnsavedChanges || model.creatingDocument) |
| + Button(accountsLabel ?? docsMacString("Accounts"), systemImage: accountsLabel == nil ? "chevron.backward" : "person.crop.circle", action: accounts).disabled(model.hasUnsavedChanges || model.creatingDocument) |
| + .accessibilityIdentifier("docs.accounts") |
| } |
| } |
| ToolbarItemGroup { |
| DocsJumpControls(presented: $jumping) |
| if model.canCreate { Button { beginDocument() } label: { Label { Text("docs.list.create.label", bundle: DocsResources.bundle) } icon: { Image(systemName: "plus") } }.accessibilityIdentifier("docs.create") } |
| - Button { if !model.hasUnsavedChanges && !model.creatingDocument { signOut() } } label: { Text("docs.signout.label", bundle: DocsResources.bundle) }.disabled(model.hasUnsavedChanges || model.creatingDocument) |
| + Button { if !model.hasUnsavedChanges && !model.creatingDocument { signOut() } } label: { signOutText }.disabled(model.hasUnsavedChanges || model.creatingDocument) |
| #if os(iOS) |
| // The Colophon, beside Sign out: the iPhone app has no |
| // settings screen of its own. The Mac has it in the Help menu. |
| @@ -99,6 +106,13 @@ import SwiftUI |
| .onChange(of: accountsRequested && !model.creatingDocument, initial: true) { _, ready in |
| if ready { accountsRequested = false; accounts?() } |
| } |
| + // Settings' "Sign out" asks the home window, which holds the guard: |
| + // nothing unsent, no draft being created, no document windows open. |
| + .onChange(of: signOutRequested, initial: true) { _, requested in |
| + guard requested, documentID == nil, !newDocument else { return } |
| + signOutRequested = false |
| + if canSignOut && !model.hasUnsavedChanges && !model.creatingDocument { signOut() } |
| + } |
| .onChange(of: createRequested, initial: true) { _, requested in |
| if requested && documentID == nil { beginDocument(); createRequested = false } |
| } |
| @@ -127,6 +141,10 @@ import SwiftUI |
| if let detail = model.detail { DocsSharingView(client: client, sqid: detail.sqid) } |
| } |
| } |
| + private var signOutText: Text { |
| + if let signOutLabel { return Text(verbatim: signOutLabel) } |
| + return Text("docs.signout.label", bundle: DocsResources.bundle) |
| + } |
| private func beginDocument() { |
| #if os(macOS) |
| createDocument?() |
diff --git a/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings| index 9dd6cc3..375d38d 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings |
| @@ -191,3 +191,15 @@ |
| "native.colophon.homeandsource" = "الصفحة الرئيسية والمصدر"; |
| "native.colophon.missing" = "تُنشر هذه الحزمة بلا ملف ترخيص، فلا يوجد نص لعرضه."; |
| "native.colophon.notincluded" = "يُبنى التطبيق بهذه الأداة لكنها ليست جزءًا مما يوزّعه، لذا لا يُنسخ نص ترخيصها هنا. إنه في مصدر المشروع."; |
| + |
| +/* Oficina ID (spec 2026-11-14-oficina-id-native, slice A) and the Mac Settings window. */ |
| +"native.oficinaid.signin" = "تسجيل الدخول باستخدام Oficina ID"; |
| +"native.oficinaid.teams" = "الفرق"; |
| +"native.done" = "تم"; |
| +"native.settings.account" = "الحساب"; |
| +"native.settings.server" = "الخادم"; |
| +"native.settings.team" = "الفريق"; |
| +"native.settings.signedOut" = "لم يتم تسجيل الدخول"; |
| +"native.settings.changeTeam" = "تغيير الفريق…"; |
| +"native.settings.accounts" = "الحسابات…"; |
| +"native.settings.signIn" = "تسجيل الدخول…"; |
diff --git a/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings| index 5b942bf..8d45471 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings |
| @@ -191,3 +191,15 @@ |
| "native.colophon.homeandsource" = "হোম পেজ ও সোর্স"; |
| "native.colophon.missing" = "এই প্যাকেজটি লাইসেন্স ফাইল ছাড়াই প্রকাশিত, তাই দেখানোর মতো কোনো লেখা নেই।"; |
| "native.colophon.notincluded" = "অ্যাপটি এটি দিয়ে তৈরি হয়, কিন্তু এটি অ্যাপের সঙ্গে দেওয়া হয় না, তাই এর লাইসেন্স এখানে কপি করা হয়নি। এটি প্রকল্পের সোর্সে আছে।"; |
| + |
| +/* Oficina ID (spec 2026-11-14-oficina-id-native, slice A) and the Mac Settings window. */ |
| +"native.oficinaid.signin" = "Oficina ID দিয়ে সাইন ইন করুন"; |
| +"native.oficinaid.teams" = "টিম"; |
| +"native.done" = "সম্পন্ন"; |
| +"native.settings.account" = "অ্যাকাউন্ট"; |
| +"native.settings.server" = "সার্ভার"; |
| +"native.settings.team" = "টিম"; |
| +"native.settings.signedOut" = "সাইন ইন করা নেই"; |
| +"native.settings.changeTeam" = "টিম পরিবর্তন করুন…"; |
| +"native.settings.accounts" = "অ্যাকাউন্ট…"; |
| +"native.settings.signIn" = "সাইন ইন করুন…"; |
diff --git a/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings| index 107f5e7..b3858ee 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings |
| @@ -196,3 +196,15 @@ |
| "native.colophon.homeandsource" = "Home page and source"; |
| "native.colophon.missing" = "This package is published without a license file, so there is no text to show."; |
| "native.colophon.notincluded" = "The app is built with this, but it isn’t part of what the app ships, so its license text isn’t copied here. It is in the project’s source."; |
| + |
| +/* Oficina ID (spec 2026-11-14-oficina-id-native, slice A) and the Mac Settings window. */ |
| +"native.oficinaid.signin" = "Sign in with Oficina ID"; |
| +"native.oficinaid.teams" = "Teams"; |
| +"native.done" = "Done"; |
| +"native.settings.account" = "Account"; |
| +"native.settings.server" = "Server"; |
| +"native.settings.team" = "Team"; |
| +"native.settings.signedOut" = "Not signed in"; |
| +"native.settings.changeTeam" = "Change team…"; |
| +"native.settings.accounts" = "Accounts…"; |
| +"native.settings.signIn" = "Sign in…"; |
diff --git a/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings| index ef6d150..cab782b 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings |
| @@ -191,3 +191,15 @@ |
| "native.colophon.homeandsource" = "Página principal y código fuente"; |
| "native.colophon.missing" = "Este paquete se publica sin archivo de licencia, así que no hay texto que mostrar."; |
| "native.colophon.notincluded" = "La app se compila con esto, pero no forma parte de lo que distribuye, así que su licencia no se copia aquí. Está en el código fuente del proyecto."; |
| + |
| +/* Oficina ID (spec 2026-11-14-oficina-id-native, slice A) and the Mac Settings window. */ |
| +"native.oficinaid.signin" = "Iniciar sesión con Oficina ID"; |
| +"native.oficinaid.teams" = "Equipos"; |
| +"native.done" = "Listo"; |
| +"native.settings.account" = "Cuenta"; |
| +"native.settings.server" = "Servidor"; |
| +"native.settings.team" = "Equipo"; |
| +"native.settings.signedOut" = "Sin iniciar sesión"; |
| +"native.settings.changeTeam" = "Cambiar de equipo…"; |
| +"native.settings.accounts" = "Cuentas…"; |
| +"native.settings.signIn" = "Iniciar sesión…"; |
diff --git a/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings| index 488f9d0..2ada34a 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings |
| @@ -191,3 +191,15 @@ |
| "native.colophon.homeandsource" = "Leathanach baile agus foinse"; |
| "native.colophon.missing" = "Foilsítear an pacáiste seo gan comhad ceadúnais, mar sin níl aon téacs le taispeáint."; |
| "native.colophon.notincluded" = "Tógtar an aip leis seo, ach ní cuid dá seachadann sí é, mar sin ní chóipeáiltear a cheadúnas anseo. Tá sé i bhfoinse an tionscadail."; |
| + |
| +/* Oficina ID (spec 2026-11-14-oficina-id-native, slice A) and the Mac Settings window. */ |
| +"native.oficinaid.signin" = "Sínigh isteach le Oficina ID"; |
| +"native.oficinaid.teams" = "Foirne"; |
| +"native.done" = "Déanta"; |
| +"native.settings.account" = "Cuntas"; |
| +"native.settings.server" = "Freastalaí"; |
| +"native.settings.team" = "Foireann"; |
| +"native.settings.signedOut" = "Níl tú sínithe isteach"; |
| +"native.settings.changeTeam" = "Athraigh foireann…"; |
| +"native.settings.accounts" = "Cuntais…"; |
| +"native.settings.signIn" = "Sínigh isteach…"; |
diff --git a/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings| index 574bece..92ea72a 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings |
| @@ -191,3 +191,15 @@ |
| "native.colophon.homeandsource" = "होम पेज और सोर्स"; |
| "native.colophon.missing" = "यह पैकेज बिना लाइसेंस फ़ाइल के प्रकाशित है, इसलिए दिखाने के लिए कोई पाठ नहीं है।"; |
| "native.colophon.notincluded" = "ऐप इससे बनाया जाता है, पर यह ऐप के साथ नहीं आता, इसलिए इसका लाइसेंस यहाँ कॉपी नहीं किया गया है। वह प्रोजेक्ट के सोर्स में है।"; |
| + |
| +/* Oficina ID (spec 2026-11-14-oficina-id-native, slice A) and the Mac Settings window. */ |
| +"native.oficinaid.signin" = "Oficina ID से साइन इन करें"; |
| +"native.oficinaid.teams" = "टीमें"; |
| +"native.done" = "हो गया"; |
| +"native.settings.account" = "खाता"; |
| +"native.settings.server" = "सर्वर"; |
| +"native.settings.team" = "टीम"; |
| +"native.settings.signedOut" = "साइन इन नहीं है"; |
| +"native.settings.changeTeam" = "टीम बदलें…"; |
| +"native.settings.accounts" = "खाते…"; |
| +"native.settings.signIn" = "साइन इन करें…"; |
diff --git a/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings| index d75ab1f..7e07cc5 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings |
| @@ -191,3 +191,15 @@ |
| "native.colophon.homeandsource" = "ホームページとソース"; |
| "native.colophon.missing" = "このパッケージはライセンスファイルなしで公開されているため、表示する本文がありません。"; |
| "native.colophon.notincluded" = "アプリはこれを使ってビルドされますが、アプリには含まれないため、ライセンス本文はここに複製していません。プロジェクトのソースにあります。"; |
| + |
| +/* Oficina ID (spec 2026-11-14-oficina-id-native, slice A) and the Mac Settings window. */ |
| +"native.oficinaid.signin" = "Oficina ID でサインイン"; |
| +"native.oficinaid.teams" = "チーム"; |
| +"native.done" = "完了"; |
| +"native.settings.account" = "アカウント"; |
| +"native.settings.server" = "サーバ"; |
| +"native.settings.team" = "チーム"; |
| +"native.settings.signedOut" = "サインインしていません"; |
| +"native.settings.changeTeam" = "チームを変更…"; |
| +"native.settings.accounts" = "アカウント…"; |
| +"native.settings.signIn" = "サインイン…"; |
diff --git a/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings| index 5a070db..51ab635 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings |
| @@ -191,3 +191,15 @@ |
| "native.colophon.homeandsource" = "Página inicial e código-fonte"; |
| "native.colophon.missing" = "Este pacote é publicado sem ficheiro de licença, por isso não há texto para mostrar."; |
| "native.colophon.notincluded" = "A app é construída com isto, mas não faz parte do que distribui, por isso a licença não é copiada aqui. Está no código-fonte do projeto."; |
| + |
| +/* Oficina ID (spec 2026-11-14-oficina-id-native, slice A) and the Mac Settings window. */ |
| +"native.oficinaid.signin" = "Iniciar sessão com o Oficina ID"; |
| +"native.oficinaid.teams" = "Equipas"; |
| +"native.done" = "Concluído"; |
| +"native.settings.account" = "Conta"; |
| +"native.settings.server" = "Servidor"; |
| +"native.settings.team" = "Equipa"; |
| +"native.settings.signedOut" = "Sessão não iniciada"; |
| +"native.settings.changeTeam" = "Mudar de equipa…"; |
| +"native.settings.accounts" = "Contas…"; |
| +"native.settings.signIn" = "Iniciar sessão…"; |
diff --git a/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings| index 549dc7c..952fb69 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings |
| @@ -191,3 +191,15 @@ |
| "native.colophon.homeandsource" = "Сайт и исходный код"; |
| "native.colophon.missing" = "Этот пакет опубликован без файла лицензии, поэтому показать нечего."; |
| "native.colophon.notincluded" = "Приложение собирается с помощью этого инструмента, но он не входит в поставку, поэтому текст его лицензии здесь не приводится. Он есть в исходном коде проекта."; |
| + |
| +/* Oficina ID (spec 2026-11-14-oficina-id-native, slice A) and the Mac Settings window. */ |
| +"native.oficinaid.signin" = "Войти с Oficina ID"; |
| +"native.oficinaid.teams" = "Команды"; |
| +"native.done" = "Готово"; |
| +"native.settings.account" = "Учётная запись"; |
| +"native.settings.server" = "Сервер"; |
| +"native.settings.team" = "Команда"; |
| +"native.settings.signedOut" = "Вход не выполнен"; |
| +"native.settings.changeTeam" = "Сменить команду…"; |
| +"native.settings.accounts" = "Учётные записи…"; |
| +"native.settings.signIn" = "Войти…"; |
diff --git a/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings| index 81196a7..2d68612 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings |
| @@ -191,3 +191,15 @@ |
| "native.colophon.homeandsource" = "Trang chủ và mã nguồn"; |
| "native.colophon.missing" = "Gói này được phát hành không kèm tệp giấy phép, nên không có nội dung để hiển thị."; |
| "native.colophon.notincluded" = "Ứng dụng được xây dựng bằng công cụ này nhưng nó không nằm trong ứng dụng, nên giấy phép không được chép ở đây. Giấy phép có trong mã nguồn của dự án."; |
| + |
| +/* Oficina ID (spec 2026-11-14-oficina-id-native, slice A) and the Mac Settings window. */ |
| +"native.oficinaid.signin" = "Đăng nhập bằng Oficina ID"; |
| +"native.oficinaid.teams" = "Nhóm"; |
| +"native.done" = "Xong"; |
| +"native.settings.account" = "Tài khoản"; |
| +"native.settings.server" = "Máy chủ"; |
| +"native.settings.team" = "Nhóm"; |
| +"native.settings.signedOut" = "Chưa đăng nhập"; |
| +"native.settings.changeTeam" = "Đổi nhóm…"; |
| +"native.settings.accounts" = "Tài khoản…"; |
| +"native.settings.signIn" = "Đăng nhập…"; |
diff --git a/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings| index 72dada2..9fca162 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings |
| @@ -191,3 +191,15 @@ |
| "native.colophon.homeandsource" = "主頁同原始碼"; |
| "native.colophon.missing" = "呢個套件發佈時冇附授權檔案,所以冇內容可以顯示。"; |
| "native.colophon.notincluded" = "個 app 係用呢樣嘢建置嘅,但佢唔係 app 嘅一部分,所以授權全文冇抄喺度。授權喺項目嘅原始碼入面。"; |
| + |
| +/* Oficina ID (spec 2026-11-14-oficina-id-native, slice A) and the Mac Settings window. */ |
| +"native.oficinaid.signin" = "用 Oficina ID 登入"; |
| +"native.oficinaid.teams" = "團隊"; |
| +"native.done" = "完成"; |
| +"native.settings.account" = "帳戶"; |
| +"native.settings.server" = "伺服器"; |
| +"native.settings.team" = "團隊"; |
| +"native.settings.signedOut" = "未登入"; |
| +"native.settings.changeTeam" = "轉團隊…"; |
| +"native.settings.accounts" = "帳戶…"; |
| +"native.settings.signIn" = "登入…"; |
diff --git a/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings| index 08f8290..21c35ce 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings |
| @@ -191,3 +191,15 @@ |
| "native.colophon.homeandsource" = "主页与源代码"; |
| "native.colophon.missing" = "该软件包发布时未附许可文件,因此没有可显示的内容。"; |
| "native.colophon.notincluded" = "应用使用它构建,但它不属于应用分发的内容,因此此处未复制其许可全文。许可见项目源代码。"; |
| + |
| +/* Oficina ID (spec 2026-11-14-oficina-id-native, slice A) and the Mac Settings window. */ |
| +"native.oficinaid.signin" = "使用 Oficina ID 登录"; |
| +"native.oficinaid.teams" = "团队"; |
| +"native.done" = "完成"; |
| +"native.settings.account" = "账户"; |
| +"native.settings.server" = "服务器"; |
| +"native.settings.team" = "团队"; |
| +"native.settings.signedOut" = "未登录"; |
| +"native.settings.changeTeam" = "更换团队…"; |
| +"native.settings.accounts" = "账户…"; |
| +"native.settings.signIn" = "登录…"; |
diff --git a/native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift b/native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift| new file mode 100644 |
| index 0000000..614bfc8 |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift |
| @@ -0,0 +1,189 @@ |
| +import Foundation |
| +import RastrilloApple |
| +import RastrilloTestSupport |
| +import XCTest |
| +@testable import DocsKit |
| + |
| +/// Docs on Oficina ID (spec 2026-11-14-oficina-id-native, slice A), against |
| +/// the kit's in-memory Home, directory and instances: no keychain, App Group |
| +/// or network. |
| +@MainActor final class OficinaIDAdoptionTests: XCTestCase { |
| + final class Clock: @unchecked Sendable { var date = Date(timeIntervalSince1970: 1_800_000_000) } |
| + |
| + let paulca = URL(string: "https://paulca.docs.oficina.works")! |
| + let tito = URL(string: "https://tito.docs.oficina.works")! |
| + var service: FakeOficinaIDService! |
| + var clock: Clock! |
| + var suites: [String] = [] |
| + |
| + override func setUp() async throws { |
| + service = FakeOficinaIDService() |
| + clock = Clock() |
| + } |
| + |
| + override func tearDown() async throws { |
| + for suite in suites { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) } |
| + } |
| + |
| + private func defaults() -> UserDefaults { |
| + let suite = "OficinaIDAdoptionTests.\(UUID().uuidString)" |
| + suites.append(suite) |
| + return UserDefaults(suiteName: suite)! |
| + } |
| + |
| + private func team(_ sqid: String, _ name: String, _ label: String, apps: [String] = ["docs"]) -> OficinaTeam { |
| + OficinaTeam(sqid: sqid, label: label, name: name, role: "member", |
| + apps: apps.map { OficinaTeamApp(app: $0, origin: "https://\(label).\($0).oficina.works", consumerID: "\(sqid)-\($0)") }) |
| + } |
| + |
| + private func session() -> DocsOficinaSession { |
| + let clock = self.clock! |
| + let store = OficinaIDStore(shared: OficinaMemoryStore(), appPrivate: OficinaMemoryStore(), group: defaults()) |
| + let model = OficinaIDModel(configuration: DocsOficinaSession.configuration, store: store, service: service, |
| + passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, now: { clock.date }, |
| + appDefaults: defaults()) |
| + return DocsOficinaSession(model: model, now: { clock.date }) |
| + } |
| + |
| + /// Welcome → Email → Code, as a person would. |
| + private func signIn(_ session: DocsOficinaSession) async { |
| + await session.start() |
| + XCTAssertEqual(session.model.step, .welcome) |
| + session.model.continueWithEmail() |
| + session.model.email = "paul@tito.io" |
| + await session.model.submitEmail() |
| + session.model.code = FakeOficinaIDService.goodCode |
| + await session.model.submitCode() |
| + } |
| + |
| + private func exchanges(at origin: URL) -> Int { service.calls.filter { $0 == "exchange \(origin.absoluteString)" }.count } |
| + |
| + func testRouteIsOficinaIDUnlessSomeoneSignedInTheOldWay() { |
| + XCTAssertEqual(DocsSignInRoute.resolve(stored: "", hasServerAccounts: false), .oficinaID) |
| + // Appendix C: old per-app sessions keep working until replaced. |
| + XCTAssertEqual(DocsSignInRoute.resolve(stored: "", hasServerAccounts: true), .server) |
| + XCTAssertEqual(DocsSignInRoute.resolve(stored: "oficina-id", hasServerAccounts: true), .oficinaID) |
| + XCTAssertEqual(DocsSignInRoute.resolve(stored: "server", hasServerAccounts: false), .server) |
| + XCTAssertEqual(DocsSignInRoute.resolve(stored: "something else", hasServerAccounts: false), .oficinaID) |
| + } |
| + |
| + func testAccountsBelongToTheirIdentityOnly() { |
| + let account = DocsOficinaSession.accountID(identity: "id-1", team: "t1") |
| + XCTAssertTrue(DocsOficinaSession.account(account, belongsTo: "id-1")) |
| + XCTAssertFalse(DocsOficinaSession.account(account, belongsTo: "id")) |
| + XCTAssertFalse(DocsOficinaSession.account(DocsOficinaSession.accountID(identity: "id-10", team: "t1"), belongsTo: "id-1")) |
| + XCTAssertFalse(DocsOficinaSession.account(UUID().uuidString, belongsTo: "id-1")) |
| + } |
| + |
| + func testOneDocsTeamSignsStraightInAndTheWorkspaceGetsItsSession() async throws { |
| + service.addPerson(email: "paul@tito.io", identityID: "id-paul") |
| + // A team without Docs is no team for Docs. |
| + service.setTeams([team("t1", "Paul", "paulca"), team("t3", "Sums", "sums", apps: ["sheets"])], for: "id-paul") |
| + service.admit("id-paul", at: paulca, as: .linked) |
| + let docs = session() |
| + await signIn(docs) |
| + let state = try XCTUnwrap(docs.signedIn) |
| + XCTAssertEqual(state.origin, paulca) |
| + let account = DocsOficinaSession.accountID(state) |
| + XCTAssertEqual(account, "oficina-id.id-paul.t1") |
| + let transport = try XCTUnwrap(docs.transport(for: account)()) |
| + XCTAssertEqual(transport.origin, paulca) |
| + XCTAssertEqual(docs.client(for: account)?.credential?.value, state.session.value) |
| + XCTAssertTrue(service.isLive(session: state.session)) |
| + // Another identity's account gets nothing. |
| + XCTAssertNil(docs.transport(for: DocsOficinaSession.accountID(identity: "id-other", team: "t1"))()) |
| + } |
| + |
| + func testARefusedSessionIsReMintedOnceAMinute() async throws { |
| + service.addPerson(email: "paul@tito.io", identityID: "id-paul") |
| + service.setTeams([team("t1", "Paul", "paulca")], for: "id-paul") |
| + service.admit("id-paul", at: paulca, as: .linked) |
| + let docs = session() |
| + await signIn(docs) |
| + let first = try XCTUnwrap(docs.signedIn) |
| + let account = DocsOficinaSession.accountID(first) |
| + XCTAssertEqual(exchanges(at: paulca), 1) |
| + |
| + service.expire(session: first.session) |
| + await docs.rejected(account) |
| + let second = try XCTUnwrap(docs.signedIn) |
| + XCTAssertNotEqual(second.session.value, first.session.value) |
| + XCTAssertEqual(docs.client(for: account)?.credential?.value, second.session.value, "the supplier follows the new session") |
| + XCTAssertEqual(exchanges(at: paulca), 2) |
| + |
| + // An instance that keeps refusing cannot set off a loop. |
| + await docs.rejected(account) |
| + XCTAssertEqual(exchanges(at: paulca), 2) |
| + clock.date.addTimeInterval(61) |
| + await docs.rejected(account) |
| + XCTAssertEqual(exchanges(at: paulca), 3) |
| + |
| + // Only the team in use is re-minted. |
| + await docs.rejected(DocsOficinaSession.accountID(identity: "id-paul", team: "t2")) |
| + XCTAssertEqual(exchanges(at: paulca), 3) |
| + } |
| + |
| + func testSigningOutLeavesNoTransport() async throws { |
| + service.addPerson(email: "paul@tito.io", identityID: "id-paul") |
| + service.setTeams([team("t1", "Paul", "paulca")], for: "id-paul") |
| + service.admit("id-paul", at: paulca, as: .linked) |
| + let docs = session() |
| + await signIn(docs) |
| + let state = try XCTUnwrap(docs.signedIn) |
| + let supplier = docs.transport(for: DocsOficinaSession.accountID(state)) |
| + XCTAssertNotNil(supplier()) |
| + docs.model.signOut() |
| + await docs.model.cleanup?.value |
| + XCTAssertEqual(docs.model.step, .welcome) |
| + XCTAssertNil(supplier(), "a workspace still open after sign-out must fail as unauthorized, not send") |
| + XCTAssertFalse(service.isLive(session: state.session), "the instance session is signed out too (§10)") |
| + } |
| + |
| + func testSwitchingTeamKeepsTheOtherTeamsSession() async throws { |
| + service.addPerson(email: "paul@tito.io", identityID: "id-paul") |
| + let paul = team("t1", "Paul", "paulca"), titoTeam = team("t2", "Tito", "tito") |
| + service.setTeams([paul, titoTeam], for: "id-paul") |
| + service.admit("id-paul", at: paulca, as: .linked) |
| + service.admit("id-paul", at: tito, as: .linked) |
| + let docs = session() |
| + await signIn(docs) |
| + guard case .teams(let teams) = docs.model.step else { return XCTFail("two Docs teams ask which: \(docs.model.step)") } |
| + XCTAssertEqual(DocsTeamPicker.teams(teams, current: paul).map(\.sqid), ["t1", "t2"]) |
| + await docs.model.choose(paul) |
| + let first = try XCTUnwrap(docs.signedIn) |
| + await docs.model.choose(titoTeam) |
| + let second = try XCTUnwrap(docs.signedIn) |
| + XCTAssertEqual(second.origin, tito) |
| + // A document window of the first team keeps its session. |
| + XCTAssertEqual(docs.client(for: DocsOficinaSession.accountID(first))?.credential?.value, first.session.value) |
| + XCTAssertNotNil(docs.client(for: DocsOficinaSession.accountID(second))) |
| + } |
| + |
| + func testTeamPickerListsDocsTeamsAndAlwaysTheCurrentOne() { |
| + let paul = team("t1", "Paul", "paulca"), sums = team("t3", "Sums", "sums", apps: ["sheets"]) |
| + let campbells = team("t2", "campbells", "campbells") |
| + XCTAssertEqual(DocsTeamPicker.teams([sums, paul, campbells], current: paul).map(\.sqid), ["t2", "t1"]) |
| + // An empty or missing cache still shows the team in use. |
| + XCTAssertEqual(DocsTeamPicker.teams(nil, current: paul).map(\.sqid), ["t1"]) |
| + } |
| + |
| + func testTheWatchReportsRefusedSessionsOnly() async throws { |
| + final class Count: @unchecked Sendable { var value = 0 } |
| + let count = Count() |
| + let scripted = ScriptedTransport([.respond(status: 200), .respond(status: 401), .respond(status: 303), |
| + .respond(status: 403), .respond(status: 401)]) |
| + let watch = DocsSessionWatch(inner: scripted) { count.value += 1 } |
| + _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024) |
| + XCTAssertEqual(count.value, 0) |
| + _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024) |
| + _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024) |
| + XCTAssertEqual(count.value, 2, "401 and the 303 to sign-in are an ended session") |
| + _ = try await watch.responseDetails("/", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024) |
| + XCTAssertEqual(count.value, 2, "403 is a refusal of the request, not of the session") |
| + do { |
| + try await watch.stream("/d/x/stream", onOpen: {}, onLine: { _ in }) |
| + XCTFail("a refused stream throws") |
| + } catch NativeClientError.unauthorized {} |
| + XCTAssertEqual(count.value, 3) |
| + } |
| +} |