fix(sharing): drop an account read answered across a record switch

Raising the record-session hold clears the query cache, which remounts the
account query, so the switching tab has a GET /api/auth/me in flight beside
its own POST /api/account/switch. When the server answered that read from
the record being left and the answer was applied after the commit, fetchMe
rewrote the scope mirror back to the old record. A peer tab that had already
settled read that write as a foreign switch and published a hold expecting
the old record, which no /me would ever confirm, so every tab sat behind the
hydration gate until the stored transition aged out.

The transition store now counts the changes a tab applies, and fetchMe
repeats a read whose request straddled one instead of applying it.
This commit is contained in:
Marc-André Bombeck committed 2026-11-15 10:58:06 +01:00
1 parent ac4a4b2fbc
commit 23a6f85b0f
4 files changed
+220 -8

No files matched your search

+6
View File
@@ -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
@@ -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();
});
});
+42 -8
View File
@@ -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<AuthUser> & {
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<MePayload> {
for (let attempt = 0; ; attempt++) {
const before = recordSessionRevision();
const data = await apiGet<MePayload>("/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<AuthUser> {
// 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<AuthUser> {
// 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<AuthUser> & {
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.
@@ -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 {