mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
feat(02-12.1): carry and verify the record context from the browser
- attach the asserted context to every same-origin request inside the three fetch entries, so no call site classifies itself - discard a response whose echoed context contradicts the adopted one; serve one that carries no echo, which is what keeps the public poll and every actor surface working - adopt from /api/auth/me and the switch response, and from nothing else - send the epoch on every switch and retry once after reconciling - hold and reconcile on the 409 instead of leaving the record
This commit is contained in:
1 parent
3a99de312e
commit
31b4857d8b
15 files changed
+939
-25
No files matched your search
@@ -17,7 +17,10 @@
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveRecordCapabilities } from "@/hooks/use-record-capabilities";
|
||||
import {
|
||||
recordContextIsUnproven,
|
||||
resolveRecordCapabilities,
|
||||
} from "@/hooks/use-record-capabilities";
|
||||
import type { AccountAccessEntry } from "@/lib/sharing/account-access-view";
|
||||
|
||||
const READ_ONLY: AccountAccessEntry = {
|
||||
@@ -155,3 +158,68 @@ describe("resolveRecordCapabilities", () => {
|
||||
expect(resolveRecordCapabilities(disagreeing).canAdd).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* v1.37.0 — the record context has to be PROVABLE before the controls appear.
|
||||
*
|
||||
* `/api/auth/me` publishes the same question from two angles: `accountAccess.active`
|
||||
* is the re-decided answer (it survived a live-grant pass), and `recordSession.scope`
|
||||
* is the raw selector the fence compares a request's assertion against. When
|
||||
* they disagree the session is pointed at a record the grant no longer opens:
|
||||
* every delegable route will refuse, while `active` being null would otherwise
|
||||
* make this hook answer "your own record, all controls". That combination
|
||||
* paints an add button on a page whose every write is about to 403 — the exact
|
||||
* failure `canAdd` exists to end.
|
||||
*/
|
||||
describe("an unprovable record context withholds every control", () => {
|
||||
it("holds when the raw selector names a record the grant no longer opens", () => {
|
||||
expect(
|
||||
recordContextIsUnproven({ epoch: 3, scope: "acct-owner" }, null),
|
||||
).toBe(true);
|
||||
const held = resolveRecordCapabilities(null, false, false, true);
|
||||
expect(held.canAdd).toBe(false);
|
||||
expect(held.canManage).toBe(false);
|
||||
expect(held.recordSessionPending).toBe(true);
|
||||
});
|
||||
|
||||
it("holds when the resolved entry names a record the selector has left", () => {
|
||||
// The mirror image: the grant resolved, but the session is back on its own
|
||||
// record. Painting the owner's controls here would be the reverse mix-up.
|
||||
expect(recordContextIsUnproven({ epoch: 4, scope: null }, READ_ONLY)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("agrees when both answers name the same record", () => {
|
||||
expect(
|
||||
recordContextIsUnproven(
|
||||
{ epoch: 3, scope: READ_ONLY.accountId },
|
||||
READ_ONLY,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(recordContextIsUnproven({ epoch: 0, scope: null }, null)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not hold when there is no context to cross-check", () => {
|
||||
// Null is the Bearer transport (no session row, no switch state) and
|
||||
// undefined is a server image that predates the field. Neither is a
|
||||
// disagreement, and neither is a reason to blank the app for everybody.
|
||||
expect(recordContextIsUnproven(null, null)).toBe(false);
|
||||
expect(recordContextIsUnproven(undefined, READ_ONLY)).toBe(false);
|
||||
// The positive control for the two above: without it, a
|
||||
// `recordContextIsUnproven` that always returned false would pass them.
|
||||
expect(recordContextIsUnproven({ epoch: 1, scope: "someone" }, null)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves every existing arm untouched when the two agree", () => {
|
||||
// The fourth argument defaults to false, so every case above this block
|
||||
// means exactly what it meant before the fence existed.
|
||||
expect(resolveRecordCapabilities(READ_ONLY)).toEqual(
|
||||
resolveRecordCapabilities(READ_ONLY, false, false, false),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,11 @@ import { useCallback } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { ApiError, apiPost } from "@/lib/api/api-fetch";
|
||||
import {
|
||||
adoptRecordFenceState,
|
||||
currentRecordFenceState,
|
||||
} from "@/lib/api/record-fence";
|
||||
import { fetchMe } from "@/hooks/use-auth";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { clearOfflineCachesForRecordSwitch } from "@/lib/pwa/query-persister";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
@@ -88,6 +93,20 @@ export function isSharingNotPermitted(error: unknown): boolean {
|
||||
return errorCodeOf(error) === SHARING_NOT_PERMITTED;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.37.0 — the record-session fence's 409. Not a refusal of access: another
|
||||
* tab moved the selector first, or this tab's context is older than the row.
|
||||
* The response is to reconcile through `/api/auth/me` and try again, NOT to
|
||||
* leave the record — which is why it is deliberately absent from the set
|
||||
* `subscribeToGrantLoss` fires on below.
|
||||
*/
|
||||
export const SHARING_SESSION_CHANGED = "sharing.session.changed";
|
||||
|
||||
/** True when the server refused because this session's record context moved. */
|
||||
export function isRecordSessionChanged(error: unknown): boolean {
|
||||
return errorCodeOf(error) === SHARING_SESSION_CHANGED;
|
||||
}
|
||||
|
||||
interface SwitchResponse {
|
||||
actingAs: {
|
||||
accountId: string;
|
||||
@@ -95,10 +114,54 @@ interface SwitchResponse {
|
||||
displayName: string | null;
|
||||
access: "READ" | "WRITE";
|
||||
} | null;
|
||||
/**
|
||||
* The context this session is now in. Null when the request carried no
|
||||
* `expectedEpoch` — which a fence-aware client never does, so in this bundle
|
||||
* it is always present on a 200.
|
||||
*/
|
||||
recordSession: { epoch: number; scope: string | null } | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask the server to move the selector, naming the epoch this browser believes
|
||||
* it is on, and adopt whatever context comes back.
|
||||
*
|
||||
* The epoch turns the write into a compare-and-set: two tabs pressing the
|
||||
* switcher at the same moment resolve to one monotonic outcome and the loser
|
||||
* gets a 409 instead of silently overwriting the winner. Adopting the response
|
||||
* is what lets the very next request prove its context — this endpoint and
|
||||
* `/api/auth/me` are the only two a client may adopt from.
|
||||
*/
|
||||
async function postSwitch(accountId: string | null): Promise<SwitchResponse> {
|
||||
return apiPost<SwitchResponse>("/api/account/switch", { accountId });
|
||||
const response = await apiPost<SwitchResponse>("/api/account/switch", {
|
||||
accountId,
|
||||
expectedEpoch: currentRecordFenceState()?.epoch ?? 0,
|
||||
});
|
||||
adoptRecordFenceState(response.recordSession);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* The switch, with one reconcile-and-retry.
|
||||
*
|
||||
* A lost compare-and-set is not a failure the person at the keyboard caused or
|
||||
* can act on: another tab of the same browser moved first. Surfacing that as a
|
||||
* failed toast would make the switcher look broken while nothing was wrong. So
|
||||
* a 409 reconciles through a network-only `/api/auth/me` — which re-adopts the
|
||||
* true epoch — and retries exactly once. A SECOND 409 means the browser is
|
||||
* genuinely racing itself faster than it can settle, and that does surface,
|
||||
* because retrying forever would spin rather than tell anybody.
|
||||
*/
|
||||
async function postSwitchWithReconcile(
|
||||
accountId: string | null,
|
||||
): Promise<SwitchResponse> {
|
||||
try {
|
||||
return await postSwitch(accountId);
|
||||
} catch (error) {
|
||||
if (!isRecordSessionChanged(error)) throw error;
|
||||
await fetchMe();
|
||||
return postSwitch(accountId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -148,7 +211,7 @@ export function useAccountSwitch() {
|
||||
void queryClient.cancelQueries();
|
||||
queryClient.clear();
|
||||
try {
|
||||
await postSwitch(accountId);
|
||||
await postSwitchWithReconcile(accountId);
|
||||
} catch (error) {
|
||||
// A client error cannot prove that the server left the session alone:
|
||||
// its response may have been lost after the server committed. Keep all
|
||||
@@ -227,7 +290,7 @@ export function useLeaveSharedRecordOnGrantLoss() {
|
||||
void queryClient.cancelQueries();
|
||||
queryClient.clear();
|
||||
try {
|
||||
await postSwitch(null);
|
||||
await postSwitchWithReconcile(null);
|
||||
commitRecordSessionTransition(transitionId, null);
|
||||
} catch {
|
||||
// The grant-loss path deliberately still reloads, but it cannot claim
|
||||
|
||||
@@ -10,6 +10,7 @@ import { useRouter } from "next/navigation";
|
||||
import { toast } from "sonner";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { apiGet, apiFetchRaw, ApiError } from "@/lib/api/api-fetch";
|
||||
import { adoptRecordFenceState } from "@/lib/api/record-fence";
|
||||
import { retryOnceOnTransientError } from "@/lib/queries/retry-transient";
|
||||
import { useMounted } from "@/hooks/use-mounted";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
@@ -332,6 +333,13 @@ export async function fetchMe(): Promise<AuthUser> {
|
||||
// whatever the switch flow stamped before its reload, the block is what the
|
||||
// resolver will actually honour on the next request, so the mirror tracks it
|
||||
// rather than the client's memory of what it asked for.
|
||||
// v1.37.0 — adopt the record-session context BEFORE anything releases a
|
||||
// hold. `/api/auth/me` is one of exactly two responses a client may learn
|
||||
// its context from, and a hold released onto an unadopted context would put
|
||||
// the shell back on screen with every subsequent request still asserting
|
||||
// `bootstrap`. Adoption first means a released hold is always released onto
|
||||
// a context the next request can prove.
|
||||
adoptRecordFenceState(data.recordSession);
|
||||
const { accountAccess, status: accountAccessStatus } =
|
||||
resolveAccountAccess(data);
|
||||
if (accountAccessStatus === "invalid") {
|
||||
|
||||
Reference in new issue
Block a user