Slice A review fixes: team refresh, origin-proof store keys, live clients, guards that say why, the workspace stays mounted
Human
Prompt
Fable reviewed docs native/oficina-id-slice-a @d143194: APPROVE AFTER FIXES. MUST: B1 team refresh (launch, picker ≤5 min, any 403); B2 sealed-store key by origin loses the store on an origin change; B3 Mac document windows keep entry.client for sharing/export/images/jump. SHOULD: S1 route only on an actual sign-in; S2 a 401 with Home unreachable keeps the workspace mounted with a banner, "Use another" through Docs' guards; S3 launch check App Group via the entitlement; S4/S5 identity-wide sign-out guard incl. crash-left outboxes, Change team… guarded, Settings matches; say why instead of silent refusal; S7 tests; surface model.error for a failed team switch; ids/sqids with '.' or '/' made safe.
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
B1: DocsOficinaSession.start() refreshes teams after launch, the picker refreshes on open (kit: at most every 5 min), and a 403 from the instance (DocsSessionWatch.refused) refreshes at once, at most once a minute. B2: an Oficina ID account's store key is filed under a fixed origin (DocsOfflineAccount.oficinaKeyOrigin), so a team origin change keeps its store and outbox; server accounts keep their host. B3: sharing, export, images, Jump and the editor context take a NativeTransport resolved at use time (the window's watched supplier, else its client). S1: DocsOficinaSession.signIns counts sign-ins made here; the route changes only on those, never on a restore. S2: DocsOficinaSession.mounted keeps the team mounted while the model is on unavailable(same team), with the Can't reach Oficina ID line and Try again over it; a failed team switch's model.error shows there and in the picker; Use another is cancelled with the reason when Docs' guard refuses. S3: the launch check reads the App Group and associated-domains entitlements via SecTask. S4/S5: DocsLeaveBlock.check is identity-wide (open document windows of any team, then every team's outbox, including ones on disk not opened this run); sign-out, Use another, the picker and Settings (Change team… and Sign out) use it and show the line (two strings, twelve languages); the workspace's Settings request alerts instead of doing nothing. Account ID parts that are not base64url-safe are encoded. Disabled sign-out in the picker no longer looks enabled.
Agent notes
S7 tests: purge on identity replacement, re-mint restarting a stopped outbox, 401 with Home down, restore vs sign-in, 24 h renew through the session, 403 and menu refresh, the store surviving an origin change, crash-left unsent blocking, guard ordering, the launch check failing unsigned, Mac identity-wide window guard. Mutations of the key origin, the mounted case, the sign-in count and the live client each fail their test.
28 files changed,
+678
−84
native/BUILDING.md+13 −3native/apple/Sources/DocsApp/DocsAccountWindow.swift+73 −20native/apple/Sources/DocsApp/DocsApp.swift+10 −1native/apple/Sources/DocsApp/DocsWindows.swift+15 −0native/apple/Sources/DocsKit/DocsAttachments.swift+2 −2native/apple/Sources/DocsKit/DocsEditorContext.swift+1 −1native/apple/Sources/DocsKit/DocsJumpControls.swift+1 −1native/apple/Sources/DocsKit/DocsOfflineAccount.swift+40 −5native/apple/Sources/DocsKit/DocsOficinaID.swift+119 −18native/apple/Sources/DocsKit/DocsOficinaViews.swift+46 −12native/apple/Sources/DocsKit/DocsSharingView.swift+1 −1native/apple/Sources/DocsKit/DocsWorkspace.swift+27 −9native/apple/Sources/DocsKit/DocumentExportControls.swift+2 −2native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings+2 −0native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings+2 −0native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings+2 −0native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings+2 −0native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings+2 −0native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings+2 −0native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings+2 −0native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings+2 −0native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings+2 −0native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings+2 −0native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings+2 −0native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings+2 −0native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift+265 −6native/apple/Tests/DocsSnapshots/DocsSnapshots.swift+13 −3native/apple/Tests/DocsWindowTests/WindowRoutingTests.swift+26 −0
diff --git a/native/BUILDING.md b/native/BUILDING.md| index a1b8474..5e85ccb 100644 |
| --- a/native/BUILDING.md |
| +++ b/native/BUILDING.md |
| @@ -100,9 +100,19 @@ publish, run the final signed, notarised artifact's executable with |
| ``` |
| macOS checks the embedded profile as the process starts. The check then reads |
| -the entitlement's group order, both keychain groups and the App Group, prints |
| -counts (never an identity or a session) and exits 0 only if all of them work. |
| -An ad hoc build fails it. |
| +the signed entitlements (the keychain groups in order, the App Group, the |
| +associated domain) and both keychain groups, prints counts (never an identity |
| +or a session) and exits 0 only if all of them work. An ad hoc build, or the |
| +unsigned test runner (`OficinaIDAdoptionTests`), fails every line. |
| + |
| +An Oficina ID team's offline store key is filed under one fixed origin, not the |
| +team's, so a team whose address changes (a label moved, a rename, self-hosting |
| +by DNS) keeps its store and unsent outbox. Docs refreshes the team list at |
| +launch, when the team picker opens (at most every five minutes) and on a 403, |
| +through the kit's `refreshTeams`. Signing out, switching team or replacing the |
| +Oficina ID waits for every team's outbox to drain, those a crash left on disk |
| +included, and on the Mac for every document window of the identity to close; |
| +the picker and Settings say which. |
| Sign-in itself needs Home's native endpoints at `id.oficina.works` and the |
| directory at `oficina.works`; passkeys also need Home's association file. The |
diff --git a/native/apple/Sources/DocsApp/DocsAccountWindow.swift b/native/apple/Sources/DocsApp/DocsAccountWindow.swift| index 80ba56c..abb08b6 100644 |
| --- a/native/apple/Sources/DocsApp/DocsAccountWindow.swift |
| +++ b/native/apple/Sources/DocsApp/DocsAccountWindow.swift |
| @@ -12,8 +12,10 @@ import SwiftUI |
| /// 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 oficina: DocsOficinaSession |
| @ObservedObject private var model: OficinaIDModel |
| + /// Why a sign-out or "Use another" was refused: said, not swallowed. |
| + @State private var leaveRefusal: DocsLeaveBlock? |
| @StateObject private var connection = NativeConnection(defaultServer: "https://docs.oficina.works") |
| @AppStorage(DocsSignInRoute.key) private var storedRoute = "" |
| @State private var pickingTeam = false |
| @@ -25,10 +27,10 @@ struct DocsAccountWindow: View { |
| #if os(macOS) |
| init(oficina: DocsOficinaSession, windows: DocsWindows) { |
| - self.oficina = oficina; _model = ObservedObject(wrappedValue: oficina.model); _windows = Bindable(windows) |
| + _oficina = ObservedObject(wrappedValue: oficina); _model = ObservedObject(wrappedValue: oficina.model); _windows = Bindable(windows) |
| } |
| #else |
| - init(oficina: DocsOficinaSession) { self.oficina = oficina; _model = ObservedObject(wrappedValue: oficina.model) } |
| + init(oficina: DocsOficinaSession) { _oficina = ObservedObject(wrappedValue: oficina); _model = ObservedObject(wrappedValue: oficina.model) } |
| #endif |
| private var route: DocsSignInRoute { |
| @@ -46,7 +48,9 @@ struct DocsAccountWindow: View { |
| Group { |
| switch route { |
| case .oficinaID: |
| - if case .signedIn(let state) = model.step { oficinaWorkspace(state) } |
| + // The mounted team stays while Oficina ID can't re-mint it (§11), with |
| + // the line saying so over it, rather than unmounting an open editor. |
| + if let state = oficina.mounted { oficinaWorkspace(state).safeAreaInset(edge: .top, spacing: 0) { oficinaBanner } } |
| else { OficinaOnboardingView(model: model, otherWays: { storedRoute = DocsSignInRoute.server.rawValue }) } |
| case .server: |
| if let client = connection.client { serverWorkspace(client) } |
| @@ -56,8 +60,20 @@ struct DocsAccountWindow: View { |
| .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 } |
| + // Only one made here: an identity restored at launch (another app's, or |
| + // last run's) leaves the route someone chose alone. |
| + .onChange(of: oficina.signIns) { _, _ in storedRoute = DocsSignInRoute.oficinaID.rawValue } |
| + // "Use another" signs the identity out on every app: Docs' guards first. |
| + .onChange(of: model.confirmingReplace) { _, confirming in |
| + guard confirming, let identity = model.identity?.id else { return } |
| + Task { |
| + if let block = await DocsLeaveBlock.check(identity: identity, openDocuments: openDocuments(of: identity)) { |
| + model.cancelReplace(); leaveRefusal = block |
| + } |
| + } |
| + } |
| + .alert(leaveRefusal?.message ?? "", isPresented: Binding(get: { leaveRefusal != nil }, set: { if !$0 { leaveRefusal = nil } })) { |
| + Button(OficinaIDText.text("cancel"), role: .cancel) { leaveRefusal = nil } |
| } |
| .onChange(of: scenePhase) { _, phase in |
| if phase == .active { Task { await oficina.renewIfNeeded() } } |
| @@ -72,19 +88,20 @@ struct DocsAccountWindow: View { |
| .focusedSceneValue(\.docsWindowAccount, currentAccount) |
| .onChange(of: currentAccount, initial: true) { _, value in windows.activeAccount = value } |
| .onChange(of: settingsAccount, initial: true) { _, value in windows.settingsAccount = value } |
| + .onChange(of: route == .oficinaID ? oficina.mounted?.identity.id : nil, initial: true) { _, value in windows.settingsIdentity = value } |
| #endif |
| } |
| private var currentAccount: String? { |
| switch route { |
| - case .oficinaID: return oficina.signedIn.map(DocsOficinaSession.accountID) |
| + case .oficinaID: return oficina.mounted.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 .oficinaID: return oficina.mounted.flatMap { oficina.client(for: DocsOficinaSession.accountID($0)) } |
| case .server: return connection.client |
| } |
| } |
| @@ -95,7 +112,7 @@ struct DocsAccountWindow: 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 } |
| + let canLeave = !openDocuments(of: state.identity.id) |
| DocsWorkspace(client: client, accountID: account, transport: oficina.transport(for: account), accounts: { pickingTeam = true }, signOut: { |
| signOutOficinaID(state) |
| }, createDocument: { |
| @@ -115,14 +132,14 @@ struct DocsAccountWindow: View { |
| .id(account) |
| .onAppear { windows.transports[account] = oficina.transport(for: account) } |
| .safeAreaInset(edge: .bottom, spacing: 0) { passkeyNudge } |
| - .sheet(isPresented: $pickingTeam) { teamPicker(state, canLeave: canLeave) } |
| + .sheet(isPresented: $pickingTeam) { teamPicker(state) } |
| #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) } |
| + .sheet(isPresented: $pickingTeam) { teamPicker(state) } |
| #endif |
| } |
| @@ -132,8 +149,37 @@ struct DocsAccountWindow: 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: { |
| + /// Whether a document window of any of `identity`'s teams is open (Mac). |
| + private func openDocuments(of identity: String) -> Bool { |
| + #if os(macOS) |
| + return windows.hasOpenDocuments(identity: identity) |
| + #else |
| + return false |
| + #endif |
| + } |
| + |
| + /// Over a mounted workspace: Oficina ID can't mint this team a session |
| + /// right now (§11), or a team switch failed. Try again, or carry on with |
| + /// what is open; nothing is unmounted. |
| + @ViewBuilder private var oficinaBanner: some View { |
| + if case .unavailable = model.step { |
| + HStack(spacing: 12) { |
| + OficinaErrorLine(OficinaIDText.text("unavailable.title") + ". " + OficinaIDText.text("unavailable.body")) |
| + Spacer(minLength: 0) |
| + Button(OficinaIDText.text("unavailable.retry")) { Task { await model.retry() } }.disabled(model.busy) |
| + .accessibilityIdentifier("docs.oficinaid.retry") |
| + } |
| + .padding(.horizontal, 16).padding(.vertical, 8).background(OficinaPalette.negativeSoft) |
| + } else if let error = model.error { |
| + OficinaErrorLine(error).padding(.horizontal, 16).padding(.vertical, 8) |
| + .frame(maxWidth: .infinity, alignment: .leading).background(OficinaPalette.negativeSoft) |
| + } |
| + } |
| + |
| + private func teamPicker(_ state: OficinaSignedIn) -> some View { |
| + DocsTeamPicker(model: model, current: state, leaveCheck: { |
| + await DocsLeaveBlock.check(identity: state.identity.id, openDocuments: openDocuments(of: state.identity.id)) |
| + }, refresh: { await oficina.pickerOpened() }, otherWays: { |
| pickingTeam = false |
| storedRoute = DocsSignInRoute.server.rawValue |
| }, signOut: { |
| @@ -147,12 +193,19 @@ struct DocsAccountWindow: View { |
| /// 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() |
| + let identity = state.identity.id |
| + Task { |
| + // Identity-wide: every team's outbox, those a crash left on disk too. |
| + if let block = await DocsLeaveBlock.check(identity: identity, openDocuments: openDocuments(of: identity)) { |
| + leaveRefusal = block; return |
| + } |
| + guard model.identity?.id == identity else { return } |
| + #if os(macOS) |
| + windows.entries.removeAll { DocsOficinaSession.account($0.account, belongsTo: identity) } |
| + windows.transports = windows.transports.filter { !DocsOficinaSession.account($0.key, belongsTo: identity) } |
| + #endif |
| + model.signOut() |
| + } |
| } |
| // MARK: Other ways (server address) |
| @@ -189,7 +242,7 @@ struct DocsAccountWindow: View { |
| private var settingsAccount: DocsSettingsView.Account { |
| switch route { |
| case .oficinaID: |
| - guard let state = oficina.signedIn else { return .none } |
| + guard let state = oficina.mounted 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 } |
diff --git a/native/apple/Sources/DocsApp/DocsApp.swift b/native/apple/Sources/DocsApp/DocsApp.swift| index 8bdf129..8941857 100644 |
| --- a/native/apple/Sources/DocsApp/DocsApp.swift |
| +++ b/native/apple/Sources/DocsApp/DocsApp.swift |
| @@ -80,12 +80,21 @@ import SwiftUI |
| struct DocsSettingsWindow: View { |
| let windows: DocsWindows |
| @Environment(\.openWindow) private var openWindow |
| + @State private var block: DocsLeaveBlock? |
| var body: some View { |
| - DocsSettingsView(account: windows.settingsAccount, canSignOut: windows.canSignOut(windows.activeAccount), manage: { |
| + DocsSettingsView(account: windows.settingsAccount, block: block, manage: { |
| windows.accountsRequested = true; openWindow(id: "home") |
| }, signOut: { |
| windows.signOutRequested = true; openWindow(id: "home") |
| }, signIn: { openWindow(id: "home") }) |
| + // The same guard as the home window's, kept current while Settings is |
| + // open: open document windows change, outboxes drain. |
| + .task(id: "\(windows.settingsIdentity ?? "")|\(windows.activeAccount ?? "")|\(windows.entries.filter(\.isOpen).count)") { |
| + while !Task.isCancelled { |
| + block = await windows.leaveBlock() |
| + try? await Task.sleep(for: .seconds(2)) |
| + } |
| + } |
| } |
| } |
| #endif |
diff --git a/native/apple/Sources/DocsApp/DocsWindows.swift b/native/apple/Sources/DocsApp/DocsWindows.swift| index 59589fc..4a004f8 100644 |
| --- a/native/apple/Sources/DocsApp/DocsWindows.swift |
| +++ b/native/apple/Sources/DocsApp/DocsWindows.swift |
| @@ -24,6 +24,8 @@ import SwiftUI |
| var signOutRequested = false |
| /// What Settings shows: the home window's account. |
| var settingsAccount: DocsSettingsView.Account = .none |
| + /// The home window's Oficina ID, for Settings' identity-wide guard. |
| + var settingsIdentity: String? |
| /// 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 |
| @@ -67,6 +69,19 @@ import SwiftUI |
| } |
| } |
| func canSignOut(_ account: String?) -> Bool { !entries.contains { $0.account == account && $0.isOpen } } |
| + /// Whether a document window of any of `identity`'s teams is open: |
| + /// signing out of an Oficina ID ends all of its teams at once. |
| + func hasOpenDocuments(identity: String) -> Bool { |
| + entries.contains { DocsOficinaSession.account($0.account, belongsTo: identity) && $0.isOpen } |
| + } |
| + /// Settings' guard, matching the home window's: identity-wide for an |
| + /// Oficina ID, the account's own windows for a server account. |
| + func leaveBlock() async -> DocsLeaveBlock? { |
| + if let identity = settingsIdentity { |
| + return await DocsLeaveBlock.check(identity: identity, openDocuments: hasOpenDocuments(identity: identity)) |
| + } |
| + return canSignOut(activeAccount) ? nil : .openDocuments |
| + } |
| } |
| extension FocusedValues { @Entry var docsWindowAccount: String? } |
| #endif |
diff --git a/native/apple/Sources/DocsKit/DocsAttachments.swift b/native/apple/Sources/DocsKit/DocsAttachments.swift| index 4dd1e0c..bebf1c1 100644 |
| --- a/native/apple/Sources/DocsKit/DocsAttachments.swift |
| +++ b/native/apple/Sources/DocsKit/DocsAttachments.swift |
| @@ -42,14 +42,14 @@ private final class ImageRedirectGuard: NSObject, URLSessionTaskDelegate, @unche |
| for node in projection.children { visit(node) } |
| return found.sorted() |
| } |
| - func images(forDocumentPath path: String, client: NativeHTTP) -> [String: DocsPlatformImage] { |
| + func images(forDocumentPath path: String, client: NativeTransport) -> [String: DocsPlatformImage] { |
| documentURL == URL(string: path, relativeTo: client.origin)?.absoluteURL ? images : [:] |
| } |
| static func resolvedURL(source: String, documentPath: String, origin: URL) -> URL? { |
| guard let document = URL(string: documentPath, relativeTo: origin)?.absoluteURL else { return nil } |
| return URL(string: source, relativeTo: document)?.absoluteURL |
| } |
| - func load(sources: [String], client: NativeHTTP, documentPath: String = "/") async { |
| + func load(sources: [String], client: NativeTransport, documentPath: String = "/") async { |
| let current = UUID(); generation = current |
| let document = URL(string: documentPath, relativeTo: client.origin)?.absoluteURL |
| if documentURL != document { images.removeAll(); documentURL = document } |
diff --git a/native/apple/Sources/DocsKit/DocsEditorContext.swift b/native/apple/Sources/DocsKit/DocsEditorContext.swift| index 9b9ac73..f604c9f 100644 |
| --- a/native/apple/Sources/DocsKit/DocsEditorContext.swift |
| +++ b/native/apple/Sources/DocsKit/DocsEditorContext.swift |
| @@ -6,7 +6,7 @@ import SwiftUI |
| struct DocsEditorContext { |
| let model: DocsModel |
| let rename: () -> Void |
| - let client: NativeHTTP |
| + let client: NativeTransport |
| let zoom: Binding<Double> |
| let paged: Binding<Bool> |
| let inspecting: Binding<Bool> |
diff --git a/native/apple/Sources/DocsKit/DocsJumpControls.swift b/native/apple/Sources/DocsKit/DocsJumpControls.swift| index c49dc36..561d2c9 100644 |
| --- a/native/apple/Sources/DocsKit/DocsJumpControls.swift |
| +++ b/native/apple/Sources/DocsKit/DocsJumpControls.swift |
| @@ -26,7 +26,7 @@ private struct DocumentSearchResult: Decodable, Identifiable { |
| @MainActor struct DocsJumpSheet: View { |
| let model: DocsModel |
| - let client: NativeHTTP |
| + let client: NativeTransport |
| @Environment(\.dismiss) private var dismiss |
| @FocusState private var searchFocused: Bool |
| @State private var query = "" |
diff --git a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift| index 630ccb6..a7c17a9 100644 |
| --- a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift |
| +++ b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift |
| @@ -11,7 +11,7 @@ struct DocsOfflineMetadata: Codable { |
| /// All windows for an account share the same outbox and send reservation. |
| @MainActor @Observable final class DocsOfflineAccount { |
| - private static var accounts: [String: DocsOfflineAccount] = [:] |
| + static var accounts: [String: DocsOfflineAccount] = [:] |
| let store: BlobStore |
| let outbox: Outbox |
| let connectivity: NativeConnectivity |
| @@ -20,13 +20,48 @@ struct DocsOfflineMetadata: Codable { |
| private(set) var drainer: OutboxDrainer! |
| static func account(_ id: String, origin: URL, fallback: NativeTransport, transport: (@MainActor () -> NativeTransport?)?) -> DocsOfflineAccount { |
| if let existing = accounts[id] { if let transport { existing.supplier = transport; existing.drainer.sessionRestored() }; return existing } |
| - let root = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] |
| - .appendingPathComponent(Bundle.main.bundleIdentifier ?? "works.oficina.docs") |
| - .appendingPathComponent("accounts").appendingPathComponent(id) |
| - let store = NativeSealedStore(root: root, accountID: id, keys: KeychainKeyProvider(accountID: id, origin: origin)) |
| + let root = accountsRoot.appendingPathComponent(id) |
| + let store = NativeSealedStore(root: root, accountID: id, keys: keys(accountID: id, origin: origin)) |
| let account = DocsOfflineAccount(store: store, accountID: id, connectivity: .shared, transport: transport ?? { fallback }) |
| accounts[id] = account; return account |
| } |
| + static var accountsRoot: URL { |
| + FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] |
| + .appendingPathComponent(Bundle.main.bundleIdentifier ?? "works.oficina.docs") |
| + .appendingPathComponent("accounts") |
| + } |
| + |
| + /// What every Oficina ID team's store key is filed under, whatever its |
| + /// origin. A team's origin can change (a label moved, a rename, a team |
| + /// self-hosting by DNS) while its account, keyed by (identity, team), |
| + /// does not; keyed by origin, the store would find no key and delete |
| + /// itself, unsent outbox and all. Server accounts keep their origin: an |
| + /// account there is a host. |
| + nonisolated static let oficinaKeyOrigin = URL(string: "https://oficina-id.invalid")! |
| + |
| + nonisolated static func keys(accountID: String, origin: URL) -> KeychainKeyProvider { |
| + KeychainKeyProvider(accountID: accountID, origin: DocsOficinaSession.isOficinaAccount(accountID) ? oficinaKeyOrigin : origin) |
| + } |
| + |
| + /// Whether any of `identity`'s teams has changes on this device not yet |
| + /// sent: the outboxes open in this run, and any left on disk by an |
| + /// earlier one (a crash, a quit with a lane held) that nothing has |
| + /// opened since. Signing out must not strand them. |
| + static func hasUnsent(identity: String, root: URL? = nil, |
| + keys: (String) -> KeyProvider = { keys(accountID: $0, origin: oficinaKeyOrigin) }) async -> Bool { |
| + for (id, account) in accounts where DocsOficinaSession.account(id, belongsTo: identity) { |
| + if await !account.outbox.summary.isEmpty { return true } |
| + } |
| + let root = root ?? accountsRoot |
| + let names = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? [] |
| + for name in names.sorted() where DocsOficinaSession.account(name, belongsTo: identity) && accounts[name] == nil { |
| + let outbox = Outbox(store: NativeSealedStore(root: root.appendingPathComponent(name), accountID: name, keys: keys(name)), account: name) |
| + guard (try? await outbox.load()) != nil else { continue } |
| + if await !outbox.summary.isEmpty { return true } |
| + } |
| + return false |
| + } |
| + |
| /// 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() } |
diff --git a/native/apple/Sources/DocsKit/DocsOficinaID.swift b/native/apple/Sources/DocsKit/DocsOficinaID.swift| index 7378956..58fff20 100644 |
| --- a/native/apple/Sources/DocsKit/DocsOficinaID.swift |
| +++ b/native/apple/Sources/DocsKit/DocsOficinaID.swift |
| @@ -34,6 +34,7 @@ public enum DocsSignInRoute: String, Sendable { |
| public let model: OficinaIDModel |
| private var sessions: [String: (session: NativeSession, client: NativeHTTP)] = [:] |
| private var lastRejection: [String: Date] = [:] |
| + private var lastRefusal: Date? |
| private var renewing = false |
| private var started = false |
| private var watch: AnyCancellable? |
| @@ -41,6 +42,19 @@ public enum DocsSignInRoute: String, Sendable { |
| nonisolated public static let configuration = OficinaIDConfiguration(app: "docs", appName: "Docs") |
| + /// The team the workspace shows. It is the signed-in team, and it stays |
| + /// while Oficina ID cannot mint that team a new session (spec §11): a |
| + /// 401 with Home unreachable must not unmount an open editor. Docs then |
| + /// shows the "Can't reach Oficina ID" line over the workspace instead. |
| + /// nil once the identity signs out, or the model moves to another team's |
| + /// question (not on it, choose, …). |
| + @Published public private(set) var mounted: OficinaSignedIn? |
| + |
| + /// Counts sign-ins a person made here: an identity chosen, a code or |
| + /// passkey, a team picked, a retry. Restoring the last team at launch is |
| + /// not one, so a restored identity never changes Docs' sign-in route. |
| + @Published public private(set) var signIns = 0 |
| + |
| /// "Teams": the workspace's button for Docs' team picker. |
| public static var teamsTitle: String { |
| NSLocalizedString("native.oficinaid.teams", bundle: DocsResources.bundle, comment: "") |
| @@ -69,11 +83,24 @@ public enum DocsSignInRoute: String, Sendable { |
| watch = model.$step.sink { [weak self] step in self?.stepChanged(step) } |
| } |
| - /// Reads the store once per launch, however many windows ask. |
| + /// Reads the store once per launch, however many windows ask, then |
| + /// refreshes the team list (spec §9: at launch). |
| public func start() async { |
| guard !started else { return } |
| started = true |
| await model.start() |
| + await model.refreshTeams() |
| + } |
| + |
| + /// The team picker opened: refresh if the list is five minutes old. |
| + public func pickerOpened() async { await model.refreshTeams() } |
| + |
| + /// An instance answered 403: the person may have left the team, or been |
| + /// given another, so the list is fetched again, at most once a minute. |
| + func refused() async { |
| + if let last = lastRefusal, now().timeIntervalSince(last) < 60 { return } |
| + lastRefusal = now() |
| + await model.refreshTeams(maxAge: 0) |
| } |
| /// The team session in use, if the model has one. |
| @@ -89,17 +116,33 @@ public enum DocsSignInRoute: String, Sendable { |
| 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 |
| + nonisolated public static func accountID(identity: String, team: String) -> String { |
| + prefix + component(identity) + "." + component(team) |
| + } |
| + |
| + nonisolated static let prefix = "oficina-id." |
| + |
| + /// An account ID names a directory and a keychain item, so each part is |
| + /// used as it is only when it is base64url-safe (as Home's identity IDs |
| + /// and sqids are). Anything else, a "." or "/" above all, is encoded, |
| + /// marked by a "~" no plain part can contain. |
| + nonisolated static func component(_ text: String) -> String { |
| + let plain = !text.isEmpty && text.unicodeScalars.allSatisfy { |
| + ("a"..."z").contains($0) || ("A"..."Z").contains($0) || ("0"..."9").contains($0) || $0 == "-" || $0 == "_" |
| + } |
| + return plain ? text : "~" + Base64URL.encode(Data(text.utf8)) |
| } |
| /// Whether `account` is one of `identity`'s teams: signing out of an |
| /// identity ends all of them. |
| - public static func account(_ account: String, belongsTo identity: String) -> Bool { |
| - account.hasPrefix("oficina-id." + identity + ".") |
| + nonisolated public static func account(_ account: String, belongsTo identity: String) -> Bool { |
| + account.hasPrefix(prefix + component(identity) + ".") |
| } |
| + /// Whether `account` is an Oficina ID team's, as against a server |
| + /// account's (a UUID). |
| + nonisolated public static func isOficinaAccount(_ account: String) -> Bool { account.hasPrefix(prefix) } |
| + |
| /// The client for `account`'s latest session, or nil once the identity |
| /// has signed out. One client per session, so requests share a |
| /// URLSession instead of making one each. |
| @@ -111,9 +154,11 @@ public enum DocsSignInRoute: String, Sendable { |
| 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 |
| + return DocsSessionWatch(inner: client, rejected: { [weak self] in |
| Task { @MainActor in await self?.rejected(account) } |
| - } |
| + }, refused: { [weak self] in |
| + Task { @MainActor in await self?.refused() } |
| + }) |
| } |
| } |
| @@ -138,7 +183,19 @@ public enum DocsSignInRoute: String, Sendable { |
| await model.sessionRejected() |
| } |
| + /// Called as the step is about to change (`@Published` publishes before |
| + /// the property is set), so `model.step` is still the previous one. |
| private func stepChanged(_ step: OficinaIDModel.Step) { |
| + let previous = model.step |
| + switch step { |
| + case .signedIn(let state): |
| + mounted = state |
| + if case .signedIn = previous {} else if previous != .loading { signIns += 1 } |
| + case .unavailable(let team) where mounted?.team.sqid == team.sqid && model.identity?.id == mounted?.identity.id: |
| + break |
| + default: |
| + mounted = nil |
| + } |
| if case .signedIn(let state) = step { |
| let account = Self.accountID(state) |
| let previous = sessions[account]?.session |
| @@ -158,18 +215,46 @@ public enum DocsSignInRoute: String, Sendable { |
| } |
| } |
| +/// Why Docs won't sign out, switch team or replace the Oficina ID just now, |
| +/// in a line the person sees instead of a button that silently does nothing. |
| +public enum DocsLeaveBlock: Equatable, Sendable { |
| + /// Changes on this device are still to be sent, in this window or in any |
| + /// team of the identity (an outbox left by a crash included). |
| + case sending |
| + /// A document window of one of the identity's teams is open (Mac). |
| + case openDocuments |
| + |
| + public var message: String { |
| + NSLocalizedString(self == .sending ? "native.leave.sending" : "native.leave.openDocuments", |
| + bundle: DocsResources.bundle, comment: "") |
| + } |
| + |
| + /// The identity-wide guard: open document windows first, then anything |
| + /// this window or any of the identity's teams has not sent. |
| + @MainActor public static func check(identity: String, openDocuments: Bool, unsentHere: Bool = false) async -> DocsLeaveBlock? { |
| + if openDocuments { return .openDocuments } |
| + if unsentHere { return .sending } |
| + return await DocsOfflineAccount.hasUnsent(identity: identity) ? .sending : nil |
| + } |
| +} |
| + |
| /// A transport that tells Docs when the instance refuses its session: a 401, |
| /// or the 303 to sign-in that `NativeClientError` also reads as an ended |
| -/// session. Everything else passes through untouched. |
| +/// session; and when it refuses a request, a 403. Everything else passes |
| +/// through untouched. |
| struct DocsSessionWatch: NativeTransport { |
| let inner: NativeTransport |
| let rejected: @Sendable () -> Void |
| + /// A 403: refused this request, not the session. Docs refreshes the team |
| + /// list on it (spec §9). |
| + var refused: @Sendable () -> Void = {} |
| var origin: URL { inner.origin } |
| 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() } |
| + if reply.status == 403 { refused() } |
| return reply |
| } |
| @@ -191,10 +276,11 @@ import Security |
| /// 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. |
| +/// against the entitlements as it starts the process. This then checks the |
| +/// signed entitlements (keychain groups in order, the App Group, the |
| +/// associated domain) and reads, never writes, both keychain groups. It |
| +/// prints what it found and exits 0 only if all of it works. It prints |
| +/// counts, never an identity or a session. |
| public enum DocsOficinaLaunchCheck { |
| public static let argument = "--oficina-id-launch-check" |
| @@ -206,8 +292,7 @@ public enum DocsOficinaLaunchCheck { |
| } |
| 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] ?? [] |
| + let groups = entitlement("keychain-access-groups") |
| // A query that names no group lands in the first: it must be Docs' own. |
| guard groups.first == own, groups.contains(OficinaKeychainStore.sharedGroup) else { |
| throw LaunchCheckError("expected [\(own), \(OficinaKeychainStore.sharedGroup)], got \(groups)") |
| @@ -225,14 +310,30 @@ public enum DocsOficinaLaunchCheck { |
| check("Docs' group \(own)") { |
| "readable, \(try OficinaKeychainStore(accessGroup: own).accounts(service: "works.oficina.id.session").count) sessions" |
| } |
| + // On a Mac, containerURL answers for any app group, granted or not, |
| + // so the entitlement itself is what proves the grant. |
| check("App Group \(DocsOficinaSession.appGroup)") { |
| - guard FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: DocsOficinaSession.appGroup) != nil, |
| - UserDefaults(suiteName: DocsOficinaSession.appGroup) != nil else { throw LaunchCheckError("no container") } |
| - return "container available" |
| + let groups = entitlement("com.apple.security.application-groups") |
| + guard groups.contains(DocsOficinaSession.appGroup) else { |
| + throw LaunchCheckError("not granted: com.apple.security.application-groups is \(groups)") |
| + } |
| + guard UserDefaults(suiteName: DocsOficinaSession.appGroup) != nil else { throw LaunchCheckError("no defaults suite") } |
| + return "granted" |
| + } |
| + check("associated domains") { |
| + let domains = entitlement("com.apple.developer.associated-domains") |
| + guard domains.contains("webcredentials:id.oficina.works") else { throw LaunchCheckError("got \(domains)") } |
| + return domains.joined(separator: ", ") |
| } |
| return (passed, lines) |
| } |
| + /// A string-array entitlement of this process, as signed. |
| + static func entitlement(_ key: String) -> [String] { |
| + guard let task = SecTaskCreateFromSelf(nil) else { return [] } |
| + return SecTaskCopyValueForEntitlement(task, key as CFString, nil) as? [String] ?? [] |
| + } |
| + |
| struct LaunchCheckError: Error, CustomStringConvertible { |
| let description: String |
| init(_ description: String) { self.description = description } |
diff --git a/native/apple/Sources/DocsKit/DocsOficinaViews.swift b/native/apple/Sources/DocsKit/DocsOficinaViews.swift| index 320e749..54bf95e 100644 |
| --- a/native/apple/Sources/DocsKit/DocsOficinaViews.swift |
| +++ b/native/apple/Sources/DocsKit/DocsOficinaViews.swift |
| @@ -7,19 +7,28 @@ import SwiftUI |
| @MainActor public struct DocsTeamPicker: View { |
| @ObservedObject private var model: OficinaIDModel |
| private let current: OficinaSignedIn |
| - private let canLeave: Bool |
| + private let leaveCheck: @MainActor () async -> DocsLeaveBlock? |
| + private let refresh: @MainActor () async -> Void |
| + @State private var block: DocsLeaveBlock? |
| + @State private var checked = false |
| 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, |
| + /// `leaveCheck` says why switching team or signing out would strand |
| + /// something (open document windows, changes not yet sent), and the |
| + /// picker shows that line by the controls it disables. `refresh` fetches |
| + /// the team list again if it is five minutes old (spec §9). |
| + public init(model: OficinaIDModel, current: OficinaSignedIn, |
| + leaveCheck: @escaping @MainActor () async -> DocsLeaveBlock? = { nil }, |
| + refresh: @escaping @MainActor () async -> Void = {}, |
| otherWays: @escaping () -> Void, signOut: @escaping () -> Void, done: @escaping () -> Void) { |
| - self.model = model; self.current = current; self.canLeave = canLeave |
| + self.model = model; self.current = current; self.leaveCheck = leaveCheck; self.refresh = refresh |
| self.otherWays = otherWays; self.signOut = signOut; self.done = done |
| } |
| + private var canLeave: Bool { checked && block == nil } |
| + |
| /// 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 } |
| @@ -50,7 +59,10 @@ import SwiftUI |
| .accessibilityAddTraits(team.sqid == current.team.sqid ? .isSelected : []) |
| .accessibilityIdentifier("docs.team-\(team.label)") |
| } |
| - } header: { Text("native.oficinaid.teams", bundle: DocsResources.bundle) } |
| + } header: { Text("native.oficinaid.teams", bundle: DocsResources.bundle) } footer: { |
| + if let block { DocsBlockLine(block) } |
| + else if let error = model.error { OficinaErrorLine(error) } |
| + } |
| Section { |
| Button(OficinaIDText.text("otherWays")) { otherWays() } |
| .buttonStyle(.borderless) |
| @@ -59,12 +71,17 @@ import SwiftUI |
| Text(verbatim: OficinaIDText.text("signOut", current.identity.label)) |
| } |
| .buttonStyle(.borderless) |
| - .foregroundStyle(OficinaPalette.negative) |
| + // Its own colour would hide that it is disabled. |
| + .foregroundStyle(canLeave ? OficinaPalette.negative : OficinaPalette.textMuted) |
| .disabled(!canLeave) |
| .accessibilityIdentifier("docs.oficinaid.signOut") |
| } |
| } |
| .navigationTitle(Text("native.oficinaid.teams", bundle: DocsResources.bundle)) |
| + .task { |
| + block = await leaveCheck(); checked = true |
| + await refresh() |
| + } |
| #if os(iOS) |
| .navigationBarTitleDisplayMode(.inline) |
| #endif |
| @@ -87,6 +104,17 @@ import SwiftUI |
| } |
| } |
| +/// The one line that says why a control is disabled. |
| +public struct DocsBlockLine: View { |
| + private let block: DocsLeaveBlock |
| + public init(_ block: DocsLeaveBlock) { self.block = block } |
| + public var body: some View { |
| + Label(block.message, systemImage: "info.circle").font(.callout).foregroundStyle(OficinaPalette.textMuted) |
| + .fixedSize(horizontal: false, vertical: true) |
| + .accessibilityIdentifier("docs.leaveBlock") |
| + } |
| +} |
| + |
| /// "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. With no account kept yet it is the sign-in |
| @@ -132,15 +160,17 @@ public struct DocsSettingsView: View { |
| } |
| private let account: Account |
| - private let canSignOut: Bool |
| + private let block: DocsLeaveBlock? |
| 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, |
| + /// `block` is the home window's guard: while it says why, "Change |
| + /// team…" and "Sign out" are disabled and the line is shown. |
| + public init(account: Account, block: DocsLeaveBlock?, version: String = DocsSettingsView.bundleVersion, |
| manage: @escaping () -> Void, signOut: @escaping () -> Void, signIn: @escaping () -> Void) { |
| - self.account = account; self.canSignOut = canSignOut; self.version = version |
| + self.account = account; self.block = block; self.version = version |
| self.manage = manage; self.signOut = signOut; self.signIn = signIn |
| } |
| @@ -159,20 +189,24 @@ public struct DocsSettingsView: View { |
| LabeledContent { Text(verbatim: "\(team) (\(teamLabel))") } label: { Text("native.settings.team", bundle: DocsResources.bundle) } |
| HStack { |
| Button { manage() } label: { Text("native.settings.changeTeam", bundle: DocsResources.bundle) } |
| + .disabled(block != nil) |
| Spacer() |
| Button(role: .destructive) { signOut() } label: { Text(verbatim: OficinaIDText.text("signOut", identity)) } |
| - .disabled(!canSignOut) |
| + .disabled(block != nil) |
| } |
| + if let block { DocsBlockLine(block) } |
| 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) } |
| + .disabled(block != nil) |
| Spacer() |
| Button(role: .destructive) { signOut() } label: { Text("docs.signout.label", bundle: DocsResources.bundle) } |
| - .disabled(!canSignOut) |
| + .disabled(block != nil) |
| } |
| + if let block { DocsBlockLine(block) } |
| 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) } |
diff --git a/native/apple/Sources/DocsKit/DocsSharingView.swift b/native/apple/Sources/DocsKit/DocsSharingView.swift| index 00b8f50..a80941b 100644 |
| --- a/native/apple/Sources/DocsKit/DocsSharingView.swift |
| +++ b/native/apple/Sources/DocsKit/DocsSharingView.swift |
| @@ -2,7 +2,7 @@ import RastrilloApple |
| import SwiftUI |
| @MainActor struct DocsSharingView: View { |
| - let client: NativeHTTP |
| + let client: NativeTransport |
| let sqid: String |
| @Environment(\.dismiss) private var dismiss |
| @State private var information: DocsShareInformation? |
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift| index ad98569..9a26437 100644 |
| --- a/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| +++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| @@ -34,6 +34,9 @@ import SwiftUI |
| private let signOut: () -> Void |
| private let accounts: (() -> Void)? |
| private let client: NativeHTTP |
| + private let transport: (@MainActor () -> NativeTransport?)? |
| + /// Why a sign-out asked from Settings was refused, said rather than swallowed. |
| + @State private var signOutRefusal: DocsLeaveBlock? |
| /// `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), signOutRequested: Binding<Bool> = .constant(false), accountsLabel: String? = nil, signOutLabel: String? = nil, openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil) { |
| @@ -41,7 +44,7 @@ import SwiftUI |
| 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) } |
| - _model = State(initialValue: DocsModel(transport: transport ?? { client }, draft: newDocument, offlineAccount: offline)); self.signOut = signOut; self.accounts = accounts; self.client = client |
| + _model = State(initialValue: DocsModel(transport: transport ?? { client }, draft: newDocument, offlineAccount: offline)); self.signOut = signOut; self.accounts = accounts; self.client = client; self.transport = transport |
| } |
| private var library: some View { |
| List { |
| @@ -100,6 +103,9 @@ import SwiftUI |
| Text("native.close", bundle: DocsResources.bundle) |
| } |
| } |
| + .alert(signOutRefusal?.message ?? "", isPresented: Binding(get: { signOutRefusal != nil }, set: { if !$0 { signOutRefusal = nil } })) { |
| + Button { signOutRefusal = nil } label: { Text("native.close", bundle: DocsResources.bundle) } |
| + } |
| .onChange(of: model.documents.map { "\($0.sqid)\u{0}\($0.title)" }) { |
| if query.isEmpty { updateRecents?(model.documents.map { ($0.sqid, $0.title) }) } |
| } |
| @@ -111,7 +117,9 @@ import SwiftUI |
| .onChange(of: signOutRequested, initial: true) { _, requested in |
| guard requested, documentID == nil, !newDocument else { return } |
| signOutRequested = false |
| - if canSignOut && !model.hasUnsavedChanges && !model.creatingDocument { signOut() } |
| + if !canSignOut { signOutRefusal = .openDocuments } |
| + else if model.hasUnsavedChanges || model.creatingDocument { signOutRefusal = .sending } |
| + else { signOut() } |
| } |
| .onChange(of: createRequested, initial: true) { _, requested in |
| if requested && documentID == nil { beginDocument(); createRequested = false } |
| @@ -121,7 +129,7 @@ import SwiftUI |
| .onChange(of: [model.detail?.sqid, model.detail?.title]) { |
| if !model.isDraft, let detail = model.detail { documentChanged?(detail.sqid, detail.title) } |
| } |
| - .sheet(isPresented: $jumping) { DocsJumpSheet(model: model, client: client) } |
| + .sheet(isPresented: $jumping) { DocsJumpSheet(model: model, client: liveClient) } |
| .onDisappear { Task { await model.stop() } } |
| .onChange(of: scenePhase) { _, phase in |
| if phase == .background { Task { await model.persistReplica() } } |
| @@ -138,9 +146,19 @@ import SwiftUI |
| Text("native.close.pending.detail", bundle: DocsResources.bundle) |
| } |
| .sheet(isPresented: $sharing) { |
| - if let detail = model.detail { DocsSharingView(client: client, sqid: detail.sqid) } |
| + if let detail = model.detail { DocsSharingView(client: liveClient, sqid: detail.sqid) } |
| } |
| } |
| + /// The client sharing, export, images and Jump use, resolved when they |
| + /// use it: the account's current session (re-minted every 24 hours and |
| + /// on a 401, and watched for both) when the window has a supplier, the |
| + /// one it was opened with otherwise. |
| + private var liveClient: NativeTransport { Self.liveClient(transport, fallback: client) } |
| + |
| + static func liveClient(_ transport: (@MainActor () -> NativeTransport?)?, fallback: NativeTransport) -> NativeTransport { |
| + transport?() ?? fallback |
| + } |
| + |
| private var signOutText: Text { |
| if let signOutLabel { return Text(verbatim: signOutLabel) } |
| return Text("docs.signout.label", bundle: DocsResources.bundle) |
| @@ -203,7 +221,7 @@ import SwiftUI |
| if model.loading { ProgressView() } |
| if let projection = model.projection { |
| let documentPath = "/d/" + (model.detail?.sqid ?? "") |
| - let text = NativeTextProjection.render(projection, images: images.images(forDocumentPath: documentPath, client: client)) |
| + let text = NativeTextProjection.render(projection, images: images.images(forDocumentPath: documentPath, client: liveClient)) |
| EditorToolbar(model: model, content: text) |
| Divider() |
| NativeDocumentTextView(content: text, generation: model.projectionGeneration, didRender: model.didRender, compositionChanged: model.compositionChanged, isEditable: model.detail?.can_write == true && !model.inputPaused, paged: paged, pendingInput: model.hasPendingInput, canRender: model.canRender, currentSelection: model.currentSelection, selection: $model.selection, edit: model.enqueue, action: { action in |
| @@ -218,7 +236,7 @@ import SwiftUI |
| return DocumentCommands(model: model, content: text).perform(action) |
| }, selectionMoved: model.selectionMovedExplicitly, canAction: { action in model.detail?.can_write == true && !model.hasPendingInput && !model.composing && !model.inputPaused && (action == "undo" ? projection.canUndo : projection.canRedo) }, explicitCommandRevision: model.explicitCommandRevision, zoom: zoom, typingMarks: model.typingMarks) |
| .id(model.editorIdentity) |
| - .task(id: [documentPath] + DocsImageStore.sources(in: projection)) { await images.load(sources: DocsImageStore.sources(in: projection), client: client, documentPath: documentPath) } |
| + .task(id: [documentPath] + DocsImageStore.sources(in: projection)) { await images.load(sources: DocsImageStore.sources(in: projection), client: liveClient, documentPath: documentPath) } |
| } else { |
| ContentUnavailableView { Label { Text("native.open", bundle: DocsResources.bundle) } icon: { Image(systemName: "doc.text") } } |
| } |
| @@ -232,7 +250,7 @@ import SwiftUI |
| DocsJumpControls(presented: $jumping) |
| if let detail = model.detail, !model.isDraft { |
| Toggle(isOn: $paged) { Text("docs.editor.menu.view.paged", bundle: DocsResources.bundle) } |
| - DocumentExportControls(client: client, sqid: detail.sqid, title: detail.title) { |
| + DocumentExportControls(client: liveClient, sqid: detail.sqid, title: detail.title) { |
| return await model.saveAll() |
| }.id(detail.sqid) |
| if let projection = model.projection { DocsToolsControls(projection: projection, content: NativeTextProjection.render(projection), selection: model.selection) } |
| @@ -246,7 +264,7 @@ import SwiftUI |
| #else |
| .background { |
| if let detail = model.detail, !model.isDraft { |
| - DocumentExportControls(client: client, sqid: detail.sqid, title: detail.title, prepare: { await model.saveAll() }, request: $exportRequest) |
| + DocumentExportControls(client: liveClient, sqid: detail.sqid, title: detail.title, prepare: { await model.saveAll() }, request: $exportRequest) |
| .frame(width: 0, height: 0).hidden().accessibilityHidden(true) |
| } |
| } |
| @@ -273,7 +291,7 @@ import SwiftUI |
| .overlay(alignment: .leading) { Divider() } |
| } |
| } |
| - .focusedSceneValue(\.docsEditor, DocsEditorContext(model: model, rename: beginRename, client: client, zoom: $zoom, paged: $paged, inspecting: $inspecting, sharing: $sharing, exportRequest: $exportRequest)) |
| + .focusedSceneValue(\.docsEditor, DocsEditorContext(model: model, rename: beginRename, client: liveClient, zoom: $zoom, paged: $paged, inspecting: $inspecting, sharing: $sharing, exportRequest: $exportRequest)) |
| #endif |
| } |
diff --git a/native/apple/Sources/DocsKit/DocumentExportControls.swift b/native/apple/Sources/DocsKit/DocumentExportControls.swift| index 7db4b70..d84fa0e 100644 |
| --- a/native/apple/Sources/DocsKit/DocumentExportControls.swift |
| +++ b/native/apple/Sources/DocsKit/DocumentExportControls.swift |
| @@ -23,7 +23,7 @@ struct ExportedDocument: Transferable { |
| } |
| } |
| @MainActor struct DocumentExportControls: View { |
| - let client: NativeHTTP |
| + let client: NativeTransport |
| let sqid: String |
| let title: String |
| let prepare: () async -> Bool |
| @@ -34,7 +34,7 @@ struct ExportedDocument: Transferable { |
| @State private var active = true |
| @State private var type = UTType.pdf |
| @State private var failed = false |
| - init(client: NativeHTTP, sqid: String, title: String, prepare: @escaping () async -> Bool, request: Binding<String?> = .constant(nil)) { |
| + init(client: NativeTransport, sqid: String, title: String, prepare: @escaping () async -> Bool, request: Binding<String?> = .constant(nil)) { |
| self.client = client; self.sqid = sqid; self.title = title; self.prepare = prepare; self._request = request |
| } |
| var body: some View { |
diff --git a/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings| index 375d38d..a2c0b6a 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings |
| @@ -203,3 +203,5 @@ |
| "native.settings.changeTeam" = "تغيير الفريق…"; |
| "native.settings.accounts" = "الحسابات…"; |
| "native.settings.signIn" = "تسجيل الدخول…"; |
| +"native.leave.sending" = "لا يزال Docs يرسل التغييرات. حاول مرة أخرى بعد حفظها."; |
| +"native.leave.openDocuments" = "أغلق المستندات المفتوحة لهذا الحساب أولًا."; |
diff --git a/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings| index 8d45471..14855a7 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings |
| @@ -203,3 +203,5 @@ |
| "native.settings.changeTeam" = "টিম পরিবর্তন করুন…"; |
| "native.settings.accounts" = "অ্যাকাউন্ট…"; |
| "native.settings.signIn" = "সাইন ইন করুন…"; |
| +"native.leave.sending" = "Docs এখনও পরিবর্তন পাঠাচ্ছে। সেগুলি সংরক্ষিত হলে আবার চেষ্টা করুন।"; |
| +"native.leave.openDocuments" = "প্রথমে এই অ্যাকাউন্টের খোলা ডকুমেন্টগুলি বন্ধ করুন।"; |
diff --git a/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings| index b3858ee..5a3688f 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings |
| @@ -208,3 +208,5 @@ |
| "native.settings.changeTeam" = "Change team…"; |
| "native.settings.accounts" = "Accounts…"; |
| "native.settings.signIn" = "Sign in…"; |
| +"native.leave.sending" = "Docs is still sending changes. Try again once they’re saved."; |
| +"native.leave.openDocuments" = "Close this account’s open documents first."; |
diff --git a/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings| index cab782b..b068458 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings |
| @@ -203,3 +203,5 @@ |
| "native.settings.changeTeam" = "Cambiar de equipo…"; |
| "native.settings.accounts" = "Cuentas…"; |
| "native.settings.signIn" = "Iniciar sesión…"; |
| +"native.leave.sending" = "Docs todavía está enviando cambios. Inténtalo de nuevo cuando se hayan guardado."; |
| +"native.leave.openDocuments" = "Cierra primero los documentos abiertos de esta cuenta."; |
diff --git a/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings| index 2ada34a..145a95a 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings |
| @@ -203,3 +203,5 @@ |
| "native.settings.changeTeam" = "Athraigh foireann…"; |
| "native.settings.accounts" = "Cuntais…"; |
| "native.settings.signIn" = "Sínigh isteach…"; |
| +"native.leave.sending" = "Tá Docs fós ag seoladh athruithe. Bain triail eile as nuair a bheidh siad sábháilte."; |
| +"native.leave.openDocuments" = "Dún doiciméid oscailte an chuntais seo ar dtús."; |
diff --git a/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings| index 92ea72a..2f8bcc7 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings |
| @@ -203,3 +203,5 @@ |
| "native.settings.changeTeam" = "टीम बदलें…"; |
| "native.settings.accounts" = "खाते…"; |
| "native.settings.signIn" = "साइन इन करें…"; |
| +"native.leave.sending" = "Docs अभी भी बदलाव भेज रहा है। उनके सहेजे जाने के बाद फिर से कोशिश करें।"; |
| +"native.leave.openDocuments" = "पहले इस खाते के खुले दस्तावेज़ बंद करें।"; |
diff --git a/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings| index 7e07cc5..5e26a65 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings |
| @@ -203,3 +203,5 @@ |
| "native.settings.changeTeam" = "チームを変更…"; |
| "native.settings.accounts" = "アカウント…"; |
| "native.settings.signIn" = "サインイン…"; |
| +"native.leave.sending" = "Docs はまだ変更を送信中です。保存されてからもう一度お試しください。"; |
| +"native.leave.openDocuments" = "先にこのアカウントの開いている書類を閉じてください。"; |
diff --git a/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings| index 51ab635..2879eac 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings |
| @@ -203,3 +203,5 @@ |
| "native.settings.changeTeam" = "Mudar de equipa…"; |
| "native.settings.accounts" = "Contas…"; |
| "native.settings.signIn" = "Iniciar sessão…"; |
| +"native.leave.sending" = "O Docs ainda está a enviar alterações. Tente de novo quando estiverem guardadas."; |
| +"native.leave.openDocuments" = "Feche primeiro os documentos abertos desta conta."; |
diff --git a/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings| index 952fb69..980a775 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings |
| @@ -203,3 +203,5 @@ |
| "native.settings.changeTeam" = "Сменить команду…"; |
| "native.settings.accounts" = "Учётные записи…"; |
| "native.settings.signIn" = "Войти…"; |
| +"native.leave.sending" = "Docs ещё отправляет изменения. Повторите попытку, когда они сохранятся."; |
| +"native.leave.openDocuments" = "Сначала закройте открытые документы этой учётной записи."; |
diff --git a/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings| index 2d68612..6584734 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings |
| @@ -203,3 +203,5 @@ |
| "native.settings.changeTeam" = "Đổi nhóm…"; |
| "native.settings.accounts" = "Tài khoản…"; |
| "native.settings.signIn" = "Đăng nhập…"; |
| +"native.leave.sending" = "Docs vẫn đang gửi các thay đổi. Hãy thử lại khi chúng đã được lưu."; |
| +"native.leave.openDocuments" = "Hãy đóng các tài liệu đang mở của tài khoản này trước."; |
diff --git a/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings| index 9fca162..d5f470a 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings |
| @@ -203,3 +203,5 @@ |
| "native.settings.changeTeam" = "轉團隊…"; |
| "native.settings.accounts" = "帳戶…"; |
| "native.settings.signIn" = "登入…"; |
| +"native.leave.sending" = "Docs 仲傳緊啲改動。儲存好之後再試吓。"; |
| +"native.leave.openDocuments" = "請先閂咗呢個帳戶開緊嘅文件。"; |
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 21c35ce..2f929b0 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings |
| @@ -203,3 +203,5 @@ |
| "native.settings.changeTeam" = "更换团队…"; |
| "native.settings.accounts" = "账户…"; |
| "native.settings.signIn" = "登录…"; |
| +"native.leave.sending" = "Docs 仍在发送更改。保存后请重试。"; |
| +"native.leave.openDocuments" = "请先关闭此账户中打开的文档。"; |
diff --git a/native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift b/native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift| index 614bfc8..1f33066 100644 |
| --- a/native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift |
| +++ b/native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift |
| @@ -1,5 +1,7 @@ |
| +import CryptoKit |
| import Foundation |
| import RastrilloApple |
| +import RastrilloNative |
| import RastrilloTestSupport |
| import XCTest |
| @testable import DocsKit |
| @@ -36,21 +38,39 @@ import XCTest |
| apps: apps.map { OficinaTeamApp(app: $0, origin: "https://\(label).\($0).oficina.works", consumerID: "\(sqid)-\($0)") }) |
| } |
| - private func session() -> DocsOficinaSession { |
| + /// One device: the shared and private stores, the App Group and Docs' |
| + /// own defaults outlive an app run, so a second session on the same |
| + /// device is Docs launched again. |
| + final class Device { |
| + let shared = OficinaMemoryStore(), own = OficinaMemoryStore() |
| + let group: UserDefaults, defaults: UserDefaults |
| + init(group: UserDefaults, defaults: UserDefaults) { self.group = group; self.defaults = defaults } |
| + } |
| + |
| + private func device() -> Device { Device(group: defaults(), defaults: defaults()) } |
| + |
| + private func session(on device: Device? = nil) -> DocsOficinaSession { |
| let clock = self.clock! |
| - let store = OficinaIDStore(shared: OficinaMemoryStore(), appPrivate: OficinaMemoryStore(), group: defaults()) |
| + let device = device ?? self.device() |
| + let store = OficinaIDStore(shared: device.shared, appPrivate: device.own, group: device.group) |
| let model = OficinaIDModel(configuration: DocsOficinaSession.configuration, store: store, service: service, |
| passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, now: { clock.date }, |
| - appDefaults: defaults()) |
| + appDefaults: device.defaults) |
| return DocsOficinaSession(model: model, now: { clock.date }) |
| } |
| + private func onePaulTeam(_ identity: String = "id-paul", email: String = "paul@tito.io") { |
| + service.addPerson(email: email, identityID: identity) |
| + service.setTeams([team("t1", "Paul", "paulca")], for: identity) |
| + service.admit(identity, at: paulca, as: .linked) |
| + } |
| + |
| /// Welcome → Email → Code, as a person would. |
| - private func signIn(_ session: DocsOficinaSession) async { |
| + private func signIn(_ session: DocsOficinaSession, email: String = "paul@tito.io") async { |
| await session.start() |
| - XCTAssertEqual(session.model.step, .welcome) |
| + if session.model.step != .email { XCTAssertEqual(session.model.step, .welcome) } |
| session.model.continueWithEmail() |
| - session.model.email = "paul@tito.io" |
| + session.model.email = email |
| await session.model.submitEmail() |
| session.model.code = FakeOficinaIDService.goodCode |
| await session.model.submitCode() |
| @@ -186,4 +206,243 @@ import XCTest |
| } catch NativeClientError.unauthorized {} |
| XCTAssertEqual(count.value, 3) |
| } |
| + |
| + // MARK: Review round (Fable, d143194) |
| + |
| + func testIdentityAndTeamThatAreNotPathSafeAreEncoded() { |
| + let odd = DocsOficinaSession.accountID(identity: "a/b", team: "c.d") |
| + XCTAssertFalse(odd.contains("/")) |
| + XCTAssertEqual(odd.split(separator: ".").count, 3, "prefix, identity, team: no stray dots") |
| + XCTAssertTrue(DocsOficinaSession.account(odd, belongsTo: "a/b")) |
| + XCTAssertFalse(DocsOficinaSession.account(odd, belongsTo: "a")) |
| + XCTAssertNotEqual(DocsOficinaSession.accountID(identity: "a", team: "b"), DocsOficinaSession.accountID(identity: "~a", team: "b")) |
| + XCTAssertEqual(DocsOficinaSession.accountID(identity: "Ab_9-z", team: "t1"), "oficina-id.Ab_9-z.t1", "safe parts stay readable") |
| + XCTAssertTrue(DocsOficinaSession.isOficinaAccount(odd)) |
| + XCTAssertFalse(DocsOficinaSession.isOficinaAccount(UUID().uuidString)) |
| + } |
| + |
| + func testReplacingTheIdentityPurgesItsSessions() async throws { |
| + onePaulTeam() |
| + onePaulTeam("id-till", email: "till@lagged.io") |
| + let docs = session() |
| + await signIn(docs) |
| + let paul = DocsOficinaSession.accountID(try XCTUnwrap(docs.signedIn)) |
| + docs.model.useAnother() |
| + XCTAssertTrue(docs.model.confirmingReplace) |
| + docs.model.confirmReplace() |
| + XCTAssertNil(docs.transport(for: paul)(), "the replaced identity's workspaces get no session") |
| + XCTAssertNil(docs.mounted) |
| + await signIn(docs, email: "till@lagged.io") |
| + let till = DocsOficinaSession.accountID(try XCTUnwrap(docs.signedIn)) |
| + XCTAssertNotEqual(till, paul) |
| + XCTAssertNotNil(docs.transport(for: till)()) |
| + XCTAssertNil(docs.transport(for: paul)(), "and never comes back") |
| + } |
| + |
| + func testAReMintRestartsAnOutboxStoppedByTheEndedSession() async throws { |
| + onePaulTeam() |
| + let docs = session() |
| + await signIn(docs) |
| + let account = DocsOficinaSession.accountID(try XCTUnwrap(docs.signedIn)) |
| + var supplied: NativeTransport? = nil |
| + let offline = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: account, |
| + connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), |
| + transport: { supplied }) |
| + DocsOfflineAccount.accounts[account] = offline |
| + defer { DocsOfflineAccount.accounts[account] = nil } |
| + try await offline.outbox.enqueue(lane: "doc:k", kind: "update", payload: Data([1])) |
| + let stopped = await offline.drainer.drain() |
| + XCTAssertEqual(stopped, .sessionEnded) |
| + XCTAssertTrue(offline.drainer.sessionEnded) |
| + supplied = docs.transport(for: account)() |
| + await docs.rejected(account) |
| + XCTAssertFalse(offline.drainer.sessionEnded, "the new session restarts the stopped outbox") |
| + } |
| + |
| + func testA401WithHomeDownKeepsTheWorkspaceMounted() async throws { |
| + onePaulTeam() |
| + let docs = session() |
| + await signIn(docs) |
| + let first = try XCTUnwrap(docs.signedIn) |
| + let account = DocsOficinaSession.accountID(first) |
| + service.expire(session: first.session) |
| + service.failNext("assert", with: .offline) |
| + await docs.rejected(account) |
| + guard case .unavailable = docs.model.step else { return XCTFail("Home down: \(docs.model.step)") } |
| + XCTAssertEqual(docs.mounted, first, "the open workspace stays, under the Can't reach line") |
| + XCTAssertNotNil(docs.transport(for: account)()) |
| + await docs.model.retry() |
| + let second = try XCTUnwrap(docs.signedIn) |
| + XCTAssertEqual(docs.mounted, second) |
| + XCTAssertNotEqual(second.session.value, first.session.value) |
| + XCTAssertEqual(docs.client(for: account)?.credential?.value, second.session.value) |
| + } |
| + |
| + func testOnlyASignInMadeHereCountsNotARestore() async throws { |
| + onePaulTeam() |
| + let device = device() |
| + let first = session(on: device) |
| + await signIn(first) |
| + XCTAssertNotNil(first.signedIn) |
| + XCTAssertEqual(first.signIns, 1) |
| + // Docs launched again: the team comes back with no sign-in. |
| + let again = session(on: device) |
| + await again.start() |
| + XCTAssertNotNil(again.signedIn) |
| + XCTAssertEqual(again.signIns, 0, "a restored identity must not change the route someone chose") |
| + } |
| + |
| + func testRenewAfterADayGoesThroughTheSession() async throws { |
| + onePaulTeam() |
| + let docs = session() |
| + await signIn(docs) |
| + let first = try XCTUnwrap(docs.signedIn) |
| + let account = DocsOficinaSession.accountID(first) |
| + await docs.renewIfNeeded() |
| + XCTAssertEqual(exchanges(at: paulca), 1, "a fresh session is kept") |
| + clock.date.addTimeInterval(25 * 3600) |
| + await docs.renewIfNeeded() |
| + XCTAssertEqual(exchanges(at: paulca), 2) |
| + let renewed = try XCTUnwrap(docs.signedIn) |
| + XCTAssertNotEqual(renewed.session.value, first.session.value) |
| + XCTAssertEqual(docs.client(for: account)?.credential?.value, renewed.session.value) |
| + } |
| + |
| + func testTeamsRefreshAtLaunchOnTheMenuAndOnA403() async throws { |
| + onePaulTeam() |
| + let device = device() |
| + await signIn(session(on: device)) |
| + let titoTeam = team("t2", "Tito", "tito") |
| + service.setTeams([team("t1", "Paul", "paulca"), titoTeam], for: "id-paul") |
| + let teamsCalls = { self.service.calls.filter { $0 == "teams" }.count } |
| + clock.date.addTimeInterval(301) |
| + let docs = session(on: device) |
| + await docs.start() |
| + XCTAssertEqual(docs.model.store.teams("id-paul")?.teams.map(\.sqid), ["t1", "t2"], "launch refreshes") |
| + let afterLaunch = teamsCalls() |
| + await docs.pickerOpened() |
| + XCTAssertEqual(teamsCalls(), afterLaunch, "the menu waits five minutes") |
| + service.setTeams([team("t1", "Paul", "paulca")], for: "id-paul") |
| + await docs.refused() |
| + XCTAssertEqual(docs.model.store.teams("id-paul")?.teams.map(\.sqid), ["t1"], "a 403 refreshes at once") |
| + await docs.refused() |
| + XCTAssertEqual(teamsCalls(), afterLaunch + 1, "at most once a minute") |
| + clock.date.addTimeInterval(301) |
| + await docs.pickerOpened() |
| + XCTAssertEqual(teamsCalls(), afterLaunch + 2) |
| + } |
| + |
| + func testTheWatchReports403sAsRefusals() async throws { |
| + final class Count: @unchecked Sendable { var rejected = 0, refused = 0 } |
| + let count = Count() |
| + let watch = DocsSessionWatch(inner: ScriptedTransport([.respond(status: 403), .respond(status: 200)]), |
| + rejected: { count.rejected += 1 }, refused: { count.refused += 1 }) |
| + _ = 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.refused, 1) |
| + XCTAssertEqual(count.rejected, 0) |
| + } |
| + |
| + func testSharingExportImagesAndJumpUseTheCurrentSession() async throws { |
| + onePaulTeam() |
| + let docs = session() |
| + await signIn(docs) |
| + let first = try XCTUnwrap(docs.signedIn) |
| + let account = DocsOficinaSession.accountID(first) |
| + let opened = first.client() |
| + service.expire(session: first.session) |
| + await docs.rejected(account) |
| + let renewed = try XCTUnwrap(docs.signedIn) |
| + let live = DocsWorkspace.liveClient(docs.transport(for: account), fallback: opened) |
| + let watched = try XCTUnwrap(live as? DocsSessionWatch, "watched for 401s") |
| + XCTAssertEqual((watched.inner as? NativeHTTP)?.credential?.value, renewed.session.value) |
| + // A window without a supplier (a server account's) keeps its client. |
| + XCTAssertTrue(DocsWorkspace.liveClient(nil, fallback: opened) as AnyObject === opened) |
| + } |
| + |
| + // MARK: The store key outlives an origin change |
| + |
| + /// A keychain in memory, one item per KeychainKeyProvider account. |
| + final class MemoryKeychain: @unchecked Sendable { |
| + let lock = NSLock() |
| + var items: [String: StoreKeyState] = [:] |
| + struct Keys: KeyProvider { |
| + let chain: MemoryKeychain, account: String |
| + func copyKey() -> (OSStatus, SymmetricKey?) { |
| + chain.lock.withLock { chain.items[account].map { (errSecSuccess, SymmetricKey(data: $0.current)) } ?? (errSecItemNotFound, nil) } |
| + } |
| + func addKey(_ key: SymmetricKey) -> OSStatus { |
| + chain.lock.withLock { |
| + guard chain.items[account] == nil else { return errSecDuplicateItem } |
| + chain.items[account] = StoreKeyState(current: key.withUnsafeBytes { Data($0) }); return errSecSuccess |
| + } |
| + } |
| + func deleteKey() -> OSStatus { chain.lock.withLock { chain.items[account] = nil }; return errSecSuccess } |
| + func sealState() -> (OSStatus, StoreKeyState?) { |
| + chain.lock.withLock { chain.items[account].map { (errSecSuccess, $0) } ?? (errSecItemNotFound, nil) } |
| + } |
| + func saveSealState(_ state: StoreKeyState) -> OSStatus { chain.lock.withLock { chain.items[account] = state }; return errSecSuccess } |
| + } |
| + func keys(_ account: String, origin: URL) -> Keys { Keys(chain: self, account: DocsOfflineAccount.keys(accountID: account, origin: origin).account) } |
| + } |
| + |
| + func testAnOficinaTeamsStoreAndOutboxSurviveAnOriginChange() async throws { |
| + let root = FileManager.default.temporaryDirectory.appendingPathComponent("docs-origin-\(UUID().uuidString)") |
| + defer { try? FileManager.default.removeItem(at: root) } |
| + let chain = MemoryKeychain() |
| + let account = DocsOficinaSession.accountID(identity: "id-paul", team: "t1") |
| + let old = URL(string: "https://paul.docs.oficina.works")!, moved = URL(string: "https://paulca.docs.oficina.works")! |
| + let before = Outbox(store: NativeSealedStore(root: root, accountID: account, keys: chain.keys(account, origin: old)), account: account) |
| + try await before.enqueue(lane: "doc:k", kind: "update", payload: Data([7])) |
| + let after = Outbox(store: NativeSealedStore(root: root, accountID: account, keys: chain.keys(account, origin: moved)), account: account) |
| + try await after.load() |
| + let kept = await after.entries(lane: "doc:k", excludingInFlight: false) |
| + XCTAssertEqual(kept.map(\.payload), [Data([7])], "the label moved; the unsent change did not go with it") |
| + // A server account is its host: a new origin is a new account. |
| + let server = UUID().uuidString |
| + XCTAssertNotEqual(DocsOfflineAccount.keys(accountID: server, origin: old).account, |
| + DocsOfflineAccount.keys(accountID: server, origin: moved).account) |
| + } |
| + |
| + func testUnsentChangesLeftOnDiskBlockSigningOutOfThatIdentity() async throws { |
| + let root = FileManager.default.temporaryDirectory.appendingPathComponent("docs-unsent-\(UUID().uuidString)") |
| + defer { try? FileManager.default.removeItem(at: root) } |
| + let chain = MemoryKeychain() |
| + let account = DocsOficinaSession.accountID(identity: "id-paul", team: "t2") |
| + let keys: (String) -> KeyProvider = { chain.keys($0, origin: DocsOfflineAccount.oficinaKeyOrigin) } |
| + // An outbox a crash left behind, for a team not opened this run. |
| + let left = Outbox(store: NativeSealedStore(root: root.appendingPathComponent(account), accountID: account, keys: keys(account)), account: account) |
| + try await left.enqueue(lane: "doc:k", kind: "update", payload: Data([1])) |
| + let paul = await DocsOfflineAccount.hasUnsent(identity: "id-paul", root: root, keys: keys) |
| + let till = await DocsOfflineAccount.hasUnsent(identity: "id-till", root: root, keys: keys) |
| + XCTAssertTrue(paul) |
| + XCTAssertFalse(till) |
| + // Once sent, nothing blocks. |
| + let entries = await left.entries(lane: "doc:k", excludingInFlight: false) |
| + try await left.ack(entries.map(\.id)) |
| + let sent = await DocsOfflineAccount.hasUnsent(identity: "id-paul", root: root, keys: keys) |
| + XCTAssertFalse(sent) |
| + } |
| + |
| + func testTheLeaveGuardOrdersOpenDocumentsFirst() async { |
| + let open = await DocsLeaveBlock.check(identity: "id-nobody", openDocuments: true, unsentHere: true) |
| + XCTAssertEqual(open, .openDocuments) |
| + let unsent = await DocsLeaveBlock.check(identity: "id-nobody", openDocuments: false, unsentHere: true) |
| + XCTAssertEqual(unsent, .sending) |
| + XCTAssertFalse(DocsLeaveBlock.sending.message.isEmpty) |
| + XCTAssertNotEqual(DocsLeaveBlock.sending.message, "native.leave.sending", "the line is translated, not a key") |
| + } |
| + |
| + #if os(macOS) |
| + func testTheLaunchCheckFailsWithoutTheEntitlements() { |
| + // The test runner is not signed with Docs' entitlements: every check |
| + // that needs them must say FAIL, or the gate could not catch a build |
| + // that lost them. |
| + let result = DocsOficinaLaunchCheck.run() |
| + XCTAssertFalse(result.passed) |
| + for name in ["keychain-access-groups", "shared group", "Docs' group", "App Group", "associated domains"] { |
| + XCTAssertTrue(result.lines.contains { $0.hasPrefix("FAIL \(name)") }, "\(name): \(result.lines)") |
| + } |
| + } |
| + #endif |
| } |
diff --git a/native/apple/Tests/DocsSnapshots/DocsSnapshots.swift b/native/apple/Tests/DocsSnapshots/DocsSnapshots.swift| index 580eb5c..fb7faf1 100644 |
| --- a/native/apple/Tests/DocsSnapshots/DocsSnapshots.swift |
| +++ b/native/apple/Tests/DocsSnapshots/DocsSnapshots.swift |
| @@ -51,17 +51,27 @@ final class DocsSnapshots: XCTestCase { |
| DocsOtherWaysView(connection: Fixtures.connection()) {} |
| }, |
| SnapshotScreen("team-picker", mac: .fixed(width: 460, height: 540), iphone: .fixed(width: 402, height: 720)) { |
| - DocsTeamPicker(model: fixtures.signedIn, current: fixtures.signedInState, canLeave: true, |
| + DocsTeamPicker(model: fixtures.signedIn, current: fixtures.signedInState, |
| + otherWays: {}, signOut: {}, done: {}) |
| + }, |
| + SnapshotScreen("team-picker-blocked", mac: .fixed(width: 460, height: 540), iphone: .fixed(width: 402, height: 720)) { |
| + // Open documents or unsent changes: the switch and sign-out |
| + // are disabled, and the line says why. |
| + DocsTeamPicker(model: fixtures.signedIn, current: fixtures.signedInState, leaveCheck: { .sending }, |
| otherWays: {}, signOut: {}, done: {}) |
| }, |
| ] |
| #if os(macOS) |
| screens.append(SnapshotScreen("settings", mac: .width(480), iphone: nil) { |
| - DocsSettingsView(account: .oficinaID(identity: "paul@tito.io", team: "Paul", teamLabel: "paulca"), canSignOut: true, |
| + DocsSettingsView(account: .oficinaID(identity: "paul@tito.io", team: "Paul", teamLabel: "paulca"), block: nil, |
| + version: "0.1.0 (1)", manage: {}, signOut: {}, signIn: {}) |
| + }) |
| + screens.append(SnapshotScreen("settings-blocked", mac: .width(480), iphone: nil) { |
| + DocsSettingsView(account: .oficinaID(identity: "paul@tito.io", team: "Paul", teamLabel: "paulca"), block: .openDocuments, |
| version: "0.1.0 (1)", manage: {}, signOut: {}, signIn: {}) |
| }) |
| screens.append(SnapshotScreen("settings-server", mac: .width(480), iphone: nil) { |
| - DocsSettingsView(account: .server(name: "Tito", host: "tito.docs.oficina.works"), canSignOut: true, |
| + DocsSettingsView(account: .server(name: "Tito", host: "tito.docs.oficina.works"), block: nil, |
| version: "0.1.0 (1)", manage: {}, signOut: {}, signIn: {}) |
| }) |
| #endif |
diff --git a/native/apple/Tests/DocsWindowTests/WindowRoutingTests.swift b/native/apple/Tests/DocsWindowTests/WindowRoutingTests.swift| index e81c94a..5a8a74b 100644 |
| --- a/native/apple/Tests/DocsWindowTests/WindowRoutingTests.swift |
| +++ b/native/apple/Tests/DocsWindowTests/WindowRoutingTests.swift |
| @@ -2,6 +2,7 @@ |
| import Foundation |
| import Testing |
| import RastrilloApple |
| +import DocsKit |
| @testable import DocsMac |
| @MainActor @Test func windowsReuseDocumentsWithinAccountAndOriginOnly() { |
| @@ -42,3 +43,28 @@ import RastrilloApple |
| #expect(windows.canSignOut("a")) |
| } |
| #endif |
| +#if os(macOS) |
| +/// Signing out of an Oficina ID ends every one of its teams, so any open |
| +/// document window of any of them blocks it, and Settings asks the same. |
| +@MainActor @Test func oficinaIDSignOutIsBlockedByAnyOfItsTeamsOpenWindows() async { |
| + let windows = DocsWindows() |
| + let client = NativeHTTP(origin: URL(string: "https://tito.docs.oficina.works")!) |
| + let tito = DocsOficinaSession.accountID(identity: "id-paul", team: "t2") |
| + let paul = DocsOficinaSession.accountID(identity: "id-paul", team: "t1") |
| + let id = windows.reserve(account: tito, document: "d", title: "Plan", client: client) |
| + windows.activeAccount = paul |
| + windows.settingsIdentity = "id-paul" |
| + #expect(windows.canSignOut(paul), "the home team's own windows are none") |
| + #expect(windows.hasOpenDocuments(identity: "id-paul"), "but another team of the identity has one") |
| + #expect(!windows.hasOpenDocuments(identity: "id-till")) |
| + #expect(await windows.leaveBlock() == .openDocuments) |
| + windows.setOpen(id, false) |
| + #expect(!windows.hasOpenDocuments(identity: "id-paul")) |
| + // A server account: its own windows only. |
| + windows.settingsIdentity = nil |
| + let server = UUID().uuidString |
| + windows.activeAccount = server |
| + _ = windows.reserve(account: server, document: "e", title: "Notes", client: client) |
| + #expect(await windows.leaveBlock() == .openDocuments) |
| +} |
| +#endif |