Sheets native: Oficina ID sign-in, straight in with one identity
The Sheets Mac and iPhone apps adopt the shared Oficina ID kit (rastrillo native 1e36aac), as Docs did in slice A, with Paul's 2026-11-19 ruling: one Oficina ID on the device signs straight in with no screen. Welcome, passkey or email code, team; "Other ways to sign in…" keeps the server sign-in, and a server-account route suspends straight in. Account menu: Teams, Use another Oficina ID (confirmed, refused with an open document), Other ways, Sign out. Sessions re-mint after 24 h or on 401/303, and on the pinned "Sign in first." 403 (contract test on the server). Oficina ID entitlements on Mac Sparkle, Mac App Store and iOS; the Developer ID profile named in mac-updates.json; --oficina-id-launch-check. Signed-in launch tests host the real window with a saved identity (they fail on a body that mutates observed state, the Docs 0.1.7/0.1.8 hang). Reviewed by Claude Fable (ded0f68 APPROVE AFTER FIXES; 0555c0f APPROVE). Hub CI passed at 0555c0f. Not released.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
34 files changed,
+1,408
−48
internal/sheets/native_contract_test.go+85 −0native/README.md+31 −3native/apple/Package.resolved+1 −1native/apple/Package.swift+2 −2native/apple/Sources/SheetsApp/SheetsAccountWindow.swift+204 −26native/apple/Sources/SheetsApp/SheetsApp.swift+16 −2native/apple/Sources/SheetsApp/SheetsWindowCommands.swift+7 −2native/apple/Sources/SheetsApp/SheetsWindows.swift+9 −3native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/zh-Hans.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/SheetsAccountActions.swift+4 −0native/apple/Sources/SheetsKit/SheetsOficinaID.swift+338 −0native/apple/Sources/SheetsKit/SheetsOficinaViews.swift+127 −0native/apple/Sources/SheetsKit/SheetsWorkspace.swift+22 −5native/apple/Tests/SheetsKitTests/OficinaIDAdoptionTests.swift+293 −0native/apple/Tests/SheetsWindowTests/SignedInLaunchTests.swift+135 −0native/apple/Tests/SheetsWindowTests/WindowRoutingTests.swift+13 −0native/ios/SheetsPhone.entitlements+23 −0native/ios/project.yml+5 −1native/mac-updates.json+3 −1native/macos/AppStore.entitlements+17 −0native/macos/DeveloperID.entitlements+23 −0native/macos/SheetsMacStore.xcodeproj/project.pbxproj+1 −1native/macos/project.yml+1 −1
CI passed — run details
CI log
amadan: .amadan/timeout: this job's budget is 15m0s (this runner allows up to 30m0s) === vet === CGO_ENABLED=0 go vet ./... CGO_ENABLED=0 go vet -tags browser ./internal/sheets/ === fmt === === build === CGO_ENABLED=0 go build ./... === migrations === go tool rastrillo migration check rastrillo migration check: models and migrations agree === go-test === CGO_ENABLED=0 go test -count=1 ./... ? amadan.net/oficina/sheets/cmd/sheets [no test files] ? amadan.net/oficina/sheets/cmd/sheets-contract [no test files] ok amadan.net/oficina/sheets/internal/guardstest 0.163s ok amadan.net/oficina/sheets/internal/sheets 14.960s ok amadan.net/oficina/sheets/internal/sheets/calc 0.011s ok amadan.net/oficina/sheets/internal/sheets/format 0.003s ? amadan.net/oficina/sheets/internal/sheets/keymailtest [no test files] ok amadan.net/oficina/sheets/internal/sheets/live 0.053s ok amadan.net/oficina/sheets/internal/sheets/seal 0.003s ok amadan.net/oficina/sheets/internal/sheets/sealtest 0.003s ok amadan.net/oficina/sheets/internal/sheets/store 6.149s ok amadan.net/oficina/sheets/internal/sheets/teamstate 0.116s ok amadan.net/oficina/sheets/internal/sheets/xlsx 4.636s ? amadan.net/oficina/sheets/tools/gencorpus [no test files] === race === go test -race -count=1 ./internal/sheets/store/... ./internal/sheets/live/... ok amadan.net/oficina/sheets/internal/sheets/store 71.594s ok amadan.net/oficina/sheets/internal/sheets/live 1.066s
diff --git a/internal/sheets/native_contract_test.go b/internal/sheets/native_contract_test.go| new file mode 100644 |
| index 0000000..fb51583 |
| --- /dev/null |
| +++ b/internal/sheets/native_contract_test.go |
| @@ -0,0 +1,85 @@ |
| +package sheets |
| + |
| +import ( |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| +) |
| + |
| +// A native contract, not copy: the native app's Oficina ID transport |
| +// (native/apple/Sources/SheetsKit/SheetsOficinaID.swift, |
| +// SheetsOficinaTransport.signInFirst) reads a 403 whose body is exactly |
| +// "Sign in first.\n" as an ended session and re-mints it. Every session |
| +// guard that refuses a non-GET request with it must keep these bytes; a |
| +// copy edit here strands a native window whose first request is a write. |
| +const nativeSignInFirst = "Sign in first.\n" |
| + |
| +func assertSignInFirst(t *testing.T, where string, rec *httptest.ResponseRecorder) { |
| + t.Helper() |
| + if rec.Code != http.StatusForbidden || rec.Body.String() != nativeSignInFirst { |
| + t.Fatalf("%s = %d %q, want 403 %q (the native transport's re-mint signal)", where, rec.Code, rec.Body.String(), nativeSignInFirst) |
| + } |
| +} |
| + |
| +// nativeWrite is the native app's POST: JSON wanted, from the app's origin, |
| +// with one session cookie. |
| +func nativeWrite(app *App, cookie *http.Cookie) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest("POST", testOrigin+"/sheets", strings.NewReader(url.Values{"title": {"x"}}.Encode())) |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.Header.Set("Accept", "application/json") |
| + r.Header.Set("Origin", testOrigin) |
| + r.AddCookie(cookie) |
| + rec := httptest.NewRecorder() |
| + app.Router().ServeHTTP(rec, r) |
| + return rec |
| +} |
| + |
| +func TestNativeContractHomeRequireSaysSignInFirst(t *testing.T) { |
| + f := newHomeFixture(t) |
| + f.local(t, signedInAddress) |
| + f.link(t, "pr_linked") |
| + _, answer := f.nativeExchange(t, "pr_linked", nil) |
| + f.age(t, answer, connect.NativeLifetime+time.Hour) |
| + assertSignInFirst(t, "homeRequire, expired native session", nativeWrite(f.app, &http.Cookie{Name: answer.Name, Value: answer.Value})) |
| +} |
| + |
| +func TestNativeContractTeamRequireSaysSignInFirst(t *testing.T) { |
| + f := newTeamFixture(t) |
| + b := teamSubject('b') |
| + f.dir.Set(b, "member") |
| + _, answer := f.nativeExchange(t, b, map[string]string{"choice": "new"}) |
| + f.age(t, answer, connect.NativeLifetime+time.Hour) |
| + assertSignInFirst(t, "teamRequire, expired native session", nativeWrite(f.app, &http.Cookie{Name: answer.Name, Value: answer.Value})) |
| +} |
| + |
| +func TestNativeContractRejectDisabledHomeSaysSignInFirst(t *testing.T) { |
| + app, _ := appWithOrigin(t, testOrigin) |
| + d, err := app.db.DB() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s, err := sessions.New(sessions.Config{DB: d, Origin: testOrigin, SigninPath: "/signin"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + token, err := s.Mint(sessions.Session{Subject: "pr_native", Method: connect.NativeMethod, AuthTime: time.Now()}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + assertSignInFirst(t, "rejectDisabledHome, native session with Home off", nativeWrite(app, &http.Cookie{Name: s.CookieName(), Value: token})) |
| +} |
| + |
| +func TestNativeContractForbiddenSaysSignInFirst(t *testing.T) { |
| + app, _ := appWithOrigin(t, testOrigin) |
| + r := httptest.NewRequest("POST", testOrigin+"/sheets", nil) |
| + r.Header.Set("Accept", "application/json") |
| + rec := httptest.NewRecorder() |
| + app.forbidden(rec, r) |
| + assertSignInFirst(t, "a.forbidden, non-HTML", rec) |
| +} |
diff --git a/native/README.md b/native/README.md| index 632b2fb..f7308fe 100644 |
| --- a/native/README.md |
| +++ b/native/README.md |
| @@ -19,14 +19,42 @@ Simulator and device builds use separate DerivedData directories. |
| project once before starting parallel builds. |
| The shared native transport and Mac packaging tools are pinned to revision |
| -`c989034602fd540531e845b0934864575be11b3e` of |
| -`https://amadan.net/rastrillo/native`, on its main branch (the merge of |
| -`native/oficina-id-slice-a`, which carries `PlainAppNameCommands`). The pin is written in |
| +`1e36aac95ed252848722926efc8ba8f9dc803216` of |
| +`https://amadan.net/rastrillo/native`, on its main branch (the merge of `native/oficina-id-straight-in`: Oficina ID |
| +straight in, Paul's ruling of 2026-11-19). The pin is written in |
| `apple/Package.swift`, `apple/Package.resolved`, `macos/project.yml`, |
| `macos/SheetsMacStore.xcodeproj/project.pbxproj`, `ios/project.yml` and here. |
| Both SwiftPM and Xcode resolve that revision; no sibling development checkout |
| is required. |
| +Sign-in is Oficina ID first (Home `docs/superpowers/specs/2026-11-14-oficina-id-native.md`, |
| +slice A, with Paul's straight-in ruling of 2026-11-19), through rastrillo/native's |
| +`RastrilloApple/OficinaID` kit: one Oficina ID on the device opens its team with no |
| +screen; several ask which; "Use another Oficina ID" is in the account menu. "Other ways |
| +to sign in…" keeps the server address and browser approval for self-hosted servers and |
| +local accounts; someone already signed in that way keeps those accounts, and nothing goes |
| +straight in while that is the route. The server half is `POST /native/oficina-id` |
| +(`internal/sheets/home_routes.go`). |
| + |
| +The kit needs these grants on every build: `macos/DeveloperID.entitlements` (Sparkle, |
| +named by `mac-updates.json`), `macos/AppStore.entitlements`, and `ios/SheetsPhone.entitlements`. |
| +Each has `keychain-access-groups` = `9U4A84C4WK.works.oficina.sheets` **first**, then |
| +`9U4A84C4WK.works.oficina.id`, the App Group (`9U4A84C4WK.works.oficina` on Mac, |
| +`group.works.oficina` on iOS) and `webcredentials:id.oficina.works`. A Developer ID build |
| +claiming them without its embedded profile is killed at launch; `mac-updates.json` names |
| +the profile by local path (never committed). A signed build, then the launch gate (spec |
| +§13), which must pass on the final notarised artifact before any Sparkle publish: |
| + |
| +```sh |
| +native/scripts/build-mac.sh --updates-config mac-updates.json \ |
| + --sign-identity 'Developer ID Application: Team Tito Limited (9U4A84C4WK)' |
| +"native/build/Oficina Sheets.app/Contents/MacOS/SheetsMac" --oficina-id-launch-check |
| +``` |
| + |
| +An ad hoc or simulator build drops the grants; Oficina ID then cannot read the keychain. |
| +`SignedInLaunchTests` hosts the home window with an Oficina ID already saved and checks it |
| +settles (Docs 0.1.7/0.1.8 hung at launch only for people signed in). |
| + |
| The Sparkle build updates quietly, as Calls does: `"install": "automatic"` in |
| `mac-updates.json` writes Sparkle's automatic check, download and install keys |
| (no first-launch question), and `NativeUpdater(policy: .quiet)` keeps scheduled |
diff --git a/native/apple/Package.resolved b/native/apple/Package.resolved| index 4eb3438..8a76148 100644 |
| --- a/native/apple/Package.resolved |
| +++ b/native/apple/Package.resolved |
| @@ -6,7 +6,7 @@ |
| "kind" : "remoteSourceControl", |
| "location" : "https://amadan.net/rastrillo/native", |
| "state" : { |
| - "revision" : "c989034602fd540531e845b0934864575be11b3e" |
| + "revision" : "1e36aac95ed252848722926efc8ba8f9dc803216" |
| } |
| }, |
| { |
diff --git a/native/apple/Package.swift b/native/apple/Package.swift| index 8d91a7e..f44b568 100644 |
| --- a/native/apple/Package.swift |
| +++ b/native/apple/Package.swift |
| @@ -3,7 +3,7 @@ import PackageDescription |
| import Foundation |
| let sharedNative: Package.Dependency = ProcessInfo.processInfo.environment["OFICINA_NATIVE_PACKAGE_PATH"].map { .package(name: "native", path: $0) } |
| - ?? .package(url: "https://amadan.net/rastrillo/native", revision: "c989034602fd540531e845b0934864575be11b3e") |
| + ?? .package(url: "https://amadan.net/rastrillo/native", revision: "1e36aac95ed252848722926efc8ba8f9dc803216") |
| let package = Package(name: "SheetsNative", defaultLocalization: "en", platforms: [.macOS(.v26), .iOS(.v26)], |
| products: [.library(name:"SheetsKit",targets:["SheetsKit"]), .executable(name:"SheetsMac",targets:["SheetsMac"]), .executable(name:"SheetsReview",targets:["SheetsReview"])], |
| @@ -12,4 +12,4 @@ let package = Package(name: "SheetsNative", defaultLocalization: "en", platforms |
| .executableTarget(name:"SheetsMac",dependencies:[.product(name: "RastrilloMacUpdates", package: "native", condition: .when(platforms: [.macOS])), "SheetsKit",.product(name:"RastrilloApple",package:"native")],path:"Sources/SheetsApp"), |
| .executableTarget(name:"SheetsReview",dependencies:["SheetsKit",.product(name:"RastrilloApple",package:"native")]), |
| .testTarget(name:"SheetsKitTests",dependencies:["SheetsKit",.product(name:"RastrilloTestSupport",package:"native")]), |
| - .testTarget(name:"SheetsWindowTests",dependencies:["SheetsMac",.product(name:"RastrilloApple",package:"native")])]) |
| + .testTarget(name:"SheetsWindowTests",dependencies:["SheetsMac",.product(name:"RastrilloApple",package:"native"),.product(name:"RastrilloTestSupport",package:"native")])]) |
diff --git a/native/apple/Sources/SheetsApp/SheetsAccountWindow.swift b/native/apple/Sources/SheetsApp/SheetsAccountWindow.swift| index c6edd46..cc3f17b 100644 |
| --- a/native/apple/Sources/SheetsApp/SheetsAccountWindow.swift |
| +++ b/native/apple/Sources/SheetsApp/SheetsAccountWindow.swift |
| @@ -4,49 +4,227 @@ 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 (Home spec 2026-11-14-oficina-id-native, slice |
| +/// A, and Paul's straight-in ruling of 2026-11-19): with one Oficina ID on the |
| +/// device Sheets opens its team with no screen at all; otherwise the kit's |
| +/// onboarding until its model is signed in, 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 |
| +/// (`SheetsSignInRoute`), and nothing goes straight in while they do. |
| +/// |
| +/// The body only reads: every change (start, route, suspension) happens in |
| +/// `.task` or `.onChange`, never while building a view (docs 84d1008). |
| struct SheetsAccountWindow: View { |
| + @ObservedObject private var oficina: SheetsOficinaSession |
| + @ObservedObject private var model: OficinaIDModel |
| @StateObject private var connection = NativeConnection(defaultServer: "https://sheets.oficina.works") |
| + @AppStorage(SheetsSignInRoute.key) private var storedRoute = "" |
| + @State private var pickingTeam = false |
| + @Environment(\.scenePhase) private var scenePhase |
| #if os(macOS) |
| @Bindable var windows: SheetsWindows |
| @Environment(\.openWindow) private var openWindow |
| #endif |
| + |
| + #if os(macOS) |
| + init(oficina: SheetsOficinaSession, windows: SheetsWindows) { |
| + _oficina = ObservedObject(wrappedValue: oficina); _model = ObservedObject(wrappedValue: oficina.model); _windows = Bindable(windows) |
| + } |
| + #else |
| + init(oficina: SheetsOficinaSession) { |
| + _oficina = ObservedObject(wrappedValue: oficina); _model = ObservedObject(wrappedValue: oficina.model) |
| + } |
| + #endif |
| + |
| + private var route: SheetsSignInRoute { |
| + SheetsSignInRoute.resolve(stored: storedRoute, hasServerAccounts: !connection.accounts.isEmpty) |
| + } |
| + |
| var body: some View { |
| Group { |
| - if let client = connection.client { |
| - #if os(macOS) |
| - if let account = connection.activeAccountID { |
| - SheetsWorkspace(client: client, accounts: connection.showAccounts, signOut: { |
| - guard connection.activeAccountID == account, windows.canSignOut(account) else { return } |
| - windows.entries.removeAll { $0.account == account } |
| - connection.signOut() |
| - }, 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) |
| + switch route { |
| + case .oficinaID: |
| + if let state = oficina.mounted { |
| + oficinaWorkspace(state) |
| + .safeAreaInset(edge: .top, spacing: 0) { oficinaBanner } |
| + .oficinaReplaceConfirmation(model) |
| + } else { |
| + OficinaOnboardingView(model: model, otherWays: { storedRoute = SheetsSignInRoute.server.rawValue }) |
| + } |
| + case .server: |
| + if let client = connection.client { serverWorkspace(client) } |
| + else { |
| + SheetsOtherWaysView(connection: connection) { storedRoute = SheetsSignInRoute.oficinaID.rawValue } |
| } |
| - #else |
| - SheetsWorkspace(client: client, accounts: connection.showAccounts, signOut: connection.signOut) |
| - .id(connection.activeAccountID) |
| - #endif |
| - } else { |
| - NativeAccountsView("Sheets", systemImage: "tablecells", connection: connection) |
| } |
| - }.onOpenURL(perform: connection.handleOpenURL) |
| + } |
| + .onOpenURL(perform: connection.handleOpenURL) |
| + .task { await oficina.start(serverRoute: route == .server) } |
| + // A sign-in made here chooses Oficina ID for good (Appendix C); a launch |
| + // going straight in leaves the route someone chose alone. |
| + .onChange(of: oficina.signIns) { _, _ in storedRoute = SheetsSignInRoute.oficinaID.rawValue } |
| + // Straight in is suspended exactly while the app's own sign-in is the |
| + // route, however the route changes: chosen, or flipped by the last |
| + // server account signing out (rule 0). |
| + .onChange(of: route) { _, value in Task { await oficina.routeChanged(to: value) } } |
| + // "Use another" re-checks the document guard when it asks, as signing |
| + // out does, and is never left asking over an outage. |
| + .onChange(of: model.confirmingReplace) { _, confirming in |
| + guard confirming else { return } |
| + let signedIn: Bool |
| + if case .signedIn = model.step { signedIn = true } else { signedIn = false } |
| + if oficina.mounted != nil, !signedIn || openDocuments(of: model.identity?.id ?? "") { model.cancelReplace() } |
| + } |
| + .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 && currentAccount == nil { windows.accountsRequested = false } |
| } |
| - .focusedSceneValue(\.sheetsWindowAccount, connection.activeAccountID) |
| - .onChange(of: connection.activeAccountID, initial: true) { _, value in windows.activeAccount = value } |
| + .focusedSceneValue(\.sheetsWindowAccount, currentAccount) |
| + // An identity gone (signed out here or elsewhere, or replaced by "Use |
| + // another") takes its recents with it: their transports answer nothing. |
| + .onChange(of: model.identity?.id) { old, new in |
| + guard let old, old != new else { return } |
| + windows.entries.removeAll { SheetsOficinaSession.account($0.account, belongsTo: old) && !$0.isOpen } |
| + } |
| + .onChange(of: currentAccount, initial: true) { _, value in windows.activeAccount = value } |
| #endif |
| .tint(.green) |
| #if os(macOS) |
| .frame(minWidth: 760, minHeight: 600) |
| #endif |
| } |
| + |
| + private var currentAccount: String? { |
| + switch route { |
| + case .oficinaID: return oficina.mounted.map(SheetsOficinaSession.accountID) |
| + case .server: return connection.activeAccountID |
| + } |
| + } |
| + |
| + // MARK: Oficina ID |
| + |
| + @ViewBuilder private func oficinaWorkspace(_ state: OficinaSignedIn) -> some View { |
| + let account = SheetsOficinaSession.accountID(state) |
| + let client = oficina.transport(for: account, origin: state.origin) |
| + let canLeave = !openDocuments(of: state.identity.id) |
| + #if os(macOS) |
| + SheetsWorkspace(client: client, accounts: { pickingTeam = true }, signOut: { signOutOficinaID(state) }, |
| + canSignOut: canLeave, createRequested: $windows.createRequested, accountsRequested: $windows.accountsRequested, |
| + 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) |
| + }, useAnother: canUseAnother ? { useAnother(state) } : nil, accountsLabel: sheetsMacString("Teams"), |
| + signOutLabel: OficinaIDText.text("signOut", state.identity.label)) |
| + .id(account) |
| + .safeAreaInset(edge: .bottom, spacing: 0) { passkeyNudge } |
| + .sheet(isPresented: $pickingTeam) { teamPicker(state, canLeave: canLeave) } |
| + #else |
| + SheetsWorkspace(client: client, accounts: { pickingTeam = true }, signOut: { signOutOficinaID(state) }, |
| + useAnother: canUseAnother ? { useAnother(state) } : nil, accountsLabel: sheetsMacString("Teams"), |
| + signOutLabel: OficinaIDText.text("signOut", state.identity.label)) |
| + .id(account) |
| + .safeAreaInset(edge: .bottom, spacing: 0) { passkeyNudge } |
| + .sheet(isPresented: $pickingTeam) { teamPicker(state, canLeave: canLeave) } |
| + #endif |
| + } |
| + |
| + @ViewBuilder private var passkeyNudge: some View { |
| + if model.offerPasskey { OficinaPasskeyNudge(model: model).padding(12) } |
| + } |
| + |
| + /// Over the mounted workspace: Oficina ID can't mint this team a new |
| + /// session right now (§11), so the open team stays, with Try again. A |
| + /// switch to another team that fails the same way unmounts this one and |
| + /// shows the kit's "Can't reach Oficina ID" (Try again, Other ways), as |
| + /// Docs does. |
| + @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("sheets.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, canLeave: Bool) -> some View { |
| + SheetsTeamPicker(model: model, current: state, canLeave: canLeave, refresh: { await oficina.pickerOpened() }, |
| + otherWays: { |
| + model.suspendStraightIn() |
| + storedRoute = SheetsSignInRoute.server.rawValue |
| + }, useAnother: { useAnother(state) }, signOut: { signOutOficinaID(state) }, done: { pickingTeam = false }) |
| + } |
| + |
| + /// 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 |
| + } |
| + |
| + /// "Use another Oficina ID" is offered only while signed in: over an |
| + /// outage there is no dialog to ask with. |
| + private var canUseAnother: Bool { |
| + if case .signedIn = model.step { return true } |
| + return false |
| + } |
| + |
| + /// "Use another Oficina ID" from the account menu: slice A replaces the |
| + /// identity, so the kit asks first (`oficinaReplaceConfirmation` above), |
| + /// and the same guard as signing out applies. |
| + private func useAnother(_ state: OficinaSignedIn) { |
| + oficina.useAnother(identity: state.identity.id, canLeave: !openDocuments(of: state.identity.id)) |
| + } |
| + |
| + /// "Sign out of <label>": every team of the identity, on every Oficina app |
| + /// on this device (spec §10), refused while one of its document windows |
| + /// is open (the menu disables it then too). |
| + private func signOutOficinaID(_ state: OficinaSignedIn) { |
| + let identity = state.identity.id |
| + guard oficina.signOut(identity: identity, canLeave: !openDocuments(of: identity)) else { return } |
| + #if os(macOS) |
| + windows.entries.removeAll { SheetsOficinaSession.account($0.account, belongsTo: identity) } |
| + #endif |
| + } |
| + |
| + // MARK: Other ways (server address) |
| + |
| + @ViewBuilder private func serverWorkspace(_ client: NativeHTTP) -> some View { |
| + #if os(macOS) |
| + if let account = connection.activeAccountID { |
| + SheetsWorkspace(client: client, accounts: connection.showAccounts, signOut: { |
| + guard connection.activeAccountID == account, windows.canSignOut(account) else { return } |
| + windows.entries.removeAll { $0.account == account } |
| + connection.signOut() |
| + }, 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 |
| + SheetsWorkspace(client: client, accounts: connection.showAccounts, signOut: connection.signOut) |
| + .id(connection.activeAccountID) |
| + #endif |
| + } |
| } |
diff --git a/native/apple/Sources/SheetsApp/SheetsApp.swift b/native/apple/Sources/SheetsApp/SheetsApp.swift| index 2c7420a..5b61e11 100644 |
| --- a/native/apple/Sources/SheetsApp/SheetsApp.swift |
| +++ b/native/apple/Sources/SheetsApp/SheetsApp.swift |
| @@ -16,10 +16,24 @@ import SwiftUI |
| @State private var windows = SheetsWindows() |
| @NSApplicationDelegateAdaptor(SheetsApplicationDelegate.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 = SheetsOficinaSession.live() |
| + init() { |
| + #if os(macOS) |
| + // The launch gate (spec §13): run the signed executable with this |
| + // argument before any Sparkle publish. |
| + if CommandLine.arguments.contains(SheetsOficinaLaunchCheck.argument) { |
| + let result = SheetsOficinaLaunchCheck.run() |
| + result.lines.forEach { print($0) } |
| + exit(result.passed ? 0 : 1) |
| + } |
| + #endif |
| + } |
| var body: some Scene { |
| #if os(macOS) |
| Window(sheetsMacString("Home"), id: "home") { |
| - SheetsAccountWindow(windows: windows) |
| + SheetsAccountWindow(oficina: oficina, windows: windows) |
| #if canImport(RastrilloMacUpdates) |
| // The quiet updater's one line, only while an update is pending: where |
| // an update that needs the person (automatic downloads off) shows up. |
| @@ -50,7 +64,7 @@ import SwiftUI |
| .defaultSize(width: 1120, height: 820) |
| .restorationBehavior(.disabled) |
| #else |
| - WindowGroup { SheetsAccountWindow() } |
| + WindowGroup { SheetsAccountWindow(oficina: oficina) } |
| #endif |
| } |
| } |
diff --git a/native/apple/Sources/SheetsApp/SheetsWindowCommands.swift b/native/apple/Sources/SheetsApp/SheetsWindowCommands.swift| index 28f2105..89988cd 100644 |
| --- a/native/apple/Sources/SheetsApp/SheetsWindowCommands.swift |
| +++ b/native/apple/Sources/SheetsApp/SheetsWindowCommands.swift |
| @@ -1,4 +1,5 @@ |
| #if os(macOS) |
| +import RastrilloApple |
| import SwiftUI |
| import SheetsKit |
| @@ -9,11 +10,15 @@ struct SheetsWindowCommands: Commands { |
| @Environment(\.openWindow) private var openWindow |
| var body: some Commands { |
| CommandGroup(after: .appSettings) { |
| - Button(sheetsMacString("Accounts")) { |
| + Button(accountActions?.accountsLabel ?? sheetsMacString("Accounts")) { |
| if let action = accountActions?.accounts { action() } |
| else { windows.accountsRequested = true; openWindow(id: "home") } |
| }.disabled(accountActions?.canManage == false) |
| - Button(sheetsMacString("Sign out")) { accountActions?.signOut() } |
| + if let useAnother = accountActions?.useAnother { |
| + Button(OficinaIDText.text("continue.another")) { useAnother() } |
| + .disabled(accountActions?.canSignOut != true) |
| + } |
| + Button(accountActions?.signOutLabel ?? sheetsMacString("Sign out")) { accountActions?.signOut() } |
| .disabled(accountActions?.canSignOut != true) |
| Divider() |
| } |
diff --git a/native/apple/Sources/SheetsApp/SheetsWindows.swift b/native/apple/Sources/SheetsApp/SheetsWindows.swift| index 90a953d..1c64826 100644 |
| --- a/native/apple/Sources/SheetsApp/SheetsWindows.swift |
| +++ b/native/apple/Sources/SheetsApp/SheetsWindows.swift |
| @@ -2,6 +2,7 @@ |
| import Foundation |
| import Observation |
| import RastrilloApple |
| +import SheetsKit |
| import SwiftUI |
| /// Scene values are opaque IDs, never credentials. Reserve before opening a scene. |
| @@ -10,7 +11,7 @@ import SwiftUI |
| let id: UUID |
| let account: String |
| let document: UInt64 |
| - let client: NativeHTTP |
| + let client: any NativeTransport |
| var title: String |
| var isOpen = false |
| } |
| @@ -18,7 +19,7 @@ import SwiftUI |
| var activeAccount: String? |
| var createRequested = false |
| var accountsRequested = false |
| - func reserve(account: String, document: UInt64, title: String, client: NativeHTTP) -> UUID { |
| + func reserve(account: String, document: UInt64, title: String, client: any NativeTransport) -> UUID { |
| if let index = entries.firstIndex(where: { $0.account == account && $0.client.origin == client.origin && $0.document == document }) { |
| var entry = entries.remove(at: index) |
| entry.title = title |
| @@ -30,7 +31,7 @@ import SwiftUI |
| entries.insert(entry, at: 0) |
| return entry.id |
| } |
| - func updateRecents(_ documents: [(UInt64, String)], account: String, client: NativeHTTP) { |
| + func updateRecents(_ documents: [(UInt64, String)], account: String, client: any NativeTransport) { |
| for (document, title) in documents { |
| if let index = entries.firstIndex(where: { $0.account == account && $0.client.origin == client.origin && $0.document == document }) { |
| entries[index].title = title |
| @@ -43,6 +44,11 @@ import SwiftUI |
| if let index = entries.firstIndex(where: { $0.id == id }) { entries[index].isOpen = value } |
| } |
| 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. |
| + func hasOpenDocuments(identity: String) -> Bool { |
| + entries.contains { $0.isOpen && SheetsOficinaSession.account($0.account, belongsTo: identity) } |
| + } |
| } |
| extension FocusedValues { @Entry var sheetsWindowAccount: String? } |
| #endif |
diff --git a/native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings| index de44d60..58fee11 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings |
| @@ -70,3 +70,7 @@ |
| "Search spreadsheets" = "البحث في جداول البيانات"; |
| "The server did not confirm the resize." = "لم يؤكد الخادم تغيير الحجم."; |
| +/* Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A): the team picker and the way back from "Other ways to sign in…". */ |
| +"Teams" = "الفرق"; |
| +"Done" = "تم"; |
| +"Sign in with Oficina ID" = "تسجيل الدخول باستخدام Oficina ID"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings| index 2184398..ca17400 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings |
| @@ -70,3 +70,7 @@ |
| "Search spreadsheets" = "স্প্রেডশিট খুঁজুন"; |
| "The server did not confirm the resize." = "সার্ভার আকার পরিবর্তন নিশ্চিত করেনি।"; |
| +/* Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A): the team picker and the way back from "Other ways to sign in…". */ |
| +"Teams" = "টিম"; |
| +"Done" = "সম্পন্ন"; |
| +"Sign in with Oficina ID" = "Oficina ID দিয়ে সাইন ইন করুন"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings| index 0d9f837..d59b41c 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings |
| @@ -71,3 +71,7 @@ |
| "The server did not confirm the resize." = "The server did not confirm the resize."; |
| "You’re offline. Waiting for a connection." = "You’re offline. Waiting for a connection."; |
| +/* Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A): the team picker and the way back from "Other ways to sign in…". */ |
| +"Teams" = "Teams"; |
| +"Done" = "Done"; |
| +"Sign in with Oficina ID" = "Sign in with Oficina ID"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings| index 58a89e9..2e6bfe4 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings |
| @@ -70,3 +70,7 @@ |
| "Search spreadsheets" = "Buscar hojas de cálculo"; |
| "The server did not confirm the resize." = "El servidor no confirmó el cambio de tamaño."; |
| +/* Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A): the team picker and the way back from "Other ways to sign in…". */ |
| +"Teams" = "Equipos"; |
| +"Done" = "Listo"; |
| +"Sign in with Oficina ID" = "Iniciar sesión con Oficina ID"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings| index 81724d5..fe98308 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings |
| @@ -70,3 +70,7 @@ |
| "Search spreadsheets" = "Cuardaigh scarbhileoga"; |
| "The server did not confirm the resize." = "Níor dheimhnigh an freastalaí an t-athrú méide."; |
| +/* Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A): the team picker and the way back from "Other ways to sign in…". */ |
| +"Teams" = "Foirne"; |
| +"Done" = "Déanta"; |
| +"Sign in with Oficina ID" = "Sínigh isteach le Oficina ID"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings| index f80cc0c..515afae 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings |
| @@ -70,3 +70,7 @@ |
| "Search spreadsheets" = "स्प्रेडशीट खोजें"; |
| "The server did not confirm the resize." = "सर्वर ने आकार बदलने की पुष्टि नहीं की।"; |
| +/* Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A): the team picker and the way back from "Other ways to sign in…". */ |
| +"Teams" = "टीमें"; |
| +"Done" = "हो गया"; |
| +"Sign in with Oficina ID" = "Oficina ID से साइन इन करें"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings| index 4f9e3da..b4493eb 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings |
| @@ -70,3 +70,7 @@ |
| "Search spreadsheets" = "スプレッドシートを検索"; |
| "The server did not confirm the resize." = "サーバーがサイズ変更を確認しませんでした。"; |
| +/* Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A): the team picker and the way back from "Other ways to sign in…". */ |
| +"Teams" = "チーム"; |
| +"Done" = "完了"; |
| +"Sign in with Oficina ID" = "Oficina ID でサインイン"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings| index e78f641..6faffe4 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings |
| @@ -70,3 +70,7 @@ |
| "Search spreadsheets" = "Pesquisar planilhas"; |
| "The server did not confirm the resize." = "O servidor não confirmou o redimensionamento."; |
| +/* Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A): the team picker and the way back from "Other ways to sign in…". */ |
| +"Teams" = "Equipas"; |
| +"Done" = "Concluído"; |
| +"Sign in with Oficina ID" = "Iniciar sessão com o Oficina ID"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings| index f2dffdc..a32025d 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings |
| @@ -70,3 +70,7 @@ |
| "Search spreadsheets" = "Поиск таблиц"; |
| "The server did not confirm the resize." = "Сервер не подтвердил изменение размера."; |
| +/* Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A): the team picker and the way back from "Other ways to sign in…". */ |
| +"Teams" = "Команды"; |
| +"Done" = "Готово"; |
| +"Sign in with Oficina ID" = "Войти с Oficina ID"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings| index e4531f4..5dffed0 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings |
| @@ -70,3 +70,7 @@ |
| "Search spreadsheets" = "Tìm bảng tính"; |
| "The server did not confirm the resize." = "Máy chủ chưa xác nhận thay đổi kích thước."; |
| +/* Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A): the team picker and the way back from "Other ways to sign in…". */ |
| +"Teams" = "Nhóm"; |
| +"Done" = "Xong"; |
| +"Sign in with Oficina ID" = "Đăng nhập bằng Oficina ID"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings| index bf496f8..2b63666 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings |
| @@ -70,3 +70,7 @@ |
| "Search spreadsheets" = "搜尋試算表"; |
| "The server did not confirm the resize." = "伺服器未確認大小調整。"; |
| +/* Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A): the team picker and the way back from "Other ways to sign in…". */ |
| +"Teams" = "團隊"; |
| +"Done" = "完成"; |
| +"Sign in with Oficina ID" = "用 Oficina ID 登入"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/zh-Hans.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/zh-Hans.lproj/Mac.strings| index 43eebfb..9d1bd66 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/zh-Hans.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/zh-Hans.lproj/Mac.strings |
| @@ -70,3 +70,7 @@ |
| "Search spreadsheets" = "搜索电子表格"; |
| "The server did not confirm the resize." = "服务器未确认大小调整。"; |
| +/* Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A): the team picker and the way back from "Other ways to sign in…". */ |
| +"Teams" = "团队"; |
| +"Done" = "完成"; |
| +"Sign in with Oficina ID" = "使用 Oficina ID 登录"; |
diff --git a/native/apple/Sources/SheetsKit/SheetsAccountActions.swift b/native/apple/Sources/SheetsKit/SheetsAccountActions.swift| index 4ee6c4b..145e921 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetsAccountActions.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetsAccountActions.swift |
| @@ -5,6 +5,10 @@ public struct SheetsAccountActions { |
| public let signOut: () -> Void |
| public let canManage: Bool |
| public let canSignOut: Bool |
| + /// "Use another Oficina ID", and the menu's words, for an Oficina ID. |
| + public var useAnother: (() -> Void)? = nil |
| + public var accountsLabel: String? = nil |
| + public var signOutLabel: String? = nil |
| } |
| extension FocusedValues { @Entry public var sheetsAccountActions: SheetsAccountActions? } |
| #endif |
diff --git a/native/apple/Sources/SheetsKit/SheetsOficinaID.swift b/native/apple/Sources/SheetsKit/SheetsOficinaID.swift| new file mode 100644 |
| index 0000000..fffa972 |
| --- /dev/null |
| +++ b/native/apple/Sources/SheetsKit/SheetsOficinaID.swift |
| @@ -0,0 +1,338 @@ |
| +import Combine |
| +import Foundation |
| +import RastrilloApple |
| + |
| +/// How Sheets signs in, as the person last chose it. Oficina ID is the |
| +/// primary way (Home 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 SheetsSignInRoute: String, Sendable { |
| + case oficinaID = "oficina-id" |
| + case server |
| + |
| + /// The `UserDefaults` key the choice is kept under. |
| + public static let key = "sheets.signin.route" |
| + |
| + /// The route to show. Nothing chosen yet means Oficina ID, except for |
| + /// someone already signed in the old way: their accounts keep working |
| + /// until an Oficina ID replaces them (spec Appendix C). An Oficina ID |
| + /// sign-in chooses `.oficinaID` for good. On `.server` the app suspends |
| + /// the kit's straight in (spec §9, rule 0). |
| + public static func resolve(stored: String, hasServerAccounts: Bool) -> SheetsSignInRoute { |
| + if let chosen = SheetsSignInRoute(rawValue: stored) { return chosen } |
| + return hasServerAccounts ? .server : .oficinaID |
| + } |
| +} |
| + |
| +/// Sheets' half of Oficina ID: the kit's model, and the team sessions it |
| +/// mints turned into the transport Sheets' 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 open workspace must |
| +/// carry on through that, so its transport reads the latest session for its |
| +/// account on every request. |
| +/// |
| +/// Nothing here is read-then-written from a view's body or init (Docs |
| +/// 0.1.7/0.1.8 hung at launch that way, docs 84d1008): `mounted`, |
| +/// `sessions` and `signIns` change only from the model's step publisher, |
| +/// and `start()` runs from a `.task`. |
| +@MainActor public final class SheetsOficinaSession: ObservableObject { |
| + 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? |
| + private let now: () -> Date |
| + |
| + nonisolated public static let configuration = OficinaIDConfiguration(app: "sheets", appName: "Sheets") |
| + |
| + /// The team the workspace shows: the signed-in team, kept while Oficina |
| + /// ID cannot mint it a new session (spec §11), so a 401 with Home |
| + /// unreachable does not unmount an open sheet. nil once the identity |
| + /// signs out or the model moves on to another team's question. |
| + @Published public private(set) var mounted: OficinaSignedIn? |
| + |
| + /// Sign-ins a person made here (a code, a passkey, a team or identity |
| + /// picked, a retry), as against a launch going straight in. Only these |
| + /// choose the Oficina ID route for good. |
| + @Published public private(set) var signIns = 0 |
| + |
| + /// The App Group holding identity order and last-used team: team-prefixed |
| + /// on the Mac, the registered `group.works.oficina` on iOS. |
| + nonisolated public static var appGroup: String { |
| + #if os(macOS) |
| + "9U4A84C4WK.works.oficina" |
| + #else |
| + "group.works.oficina" |
| + #endif |
| + } |
| + |
| + /// The real wiring: the shared keychain group, Sheets' own, the App |
| + /// Group, Home over HTTPS and the platform's passkey sheet. |
| + public static func live() -> SheetsOficinaSession { |
| + SheetsOficinaSession(model: .live(configuration: configuration, appGroup: appGroup)) |
| + } |
| + |
| + public init(model: OficinaIDModel, now: @escaping () -> Date = Date.init) { |
| + self.model = model |
| + self.now = now |
| + watch = model.$step.sink { [weak self] step in self?.stepChanged(step) } |
| + } |
| + |
| + /// Reads the store once per launch, however many windows ask, then |
| + /// refreshes the team list (spec §9: at launch). `serverRoute` is the app's |
| + /// own sign-in being the route: nothing goes straight in then (rule 0). |
| + public func start(serverRoute: Bool = false) async { |
| + guard !started else { return } |
| + started = true |
| + if serverRoute { model.suspendStraightIn() } |
| + await model.start() |
| + await model.refreshTeams() |
| + } |
| + |
| + /// The route changed, by the person or by itself (the last server account |
| + /// signed out, say): straight in is suspended exactly while the app's |
| + /// own sign-in is the route, and resumes when it stops being (spec §9, |
| + /// rule 0). Without this a route that flips on its own would leave |
| + /// Welcome with straight in still suspended (Fable, sheets ded0f68). |
| + public func routeChanged(to route: SheetsSignInRoute) async { |
| + switch route { |
| + case .server: model.suspendStraightIn() |
| + case .oficinaID: await model.resumeStraightIn() |
| + } |
| + } |
| + |
| + /// "Use another Oficina ID" from the account menu: only while signed in |
| + /// (over an outage there is no dialog to ask with), and only when |
| + /// `canLeave` (no document window of the identity open). Returns whether |
| + /// it asked. |
| + @discardableResult |
| + public func useAnother(identity: String, canLeave: Bool) -> Bool { |
| + guard case .signedIn(let state) = model.step, state.identity.id == identity, canLeave else { return false } |
| + model.useAnother() |
| + return true |
| + } |
| + |
| + /// "Sign out of <label>", refused while a document window of the |
| + /// identity is open. Returns whether it signed out. |
| + @discardableResult |
| + public func signOut(identity: String, canLeave: Bool) -> Bool { |
| + guard model.identity?.id == identity, canLeave else { return false } |
| + model.signOut() |
| + return true |
| + } |
| + |
| + /// The team picker opened: refresh if the list is five minutes old. |
| + public func pickerOpened() async { await model.refreshTeams() } |
| + |
| + /// An instance answered 403: fetch the team list again, at most once a |
| + /// minute (spec §9). |
| + func refused() async { |
| + if let last = lastRefusal, now().timeIntervalSince(last) < 60 { return } |
| + lastRefusal = now() |
| + await model.refreshTeams(maxAge: 0) |
| + } |
| + |
| + /// The account Sheets files an Oficina ID team under (its windows and |
| + /// recents): stable for the life of the identity on this device. |
| + nonisolated public static func accountID(_ state: OficinaSignedIn) -> String { |
| + accountID(identity: state.identity.id, team: state.team.sqid) |
| + } |
| + |
| + nonisolated public static func accountID(identity: String, team: String) -> String { |
| + prefix + component(identity) + "." + component(team) |
| + } |
| + |
| + nonisolated static let prefix = "oficina-id." |
| + |
| + /// Each part is used as it is only when base64url-safe (as Home's |
| + /// identity IDs and sqids are); anything else is encoded behind a "~". |
| + 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. |
| + nonisolated public static func account(_ account: String, belongsTo identity: String) -> Bool { |
| + account.hasPrefix(prefix + component(identity) + ".") |
| + } |
| + |
| + /// The transport for `account`: its latest session on every request; a |
| + /// 401 re-mints silently (spec §7), a 403 refreshes the teams; after |
| + /// sign-out every request fails as `.unauthorized`. |
| + public func transport(for account: String, origin: URL) -> SheetsOficinaTransport { |
| + SheetsOficinaTransport(origin: origin, current: { [weak self] in self?.sessions[account]?.client as (any NativeTransport)? }, |
| + rejected: { [weak self] in Task { @MainActor in await self?.rejected(account) } }, |
| + refused: { [weak self] in Task { @MainActor in await self?.refused() } }) |
| + } |
| + |
| + /// Re-mints a session older than 24 hours; call when a scene comes back. |
| + public func renewIfNeeded() async { |
| + guard !renewing else { return } |
| + renewing = true |
| + defer { renewing = false } |
| + await model.renewIfNeeded() |
| + } |
| + |
| + /// The instance refused the session: only the team in use is re-minted, |
| + /// at most once a minute per account, so a refusing instance cannot set |
| + /// off a loop of assertions. |
| + func rejected(_ account: String) async { |
| + guard case .signedIn(let state) = model.step, 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() |
| + } |
| + |
| + /// 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) |
| + if sessions[account]?.session.value != state.session.value { |
| + sessions[account] = (state.session, state.client()) |
| + } |
| + // The identity's other teams keep theirs (open document windows); |
| + // 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 workspace's transport for an Oficina ID team: the latest session's |
| +/// client on every request, and word back when the instance refuses the |
| +/// session (401, or the 303 to sign-in `NativeClientError` also reads as an |
| +/// ended session) or a request (403). |
| +/// |
| +/// Sheets' session guards answer a non-GET request with an ended or refused |
| +/// session as 403 "Sign in first." (home.go, team_access.go), not 401: read |
| +/// as a refused request, a window open past the session's seven days whose |
| +/// first request is a cell write would never re-mint. That one 403 is an |
| +/// ended session, re-minted and surfaced as the 401 it means. |
| +public struct SheetsOficinaTransport: NativeTransport { |
| + public let origin: URL |
| + let current: @MainActor @Sendable () -> (any NativeTransport)? |
| + let rejected: @Sendable () -> Void |
| + let refused: @Sendable () -> Void |
| + |
| + public init(origin: URL, current: @escaping @MainActor @Sendable () -> (any NativeTransport)?, |
| + rejected: @escaping @Sendable () -> Void, refused: @escaping @Sendable () -> Void) { |
| + self.origin = origin; self.current = current; self.rejected = rejected; self.refused = refused |
| + } |
| + |
| + /// The session guards' refusal, byte for byte (`http.Error` adds the newline). |
| + static let signInFirst = Data("Sign in first.\n".utf8) |
| + |
| + private func client() async throws -> any NativeTransport { |
| + guard let client = await current() else { throw NativeClientError.unauthorized } |
| + return client |
| + } |
| + |
| + public func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| + let reply = try await client().responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes) |
| + if reply.status == 403, reply.data == Self.signInFirst { |
| + rejected() |
| + return NativeResponse(data: reply.data, status: 401, headers: reply.headers) |
| + } |
| + if reply.status == 401 || reply.status == 303 { rejected() } |
| + if reply.status == 403 { refused() } |
| + return reply |
| + } |
| + |
| + public func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| + do { try await client().stream(path, onOpen: onOpen, onLine: onLine) } |
| + catch NativeClientError.unauthorized { rejected(); throw NativeClientError.unauthorized } |
| + } |
| + |
| + public func download(_ path: String, to destination: URL) async throws { |
| + do { try await client().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`. It checks the signed entitlements and |
| +/// reads, never writes, both keychain groups; it prints counts, never an |
| +/// identity or a session, and exits 0 only if all of it works. |
| +public enum SheetsOficinaLaunchCheck { |
| + 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: SheetsOficinaSession.configuration.app) |
| + check("keychain-access-groups") { |
| + let groups = entitlement("keychain-access-groups") |
| + // A query that names no group lands in the first: it must be Sheets' 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)") { |
| + let store = OficinaIDStore(shared: OficinaKeychainStore(accessGroup: OficinaKeychainStore.sharedGroup), |
| + appPrivate: OficinaKeychainStore(accessGroup: own), |
| + group: UserDefaults(suiteName: SheetsOficinaSession.appGroup) ?? .standard) |
| + return "readable, \(try store.identities().count) identities" |
| + + " (\(store.unreadableIdentities().count) only a newer app can read)" |
| + } |
| + check("Sheets' 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 \(SheetsOficinaSession.appGroup)") { |
| + let groups = entitlement("com.apple.security.application-groups") |
| + guard groups.contains(SheetsOficinaSession.appGroup) else { |
| + throw LaunchCheckError("not granted: com.apple.security.application-groups is \(groups)") |
| + } |
| + guard UserDefaults(suiteName: SheetsOficinaSession.appGroup) != nil else { throw LaunchCheckError("no defaults suite") } |
| + return "granted" |
| + } |
| + check("associated domains") { |
| + let domains = entitlement("com.apple.developer.associated-domains") |
| + guard domains.contains("webcredentials:id.oficina.works") else { throw LaunchCheckError("got \(domains)") } |
| + return domains.joined(separator: ", ") |
| + } |
| + return (passed, lines) |
| + } |
| + |
| + /// A string-array entitlement of this process, as signed. |
| + static func entitlement(_ key: String) -> [String] { |
| + guard let task = SecTaskCreateFromSelf(nil) else { return [] } |
| + return SecTaskCopyValueForEntitlement(task, key as CFString, nil) as? [String] ?? [] |
| + } |
| + |
| + struct LaunchCheckError: Error, CustomStringConvertible { |
| + let description: String |
| + init(_ description: String) { self.description = description } |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/SheetsKit/SheetsOficinaViews.swift b/native/apple/Sources/SheetsKit/SheetsOficinaViews.swift| new file mode 100644 |
| index 0000000..656708a |
| --- /dev/null |
| +++ b/native/apple/Sources/SheetsKit/SheetsOficinaViews.swift |
| @@ -0,0 +1,127 @@ |
| +import RastrilloApple |
| +import SwiftUI |
| + |
| +/// Sheets' account menu for an Oficina ID (spec §9): who is signed in, the |
| +/// identity's teams that have Sheets, "Use another Oficina ID" (Paul, |
| +/// 2026-11-19), "Other ways to sign in…" and "Sign out of <label>". The |
| +/// several-identities menu is slice A2. |
| +@MainActor public struct SheetsTeamPicker: View { |
| + @ObservedObject private var model: OficinaIDModel |
| + private let current: OficinaSignedIn |
| + private let canLeave: Bool |
| + private let refresh: @MainActor () async -> Void |
| + private let otherWays: () -> Void |
| + private let useAnother: () -> Void |
| + private let signOut: () -> Void |
| + private let done: () -> Void |
| + |
| + /// `canLeave` is false while leaving would strand something (a document |
| + /// window of this identity open, an edit not yet confirmed): switching |
| + /// team, "Use another" and signing out are disabled then. |
| + public init(model: OficinaIDModel, current: OficinaSignedIn, canLeave: Bool, |
| + refresh: @escaping @MainActor () async -> Void = {}, |
| + otherWays: @escaping () -> Void, useAnother: @escaping () -> Void, |
| + signOut: @escaping () -> Void, done: @escaping () -> Void) { |
| + self.model = model; self.current = current; self.canLeave = canLeave; self.refresh = refresh |
| + self.otherWays = otherWays; self.useAnother = useAnother; self.signOut = signOut; self.done = done |
| + } |
| + |
| + /// The cached teams that have Sheets, the current one always among them. |
| + public static func teams(_ cached: [OficinaTeam]?, current: OficinaTeam) -> [OficinaTeam] { |
| + var teams = (cached ?? []).filter { $0.origin(for: SheetsOficinaSession.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: .sheets) |
| + } header: { Text(verbatim: "Oficina ID") } |
| + Section { |
| + ForEach(teams) { team in |
| + Button { choose(team) } label: { |
| + OficinaTeamRow(team: team).overlay(alignment: .trailing) { |
| + if team.sqid == current.team.sqid { |
| + Image(systemName: "checkmark").font(.headline).foregroundStyle(OficinaPalette.accent(.sheets)) |
| + .padding(.trailing, 14).accessibilityHidden(true) |
| + } |
| + } |
| + } |
| + .buttonStyle(.plain) |
| + .disabled(team.sqid != current.team.sqid && (!canLeave || model.busy)) |
| + .accessibilityAddTraits(team.sqid == current.team.sqid ? .isSelected : []) |
| + .accessibilityIdentifier("sheets.team-\(team.label)") |
| + } |
| + } header: { Text(verbatim: sheetsMacString("Teams")) } footer: { |
| + if let error = model.error { OficinaErrorLine(error) } |
| + } |
| + Section { |
| + Button(OficinaIDText.text("continue.another")) { done(); useAnother() } |
| + .buttonStyle(.borderless) |
| + .disabled(!canLeave) |
| + .accessibilityIdentifier("sheets.oficinaid.useAnother") |
| + Button(OficinaIDText.text("otherWays")) { done(); otherWays() } |
| + .buttonStyle(.borderless) |
| + .accessibilityIdentifier("sheets.otherWays") |
| + Button(role: .destructive) { done(); signOut() } label: { |
| + Text(verbatim: OficinaIDText.text("signOut", current.identity.label)) |
| + } |
| + .buttonStyle(.borderless) |
| + // Its own colour would hide that it is disabled. |
| + .foregroundStyle(canLeave ? OficinaPalette.negative : OficinaPalette.textMuted) |
| + .disabled(!canLeave) |
| + .accessibilityIdentifier("sheets.oficinaid.signOut") |
| + } |
| + } |
| + .navigationTitle(Text(verbatim: sheetsMacString("Teams"))) |
| + .task { await refresh() } |
| + #if os(iOS) |
| + .navigationBarTitleDisplayMode(.inline) |
| + #endif |
| + .toolbar { |
| + ToolbarItem(placement: .confirmationAction) { |
| + Button { done() } label: { Text(verbatim: sheetsMacString("Done")) } |
| + } |
| + } |
| + } |
| + .tint(OficinaPalette.accent(.sheets)) |
| + #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 kept |
| +/// for self-hosted servers and local accounts (spec §11), with the way back |
| +/// to Oficina ID beneath. |
| +@MainActor public struct SheetsOtherWaysView: 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("Sheets", systemImage: "tablecells", connection: connection) |
| + .safeAreaInset(edge: .bottom, spacing: 0) { |
| + Button { connection.cancel(); oficinaID() } label: { |
| + Label { Text(verbatim: sheetsMacString("Sign in with Oficina ID")) } icon: { Image(systemName: "person.crop.circle") } |
| + } |
| + .buttonStyle(.borderless) |
| + .accessibilityIdentifier("sheets.oficinaid.signin") |
| + .padding(16) |
| + .frame(maxWidth: .infinity) |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/SheetsKit/SheetsWorkspace.swift b/native/apple/Sources/SheetsKit/SheetsWorkspace.swift| index f362578..e8696e2 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetsWorkspace.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetsWorkspace.swift |
| @@ -23,11 +23,23 @@ import SwiftUI |
| private let openDocument: ((UInt64, String) -> Void)? |
| private let signOut: () -> Void |
| private let accounts: (() -> Void)? |
| - public init(client: NativeHTTP, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: UInt64? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), openDocument: ((UInt64, String) -> Void)? = nil, updateRecents: (([(UInt64, String)]) -> Void)? = nil) { |
| + /// "Use another Oficina ID" in the account menu (Paul, 2026-11-19); nil |
| + /// for a server account. |
| + private let useAnother: (() -> Void)? |
| + /// The menu's words for an Oficina ID ("Teams", "Sign out of <label>"); |
| + /// nil keeps "Accounts" and "Sign out". |
| + private let accountsLabel: String? |
| + private let signOutLabel: String? |
| + /// `client` is any transport: a server account's `NativeHTTP`, or an |
| + /// Oficina ID team's `SheetsOficinaTransport`, which reads the latest |
| + /// session on every request. Building the model here only constructs it: |
| + /// nothing observed is read or written (docs 84d1008). |
| + public init(client: any NativeTransport, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: UInt64? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), openDocument: ((UInt64, String) -> Void)? = nil, updateRecents: (([(UInt64, String)]) -> Void)? = nil, useAnother: (() -> Void)? = nil, accountsLabel: String? = nil, signOutLabel: String? = nil) { |
| self.updateRecents = updateRecents; self.canSignOut = canSignOut; self._createRequested = createRequested; self._accountsRequested = accountsRequested; self.documentID = documentID; self.openDocument = openDocument |
| _model = State(initialValue: SheetModel(client: client)) |
| self.signOut = signOut |
| self.accounts = accounts |
| + self.useAnother = useAnother; self.accountsLabel = accountsLabel; self.signOutLabel = signOutLabel |
| } |
| public var body: some View { |
| Group { |
| @@ -143,7 +155,7 @@ import SwiftUI |
| .toolbar { |
| if let accounts { |
| ToolbarItem(placement: .navigation) { |
| - Button(sheetsMacString("Accounts"), systemImage: "chevron.backward", action: accounts) |
| + Button(accountsLabel ?? sheetsMacString("Accounts"), systemImage: "chevron.backward", action: accounts) |
| .disabled(model.hasUnconfirmedChanges || model.busy) |
| } |
| } |
| @@ -156,8 +168,12 @@ import SwiftUI |
| Text("Light").tag("light") |
| Text("Dark").tag("dark") |
| } |
| - Button(sheetsMacString("Sign out"), systemImage: "rectangle.portrait.and.arrow.right", role: .destructive, |
| - action: signOut).disabled(model.hasUnconfirmedChanges || model.busy) |
| + if let useAnother { |
| + Button(OficinaIDText.text("continue.another"), systemImage: "person.crop.circle.badge.plus", action: useAnother) |
| + .disabled(model.hasUnconfirmedChanges || model.busy || !canSignOut) |
| + } |
| + Button(signOutLabel ?? sheetsMacString("Sign out"), systemImage: "rectangle.portrait.and.arrow.right", role: .destructive, |
| + action: signOut).disabled(model.hasUnconfirmedChanges || model.busy || !canSignOut) |
| } label: { |
| VStack(spacing: 3) { |
| Circle().frame(width: 3, height: 3) |
| @@ -300,7 +316,8 @@ import SwiftUI |
| } |
| .navigationTitle(sheetsMacString("Home")) |
| .searchable(text: $query, prompt: sheetsMacString("Search spreadsheets")) |
| - .focusedSceneValue(\.sheetsAccountActions, SheetsAccountActions(accounts: accounts, signOut: signOut, canManage: !model.busy, canSignOut: canSignOut && !model.busy)) |
| + .focusedSceneValue(\.sheetsAccountActions, SheetsAccountActions(accounts: accounts, signOut: signOut, canManage: !model.busy, canSignOut: canSignOut && !model.busy, |
| + useAnother: useAnother, accountsLabel: accountsLabel, signOutLabel: signOutLabel)) |
| .toolbar { |
| newSheet |
| Button(sheetsMacString("Import workbook")) { show("Import") } |
diff --git a/native/apple/Tests/SheetsKitTests/OficinaIDAdoptionTests.swift b/native/apple/Tests/SheetsKitTests/OficinaIDAdoptionTests.swift| new file mode 100644 |
| index 0000000..9dc56d5 |
| --- /dev/null |
| +++ b/native/apple/Tests/SheetsKitTests/OficinaIDAdoptionTests.swift |
| @@ -0,0 +1,293 @@ |
| +import Combine |
| +import Foundation |
| +import Observation |
| +import Synchronization |
| +import RastrilloApple |
| +import RastrilloTestSupport |
| +import XCTest |
| +@testable import SheetsKit |
| + |
| +/// Sheets on Oficina ID (Home spec 2026-11-14-oficina-id-native, slice A, |
| +/// and Paul's straight-in ruling of 2026-11-19), against the kit's in-memory |
| +/// Home, directory and instances. Two models sharing one shared store and |
| +/// App Group are two apps on one device. |
| +@MainActor final class OficinaIDAdoptionTests: XCTestCase { |
| + /// `.invalid`, so a workspace that does talk to it fails at once. |
| + static let sheetsOrigin = URL(string: "https://paulca.sheets.invalid")! |
| + static let docsOrigin = URL(string: "https://paulca.docs.invalid")! |
| + |
| + var service: FakeOficinaIDService! |
| + var shared: OficinaMemoryStore! |
| + var notifier: OficinaLocalNotifier! |
| + var suites: [String] = [] |
| + lazy var group = defaults() |
| + |
| + override func setUp() async throws { |
| + service = FakeOficinaIDService() |
| + shared = OficinaMemoryStore() |
| + notifier = OficinaLocalNotifier() |
| + } |
| + |
| + override func tearDown() async throws { |
| + for suite in suites { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) } |
| + } |
| + |
| + func defaults() -> UserDefaults { |
| + let suite = "SheetsOficinaIDTests.\(UUID().uuidString)" |
| + suites.append(suite) |
| + return UserDefaults(suiteName: suite)! |
| + } |
| + |
| + func model(_ slug: String, _ name: String) -> OficinaIDModel { |
| + let store = OficinaIDStore(shared: shared, appPrivate: OficinaMemoryStore(), group: group, notifier: notifier) |
| + return OficinaIDModel(configuration: OficinaIDConfiguration(app: slug, appName: name, platform: "macos"), store: store, |
| + service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, appDefaults: defaults()) |
| + } |
| + |
| + /// Paul on one team with Docs and Sheets, signed in on this device by Docs: |
| + /// the saved identity Sheets finds at launch. |
| + @discardableResult |
| + func savedIdentity() async throws -> OficinaTeam { |
| + let apps = [OficinaTeamApp(app: "docs", origin: Self.docsOrigin.absoluteString, consumerID: "t1-docs"), |
| + OficinaTeamApp(app: "sheets", origin: Self.sheetsOrigin.absoluteString, consumerID: "t1-sheets")] |
| + let paulca = OficinaTeam(sqid: "t1", label: "paulca", name: "Paul", role: "member", apps: apps) |
| + service.addPerson(email: "paul@tito.io", identityID: "id-1") |
| + service.setTeams([paulca], for: "id-1") |
| + service.admit("id-1", at: Self.docsOrigin, as: .linked) |
| + service.admit("id-1", at: Self.sheetsOrigin, as: .linked) |
| + let docs = model("docs", "Docs") |
| + await docs.start() |
| + docs.continueWithEmail() |
| + docs.email = "paul@tito.io" |
| + await docs.submitEmail() |
| + docs.code = FakeOficinaIDService.goodCode |
| + await docs.submitCode() |
| + // A fixture that cannot sign in fails the test: skipping would hide the |
| + // launch suite behind it. |
| + guard case .signedIn = docs.step else { |
| + XCTFail("Docs did not sign in: \(docs.step)") |
| + throw CancellationError() |
| + } |
| + return paulca |
| + } |
| + |
| + // MARK: Straight in |
| + |
| + /// One Oficina ID on the device: Sheets opens its team with no screen, |
| + /// and the launch is not counted as a sign-in made here. |
| + func testASavedIdentitySignsSheetsStraightIn() async throws { |
| + let paulca = try await savedIdentity() |
| + let sheets = SheetsOficinaSession(model: model("sheets", "Sheets")) |
| + var steps: [String] = [] |
| + let watching = sheets.model.$step.sink { steps.append("\($0)".components(separatedBy: "(").first ?? "") } |
| + await sheets.start() |
| + watching.cancel() |
| + let mounted = try XCTUnwrap(sheets.mounted) |
| + XCTAssertEqual(mounted.team, paulca) |
| + XCTAssertEqual(mounted.origin, Self.sheetsOrigin) |
| + XCTAssertEqual(Set(steps), ["loading", "signedIn"], "no screen on the way in") |
| + XCTAssertEqual(sheets.signIns, 0, "a launch going straight in does not choose the route") |
| + XCTAssertEqual(service.calls.filter { $0.hasPrefix("startCode") }.count, 1, "one sign-in for both apps") |
| + } |
| + |
| + /// Sheets' last route was its own sign-in: nothing goes straight in, and |
| + /// no network is used, until the person comes back to Oficina ID. |
| + func testTheServerRouteSuspendsStraightIn() async throws { |
| + try await savedIdentity() |
| + let sheets = SheetsOficinaSession(model: model("sheets", "Sheets")) |
| + let calls = service.calls.count |
| + await sheets.start(serverRoute: true) |
| + XCTAssertNil(sheets.mounted) |
| + XCTAssertEqual(sheets.model.step, .welcome) |
| + XCTAssertEqual(service.calls.count, calls, "no network while the app's own sign-in is the route") |
| + await sheets.model.resumeStraightIn() |
| + XCTAssertEqual(sheets.mounted?.origin, Self.sheetsOrigin) |
| + } |
| + |
| + /// The route flipping to Oficina ID on its own (the last server account |
| + /// signed out) resumes straight in; flipping back to the app's own |
| + /// sign-in while signed in disturbs nothing (Fable, sheets ded0f68). |
| + func testTheRouteAloneDecidesTheSuspension() async throws { |
| + try await savedIdentity() |
| + let sheets = SheetsOficinaSession(model: model("sheets", "Sheets")) |
| + await sheets.start(serverRoute: true) |
| + XCTAssertTrue(sheets.model.straightInSuspended) |
| + XCTAssertNil(sheets.mounted) |
| + await sheets.routeChanged(to: .oficinaID) |
| + XCTAssertFalse(sheets.model.straightInSuspended) |
| + let mounted = try XCTUnwrap(sheets.mounted, "straight in once the route is Oficina ID") |
| + await sheets.routeChanged(to: .server) |
| + XCTAssertTrue(sheets.model.straightInSuspended) |
| + XCTAssertEqual(sheets.mounted, mounted, "signed in, suspending changes nothing") |
| + } |
| + |
| + /// Sign-out and "Use another" are refused while a document window of the |
| + /// identity is open, and "Use another" while the team is unreachable. |
| + func testLeavingIsRefusedWithAnOpenDocumentOrOverAnOutage() async throws { |
| + let paulca = try await savedIdentity() |
| + let sheets = SheetsOficinaSession(model: model("sheets", "Sheets")) |
| + await sheets.start() |
| + let state = try XCTUnwrap(sheets.mounted) |
| + XCTAssertFalse(sheets.useAnother(identity: state.identity.id, canLeave: false)) |
| + XCTAssertFalse(sheets.model.confirmingReplace) |
| + XCTAssertFalse(sheets.signOut(identity: state.identity.id, canLeave: false)) |
| + XCTAssertEqual(sheets.mounted, state) |
| + XCTAssertEqual(try sheets.model.store.identities().map(\.id), ["id-1"]) |
| + |
| + // Over an outage the team stays mounted, but there is no dialog to ask |
| + // "Use another" with. |
| + service.expire(session: state.session) |
| + service.failNext("exchange", at: Self.sheetsOrigin.absoluteString, with: .offline) |
| + await sheets.rejected(SheetsOficinaSession.accountID(state)) |
| + XCTAssertEqual(sheets.model.step, .unavailable(paulca)) |
| + XCTAssertNotNil(sheets.mounted) |
| + XCTAssertFalse(sheets.useAnother(identity: state.identity.id, canLeave: true)) |
| + XCTAssertFalse(sheets.model.confirmingReplace) |
| + |
| + await sheets.model.retry() |
| + XCTAssertTrue(sheets.useAnother(identity: state.identity.id, canLeave: true)) |
| + XCTAssertTrue(sheets.model.confirmingReplace) |
| + sheets.model.cancelReplace() |
| + XCTAssertTrue(sheets.signOut(identity: state.identity.id, canLeave: true)) |
| + XCTAssertNil(sheets.mounted) |
| + } |
| + |
| + // MARK: Transport |
| + |
| + /// The workspace's transport reads the latest session: a 401 re-mints |
| + /// silently and the next request carries the new one. |
| + func testTheTransportFollowsARemintedSession() async throws { |
| + try await savedIdentity() |
| + let sheets = SheetsOficinaSession(model: model("sheets", "Sheets")) |
| + await sheets.start() |
| + let before = try XCTUnwrap(sheets.mounted) |
| + let account = SheetsOficinaSession.accountID(before) |
| + service.expire(session: before.session) |
| + await sheets.rejected(account) |
| + let after = try XCTUnwrap(sheets.mounted) |
| + XCTAssertNotEqual(after.session, before.session) |
| + XCTAssertTrue(service.isLive(session: after.session)) |
| + // At most once a minute per account: a refusing instance cannot loop. |
| + let asserts = service.calls.filter { $0.hasPrefix("assert") }.count |
| + await sheets.rejected(account) |
| + XCTAssertEqual(service.calls.filter { $0.hasPrefix("assert") }.count, asserts) |
| + } |
| + |
| + /// After sign-out the transport has no session to send: unauthorized, |
| + /// never the old cookie. |
| + func testAfterSignOutTheTransportRefusesToSend() async throws { |
| + try await savedIdentity() |
| + let sheets = SheetsOficinaSession(model: model("sheets", "Sheets")) |
| + await sheets.start() |
| + let state = try XCTUnwrap(sheets.mounted) |
| + let transport = sheets.transport(for: SheetsOficinaSession.accountID(state), origin: state.origin) |
| + sheets.model.signOut() |
| + XCTAssertNil(sheets.mounted) |
| + XCTAssertEqual(sheets.model.step, .welcome) |
| + do { |
| + _ = try await transport.responseDetails("/sheets", method: "GET", body: nil, contentType: "application/json", maxBytes: 1024) |
| + XCTFail("sent after sign-out") |
| + } catch NativeClientError.unauthorized {} |
| + } |
| + |
| + /// A non-GET request with an ended session gets 403 "Sign in first." |
| + /// from Sheets' guards: that is the session, not the request, so it |
| + /// re-mints and reads as unauthorized. Any other 403 stays a refusal. |
| + func testASignInFirst403IsAnEndedSession() async throws { |
| + final class Counts: @unchecked Sendable { var rejected = 0; var refused = 0 } |
| + let counts = Counts() |
| + let server = ScriptedTransport(origin: Self.sheetsOrigin, [ |
| + .respond(status: 403, body: Data("Sign in first.\n".utf8)), |
| + .respond(status: 403, body: Data(#"{"error":"not yours"}"#.utf8)), |
| + ]) |
| + let transport = SheetsOficinaTransport(origin: Self.sheetsOrigin, current: { server }, |
| + rejected: { counts.rejected += 1 }, refused: { counts.refused += 1 }) |
| + let ended = try await transport.responseDetails("/sheets/1/cells", method: "POST", body: Data("{}".utf8), |
| + contentType: "application/json", maxBytes: 1024) |
| + XCTAssertEqual(ended.status, 401) |
| + XCTAssertEqual(counts.rejected, 1) |
| + XCTAssertEqual(counts.refused, 0) |
| + let refusal = try await transport.responseDetails("/sheets/1/cells", method: "POST", body: Data("{}".utf8), |
| + contentType: "application/json", maxBytes: 1024) |
| + XCTAssertEqual(refusal.status, 403) |
| + XCTAssertEqual(counts.rejected, 1) |
| + XCTAssertEqual(counts.refused, 1) |
| + } |
| + |
| + // MARK: "Use another Oficina ID" in the account menu |
| + |
| + func testUseAnotherFromTheMenuAsksThenReplaces() async throws { |
| + try await savedIdentity() |
| + let sheets = SheetsOficinaSession(model: model("sheets", "Sheets")) |
| + await sheets.start() |
| + let state = try XCTUnwrap(sheets.mounted) |
| + sheets.model.useAnother() |
| + XCTAssertTrue(sheets.model.confirmingReplace) |
| + sheets.model.cancelReplace() |
| + XCTAssertEqual(sheets.mounted, state, "cancelling changes nothing") |
| + sheets.model.useAnother() |
| + sheets.model.confirmReplace() |
| + XCTAssertNil(sheets.mounted) |
| + XCTAssertEqual(sheets.model.step, .email) |
| + XCTAssertEqual(try sheets.model.store.identities(), []) |
| + } |
| + |
| + // MARK: Accounts and teams |
| + |
| + func testAccountIDsArePerIdentityAndTeam() { |
| + let id = SheetsOficinaSession.accountID(identity: "id-1", team: "t1") |
| + XCTAssertEqual(id, "oficina-id.id-1.t1") |
| + XCTAssertTrue(SheetsOficinaSession.account(id, belongsTo: "id-1")) |
| + XCTAssertFalse(SheetsOficinaSession.account(id, belongsTo: "id-10")) |
| + let odd = SheetsOficinaSession.accountID(identity: "a.b", team: "t/1") |
| + XCTAssertFalse(odd.dropFirst(SheetsOficinaSession.prefix.count).contains("/")) |
| + XCTAssertTrue(SheetsOficinaSession.account(odd, belongsTo: "a.b")) |
| + XCTAssertFalse(SheetsOficinaSession.account(odd, belongsTo: "a")) |
| + } |
| + |
| + func testThePickerListsOnlyTeamsWithSheets() { |
| + let current = OficinaTeam(sqid: "t1", label: "paulca", name: "Paul", role: "member", |
| + apps: [OficinaTeamApp(app: "sheets", origin: Self.sheetsOrigin.absoluteString, consumerID: "c")]) |
| + let docsOnly = OficinaTeam(sqid: "t2", label: "docs", name: "Another", role: "member", |
| + apps: [OficinaTeamApp(app: "docs", origin: Self.docsOrigin.absoluteString, consumerID: "d")]) |
| + XCTAssertEqual(SheetsTeamPicker.teams([docsOnly], current: current).map(\.sqid), ["t1"]) |
| + } |
| + |
| + func testTheRouteKeepsServerAccountsUntilOficinaIDIsChosen() { |
| + XCTAssertEqual(SheetsSignInRoute.resolve(stored: "", hasServerAccounts: false), .oficinaID) |
| + XCTAssertEqual(SheetsSignInRoute.resolve(stored: "", hasServerAccounts: true), .server) |
| + XCTAssertEqual(SheetsSignInRoute.resolve(stored: "oficina-id", hasServerAccounts: true), .oficinaID) |
| + XCTAssertEqual(SheetsSignInRoute.resolve(stored: "server", hasServerAccounts: false), .server) |
| + } |
| + |
| + // MARK: Launch with a saved account (the Docs 0.1.7/0.1.8 lesson, docs 84d1008) |
| + |
| + /// What the signed-in window's body builds, built under observation as a |
| + /// body is: the transport and the workspace. Neither may change anything |
| + /// a view watches, or each body pass would invalidate the next. |
| + func testBuildingTheSignedInWorkspaceChangesNothingAViewWatches() async throws { |
| + try await savedIdentity() |
| + let sheets = SheetsOficinaSession(model: model("sheets", "Sheets")) |
| + await sheets.start() |
| + let state = try XCTUnwrap(sheets.mounted) |
| + let account = SheetsOficinaSession.accountID(state) |
| + let connectivity = NativeConnectivity.shared |
| + var published = 0 |
| + let watches = [sheets.objectWillChange.sink { published += 1 }, sheets.model.objectWillChange.sink { published += 1 }] |
| + let changed = Mutex(false) |
| + withObservationTracking { |
| + _ = connectivity.path |
| + _ = connectivity.serverReachable |
| + let transport = sheets.transport(for: account, origin: state.origin) |
| + _ = SheetsWorkspace(client: transport, signOut: {}, useAnother: {}, accountsLabel: "Teams", signOutLabel: "Sign out") |
| + _ = sheets.mounted |
| + _ = sheets.model.step |
| + } onChange: { changed.withLock { $0 = true } } |
| + for _ in 0..<3 { |
| + _ = SheetsWorkspace(client: sheets.transport(for: account, origin: state.origin), signOut: {}) |
| + } |
| + watches.forEach { $0.cancel() } |
| + XCTAssertFalse(changed.withLock { $0 }, "building the signed-in workspace must not invalidate its window") |
| + XCTAssertEqual(published, 0, "nor publish from the session or the model") |
| + } |
| +} |
diff --git a/native/apple/Tests/SheetsWindowTests/SignedInLaunchTests.swift b/native/apple/Tests/SheetsWindowTests/SignedInLaunchTests.swift| new file mode 100644 |
| index 0000000..521b5de |
| --- /dev/null |
| +++ b/native/apple/Tests/SheetsWindowTests/SignedInLaunchTests.swift |
| @@ -0,0 +1,135 @@ |
| +#if os(macOS) |
| +import AppKit |
| +import Combine |
| +import Foundation |
| +import Observation |
| +import Synchronization |
| +import SwiftUI |
| +import XCTest |
| +import RastrilloApple |
| +import RastrilloTestSupport |
| +import SheetsKit |
| +@testable import SheetsMac |
| + |
| +/// Launching with a saved account (the Docs 0.1.7/0.1.8 lesson, docs |
| +/// 84d1008): Docs' window body built a workspace whose init read and then |
| +/// changed state the body watched, so every pass invalidated the next and |
| +/// the main thread never came back, but only for someone already signed |
| +/// in. A clean launch never shows it. These host Sheets' real home window |
| +/// with an Oficina ID already on the device, let it settle, and check that |
| +/// it stops changing. |
| +@MainActor final class SignedInLaunchTests: XCTestCase { |
| + static let sheetsOrigin = URL(string: "https://paulca.sheets.invalid")! |
| + |
| + /// An Oficina ID another app saved, and Sheets' session after going |
| + /// straight in with it. |
| + private func signedInSession() async throws -> SheetsOficinaSession { |
| + let service = FakeOficinaIDService() |
| + let shared = OficinaMemoryStore(), notifier = OficinaLocalNotifier() |
| + let group = UserDefaults(suiteName: "SignedInLaunchTests.\(UUID().uuidString)")! |
| + func model(_ slug: String, _ name: String) -> OficinaIDModel { |
| + OficinaIDModel(configuration: OficinaIDConfiguration(app: slug, appName: name, platform: "macos"), |
| + store: OficinaIDStore(shared: shared, appPrivate: OficinaMemoryStore(), group: group, notifier: notifier), |
| + service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, |
| + appDefaults: UserDefaults(suiteName: "SignedInLaunchTests.\(UUID().uuidString)")!) |
| + } |
| + let team = OficinaTeam(sqid: "t1", label: "paulca", name: "Paul", role: "member", |
| + apps: [OficinaTeamApp(app: "sheets", origin: Self.sheetsOrigin.absoluteString, consumerID: "t1-sheets"), |
| + OficinaTeamApp(app: "docs", origin: "https://paulca.docs.invalid", consumerID: "t1-docs")]) |
| + service.addPerson(email: "paul@tito.io", identityID: "id-1") |
| + service.setTeams([team], for: "id-1") |
| + service.admit("id-1", at: Self.sheetsOrigin, as: .linked) |
| + service.admit("id-1", at: URL(string: "https://paulca.docs.invalid")!, as: .linked) |
| + let docs = model("docs", "Docs") |
| + await docs.start() |
| + docs.continueWithEmail() |
| + docs.email = "paul@tito.io" |
| + await docs.submitEmail() |
| + docs.code = FakeOficinaIDService.goodCode |
| + await docs.submitCode() |
| + let sheets = SheetsOficinaSession(model: model("sheets", "Sheets")) |
| + await sheets.start() |
| + // Failing, not skipping: a skip here would hide the whole launch suite. |
| + guard sheets.mounted != nil else { |
| + XCTFail("Sheets did not go straight in: \(sheets.model.step)") |
| + throw CancellationError() |
| + } |
| + return sheets |
| + } |
| + |
| + func testTheSignedInHomeWindowSettlesWithASavedIdentity() async throws { |
| + let sheets = try await signedInSession() |
| + let mounted = try XCTUnwrap(sheets.mounted) |
| + UserDefaults.standard.removeObject(forKey: SheetsSignInRoute.key) |
| + defer { UserDefaults.standard.removeObject(forKey: SheetsSignInRoute.key) } |
| + let windows = SheetsWindows() |
| + |
| + // If the window loops, the main thread never returns here; say why |
| + // rather than hang the run. |
| + let finished = Mutex(false) |
| + DispatchQueue.global().asyncAfter(deadline: .now() + 60) { |
| + if !finished.withLock({ $0 }) { |
| + fatalError("Sheets' signed-in home window never let the main thread go: a view loop (docs 84d1008)") |
| + } |
| + } |
| + let host = NSHostingView(rootView: SheetsAccountWindow(oficina: sheets, windows: windows)) |
| + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 760), styleMask: [.titled, .resizable], |
| + backing: .buffered, defer: false) |
| + window.contentView = host |
| + window.orderFrontRegardless() |
| + defer { window.orderOut(nil); window.contentView = nil } |
| + |
| + func pump(_ seconds: Double) async { |
| + let end = Date().addingTimeInterval(seconds) |
| + while Date() < end { |
| + host.layoutSubtreeIfNeeded() |
| + try? await Task.sleep(nanoseconds: 20_000_000) |
| + } |
| + } |
| + // Launch: the body runs, its .task and .onChange(initial:) fire, the |
| + // workspace's first request fails at once (.invalid). |
| + await pump(1.5) |
| + XCTAssertEqual(windows.activeAccount, SheetsOficinaSession.accountID(mounted), "the signed-in workspace is what showed") |
| + |
| + // Settled: nothing the window watches keeps changing. |
| + var published = 0 |
| + let watches = [sheets.objectWillChange.sink { published += 1 }, sheets.model.objectWillChange.sink { published += 1 }] |
| + let invalidated = Mutex(0) |
| + func track() { |
| + withObservationTracking { |
| + _ = windows.activeAccount |
| + _ = windows.entries |
| + _ = windows.accountsRequested |
| + } onChange: { invalidated.withLock { $0 += 1 } } |
| + } |
| + track() |
| + await pump(1.0) |
| + watches.forEach { $0.cancel() } |
| + finished.withLock { $0 = true } |
| + XCTAssertEqual(published, 0, "the session and model stay still once the window has settled") |
| + XCTAssertEqual(invalidated.withLock { $0 }, 0, "the window state it writes stays still once settled") |
| + XCTAssertEqual(sheets.mounted, mounted, "still signed in to the same team") |
| + } |
| + |
| + /// The window's body itself, evaluated as SwiftUI would, three times |
| + /// over, under observation: building it must change nothing it watches. |
| + func testBuildingTheSignedInWindowBodyChangesNothingItWatches() async throws { |
| + let sheets = try await signedInSession() |
| + UserDefaults.standard.removeObject(forKey: SheetsSignInRoute.key) |
| + let windows = SheetsWindows() |
| + var published = 0 |
| + let watches = [sheets.objectWillChange.sink { published += 1 }, sheets.model.objectWillChange.sink { published += 1 }] |
| + let changed = Mutex(false) |
| + let view = SheetsAccountWindow(oficina: sheets, windows: windows) |
| + withObservationTracking { |
| + _ = windows.activeAccount |
| + _ = windows.entries |
| + _ = view.body |
| + } onChange: { changed.withLock { $0 = true } } |
| + for _ in 0..<3 { _ = view.body } |
| + watches.forEach { $0.cancel() } |
| + XCTAssertFalse(changed.withLock { $0 }, "a body pass must not invalidate the next") |
| + XCTAssertEqual(published, 0) |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Tests/SheetsWindowTests/WindowRoutingTests.swift b/native/apple/Tests/SheetsWindowTests/WindowRoutingTests.swift| index 648936e..3f5b1f7 100644 |
| --- a/native/apple/Tests/SheetsWindowTests/WindowRoutingTests.swift |
| +++ b/native/apple/Tests/SheetsWindowTests/WindowRoutingTests.swift |
| @@ -24,4 +24,17 @@ import RastrilloApple |
| #expect(windows.entries.first(where: { $0.id == id })?.title == "Current title") |
| #expect(windows.entries.first(where: { $0.id == id })?.isOpen == false) |
| } |
| + |
| +/// Signing out of an Oficina ID ends all its teams, so any of its teams' |
| +/// open document windows blocks it; another identity's never does. |
| +@MainActor @Test func openDocumentsBlockLeavingTheirIdentityOnly() { |
| + let windows = SheetsWindows() |
| + let client = NativeHTTP(origin: URL(string: "https://team.invalid")!) |
| + let account = "oficina-id.id-1.t2" |
| + let id = windows.reserve(account: account, document: 1, title: "Plan", client: client) |
| + #expect(windows.hasOpenDocuments(identity: "id-1")) |
| + #expect(!windows.hasOpenDocuments(identity: "id-10")) |
| + windows.setOpen(id, false) |
| + #expect(!windows.hasOpenDocuments(identity: "id-1")) |
| +} |
| #endif |
diff --git a/native/ios/SheetsPhone.entitlements b/native/ios/SheetsPhone.entitlements| new file mode 100644 |
| index 0000000..958297e |
| --- /dev/null |
| +++ b/native/ios/SheetsPhone.entitlements |
| @@ -0,0 +1,23 @@ |
| +<?xml version="1.0" encoding="UTF-8"?> |
| +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> |
| +<plist version="1.0"> |
| +<dict> |
| + <key>com.apple.developer.associated-domains</key> |
| + <array> |
| + <string>webcredentials:id.oficina.works</string> |
| + </array> |
| + <key>com.apple.security.application-groups</key> |
| + <array> |
| + <string>group.works.oficina</string> |
| + </array> |
| + <!-- Sheets' own group FIRST: a keychain query that names no group lands in |
| + the first one, and Sheets' sessions must never land in the group |
| + every Oficina app reads (rastrillo/native APPLE.md, "Oficina ID, |
| + slice A"). The second is the shared Oficina ID group. --> |
| + <key>keychain-access-groups</key> |
| + <array> |
| + <string>9U4A84C4WK.works.oficina.sheets</string> |
| + <string>9U4A84C4WK.works.oficina.id</string> |
| + </array> |
| +</dict> |
| +</plist> |
diff --git a/native/ios/project.yml b/native/ios/project.yml| index 3ce2f3c..9501272 100644 |
| --- a/native/ios/project.yml |
| +++ b/native/ios/project.yml |
| @@ -8,7 +8,7 @@ packages: |
| path: ../apple |
| RastrilloNative: |
| url: https://amadan.net/rastrillo/native |
| - revision: c989034602fd540531e845b0934864575be11b3e |
| + revision: 1e36aac95ed252848722926efc8ba8f9dc803216 |
| settings: |
| base: |
| SWIFT_VERSION: '6.0' |
| @@ -36,6 +36,10 @@ targets: |
| ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon |
| PROVISIONING_PROFILE_SPECIFIER: $(OFICINA_PROVISIONING_PROFILE) |
| PRODUCT_BUNDLE_IDENTIFIER: works.oficina.sheets |
| + # Oficina ID (rastrillo/native APPLE.md, "Oficina ID, slice A"): |
| + # Sheets' own keychain group first, then the shared one; |
| + # group.works.oficina; webcredentials:id.oficina.works for passkeys. |
| + CODE_SIGN_ENTITLEMENTS: SheetsPhone.entitlements |
| TARGETED_DEVICE_FAMILY: 1,2 |
| GENERATE_INFOPLIST_FILE: true |
| INFOPLIST_KEY_CFBundleDisplayName: Oficina Sheets |
diff --git a/native/mac-updates.json b/native/mac-updates.json| index 14d24be..89ccaba 100644 |
| --- a/native/mac-updates.json |
| +++ b/native/mac-updates.json |
| @@ -20,5 +20,7 @@ |
| "vi", |
| "yue", |
| "zh-Hans" |
| - ] |
| + ], |
| + "entitlements": "macos/DeveloperID.entitlements", |
| + "provisioning_profile": "~/private_keys/oficina/profiles/Oficina-Sheets-macOS-Developer-ID.provisionprofile" |
| } |
diff --git a/native/macos/AppStore.entitlements b/native/macos/AppStore.entitlements| index a046386..87ba1f5 100644 |
| --- a/native/macos/AppStore.entitlements |
| +++ b/native/macos/AppStore.entitlements |
| @@ -8,5 +8,22 @@ |
| <true/> |
| <key>com.apple.security.network.client</key> |
| <true/> |
| + <key>com.apple.developer.associated-domains</key> |
| + <array> |
| + <string>webcredentials:id.oficina.works</string> |
| + </array> |
| + <key>com.apple.security.application-groups</key> |
| + <array> |
| + <string>9U4A84C4WK.works.oficina</string> |
| + </array> |
| + <!-- Sheets' own group FIRST: a keychain query that names no group lands in |
| + the first one, and Sheets' sessions must never land in the group |
| + every Oficina app reads (rastrillo/native APPLE.md, "Oficina ID, |
| + slice A"). The second is the shared Oficina ID group. --> |
| + <key>keychain-access-groups</key> |
| + <array> |
| + <string>9U4A84C4WK.works.oficina.sheets</string> |
| + <string>9U4A84C4WK.works.oficina.id</string> |
| + </array> |
| </dict> |
| </plist> |
diff --git a/native/macos/DeveloperID.entitlements b/native/macos/DeveloperID.entitlements| new file mode 100644 |
| index 0000000..e76c2c6 |
| --- /dev/null |
| +++ b/native/macos/DeveloperID.entitlements |
| @@ -0,0 +1,23 @@ |
| +<?xml version="1.0" encoding="UTF-8"?> |
| +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> |
| +<plist version="1.0"> |
| +<dict> |
| + <key>com.apple.developer.associated-domains</key> |
| + <array> |
| + <string>webcredentials:id.oficina.works</string> |
| + </array> |
| + <key>com.apple.security.application-groups</key> |
| + <array> |
| + <string>9U4A84C4WK.works.oficina</string> |
| + </array> |
| + <!-- Sheets' own group FIRST: a keychain query that names no group lands in |
| + the first one, and Sheets' sessions must never land in the group |
| + every Oficina app reads (rastrillo/native APPLE.md, "Oficina ID, |
| + slice A"). The second is the shared Oficina ID group. --> |
| + <key>keychain-access-groups</key> |
| + <array> |
| + <string>9U4A84C4WK.works.oficina.sheets</string> |
| + <string>9U4A84C4WK.works.oficina.id</string> |
| + </array> |
| +</dict> |
| +</plist> |
diff --git a/native/macos/SheetsMacStore.xcodeproj/project.pbxproj b/native/macos/SheetsMacStore.xcodeproj/project.pbxproj| index f7d9633..cd66fe9 100644 |
| --- a/native/macos/SheetsMacStore.xcodeproj/project.pbxproj |
| +++ b/native/macos/SheetsMacStore.xcodeproj/project.pbxproj |
| @@ -384,7 +384,7 @@ |
| repositoryURL = "https://amadan.net/rastrillo/native"; |
| requirement = { |
| kind = revision; |
| - revision = c989034602fd540531e845b0934864575be11b3e; |
| + revision = 1e36aac95ed252848722926efc8ba8f9dc803216; |
| }; |
| }; |
| /* End XCRemoteSwiftPackageReference section */ |
diff --git a/native/macos/project.yml b/native/macos/project.yml| index 0a2af50..f3a8a46 100644 |
| --- a/native/macos/project.yml |
| +++ b/native/macos/project.yml |
| @@ -7,7 +7,7 @@ packages: |
| path: ../apple |
| RastrilloNative: |
| url: https://amadan.net/rastrillo/native |
| - revision: c989034602fd540531e845b0934864575be11b3e |
| + revision: 1e36aac95ed252848722926efc8ba8f9dc803216 |
| settings: |
| base: |
| SWIFT_VERSION: '6.0' |