diff --git a/specs/product/GLOSSARY.md b/specs/product/GLOSSARY.md
index e3503357f..d50c4c999 100644
--- a/specs/product/GLOSSARY.md
+++ b/specs/product/GLOSSARY.md
@@ -1380,6 +1380,48 @@ out of scope here (personal-data erasure is #272). Break-glass recovery
would not restore access, because a disabled user is turned away before the
password is ever checked; re-enable them first.
+**Two-factor authentication (#1277)** — signing in with the password and a
+second proof from a phone: an **authenticator code**, or a **recovery code**
+without the phone. Any user turns it on from **Account** → **Security** →
+**Set up**, after confirming it's them with their password (see **Step-up
+authentication**). The set-up screen shows a QR code, the set-up key as text
+and, on a phone, a link that opens the authenticator app. It warns that the
+user's other devices and connected apps will need to sign in again, and
+confirming a code from the app turns it on, ends every other session and
+connected app, keeps this device signed in, and shows the ten recovery codes
+once. A wrong code shows the tries left, except one that is not six digits,
+which is refused without a count; the fifth wrong code, or a set-up older
+than 10 minutes, ends the set-up and the user starts again. **Replace
+authenticator app** (for a new phone) runs the same set-up after a step-up with
+the password and a code; the old app keeps working until the new one's code is
+confirmed. Turning it on and replacing the app are audited
+(`User.TwoFactorEnabled`).
+
+**Authenticator app (#1277)** — the phone app that shows a new 6-digit code
+every 30 seconds for each account added to it. Cluckwork appears in it as
+"Cluckwork (farm name)" with the user's email.
+
+**Authenticator code (#1277)** — the 6-digit code from the **authenticator app**.
+Not "verification code", and never shortened to "code" where the **farm code**
+is also on screen. Each one works once.
+
+**Recovery code (#1277)** — one of ten single-use codes, shown once when
+two-factor authentication is turned on, for signing in or confirming it's you
+without the phone. Each is 16 letters and digits, shown as
+`XXXX-XXXX-XXXX-XXXX`, and is accepted with or without the hyphens. The **Security** section shows how many are left
+and, from 2 or fewer, warns. **Regenerate** (password and a code) replaces the
+whole set and shows the new one once; the old codes stop working. It is audited
+(`User.RecoveryCodesRegenerated`). Using one is audited too
+(`User.RecoveryCodeUsed`).
+
+**Turn off two-factor authentication (#1277)** — a user removes their own
+second factor from **Account** → **Security** → **Turn off**, after a step-up
+with the password and a code. Their authenticator app and recovery codes stop
+working, every other session and connected app ends, this device stays signed
+in, and the next sign-in asks for the password only. It is audited
+(`User.TwoFactorDisabled`). Removing another user's is **Reset two-factor
+authentication**.
+
**Reset two-factor authentication (#1280)** — an Owner, or `recover-admin`,
removes another user's second factor so they can enrol again, for example after
they lose their phone or their recovery codes. On the Users screen the selected
@@ -1500,9 +1542,9 @@ epoch** (see above) in that same transaction, and every authenticated request
is checked against it — so an already-issued access token is rejected on its
very next request, not merely bounded by the ~15-min access-token lifetime.
-**Step-up authentication (#308, #360, #606)** — a fresh proof of identity
-required, on top of a normal valid Owner access token, before nine categories
-of action: **creating any user**, **resetting any user's password**,
+**Step-up authentication (#308, #360, #606, #1277)** — a fresh proof of identity
+required on top of a valid access token. An Owner gives it before these
+Users-screen actions: **creating any user**, **resetting any user's password**,
**changing any user's role** (#355), **changing a login email**, **disabling a
user**, **re-enabling a user** (#356), **assigning a worker to a flock**,
**removing a worker's flock assignment** (#606), or **resetting a user's
@@ -1538,6 +1580,10 @@ beside the password and cleared with it. The password alone is refused, and that
refusal counts no failed attempt. Each code works for one action only, so a
second gated action straight after waits for the authenticator app's next code.
A user without two-factor authentication steps up with the password, as before.
+Any user steps up on the **Account** screen's **Security** section too (#1277):
+**Set up** asks for the password, because the user has no second factor yet, and
+**Replace authenticator app**, **Regenerate** and **Turn off** ask for the
+password and a code.
WebAuthn step-up remains a deferred follow-up (#320).
**Connecting an app (#798)** — approving an outside app, such as an AI assistant,
diff --git a/web/package-lock.json b/web/package-lock.json
index 2d7c802d6..ea8ba25cb 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -19,6 +19,7 @@
"react-dom": "^19.3.1",
"react-i18next": "^17.1.11",
"react-router": "^8.5.1",
+ "uqr": "^0.1.3",
"workbox-expiration": "^7.4.1"
},
"devDependencies": {
@@ -7996,6 +7997,12 @@
"browserslist": ">= 4.21.0"
}
},
+ "node_modules/uqr": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/uqr/-/uqr-0.1.3.tgz",
+ "integrity": "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==",
+ "license": "MIT"
+ },
"node_modules/use-sync-external-store": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
diff --git a/web/package.json b/web/package.json
index 1dcabf99f..9e0348df9 100644
--- a/web/package.json
+++ b/web/package.json
@@ -28,6 +28,7 @@
"react-dom": "^19.3.1",
"react-i18next": "^17.1.11",
"react-router": "^8.5.1",
+ "uqr": "^0.1.3",
"workbox-expiration": "^7.4.1"
},
"devDependencies": {
diff --git a/web/src/App.recoveryCodes.test.tsx b/web/src/App.recoveryCodes.test.tsx
new file mode 100644
index 000000000..4a9b1be2d
--- /dev/null
+++ b/web/src/App.recoveryCodes.test.tsx
@@ -0,0 +1,119 @@
+import type { ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { App } from "./App";
+import { getTwoFactorStatus, listMyConnectedApps, regenerateRecoveryCodes } from "./api/cluckwork";
+import { stepUp } from "./api/client";
+import { askConsent } from "./api/oauth";
+import { clearAccessToken } from "./auth/tokenStore";
+import { setStoredToken } from "./test/jwt";
+import { freshCode } from "./test/codes";
+import i18n from "./i18n";
+
+// #1277 — App.tsx places the slot above the router and the shell: codes held
+// there survive route changes inside the shell and a route outside it
+// (/connect). SessionProvider is stubbed, so this proves the
+// slot's place in App's tree, not the session bootstrap.
+vi.mock("./session/SessionContext", async (importOriginal) => ({
+ ...await importOriginal(),
+ SessionProvider: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock("./pwa/UpdatePrompt", () => ({ UpdatePrompt: () => null }));
+// The Connect page asks the server about a consent; here it waits forever, so
+// the page is on screen, loading, whenever its lazy chunk has arrived.
+vi.mock("./api/oauth", async (importOriginal) => ({
+ ...await importOriginal(),
+ askConsent: vi.fn(() => new Promise(() => undefined)),
+}));
+vi.mock("./api/cluckwork", async (importOriginal) => ({
+ ...await importOriginal(),
+ getTwoFactorStatus: vi.fn(),
+ regenerateRecoveryCodes: vi.fn(),
+ listMyConnectedApps: vi.fn(),
+}));
+vi.mock("./api/client", async (importOriginal) => ({
+ ...await importOriginal(),
+ stepUp: vi.fn(),
+}));
+
+const t = (key: string): string => i18n.t(`account:${key}` as "account:heading");
+
+beforeEach(() => {
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 1 });
+ vi.mocked(listMyConnectedApps).mockResolvedValue([]);
+ vi.mocked(stepUp).mockResolvedValue({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" });
+ setStoredToken({ sub: "u1", role: "Worker", two_factor: "true" });
+ // The one request this tree makes that the mocks above do not answer; any
+ // other is a failure, not a silent empty answer.
+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
+ if (String(input) === "/api/v1/egg-unit-conversions")
+ return new Response("[]", { status: 200, headers: { "Content-Type": "application/json" } });
+ throw new Error(`Unexpected fetch: ${String(input)}`);
+ }));
+ window.history.replaceState(null, "", "/");
+ window.history.pushState(null, "", "/account");
+});
+
+afterEach(() => {
+ clearAccessToken();
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+});
+
+async function holdRegeneratedCodes() {
+ const codes = Array.from({ length: 10 }, () => crypto.randomUUID().slice(0, 19));
+ vi.mocked(regenerateRecoveryCodes).mockResolvedValue({ recoveryCodes: codes });
+ render();
+ const regenerate = await screen.findByRole("button", { name: t("regenerateButton") }, { timeout: 5000 });
+ await act(async () => { fireEvent.click(regenerate); });
+ const proof = screen.getByRole("dialog");
+ fireEvent.change(within(proof).getByLabelText(/Your current password/), { target: { value: crypto.randomUUID() } });
+ fireEvent.change(within(proof).getByLabelText(/Authenticator or recovery code/), { target: { value: freshCode() } });
+ await act(async () => { fireEvent.click(within(proof).getByRole("button", { name: t("regenerateButton") })); });
+ await screen.findByRole("dialog", { name: t("codesHeading") });
+ return codes;
+}
+
+const shownCodes = () =>
+ within(screen.getByRole("dialog", { name: t("codesHeading") })).getAllByRole("listitem").map((li) => li.textContent);
+
+const onlyExpectedFetches = () => {
+ expect(vi.mocked(fetch).mock.calls.length).toBeGreaterThan(0);
+ expect(vi.mocked(fetch).mock.calls.map(([input]) => String(input)).filter((url) => url !== "/api/v1/egg-unit-conversions")).toEqual([]);
+};
+
+describe("the app's own provider tree", () => {
+ it("keeps unsaved recovery codes on screen through two route changes", async () => {
+ const codes = await holdRegeneratedCodes();
+
+ const rail = screen.getByRole("navigation", { name: i18n.t("nav:primaryNavAriaLabel"), hidden: true });
+ await act(async () => { fireEvent.click(rail.querySelector('a[href="/help"]')!); });
+ await waitFor(() => expect(window.location.pathname).toBe("/help"));
+ await act(async () => { window.history.back(); });
+ await waitFor(() => expect(window.location.pathname).toBe("/account"));
+
+ expect(shownCodes()).toEqual(codes);
+ onlyExpectedFetches();
+ }, 20_000);
+
+ it("keeps them on a route outside the shell, and back", async () => {
+ const codes = await holdRegeneratedCodes();
+
+ await act(async () => {
+ window.history.pushState({ key: crypto.randomUUID() }, "", "/connect");
+ window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
+ });
+ await waitFor(() => expect(window.location.pathname).toBe("/connect"));
+ // The Connect page itself, not only the route: the shell is gone and the
+ // page is waiting on its consent request.
+ await screen.findByText(i18n.t("connect:loading"), undefined, { timeout: 5000 });
+ await waitFor(() => expect(askConsent).toHaveBeenCalled());
+ expect(screen.queryByRole("navigation", { name: i18n.t("nav:primaryNavAriaLabel"), hidden: true })).toBeNull();
+ expect(shownCodes()).toEqual(codes);
+ await act(async () => { window.history.back(); });
+ await waitFor(() => expect(window.location.pathname).toBe("/account"));
+
+ expect(shownCodes()).toEqual(codes);
+ onlyExpectedFetches();
+ }, 20_000);
+});
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 4263c7b86..9078874dc 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -8,6 +8,7 @@ import { SessionProvider } from "./session/SessionContext";
import { ProtectedRoute } from "./routes/ProtectedRoute";
import { AppLayout } from "./routes/AppLayout";
import { Login } from "./routes/Login";
+import { RecoveryCodesProvider } from "./routes/account/recoveryCodes";
// Under , navigate() returns nothing; only a data router
// () returns a Promise. React Router types the union and
@@ -58,6 +59,9 @@ export function App() {
applied from this device's cache before anyone signs in (#586). */}
+ {/* #1277 — above every route, so no navigation drops recovery
+ codes that are not saved yet; it clears when the session ends. */}
+ } />
@@ -99,6 +103,7 @@ export function App() {
} />
+
{/* Outside the router and the auth gate: an update is worth offering on
diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts
index 8b5ecc5f4..b0418dd75 100644
--- a/web/src/api/client.test.ts
+++ b/web/src/api/client.test.ts
@@ -199,6 +199,65 @@ describe("apiFetch — no in-memory token", () => {
});
});
+// #1277 — after a 401 and a successful refresh, the resend answers for the
+// request itself: its refusal, a 5xx or a network error is the caller's to
+// show. Only a 401 to the fresh token ends the session.
+describe.each(["json", "blob"] as const)("the %s resend after a successful refresh", (kind) => {
+ const send = () => kind === "json" ? apiPost("/thing", { value: 42 }) : apiGetBlob("/thing");
+ const afterRefresh = (resend: Response | Error) => {
+ const refreshed = claimfulToken("at2-resend");
+ fetchMock.mockResolvedValueOnce(jsonResponse({ title: "Original401" }, 401))
+ .mockResolvedValueOnce(accessResponse(refreshed));
+ if (resend instanceof Error) fetchMock.mockRejectedValueOnce(resend);
+ else fetchMock.mockResolvedValueOnce(resend);
+ return refreshed;
+ };
+
+ it.each([400, 403, 409, 429, 500, 503])("returns a %i as itself, sent once, and keeps the session", async (status) => {
+ const refreshed = afterRefresh(jsonResponse({ title: "Thing.Refused", attemptsLeft: 3 }, status));
+
+ const error = await send().catch((err: unknown) => err);
+
+ expect(error).toMatchObject({ status, title: "Thing.Refused", extensions: { attemptsLeft: 3 } });
+ expect(onUnauth).not.toHaveBeenCalled();
+ expect(getAccessToken()).toBe(refreshed);
+ expect(callsTo(fetchMock, "/auth/refresh")).toHaveLength(1);
+ expect(callsTo(fetchMock, "/thing")).toHaveLength(2);
+ });
+
+ it("returns a network error as itself and keeps the session", async () => {
+ const offline = new TypeError("offline");
+ const refreshed = afterRefresh(offline);
+
+ await expect(send()).rejects.toBe(offline);
+
+ expect(onUnauth).not.toHaveBeenCalled();
+ expect(getAccessToken()).toBe(refreshed);
+ expect(callsTo(fetchMock, "/thing")).toHaveLength(2);
+ });
+
+ it("ends the session once on a 401 to the fresh token, with the original 401", async () => {
+ afterRefresh(jsonResponse({ title: "Fresh401" }, 401));
+
+ await expect(send()).rejects.toMatchObject({ status: 401, title: "Original401" });
+
+ expect(onUnauth).toHaveBeenCalledExactlyOnceWith("Original401");
+ expect(getAccessToken()).toBeNull();
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ it("returns a 200 once", async () => {
+ afterRefresh(kind === "json" ? jsonResponse({ value: 42 }) : new Response("export"));
+
+ const answer = await send();
+
+ if (kind === "json") expect(answer).toEqual({ value: 42 });
+ else expect(answer).toHaveProperty("blob");
+ expect(onUnauth).not.toHaveBeenCalled();
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+});
+
describe("apiFetch — unrecoverable session reason", () => {
it("passes the original protected-request 401 title to auth teardown after refresh fails", async () => {
fetchMock
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index 2801b8347..4df270086 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -1,12 +1,6 @@
-// #308/#360/#606 — carries a short-lived step-up grant (see stepUp() in
-// ./session) on the user-administration calls that require recent proof (every user
-// creation, every administrative password reset, every role change,
-// login-email change, disable/re-enable, and every flock assign/unassign).
-// Mirrors AuthEndpoints.StepUpHeaderName.
-export const STEP_UP_HEADER = "X-Cluckwork-Step-Up";
-
+export { STEP_UP_HEADER } from "./request";
export { apiGet, apiPost, apiPut, apiPutBytes, apiDelete, apiGetBlob, apiFetch, restoreSession } from "./refresh";
-export { login, completeSecondFactor, changePassword, stepUp, logout, NO_PROOF } from "./session";
+export { login, completeSecondFactor, changePassword, confirmTwoFactor, turnOffTwoFactor, stepUp, logout, NO_PROOF, currentSessionGeneration, isSignedOut } from "./session";
export type { LoginOutcome, StepUpProof } from "./session";
export { setOnUnauthenticated, setOnTokensChanged } from "./sessionState";
export { getLastTraceId } from "./trace";
diff --git a/web/src/api/cluckwork.ts b/web/src/api/cluckwork.ts
index 8624055db..f0acabaa2 100644
--- a/web/src/api/cluckwork.ts
+++ b/web/src/api/cluckwork.ts
@@ -15,3 +15,4 @@ export * from "./cluckwork/catalog";
export * from "./cluckwork/exports";
export * from "./cluckwork/reports";
export * from "./cluckwork/expenses";
+export * from "./cluckwork/twoFactor";
diff --git a/web/src/api/cluckwork/twoFactor.ts b/web/src/api/cluckwork/twoFactor.ts
new file mode 100644
index 000000000..8e6cc3438
--- /dev/null
+++ b/web/src/api/cluckwork/twoFactor.ts
@@ -0,0 +1,28 @@
+import { apiGet, apiPost, STEP_UP_HEADER } from "../client";
+
+// #1277 — the signed-in user's own two-factor authentication. Confirm and
+// turn-off rotate the session, so they live with the token writers in
+// api/session.ts.
+
+export interface TwoFactorStatus {
+ enabled: boolean;
+ recoveryCodesLeft: number;
+}
+
+// The key and the URI are credentials: the enrolment screen shows them and
+// keeps them nowhere else.
+export interface EnrolmentStart {
+ key: string;
+ otpauthUri: string;
+}
+
+export const getTwoFactorStatus = (signal?: AbortSignal) => apiGet("/auth/two-factor", signal);
+
+// apiPost sends a fresh Idempotency-Key: the server keeps no response for
+// these routes, so a reused key would replay nothing.
+export const startTwoFactor = (stepUpToken: string) =>
+ apiPost("/auth/two-factor/start", undefined, undefined, { [STEP_UP_HEADER]: stepUpToken });
+
+// Optional on the type as on the wire: the caller must check a 200 for it.
+export const regenerateRecoveryCodes = (stepUpToken: string) =>
+ apiPost<{ recoveryCodes?: string[] }>("/auth/two-factor/recovery-codes", undefined, undefined, { [STEP_UP_HEADER]: stepUpToken });
diff --git a/web/src/api/refresh.ts b/web/src/api/refresh.ts
index f8791e1e4..c6187538a 100644
--- a/web/src/api/refresh.ts
+++ b/web/src/api/refresh.ts
@@ -5,7 +5,7 @@ import { raw, CSRF_HEADER, ACCOUNT_HEADER } from "./request";
import { ApiError } from "./errors";
import { StaleSessionError, revokeSupersededCookie, onUnauthenticated, onTokensChanged } from "./sessionState";
import { withAuthCookieLock, REFRESH_TIMEOUT_MS } from "./authCookieLock";
-import { sessionGeneration, settledLogin } from "./session";
+import { isSignedOut, sessionGeneration, settledLogin } from "./session";
import { newId } from "../lib/ids";
import { rawBlob } from "./request";
import type { HeldAuthCookieLock } from "./authCookieLock";
@@ -38,6 +38,10 @@ class RefreshAdoptionRefusedError extends Error {
}
async function executeRefresh(generation: number, signal?: AbortSignal): Promise {
+ // #1277 — checked where every refresh sends, so one queued behind the
+ // cross-tab lock, the bootstrap and a download refuse alike. Its callers
+ // treat this as a superseded session: no teardown.
+ if (isSignedOut()) throw new StaleSessionError();
try {
// #547/#532 — tell the server which per-farm cookie THIS tab expects.
// Unbound tabs (the load-time bootstrap) omit it; the server accepts one
@@ -137,9 +141,7 @@ async function executeRefresh(generation: number, signal?: AbortSignal): Promise
// closed instead.
if (err instanceof ApiError && err.status === 401
&& (err.title === SESSION_CHANGED_TITLE || err.title === FARM_SELECTION_REQUIRED_TITLE)) {
- clearAccessToken();
- onUnauthenticated?.(err.title);
- throw err;
+ endSession(err);
}
if (err instanceof RefreshAdoptionRefusedError) {
// #547/#532 — do NOT revoke here. This refusal means the browser's
@@ -183,6 +185,8 @@ export async function refreshTokens(heldLock?: HeldAuthCookieLock): Promise(
export async function apiGetBlob(
path: string,
): Promise<{ blob: Blob; filename: string | null }> {
- const token = await currentAccessToken();
- try {
- return await rawBlob(path, token);
- } catch (err) {
- if (!(err instanceof ApiError) || err.status !== 401) throw err;
- try {
- const refreshed = await refreshTokens();
- return await rawBlob(path, refreshed);
- } catch (refreshErr) {
- // #310 review — same supersession handling as apiFetch.
- if (refreshErr instanceof StaleSessionError) {
- // #438 — as in apiFetch: await the queued login before concluding
- // there is no session to download on.
- await settledLogin();
- const fresh = getAccessToken();
- if (fresh) return await rawBlob(path, fresh);
- throw err;
- }
- if (isTransientRefreshFailure(refreshErr)) throw refreshErr;
- clearAccessToken();
- onUnauthenticated?.(err.title);
- throw err;
- }
- }
+ return sendWithRefresh((token) => rawBlob(path, token), await currentAccessToken());
}
+// #1277 — a two-factor write that answers 401 Auth.CredentialsSuperseded found
+// the session stale under the user-row lock, after it may have spent its
+// step-up grant. Resending it on a refreshed session would act on a security
+// state the user never confirmed, so the refusal goes back to the dialog.
+const isUnresendable = (path: string, init: RequestInit, err: ApiError) =>
+ path.startsWith("/auth/two-factor") && (init.method ?? "GET") !== "GET"
+ && err.title === "Auth.CredentialsSuperseded";
+
export async function apiFetch(
path: string,
init: RequestInit = {},
@@ -336,37 +325,65 @@ export async function apiFetch(
// stale form borrow the newer session's bearer for its first request.
if (heldAuthCookieLock && sessionGeneration !== heldAuthCookieLock.generation)
throw new StaleSessionError();
+ return sendWithRefresh((bearer) => raw(path, init, bearer), token, {
+ held: heldAuthCookieLock,
+ unresendable: (err) => isUnresendable(path, init, err),
+ });
+}
+
+// Clears this tab's session, tells the app why, and rethrows the 401 that
+// showed it was over.
+function endSession(err: ApiError): never {
+ clearAccessToken();
+ onUnauthenticated?.(err.title);
+ throw err;
+}
+
+// One request with one transparent refresh-and-retry, for apiFetch and
+// apiGetBlob alike.
+async function sendWithRefresh(
+ send: (token: string) => Promise,
+ token: string,
+ { held, unresendable = () => false }: { held?: HeldAuthCookieLock; unresendable?: (err: ApiError) => boolean } = {},
+): Promise {
+ // A held context identifies the non-replayable password form. Generic API
+ // requests may continue on a newer login after supersession; this one must
+ // not refresh that newer cookie or resend the old password body against it.
+ const superseded = () => held !== undefined && sessionGeneration !== held.generation;
try {
- return await raw(path, init, token);
+ return await send(token);
} catch (err) {
- if (!(err instanceof ApiError) || err.status !== 401) throw err;
- // A held context identifies the non-replayable password form. Generic API
- // requests may continue on a newer login after supersession; this one must
- // not refresh that newer cookie or resend the old password body against it.
- if (heldAuthCookieLock && sessionGeneration !== heldAuthCookieLock.generation)
- throw new StaleSessionError();
+ if (!(err instanceof ApiError) || err.status !== 401 || unresendable(err)) throw err;
+ if (superseded()) throw new StaleSessionError();
+ let refreshed: string;
try {
- const refreshed = await refreshTokens(heldAuthCookieLock);
- if (heldAuthCookieLock && sessionGeneration !== heldAuthCookieLock.generation)
- throw new StaleSessionError();
- return await raw(path, init, refreshed);
+ refreshed = await refreshTokens(held);
+ if (superseded()) throw new StaleSessionError();
} catch (refreshErr) {
// #310 review — superseded mid-retry: retry once on the newer login's
// token, or surface the ORIGINAL 401 if a logout ended the session.
// Never let the internal marker reach the caller.
if (refreshErr instanceof StaleSessionError) {
- if (heldAuthCookieLock) throw refreshErr;
+ if (held) throw refreshErr;
// #438 — same wait as supersededToken: the login that superseded this
// refresh can still be queued behind it.
await settledLogin();
const fresh = getAccessToken();
- if (fresh) return await raw(path, init, fresh);
+ if (fresh) return await send(fresh);
throw err;
}
if (isTransientRefreshFailure(refreshErr)) throw refreshErr;
- clearAccessToken();
- onUnauthenticated?.(err.title);
- throw err;
+ endSession(err);
+ }
+ // #1277 — the refresh worked, so the resend answers for the request
+ // itself: a 4xx, a 5xx or a network error is the caller's to show. Only a
+ // 401 to a fresh token means the session is dead, and then the original
+ // 401 surfaces.
+ try {
+ return await send(refreshed);
+ } catch (resendErr) {
+ if (!(resendErr instanceof ApiError) || resendErr.status !== 401) throw resendErr;
+ endSession(err);
}
}
}
diff --git a/web/src/api/request.ts b/web/src/api/request.ts
index 14200dfb2..c8cf58852 100644
--- a/web/src/api/request.ts
+++ b/web/src/api/request.ts
@@ -15,6 +15,13 @@ export const CSRF_HEADER = "X-Cluckwork-Auth";
// session, see executeRefresh).
export const ACCOUNT_HEADER = "X-Cluckwork-Account";
+// #308/#360/#606 — carries a short-lived step-up grant (see stepUp() in
+// ./session) on the user-administration calls that require recent proof (every user
+// creation, every administrative password reset, every role change,
+// login-email change, disable/re-enable, and every flock assign/unassign).
+// Mirrors AuthEndpoints.StepUpHeaderName.
+export const STEP_UP_HEADER = "X-Cluckwork-Step-Up";
+
export async function raw(
path: string,
init: RequestInit,
diff --git a/web/src/api/session.ts b/web/src/api/session.ts
index cb74fae93..2d8bc7503 100644
--- a/web/src/api/session.ts
+++ b/web/src/api/session.ts
@@ -8,7 +8,7 @@ import { clearAccessToken, getAccessToken, setAccessToken, bindAccount, clearBou
import { accountIdFromToken } from "../auth/claims";
import { newId } from "../lib/ids";
import type { AccessTokenResponse, LoginRequest } from "./types";
-import { raw, CSRF_HEADER, ACCOUNT_HEADER } from "./request";
+import { raw, CSRF_HEADER, ACCOUNT_HEADER, STEP_UP_HEADER } from "./request";
import { ApiError } from "./errors";
import { StaleSessionError, revokeSupersededCookie, onTokensChanged } from "./sessionState";
import { withAuthCookieLock, REFRESH_TIMEOUT_MS, abortInFlightAuthCookieOperation } from "./authCookieLock";
@@ -28,6 +28,10 @@ import { apiFetch, apiPost, refreshInFlight } from "./refresh";
// clobbering whatever the (newer) generation already did.
export let sessionGeneration = 0;
+// #1277 — read through a call, so a module spread (a test's partial mock)
+// still sees the live value.
+export const currentSessionGeneration = () => sessionGeneration;
+
// #438 — the settlement handle of the login currently in flight, or null. A
// request parked on a refresh that came back superseded cannot simply peek at
// the token store any more: since login joins the cross-tab cookie lock below,
@@ -211,6 +215,7 @@ async function performLogin(path: string, body: unknown, generation: number): Pr
await revokeSupersededCookie(res.accessToken);
throw new StaleSessionError();
}
+ signOutIntent = false;
setAccessToken(res.accessToken);
// #532 — a tab that logged in must be bound to its farm before its first
// refresh, or that refresh is treated as a cold restore and could adopt a
@@ -259,35 +264,68 @@ const withCode = (body: T, code: string | undefined): T & { co
export async function changePassword(
{ code, ...passwords }: { currentPassword: string; newPassword: string; code?: string },
): Promise {
- const body = withCode(passwords, code);
+ await noteCode(adoptingWrite("/auth/change-password", {
+ method: "POST",
+ headers: { "Idempotency-Key": newId() },
+ body: JSON.stringify(withCode(passwords, code)),
+ }), code);
+}
+
+// #1277 — confirming an enrolment ends every other session and hands this one
+// a fresh pair, as change-password does. A first enrolment's answer also holds
+// the recovery codes, which the caller shows once and keeps nowhere else.
+// The server keeps no response for any two-factor route (ResponseNotCacheable),
+// so the key each write must carry is a fresh one, as change-password's is.
+export function confirmTwoFactor(code: string): Promise<{ recoveryCodes?: string[] }> {
+ return adoptingWrite("/auth/two-factor/confirm", {
+ method: "POST",
+ headers: { "Idempotency-Key": newId() },
+ body: JSON.stringify({ code }),
+ }).then((res) => ({ recoveryCodes: res.recoveryCodes }));
+}
+
+// #1280 — 200 with a fresh pair when two-factor was on, 204 when it was not.
+export async function turnOffTwoFactor(stepUpToken: string): Promise {
+ await adoptingWrite("/auth/two-factor", {
+ method: "DELETE",
+ headers: { "Idempotency-Key": newId(), [STEP_UP_HEADER]: stepUpToken },
+ }, { noContent: true });
+}
+
+// A write whose answer rotates this farm's refresh cookie and hands this tab a
+// fresh pair. Only turn-off may answer 204, which rotates nothing; from the
+// others a 204 is a broken answer and throws.
+function adoptingWrite(path: string, init: RequestInit): Promise;
+function adoptingWrite(path: string, init: RequestInit, options: { noContent: true }): Promise;
+async function adoptingWrite(
+ path: string, init: RequestInit, { noContent = false }: { noContent?: boolean } = {},
+): Promise {
// #310 — this is a token-store writer like login/refresh, so it needs the
// same generation guard: logout is reachable from every screen (AppLayout's
- // persistent button), so a user who submits a password change and logs out
- // before it lands would otherwise have the response write a fresh token back
- // over the cleared session.
+ // persistent button), so a user who submits and logs out before the answer
+ // lands would otherwise have the response write a fresh token back over the
+ // cleared session.
const generation = sessionGeneration;
- // Refresh and password-change both replace this farm's HttpOnly cookie.
- // Keep the password change inside the same cross-tab lock as refresh,
- // or an already-started old-epoch refresh can answer last and overwrite the
- // E+1 cookie this request just issued. Passing the held lock context lets
- // apiFetch do its normal 401 refresh-and-retry inside this lock without
- // trying to acquire the non-reentrant Web Lock a second time.
- const res = await noteCode(withAuthCookieLock((signal) => {
+ // Refresh and these writes all replace this farm's HttpOnly cookie. Keep the
+ // write inside the same cross-tab lock as refresh, or an already-started
+ // old-epoch refresh can answer last and overwrite the E+1 cookie this request
+ // just issued. Passing the held lock context lets apiFetch do its normal 401
+ // refresh-and-retry inside this lock without trying to acquire the
+ // non-reentrant Web Lock a second time.
+ const res = await withAuthCookieLock((signal) => {
// The operation may have waited behind another tab's refresh. Logout or a
// newer login that happened while queued wins before this request sends a
- // byte; never let the stale password form act on the superseding session.
+ // byte; never let the stale form act on the superseding session.
if (sessionGeneration !== generation) throw new StaleSessionError();
- return apiFetch(
- "/auth/change-password",
- {
- method: "POST",
- headers: { "Idempotency-Key": newId() },
- body: JSON.stringify(body),
- signal,
- },
- { generation, signal },
- );
- }), code);
+ return apiFetch(path, { ...init, signal }, { generation, signal });
+ });
+ if (res === undefined) {
+ if (!noContent) throw new Error(`${path} answered 204 instead of a fresh pair.`);
+ // No cookie to revoke, but a session that ended meanwhile is not told the
+ // write happened, as the 200 path below does not tell it either.
+ if (sessionGeneration !== generation) throw new StaleSessionError();
+ return undefined;
+ }
// This response rotates the refresh cookie too, so a discarded one needs that
// cookie revoked, not merely the in-memory token dropped.
if (sessionGeneration !== generation) {
@@ -295,13 +333,14 @@ export async function changePassword(
throw new StaleSessionError();
}
setAccessToken(res.accessToken);
- // #532 — changePassword adopts a token (the server hands this device a fresh
+ // #532 — the write adopts a token (the server hands this device a fresh
// pair after revoking every other session), so like login it must bind the
// tab to its farm. Without this, the tab's next refresh would omit
// X-Cluckwork-Account and fall into the bootstrap path instead of naming
// the farm it just authenticated.
bindAccount(accountIdFromToken(res.accessToken));
onTokensChanged?.();
+ return res;
}
// #308/#360/#606 — re-confirms the CURRENT password to mint a short-lived
@@ -333,17 +372,31 @@ export async function stepUp(proof: StepUpProof): Promise<{ token: string; expir
return noteCode(apiPost<{ token: string; expiresAt: string }>("/auth/step-up", body), proof.code);
}
+// #1277 — set by logout(), and cleared only where a login's own answer
+// commits its tokens. Until then this tab is signed out: no refresh sends, so
+// no new token is issued, and the recovery-codes slot starts no code-issuing
+// work. A request that already holds a bearer still sends with
+// it. A generation bump is not a sign-in: a login abandoned at its deadline,
+// or superseded, leaves the tab signed out, and so does a failed revoke.
+let signOutIntent = false;
+export const isSignedOut = () => signOutIntent;
+
+// A test that signs out must not leave the next test signed out: tests seed
+// tokens directly instead of signing in, which would end the refusal.
+export function resetSignOutForTests(): void {
+ signOutIntent = false;
+}
+
export async function logout(): Promise {
// #310 — bump the generation and clear in-memory state SYNCHRONOUSLY, before
// any await: local logout must win immediately, whatever a slower in-flight
// login/refresh does later. Also cancel any refresh currently in flight —
// note this only reaches a refresh that has already been GRANTED the
// cross-tab lock (#169); one still queued behind another tab has no
- // controller yet, so it will still fire its request and then be discarded on
- // arrival by the generation check. Correctness rests on the generation, not
- // on the abort; the abort is only an optimisation so it stops sooner
- // instead of only being
- // discarded on arrival by the generation check in refreshTokens().
+ // controller yet, and the sign-out intent refuses it before it sends.
+ // Correctness rests on the generation and the intent, not on the abort; the
+ // abort is only an optimisation so it stops sooner.
+ signOutIntent = true;
sessionGeneration++;
abortInFlightAuthCookieOperation?.();
// #336/#532 — capture BEFORE clearing: the bearer identifies the actor and
@@ -356,28 +409,45 @@ export async function logout(): Promise {
// #532 — explicit logout is the user ending the session: the binding is
// cleared with the token, and the next login rebinds.
clearBoundAccount();
- try {
- // Cookie-authenticated: the HttpOnly refresh cookie rides along and the CSRF
- // header satisfies the check. Always fires — JS can't read the HttpOnly
- // cookie to know whether a session exists, so we always ask the server to
- // revoke + clear it.
- //
- // #336/#532 — the bearer records the actor when this tab still has one;
- // the account header selects the same tab's per-farm cookie even after the
- // access token expires. Both remain optional because the endpoint is
- // AllowAnonymous, and it is exempt from the Idempotency-Key requirement.
- const headers: Record = { [CSRF_HEADER]: "1" };
- if (accountId !== null) headers[ACCOUNT_HEADER] = accountId;
- await raw(
- "/auth/logout",
- { method: "POST", headers },
- bearer ?? undefined,
- );
- } catch (err) {
+ // Cookie-authenticated: the HttpOnly refresh cookie rides along and the CSRF
+ // header satisfies the check. Always fires — JS can't read the HttpOnly
+ // cookie to know whether a session exists, so we always ask the server to
+ // revoke + clear it.
+ //
+ // #336/#532 — the bearer records the actor when this tab still has one;
+ // the account header selects the same tab's per-farm cookie even after the
+ // access token expires. Both remain optional because the endpoint is
+ // AllowAnonymous, and it is exempt from the Idempotency-Key requirement.
+ const headers: Record = { [CSRF_HEADER]: "1" };
+ if (accountId !== null) headers[ACCOUNT_HEADER] = accountId;
+ // #1277 — the wait ends at the refresh timeout, and so does the request. Its
+ // late answer would carry a Set-Cookie that deletes this farm's refresh
+ // cookie by name, by then a newer sign-in's; the browser drops an aborted
+ // request's answer. What the server does depends on whether the request got
+ // there, as the backend half of #1277 makes it:
+ // - Once the request reaches the handler, the server finishes the revoke:
+ // Logout runs its writes with CancellationToken.None and skips the
+ // flock-scope read. The browser keeps the revoked cookie, which is marked
+ // as a logout revocation, so reusing it fails quietly instead of tripping
+ // #176's replay rule.
+ // - A request that never arrives revokes nothing. The cookie stays live, and
+ // a reload restores the session.
+ const giveUp = new AbortController();
+ const gaveUp = setTimeout(() => giveUp.abort(), REFRESH_TIMEOUT_MS);
+ await raw("/auth/logout", { method: "POST", headers, signal: giveUp.signal }, bearer ?? undefined).catch((err: unknown) => {
+ // Only this tab's own abort is a give-up: fetch rejects with the signal's
+ // reason, so identity proves the abort caused this error. A 500 whose body
+ // was still arriving at the deadline is a failure, and so is an abort
+ // from elsewhere.
+ if (err === giveUp.signal.reason) {
+ console.warn("logout: stopped waiting for the server-side revoke");
+ return;
+ }
// Best-effort revoke: the in-memory token is already cleared above and this
// failure can never reverse that. Still surfaced (not silently swallowed,
// #310) so an operator can see the server-side session may be un-revoked —
// logged, never the (already-cleared) token itself.
console.error("logout: server-side session revoke failed", err);
- }
+ });
+ clearTimeout(gaveUp);
}
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
new file mode 100644
index 000000000..1a87911ba
--- /dev/null
+++ b/web/src/api/twoFactor.test.ts
@@ -0,0 +1,576 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { apiGetBlob, changePassword, completeSecondFactor, confirmTwoFactor, currentSessionGeneration, isSignedOut, login, logout, restoreSession, setOnTokensChanged, setOnUnauthenticated, STEP_UP_HEADER, turnOffTwoFactor } from "./client";
+import { refreshTokens } from "./refresh";
+import { REFRESH_TIMEOUT_MS } from "./authCookieLock";
+import { getTwoFactorStatus, regenerateRecoveryCodes, startTwoFactor } from "./cluckwork";
+import { clearAccessToken, clearBoundAccount, getAccessToken, getBoundAccountId, setAccessToken } from "../auth/tokenStore";
+import { freshCode } from "../test/codes";
+import { StaleSessionError } from "./sessionState";
+
+// #1277 — the two-factor routes. Confirm and turn-off hand this tab a fresh
+// pair; every write's stale-session 401 goes back to the caller unsent again.
+const json = (body: unknown, status = 200) =>
+ new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
+const b64url = (s: string) => btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+const token = (accountId: string) =>
+ `hdr.${b64url(JSON.stringify({ sub: crypto.randomUUID(), account_id: accountId, exp: 9999999999 }))}.sig`;
+const pair = (accessToken: string, extra: object = {}) =>
+ json({ accessToken, accessTokenExpiry: "2099-01-01T00:00:00Z", ...extra });
+const superseded = () => json({ title: "Auth.CredentialsSuperseded", detail: "Your credentials changed." }, 401);
+const credentials = () => ({ farmCode: "farm", email: "a@example.test", password: crypto.randomUUID() });
+
+type Call = [string, RequestInit];
+let fetchMock: ReturnType;
+let onTokens: ReturnType void>>;
+let onUnauth: ReturnType void>>;
+const calls = () => fetchMock.mock.calls as Call[];
+const to = (suffix: string) => calls().filter(([url]) => url.endsWith(suffix));
+const header = (call: Call, name: string) => new Headers(call[1].headers).get(name);
+
+beforeEach(() => {
+ fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ onTokens = vi.fn();
+ onUnauth = vi.fn();
+ setOnTokensChanged(onTokens);
+ setOnUnauthenticated(onUnauth);
+ setAccessToken("at1");
+ clearBoundAccount();
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ setOnTokensChanged(null);
+ setOnUnauthenticated(null);
+ clearAccessToken();
+ clearBoundAccount();
+});
+
+describe("confirmTwoFactor", () => {
+ it("sends the code with a key, adopts the fresh pair and returns the codes", async () => {
+ const fresh = token("acct-A");
+ const codes = [crypto.randomUUID(), crypto.randomUUID()];
+ fetchMock.mockResolvedValueOnce(pair(fresh, { recoveryCodes: codes }));
+ const code = freshCode();
+
+ await expect(confirmTwoFactor(code)).resolves.toEqual({ recoveryCodes: codes });
+
+ const [call] = to("/auth/two-factor/confirm");
+ expect(call![1].method).toBe("POST");
+ expect(JSON.parse(String(call![1].body))).toEqual({ code });
+ expect(header(call!, "Idempotency-Key")).toMatch(/^[0-9a-f-]{36}$/);
+ expect(header(call!, "Authorization")).toBe("Bearer at1");
+ expect(getAccessToken()).toBe(fresh);
+ expect(getBoundAccountId()).toBe("acct-A");
+ expect(onTokens).toHaveBeenCalled();
+ });
+
+ it("adopts a replacement's pair, which carries no codes", async () => {
+ const fresh = token("acct-B");
+ fetchMock.mockResolvedValueOnce(pair(fresh));
+
+ await expect(confirmTwoFactor(freshCode())).resolves.toEqual({ recoveryCodes: undefined });
+ expect(getAccessToken()).toBe(fresh);
+ });
+
+ it("keeps attemptsLeft on a wrong code's error", async () => {
+ fetchMock.mockResolvedValueOnce(json({ title: "Auth.EnrolmentCodeIncorrect", attemptsLeft: 3 }, 400));
+
+ await expect(confirmTwoFactor(freshCode()))
+ .rejects.toMatchObject({ status: 400, title: "Auth.EnrolmentCodeIncorrect", extensions: { attemptsLeft: 3 } });
+ expect(getAccessToken()).toBe("at1");
+ });
+});
+
+describe("turnOffTwoFactor", () => {
+ it("sends DELETE with the grant and a key, and adopts the 200's fresh pair", async () => {
+ const fresh = token("acct-C");
+ fetchMock.mockResolvedValueOnce(pair(fresh));
+ const grant = crypto.randomUUID();
+
+ await turnOffTwoFactor(grant);
+
+ const [call] = to("/auth/two-factor");
+ expect(call![1].method).toBe("DELETE");
+ expect(header(call!, STEP_UP_HEADER)).toBe(grant);
+ expect(header(call!, "Idempotency-Key")).toMatch(/^[0-9a-f-]{36}$/);
+ expect(getAccessToken()).toBe(fresh);
+ expect(onTokens).toHaveBeenCalled();
+ });
+
+ it("adopts nothing on a 204", async () => {
+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
+
+ await turnOffTwoFactor(crypto.randomUUID());
+
+ expect(getAccessToken()).toBe("at1");
+ expect(onTokens).not.toHaveBeenCalled();
+ });
+
+ // A 204 rotates nothing, but a session that ended while it was in flight
+ // must not be told its two-factor was turned off.
+ it("does not report a 204 that lands after a logout", async () => {
+ let answer!: (res: Response) => void;
+ fetchMock
+ .mockReturnValueOnce(new Promise((resolve) => { answer = resolve; }))
+ .mockResolvedValue(new Response(null, { status: 204 }));
+
+ const turnOff = turnOffTwoFactor(crypto.randomUUID());
+ await vi.waitFor(() => expect(to("/auth/two-factor")).toHaveLength(1));
+ await logout();
+ answer(new Response(null, { status: 204 }));
+
+ await expect(turnOff).rejects.toBeInstanceOf(StaleSessionError);
+ });
+});
+
+// Only turn-off answers 204. The other two rotate the session on every
+// success, so a 204 from them is a broken answer, not a quiet success.
+describe("a 204 where a fresh pair is due", () => {
+ it.each([
+ ["confirm", () => confirmTwoFactor(freshCode())],
+ ["change-password", () => changePassword({ currentPassword: crypto.randomUUID(), newPassword: crypto.randomUUID() })],
+ ])("from %s is an error", async (_, write) => {
+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
+
+ await expect(write()).rejects.toThrow(/answered 204/);
+ expect(getAccessToken()).toBe("at1");
+ });
+});
+
+// #1280 review — the 401 means the session went stale after the grant was
+// spent. A refresh-and-resend would act on a state the user never confirmed.
+describe("a stale session's 401 Auth.CredentialsSuperseded", () => {
+ const writes: [string, string, () => Promise][] = [
+ ["turn-off", "/auth/two-factor", () => turnOffTwoFactor(crypto.randomUUID())],
+ ["confirm", "/auth/two-factor/confirm", () => confirmTwoFactor(freshCode())],
+ ["start", "/auth/two-factor/start", () => startTwoFactor(crypto.randomUUID())],
+ ["regenerate", "/auth/two-factor/recovery-codes", () => regenerateRecoveryCodes(crypto.randomUUID())],
+ ];
+
+ it.each(writes)("on %s is sent once, with no refresh, and does not end the session", async (_, path, write) => {
+ fetchMock.mockResolvedValueOnce(superseded()).mockResolvedValue(pair(token("acct-D")));
+
+ await expect(write()).rejects.toMatchObject({ status: 401, title: "Auth.CredentialsSuperseded" });
+
+ expect(calls().map(([url]) => url)).toEqual([`/api/v1${path}`]);
+ expect(onUnauth).not.toHaveBeenCalled();
+ expect(getAccessToken()).toBe("at1");
+ });
+
+ it("on the status read still refreshes and retries, like any read", async () => {
+ fetchMock
+ .mockResolvedValueOnce(superseded())
+ .mockResolvedValueOnce(pair(token("acct-E")))
+ .mockResolvedValueOnce(json({ enabled: true, recoveryCodesLeft: 10 }));
+
+ await expect(getTwoFactorStatus()).resolves.toEqual({ enabled: true, recoveryCodesLeft: 10 });
+ expect(to("/auth/refresh")).toHaveLength(1);
+ });
+});
+
+// A plain 401 is an expired token: the write is refreshed and resent once.
+describe("an expired token's plain 401", () => {
+ it("surfaces confirm's wrong code after a refresh, and keeps the session", async () => {
+ const refreshed = token("acct-G");
+ fetchMock
+ .mockResolvedValueOnce(json({ title: "Unauthorized" }, 401))
+ .mockResolvedValueOnce(pair(refreshed))
+ .mockResolvedValueOnce(json({ title: "Auth.EnrolmentCodeIncorrect", attemptsLeft: 2 }, 400));
+
+ await expect(confirmTwoFactor(freshCode()))
+ .rejects.toMatchObject({ status: 400, title: "Auth.EnrolmentCodeIncorrect", extensions: { attemptsLeft: 2 } });
+ expect(onUnauth).not.toHaveBeenCalled();
+ expect(getAccessToken()).toBe(refreshed);
+ });
+
+ it("refreshes and resends a write after an expired token's plain 401", async () => {
+ fetchMock
+ .mockResolvedValueOnce(json({ title: "Unauthorized" }, 401))
+ .mockResolvedValueOnce(pair(token("acct-F")))
+ .mockResolvedValueOnce(json({ recoveryCodes: [] }));
+ await regenerateRecoveryCodes(crypto.randomUUID());
+
+ expect(to("/auth/two-factor/recovery-codes")).toHaveLength(2);
+ });
+});
+
+// #1277 — from the moment sign-out starts until the next sign-in, no refresh
+// sends, so no request can get a new token.
+describe("after sign-out starts", () => {
+ let held: ((res?: Response | Error) => Promise) | null = null;
+ afterEach(async () => { await held?.(); held = null; });
+
+ // Sign-out with its request held; a refresh would succeed, so only the
+ // refusal keeps one from happening.
+ async function signOutHeld() {
+ let finish!: (res: Response | Error) => void;
+ fetchMock.mockImplementationOnce(() => new Promise((resolve, reject) => {
+ finish = (res) => (res instanceof Error ? reject(res) : resolve(res));
+ }));
+ const done = logout();
+ await vi.waitFor(() => expect(to("/auth/logout")).toHaveLength(1));
+ fetchMock.mockImplementation(async () => pair(token("acct-S")));
+ held = async (res: Response | Error = new Response(null, { status: 204 })) => { finish(res); await done; };
+ return held;
+ }
+
+ it("refuses from its first line, before any await", async () => {
+ let finish!: () => void;
+ fetchMock.mockImplementationOnce(() => new Promise((resolve) => { finish = () => resolve(new Response(null, { status: 204 })); }));
+
+ const done = logout();
+ held = async () => { finish(); await done; };
+
+ expect(isSignedOut()).toBe(true);
+ });
+
+ it.each([
+ ["the status read", "GET", () => getTwoFactorStatus()],
+ ["confirm", "POST", () => confirmTwoFactor(freshCode())],
+ ["start", "POST", () => startTwoFactor(crypto.randomUUID())],
+ ["turn-off", "DELETE", () => turnOffTwoFactor(crypto.randomUUID())],
+ ] as const)("%s sends nothing and refreshes nothing", async (_, method, call) => {
+ await signOutHeld();
+
+ await expect(call()).rejects.toMatchObject({ status: 401 });
+
+ expect(to("/auth/refresh")).toHaveLength(0);
+ expect(calls().filter(([url, init]) => url.includes("/auth/two-factor") && (init.method ?? "GET") === method)).toHaveLength(0);
+ expect(onUnauth).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["a session restore", () => restoreSession().then((restored) => { if (restored) throw new Error("restored"); })],
+ ["a download", () => apiGetBlob("/exports/test").then(() => { throw new Error("downloaded"); }, () => undefined)],
+ ] as const)("%s refreshes nothing", async (_, call) => {
+ await signOutHeld();
+
+ await call();
+
+ expect(calls().map(([url]) => url)).toEqual(["/api/v1/auth/logout"]);
+ });
+
+ it.each([
+ ["answers", new Response(null, { status: 204 })],
+ ["fails", new TypeError("offline")],
+ ] as const)("stays refused after the sign-out request %s, until the next sign-in", async (_, answer) => {
+ const quiet = vi.spyOn(console, "error").mockImplementation(() => undefined);
+ try {
+ const settle = await signOutHeld();
+ await settle(answer);
+ held = null;
+
+ await expect(getTwoFactorStatus()).rejects.toMatchObject({ status: 401 });
+
+ expect(to("/auth/refresh")).toHaveLength(0);
+ } finally {
+ quiet.mockRestore();
+ }
+ });
+
+ it("stays refused while an earlier sign-out is still out, though a later one has settled", async () => {
+ let first!: () => void;
+ fetchMock
+ .mockImplementationOnce(() => new Promise((resolve) => { first = () => resolve(new Response(null, { status: 204 })); }))
+ .mockResolvedValueOnce(new Response(null, { status: 204 }));
+ const a = logout();
+ held = async () => { first(); await a; };
+ await logout();
+ fetchMock.mockImplementation(async () => pair(token("acct-S")));
+
+ await expect(startTwoFactor(crypto.randomUUID())).rejects.toMatchObject({ status: 401 });
+
+ expect(to("/auth/refresh")).toHaveLength(0);
+ expect(to("/auth/two-factor/start")).toHaveLength(0);
+ });
+
+ it("refuses a refresh that was queued behind the cross-tab lock before sign-out", async () => {
+ let enter!: () => Promise;
+ const queued = new Promise((ready) => {
+ vi.stubGlobal("navigator", { locks: { request: (_name: string, run: () => Promise) => {
+ ready();
+ return new Promise((resolve, reject) => { enter = () => run().then(resolve, reject); });
+ } } });
+ });
+ fetchMock.mockImplementation(async (url: string) => (url.endsWith("/auth/logout") ? new Response(null, { status: 204 }) : pair(token("acct-Q"))));
+ const refresh = refreshTokens().then(() => "adopted", () => "refused");
+ await queued;
+ vi.stubGlobal("navigator", {});
+ await logout();
+
+ await enter().catch(() => undefined);
+
+ expect(await refresh).toBe("refused");
+ expect(to("/auth/refresh")).toHaveLength(0);
+ });
+
+ describe("with a sign-in that is abandoned before it commits", () => {
+ afterEach(() => { vi.useRealTimers(); });
+
+ // The cross-tab lock is held elsewhere (a password change in another
+ // tab), so the sign-in waits behind it until its deadline passes.
+ function lockHeldElsewhere() {
+ const turns: (() => Promise)[] = [];
+ vi.stubGlobal("navigator", { locks: { request: (_name: string, run: () => Promise) =>
+ new Promise((resolve, reject) => { turns.push(() => run().then(resolve, reject)); }) } });
+ return turns;
+ }
+
+ // Runs each turn as it arrives, the ones queued behind earlier turns too.
+ async function drain(turns: (() => Promise)[]) {
+ for (let i = 0; i < turns.length; i++) {
+ await turns[i]!().catch(() => undefined);
+ await vi.advanceTimersByTimeAsync(0);
+ }
+ }
+
+ it("refuses a refresh started behind it, and adopts no token", async () => {
+ vi.useFakeTimers();
+ fetchMock.mockImplementation(async (url: string) => (url.endsWith("/auth/logout") ? new Response(null, { status: 204 }) : pair(token("acct-A"))));
+ await logout();
+ const turns = lockHeldElsewhere();
+ const signIn = login(credentials()).then(() => "signed in", () => "abandoned");
+ await vi.advanceTimersByTimeAsync(0);
+ const parked = refreshTokens().then(() => "adopted", () => "refused");
+
+ await vi.advanceTimersByTimeAsync(REFRESH_TIMEOUT_MS);
+ expect(await signIn).toBe("abandoned");
+ await drain(turns);
+
+ expect(await parked).toBe("refused");
+ expect(isSignedOut()).toBe(true);
+ expect(getAccessToken()).toBeNull();
+ expect(calls().map(([url]) => url)).toEqual(["/api/v1/auth/logout"]);
+ });
+
+ it("gives its generation back, because a signed-out refresh queues nothing", async () => {
+ vi.useFakeTimers();
+ fetchMock.mockImplementation(async () => new Response(null, { status: 204 }));
+ await logout();
+ const signedOut = currentSessionGeneration();
+ const turns = lockHeldElsewhere();
+ const signIn = login(credentials()).catch(() => undefined);
+ const whileQueued = currentSessionGeneration();
+ await vi.advanceTimersByTimeAsync(0);
+ const parked = refreshTokens().catch(() => undefined);
+
+ await vi.advanceTimersByTimeAsync(REFRESH_TIMEOUT_MS);
+ await signIn;
+ const afterDeadline = currentSessionGeneration();
+ await drain(turns);
+ await parked;
+
+ expect(whileQueued).toBe(signedOut + 1);
+ expect(afterDeadline).toBe(signedOut);
+ expect(to("/auth/refresh")).toHaveLength(0);
+ });
+
+ it("refuses the refresh an older write's 401 would supply, and does not resend the write", async () => {
+ vi.useFakeTimers();
+ let answer: ((res: Response) => void) | undefined;
+ fetchMock.mockImplementation(async (url: string) => (url.endsWith("/auth/logout") ? new Response(null, { status: 204 })
+ : url.endsWith("/auth/refresh") ? pair(token("acct-W"))
+ : answer ? json({ key: crypto.randomUUID(), otpauthUri: "otpauth://totp/x" })
+ : new Promise((resolve) => { answer = resolve; })));
+ const write = startTwoFactor(crypto.randomUUID()).then(() => "resent", () => "refused");
+ await vi.advanceTimersByTimeAsync(0);
+ await logout();
+ const turns = lockHeldElsewhere();
+ const signIn = login(credentials()).catch(() => undefined);
+ await vi.advanceTimersByTimeAsync(0);
+
+ answer!(json({ title: "Unauthorized" }, 401));
+ await vi.advanceTimersByTimeAsync(REFRESH_TIMEOUT_MS);
+ await signIn;
+ await drain(turns);
+
+ expect(await write).toBe("refused");
+ expect(to("/auth/two-factor/start")).toHaveLength(1);
+ expect(to("/auth/refresh")).toHaveLength(0);
+ expect(to("/auth/login")).toHaveLength(0);
+ });
+ });
+
+ it("ends at the next sign-in, whose requests authenticate", async () => {
+ const settle = await signOutHeld();
+ await settle();
+ held = null;
+ fetchMock.mockReset();
+ fetchMock
+ .mockResolvedValueOnce(pair(token("acct-L")))
+ .mockResolvedValueOnce(json({ enabled: false, recoveryCodesLeft: 0 }));
+
+ await login(credentials());
+
+ expect(isSignedOut()).toBe(false);
+ await expect(getTwoFactorStatus()).resolves.toEqual({ enabled: false, recoveryCodesLeft: 0 });
+ });
+});
+
+// #1277 — only a sign-in whose answer commits its tokens ends a sign-out; a
+// refused, challenged or superseded one leaves the tab refused.
+describe("the sign-out intent at each sign-in outcome", () => {
+ const challenge = () => json({ title: "Auth.SecondFactorRequired", challenge: crypto.randomUUID(), challengeExpiresAt: "2099-01-01T00:00:00Z" }, 401);
+ // Every other route, the code step's commit included, gets a fresh pair.
+ const answering = (signInAnswer: () => Response | Promise, path = "/auth/login") =>
+ fetchMock.mockImplementation(async (url: string) => (url.endsWith(path) ? signInAnswer()
+ : url.endsWith("/auth/login") ? challenge()
+ : url.endsWith("/auth/logout") ? new Response(null, { status: 204 })
+ : pair(token("acct-I"))));
+ // Signs in with a password, and fails unless the server asks for the code.
+ const codeStep = async () => {
+ const outcome = await login(credentials());
+ if (outcome.kind !== "secondFactor") throw new Error("expected the code step");
+ return outcome.challenge;
+ };
+ const refusedSignIns = [
+ ["the password", "/auth/login", () => login(credentials())],
+ ["the code step", "/auth/login/second-factor", async () => completeSecondFactor(await codeStep(), freshCode())],
+ ] as const;
+ // One answer of each kind the client tells apart: validation, credentials,
+ // a titled refusal, forbidden, rate limit, server and transport.
+ const failures = [
+ ["400", () => json({ title: "Validation failed" }, 400)],
+ ["401", () => json({ title: "Unauthorized" }, 401)],
+ ["a suspended farm's 401", () => json({ title: "Auth.FarmSuspended" }, 401)],
+ ["403", () => json({ title: "Forbidden" }, 403)],
+ ["429", () => json({ title: "Too many requests" }, 429)],
+ ["500", () => json({ title: "Server error" }, 500)],
+ ["a network error", () => Promise.reject(new TypeError("Failed to fetch"))],
+ ] as const;
+
+ it.each(refusedSignIns.flatMap(([entry, path, signIn]) => failures.map(([outcome, answer]) => [entry, outcome, path, signIn, answer] as const)))(
+ "%s answering %s leaves refresh refused, with no token",
+ async (_entry, _outcome, path, signIn, answer) => {
+ answering(answer, path);
+ await logout();
+
+ await expect(signIn()).rejects.toBeDefined();
+
+ expect(to(path)).toHaveLength(1);
+ expect(isSignedOut()).toBe(true);
+ await expect(refreshTokens()).rejects.toBeInstanceOf(StaleSessionError);
+ expect(to("/auth/refresh")).toHaveLength(0);
+ expect(getAccessToken()).toBeNull();
+ },
+ );
+
+ it("the second-factor challenge leaves refresh refused", async () => {
+ answering(challenge);
+ await logout();
+
+ expect((await login(credentials())).kind).toBe("secondFactor");
+
+ expect(isSignedOut()).toBe(true);
+ await expect(refreshTokens()).rejects.toBeInstanceOf(StaleSessionError);
+ expect(to("/auth/refresh")).toHaveLength(0);
+ expect(getAccessToken()).toBeNull();
+ });
+
+ it("the code step's commit ends it, and refresh sends again", async () => {
+ answering(challenge);
+ await logout();
+
+ await completeSecondFactor(await codeStep(), freshCode());
+
+ expect(isSignedOut()).toBe(false);
+ await expect(refreshTokens()).resolves.toEqual(expect.any(String));
+ expect(to("/auth/refresh")).toHaveLength(1);
+ });
+
+ it("a sign-in that a later sign-out superseded leaves it set", async () => {
+ let answer: ((res: Response) => void) | undefined;
+ answering(() => new Promise((resolve) => { answer = resolve; }));
+ const signIn = login(credentials()).catch(() => undefined);
+ await vi.waitFor(() => expect(answer).toBeDefined());
+
+ await logout();
+ answer!(pair(token("acct-I")));
+ await signIn;
+
+ expect(isSignedOut()).toBe(true);
+ expect(getAccessToken()).toBeNull();
+ await expect(refreshTokens()).rejects.toBeInstanceOf(StaleSessionError);
+ });
+});
+
+// #1277 — a sign-out the server never answers still ends locally.
+describe("a sign-out the server never answers", () => {
+ afterEach(() => { vi.useRealTimers(); });
+
+ it("stops waiting at the refresh timeout, and aborts the revoke so its late answer cannot land", async () => {
+ vi.useFakeTimers();
+ const failed = vi.spyOn(console, "error");
+ const stopped = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ // As fetch does: the request rejects with the signal's reason when it
+ // aborts, and not before.
+ fetchMock.mockImplementation((_url: string, init: RequestInit) => new Promise((_, reject) => {
+ init.signal?.addEventListener("abort", () => reject(init.signal!.reason));
+ }));
+ try {
+ let ended = false;
+ void logout().then(() => { ended = true; });
+
+ await vi.advanceTimersByTimeAsync(REFRESH_TIMEOUT_MS - 1);
+ expect(ended).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+
+ expect(ended).toBe(true);
+ // A late answer's Set-Cookie would delete a newer sign-in's refresh
+ // cookie on the same farm; the browser drops an aborted request's answer.
+ const [, init] = to("/auth/logout")[0]!;
+ expect(init.signal?.aborted).toBe(true);
+ expect(failed).not.toHaveBeenCalled();
+ expect(stopped).toHaveBeenCalledOnce();
+ } finally {
+ failed.mockRestore();
+ stopped.mockRestore();
+ }
+ });
+
+ // A revoke that answers in time is never aborted later.
+ it.each([204, 500])("never aborts a revoke that answered %s in time", async (status) => {
+ vi.useFakeTimers();
+ const quiet = vi.spyOn(console, "error").mockImplementation(() => undefined);
+ try {
+ fetchMock.mockImplementation(async () => (status === 204 ? new Response(null, { status }) : json({ title: "Server error" }, status)));
+
+ await logout();
+ await vi.advanceTimersByTimeAsync(REFRESH_TIMEOUT_MS + 1);
+
+ const [, init] = to("/auth/logout")[0]!;
+ expect(init.signal?.aborted).toBe(false);
+ } finally {
+ quiet.mockRestore();
+ }
+ });
+
+ // A failure that is not this tab's own abort is logged as one, whether it
+ // lands before the deadline or after it.
+ it.each([
+ ["a network error", async () => { throw new TypeError("Failed to fetch"); }],
+ ["a 500", async () => json({ title: "Server error" }, 500)],
+ ["an abort this tab did not make", async () => { throw new DOMException("cancelled elsewhere", "AbortError"); }],
+ ["a 500 whose body stalls past the deadline", async (_url: string, init: RequestInit) =>
+ new Response(new ReadableStream({ start(body) { init.signal?.addEventListener("abort", () => body.error(init.signal!.reason)); } }),
+ { status: 500, headers: { "Content-Type": "application/problem+json" } })],
+ ] as const)("logs %s as a failed revoke, not a give-up", async (_, answer) => {
+ vi.useFakeTimers();
+ const failed = vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const stopped = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ try {
+ fetchMock.mockImplementation(answer);
+
+ const done = logout();
+ await vi.advanceTimersByTimeAsync(REFRESH_TIMEOUT_MS);
+ await done;
+
+ expect(failed).toHaveBeenCalledOnce();
+ expect(stopped).not.toHaveBeenCalled();
+ } finally {
+ failed.mockRestore();
+ stopped.mockRestore();
+ }
+ });
+});
diff --git a/web/src/components/BottomNav.test.tsx b/web/src/components/BottomNav.test.tsx
index 15ab1040a..53b551d84 100644
--- a/web/src/components/BottomNav.test.tsx
+++ b/web/src/components/BottomNav.test.tsx
@@ -14,7 +14,7 @@ function renderBottomNav(route = "/", onLogout = vi.fn()) {
const tabs = tabEntries(groups);
render(
-
+ ,
);
return { groups, tabs, onLogout };
diff --git a/web/src/components/BottomNav.tsx b/web/src/components/BottomNav.tsx
index 1f7dcfc87..0e01de627 100644
--- a/web/src/components/BottomNav.tsx
+++ b/web/src/components/BottomNav.tsx
@@ -28,19 +28,21 @@ const MORE_VALUE = "__more__";
// sheet, not a route — carrying `aria-haspopup="dialog"`, `aria-expanded` and
// `aria-current="page"` when the route is under More, none of which
// `BottomNavigationAction` models on its own. More itself stays on the MUI
-// `Dialog` component #827 shipped, rendering `fullScreen` below 900px — the
-// one caller that asks for it, since form dialogs stay centred and sized to
-// their content (owner, 2026-09-17, #892) and a twenty-link menu is the case
-// full screen exists for — rather than the retired bottom sheet; the
-// `SwipeableDrawer` alternative §7 names is still open and unanswered here —
+// `Dialog` component #827 shipped, rendering `fullScreen` below 900px — form
+// dialogs stay centred and sized to their content (maintainer, 2026-09-17,
+// #892), and a twenty-link menu needs the height — rather than the retired
+// bottom sheet; the `SwipeableDrawer` alternative §7 names is still open and
+// unanswered here —
// #829 decides it. `anyDialogOpen()` still reads true while More is open,
// same as before #827: it is a real `Dialog` instance either way.
export function BottomNav({
- groups, tabs, onLogout,
+ groups, tabs, onLogout, signingOut,
}: {
groups: NavGroup[];
tabs: NavEntry[];
onLogout: () => void;
+ // A sign-out is in flight: Sign out waits for it.
+ signingOut: boolean;
}) {
const { t } = useTranslation("nav");
const [moreOpen, setMoreOpen] = useState(false);
@@ -143,7 +145,7 @@ export function BottomNav({
{t("updateAvailableAction")}
)}
-
} />
+ }>Home} />
+ ,
+ { token: { sub: "u1", role: "Worker" } },
+ );
+ const signOut = () => within(screen.getByRole("complementary")).getByRole("button", { name: i18n.t("nav:signOut") });
+
+ await act(async () => { fireEvent.click(signOut()); });
+ await act(async () => { fireEvent.click(signOut()); });
+
+ expect(signOut()).toBeDisabled();
+ expect(vi.mocked(fetch).mock.calls.filter(([input]) => String(input).endsWith("/auth/logout"))).toHaveLength(1);
+ await act(async () => { answer(); });
+ await waitFor(() => expect(screen.getByText("Login page")).toBeInTheDocument());
+ });
+
+ it("keeps the More menu's Sign out disabled after the menu reopens", async () => {
+ let answer: (() => void) | undefined;
+ vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => (String(input).endsWith("/auth/logout")
+ ? new Promise((resolve) => { answer = () => resolve(new Response(null, { status: 204 })); })
+ : new Response("[]", { status: 200, headers: { "Content-Type": "application/json" } })));
+ renderWithProviders(
+
+ Login page} />
+ }>Home} />
+ ,
+ { token: { sub: "u1", role: "Worker" } },
+ );
+ const more = () => screen.getByRole("button", { name: i18n.t("nav:moreButton") });
+ const signOut = () => within(screen.getByRole("dialog")).getByRole("button", { name: i18n.t("nav:signOut") });
+ await act(async () => { fireEvent.click(more()); });
+ expect(signOut()).toBeEnabled();
+
+ try {
+ await act(async () => { fireEvent.click(signOut()); });
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ await act(async () => { fireEvent.click(more()); });
+ expect(signOut()).toBeDisabled();
+ await act(async () => { fireEvent.click(signOut()); });
+
+ expect(vi.mocked(fetch).mock.calls.filter(([input]) => String(input).endsWith("/auth/logout"))).toHaveLength(1);
+ } finally {
+ await act(async () => { answer?.(); });
+ }
+ await waitFor(() => expect(screen.getByText("Login page")).toBeInTheDocument());
+ });
+});
diff --git a/web/src/routes/AppLayout.tsx b/web/src/routes/AppLayout.tsx
index 7b9166ad1..ffd7cce84 100644
--- a/web/src/routes/AppLayout.tsx
+++ b/web/src/routes/AppLayout.tsx
@@ -1,4 +1,4 @@
-import { Fragment, Suspense, useEffect } from "react";
+import { Fragment, Suspense, useEffect, useState } from "react";
import { NavLink, Outlet, useLocation, useNavigate } from "react-router";
import { LogOut, RefreshCw } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -11,6 +11,7 @@ import { BottomNav } from "../components/BottomNav";
import { useMissedAnnouncement } from "../components/useMissedAnnouncement";
import { ErrorBoundary } from "../components/ErrorBoundary";
import { FarmBrand } from "../components/FarmBrand";
+import { MAIN_CONTENT_ID } from "../lib/mainContent";
import { useFarm } from "../farm/useFarm";
import { reopenUpdate, useIsUpdateWaiting } from "../pwa/updateStore";
import { navGroups, tabEntries } from "./nav";
@@ -66,7 +67,11 @@ export function AppLayout() {
document.title = active ? `${t(active.labelKey)}${t("titleSuffix")}` : "Cluckwork";
}, [groups, location.pathname, t]);
+ // #1277 — one sign-out at a time: Sign out in the rail and the More menu
+ // stays disabled until it lands.
+ const [leaving, setLeaving] = useState(false);
async function onLogout() {
+ setLeaving(true);
await logout();
navigate("/login", { replace: true });
}
@@ -75,7 +80,13 @@ export function AppLayout() {
{/* First focusable element: lets a keyboard/screen-reader user jump past
the nav links straight to the screen content (#182, Task 7). */}
- {t("skipToContent")}
+ {/* #1277 — focused in place, not followed: a fragment navigation
+ writes a history entry with no state, which gives the location a new
+ key and remounts the screen, dropping whatever it held. */}
+ {
+ e.preventDefault();
+ document.getElementById(MAIN_CONTENT_ID)?.focus();
+ }}>{t("skipToContent")}
)}
- }
+ }
sx={{ justifyContent: "flex-start", width: "100%" }}>
{t("signOut")}
@@ -143,7 +154,7 @@ export function AppLayout() {
-
+
{/* Carries the warning the banner below could not announce because a
dialog had it inert (#485), and stays empty otherwise so the two
never say the same thing twice.
@@ -189,7 +200,7 @@ export function AppLayout() {
-
+
);
}
diff --git a/web/src/routes/ExportPage.tsx b/web/src/routes/ExportPage.tsx
index 2a5a65df6..38305e24a 100644
--- a/web/src/routes/ExportPage.tsx
+++ b/web/src/routes/ExportPage.tsx
@@ -7,23 +7,13 @@ import {
downloadFullBackup,
} from "../api/cluckwork";
import { ApiError } from "../api/client";
+import { saveBlob } from "../lib/saveBlob";
function errText(err: unknown): string {
if (err instanceof ApiError) return err.message;
return err instanceof Error ? err.message : String(err);
}
-function saveBlob(blob: Blob, filename: string) {
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = filename;
- document.body.appendChild(a);
- a.click();
- a.remove();
- URL.revokeObjectURL(url);
-}
-
export function ExportPage() {
const { t } = useTranslation("export");
const [busy, setBusy] = useState<"all" | "csv" | null>(null);
diff --git a/web/src/routes/HelpPage.test.tsx b/web/src/routes/HelpPage.test.tsx
index 5b88fe2b8..d07ddb474 100644
--- a/web/src/routes/HelpPage.test.tsx
+++ b/web/src/routes/HelpPage.test.tsx
@@ -394,11 +394,11 @@ describe("HelpPage", () => {
expect(tl.help.glossaryFarmProvisioningDef).toContain("Settings");
});
- it("enumerates every step-up-gated category and the explicit ungated boundary (#356, #360, #1280)", () => {
+ it("enumerates every step-up-gated category and the explicit ungated boundary (#356, #360, #1280, #1277)", () => {
// Pin the semantics, not merely the count: a stale Owner-only description
// can still say "Six" while omitting one of the widened categories.
render();
- const paragraph = screen.getByText(/Nine actions on the/i).closest("li")!;
+ const paragraph = screen.getByText(/Some actions on the/i).closest("li")!;
expect(paragraph).toHaveTextContent(/creating any user/i);
expect(paragraph).toHaveTextContent(/resetting any user's password/i);
expect(paragraph).toHaveTextContent(/changing any user's role/i);
@@ -408,6 +408,8 @@ describe("HelpPage", () => {
expect(paragraph).toHaveTextContent(/assigning a worker to a flock/i);
expect(paragraph).toHaveTextContent(/removing a worker's flock assignment/i);
expect(paragraph).toHaveTextContent(/resetting a user's two-factor authentication/i);
+ // #1277 — the Account page's own step-up actions.
+ expect(paragraph).toHaveTextContent(/Under Account › Security, Set up asks for your password, and Replace authenticator app, Regenerate and Turn off ask for your password and a code/i);
// #606 — flock-assignment changes are no longer ungated; only display
// name is left as the explicit contrast.
expect(paragraph).toHaveTextContent(/Display-name changes do not ask again/i);
diff --git a/web/src/routes/UsersPage.test.tsx b/web/src/routes/UsersPage.test.tsx
index 305b2e449..ac22b89c2 100644
--- a/web/src/routes/UsersPage.test.tsx
+++ b/web/src/routes/UsersPage.test.tsx
@@ -4270,11 +4270,12 @@ describe("UsersPage step-up with two-factor authentication (#1279)", () => {
});
// 407 "walk everything": the production stepUp() call sites and the callers
- // above, plus /connect's (ConnectPage.test.tsx), must be the same set, so a
- // new caller and a stale row both fail. test/stepUpCallers.test.ts pins the
- // walk itself, its floor and that no two sites share a name.
+ // above, plus /connect's (ConnectPage.test.tsx) and the Account page
+ // Security section's (routes/account/Security.test.tsx), must be the same
+ // set, so a new caller and a stale row both fail. test/stepUpCallers.test.ts
+ // pins the walk itself, its floor and that no two sites share a name.
it("covers exactly the SPA's stepUp() call sites", () => {
- const covered = new Set([...callers.map((c) => c.site), "ConnectPage.allow"]);
+ const covered = new Set([...callers.map((c) => c.site), "ConnectPage.allow", "useTwoFactor.prove"]);
const found = new Set(productionStepUpCallSites());
expect([...found].filter((site) => !covered.has(site))).toEqual([]);
diff --git a/web/src/routes/account/Security.test.tsx b/web/src/routes/account/Security.test.tsx
new file mode 100644
index 000000000..e93c0b55f
--- /dev/null
+++ b/web/src/routes/account/Security.test.tsx
@@ -0,0 +1,428 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { MemoryRouter } from "react-router";
+import { AccountPage } from "../AccountPage";
+import { renderWithProviders } from "../../test/renderWithProviders";
+import { farmState } from "../../test/fixtures";
+import { freshCode } from "../../test/codes";
+import { AuthContext } from "../../auth/AuthContext";
+import { FarmContext } from "../../farm/FarmContext";
+import { MeContext } from "../../session/SessionContext";
+import { RecoveryCodesProvider } from "./recoveryCodes";
+import { getTwoFactorStatus, listMyConnectedApps, regenerateRecoveryCodes, startTwoFactor } from "../../api/cluckwork";
+import type { TwoFactorStatus } from "../../api/cluckwork";
+import { ApiError, confirmTwoFactor, stepUp, turnOffTwoFactor } from "../../api/client";
+import i18n from "../../i18n";
+
+// #1277 — the Account page's Security section. The network is mocked at the
+// API seam; ApiError stays real, because the section branches on it.
+vi.mock("../../api/cluckwork", async (importOriginal) => ({
+ ...await importOriginal(),
+ getTwoFactorStatus: vi.fn(),
+ startTwoFactor: vi.fn(),
+ regenerateRecoveryCodes: vi.fn(),
+ listMyConnectedApps: vi.fn(),
+}));
+vi.mock("../../api/client", async (importOriginal) => ({
+ ...await importOriginal(),
+ stepUp: vi.fn(),
+ confirmTwoFactor: vi.fn(),
+ turnOffTwoFactor: vi.fn(),
+ changePassword: vi.fn(),
+ logout: vi.fn(),
+ setOnTokensChanged: vi.fn(),
+ setOnUnauthenticated: vi.fn(),
+}));
+
+const mockStatus = vi.mocked(getTwoFactorStatus);
+const mockStart = vi.mocked(startTwoFactor);
+const mockRegenerate = vi.mocked(regenerateRecoveryCodes);
+const mockStepUp = vi.mocked(stepUp);
+const mockConfirm = vi.mocked(confirmTwoFactor);
+const mockTurnOff = vi.mocked(turnOffTwoFactor);
+
+const EMAIL = "test@farm.local";
+const OFF: TwoFactorStatus = { enabled: false, recoveryCodesLeft: 0 };
+const ON: TwoFactorStatus = { enabled: true, recoveryCodesLeft: 10 };
+const UNENROLLED = { sub: "u1", role: "Worker" };
+const ENROLLED = { ...UNENROLLED, two_factor: "true" };
+// Every key, URI, grant and code is made at run time; none is a literal.
+const freshKey = () => crypto.randomUUID().replace(/-/g, "").toUpperCase().slice(0, 32);
+const enrolmentFor = (key = freshKey()) => ({ key, otpauthUri: `otpauth://totp/Cluckwork:${EMAIL}?secret=${key}&issuer=Cluckwork` });
+const freshCodes = () => Array.from({ length: 10 }, () => crypto.randomUUID().slice(0, 19));
+const grant = () => ({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" });
+const password = () => `Aa1!${crypto.randomUUID()}`;
+
+const t = (key: string, options: Record = {}): string => i18n.t(`account:${key}` as "account:heading", options);
+const dialog = () => screen.getByRole("dialog");
+const press = async (name: string | RegExp, within_: HTMLElement = document.body) => {
+ await act(async () => { fireEvent.click(within(within_).getByRole("button", { name })); });
+};
+const passwordField = () => within(dialog()).getByLabelText(/Your current password/);
+const codeField = () => within(dialog()).queryByLabelText(/Authenticator or recovery code/);
+const prove = (enrolled: boolean) => {
+ const proof = { password: password(), ...(enrolled && { code: freshCode() }) };
+ fireEvent.change(passwordField(), { target: { value: proof.password } });
+ if (proof.code) fireEvent.change(codeField()!, { target: { value: proof.code } });
+ return proof;
+};
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(listMyConnectedApps).mockResolvedValue([]);
+ mockStepUp.mockImplementation(async () => grant());
+});
+
+async function renderAccount(status: TwoFactorStatus, token: Record = status.enabled ? ENROLLED : UNENROLLED) {
+ mockStatus.mockResolvedValue(status);
+ const view = renderWithProviders(, { token });
+ await screen.findByRole("heading", { name: t("twoFactorHeading") });
+ return view;
+}
+
+async function enrol(enrolment = enrolmentFor()) {
+ mockStart.mockResolvedValueOnce(enrolment);
+ await press(t("setUpButton"));
+ prove(false);
+ await press(t("continueButton"), dialog());
+ await screen.findByRole("heading", { name: t("enrolHeading") });
+ return enrolment;
+}
+
+const typeCode = (code = freshCode()) => {
+ fireEvent.change(screen.getByLabelText(new RegExp(t("codeLabel"))), { target: { value: code } });
+ return code;
+};
+
+describe("the status drives the Security section", () => {
+ it("offers Set up, and nothing else, while two-factor is off", async () => {
+ await renderAccount(OFF);
+
+ expect(screen.getByText(t("twoFactorOff"))).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: t("setUpButton") })).toBeInTheDocument();
+ for (const name of [t("regenerateButton"), t("replaceButton"), t("turnOffButton")])
+ expect(screen.queryByRole("button", { name })).not.toBeInTheDocument();
+ });
+
+ it("shows the codes left with Regenerate, Replace and Turn off once it is on", async () => {
+ await renderAccount(ON);
+
+ expect(screen.getByText(t("twoFactorOn"))).toBeInTheDocument();
+ expect(screen.getByText(t("recoveryCodesLeft", { count: 10 }))).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: t("setUpButton") })).not.toBeInTheDocument();
+ for (const name of [t("regenerateButton"), t("replaceButton"), t("turnOffButton")])
+ expect(screen.getByRole("button", { name })).toBeInTheDocument();
+ });
+
+ it.each([[3, false], [2, true], [1, true], [0, true]])("with %i codes left, warns: %s", async (left, warns) => {
+ await renderAccount({ enabled: true, recoveryCodesLeft: left });
+
+ expect(screen.queryByText(t("recoveryCodesLow", { count: left })) !== null).toBe(warns);
+ expect(screen.getByRole("button", { name: t("regenerateButton") })).toBeInTheDocument();
+ });
+
+ it("says when the status could not load, and loads it again on Try again", async () => {
+ mockStatus.mockRejectedValueOnce(new Error("offline")).mockResolvedValue(ON);
+ renderWithProviders(, { token: ENROLLED });
+
+ await screen.findByText(t("statusLoadFailed"));
+ await press(t("statusRetry"));
+
+ expect(await screen.findByText(t("twoFactorOn"))).toBeInTheDocument();
+ });
+});
+
+describe("enrolment", () => {
+ it("steps up with the password, shows the QR code, the key and the phone link, and warns before confirm", async () => {
+ await renderAccount(OFF);
+ const grantToken = crypto.randomUUID();
+ mockStepUp.mockResolvedValueOnce({ token: grantToken, expiresAt: "2099-01-01T00:00:00Z" });
+ mockStart.mockResolvedValueOnce(enrolmentFor());
+
+ await press(t("setUpButton"));
+ expect(within(dialog()).getByRole("heading", { name: i18n.t("users:confirmItsYouHeading") })).toBeInTheDocument();
+ expect(within(dialog()).getByText(t("proofHintPassword"))).toBeInTheDocument();
+ expect(within(dialog()).getByText(i18n.t("users:signedInAsCaption", { email: EMAIL }))).toBeInTheDocument();
+ expect(codeField()).toBeNull();
+ const proof = prove(false);
+ await press(t("continueButton"), dialog());
+
+ expect(mockStepUp).toHaveBeenCalledWith(proof);
+ expect(mockStart).toHaveBeenCalledWith(grantToken);
+ const { key: shownKey, otpauthUri: shownUri } = await mockStart.mock.results[0]!.value;
+ const qr = screen.getByRole("img", { name: t("qrLabel") });
+ expect(qr.querySelector("path")!.getAttribute("d")).toMatch(/^M\d+ \d+h1v1h-1z/);
+ expect(screen.getByText(shownKey.match(/.{4}/g)!.join(" "))).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: t("openInAppLink") })).toHaveAttribute("href", shownUri);
+ expect(screen.getByText(t("signOutWarning"))).toBeInTheDocument();
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+
+ it("confirms the typed code, then shows the recovery codes once and never asks for them again", async () => {
+ await renderAccount(OFF);
+ await enrol();
+ const codes = freshCodes();
+ mockConfirm.mockResolvedValueOnce({ recoveryCodes: codes });
+ mockStatus.mockResolvedValue({ enabled: true, recoveryCodesLeft: 10 });
+
+ const code = typeCode();
+ await press(t("confirmButton"));
+
+ expect(mockConfirm).toHaveBeenCalledWith(code);
+ const list = await screen.findByRole("list", { name: t("codesListLabel") });
+ expect(within(list).getAllByRole("listitem").map((li) => li.textContent)).toEqual(codes);
+ expect(screen.queryByText(t("codesReplaced"))).not.toBeInTheDocument();
+
+ const done = screen.getByRole("button", { name: t("doneButton") });
+ expect(done).toBeDisabled();
+ fireEvent.click(screen.getByRole("checkbox", { name: t("savedCheckbox") }));
+ await press(t("doneButton"));
+
+ expect(await screen.findByText(t("twoFactorOn"))).toBeInTheDocument();
+ for (const c of codes) expect(screen.queryByText(c)).not.toBeInTheDocument();
+ await waitFor(() => expect(screen.getByRole("button", { name: t("securityHeading") })).toHaveFocus());
+ expect(mockConfirm).toHaveBeenCalledTimes(1);
+ expect(mockRegenerate).not.toHaveBeenCalled();
+ });
+
+ // Maintainer, 2026-11-05: "Codes in a locked dialog". A modal dialog blocks
+ // the sidebar, the bottom nav and Help, and nothing dismisses it before the
+ // codes are saved.
+ it("shows the codes in a dialog nothing dismisses until they are saved", async () => {
+ await renderAccount(OFF);
+ await enrol();
+ mockConfirm.mockResolvedValueOnce({ recoveryCodes: freshCodes() });
+ typeCode();
+ await press(t("confirmButton"));
+
+ const codes = await screen.findByRole("dialog", { name: t("codesHeading") });
+ expect(within(codes).getByRole("button", { name: i18n.t("common:close") })).toBeDisabled();
+ // Why it does not close, without reading out the codes.
+ expect(codes).toHaveAccessibleDescription(t("codesLockedHint"));
+ fireEvent.keyDown(codes, { key: "Escape" });
+ expect(screen.getByRole("dialog", { name: t("codesHeading") })).toBeInTheDocument();
+
+ fireEvent.click(within(codes).getByRole("checkbox", { name: t("savedCheckbox") }));
+ expect(within(codes).getByRole("button", { name: i18n.t("common:close") })).toBeEnabled();
+ fireEvent.keyDown(codes, { key: "Escape" });
+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
+ expect(screen.queryByRole("list", { name: t("codesListLabel") })).not.toBeInTheDocument();
+ });
+
+ it.each([
+ ["with attemptsLeft", { attemptsLeft: 3 }, () => t("codeIncorrectAttempts", { count: 3 })],
+ ["malformed, with no attemptsLeft", {}, () => t("codeIncorrect")],
+ ])("reports a wrong code %s, clears the field and stays on the QR code", async (_, extensions, text) => {
+ await renderAccount(OFF);
+ await enrol();
+ mockConfirm.mockRejectedValueOnce(new ApiError(400, "Auth.EnrolmentCodeIncorrect", "Wrong.", { extensions }));
+
+ typeCode();
+ await press(t("confirmButton"));
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(text());
+ expect(screen.getByLabelText(new RegExp(t("codeLabel")))).toHaveValue("");
+ expect(screen.getByRole("img", { name: t("qrLabel") })).toBeInTheDocument();
+ });
+
+ it.each([
+ ["an expired enrolment", new ApiError(409, "Auth.EnrolmentExpired", "Expired."), () => t("setUpExpired")],
+ ["the fifth wrong code", new ApiError(400, "Auth.EnrolmentCodeIncorrect", "Wrong.", { extensions: { attemptsLeft: 0 } }), () => t("setUpTooManyAttempts")],
+ // The pending enrolment is bound to the old epoch, so Try again could never work.
+ ["a stale session", new ApiError(401, "Auth.CredentialsSuperseded", "Your credentials changed."), () => t("setUpSessionChanged")],
+ ])("after %s, drops the QR code and starts again from a fresh step-up", async (_, err, text) => {
+ await renderAccount(OFF);
+ const { key } = await enrol();
+ mockConfirm.mockRejectedValueOnce(err);
+
+ typeCode();
+ await press(t("confirmButton"));
+
+ expect(await screen.findByText(text())).toBeInTheDocument();
+ expect(screen.queryByRole("img", { name: t("qrLabel") })).not.toBeInTheDocument();
+ expect(screen.queryByText(key.match(/.{4}/g)!.join(" "))).not.toBeInTheDocument();
+
+ mockStart.mockResolvedValueOnce(enrolmentFor());
+ await press(t("startAgainButton"));
+ prove(false);
+ await press(t("continueButton"), dialog());
+ expect(await screen.findByRole("img", { name: t("qrLabel") })).toBeInTheDocument();
+ expect(mockStart).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe("an enrolled user's step-up actions", () => {
+ it("replaces the authenticator app with the password and a code, and confirm returns no codes", async () => {
+ await renderAccount(ON);
+ mockStart.mockResolvedValueOnce(enrolmentFor());
+
+ await press(t("replaceButton"));
+ expect(within(dialog()).getByRole("heading", { name: t("replaceTitle") })).toBeInTheDocument();
+ expect(within(dialog()).getByText(t("proofHint"))).toBeInTheDocument();
+ const proof = prove(true);
+ await press(t("continueButton"), dialog());
+
+ expect(mockStepUp).toHaveBeenCalledWith(proof);
+ expect(await screen.findByRole("heading", { name: t("replaceHeading") })).toBeInTheDocument();
+ mockConfirm.mockResolvedValueOnce({ recoveryCodes: undefined });
+ typeCode();
+ await press(t("confirmButton"));
+
+ expect(await screen.findByText(t("replacedMessage"))).toBeInTheDocument();
+ expect(screen.queryByRole("list", { name: t("codesListLabel") })).not.toBeInTheDocument();
+ });
+
+ it("regenerates the recovery codes and shows the new set as replacing the old", async () => {
+ await renderAccount({ enabled: true, recoveryCodesLeft: 1 });
+ const codes = freshCodes();
+ mockRegenerate.mockResolvedValueOnce({ recoveryCodes: codes });
+
+ await press(t("regenerateButton"));
+ const proof = prove(true);
+ await press(t("regenerateButton"), dialog());
+
+ expect(mockStepUp).toHaveBeenCalledWith(proof);
+ expect(await screen.findByText(t("codesReplaced"))).toBeInTheDocument();
+ expect(within(screen.getByRole("list", { name: t("codesListLabel") })).getAllByRole("listitem")).toHaveLength(10);
+ });
+
+ // #1277 contract item 8: the status was stale.
+ it("says Regenerate found two-factor off, and loads the status again", async () => {
+ await renderAccount(ON);
+ mockRegenerate.mockRejectedValueOnce(new ApiError(409, "Auth.TwoFactorNotEnabled", "Not enabled."));
+ mockStatus.mockResolvedValue(OFF);
+
+ await press(t("regenerateButton"));
+ prove(true);
+ await press(t("regenerateButton"), dialog());
+
+ expect(await within(dialog()).findByRole("alert")).toHaveTextContent(t("regenerateNotEnabled"));
+ // The section behind the dialog now reads the fresh status.
+ expect(await screen.findByText(t("twoFactorOff"))).toBeInTheDocument();
+ });
+
+ it("turns two-factor off and reports it", async () => {
+ await renderAccount(ON);
+ const grantToken = crypto.randomUUID();
+ mockStepUp.mockResolvedValueOnce({ token: grantToken, expiresAt: "2099-01-01T00:00:00Z" });
+ mockTurnOff.mockResolvedValueOnce(undefined);
+ mockStatus.mockResolvedValue(OFF);
+
+ await press(t("turnOffButton"));
+ expect(within(dialog()).getByText(t("turnOffBody"))).toBeInTheDocument();
+ prove(true);
+ await press(t("turnOffButton"), dialog());
+
+ expect(mockTurnOff).toHaveBeenCalledWith(grantToken);
+ expect(await screen.findByText(t("turnedOffMessage"))).toBeInTheDocument();
+ expect(await screen.findByText(t("twoFactorOff"))).toBeInTheDocument();
+ });
+
+ it("reports a stale session's turn-off once, as nothing changed", async () => {
+ await renderAccount(ON);
+ mockTurnOff.mockRejectedValueOnce(new ApiError(401, "Auth.CredentialsSuperseded", "Your credentials changed."));
+
+ await press(t("turnOffButton"));
+ prove(true);
+ await press(t("turnOffButton"), dialog());
+
+ expect(await within(dialog()).findByRole("alert")).toHaveTextContent(t("sessionChanged"));
+ expect(mockTurnOff).toHaveBeenCalledTimes(1);
+ });
+});
+
+// The useDialogSession rules (#1280): every path clears the proof, and a grant
+// that lands after the dialog or the page is gone sends nothing.
+describe("the step-up proof", () => {
+ const actions = [
+ ["Set up", OFF, () => t("setUpButton"), () => t("continueButton")],
+ ["Replace", ON, () => t("replaceButton"), () => t("continueButton")],
+ ["Regenerate", ON, () => t("regenerateButton"), () => t("regenerateButton")],
+ ["Turn off", ON, () => t("turnOffButton"), () => t("turnOffButton")],
+ ] as const;
+
+ it.each(actions)("%s clears it on cancel, so the reopened dialog is empty", async (_, status, open) => {
+ await renderAccount(status);
+ await press(open());
+ prove(status.enabled);
+
+ await press(i18n.t("common:cancel"), dialog());
+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
+ await press(open());
+
+ expect(passwordField()).toHaveValue("");
+ if (status.enabled) expect(codeField()).toHaveValue("");
+ });
+
+ it.each(actions)("%s clears it the moment the proof is sent, and after a refusal", async (_, status, open, submit) => {
+ await renderAccount(status);
+ mockStepUp.mockRejectedValueOnce(new ApiError(400, "Users.CurrentPasswordIncorrect", "Wrong password."));
+ await press(open());
+ prove(status.enabled);
+
+ await press(submit(), dialog());
+
+ expect(await within(dialog()).findByRole("alert")).toBeInTheDocument();
+ expect(passwordField()).toHaveValue("");
+ if (status.enabled) expect(codeField()).toHaveValue("");
+ });
+
+ it.each(actions)("%s sends nothing when its grant lands after the page is gone", async (_, status, open, submit) => {
+ const view = await renderAccount(status);
+ let release!: (value: ReturnType) => void;
+ mockStepUp.mockReturnValueOnce(new Promise((resolve) => { release = resolve; }));
+ await press(open());
+ prove(status.enabled);
+ await press(submit(), dialog());
+
+ view.unmount();
+ await act(async () => { release(grant()); });
+
+ expect(mockStart).not.toHaveBeenCalled();
+ expect(mockRegenerate).not.toHaveBeenCalled();
+ expect(mockTurnOff).not.toHaveBeenCalled();
+ });
+
+ it("drops the key and clears a typed proof the instant the session ends", async () => {
+ mockStatus.mockResolvedValue(ON);
+ const tree = (isAuthenticated: boolean) => (
+
+
+
+
+
+
+
+
+
+ );
+ const view = render(tree(true));
+ await screen.findByRole("heading", { name: t("twoFactorHeading") });
+ mockStart.mockResolvedValueOnce(enrolmentFor());
+ await press(t("replaceButton"));
+ prove(true);
+ await press(t("continueButton"), dialog());
+ const { key } = await mockStart.mock.results[0]!.value;
+ await screen.findByRole("img", { name: t("qrLabel") });
+
+ view.rerender(tree(false));
+
+ expect(screen.queryByRole("img", { name: t("qrLabel") })).not.toBeInTheDocument();
+ expect(screen.queryByText(key.match(/.{4}/g)!.join(" "))).not.toBeInTheDocument();
+ view.rerender(tree(true));
+ await press(t("turnOffButton"));
+ prove(true);
+
+ view.rerender(tree(false));
+
+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
+ view.rerender(tree(true));
+ await press(t("turnOffButton"));
+ expect(passwordField()).toHaveValue("");
+ expect(codeField()).toHaveValue("");
+ });
+});
diff --git a/web/src/routes/account/SecurityPanel.tsx b/web/src/routes/account/SecurityPanel.tsx
new file mode 100644
index 000000000..e81fb5070
--- /dev/null
+++ b/web/src/routes/account/SecurityPanel.tsx
@@ -0,0 +1,152 @@
+import { useId } from "react";
+import type { ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+import { ChevronDown } from "lucide-react";
+import {
+ Accordion, AccordionDetails, AccordionSummary, Alert, Box, Button, DialogActions, Divider, Stack, Typography,
+} from "@mui/material";
+import { useAuth } from "../../auth/useAuth";
+import { BusyButton } from "../../components/BusyButton";
+import { Dialog } from "../../components/Dialog";
+import { DialogError } from "../../components/DialogError";
+import { StepUpProofFields } from "../../components/StepUpProofFields";
+import { useMe } from "../../session/SessionContext";
+import { StatusDot } from "../dashboard/StatusDot";
+import { SECURITY_SUMMARY_ID, useRecoveryCodesSlot } from "./recoveryCodes";
+import { LOW_RECOVERY_CODES } from "./useTwoFactor";
+import type { ProofAction, TwoFactor } from "./useTwoFactor";
+
+// #1275 "Account": the status, the recovery codes left, Regenerate and Turn
+// off together in one accordion.
+export function SecurityPanel({ twoFactor }: { twoFactor: TwoFactor }) {
+ const { t } = useTranslation("account");
+ const { status, message, openProof } = twoFactor;
+ const state = status.data;
+ // One code-issuing request at a time, and none while codes wait to be
+ // saved; Turn off waits too, so a late set never lands on a disabled factor.
+ // Nor while the status reloads: what is on screen may be out of date.
+ const { busy: slotBusy } = useRecoveryCodesSlot();
+ const busy = slotBusy || status.loading;
+ const low = state?.enabled && state.recoveryCodesLeft <= LOW_RECOVERY_CODES;
+
+ return (
+
+ }>
+ {t("securityHeading")}
+
+
+
+
+ {message && {message}}
+
+ {status.error !== null && (
+ {t("statusRetry")}}>
+ {t("statusLoadFailed")}
+
+ )}
+ {state && (
+ openProof("start")}>{t("setUpButton")}}>
+ {t("twoFactorHeading")}
+ {t("twoFactorHint")}
+ {state.enabled
+ ?
+ : }
+
+ )}
+ {state && !state.enabled && {t("twoFactorOffHint")}}
+ {state?.enabled && (
+ <>
+ openProof("regenerate")}>{t("regenerateButton")}}>
+ {t("recoveryCodesHeading")}
+ {t("recoveryCodesLeft", { count: state.recoveryCodesLeft })}
+ {t("recoveryCodesCaption")}
+
+ {low && {t("recoveryCodesLow", { count: state.recoveryCodesLeft })}}
+ openProof("start")}>{t("replaceButton")}}>
+ {t("replaceHint")}
+
+ openProof("turn-off")}>{t("turnOffButton")}}>
+ {t("turnOffHint")}
+
+ >
+ )}
+
+
+
+ );
+}
+
+function Row({ children, action }: { children: ReactNode; action?: ReactNode }) {
+ return (
+
+ {children}
+ {action && {action}}
+
+ );
+}
+
+function copyFor(action: ProofAction, enrolled: boolean) {
+ if (action === "regenerate") return { title: "regenerateTitle", body: "regenerateBody", submit: "regenerateButton" } as const;
+ if (action === "turn-off") return { title: "turnOffTitle", body: "turnOffBody", submit: "turnOffButton" } as const;
+ return enrolled
+ ? { title: "replaceTitle", body: "replaceBody", submit: "continueButton" } as const
+ : { title: "setUpTitle", body: "setUpBody", submit: "continueButton" } as const;
+}
+
+// The lab's proof(): "Confirm it's you", what to enter and who is signed in,
+// then the password and, once two-factor is on, the code. Start again opens it
+// from the enrolment screen too, so the page renders it outside both. Its copy
+// reads the session's two_factor claim, the same fact StepUpProofFields reads
+// for the code field, so the words and the fields always agree.
+export function ProofDialog({ twoFactor }: { twoFactor: TwoFactor }) {
+ const bodyId = useId();
+ const { t } = useTranslation("account");
+ const { t: tu } = useTranslation("users");
+ const { t: tc } = useTranslation("common");
+ const { twoFactor: enrolled } = useAuth();
+ const me = useMe();
+ const { action, proof, setProof, closeProof, onProof, dialog: { busy, isPending, errors } } = twoFactor;
+ const copy = action && copyFor(action, enrolled);
+ return (
+
+ );
+}
diff --git a/web/src/routes/account/TwoFactorFlow.tsx b/web/src/routes/account/TwoFactorFlow.tsx
new file mode 100644
index 000000000..b77bb667d
--- /dev/null
+++ b/web/src/routes/account/TwoFactorFlow.tsx
@@ -0,0 +1,94 @@
+import { useTranslation } from "react-i18next";
+import { Alert, Box, Button, Link, Paper, Stack, TextField, Typography } from "@mui/material";
+import { BusyButton } from "../../components/BusyButton";
+import { DialogError } from "../../components/DialogError";
+import { useCopy } from "../../components/useCopy";
+import { TwoFactorQr } from "./TwoFactorQr";
+import type { Flow, TwoFactor } from "./useTwoFactor";
+
+// #1275 "Enrolment A": the steps that replace the Account page while they run,
+// so the QR code and the key leave the screen with the step that shows them.
+export function TwoFactorFlow({ twoFactor }: { twoFactor: TwoFactor }) {
+ const { t } = useTranslation("account");
+ const { flow } = twoFactor;
+ return (
+
+ {t("flowEyebrow")}
+
+ {flow.step === "scan" && }
+ {flow.step === "restart" && }
+
+
+ );
+}
+
+const heading = (replacing: boolean) => (replacing ? "replaceHeading" : "enrolHeading");
+
+const RESTART_REASONS = { expired: "setUpExpired", attempts: "setUpTooManyAttempts", session: "setUpSessionChanged" } as const;
+
+function ScanStep({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract }) {
+ const { t } = useTranslation("account");
+ const { t: tc } = useTranslation("common");
+ const { code, setCode, onConfirm, leaveFlow, dialog: { busy, isPending, errors } } = twoFactor;
+ const { key, otpauthUri } = flow.enrolment;
+ const { copy, notice } = useCopy();
+ return (
+
+ {t(heading(flow.replacing))}
+
+
+
+ {t("scanHeading")}
+ {t("scanHint")}
+ {/* A phone cannot scan its own screen; the link hands the URI to its app. */}
+ {t("openInAppLink")}
+ summary": { cursor: "pointer", py: 1.25 } }}>
+ {t("cannotScan")}
+
+ {t("keyHint")}
+
+ {key.match(/.{1,4}/g)?.join(" ")}
+
+ void copy(key, t("keyCopied"), t("copyFailed"))}>{t("copyKeyButton")}
+ {notice}
+
+
+
+
+
+ {t("confirmHeading")}
+ {t("confirmHint")}
+ setCode(e.target.value)}
+ slotProps={{ htmlInput: { inputMode: "numeric", autoComplete: "one-time-code", maxLength: 8 } }}
+ />
+ {t("signOutWarning")}
+
+
+
+ {t("confirmButton")}
+ {tc("cancel")}
+
+
+ );
+}
+
+function RestartStep({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract }) {
+ const { t } = useTranslation("account");
+ const { t: tc } = useTranslation("common");
+ const { openProof, leaveFlow } = twoFactor;
+ return (
+
+ {t(heading(flow.replacing))}
+ {t(RESTART_REASONS[flow.reason])}
+
+ openProof("start")}>{t("startAgainButton")}
+ {tc("cancel")}
+
+
+ );
+}
diff --git a/web/src/routes/account/TwoFactorQr.test.ts b/web/src/routes/account/TwoFactorQr.test.ts
new file mode 100644
index 000000000..2f842f471
--- /dev/null
+++ b/web/src/routes/account/TwoFactorQr.test.ts
@@ -0,0 +1,26 @@
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { describe, expect, it } from "vitest";
+import { encode } from "uqr";
+import { QR_OPTIONS } from "./TwoFactorQr";
+
+// #1274 G2.6 — the longest URI the server can build still fits the QR version
+// the record measured. #1278's G3.32 writes the fixture from the C# builder; a
+// missing file fails here instead of passing on nothing.
+const FIXTURE = resolve(process.cwd(), "src/test/otpauth-worst-case.txt");
+const PLACEHOLDER = "_".repeat(32);
+const DEFAULTS = "&algorithm=SHA1&digits=6&period=30";
+
+describe("G2.6: the worst-case otpauth URI", () => {
+ const uri = () => readFileSync(FIXTURE, "utf8").replace(/\n$/, "");
+
+ it("holds the secret placeholder once, 32 characters long", () => {
+ expect(uri().match(/_+/g)).toEqual([PLACEHOLDER]);
+ expect(new URLSearchParams(uri().slice(uri().indexOf("?") + 1)).get("secret")).toBe(PLACEHOLDER);
+ });
+
+ it.each([["as built", ""], ["with the three defaults spelled out", DEFAULTS]])("draws at level M as version 21 or lower, %s", (_, tail) => {
+ expect(QR_OPTIONS).toMatchObject({ ecc: "M", boostEcc: false });
+ expect(encode(`${uri()}${tail}`, QR_OPTIONS).version).toBeLessThanOrEqual(21);
+ });
+});
diff --git a/web/src/routes/account/TwoFactorQr.tsx b/web/src/routes/account/TwoFactorQr.tsx
new file mode 100644
index 000000000..ad7071dc9
--- /dev/null
+++ b/web/src/routes/account/TwoFactorQr.tsx
@@ -0,0 +1,25 @@
+import { useMemo } from "react";
+import { Box } from "@mui/material";
+import { encode } from "uqr";
+
+// #1274 decision 21 — exactly level M, as the worst-case URI was measured
+// against (G2.6), never boosted, and the four-module quiet zone the QR
+// specification asks for.
+export const QR_OPTIONS = { ecc: "M", boostEcc: false, border: 4 } as const;
+
+// Drawn here from the module matrix, so the key never leaves the page: no
+// image endpoint, and no data: URI, which the CSP forbids.
+export function TwoFactorQr({ uri, label }: { uri: string; label: string }) {
+ const { size, path } = useMemo(() => {
+ const { size, data } = encode(uri, QR_OPTIONS);
+ return { size, path: data.flatMap((row, y) => row.map((dark, x) => (dark ? `M${x} ${y}h1v1h-1z` : ""))).join("") };
+ }, [uri]);
+ // Dark on light in both themes, and three CSS pixels a module: at about two,
+ // jsQR could not read a version 18 code from a 1x screenshot (#1277 proof).
+ return (
+
+
+
+ );
+}
diff --git a/web/src/routes/account/recoveryCodes.slot.test.tsx b/web/src/routes/account/recoveryCodes.slot.test.tsx
new file mode 100644
index 000000000..728c25f9b
--- /dev/null
+++ b/web/src/routes/account/recoveryCodes.slot.test.tsx
@@ -0,0 +1,51 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, renderHook, screen } from "@testing-library/react";
+import { RecoveryCodesProvider, useRecoveryCodesSlot } from "./recoveryCodes";
+import { logout } from "../../api/session";
+
+// #1277 — the slot's own contract, below the UI that disables its triggers:
+// while a set is held, saved or not, no new request may start.
+const auth = vi.hoisted(() => ({ isAuthenticated: true }));
+vi.mock("../../auth/useAuth", () => ({ useAuth: () => auth }));
+
+beforeEach(() => { auth.isAuthenticated = true; });
+
+describe("expect()", () => {
+ it("refuses a request once sign-out has started", () => {
+ vi.mocked(fetch).mockReturnValue(new Promise(() => undefined));
+ const { result } = renderHook(useRecoveryCodesSlot, { wrapper: RecoveryCodesProvider });
+ // The floor: before sign-out a request starts (and ends at once).
+ act(() => {
+ const before = result.current.expect();
+ expect(before).not.toBeNull();
+ before!.release();
+ });
+
+ void logout();
+
+ act(() => { expect(result.current.expect()).toBeNull(); });
+ });
+
+ it("refuses a second request while the first is pending", () => {
+ const { result } = renderHook(useRecoveryCodesSlot, { wrapper: RecoveryCodesProvider });
+ act(() => {
+ const first = result.current.expect();
+ expect(first).not.toBeNull();
+ expect(result.current.expect()).toBeNull();
+ first!.release();
+ });
+ });
+
+ it("refuses a new request while a set is held, unsaved and saved", () => {
+ const { result } = renderHook(useRecoveryCodesSlot, { wrapper: RecoveryCodesProvider });
+ act(() => {
+ const ticket = result.current.expect()!;
+ ticket.deliver([crypto.randomUUID()], { regenerated: true, email: "test@farm.local" });
+ ticket.release();
+ });
+
+ act(() => { expect(result.current.expect()).toBeNull(); });
+ fireEvent.click(screen.getByRole("checkbox"));
+ act(() => { expect(result.current.expect()).toBeNull(); });
+ });
+});
diff --git a/web/src/routes/account/recoveryCodes.test.tsx b/web/src/routes/account/recoveryCodes.test.tsx
new file mode 100644
index 000000000..59a47aee2
--- /dev/null
+++ b/web/src/routes/account/recoveryCodes.test.tsx
@@ -0,0 +1,861 @@
+import { useState } from "react";
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { BrowserRouter, Route, Routes, useLocation } from "react-router";
+import { AccountPage } from "../AccountPage";
+import { AppLayout } from "../AppLayout";
+import { ProtectedRoute } from "../ProtectedRoute";
+import { RecoveryCodesProvider } from "./recoveryCodes";
+import { farmState } from "../../test/fixtures";
+import { freshCode } from "../../test/codes";
+import { makeToken, setStoredToken } from "../../test/jwt";
+import { getAccessToken } from "../../auth/tokenStore";
+import { AuthProvider } from "../../auth/AuthContext";
+import { useAuth } from "../../auth/useAuth";
+import { FarmContext } from "../../farm/FarmContext";
+import { MeContext } from "../../session/SessionContext";
+import { getTwoFactorStatus, listMyConnectedApps, regenerateRecoveryCodes, startTwoFactor } from "../../api/cluckwork";
+import type { TwoFactorStatus } from "../../api/cluckwork";
+import { ApiError, confirmTwoFactor, logout, setOnTokensChanged, setOnUnauthenticated, stepUp } from "../../api/client";
+import { isSignedOut, login as signInHere, logout as endSessionHere } from "../../api/session";
+import i18n from "../../i18n";
+
+// #1277 (maintainer, 2026-11-05: "Keep codes above pages"): unsaved
+// recovery codes, and the answer of a confirm or regenerate still in flight,
+// live in a slot above the routes. No navigation drops them; only the end of
+// the session does. Driven through a real BrowserRouter over jsdom's history,
+// because a MemoryRouter would ignore Back and the skip link.
+vi.mock("../../api/cluckwork", async (importOriginal) => ({
+ ...await importOriginal(),
+ getTwoFactorStatus: vi.fn(),
+ startTwoFactor: vi.fn(),
+ regenerateRecoveryCodes: vi.fn(),
+ listMyConnectedApps: vi.fn(),
+}));
+vi.mock("../../api/client", async (importOriginal) => ({
+ ...await importOriginal(),
+ stepUp: vi.fn(),
+ confirmTwoFactor: vi.fn(),
+ logout: vi.fn(),
+ setOnTokensChanged: vi.fn(),
+ setOnUnauthenticated: vi.fn(),
+}));
+
+const t = (key: string, options: Record = {}): string => i18n.t(`account:${key}` as "account:heading", options);
+const EMAIL = "test@farm.local";
+const freshKey = () => crypto.randomUUID().replace(/-/g, "").toUpperCase().slice(0, 32);
+const freshCodes = () => Array.from({ length: 10 }, () => crypto.randomUUID().slice(0, 19));
+const codesDialog = () => screen.queryByRole("dialog", { name: t("codesHeading") });
+
+function deferred() {
+ let resolve!: (value: T) => void;
+ let reject!: (err: unknown) => void;
+ const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
+ return { promise, resolve, reject };
+}
+
+// The form route shows its location key and keeps a typed value in state.
+function FormScreen() {
+ const [typed, setTyped] = useState("");
+ return (
+ <>
+
{useLocation().key}
+ setTyped(e.target.value)} />
+ >
+ );
+}
+
+// The login route, with a way to sign in again through the real AuthProvider.
+function LoginPage() {
+ const { login } = useAuth();
+ return (
+ <>
+
Login page
+ void login("farm", EMAIL, crypto.randomUUID())}>Sign in again
+ >
+ );
+}
+
+// History before the test: /help, then /, then the starting path, so Back
+// lands on "/" and history.go(-2) on "/help".
+function renderApp(path: string, enrolled: boolean) {
+ window.history.replaceState(null, "", "/help");
+ window.history.pushState(null, "", "/");
+ window.history.pushState(null, "", path);
+ setStoredToken({ sub: "u1", role: "Worker", ...(enrolled && { two_factor: "true" }) });
+ return render(
+
+
+
+
+
+
+ } />
+ }>
+ }>
+ Elsewhere} />
+ Help page} />
+ } />
+ } />
+
+
+
+
+
+
+
+ ,
+ );
+}
+
+const rail = () => screen.getByRole("navigation", { name: i18n.t("nav:primaryNavAriaLabel"), hidden: true });
+const skipLink = () => screen.getByRole("link", { name: i18n.t("nav:skipToContent"), hidden: true });
+
+// Each way to leave the Account page, and the route it leaves for. The skip
+// link stays on the page now, so its own test is at the end.
+const LEAVE = {
+ "a nav click": { go: () => fireEvent.click(rail().querySelector('a[href="/"]')!), lands: "Elsewhere" },
+ "a single Back": { go: () => window.history.back(), lands: "Elsewhere" },
+ "history.go(-2)": { go: () => window.history.go(-2), lands: "Help page" },
+} as const;
+
+async function proveAndSubmit(submit: string, enrolled: boolean) {
+ const dialog = await screen.findByRole("dialog");
+ fireEvent.change(within(dialog).getByLabelText(/Your current password/), { target: { value: crypto.randomUUID() } });
+ if (enrolled) fireEvent.change(within(dialog).getByLabelText(/Authenticator or recovery code/), { target: { value: freshCode() } });
+ await act(async () => { fireEvent.click(within(dialog).getByRole("button", { name: submit })); });
+}
+
+// On the set-up step, with a code typed and Confirm code not yet pressed.
+async function toScan() {
+ renderApp("/account", false);
+ const setUp = await screen.findByRole("button", { name: t("setUpButton") }, { timeout: 3000 });
+ await act(async () => { fireEvent.click(setUp); });
+ await proveAndSubmit(t("continueButton"), false);
+ await screen.findByRole("img", { name: t("qrLabel") });
+ fireEvent.change(screen.getByLabelText(new RegExp(t("codeLabel"))), { target: { value: freshCode() } });
+}
+
+async function confirmPending() {
+ const answer = deferred<{ recoveryCodes?: string[] }>();
+ vi.mocked(confirmTwoFactor).mockReturnValue(answer.promise);
+ await toScan();
+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: t("confirmButton") })); });
+ expect(confirmTwoFactor).toHaveBeenCalledTimes(1);
+ return answer;
+}
+
+// A regenerate whose step-up, or whose answer, the test settles by hand.
+async function regenerateOpen() {
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 1 });
+ renderApp("/account", true);
+ const regenerate = await screen.findByRole("button", { name: t("regenerateButton") }, { timeout: 3000 });
+ await act(async () => { fireEvent.click(regenerate); });
+}
+
+async function regeneratePending() {
+ const answer = deferred<{ recoveryCodes: string[] }>();
+ vi.mocked(regenerateRecoveryCodes).mockReturnValue(answer.promise);
+ await regenerateOpen();
+ await proveAndSubmit(t("regenerateButton"), true);
+ expect(regenerateRecoveryCodes).toHaveBeenCalledTimes(1);
+ return answer;
+}
+
+async function leave(how: keyof typeof LEAVE) {
+ const { go, lands } = LEAVE[how];
+ await act(async () => { go(); });
+ await screen.findByText(lands);
+}
+
+const backToAccount = async () => {
+ await act(async () => { fireEvent.click(rail().querySelector('a[href="/account"]')!); });
+ await screen.findByRole("heading", { name: t("twoFactorHeading") }, { timeout: 3000 });
+};
+
+async function codesShown(codes: string[]) {
+ const dialog = await screen.findByRole("dialog", { name: t("codesHeading") });
+ expect(within(dialog).getAllByRole("listitem").map((li) => li.textContent)).toEqual(codes);
+ return dialog;
+}
+
+// The session's last request reported it over, as endSession does.
+const sessionEnds = async (title: string) => {
+ const onUnauthenticated = vi.mocked(setOnUnauthenticated).mock.calls.at(-1)?.[0];
+ if (!onUnauthenticated) throw new Error("AuthProvider registered no session-end handler");
+ await act(async () => { onUnauthenticated(title); });
+};
+
+// Every place the page could still hold a code: the DOM, web storage, the URL
+// and the history entry. The floor is the login page itself, so the walk read
+// a live document.
+function expectNoCodesAnywhere(codes: string[]) {
+ const readable = [
+ document.body.innerHTML, JSON.stringify({ ...localStorage }), JSON.stringify({ ...sessionStorage }),
+ window.location.href, JSON.stringify(window.history.state),
+ ].join("\n");
+ expect(readable).toContain("Login page");
+ for (const code of codes) expect(readable).not.toContain(code);
+}
+
+const tabCloseAsks = () => {
+ const event = new Event("beforeunload", { cancelable: true });
+ window.dispatchEvent(event);
+ return event.defaultPrevented;
+};
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ // Only sign-in answers with a body: a fresh token for the same farm.
+ vi.stubGlobal("fetch", vi.fn(async (url: string) => (url.endsWith("/auth/login")
+ ? new Response(JSON.stringify({ accessToken: makeToken({ sub: "u1", role: "Worker", account_id: "acct-1" }), accessTokenExpiry: "2099-01-01T00:00:00Z" }), { status: 200, headers: { "Content-Type": "application/json" } })
+ : new Response(null, { status: 204 }))));
+ vi.mocked(listMyConnectedApps).mockResolvedValue([]);
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: false, recoveryCodesLeft: 0 });
+ vi.mocked(stepUp).mockImplementation(async () => ({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" }));
+ const key = freshKey();
+ vi.mocked(startTwoFactor).mockResolvedValue({ key, otpauthUri: `otpauth://totp/Cluckwork:${EMAIL}?secret=${key}` });
+});
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe("while confirm is in flight", () => {
+ it.each(Object.keys(LEAVE) as (keyof typeof LEAVE)[])("%s leaves, and the codes still show when confirm settles", async (how) => {
+ const answer = await confirmPending();
+ const codes = freshCodes();
+
+ await leave(how);
+ await act(async () => { answer.resolve({ recoveryCodes: codes }); });
+
+ await codesShown(codes);
+ });
+});
+
+describe("while the codes are unsaved", () => {
+ const STAY = {
+ "a nav click": async () => { await leave("a nav click"); },
+ "Back": async () => { await leave("a single Back"); },
+ "history.go(-2)": async () => { await leave("history.go(-2)"); },
+ "Forward": async () => {
+ await leave("a single Back");
+ await act(async () => { window.history.forward(); });
+ await waitFor(() => expect(window.location.pathname).toBe("/account"));
+ },
+ } as const;
+
+ it.each(Object.keys(STAY) as (keyof typeof STAY)[])("%s keeps the dialog and the codes", async (how) => {
+ const answer = await confirmPending();
+ const codes = freshCodes();
+ await act(async () => { answer.resolve({ recoveryCodes: codes }); });
+ await codesShown(codes);
+
+ await STAY[how]();
+
+ await codesShown(codes);
+ });
+});
+
+describe("while regenerate is in flight", () => {
+ it.each(Object.keys(LEAVE) as (keyof typeof LEAVE)[])("%s leaves, and the new codes still show when it settles", async (how) => {
+ const answer = await regeneratePending();
+ const codes = freshCodes();
+
+ await leave(how);
+ await act(async () => { answer.resolve({ recoveryCodes: codes }); });
+
+ const dialog = await codesShown(codes);
+ expect(within(dialog).getByText(t("codesReplaced"))).toBeInTheDocument();
+ });
+});
+
+describe("when the session ends", () => {
+ it("while confirm is in flight, because the resend's fresh token was refused, no codes appear", async () => {
+ const answer = await confirmPending();
+ const codes = freshCodes();
+
+ answer.reject(new ApiError(401, "Auth.CredentialsSuperseded", "Your credentials changed."));
+ await sessionEnds("Auth.CredentialsSuperseded");
+
+ await screen.findByText("Login page");
+ expect(codesDialog()).toBeNull();
+ expectNoCodesAnywhere(codes);
+ });
+
+ it("while confirm is in flight, by a sign-out, the late answer's codes are dropped", async () => {
+ const answer = await confirmPending();
+ const codes = freshCodes();
+
+ await act(async () => { await endSessionHere(); });
+ await act(async () => { answer.resolve({ recoveryCodes: codes }); });
+ expect(codesDialog()).toBeNull();
+ await sessionEnds("Auth.SessionEnded");
+
+ await screen.findByText("Login page");
+ expectNoCodesAnywhere(codes);
+ });
+
+ it("with codes on screen and unsaved, the codes go with the session", async () => {
+ const answer = await confirmPending();
+ const codes = freshCodes();
+ await act(async () => { answer.resolve({ recoveryCodes: codes }); });
+ await codesShown(codes);
+
+ await sessionEnds("Auth.CredentialsSuperseded");
+
+ await screen.findByText("Login page");
+ expect(codesDialog()).toBeNull();
+ expectNoCodesAnywhere(codes);
+ });
+});
+
+describe("a second set of codes in one mount", () => {
+ it("starts unticked, with Done disabled", async () => {
+ const answer = await confirmPending();
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 10 });
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+ const first = await screen.findByRole("dialog", { name: t("codesHeading") });
+ fireEvent.click(within(first).getByRole("checkbox", { name: t("savedCheckbox") }));
+ await act(async () => { fireEvent.click(within(first).getByRole("button", { name: t("doneButton") })); });
+ await waitFor(() => expect(codesDialog()).toBeNull());
+
+ const codes = freshCodes();
+ vi.mocked(regenerateRecoveryCodes).mockResolvedValue({ recoveryCodes: codes });
+ const regenerate = await screen.findByRole("button", { name: t("regenerateButton") });
+ await act(async () => { fireEvent.click(regenerate); });
+ await proveAndSubmit(t("regenerateButton"), false);
+
+ const second = await codesShown(codes);
+ expect(within(second).getByRole("checkbox", { name: t("savedCheckbox") })).not.toBeChecked();
+ expect(within(second).getByRole("button", { name: t("doneButton") })).toBeDisabled();
+ });
+});
+
+describe("closing the tab", () => {
+ it("asks first while the codes are unsaved, and not once they are saved or done", async () => {
+ const answer = await confirmPending();
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+ const dialog = await screen.findByRole("dialog", { name: t("codesHeading") });
+
+ expect(tabCloseAsks()).toBe(true);
+ fireEvent.click(within(dialog).getByRole("checkbox", { name: t("savedCheckbox") }));
+ expect(tabCloseAsks()).toBe(false);
+ await act(async () => { fireEvent.click(within(dialog).getByRole("button", { name: t("doneButton") })); });
+ expect(tabCloseAsks()).toBe(false);
+ });
+});
+
+describe("focus after Done", () => {
+ async function done() {
+ const dialog = await screen.findByRole("dialog", { name: t("codesHeading") });
+ fireEvent.click(within(dialog).getByRole("checkbox", { name: t("savedCheckbox") }));
+ await act(async () => { fireEvent.click(within(dialog).getByRole("button", { name: t("doneButton") })); });
+ }
+
+ it("goes to the Security section when Account is on screen", async () => {
+ const answer = await confirmPending();
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+
+ await done();
+
+ await waitFor(() => expect(document.activeElement?.id).toBe("account-security"));
+ });
+
+ it("goes to the main content when another page is", async () => {
+ const answer = await confirmPending();
+ await leave("a nav click");
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+
+ await done();
+
+ await waitFor(() => expect(document.activeElement?.id).toBe("main-content"));
+ });
+});
+
+describe("closing the tab while a code-issuing request is in flight", () => {
+ it("asks while confirm is pending, on Account and after leaving it", async () => {
+ await confirmPending();
+ expect(tabCloseAsks()).toBe(true);
+
+ await leave("a nav click");
+
+ expect(tabCloseAsks()).toBe(true);
+ });
+
+ it("asks while regenerate is pending", async () => {
+ await regeneratePending();
+
+ expect(tabCloseAsks()).toBe(true);
+ });
+
+ it("stops asking when confirm fails without codes", async () => {
+ const answer = await confirmPending();
+
+ await act(async () => { answer.reject(new ApiError(400, "Auth.EnrolmentCodeIncorrect", "Wrong.", { extensions: { attemptsLeft: 3 } })); });
+
+ await waitFor(() => expect(tabCloseAsks()).toBe(false));
+ });
+
+ it("stops asking when the session ends, and the late answer shows nothing", async () => {
+ const answer = await confirmPending();
+ const codes = freshCodes();
+
+ await sessionEnds("Auth.CredentialsSuperseded");
+ expect(tabCloseAsks()).toBe(false);
+ await act(async () => { answer.resolve({ recoveryCodes: codes }); });
+
+ await screen.findByText("Login page");
+ expect(tabCloseAsks()).toBe(false);
+ expectNoCodesAnywhere(codes);
+ });
+});
+
+describe("one code-issuing request at a time", () => {
+ it("disables Regenerate and Replace while regenerate is pending, also after leaving and coming back", async () => {
+ await regeneratePending();
+ await leave("a nav click");
+
+ await backToAccount();
+
+ expect(screen.getByRole("button", { name: t("regenerateButton") })).toBeDisabled();
+ expect(screen.getByRole("button", { name: t("replaceButton") })).toBeDisabled();
+ });
+
+ it("disables Turn off while regenerate is pending, after leaving and coming back", async () => {
+ await regeneratePending();
+ await leave("a nav click");
+
+ await backToAccount();
+
+ expect(screen.getByRole("button", { name: t("turnOffButton") })).toBeDisabled();
+ });
+
+ it("disables Set up while confirm is pending, after leaving and coming back", async () => {
+ await confirmPending();
+ await leave("a nav click");
+
+ await backToAccount();
+
+ expect(screen.getByRole("button", { name: t("setUpButton") })).toBeDisabled();
+ });
+});
+
+describe("what the slot holds after a request ends", () => {
+ it("(a) after a session end with regenerate pending, and the next sign-in, the answer shows nothing", async () => {
+ const answer = await regeneratePending();
+ const codes = freshCodes();
+ await sessionEnds("Auth.CredentialsSuperseded");
+ await screen.findByText("Login page");
+
+ // endSession leaves the generation alone, so only the session-end clear
+ // stands between this answer and the login page.
+ await act(async () => { answer.resolve({ recoveryCodes: codes }); });
+ expect(codesDialog()).toBeNull();
+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Sign in again" })); });
+ await waitFor(() => expect(getAccessToken()).not.toBeNull());
+
+ expect(codesDialog()).toBeNull();
+ expectNoCodesAnywhere(codes);
+ });
+
+ it("(b) a set whose session ended while regenerate was pending is dropped", async () => {
+ const answer = await regeneratePending();
+
+ await act(async () => { await endSessionHere(); });
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+
+ expect(codesDialog()).toBeNull();
+ });
+
+ it("(c) a proof that lands after its session ended sends nothing", async () => {
+ const proof = deferred<{ token: string; expiresAt: string }>();
+ vi.mocked(stepUp).mockReturnValueOnce(proof.promise);
+ vi.mocked(regenerateRecoveryCodes).mockResolvedValue({ recoveryCodes: freshCodes() });
+ await regenerateOpen();
+ await proveAndSubmit(t("regenerateButton"), true);
+
+ await act(async () => { await endSessionHere(); });
+ await act(async () => { proof.resolve({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" }); });
+
+ expect(regenerateRecoveryCodes).not.toHaveBeenCalled();
+ expect(codesDialog()).toBeNull();
+ expect(tabCloseAsks()).toBe(false);
+ });
+
+ it("(e) a proof from before a sign-out sends nothing after a newer sign-in", async () => {
+ const proof = deferred<{ token: string; expiresAt: string }>();
+ vi.mocked(stepUp).mockReturnValueOnce(proof.promise);
+ vi.mocked(regenerateRecoveryCodes).mockResolvedValue({ recoveryCodes: freshCodes() });
+ await regenerateOpen();
+ await proveAndSubmit(t("regenerateButton"), true);
+
+ expect(stepUp).toHaveBeenCalledOnce();
+
+ // The session module's sign-out, not the app's Sign out: the dialog stays
+ // current, so only the generation check stands in the way.
+ await act(async () => {
+ await endSessionHere();
+ await signInHere({ farmCode: "farm", email: EMAIL, password: crypto.randomUUID() });
+ });
+ expect(isSignedOut()).toBe(false);
+ await act(async () => { proof.resolve({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" }); });
+
+ expect(regenerateRecoveryCodes).not.toHaveBeenCalled();
+ expect(codesDialog()).toBeNull();
+ });
+
+ it("(d) Done empties the slot, which frees Regenerate again", async () => {
+ const answer = await regeneratePending();
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+ const dialog = await screen.findByRole("dialog", { name: t("codesHeading") });
+ const regenerate = () => screen.getByRole("button", { name: t("regenerateButton"), hidden: true });
+ expect(regenerate()).toBeDisabled();
+
+ fireEvent.click(within(dialog).getByRole("checkbox", { name: t("savedCheckbox") }));
+ await act(async () => { fireEvent.click(within(dialog).getByRole("button", { name: t("doneButton") })); });
+
+ await waitFor(() => expect(codesDialog()).toBeNull());
+ expect(regenerate()).toBeEnabled();
+ expect(tabCloseAsks()).toBe(false);
+ });
+});
+
+describe("a regenerate answer without codes", () => {
+ it("shows an error in its dialog and holds nothing", async () => {
+ vi.mocked(regenerateRecoveryCodes).mockResolvedValue({});
+ await regenerateOpen();
+
+ await proveAndSubmit(t("regenerateButton"), true);
+
+ expect(await within(screen.getByRole("dialog")).findByRole("alert")).toHaveTextContent(t("codesMissing"));
+ expect(codesDialog()).toBeNull();
+ expect(tabCloseAsks()).toBe(false);
+ });
+});
+
+async function saveAndDone() {
+ const dialog = await screen.findByRole("dialog", { name: t("codesHeading") });
+ fireEvent.click(within(dialog).getByRole("checkbox", { name: t("savedCheckbox") }));
+ await act(async () => { fireEvent.click(within(dialog).getByRole("button", { name: t("doneButton") })); });
+}
+
+describe("a Turn off that answers after the user came back", () => {
+ it("shows two-factor off once the adopted session says so", async () => {
+ // Turn off goes through the real client; its DELETE is held.
+ let answer!: () => void;
+ vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => (
+ String(input).endsWith("/auth/two-factor") && init?.method === "DELETE"
+ ? new Promise((resolve) => {
+ answer = () => resolve(new Response(JSON.stringify({ accessToken: makeToken({ sub: "u1", role: "Worker", account_id: "acct-1" }), accessTokenExpiry: "2099-01-01T00:00:00Z" }), { status: 200, headers: { "Content-Type": "application/json" } }));
+ })
+ : new Response(null, { status: 204 })));
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 10 });
+ renderApp("/account", true);
+ const turnOff = await screen.findByRole("button", { name: t("turnOffButton") }, { timeout: 3000 });
+ await act(async () => { fireEvent.click(turnOff); });
+ await proveAndSubmit(t("turnOffButton"), true);
+ await waitFor(() => expect(vi.mocked(fetch).mock.calls.some(([, init]) => init?.method === "DELETE")).toBe(true));
+ await leave("a single Back");
+ await backToAccount();
+ expect(screen.getByText(t("twoFactorOn"))).toBeInTheDocument();
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: false, recoveryCodesLeft: 0 });
+
+ await act(async () => { answer(); });
+ // The adopted pair carries no two_factor claim; the app hears of it as
+ // AuthProvider does from the client.
+ await act(async () => { vi.mocked(setOnTokensChanged).mock.calls.at(-1)![0]!(); });
+
+ expect(await screen.findByText(t("twoFactorOff"))).toBeInTheDocument();
+ });
+});
+
+describe("the status while it reloads after a request settles", () => {
+ it("loads once at mount and once when the request settles, not when it starts or at Done", async () => {
+ const answer = await regeneratePending();
+ expect(getTwoFactorStatus).toHaveBeenCalledTimes(1);
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 10 });
+
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+ expect(getTwoFactorStatus).toHaveBeenCalledTimes(2);
+ await saveAndDone();
+
+ expect(getTwoFactorStatus).toHaveBeenCalledTimes(2);
+ expect(screen.getByText(t("recoveryCodesLeft", { count: 10 }))).toBeInTheDocument();
+ });
+
+ // Each button stays disabled at Done until the settle reload lands. hidden:
+ // the closing dialogs may still mark the page aria-hidden.
+ it.each([
+ ["Set up", "setUpButton", "confirm"],
+ ["Regenerate", "regenerateButton", "regenerate"],
+ ["Replace authenticator app", "replaceButton", "regenerate"],
+ ["Turn off", "turnOffButton", "regenerate"],
+ ] as const)("keeps %s disabled until the reloaded status arrives", async (_, key, request) => {
+ const answer = request === "confirm" ? await confirmPending() : await regeneratePending();
+ const status = deferred();
+ vi.mocked(getTwoFactorStatus).mockReturnValueOnce(status.promise);
+ const button = () => screen.getByRole("button", { name: t(key), hidden: true });
+
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+ await saveAndDone();
+
+ expect(button()).toBeDisabled();
+ // The confirm case keeps two-factor off, so Set up is still the action.
+ await act(async () => { status.resolve(request === "confirm" ? { enabled: false, recoveryCodesLeft: 0 } : { enabled: true, recoveryCodesLeft: 10 }); });
+ await waitFor(() => expect(button()).toBeEnabled());
+ });
+
+ it.each([
+ ["a network error", () => new TypeError("offline")],
+ ["an aborted request", () => new DOMException("aborted by transport", "AbortError")],
+ ] as const)("says so after %s, and Try again loads it", async (_, failure) => {
+ const answer = await regeneratePending();
+ const status = deferred();
+ vi.mocked(getTwoFactorStatus).mockReturnValueOnce(status.promise);
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+ await saveAndDone();
+
+ await act(async () => { status.reject(failure()); });
+
+ expect(await screen.findByText(t("statusLoadFailed"))).toBeInTheDocument();
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 10 });
+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: t("statusRetry"), hidden: true })); });
+ await waitFor(() => expect(screen.getByRole("button", { name: t("regenerateButton"), hidden: true })).toBeEnabled());
+ });
+});
+
+describe("a confirm answer with an empty set", () => {
+ it.each([
+ ["a first enrolment", false, "alert", "codesMissing"],
+ ["a replacement", true, "status", "replacedMessage"],
+ ] as const)("opens no codes dialog for %s, and says what happened", async (_, replacing, role, said) => {
+ const answer = deferred<{ recoveryCodes?: string[] }>();
+ vi.mocked(confirmTwoFactor).mockReturnValue(answer.promise);
+ vi.mocked(getTwoFactorStatus).mockResolvedValue(replacing ? { enabled: true, recoveryCodesLeft: 10 } : { enabled: false, recoveryCodesLeft: 0 });
+ renderApp("/account", replacing);
+ const start = await screen.findByRole("button", { name: t(replacing ? "replaceButton" : "setUpButton") }, { timeout: 3000 });
+ await act(async () => { fireEvent.click(start); });
+ await proveAndSubmit(t("continueButton"), replacing);
+ await screen.findByRole("img", { name: t("qrLabel") });
+ fireEvent.change(screen.getByLabelText(new RegExp(t("codeLabel"))), { target: { value: freshCode() } });
+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: t("confirmButton") })); });
+
+ await act(async () => { answer.resolve({ recoveryCodes: [] }); });
+
+ expect(codesDialog()).toBeNull();
+ expect((await screen.findByText(t(said))).closest(`[role="${role}"]`)).not.toBeNull();
+ });
+});
+
+describe("the status after a refused regenerate", () => {
+ it("reloads after a late 409, when the earlier read still said On", async () => {
+ const answer = await regeneratePending();
+ expect(screen.getByText(t("twoFactorOn"))).toBeInTheDocument();
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: false, recoveryCodesLeft: 0 });
+
+ await act(async () => { answer.reject(new ApiError(409, "Auth.TwoFactorNotEnabled", "Not enabled.")); });
+
+ expect(await within(screen.getByRole("dialog")).findByRole("alert")).toHaveTextContent(t("regenerateNotEnabled"));
+ expect(await screen.findByText(t("twoFactorOff"))).toBeInTheDocument();
+ });
+
+ it("reloads after a late answer without codes, when the earlier count was old", async () => {
+ const answer = deferred<{ recoveryCodes?: string[] }>();
+ vi.mocked(regenerateRecoveryCodes).mockReturnValue(answer.promise);
+ await regenerateOpen();
+ await proveAndSubmit(t("regenerateButton"), true);
+ expect(screen.getByText(t("recoveryCodesLeft", { count: 1 }))).toBeInTheDocument();
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 10 });
+
+ await act(async () => { answer.resolve({}); });
+
+ expect(await within(screen.getByRole("dialog")).findByRole("alert")).toHaveTextContent(t("codesMissing"));
+ expect(await screen.findByText(t("recoveryCodesLeft", { count: 10 }))).toBeInTheDocument();
+ });
+
+ it("treats an empty set as missing", async () => {
+ vi.mocked(regenerateRecoveryCodes).mockResolvedValue({ recoveryCodes: [] });
+ await regenerateOpen();
+
+ await proveAndSubmit(t("regenerateButton"), true);
+
+ expect(await within(screen.getByRole("dialog")).findByRole("alert")).toHaveTextContent(t("codesMissing"));
+ expect(codesDialog()).toBeNull();
+ });
+});
+
+describe("the status after coming back to Account", () => {
+ it("shows the regenerated count once a regenerate settles after the user came back", async () => {
+ const answer = await regeneratePending();
+ await leave("a nav click");
+ await backToAccount();
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 10 });
+
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+ await saveAndDone();
+
+ expect(await screen.findByText(t("recoveryCodesLeft", { count: 10 }))).toBeInTheDocument();
+ });
+
+ it("shows two-factor on once an enrolment settles after the user came back", async () => {
+ const answer = await confirmPending();
+ await leave("a nav click");
+ await backToAccount();
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 10 });
+
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+ await saveAndDone();
+
+ expect(await screen.findByText(t("twoFactorOn"))).toBeInTheDocument();
+ });
+});
+
+describe("regenerate's request ends on every path", () => {
+ it("a refused proof ends it, and a retry goes out", async () => {
+ vi.mocked(stepUp).mockRejectedValueOnce(new ApiError(400, "Users.CurrentPasswordIncorrect", "Wrong."));
+ await regenerateOpen();
+
+ await proveAndSubmit(t("regenerateButton"), true);
+ expect(await within(screen.getByRole("dialog")).findByRole("alert")).toBeInTheDocument();
+ expect(tabCloseAsks()).toBe(false);
+ vi.mocked(regenerateRecoveryCodes).mockResolvedValueOnce({ recoveryCodes: freshCodes() });
+ await proveAndSubmit(t("regenerateButton"), true);
+
+ expect(regenerateRecoveryCodes).toHaveBeenCalledTimes(1);
+ expect(codesDialog()).not.toBeNull();
+ });
+
+ it("a proof abandoned by Back ends it, and no write is sent", async () => {
+ const proof = deferred<{ token: string; expiresAt: string }>();
+ vi.mocked(stepUp).mockReturnValueOnce(proof.promise);
+ await regenerateOpen();
+ await proveAndSubmit(t("regenerateButton"), true);
+ expect(tabCloseAsks()).toBe(true);
+
+ // The proof lands in the first microtask after Back puts the next page in
+ // the DOM: before a deferred passive cleanup of the page that asked, when
+ // React defers it to a later task.
+ const landed = new Promise((resolve) => {
+ const arrival = new MutationObserver(() => {
+ if (!document.body.textContent?.includes("Elsewhere")) return;
+ arrival.disconnect();
+ proof.resolve({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" });
+ resolve();
+ });
+ arrival.observe(document.body, { childList: true, subtree: true, characterData: true });
+ });
+ await leave("a single Back");
+ await act(async () => { await landed; });
+
+ expect(regenerateRecoveryCodes).not.toHaveBeenCalled();
+ expect(tabCloseAsks()).toBe(false);
+ await backToAccount();
+ expect(screen.getByRole("button", { name: t("regenerateButton") })).toBeEnabled();
+ });
+
+ it("a refusal after Account is gone ends it", async () => {
+ const answer = await regeneratePending();
+ await leave("a single Back");
+
+ await act(async () => { answer.reject(new ApiError(409, "Auth.TwoFactorNotEnabled", "Not enabled.")); });
+
+ expect(tabCloseAsks()).toBe(false);
+ await backToAccount();
+ expect(screen.getByRole("button", { name: t("regenerateButton") })).toBeEnabled();
+ });
+
+ it("a delivery after Account is gone ends it once the codes are Done", async () => {
+ const answer = await regeneratePending();
+ await leave("a single Back");
+
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+ const dialog = screen.getByRole("dialog", { name: t("codesHeading") });
+ fireEvent.click(within(dialog).getByRole("checkbox", { name: t("savedCheckbox") }));
+ await act(async () => { fireEvent.click(within(dialog).getByRole("button", { name: t("doneButton") })); });
+
+ expect(tabCloseAsks()).toBe(false);
+ await backToAccount();
+ expect(screen.getByRole("button", { name: t("regenerateButton") })).toBeEnabled();
+ });
+});
+
+describe("a request from an ended session", () => {
+ it("cannot end the next session's request, which still shows its codes", async () => {
+ const first = await regeneratePending();
+ await sessionEnds("Auth.SessionEnded");
+ await screen.findByText("Login page");
+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Sign in again" })); });
+ await waitFor(() => expect(getAccessToken()).not.toBeNull());
+ await act(async () => {
+ window.history.pushState({ key: crypto.randomUUID() }, "", "/account");
+ window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
+ });
+ const regenerate = await screen.findByRole("button", { name: t("regenerateButton") }, { timeout: 3000 });
+ const second = deferred<{ recoveryCodes: string[] }>();
+ vi.mocked(regenerateRecoveryCodes).mockReturnValueOnce(second.promise);
+ await act(async () => { fireEvent.click(regenerate); });
+ await proveAndSubmit(t("regenerateButton"), false);
+ expect(regenerateRecoveryCodes).toHaveBeenCalledTimes(2);
+
+ await act(async () => { first.resolve({ recoveryCodes: freshCodes() }); });
+
+ expect(codesDialog()).toBeNull();
+ expect(tabCloseAsks()).toBe(true);
+ const codes = freshCodes();
+ await act(async () => { second.resolve({ recoveryCodes: codes }); });
+ await codesShown(codes);
+ });
+});
+
+describe("a first enrolment's answer without codes", () => {
+ it("says so on the set-up step and holds nothing", async () => {
+ const answer = await confirmPending();
+
+ await act(async () => { answer.resolve({}); });
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(t("codesMissing"));
+ expect(codesDialog()).toBeNull();
+ expect(tabCloseAsks()).toBe(false);
+ });
+});
+
+describe("Sign out while the set-up step is open", () => {
+ it("sends no confirm once Sign out has been pressed, and no codes appear", async () => {
+ // The app's Sign out runs the real session sign-out, its request held.
+ let finish!: () => void;
+ vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => (String(input).endsWith("/auth/logout")
+ ? new Promise((resolve) => { finish = () => resolve(new Response(null, { status: 204 })); })
+ : new Response(null, { status: 204 })));
+ vi.mocked(logout).mockImplementation(() => endSessionHere());
+ vi.mocked(confirmTwoFactor).mockResolvedValue({ recoveryCodes: freshCodes() });
+ await toScan();
+
+ await act(async () => { fireEvent.click(within(rail().closest("aside")!).getByRole("button", { name: i18n.t("nav:signOut"), hidden: true })); });
+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: t("confirmButton") })); });
+
+ expect(confirmTwoFactor).not.toHaveBeenCalled();
+ expect(tabCloseAsks()).toBe(false);
+ await act(async () => { finish(); });
+ await screen.findByText("Login page");
+ expect(codesDialog()).toBeNull();
+ });
+});
+
+// A browser's fragment navigation writes a history entry with no state, which
+// gives the location a new key and remounts the screen. jsdom fires no
+// popstate for it, so the test pins the cause: the click is never followed.
+describe("the skip link", () => {
+ it("moves focus to the content without a navigation, so the screen keeps its state", async () => {
+ renderApp("/form", false);
+ const key = (await screen.findByTestId("location-key")).textContent;
+ fireEvent.change(screen.getByLabelText("Notes"), { target: { value: "half-typed" } });
+
+ let followed = true;
+ await act(async () => { followed = fireEvent.click(skipLink()); });
+
+ expect(followed).toBe(false);
+ expect(window.location.hash).toBe("");
+ expect(document.activeElement?.id).toBe("main-content");
+ expect(screen.getByTestId("location-key")).toHaveTextContent(key!);
+ expect(screen.getByLabelText("Notes")).toHaveValue("half-typed");
+ });
+});
diff --git a/web/src/routes/account/recoveryCodes.tsx b/web/src/routes/account/recoveryCodes.tsx
new file mode 100644
index 000000000..56af60221
--- /dev/null
+++ b/web/src/routes/account/recoveryCodes.tsx
@@ -0,0 +1,192 @@
+import { createContext, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
+import type { ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+import { Alert, Box, Button, Checkbox, DialogActions, FormControlLabel, Stack, Typography } from "@mui/material";
+import { currentSessionGeneration, isSignedOut } from "../../api/client";
+import { useAuth } from "../../auth/useAuth";
+import { Dialog } from "../../components/Dialog";
+import { useCopy } from "../../components/useCopy";
+import { MAIN_CONTENT_ID } from "../../lib/mainContent";
+import { saveBlob } from "../../lib/saveBlob";
+
+// #1277 (maintainer, 2026-11-05: "Keep codes above pages"): recovery codes
+// that are shown once live here, above the routes, until the user saves them,
+// and so does the request that will hand them out. A confirm or regenerate
+// that settles after its page is gone still lands here, and no navigation drops
+// the set: only Done, or the end of this tab's session. Another tab's sign-out
+// does not reach it (a known limit, as on every other screen). In memory
+// only: never in storage, a URL or a log.
+interface HeldRecoveryCodes {
+ // Keys the dialog, so a new set never shows the last set's notes.
+ id: number;
+ codes: readonly string[];
+ regenerated: boolean;
+ // Part of the value, so a new set starts unticked.
+ saved: boolean;
+ // For the download's title; the session's Me lives below this slot.
+ email: string;
+}
+
+// One code-issuing request. deliver shows its set unless the request's session
+// has ended since; release, from a finally, ends the request either way.
+export interface Delivery {
+ // Still the active request, in the session that started it.
+ live: () => boolean;
+ deliver: (codes: readonly string[], set: { regenerated: boolean; email: string }) => void;
+ release: () => void;
+}
+
+interface Slot {
+ // A request is out or a set is held: Set up, Replace and Regenerate wait.
+ busy: boolean;
+ // Counts the requests that have ended, so the status can reload on each.
+ settled: number;
+ // Null while busy, so only one request can issue codes at a time. Call it
+ // before the step-up proof: it reads the session generation then.
+ expect: () => Delivery | null;
+}
+
+const RecoveryCodesContext = createContext(null);
+
+// Here rather than in SecurityPanel: this module is in the main bundle, and
+// importing it from the lazy Account chunk is the only direction that keeps
+// the two apart.
+export const SECURITY_SUMMARY_ID = "account-security";
+
+export function useRecoveryCodesSlot(): Slot {
+ const slot = useContext(RecoveryCodesContext);
+ if (!slot) throw new Error("useRecoveryCodesSlot needs a RecoveryCodesProvider above it.");
+ return slot;
+}
+
+export function RecoveryCodesProvider({ children }: { children: ReactNode }) {
+ const { isAuthenticated } = useAuth();
+ // State renders the slot; the refs answer expect and deliver, which run
+ // between renders.
+ const [held, setHeld] = useState(null);
+ const [pending, setPending] = useState(null);
+ const [settled, setSettled] = useState(0);
+ const heldRef = useRef(null);
+ const pendingRef = useRef(null);
+ const tickets = useRef(0);
+ const put = (set: HeldRecoveryCodes | null) => { heldRef.current = set; setHeld(set); };
+ const putPending = (ticket: number | null) => { pendingRef.current = ticket; setPending(ticket); };
+
+ // #308 — the set, and the request it waits on, end with this tab's session.
+ // The clear runs before paint and overwrites anything that arrived earlier.
+ // A layout effect is the safe side; no jsdom test can tell it from a
+ // passive one.
+ useLayoutEffect(() => {
+ if (isAuthenticated) return;
+ put(null);
+ putPending(null);
+ }, [isAuthenticated]);
+
+ const asks = pending !== null || (held !== null && !held.saved);
+ useEffect(() => {
+ if (!asks) return;
+ const warn = (e: BeforeUnloadEvent) => {
+ e.preventDefault();
+ e.returnValue = "";
+ };
+ window.addEventListener("beforeunload", warn);
+ return () => window.removeEventListener("beforeunload", warn);
+ }, [asks]);
+
+ // No deps: put and putPending must stay ref-and-setter only, so this
+ // callback never closes over a render's state.
+ const expect = useCallback((): Delivery | null => {
+ // #1277 — no code-issuing work starts once sign-out has begun.
+ if (isSignedOut()) return null;
+ // Unreachable from the UI, which disables its triggers while busy; the
+ // slot-contract test pins it.
+ if (pendingRef.current !== null || heldRef.current !== null) return null;
+ const ticket = ++tickets.current;
+ const generation = currentSessionGeneration();
+ putPending(ticket);
+ const current = () => pendingRef.current === ticket && generation === currentSessionGeneration();
+ return {
+ live: current,
+ deliver: (codes, { regenerated, email }) => {
+ if (current()) put({ id: ticket, codes, regenerated, email, saved: false });
+ },
+ release: () => {
+ if (pendingRef.current !== ticket) return;
+ putPending(null);
+ setSettled((n) => n + 1);
+ },
+ };
+ }, []);
+
+ // The trigger that opened the dialog is gone by now, so focus goes to the
+ // Security section if it is on screen, else to the page's content.
+ const done = () => {
+ put(null);
+ requestAnimationFrame(() => (document.getElementById(SECURITY_SUMMARY_ID) ?? document.getElementById(MAIN_CONTENT_ID))?.focus());
+ };
+
+ const slot = useMemo(() => ({ busy: pending !== null || held !== null, settled, expect }), [pending, held, settled, expect]);
+ return (
+
+ {children}
+ {held && (
+ put(heldRef.current && { ...heldRef.current, saved })} onDone={done} />
+ )}
+
+ );
+}
+
+// #1275 "Recovery codes", shown once. The maintainer chose a locked dialog
+// (2026-11-05): until the codes are saved nothing dismisses it, and the modal
+// keeps the sidebar, the bottom nav and Help out of reach.
+function RecoveryCodesDialog({ held, onSaved, onDone }: {
+ held: HeldRecoveryCodes;
+ onSaved: (saved: boolean) => void;
+ onDone: () => void;
+}) {
+ const { t } = useTranslation("account");
+ const { copy, notice, setNote } = useCopy();
+ const hintId = useId();
+ const text = held.codes.join("\n");
+
+ const download = () => {
+ saveBlob(new Blob([`${t("codesFileTitle", { email: held.email })}\n\n${text}\n`], { type: "text/plain" }), "cluckwork-recovery-codes.txt");
+ setNote({ text: t("codesDownloaded"), ok: true });
+ };
+
+ return (
+
+ );
+}
diff --git a/web/src/routes/account/useTwoFactor.test.tsx b/web/src/routes/account/useTwoFactor.test.tsx
new file mode 100644
index 000000000..bf401bdd1
--- /dev/null
+++ b/web/src/routes/account/useTwoFactor.test.tsx
@@ -0,0 +1,46 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { act, renderHook, screen, waitFor } from "@testing-library/react";
+import type { FormEvent } from "react";
+import { useTwoFactor } from "./useTwoFactor";
+import { RecoveryCodesProvider } from "./recoveryCodes";
+import { getTwoFactorStatus, regenerateRecoveryCodes } from "../../api/cluckwork";
+import { stepUp } from "../../api/client";
+
+// #1277 — the hook hands new recovery codes to the slot above the routes and
+// never keeps them itself. JSON.stringify sees only the
+// serializable part of the hook's result (its state, not its closures), which
+// is where a kept set would sit.
+const auth = vi.hoisted(() => ({ isAuthenticated: true }));
+vi.mock("../../auth/useAuth", () => ({ useAuth: () => auth }));
+vi.mock("../../api/cluckwork", async (original) => ({
+ ...await original(),
+ getTwoFactorStatus: vi.fn(), regenerateRecoveryCodes: vi.fn(),
+}));
+vi.mock("../../api/client", async (original) => ({
+ ...await original(), stepUp: vi.fn(),
+}));
+
+let code: string;
+
+beforeEach(() => {
+ code = crypto.randomUUID();
+ auth.isAuthenticated = true;
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 10 });
+ vi.mocked(regenerateRecoveryCodes).mockResolvedValue({ recoveryCodes: [code] });
+ vi.mocked(stepUp).mockResolvedValue({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" });
+});
+
+describe("new recovery codes", () => {
+ it("go to the slot, which shows them, and never into the hook's state", async () => {
+ const { result } = renderHook(useTwoFactor, { wrapper: RecoveryCodesProvider });
+ await waitFor(() => expect(result.current.status.data?.enabled).toBe(true));
+ act(() => result.current.openProof("regenerate"));
+ act(() => result.current.setProof({ password: crypto.randomUUID() }));
+
+ await act(async () => { await result.current.onProof({ preventDefault() {} } as FormEvent); });
+
+ expect(await screen.findByText(code)).toBeInTheDocument();
+ expect(JSON.stringify(result.current)).not.toContain(code);
+ expect(result.current.flow).toEqual({ step: "summary" });
+ });
+});
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
new file mode 100644
index 000000000..a052c00e7
--- /dev/null
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -0,0 +1,227 @@
+import { useEffect, useState } from "react";
+import type { FormEvent } from "react";
+import { getTwoFactorStatus, regenerateRecoveryCodes, startTwoFactor } from "../../api/cluckwork";
+import type { EnrolmentStart } from "../../api/cluckwork";
+import { ApiError, confirmTwoFactor, NO_PROOF, stepUp, turnOffTwoFactor } from "../../api/client";
+import type { StepUpProof } from "../../api/client";
+import { useAuth } from "../../auth/useAuth";
+import { useDialogAction } from "../../components/useDialogAction";
+import { useLatestLoad } from "../../components/useLatestLoad";
+import i18n from "../../i18n";
+import { useMe } from "../../session/SessionContext";
+import { useRecoveryCodesSlot } from "./recoveryCodes";
+import type { Delivery } from "./recoveryCodes";
+
+// #1277 — the Security section's two-factor authentication. Start,
+// Regenerate and Turn off each step up in a dialog first; confirm is the
+// enrolment screen's own form.
+export type ProofAction = "start" | "regenerate" | "turn-off";
+const SCOPES = ["start", "regenerate", "turn-off", "confirm"] as const;
+
+// From this many recovery codes left, the section warns (#1274 decision 9).
+export const LOW_RECOVERY_CODES = 2;
+
+// What the section shows. The key and the URI live only in the step that
+// shows them, and leave with it. New recovery codes go to the slot above the
+// routes (recoveryCodes.tsx), never into this state.
+export type Flow =
+ | { step: "summary" }
+ | { step: "scan"; enrolment: EnrolmentStart; replacing: boolean }
+ | { step: "restart"; replacing: boolean; reason: "expired" | "attempts" | "session" };
+
+const SUMMARY: Flow = { step: "summary" };
+
+const isProblem = (err: unknown, status: number, title: string): err is ApiError =>
+ err instanceof ApiError && err.status === status && err.title === title;
+
+// The stale-session refusal changed nothing on the server (#1280), and the API
+// layer never resends it, so the user only needs to try again.
+function stale(err: unknown): unknown {
+ return isProblem(err, 401, "Auth.CredentialsSuperseded") ? new Error(i18n.t("account:sessionChanged")) : err;
+}
+
+export function useTwoFactor() {
+ const { isAuthenticated, twoFactor: enrolled } = useAuth();
+ const dialog = useDialogAction(SCOPES);
+ const { busy, run, openDialog, dismissDialog } = dialog;
+ const [flow, setFlow] = useState(SUMMARY);
+ const [action, setAction] = useState(null);
+ const [proof, setProof] = useState(NO_PROOF);
+ const [code, setCode] = useState("");
+ const [message, setMessage] = useState(null);
+ const slot = useRecoveryCodesSlot();
+ // #1277 — reloaded each time a code-issuing request settles, and
+ // whenever the session's two_factor claim changes (a Turn off that
+ // answers after the user came back), so a page mounted since still shows
+ // what the server now holds. Both triggers stay: a Turn off is not a slot
+ // request, and a regenerate changes no claim.
+ const status = useLatestLoad([slot.settled, enrolled], getTwoFactorStatus);
+ const email = useMe()?.email ?? "";
+
+ // #308 — a proof, a code, a key or a recovery code never outlives the session.
+ useEffect(() => {
+ if (isAuthenticated) return;
+ setProof(NO_PROOF);
+ setCode("");
+ setFlow(SUMMARY);
+ setAction(null);
+ for (const scope of SCOPES) dismissDialog(scope);
+ }, [isAuthenticated, dismissDialog]);
+
+ // Every way out clears the proof (cancel, send, logout), so opening does not.
+ function openProof(next: ProofAction) {
+ openDialog(next);
+ setMessage(null);
+ setAction(next);
+ }
+
+ function closeProof() {
+ setProof(NO_PROOF);
+ setAction(null);
+ if (action) dismissDialog(action);
+ }
+
+ async function send(next: "start" | "turn-off", token: string, current: () => boolean) {
+ if (next === "start") {
+ // As the dialog does: replacing means the session proved two factors.
+ const replacing = enrolled;
+ const enrolment = await startTwoFactor(token);
+ if (!current()) return;
+ setCode("");
+ openDialog("confirm");
+ setFlow({ step: "scan", enrolment, replacing });
+ } else {
+ await turnOffTwoFactor(token);
+ // A 204 (two-factor was already off) rotates nothing, so neither the
+ // claim nor a settle would reload the status; this does.
+ status.retry();
+ if (!current()) return;
+ setMessage(i18n.t("account:turnedOffMessage"));
+ }
+ setAction(null);
+ dismissDialog(next);
+ }
+
+ // dialogCurrent is the Regenerate dialog's session; delivery.live() is the
+ // slot's request in this tab's session. Either can end without the other.
+ async function regenerate(token: string, dialogCurrent: () => boolean, delivery: Delivery) {
+ // Either refusal reloads the status through the slot: release ends the
+ // request and the status reads again.
+ const { recoveryCodes } = await regenerateRecoveryCodes(token).catch((err: unknown) => {
+ // The status was stale (#1277 contract item 8).
+ if (!isProblem(err, 409, "Auth.TwoFactorNotEnabled")) throw err;
+ throw new Error(i18n.t("account:regenerateNotEnabled"));
+ });
+ // The old set no longer works, so a broken answer is said, not shown.
+ if (!isCodeSet(recoveryCodes)) throw new Error(i18n.t("account:codesMissing"));
+ // Before the dialogCurrent() check: the codes are shown even if the user
+ // has left this page, because the old set no longer works.
+ delivery.deliver(recoveryCodes, { regenerated: true, email });
+ if (!dialogCurrent()) return;
+ setAction(null);
+ dismissDialog("regenerate");
+ }
+
+ // The step-up proof every Security dialog sends first.
+ async function prove() {
+ const entered = proof;
+ setProof(NO_PROOF);
+ return (await stepUp(entered)).token;
+ }
+
+ async function onProof(e: FormEvent) {
+ e.preventDefault();
+ const next = action;
+ if (!next || busy) return;
+ setMessage(null);
+ await run(next, async (current) => {
+ if (next !== "regenerate") {
+ const token = await prove();
+ if (!current()) return;
+ await send(next, token, current).catch((err: unknown) => { throw stale(err); });
+ return;
+ }
+ // Taken before the step-up proof, so the slot reads the session then,
+ // and released however the request ends.
+ const delivery = slot.expect();
+ if (delivery === null) return;
+ try {
+ const token = await prove();
+ // #1277 — a session that ended during the proof sends nothing: the
+ // server would replace the set, and deliver would drop the only copy.
+ if (!current() || !delivery.live()) return;
+ await regenerate(token, current, delivery).catch((err: unknown) => { throw stale(err); });
+ } finally {
+ delivery.release();
+ }
+ }, { dialog: next });
+ }
+
+ async function onConfirm(e: FormEvent) {
+ e.preventDefault();
+ if (flow.step !== "scan" || busy) return;
+ const { replacing } = flow;
+ await run("confirm", async (current) => {
+ const delivery = slot.expect();
+ if (delivery === null) return;
+ try {
+ await confirmWith(delivery, current, replacing);
+ } finally {
+ delivery.release();
+ }
+ });
+ }
+
+ async function confirmWith(delivery: Delivery, current: () => boolean, replacing: boolean) {
+ const typed = code;
+ setCode("");
+ let recoveryCodes: string[] | undefined;
+ try {
+ ({ recoveryCodes } = await confirmTwoFactor(typed));
+ } catch (err) {
+ // The fifth wrong code ended the enrolment, and every later confirm
+ // answers 409. A stale session's enrolment is bound to the old epoch,
+ // so it can only answer 409 too. Each way the user starts again.
+ const attemptsLeft = err instanceof ApiError ? err.extensions.attemptsLeft : undefined;
+ const reason = isProblem(err, 409, "Auth.EnrolmentExpired") ? "expired"
+ : isProblem(err, 401, "Auth.CredentialsSuperseded") ? "session"
+ : isProblem(err, 400, "Auth.EnrolmentCodeIncorrect") && attemptsLeft === 0 ? "attempts" : null;
+ if (reason === null) throw incorrect(err, attemptsLeft);
+ if (current()) setFlow({ step: "restart", replacing, reason });
+ return;
+ }
+ // A first enrolment's answer carries the codes; without them the user is
+ // enrolled with none to save, and Regenerate is the way out.
+ if (!replacing && !isCodeSet(recoveryCodes)) throw new Error(i18n.t("account:codesMissing"));
+ // Before the current() check, as regenerate does: the user is enrolled
+ // now, so the codes are shown wherever the user has gone.
+ if (isCodeSet(recoveryCodes)) delivery.deliver(recoveryCodes, { regenerated: false, email });
+ if (!current()) return;
+ setFlow(SUMMARY);
+ if (!isCodeSet(recoveryCodes)) setMessage(i18n.t("account:replacedMessage"));
+ }
+
+ function leaveFlow() {
+ dismissDialog("confirm");
+ setCode("");
+ setFlow(SUMMARY);
+ }
+
+ return {
+ status, flow, action, proof, setProof, code, setCode, message, dialog,
+ openProof, closeProof, onProof, onConfirm, leaveFlow,
+ };
+}
+
+// An answer's codes, if it has any: a missing or empty list is no set.
+const isCodeSet = (codes: string[] | undefined): codes is string[] => Array.isArray(codes) && codes.length > 0;
+
+// A malformed code answers without a count (#1277 contract item 7).
+function incorrect(err: unknown, attemptsLeft: unknown): unknown {
+ if (!isProblem(err, 400, "Auth.EnrolmentCodeIncorrect")) return err;
+ return new Error(typeof attemptsLeft === "number"
+ ? i18n.t("account:codeIncorrectAttempts", { count: attemptsLeft })
+ : i18n.t("account:codeIncorrect"));
+}
+
+export type TwoFactor = ReturnType;
diff --git a/web/src/routes/help/HelpAdminSections.tsx b/web/src/routes/help/HelpAdminSections.tsx
index f6771b6d3..338a8aa94 100644
--- a/web/src/routes/help/HelpAdminSections.tsx
+++ b/web/src/routes/help/HelpAdminSections.tsx
@@ -75,6 +75,9 @@ export function HelpAdminSections({ openLink }: { openLink: (sectionId: string)
}} />
+
+ }} />
+
diff --git a/web/src/routes/helpGlossary.ts b/web/src/routes/helpGlossary.ts
index 72eafef40..dc316fc95 100644
--- a/web/src/routes/helpGlossary.ts
+++ b/web/src/routes/helpGlossary.ts
@@ -40,6 +40,11 @@ const ENTRIES = [
{ key: "Roles", group: "signingIn", spec: "Roles" },
{ key: "FlockScoping", group: "signingIn", spec: "Flock scoping" },
{ key: "DisabledUser", group: "signingIn", spec: "Disabled user" },
+ { key: "TwoFactorAuth", group: "signingIn", spec: "Two-factor authentication" },
+ { key: "AuthenticatorApp", group: "signingIn", spec: "Authenticator app" },
+ { key: "AuthenticatorCode", group: "signingIn", spec: "Authenticator code" },
+ { key: "RecoveryCode", group: "signingIn", spec: "Recovery code" },
+ { key: "TurnOffTwoFactor", group: "signingIn", spec: "Turn off two-factor authentication" },
{ key: "ResetTwoFactor", group: "signingIn", spec: "Reset two-factor authentication" },
{ key: "ConnectedApp", group: "signingIn", spec: "Connected app" },
// Flocks & daily entry
diff --git a/web/src/styles.skip-link.test.ts b/web/src/styles.skip-link.test.ts
new file mode 100644
index 000000000..f95bd9331
--- /dev/null
+++ b/web/src/styles.skip-link.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import postcss from "postcss";
+import type { Rule } from "postcss";
+import { createTheme } from "@mui/material/styles";
+import { readStylesheet } from "./test/stylesheet";
+
+// #1277 — the focused skip link opens over the docked rail. Chromium
+// showed the rail (the MUI drawer layer) painting over it; it must still sit
+// under a modal dialog, which covers the whole page.
+const root = postcss.parse(readStylesheet());
+
+function zIndexOf(selector: string): number {
+ let value: string | undefined;
+ root.walkRules((rule: Rule) => {
+ if (rule.selectors.map((s) => s.trim()).includes(selector))
+ rule.walkDecls("z-index", (d) => { value = d.value; });
+ });
+ if (value === undefined) throw new Error(`${selector} sets no z-index`);
+ return Number(value);
+}
+
+describe("the skip link's layer", () => {
+ it("is above the rail and below a modal dialog", () => {
+ const { zIndex } = createTheme();
+ const skip = zIndexOf(".skip-link");
+
+ expect(skip).toBeGreaterThan(zIndex.drawer);
+ expect(skip).toBeLessThan(zIndex.modal);
+ });
+});
diff --git a/web/src/styles/dialogs.css b/web/src/styles/dialogs.css
index e5de605eb..75a6f9a63 100644
--- a/web/src/styles/dialogs.css
+++ b/web/src/styles/dialogs.css
@@ -106,7 +106,9 @@
position: absolute;
top: -3rem;
left: 0.75rem;
- z-index: 1000;
+ /* Above MUI's drawer layer (1200), where the docked rail paints over it,
+ and below its modal layer (1300) (#1277). */
+ z-index: 1250;
background: var(--brand);
color: var(--on-brand);
padding: 0.6rem 1rem;
diff --git a/web/src/test/renderWithProviders.tsx b/web/src/test/renderWithProviders.tsx
index 8867e3233..28a900c36 100644
--- a/web/src/test/renderWithProviders.tsx
+++ b/web/src/test/renderWithProviders.tsx
@@ -9,6 +9,7 @@ import type { Account, Me } from "../api/cluckwork";
import { farmState } from "./fixtures";
import { setStoredToken } from "./jwt";
import { clearAccessToken } from "../auth/tokenStore";
+import { RecoveryCodesProvider } from "../routes/account/recoveryCodes";
// The default signed-in user for screen tests that don't care who is logged
// in. A test that DOES care passes `me: `; one that cares the identity
@@ -62,9 +63,11 @@ export function renderWithProviders(
return render(
+ {ui}
+ ,
);
diff --git a/web/src/test/setup.ts b/web/src/test/setup.ts
index 0e48a2d95..914b65950 100644
--- a/web/src/test/setup.ts
+++ b/web/src/test/setup.ts
@@ -25,13 +25,16 @@ beforeEach(() => {
vi.stubGlobal("indexedDB", createFakeIndexedDb());
});
-afterEach(() => {
+afterEach(async () => {
const { violations } = ledgerCellStyles(document);
const scrollingActions = Array.from(document.querySelectorAll(".MuiDialogContent-root .MuiDialogActions-root"))
.map(actions => actions.closest('[role="dialog"]')?.querySelector("h2")?.textContent ?? actions.textContent);
cleanup();
vi.unstubAllGlobals();
clearAccessToken();
+ // Imported here, not at the top, so a test file's vi.mock of the token path
+ // still takes effect.
+ (await import("../api/session")).resetSignOutForTests();
// A test that switches the UI language (e.g. via changeLanguage or the
// LanguageSelector) must not leak that language into the next test file's
// shared i18next singleton — reset to the default so every test starts en.
diff --git a/web/src/test/stepUpCallers.test.ts b/web/src/test/stepUpCallers.test.ts
index 795c44a2a..3fd8d9d60 100644
--- a/web/src/test/stepUpCallers.test.ts
+++ b/web/src/test/stepUpCallers.test.ts
@@ -105,12 +105,13 @@ describe("isProductionSource", () => {
});
describe("productionStepUpUses", () => {
- // Seven in the Users hooks (disable and enable share one) and /connect's.
+ // Seven in the Users hooks (disable and enable share one), /connect's and
+ // the Account page Security section's.
it("finds every call site in the SPA, each under its own name, and no other use", () => {
const { sites: found, violations } = productionStepUpUses();
expect(violations).toEqual([]);
- expect(found.length).toBeGreaterThanOrEqual(8);
+ expect(found.length).toBeGreaterThanOrEqual(9);
expect(new Set(found).size).toBe(found.length);
});
});