diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d4156079..69ca20e46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,12 @@ default was rejected as in the future, and onset dates could display as the wrong calendar day in non-UTC time zones. Saving now anchors to the current time when before local noon and preserves stored timestamps on edit. +- **Opening a record with the app open in a second tab.** Switching into or + out of a shared record could leave both tabs on the loading spinner, and a + reload within the next half minute did not help. An account check the + switching tab had started a moment before the switch could answer with the + record being left and overwrite the switch the other tabs were waiting on. + Such an answer is now discarded and asked again. ### Security diff --git a/src/hooks/__tests__/use-auth-superseded-me.test.ts b/src/hooks/__tests__/use-auth-superseded-me.test.ts new file mode 100644 index 000000000..86f1b154c --- /dev/null +++ b/src/hooks/__tests__/use-auth-superseded-me.test.ts @@ -0,0 +1,149 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { + __resetRecordFenceForTests, + currentRecordFenceState, +} from "@/lib/api/record-fence"; +import { + __resetRecordScopeForTests, + getRecordScope, + setRecordScope, +} from "@/lib/query-keys/record-scope"; +import { + __resetRecordSessionTransitionForTests, + beginRecordSessionTransition, + commitRecordSessionTransition, + getRecordSessionTransition, +} from "@/lib/query-keys/record-session-transition"; + +const apiGet = vi.fn(); + +vi.mock("@/lib/api/api-fetch", () => ({ + apiGet: (...args: unknown[]) => apiGet(...args), + apiFetchRaw: vi.fn(), + ApiError: class ApiError extends Error {}, +})); + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: vi.fn(), replace: vi.fn() }), +})); + +import { fetchMe } from "../use-auth"; + +/** + * A `/api/auth/me` answered across a record-session transition. + * + * The browser journey that found this: the switcher clears the query cache + * when it raises the hold, which remounts the account query, so the initiating + * tab has a `/me` in flight beside its own switch POST. The server answers it + * with the record being left. Applied after the commit, that answer rewrote the + * scope mirror to the old record, a settled peer read the write as a foreign + * switch, and every tab then waited for a `/me` naming a record the server had + * already left — behind the hydration gate, for good. + */ + +const TARGET = "record-b"; + +const entry = { + accountId: TARGET, + username: "record-b", + displayName: null, + fullName: null, + access: "read", + level: "read", + recordKind: "shared", + sections: null, + canWrite: false, + writableDomains: [], + manageableDomains: [], +}; + +const base = { + id: "delegate", + username: "delegate", + role: "USER", + timezone: "Europe/Berlin", +}; + +/** What the server says before the switch lands: the caller's own record. */ +const beforeSwitch = { + ...base, + accountAccess: { + accounts: [entry], + active: null, + recordKind: "self", + canSwitch: true, + }, + recordSession: { epoch: 4, scope: null }, +}; + +/** And after it. */ +const afterSwitch = { + ...base, + accountAccess: { + accounts: [entry], + active: entry, + recordKind: "shared", + canSwitch: true, + }, + recordSession: { epoch: 5, scope: TARGET }, +}; + +beforeEach(() => { + apiGet.mockReset(); + __resetRecordScopeForTests(); + __resetRecordSessionTransitionForTests(); + __resetRecordFenceForTests(); +}); + +describe("fetchMe across a record-session transition", () => { + it("drops an answer that straddled the commit and reads again", async () => { + setRecordScope(null); + const id = beginRecordSessionTransition(TARGET); + + apiGet + .mockImplementationOnce(async () => { + // The switch commits while this read is on the wire, and the server + // had already answered it from the record being left. + commitRecordSessionTransition(id, TARGET); + return beforeSwitch; + }) + .mockResolvedValueOnce(afterSwitch); + + const user = await fetchMe(); + + expect(apiGet).toHaveBeenCalledTimes(2); + expect(user.accountAccess?.active?.accountId).toBe(TARGET); + // The committed scope survives; the pre-switch answer never reached the + // mirror or the fence. + expect(getRecordScope()).toBe(TARGET); + expect(currentRecordFenceState()).toEqual({ epoch: 5, scope: TARGET }); + // And the hold releases on the read that describes the switched session. + expect(getRecordSessionTransition().phase).toBe("ready"); + }); + + it("applies an answer when nothing moved while it was in flight", async () => { + const id = beginRecordSessionTransition(TARGET); + commitRecordSessionTransition(id, TARGET); + apiGet.mockResolvedValueOnce(afterSwitch); + + await fetchMe(); + + expect(apiGet).toHaveBeenCalledTimes(1); + expect(getRecordScope()).toBe(TARGET); + expect(getRecordSessionTransition().phase).toBe("ready"); + }); + + it("gives up without applying anything when the session never holds still", async () => { + setRecordScope(null); + apiGet.mockImplementation(async () => { + // Every read straddles a fresh transition. + beginRecordSessionTransition(TARGET); + return beforeSwitch; + }); + + await expect(fetchMe()).rejects.toThrow(/kept moving/); + expect(apiGet).toHaveBeenCalledTimes(4); + expect(currentRecordFenceState()).toBeNull(); + }); +}); diff --git a/src/hooks/use-auth.ts b/src/hooks/use-auth.ts index 0c84e4924..580d4a7bf 100644 --- a/src/hooks/use-auth.ts +++ b/src/hooks/use-auth.ts @@ -36,6 +36,7 @@ import { setRefusedRecordScope, } from "@/lib/query-keys/record-scope"; import { + recordSessionRevision, settleRecordSessionTransition, settleRefusedRecordSessionTransition, } from "@/lib/query-keys/record-session-transition"; @@ -361,6 +362,46 @@ export function isAuthVerdictUnknown(error: unknown): boolean { return true; } +/** + * How many times `fetchMe` asks again when a record-session transition moved + * while its request was in flight. Each repeat needs another transition inside + * one round trip, which only a browser switching records over and over + * produces. + */ +const SUPERSEDED_ME_RETRIES = 3; + +type MePayload = Partial & { + id: string; + username: string; + role: string; + timezone: string; +}; + +/** + * `GET /api/auth/me`, never answered across a record-session transition. + * + * Everything `fetchMe` does with the payload is a statement about which record + * this browser is in: it adopts the fence context, rewrites the cache-scope + * mirror every other tab watches, and may release the hold. A request issued + * before a transition and answered after it may have been read on the far side + * of a switch, and applying it is how a browser ended up wedged behind the + * hydration gate (see `recordSessionRevision`). Such an answer is dropped and + * the read repeated; the repeat is issued after the change, so it describes the + * session as it now is. + */ +async function getCurrentMe(): Promise { + for (let attempt = 0; ; attempt++) { + const before = recordSessionRevision(); + const data = await apiGet("/api/auth/me"); + if (recordSessionRevision() === before) return data; + if (attempt >= SUPERSEDED_ME_RETRIES) { + // Not an `ApiError`: no verdict on the session, so nothing is wiped and + // the hold stays until a later read settles it. + throw new Error("record session kept moving during /api/auth/me"); + } + } +} + export async function fetchMe(): Promise { // v1.16.4 — routed through the typed wrapper; a non-OK /me (401) // throws `ApiError`, which `useAuth` treats as "not authenticated" @@ -369,14 +410,7 @@ export async function fetchMe(): Promise { // v1.4.47 — coerce `disableCoach` against `undefined` so a stale // /me payload from a partial-deploy rollback (older server image // without the field) keeps the Coach surface visible by default. - const data = await apiGet< - Partial & { - id: string; - username: string; - role: string; - timezone: string; - } - >("/api/auth/me"); + const data = await getCurrentMe(); // Hour-cycle preference: coerce against a stale /me payload, then mirror // into localStorage so `useFormatters()` and the legacy format helpers // (which cannot reach the query cache) render the same clock. diff --git a/src/lib/query-keys/record-session-transition.ts b/src/lib/query-keys/record-session-transition.ts index c971883c3..d44f8d5a9 100644 --- a/src/lib/query-keys/record-session-transition.ts +++ b/src/lib/query-keys/record-session-transition.ts @@ -51,6 +51,8 @@ const READY: RecordSessionTransition = { let transition = READY; let seeded = false; +/** Bumped on every change this tab applies; see `recordSessionRevision`. */ +let revision = 0; const listeners = new Set<() => void>(); let channel: BroadcastChannel | null = null; let storageListenerAttached = false; @@ -107,6 +109,7 @@ function applyWire(next: WireTransition): void { } transition = toSnapshot(next); seeded = true; + revision += 1; notify(); } @@ -228,6 +231,26 @@ export function getRecordSessionTransition(): RecordSessionTransition { return transition; } +/** + * A counter that moves whenever this tab applies a transition change — its own + * publish, or one received from another tab. + * + * `fetchMe` reads it on both sides of its request. A `/api/auth/me` answered + * across a change cannot say which side of that change the server read it on: + * the switcher's own `queryClient.clear()` remounts the account query the + * moment the hold goes up, so the initiator routinely has a `/me` in flight + * beside its own `POST /api/account/switch`, and that answer can describe the + * record the session has just left. Applied after the commit, it rewrites the + * scope mirror back to the old record; every peer that has already settled + * reads that write as a foreign switch and holds for a `/me` naming the old + * record, which no server answer will ever give. The counter is how `fetchMe` + * recognises such an answer and asks again instead of applying it. + */ +export function recordSessionRevision(): number { + seed(); + return revision; +} + export function subscribeToRecordSessionTransition( listener: () => void, ): () => void {