From d103f41f41bb06a4fcd09b3bb6ef0c13fd56259b Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 01:50:04 +0000
Subject: [PATCH 01/45] feat(web): draw the enrolment QR code with uqr
The otpauth URI becomes an SVG path from uqr's module matrix at level M, so the key never leaves the page. G2.6 reads #1278's worst-case fixture and asserts version 21 or lower, with and without the three spelled-out defaults.
Refs #1277
---
web/package-lock.json | 7 ++++++
web/package.json | 1 +
web/src/routes/account/TwoFactorQr.test.ts | 26 ++++++++++++++++++++++
web/src/routes/account/TwoFactorQr.tsx | 24 ++++++++++++++++++++
4 files changed, 58 insertions(+)
create mode 100644 web/src/routes/account/TwoFactorQr.test.ts
create mode 100644 web/src/routes/account/TwoFactorQr.tsx
diff --git a/web/package-lock.json b/web/package-lock.json
index 2ba23d383..c2bd0b383 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -19,6 +19,7 @@
"react-dom": "^19.3.1",
"react-i18next": "^17.1.9",
"react-router": "^8.5.0",
+ "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 97f17aa07..e17975b8b 100644
--- a/web/package.json
+++ b/web/package.json
@@ -28,6 +28,7 @@
"react-dom": "^19.3.1",
"react-i18next": "^17.1.9",
"react-router": "^8.5.0",
+ "uqr": "^0.1.3",
"workbox-expiration": "^7.4.1"
},
"devDependencies": {
diff --git a/web/src/routes/account/TwoFactorQr.test.ts b/web/src/routes/account/TwoFactorQr.test.ts
new file mode 100644
index 000000000..fa102ba1d
--- /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.ecc).toBe("M");
+ 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..c29dc79cc
--- /dev/null
+++ b/web/src/routes/account/TwoFactorQr.tsx
@@ -0,0 +1,24 @@
+import { useMemo } from "react";
+import { Box } from "@mui/material";
+import { encode } from "uqr";
+
+// #1274 decision 21 — level M, as the worst-case URI was measured against
+// (G2.6), and the four-module quiet zone the QR specification asks for.
+export const QR_OPTIONS = { ecc: "M", 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 (
+
+
+
+ );
+}
From c77947b68b91ef78242756d9af276def125b8dbf Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 01:50:23 +0000
Subject: [PATCH 02/45] feat(web): call the two-factor status, start, confirm,
recovery-code and turn-off routes
Confirm and turn-off rotate the session as change-password does, so all three share one adopting write: the cookie lock, the generation check, the stale-cookie revoke and the farm binding. A two-factor write that answers 401 Auth.CredentialsSuperseded is never refreshed and resent; the status read and an expired token's plain 401 still are.
Refs #1277
---
web/src/api/client.ts | 10 +-
web/src/api/cluckwork.ts | 1 +
web/src/api/cluckwork/twoFactor.ts | 25 +++++
web/src/api/refresh.ts | 10 +-
web/src/api/request.ts | 7 ++
web/src/api/session.ts | 71 +++++++++-----
web/src/api/twoFactor.test.ts | 152 +++++++++++++++++++++++++++++
7 files changed, 242 insertions(+), 34 deletions(-)
create mode 100644 web/src/api/cluckwork/twoFactor.ts
create mode 100644 web/src/api/twoFactor.test.ts
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index 2801b8347..0b38e5eee 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 } 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..32fb34a04
--- /dev/null
+++ b/web/src/api/cluckwork/twoFactor.ts
@@ -0,0 +1,25 @@
+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);
+
+export const startTwoFactor = (key: string, stepUpToken: string) =>
+ apiPost("/auth/two-factor/start", undefined, key, { [STEP_UP_HEADER]: stepUpToken });
+
+export const regenerateRecoveryCodes = (key: string, stepUpToken: string) =>
+ apiPost<{ recoveryCodes: string[] }>("/auth/two-factor/recovery-codes", undefined, key, { [STEP_UP_HEADER]: stepUpToken });
diff --git a/web/src/api/refresh.ts b/web/src/api/refresh.ts
index f8791e1e4..9c9afaff2 100644
--- a/web/src/api/refresh.ts
+++ b/web/src/api/refresh.ts
@@ -325,6 +325,14 @@ export async function apiGetBlob(
}
}
+// #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 = {},
@@ -339,7 +347,7 @@ export async function apiFetch(
try {
return await raw(path, init, token);
} catch (err) {
- if (!(err instanceof ApiError) || err.status !== 401) throw err;
+ if (!(err instanceof ApiError) || err.status !== 401 || isUnresendable(path, init, err)) 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.
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..d8f045c8b 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";
@@ -259,35 +259,55 @@ 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.
+export function confirmTwoFactor(code: string, idempotencyKey: string): Promise<{ recoveryCodes?: string[] }> {
+ return adoptingWrite("/auth/two-factor/confirm", {
+ method: "POST",
+ headers: { "Idempotency-Key": idempotencyKey },
+ 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(idempotencyKey: string, stepUpToken: string): Promise {
+ await adoptingWrite("/auth/two-factor", {
+ method: "DELETE",
+ headers: { "Idempotency-Key": idempotencyKey, [STEP_UP_HEADER]: stepUpToken },
+ });
+}
+
+// A write whose answer rotates this farm's refresh cookie and hands this tab a
+// fresh pair; undefined for a 204, which rotates nothing.
+async function adoptingWrite(path: string, init: RequestInit): 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) 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 +315,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
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
new file mode 100644
index 000000000..6328f36ae
--- /dev/null
+++ b/web/src/api/twoFactor.test.ts
@@ -0,0 +1,152 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { confirmTwoFactor, setOnTokensChanged, setOnUnauthenticated, STEP_UP_HEADER, turnOffTwoFactor } from "./client";
+import { getTwoFactorStatus, regenerateRecoveryCodes, startTwoFactor } from "./cluckwork";
+import { clearAccessToken, clearBoundAccount, getAccessToken, getBoundAccountId, setAccessToken } from "../auth/tokenStore";
+import { freshCode } from "../test/codes";
+
+// #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);
+
+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 its 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();
+ const key = crypto.randomUUID();
+
+ await expect(confirmTwoFactor(code, key)).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")).toBe(key);
+ 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(), crypto.randomUUID())).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(), crypto.randomUUID()))
+ .rejects.toMatchObject({ status: 400, title: "Auth.EnrolmentCodeIncorrect", extensions: { attemptsLeft: 3 } });
+ expect(getAccessToken()).toBe("at1");
+ });
+});
+
+describe("turnOffTwoFactor", () => {
+ it("sends DELETE with the grant and the key, and adopts the 200's fresh pair", async () => {
+ const fresh = token("acct-C");
+ fetchMock.mockResolvedValueOnce(pair(fresh));
+ const key = crypto.randomUUID();
+ const grant = crypto.randomUUID();
+
+ await turnOffTwoFactor(key, 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")).toBe(key);
+ 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(), crypto.randomUUID());
+
+ expect(getAccessToken()).toBe("at1");
+ expect(onTokens).not.toHaveBeenCalled();
+ });
+});
+
+// #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(), crypto.randomUUID())],
+ ["confirm", "/auth/two-factor/confirm", () => confirmTwoFactor(freshCode(), crypto.randomUUID())],
+ ["start", "/auth/two-factor/start", () => startTwoFactor(crypto.randomUUID(), crypto.randomUUID())],
+ ["regenerate", "/auth/two-factor/recovery-codes", () => regenerateRecoveryCodes(crypto.randomUUID(), 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);
+ });
+
+ 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: [] }));
+ const key = crypto.randomUUID();
+
+ await regenerateRecoveryCodes(key, crypto.randomUUID());
+
+ const sent = to("/auth/two-factor/recovery-codes");
+ expect(sent).toHaveLength(2);
+ expect(sent.map((call) => header(call, "Idempotency-Key"))).toEqual([key, key]);
+ });
+});
From a188323286b51882a26c0b22f1a9d5156c9d2644 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 01:50:40 +0000
Subject: [PATCH 03/45] feat(web): turn two-factor authentication on from the
Account page
A Security section shows two-factor on or off and the recovery codes left, warns from 2 or fewer, and offers Set up, Regenerate, Replace authenticator app and Turn off, each after a step-up in the lab's Confirm it's you form. Set-up shows the QR code, the key and a phone link, warns that other devices and connected apps sign out, and confirms a code; a first enrolment then shows the ten recovery codes once, with copy, download and a saved confirmation.
Adds the five #1277 glossary terms with their in-app entries and Help text in en, es and tl.
Refs #1277
---
specs/product/GLOSSARY.md | 41 ++
web/src/i18n/en.ts | 103 +++++
web/src/i18n/es.ts | 105 +++++
web/src/i18n/tl.ts | 105 +++++
web/src/lib/saveBlob.ts | 10 +
web/src/routes/AccountPage.tsx | 11 +
web/src/routes/ExportPage.tsx | 12 +-
web/src/routes/UsersPage.test.tsx | 9 +-
web/src/routes/account/Security.test.tsx | 471 ++++++++++++++++++++++
web/src/routes/account/SecurityPanel.tsx | 149 +++++++
web/src/routes/account/TwoFactorFlow.tsx | 155 +++++++
web/src/routes/account/useTwoFactor.ts | 176 ++++++++
web/src/routes/help/HelpAdminSections.tsx | 3 +
web/src/routes/helpGlossary.ts | 5 +
web/src/test/stepUpCallers.test.ts | 5 +-
15 files changed, 1343 insertions(+), 17 deletions(-)
create mode 100644 web/src/lib/saveBlob.ts
create mode 100644 web/src/routes/account/Security.test.tsx
create mode 100644 web/src/routes/account/SecurityPanel.tsx
create mode 100644 web/src/routes/account/TwoFactorFlow.tsx
create mode 100644 web/src/routes/account/useTwoFactor.ts
diff --git a/specs/product/GLOSSARY.md b/specs/product/GLOSSARY.md
index e3503357f..5ed9f4d20 100644
--- a/specs/product/GLOSSARY.md
+++ b/specs/product/GLOSSARY.md
@@ -1380,6 +1380,47 @@ 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; 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 in four groups of four, 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
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 1ef477510..fa15c44c2 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -290,6 +290,78 @@ export const en = {
passwordMismatchError: "The new passwords don't match.",
passwordTooShortError: "The new password must be at least {{min}} characters.",
passwordChangedMessage: "Password changed. Any other devices have been signed out.",
+
+ // #1277 — the Security section: the user's own two-factor authentication.
+ securityHeading: "Security",
+ twoFactorHeading: "Two-factor authentication",
+ twoFactorHint: "Add a code from your authenticator app when you sign in.",
+ twoFactorOn: "On",
+ twoFactorOff: "Off",
+ twoFactorOffHint: "You sign in with your password only.",
+ setUpButton: "Set up",
+ statusLoadFailed: "Your two-factor authentication could not be loaded.",
+ statusRetry: "Try again",
+ recoveryCodesHeading: "Recovery codes",
+ recoveryCodesLeft_one: "{{count}} code left",
+ recoveryCodesLeft_other: "{{count}} codes left",
+ recoveryCodesCaption: "Each code works once if you cannot use your authenticator app.",
+ recoveryCodesLow_one: "You have {{count}} recovery code left. Save a new set before you need it.",
+ recoveryCodesLow_other: "You have {{count}} recovery codes left. Save a new set before you need it.",
+ regenerateButton: "Regenerate",
+ replaceHint: "New phone? Move Cluckwork to its authenticator app.",
+ replaceButton: "Replace authenticator app",
+ turnOffHint: "Remove the extra code at sign-in.",
+ turnOffButton: "Turn off",
+ setUpTitle: "Set up two-factor authentication",
+ setUpBody: "You add Cluckwork to an authenticator app on your phone, then confirm a code from it.",
+ replaceTitle: "Replace your authenticator app?",
+ replaceBody: "Your current authenticator app keeps working until you confirm a code from the new one.",
+ regenerateTitle: "Regenerate recovery codes?",
+ regenerateBody: "The new set replaces every code you saved before. Save the new codes after this step.",
+ turnOffTitle: "Turn off two-factor authentication?",
+ turnOffBody: "You will sign in with your password only. Your other devices and connected apps will need to sign in again.",
+ proofHintPassword: "Enter your password to confirm this change.",
+ proofHint: "Enter your password and a code from your authenticator app, or a recovery code, to confirm this change.",
+ continueButton: "Continue",
+ flowEyebrow: "Account / Security",
+ enrolHeading: "Set up two-factor authentication",
+ replaceHeading: "Replace your authenticator app",
+ scanHeading: "Add Cluckwork",
+ scanHint: "Open your authenticator app and scan this QR code.",
+ qrLabel: "QR code to add Cluckwork to your authenticator app",
+ cannotScan: "Cannot scan the QR code?",
+ keyHint: "In your authenticator app, add a set-up key for Cluckwork.",
+ copyKeyButton: "Copy key",
+ keyCopied: "Key copied.",
+ openInAppLink: "Open in your authenticator app",
+ confirmHeading: "Confirm a code",
+ confirmHint: "Enter the code for Cluckwork in your authenticator app.",
+ codeLabel: "Authenticator code",
+ signOutWarning: "Your other devices and connected apps will need to sign in again.",
+ confirmButton: "Confirm code",
+ codeIncorrect: "That code did not work. Try the next code in your app.",
+ codeIncorrectAttempts_one: "That code did not work. Try the next code in your app. {{count}} try left.",
+ codeIncorrectAttempts_other: "That code did not work. Try the next code in your app. {{count}} tries left.",
+ setUpExpired: "This set-up expired. Start again to get a new QR code.",
+ setUpTooManyAttempts: "Too many wrong codes. Start again to get a new QR code.",
+ startAgainButton: "Start again",
+ codesHeading: "Save your recovery codes",
+ codesOn: "Two-factor authentication is on.",
+ codesReplaced: "These replace your previous codes. The old codes no longer work.",
+ codesHint: "Use one if you cannot use your authenticator app. Each code works once. You cannot view these again.",
+ codesListLabel: "Recovery codes",
+ copyCodesButton: "Copy all codes",
+ codesCopied: "Codes copied. Keep them somewhere safe.",
+ copyFailed: "Could not copy. Select the text and copy it yourself.",
+ downloadButton: "Download codes",
+ codesDownloaded: "Download started. Check the file before you leave.",
+ codesFileTitle: "Cluckwork recovery codes for {{email}}",
+ savedCheckbox: "I saved my recovery codes somewhere safe.",
+ doneButton: "Done",
+ replacedMessage: "Your new authenticator app is set up. The old one no longer works.",
+ turnedOffMessage: "Two-factor authentication is off.",
+ regenerateNotEnabled: "Two-factor authentication is not on for your account, so it has no recovery codes to replace.",
+ sessionChanged: "Your sign-in changed while this was sent, so nothing changed. Try again.",
},
// #799 — Connected apps: the Account panel and the Owner's farm-wide page.
connectedApps: {
@@ -4009,6 +4081,13 @@ export const en = {
"Daily Entry counting unit — how much YOUR +/− taps count by, overriding the farm "
+ "default from Settings. Pick a pack unit like Tray to count by the tray, or follow the farm "
+ "default so a later farm-wide change follows you automatically.",
+ accountSecurity:
+ "Security turns on two-factor authentication with Set up: scan the QR "
+ + "code with your authenticator app, enter its code, then save the ten recovery codes it shows once. "
+ + "Once it's on, Regenerate replaces your recovery codes, Replace authenticator "
+ + "app moves Cluckwork to a new phone, and Turn off removes it. Each asks for "
+ + "your password and a code first. Turning it on, replacing the app and turning it off sign out your "
+ + "other devices and connected apps.",
// Install on a phone
installHeading: "Install on a phone",
@@ -4533,6 +4612,30 @@ export const en = {
+ "those old sessions — anything issued before the disable never works again. The account's last "
+ "active Admin (owner) can't be disabled, and nobody can disable themselves.",
+ // #1277
+ glossaryTwoFactorAuthTerm: "Two-factor authentication",
+ glossaryTwoFactorAuthDef:
+ "Signing in with your password and a second proof from your phone: a code from your authenticator app, "
+ + "or a recovery code without the phone. Turn it on in Account, Security, with Set up. Turning it on signs "
+ + "out your other devices and connected apps.",
+ glossaryAuthenticatorAppTerm: "Authenticator app",
+ glossaryAuthenticatorAppDef:
+ "The app on your phone that shows a new 6-digit code every 30 seconds. Cluckwork appears in it with your "
+ + "farm's name and your email.",
+ glossaryAuthenticatorCodeTerm: "Authenticator code",
+ glossaryAuthenticatorCodeDef:
+ "The 6-digit code your authenticator app shows for Cluckwork. Each one works once, so after a refusal wait "
+ + "for the next one.",
+ glossaryRecoveryCodeTerm: "Recovery code",
+ glossaryRecoveryCodeDef:
+ "One of ten codes you get once, when you turn on two-factor authentication, for when you can't use your "
+ + "phone. Each works once. Account, Security, shows how many are left, and Regenerate replaces the set.",
+ glossaryTurnOffTwoFactorTerm: "Turn off two-factor authentication",
+ glossaryTurnOffTwoFactorDef:
+ "Removing your own second factor, with Turn off in Account, Security. Your authenticator app and recovery "
+ + "codes stop working, your other devices and connected apps are signed out, and you sign in with your "
+ + "password only.",
+
// #1280
glossaryResetTwoFactorTerm: "Reset two-factor authentication",
glossaryResetTwoFactorDef:
diff --git a/web/src/i18n/es.ts b/web/src/i18n/es.ts
index 8959a3fd2..79a047d64 100644
--- a/web/src/i18n/es.ts
+++ b/web/src/i18n/es.ts
@@ -221,6 +221,78 @@ export const es = {
passwordMismatchError: "Las nuevas contraseñas no coinciden.",
passwordTooShortError: "La nueva contraseña debe tener al menos {{min}} caracteres.",
passwordChangedMessage: "Contraseña cambiada. Se cerró la sesión en los demás dispositivos.",
+
+ // #1277 — la sección Seguridad: la autenticación en dos pasos del usuario.
+ securityHeading: "Seguridad",
+ twoFactorHeading: "Autenticación en dos pasos",
+ twoFactorHint: "Agregue un código de su aplicación de autenticación al iniciar sesión.",
+ twoFactorOn: "Activada",
+ twoFactorOff: "Desactivada",
+ twoFactorOffHint: "Inicia sesión solo con su contraseña.",
+ setUpButton: "Configurar",
+ statusLoadFailed: "No se pudo cargar su autenticación en dos pasos.",
+ statusRetry: "Intentar de nuevo",
+ recoveryCodesHeading: "Códigos de recuperación",
+ recoveryCodesLeft_one: "Queda {{count}} código",
+ recoveryCodesLeft_other: "Quedan {{count}} códigos",
+ recoveryCodesCaption: "Cada código funciona una vez si no puede usar su aplicación de autenticación.",
+ recoveryCodesLow_one: "Le queda {{count}} código de recuperación. Guarde un nuevo juego antes de necesitarlo.",
+ recoveryCodesLow_other: "Le quedan {{count}} códigos de recuperación. Guarde un nuevo juego antes de necesitarlo.",
+ regenerateButton: "Regenerar",
+ replaceHint: "¿Teléfono nuevo? Pase Cluckwork a su aplicación de autenticación.",
+ replaceButton: "Reemplazar aplicación de autenticación",
+ turnOffHint: "Quite el código adicional al iniciar sesión.",
+ turnOffButton: "Desactivar",
+ setUpTitle: "Configurar la autenticación en dos pasos",
+ setUpBody: "Agregará Cluckwork a una aplicación de autenticación en su teléfono y luego confirmará un código de ella.",
+ replaceTitle: "¿Reemplazar su aplicación de autenticación?",
+ replaceBody: "Su aplicación de autenticación actual sigue funcionando hasta que confirme un código de la nueva.",
+ regenerateTitle: "¿Regenerar los códigos de recuperación?",
+ regenerateBody: "El nuevo juego reemplaza todos los códigos que guardó antes. Guarde los nuevos códigos después de este paso.",
+ turnOffTitle: "¿Desactivar la autenticación en dos pasos?",
+ turnOffBody: "Iniciará sesión solo con su contraseña. Sus otros dispositivos y aplicaciones conectadas tendrán que iniciar sesión de nuevo.",
+ proofHintPassword: "Ingrese su contraseña para confirmar este cambio.",
+ proofHint: "Ingrese su contraseña y un código de su aplicación de autenticación, o un código de recuperación, para confirmar este cambio.",
+ continueButton: "Continuar",
+ flowEyebrow: "Cuenta / Seguridad",
+ enrolHeading: "Configurar la autenticación en dos pasos",
+ replaceHeading: "Reemplazar su aplicación de autenticación",
+ scanHeading: "Agregar Cluckwork",
+ scanHint: "Abra su aplicación de autenticación y escanee este código QR.",
+ qrLabel: "Código QR para agregar Cluckwork a su aplicación de autenticación",
+ cannotScan: "¿No puede escanear el código QR?",
+ keyHint: "En su aplicación de autenticación, agregue una clave de configuración para Cluckwork.",
+ copyKeyButton: "Copiar clave",
+ keyCopied: "Clave copiada.",
+ openInAppLink: "Abrir en su aplicación de autenticación",
+ confirmHeading: "Confirmar un código",
+ confirmHint: "Ingrese el código de Cluckwork que muestra su aplicación de autenticación.",
+ codeLabel: "Código de autenticación",
+ signOutWarning: "Sus otros dispositivos y aplicaciones conectadas tendrán que iniciar sesión de nuevo.",
+ confirmButton: "Confirmar código",
+ codeIncorrect: "Ese código no funcionó. Pruebe el siguiente código de su aplicación.",
+ codeIncorrectAttempts_one: "Ese código no funcionó. Pruebe el siguiente código de su aplicación. Queda {{count}} intento.",
+ codeIncorrectAttempts_other: "Ese código no funcionó. Pruebe el siguiente código de su aplicación. Quedan {{count}} intentos.",
+ setUpExpired: "Esta configuración caducó. Empiece de nuevo para obtener un código QR nuevo.",
+ setUpTooManyAttempts: "Demasiados códigos incorrectos. Empiece de nuevo para obtener un código QR nuevo.",
+ startAgainButton: "Empezar de nuevo",
+ codesHeading: "Guarde sus códigos de recuperación",
+ codesOn: "La autenticación en dos pasos está activada.",
+ codesReplaced: "Estos reemplazan sus códigos anteriores. Los códigos antiguos ya no funcionan.",
+ codesHint: "Use uno si no puede usar su aplicación de autenticación. Cada código funciona una vez. No podrá verlos de nuevo.",
+ codesListLabel: "Códigos de recuperación",
+ copyCodesButton: "Copiar todos los códigos",
+ codesCopied: "Códigos copiados. Guárdelos en un lugar seguro.",
+ copyFailed: "No se pudo copiar. Seleccione el texto y cópielo usted.",
+ downloadButton: "Descargar códigos",
+ codesDownloaded: "Descarga iniciada. Revise el archivo antes de salir.",
+ codesFileTitle: "Códigos de recuperación de Cluckwork para {{email}}",
+ savedCheckbox: "Guardé mis códigos de recuperación en un lugar seguro.",
+ doneButton: "Listo",
+ replacedMessage: "Su nueva aplicación de autenticación está configurada. La anterior ya no funciona.",
+ turnedOffMessage: "La autenticación en dos pasos está desactivada.",
+ regenerateNotEnabled: "La autenticación en dos pasos no está activada en su cuenta, así que no tiene códigos de recuperación que reemplazar.",
+ sessionChanged: "Su inicio de sesión cambió mientras se enviaba esto, así que no cambió nada. Inténtelo de nuevo.",
},
// #799 — Connected apps: the Account panel and the Owner's farm-wide page.
connectedApps: {
@@ -3298,6 +3370,14 @@ export const es = {
+ "anulando el valor predeterminado de la granja en Configuración. Elija una unidad de empaque como "
+ "Tray para contar por bandeja, o siga el predeterminado de la granja para que un cambio posterior "
+ "en toda la granja le aplique automáticamente.",
+ accountSecurity:
+ "Seguridad activa la autenticación en dos pasos con Configurar: escanee "
+ + "el código QR con su aplicación de autenticación, ingrese su código y guarde los diez códigos de "
+ + "recuperación que muestra una sola vez. Una vez activada, Regenerar reemplaza sus "
+ + "códigos de recuperación, Reemplazar aplicación de autenticación pasa Cluckwork a un "
+ + "teléfono nuevo y Desactivar la quita. Cada uno pide antes su contraseña y un código. "
+ + "Activarla, reemplazar la aplicación y desactivarla cierran la sesión en sus otros dispositivos y "
+ + "aplicaciones conectadas.",
installHeading: "Instalar en un teléfono",
installIntro:
@@ -3873,6 +3953,31 @@ export const es = {
+ "Administrador (propietario) activo de la cuenta no puede deshabilitarse, y nadie puede "
+ "deshabilitarse a sí mismo.",
+ // #1277
+ glossaryTwoFactorAuthTerm: "Autenticación en dos pasos",
+ glossaryTwoFactorAuthDef:
+ "Iniciar sesión con su contraseña y una segunda prueba de su teléfono: un código de su aplicación de "
+ + "autenticación, o un código de recuperación sin el teléfono. Actívela en Cuenta, Seguridad, con "
+ + "Configurar. Al activarla se cierra la sesión en sus otros dispositivos y aplicaciones conectadas.",
+ glossaryAuthenticatorAppTerm: "Aplicación de autenticación",
+ glossaryAuthenticatorAppDef:
+ "La aplicación de su teléfono que muestra un código nuevo de 6 dígitos cada 30 segundos. Cluckwork aparece "
+ + "en ella con el nombre de su granja y su correo.",
+ glossaryAuthenticatorCodeTerm: "Código de autenticación",
+ glossaryAuthenticatorCodeDef:
+ "El código de 6 dígitos que su aplicación de autenticación muestra para Cluckwork. Cada uno funciona una "
+ + "vez, así que después de un rechazo espere al siguiente.",
+ glossaryRecoveryCodeTerm: "Código de recuperación",
+ glossaryRecoveryCodeDef:
+ "Uno de diez códigos que recibe una vez, al activar la autenticación en dos pasos, para cuando no puede "
+ + "usar su teléfono. Cada uno funciona una vez. Cuenta, Seguridad, muestra cuántos quedan, y Regenerar "
+ + "reemplaza el juego.",
+ glossaryTurnOffTwoFactorTerm: "Desactivar la autenticación en dos pasos",
+ glossaryTurnOffTwoFactorDef:
+ "Quitar su propio segundo factor, con Desactivar en Cuenta, Seguridad. Su aplicación de autenticación y "
+ + "sus códigos de recuperación dejan de funcionar, se cierra la sesión en sus otros dispositivos y "
+ + "aplicaciones conectadas, e inicia sesión solo con su contraseña.",
+
glossaryResetTwoFactorTerm: "Restablecer la autenticación en dos pasos",
glossaryResetTwoFactorDef:
"Un propietario quita la autenticación en dos pasos de otro usuario para que pueda volver a "
diff --git a/web/src/i18n/tl.ts b/web/src/i18n/tl.ts
index d438819ae..a67db9db2 100644
--- a/web/src/i18n/tl.ts
+++ b/web/src/i18n/tl.ts
@@ -230,6 +230,78 @@ export const tl = {
passwordMismatchError: "Hindi magkatugma ang mga bagong password.",
passwordTooShortError: "Dapat hindi bababa sa {{min}} na karakter ang bagong password.",
passwordChangedMessage: "Napalitan ang password. Na-sign out na ang ibang mga device.",
+
+ // #1277 — ang Security section: ang sariling two-factor authentication ng user.
+ securityHeading: "Seguridad",
+ twoFactorHeading: "Two-factor authentication",
+ twoFactorHint: "Magdagdag ng code mula sa iyong authenticator app kapag nagsa-sign in ka.",
+ twoFactorOn: "Naka-on",
+ twoFactorOff: "Naka-off",
+ twoFactorOffHint: "Password lang ang gamit mo sa pag-sign in.",
+ setUpButton: "I-set up",
+ statusLoadFailed: "Hindi ma-load ang iyong two-factor authentication.",
+ statusRetry: "Subukan ulit",
+ recoveryCodesHeading: "Mga recovery code",
+ recoveryCodesLeft_one: "{{count}} code ang natitira",
+ recoveryCodesLeft_other: "{{count}} code ang natitira",
+ recoveryCodesCaption: "Isang beses gumagana ang bawat code kung hindi mo magamit ang iyong authenticator app.",
+ recoveryCodesLow_one: "{{count}} recovery code na lang ang natitira sa iyo. Mag-save ng bagong set bago mo ito kailanganin.",
+ recoveryCodesLow_other: "{{count}} recovery code na lang ang natitira sa iyo. Mag-save ng bagong set bago mo ito kailanganin.",
+ regenerateButton: "Gumawa ulit",
+ replaceHint: "Bagong phone? Ilipat ang Cluckwork sa authenticator app nito.",
+ replaceButton: "Palitan ang authenticator app",
+ turnOffHint: "Alisin ang dagdag na code sa pag-sign in.",
+ turnOffButton: "I-off",
+ setUpTitle: "I-set up ang two-factor authentication",
+ setUpBody: "Idaragdag mo ang Cluckwork sa isang authenticator app sa iyong phone, tapos kukumpirmahin mo ang isang code mula rito.",
+ replaceTitle: "Palitan ang iyong authenticator app?",
+ replaceBody: "Gumagana pa rin ang kasalukuyan mong authenticator app hanggang makumpirma mo ang code mula sa bago.",
+ regenerateTitle: "Gumawa ulit ng mga recovery code?",
+ regenerateBody: "Papalitan ng bagong set ang lahat ng code na na-save mo dati. I-save ang mga bagong code pagkatapos ng hakbang na ito.",
+ turnOffTitle: "I-off ang two-factor authentication?",
+ turnOffBody: "Password lang ang gagamitin mo sa pag-sign in. Kailangang mag-sign in ulit ng iba mo pang device at mga connected app.",
+ proofHintPassword: "Ilagay ang iyong password para kumpirmahin ang pagbabagong ito.",
+ proofHint: "Ilagay ang iyong password at isang code mula sa iyong authenticator app, o isang recovery code, para kumpirmahin ang pagbabagong ito.",
+ continueButton: "Magpatuloy",
+ flowEyebrow: "Account / Seguridad",
+ enrolHeading: "I-set up ang two-factor authentication",
+ replaceHeading: "Palitan ang iyong authenticator app",
+ scanHeading: "Idagdag ang Cluckwork",
+ scanHint: "Buksan ang iyong authenticator app at i-scan ang QR code na ito.",
+ qrLabel: "QR code para idagdag ang Cluckwork sa iyong authenticator app",
+ cannotScan: "Hindi ma-scan ang QR code?",
+ keyHint: "Sa iyong authenticator app, magdagdag ng set-up key para sa Cluckwork.",
+ copyKeyButton: "Kopyahin ang key",
+ keyCopied: "Nakopya ang key.",
+ openInAppLink: "Buksan sa iyong authenticator app",
+ confirmHeading: "Kumpirmahin ang isang code",
+ confirmHint: "Ilagay ang code para sa Cluckwork mula sa iyong authenticator app.",
+ codeLabel: "Authenticator code",
+ signOutWarning: "Kailangang mag-sign in ulit ng iba mo pang device at mga connected app.",
+ confirmButton: "Kumpirmahin ang code",
+ codeIncorrect: "Hindi gumana ang code na iyon. Subukan ang susunod na code sa iyong app.",
+ codeIncorrectAttempts_one: "Hindi gumana ang code na iyon. Subukan ang susunod na code sa iyong app. {{count}} subok na lang.",
+ codeIncorrectAttempts_other: "Hindi gumana ang code na iyon. Subukan ang susunod na code sa iyong app. {{count}} subok na lang.",
+ setUpExpired: "Nag-expire ang set-up na ito. Magsimula ulit para makakuha ng bagong QR code.",
+ setUpTooManyAttempts: "Sobrang daming maling code. Magsimula ulit para makakuha ng bagong QR code.",
+ startAgainButton: "Magsimula ulit",
+ codesHeading: "I-save ang iyong mga recovery code",
+ codesOn: "Naka-on na ang two-factor authentication.",
+ codesReplaced: "Papalitan ng mga ito ang dati mong mga code. Hindi na gumagana ang mga lumang code.",
+ codesHint: "Gumamit ng isa kung hindi mo magamit ang iyong authenticator app. Isang beses gumagana ang bawat code. Hindi mo na ito makikita ulit.",
+ codesListLabel: "Mga recovery code",
+ copyCodesButton: "Kopyahin lahat ng code",
+ codesCopied: "Nakopya ang mga code. Itago ang mga ito sa ligtas na lugar.",
+ copyFailed: "Hindi makopya. Piliin ang text at ikaw na ang kumopya.",
+ downloadButton: "I-download ang mga code",
+ codesDownloaded: "Nagsimula ang download. Tingnan ang file bago ka umalis.",
+ codesFileTitle: "Mga recovery code ng Cluckwork para kay {{email}}",
+ savedCheckbox: "Na-save ko ang aking mga recovery code sa ligtas na lugar.",
+ doneButton: "Tapos na",
+ replacedMessage: "Naka-set up na ang bago mong authenticator app. Hindi na gumagana ang luma.",
+ turnedOffMessage: "Naka-off na ang two-factor authentication.",
+ regenerateNotEnabled: "Hindi naka-on ang two-factor authentication sa iyong account, kaya wala itong recovery code na papalitan.",
+ sessionChanged: "Nagbago ang iyong sign-in habang ipinapadala ito, kaya walang nagbago. Subukan ulit.",
},
// #799 — Connected apps: the Account panel and the Owner's farm-wide page.
connectedApps: {
@@ -3418,6 +3490,14 @@ export const tl = {
+ "+/−, na nag-o-override sa default ng bukid mula sa Settings. Pumili ng pack unit tulad ng Tray "
+ "para magbilang bawat tray, o sundin ang default ng bukid para awtomatikong sumunod sa iyo ang "
+ "isang susunod na pagbabago sa buong bukid.",
+ accountSecurity:
+ "Ino-on ng Seguridad ang two-factor authentication gamit ang I-set up: "
+ + "i-scan ang QR code gamit ang iyong authenticator app, ilagay ang code nito, tapos i-save ang sampung "
+ + "recovery code na isang beses lang nitong ipapakita. Kapag naka-on na, pinapalitan ng Gumawa "
+ + "ulit ang iyong mga recovery code, inililipat ng Palitan ang authenticator app "
+ + "ang Cluckwork sa bagong phone, at inaalis ito ng I-off. Hinihingi muna ng bawat isa "
+ + "ang iyong password at isang code. Ang pag-on, pagpapalit ng app at pag-off ay nagsa-sign out sa iba "
+ + "mo pang device at mga connected app.",
installHeading: "Pag-install sa Telepono",
installIntro:
@@ -4013,6 +4093,31 @@ export const tl = {
+ "kahit anong ibinigay bago ang pag-disable ay hindi na kailanman gagana. Hindi puwedeng i-disable "
+ "ang huling aktibong Admin (may-ari) ng account, at walang puwedeng mag-disable sa sarili niya.",
+ // #1277
+ glossaryTwoFactorAuthTerm: "Two-factor authentication",
+ glossaryTwoFactorAuthDef:
+ "Pag-sign in gamit ang iyong password at pangalawang patunay mula sa iyong phone: isang code mula sa "
+ + "iyong authenticator app, o isang recovery code kung wala ang phone. I-on ito sa Account, Seguridad, "
+ + "gamit ang I-set up. Kapag in-on ito, masa-sign out ang iba mo pang device at mga connected app.",
+ glossaryAuthenticatorAppTerm: "Authenticator app",
+ glossaryAuthenticatorAppDef:
+ "Ang app sa iyong phone na nagpapakita ng bagong 6-digit na code bawat 30 segundo. Lumalabas dito ang "
+ + "Cluckwork kasama ang pangalan ng iyong farm at ang iyong email.",
+ glossaryAuthenticatorCodeTerm: "Authenticator code",
+ glossaryAuthenticatorCodeDef:
+ "Ang 6-digit na code na ipinapakita ng iyong authenticator app para sa Cluckwork. Isang beses lang "
+ + "gumagana ang bawat isa, kaya pagkatapos ng pagtanggi, hintayin ang susunod.",
+ glossaryRecoveryCodeTerm: "Recovery code",
+ glossaryRecoveryCodeDef:
+ "Isa sa sampung code na isang beses mong makukuha, kapag in-on mo ang two-factor authentication, para sa "
+ + "oras na hindi mo magamit ang iyong phone. Isang beses gumagana ang bawat isa. Ipinapakita ng Account, "
+ + "Seguridad, kung ilan ang natitira, at pinapalitan ng Gumawa ulit ang buong set.",
+ glossaryTurnOffTwoFactorTerm: "I-off ang two-factor authentication",
+ glossaryTurnOffTwoFactorDef:
+ "Pag-alis ng sarili mong pangalawang factor, gamit ang I-off sa Account, Seguridad. Hihinto sa paggana "
+ + "ang iyong authenticator app at mga recovery code, masa-sign out ang iba mo pang device at mga connected "
+ + "app, at password lang ang gagamitin mo sa pag-sign in.",
+
glossaryResetTwoFactorTerm: "Pag-reset ng two-factor authentication",
glossaryResetTwoFactorDef:
"Inaalis ng isang Owner ang two-factor authentication ng ibang user para ma-set up niya ito ulit, "
diff --git a/web/src/lib/saveBlob.ts b/web/src/lib/saveBlob.ts
new file mode 100644
index 000000000..075adda10
--- /dev/null
+++ b/web/src/lib/saveBlob.ts
@@ -0,0 +1,10 @@
+export 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);
+}
diff --git a/web/src/routes/AccountPage.tsx b/web/src/routes/AccountPage.tsx
index a0bcfc671..4887b4618 100644
--- a/web/src/routes/AccountPage.tsx
+++ b/web/src/routes/AccountPage.tsx
@@ -20,6 +20,9 @@ import { StepperUnitSelector } from "../session/StepperUnitSelector";
import { SUPPORTED_LANGUAGES } from "../i18n";
import { roleLabel } from "../i18n/enums";
import { errText } from "../lib/errText";
+import { ProofDialog, SecurityPanel } from "./account/SecurityPanel";
+import { TwoFactorFlow } from "./account/TwoFactorFlow";
+import { useTwoFactor } from "./account/useTwoFactor";
const MIN_LENGTH = 12;
@@ -38,6 +41,7 @@ export function AccountPage() {
const [error, setError] = useState(null);
const [message, setMessage] = useState(null);
const { busy, run } = usePendingAction();
+ const twoFactorSection = useTwoFactor();
async function onSubmit(e: FormEvent) {
e.preventDefault();
@@ -75,6 +79,10 @@ export function AccountPage() {
});
}
+ // #1277 — enrolment and new recovery codes take the page while they run.
+ const proofDialog = ;
+ if (twoFactorSection.flow.step !== "summary") return <>{proofDialog}>;
+
return (
@@ -149,6 +157,9 @@ export function AccountPage() {
+
+ {proofDialog}
+
);
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/UsersPage.test.tsx b/web/src/routes/UsersPage.test.tsx
index 305b2e449..f2486d47d 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.onProof"]);
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..c3b066cfa
--- /dev/null
+++ b/web/src/routes/account/Security.test.tsx
@@ -0,0 +1,471 @@
+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 { 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 });
+
+ const warning = screen.queryByText(t("recoveryCodesLow", { count: left }));
+ expect(warning !== null).toBe(warns);
+ if (warns) expect(within(warning!.closest(".MuiAlert-root")!.parentElement!).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(expect.any(String), 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, expect.any(String));
+ 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();
+ expect(mockConfirm).toHaveBeenCalledTimes(1);
+ expect(mockRegenerate).not.toHaveBeenCalled();
+ });
+
+ 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")],
+ ])("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"));
+ expect(mockStatus).toHaveBeenCalledTimes(2);
+ });
+
+ 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(expect.any(String), 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("");
+ });
+});
+
+// Each write keeps its key across a failure, so a retry replays it, and takes
+// a new one after a success.
+describe("idempotency keys", () => {
+ const failure = () => new ApiError(503, "Service.Unavailable", "Try later.");
+
+ const writes: Record> = { start: mockStart, regenerate: mockRegenerate, "turn-off": mockTurnOff };
+ const answers: Record unknown> = {
+ start: () => enrolmentFor(), regenerate: () => ({ recoveryCodes: freshCodes() }), "turn-off": () => undefined,
+ };
+
+ it.each([
+ ["start", OFF, "setUpButton", "continueButton"],
+ ["regenerate", ON, "regenerateButton", "regenerateButton"],
+ ["turn-off", ON, "turnOffButton", "turnOffButton"],
+ ] as const)("%s reuses its key after a failure and rotates it after a success", async (name, status, openKey, submitKey) => {
+ await renderAccount(status);
+ const write = writes[name]!;
+ const ok = answers[name]!;
+ const open = () => t(openKey);
+ const submit = () => t(submitKey);
+ write.mockRejectedValueOnce(failure()).mockResolvedValueOnce(ok()).mockResolvedValueOnce(ok());
+ const attempt = async (reopen: boolean) => {
+ if (reopen) await press(open());
+ prove(status.enabled);
+ await press(submit(), dialog());
+ };
+
+ await attempt(true);
+ await within(dialog()).findByRole("alert");
+ await attempt(false);
+ await waitFor(() => expect(write).toHaveBeenCalledTimes(2));
+ if (name === "start") await press(i18n.t("common:cancel"));
+ if (name === "regenerate") {
+ fireEvent.click(screen.getByRole("checkbox", { name: t("savedCheckbox") }));
+ await press(t("doneButton"));
+ }
+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
+ await attempt(true);
+ await waitFor(() => expect(write).toHaveBeenCalledTimes(3));
+
+ const keys = write.mock.calls.map((call: unknown[]) => call[0]);
+ expect(keys[1]).toBe(keys[0]);
+ expect(keys[2]).not.toBe(keys[1]);
+ });
+
+ it("confirm reuses its key after a wrong code and rotates it after a success", async () => {
+ await renderAccount(OFF);
+ await enrol();
+ mockConfirm
+ .mockRejectedValueOnce(new ApiError(400, "Auth.EnrolmentCodeIncorrect", "Wrong.", { extensions: { attemptsLeft: 4 } }))
+ .mockResolvedValueOnce({ recoveryCodes: freshCodes() });
+ typeCode();
+ await press(t("confirmButton"));
+ await screen.findByRole("alert");
+ typeCode();
+ await press(t("confirmButton"));
+ fireEvent.click(await screen.findByRole("checkbox", { name: t("savedCheckbox") }));
+ await press(t("doneButton"));
+
+ mockStart.mockResolvedValueOnce(enrolmentFor());
+ await press(t("setUpButton"));
+ prove(false);
+ await press(t("continueButton"), dialog());
+ mockConfirm.mockResolvedValueOnce({ recoveryCodes: undefined });
+ typeCode();
+ await press(t("confirmButton"));
+
+ const keys = mockConfirm.mock.calls.map((call) => call[1]);
+ expect(keys[1]).toBe(keys[0]);
+ expect(keys[2]).not.toBe(keys[1]);
+ });
+});
diff --git a/web/src/routes/account/SecurityPanel.tsx b/web/src/routes/account/SecurityPanel.tsx
new file mode 100644
index 000000000..c3756b65d
--- /dev/null
+++ b/web/src/routes/account/SecurityPanel.tsx
@@ -0,0 +1,149 @@
+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 { 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;
+ 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}}
+
+ );
+}
+
+const TITLES = {
+ start: { title: "setUpTitle", replaceTitle: "replaceTitle", body: "setUpBody", replaceBody: "replaceBody", submit: "continueButton" },
+ regenerate: { title: "regenerateTitle", body: "regenerateBody", submit: "regenerateButton" },
+ "turn-off": { title: "turnOffTitle", body: "turnOffBody", submit: "turnOffButton" },
+} as const;
+
+function copyFor(action: ProofAction, replacing: boolean) {
+ const entry = TITLES[action];
+ return "replaceTitle" in entry && replacing
+ ? { title: entry.replaceTitle, body: entry.replaceBody, submit: entry.submit }
+ : entry;
+}
+
+// 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.
+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, status, dialog: { busy, isPending, errors } } = twoFactor;
+ const copy = action && copyFor(action, status.data?.enabled ?? false);
+ return (
+
+ );
+}
diff --git a/web/src/routes/account/TwoFactorFlow.tsx b/web/src/routes/account/TwoFactorFlow.tsx
new file mode 100644
index 000000000..5ae8bc078
--- /dev/null
+++ b/web/src/routes/account/TwoFactorFlow.tsx
@@ -0,0 +1,155 @@
+import { useEffect, useState } from "react";
+import type { ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+import { Alert, Box, Button, Checkbox, FormControlLabel, Link, Paper, Stack, TextField, Typography } from "@mui/material";
+import { BusyButton } from "../../components/BusyButton";
+import { DialogError } from "../../components/DialogError";
+import { saveBlob } from "../../lib/saveBlob";
+import { useMe } from "../../session/SessionContext";
+import { TwoFactorQr } from "./TwoFactorQr";
+import type { Flow, TwoFactor } from "./useTwoFactor";
+
+// #1275 "Enrolment A" and "Recovery codes": the steps that replace the Account
+// page while they run, so the QR code, the key and the codes 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" && }
+ {flow.step === "codes" && }
+
+
+ );
+}
+
+const heading = (replacing: boolean) => (replacing ? "replaceHeading" : "enrolHeading");
+
+// Copy feedback, keyed so a second press announces again.
+function useCopy() {
+ const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);
+ // Started inside the promise: a plain-http origin has no clipboard at all.
+ const copy = (text: string, done: string, failed: string) =>
+ Promise.resolve().then(() => navigator.clipboard.writeText(text))
+ .then(() => setNote({ text: done, ok: true }), () => setNote({ text: failed, ok: false }));
+ const notice: ReactNode = (
+
+ {note && {note.text}}
+
+ );
+ return { copy, notice, setNote };
+}
+
+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(" ")}
+
+
+ {notice}
+
+
+
+
+
+ {t("confirmHeading")}
+ {t("confirmHint")}
+ setCode(e.target.value)}
+ slotProps={{ htmlInput: { inputMode: "numeric", autoComplete: "one-time-code", maxLength: 8 } }}
+ />
+ {t("signOutWarning")}
+
+
+
+ {t("confirmButton")}
+
+
+
+ );
+}
+
+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(flow.reason === "expired" ? "setUpExpired" : "setUpTooManyAttempts")}
+
+
+
+
+
+ );
+}
+
+// Shown once: the codes are in this step's props and nowhere else, and Done
+// drops them. Closing the tab first asks the browser to confirm.
+function CodesStep({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract }) {
+ const { t } = useTranslation("account");
+ const me = useMe();
+ const { copy, notice, setNote } = useCopy();
+ const [saved, setSaved] = useState(false);
+ const text = flow.codes.join("\n");
+
+ useEffect(() => {
+ const warn = (e: BeforeUnloadEvent) => e.preventDefault();
+ window.addEventListener("beforeunload", warn);
+ return () => window.removeEventListener("beforeunload", warn);
+ }, []);
+
+ const download = () => {
+ saveBlob(new Blob([`${t("codesFileTitle", { email: me?.email ?? "" })}\n\n${text}\n`], { type: "text/plain" }), "cluckwork-recovery-codes.txt");
+ setNote({ text: t("codesDownloaded"), ok: true });
+ };
+
+ return (
+
+ {t("codesHeading")}
+ {t("codesOn")}
+ {flow.regenerated && {t("codesReplaced")}}
+ {t("codesHint")}
+
+ {flow.codes.map((c) =>
{c}
)}
+
+
+
+
+
+ {notice}
+ setSaved(e.target.checked)} />} label={t("savedCheckbox")} />
+
+
+ );
+}
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
new file mode 100644
index 000000000..0682a2be5
--- /dev/null
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -0,0 +1,176 @@
+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 { useIdempotencyKeys } from "../sales/useIdempotencyKeys";
+
+// #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, the URI and the recovery codes live only in
+// the step that shows them, and leave with it.
+export type Flow =
+ | { step: "summary" }
+ | { step: "scan"; enrolment: EnrolmentStart; replacing: boolean }
+ | { step: "restart"; replacing: boolean; reason: "expired" | "attempts" }
+ | { step: "codes"; codes: string[]; regenerated: boolean };
+
+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 } = useAuth();
+ const status = useLatestLoad([], getTwoFactorStatus);
+ const dialog = useDialogAction(SCOPES);
+ const { busy, run, openDialog, dismissDialog } = dialog;
+ const { keyFor, clearKey } = useIdempotencyKeys();
+ 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);
+
+ // #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]);
+
+ function openProof(next: ProofAction) {
+ openDialog(next);
+ setMessage(null);
+ setProof(NO_PROOF);
+ setAction(next);
+ }
+
+ function closeProof() {
+ setProof(NO_PROOF);
+ setAction(null);
+ if (action) dismissDialog(action);
+ }
+
+ async function send(next: ProofAction, token: string, current: () => boolean) {
+ const scope = next;
+ if (next === "start") {
+ const replacing = status.data?.enabled ?? false;
+ const enrolment = await startTwoFactor(keyFor(scope), token);
+ clearKey(scope);
+ if (!current()) return;
+ setCode("");
+ openDialog("confirm");
+ setFlow({ step: "scan", enrolment, replacing });
+ } else if (next === "regenerate") {
+ const { recoveryCodes } = await regenerateRecoveryCodes(keyFor(scope), token).catch((err: unknown) => {
+ // The status was stale: the user is not enrolled, so it says so again.
+ if (!isProblem(err, 409, "Auth.TwoFactorNotEnabled")) throw err;
+ clearKey(scope);
+ status.retry();
+ throw new Error(i18n.t("account:regenerateNotEnabled"));
+ });
+ clearKey(scope);
+ status.retry();
+ if (!current()) return;
+ setFlow({ step: "codes", codes: recoveryCodes, regenerated: true });
+ } else {
+ await turnOffTwoFactor(keyFor(scope), token);
+ clearKey(scope);
+ status.retry();
+ if (!current()) return;
+ setMessage(i18n.t("account:turnedOffMessage"));
+ }
+ setAction(null);
+ dismissDialog(next);
+ }
+
+ async function onProof(e: FormEvent) {
+ e.preventDefault();
+ const next = action;
+ if (!next || busy) return;
+ setMessage(null);
+ await run(next, async (current) => {
+ const entered = proof;
+ setProof(NO_PROOF);
+ const token = (await stepUp(entered)).token;
+ if (!current()) return;
+ await send(next, token, current).catch((err: unknown) => { throw stale(err); });
+ }, { dialog: next });
+ }
+
+ async function onConfirm(e: FormEvent) {
+ e.preventDefault();
+ if (flow.step !== "scan" || busy) return;
+ const { replacing } = flow;
+ await run("confirm", async (current) => {
+ const typed = code;
+ setCode("");
+ let recoveryCodes: string[] | undefined;
+ try {
+ ({ recoveryCodes } = await confirmTwoFactor(typed, keyFor("confirm")));
+ } catch (err) {
+ // The fifth wrong code ended the enrolment, and every later confirm
+ // answers 409: either way the user starts again.
+ const attemptsLeft = err instanceof ApiError ? err.extensions.attemptsLeft : undefined;
+ const reason = isProblem(err, 409, "Auth.EnrolmentExpired") ? "expired"
+ : isProblem(err, 400, "Auth.EnrolmentCodeIncorrect") && attemptsLeft === 0 ? "attempts" : null;
+ if (reason === null) throw incorrect(err, attemptsLeft);
+ clearKey("confirm");
+ if (current()) setFlow({ step: "restart", replacing, reason });
+ return;
+ }
+ clearKey("confirm");
+ status.retry();
+ if (!current()) return;
+ if (recoveryCodes) {
+ setFlow({ step: "codes", codes: recoveryCodes, regenerated: false });
+ } else {
+ setFlow(SUMMARY);
+ 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,
+ };
+}
+
+// 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 stale(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/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);
});
});
From aca3d3e67607a8c5df8375bcd13f65e27257ba14 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 01:57:59 +0000
Subject: [PATCH 04/45] refactor(web): clear the step-up proof on the way out
only
Opening a Security dialog reset the proof that cancel, send and logout had already cleared, so a mutation to either reset alone stayed green. The close reset is the one that keeps a typed password from outliving its dialog; the open reset goes.
Refs #1277
---
web/src/routes/account/Security.test.tsx | 5 ++---
web/src/routes/account/TwoFactorFlow.tsx | 2 +-
web/src/routes/account/useTwoFactor.ts | 19 +++++++++----------
3 files changed, 12 insertions(+), 14 deletions(-)
diff --git a/web/src/routes/account/Security.test.tsx b/web/src/routes/account/Security.test.tsx
index c3b066cfa..ea42d17c2 100644
--- a/web/src/routes/account/Security.test.tsx
+++ b/web/src/routes/account/Security.test.tsx
@@ -116,9 +116,8 @@ describe("the status drives the Security section", () => {
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 });
- const warning = screen.queryByText(t("recoveryCodesLow", { count: left }));
- expect(warning !== null).toBe(warns);
- if (warns) expect(within(warning!.closest(".MuiAlert-root")!.parentElement!).getByRole("button", { name: t("regenerateButton") })).toBeInTheDocument();
+ 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 () => {
diff --git a/web/src/routes/account/TwoFactorFlow.tsx b/web/src/routes/account/TwoFactorFlow.tsx
index 5ae8bc078..326b2a999 100644
--- a/web/src/routes/account/TwoFactorFlow.tsx
+++ b/web/src/routes/account/TwoFactorFlow.tsx
@@ -29,7 +29,7 @@ export function TwoFactorFlow({ twoFactor }: { twoFactor: TwoFactor }) {
const heading = (replacing: boolean) => (replacing ? "replaceHeading" : "enrolHeading");
-// Copy feedback, keyed so a second press announces again.
+// Copy and download feedback, announced in one live region.
function useCopy() {
const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);
// Started inside the promise: a plain-http origin has no clipboard at all.
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index 0682a2be5..716303a65 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -60,10 +60,10 @@ export function useTwoFactor() {
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);
- setProof(NO_PROOF);
setAction(next);
}
@@ -74,30 +74,29 @@ export function useTwoFactor() {
}
async function send(next: ProofAction, token: string, current: () => boolean) {
- const scope = next;
if (next === "start") {
const replacing = status.data?.enabled ?? false;
- const enrolment = await startTwoFactor(keyFor(scope), token);
- clearKey(scope);
+ const enrolment = await startTwoFactor(keyFor(next), token);
+ clearKey(next);
if (!current()) return;
setCode("");
openDialog("confirm");
setFlow({ step: "scan", enrolment, replacing });
} else if (next === "regenerate") {
- const { recoveryCodes } = await regenerateRecoveryCodes(keyFor(scope), token).catch((err: unknown) => {
- // The status was stale: the user is not enrolled, so it says so again.
+ const { recoveryCodes } = await regenerateRecoveryCodes(keyFor(next), token).catch((err: unknown) => {
+ // The status was stale (#1277 contract item 8): reload it.
if (!isProblem(err, 409, "Auth.TwoFactorNotEnabled")) throw err;
- clearKey(scope);
+ clearKey(next);
status.retry();
throw new Error(i18n.t("account:regenerateNotEnabled"));
});
- clearKey(scope);
+ clearKey(next);
status.retry();
if (!current()) return;
setFlow({ step: "codes", codes: recoveryCodes, regenerated: true });
} else {
- await turnOffTwoFactor(keyFor(scope), token);
- clearKey(scope);
+ await turnOffTwoFactor(keyFor(next), token);
+ clearKey(next);
status.retry();
if (!current()) return;
setMessage(i18n.t("account:turnedOffMessage"));
From 76104ed0d07d8dd85f61374e47a71f6385040675 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 14:28:51 +0000
Subject: [PATCH 05/45] fix(web): surface a refused resend instead of signing
the user out
After a 401 and a successful refresh, apiFetch and apiGetBlob resent inside the refresh's catch, so a resend that answered 400 or 409 cleared the token and fired onUnauthenticated. The resend now answers for the request itself; only a failed refresh, or a 401 to the fresh token, ends the session.
Refs #1277
---
web/src/api/client.test.ts | 36 +++++++++++++++++++++++++++++++++++
web/src/api/refresh.ts | 28 +++++++++++++++++++++++----
web/src/api/twoFactor.test.ts | 13 +++++++++++++
3 files changed, 73 insertions(+), 4 deletions(-)
diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts
index 8b5ecc5f4..6b4d02cd2 100644
--- a/web/src/api/client.test.ts
+++ b/web/src/api/client.test.ts
@@ -199,6 +199,42 @@ describe("apiFetch — no in-memory token", () => {
});
});
+// #1277 review — the resend after a successful refresh answers for the request
+// itself. Its refusal is the caller's to show; only a failed refresh ends the
+// session.
+describe("apiFetch — a refused resend after a successful refresh", () => {
+ it.each([
+ ["a 400 with its extensions", 400, { title: "Auth.EnrolmentCodeIncorrect", attemptsLeft: 3 }],
+ ["a 409", 409, { title: "Auth.EnrolmentExpired" }],
+ ])("surfaces %s and keeps the session", async (_, status, body) => {
+ const refreshed = claimfulToken("at2-resend");
+ fetchMock
+ .mockResolvedValueOnce(jsonResponse({ title: "Unauthorized" }, 401))
+ .mockResolvedValueOnce(accessResponse(refreshed))
+ .mockResolvedValueOnce(jsonResponse(body, status));
+
+ const refusal = await apiPost("/thing", {}).catch((err: unknown) => err);
+
+ expect(refusal).toMatchObject({ status, title: body.title });
+ if ("attemptsLeft" in body) expect((refusal as ApiError).extensions).toEqual({ attemptsLeft: 3 });
+ expect(onUnauth).not.toHaveBeenCalled();
+ expect(getAccessToken()).toBe(refreshed);
+ });
+
+ it("does the same for a file download", async () => {
+ const refreshed = claimfulToken("at2-blob");
+ fetchMock
+ .mockResolvedValueOnce(jsonResponse({ title: "Unauthorized" }, 401))
+ .mockResolvedValueOnce(accessResponse(refreshed))
+ .mockResolvedValueOnce(jsonResponse({ title: "Export.NotFound" }, 404));
+
+ await expect(apiGetBlob("/export")).rejects.toMatchObject({ status: 404 });
+
+ expect(onUnauth).not.toHaveBeenCalled();
+ expect(getAccessToken()).toBe(refreshed);
+ });
+});
+
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/refresh.ts b/web/src/api/refresh.ts
index 9c9afaff2..e3b0e87be 100644
--- a/web/src/api/refresh.ts
+++ b/web/src/api/refresh.ts
@@ -304,9 +304,9 @@ export async function apiGetBlob(
return await rawBlob(path, token);
} catch (err) {
if (!(err instanceof ApiError) || err.status !== 401) throw err;
+ let refreshed: string;
try {
- const refreshed = await refreshTokens();
- return await rawBlob(path, refreshed);
+ refreshed = await refreshTokens();
} catch (refreshErr) {
// #310 review — same supersession handling as apiFetch.
if (refreshErr instanceof StaleSessionError) {
@@ -322,6 +322,15 @@ export async function apiGetBlob(
onUnauthenticated?.(err.title);
throw err;
}
+ // As in apiFetch: only a 401 to the resend means the session is dead.
+ try {
+ return await rawBlob(path, refreshed);
+ } catch (resendErr) {
+ if (!(resendErr instanceof ApiError) || resendErr.status !== 401) throw resendErr;
+ clearAccessToken();
+ onUnauthenticated?.(err.title);
+ throw err;
+ }
}
}
@@ -353,11 +362,11 @@ export async function apiFetch(
// not refresh that newer cookie or resend the old password body against it.
if (heldAuthCookieLock && sessionGeneration !== heldAuthCookieLock.generation)
throw new StaleSessionError();
+ let refreshed: string;
try {
- const refreshed = await refreshTokens(heldAuthCookieLock);
+ refreshed = await refreshTokens(heldAuthCookieLock);
if (heldAuthCookieLock && sessionGeneration !== heldAuthCookieLock.generation)
throw new StaleSessionError();
- return await raw(path, init, refreshed);
} 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.
@@ -376,6 +385,17 @@ export async function apiFetch(
onUnauthenticated?.(err.title);
throw err;
}
+ // #1277 review — the refresh worked, so the resend answers for the request
+ // itself: a 400 or a 409 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 raw(path, init, refreshed);
+ } catch (resendErr) {
+ if (!(resendErr instanceof ApiError) || resendErr.status !== 401) throw resendErr;
+ clearAccessToken();
+ onUnauthenticated?.(err.title);
+ throw err;
+ }
}
}
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
index 6328f36ae..42c3b806a 100644
--- a/web/src/api/twoFactor.test.ts
+++ b/web/src/api/twoFactor.test.ts
@@ -136,6 +136,19 @@ describe("a stale session's 401 Auth.CredentialsSuperseded", () => {
expect(to("/auth/refresh")).toHaveLength(1);
});
+ 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(), crypto.randomUUID()))
+ .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))
From 325f8365282ca67c85571be10531e6840b8abcab Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 14:29:59 +0000
Subject: [PATCH 06/45] refactor(web): send a fresh Idempotency-Key on each
two-factor write
The server keeps no response for any route under /api/v1/auth/two-factor (ResponseNotCacheable), so a key reused after a failure replayed nothing. Each write now sends newId(), as change-password does; the per-action key bookkeeping and the two tests that pinned it go.
Refs #1277
---
web/src/api/cluckwork/twoFactor.ts | 10 +--
web/src/api/session.ts | 10 +--
web/src/api/twoFactor.test.ts | 38 +++++-------
web/src/routes/account/Security.test.tsx | 79 +-----------------------
web/src/routes/account/useTwoFactor.ts | 16 ++---
5 files changed, 35 insertions(+), 118 deletions(-)
diff --git a/web/src/api/cluckwork/twoFactor.ts b/web/src/api/cluckwork/twoFactor.ts
index 32fb34a04..5ce7e1fce 100644
--- a/web/src/api/cluckwork/twoFactor.ts
+++ b/web/src/api/cluckwork/twoFactor.ts
@@ -18,8 +18,10 @@ export interface EnrolmentStart {
export const getTwoFactorStatus = (signal?: AbortSignal) => apiGet("/auth/two-factor", signal);
-export const startTwoFactor = (key: string, stepUpToken: string) =>
- apiPost("/auth/two-factor/start", undefined, key, { [STEP_UP_HEADER]: stepUpToken });
+// 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 });
-export const regenerateRecoveryCodes = (key: string, stepUpToken: string) =>
- apiPost<{ recoveryCodes: string[] }>("/auth/two-factor/recovery-codes", undefined, key, { [STEP_UP_HEADER]: stepUpToken });
+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/session.ts b/web/src/api/session.ts
index d8f045c8b..627fe71b5 100644
--- a/web/src/api/session.ts
+++ b/web/src/api/session.ts
@@ -269,19 +269,21 @@ export async function changePassword(
// #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.
-export function confirmTwoFactor(code: string, idempotencyKey: string): Promise<{ recoveryCodes?: string[] }> {
+// 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": idempotencyKey },
+ 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(idempotencyKey: string, stepUpToken: string): Promise {
+export async function turnOffTwoFactor(stepUpToken: string): Promise {
await adoptingWrite("/auth/two-factor", {
method: "DELETE",
- headers: { "Idempotency-Key": idempotencyKey, [STEP_UP_HEADER]: stepUpToken },
+ headers: { "Idempotency-Key": newId(), [STEP_UP_HEADER]: stepUpToken },
});
}
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
index 42c3b806a..c76068205 100644
--- a/web/src/api/twoFactor.test.ts
+++ b/web/src/api/twoFactor.test.ts
@@ -43,19 +43,18 @@ afterEach(() => {
});
describe("confirmTwoFactor", () => {
- it("sends the code with its key, adopts the fresh pair and returns the codes", async () => {
+ 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();
- const key = crypto.randomUUID();
- await expect(confirmTwoFactor(code, key)).resolves.toEqual({ recoveryCodes: codes });
+ 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")).toBe(key);
+ 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");
@@ -66,32 +65,31 @@ describe("confirmTwoFactor", () => {
const fresh = token("acct-B");
fetchMock.mockResolvedValueOnce(pair(fresh));
- await expect(confirmTwoFactor(freshCode(), crypto.randomUUID())).resolves.toEqual({ recoveryCodes: undefined });
+ 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(), crypto.randomUUID()))
+ 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 the key, and adopts the 200's fresh pair", async () => {
+ 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 key = crypto.randomUUID();
const grant = crypto.randomUUID();
- await turnOffTwoFactor(key, grant);
+ 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")).toBe(key);
+ expect(header(call!, "Idempotency-Key")).toMatch(/^[0-9a-f-]{36}$/);
expect(getAccessToken()).toBe(fresh);
expect(onTokens).toHaveBeenCalled();
});
@@ -99,7 +97,7 @@ describe("turnOffTwoFactor", () => {
it("adopts nothing on a 204", async () => {
fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
- await turnOffTwoFactor(crypto.randomUUID(), crypto.randomUUID());
+ await turnOffTwoFactor(crypto.randomUUID());
expect(getAccessToken()).toBe("at1");
expect(onTokens).not.toHaveBeenCalled();
@@ -110,10 +108,10 @@ describe("turnOffTwoFactor", () => {
// 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(), crypto.randomUUID())],
- ["confirm", "/auth/two-factor/confirm", () => confirmTwoFactor(freshCode(), crypto.randomUUID())],
- ["start", "/auth/two-factor/start", () => startTwoFactor(crypto.randomUUID(), crypto.randomUUID())],
- ["regenerate", "/auth/two-factor/recovery-codes", () => regenerateRecoveryCodes(crypto.randomUUID(), crypto.randomUUID())],
+ ["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) => {
@@ -143,7 +141,7 @@ describe("a stale session's 401 Auth.CredentialsSuperseded", () => {
.mockResolvedValueOnce(pair(refreshed))
.mockResolvedValueOnce(json({ title: "Auth.EnrolmentCodeIncorrect", attemptsLeft: 2 }, 400));
- await expect(confirmTwoFactor(freshCode(), crypto.randomUUID()))
+ await expect(confirmTwoFactor(freshCode()))
.rejects.toMatchObject({ status: 400, title: "Auth.EnrolmentCodeIncorrect", extensions: { attemptsLeft: 2 } });
expect(onUnauth).not.toHaveBeenCalled();
expect(getAccessToken()).toBe(refreshed);
@@ -154,12 +152,8 @@ describe("a stale session's 401 Auth.CredentialsSuperseded", () => {
.mockResolvedValueOnce(json({ title: "Unauthorized" }, 401))
.mockResolvedValueOnce(pair(token("acct-F")))
.mockResolvedValueOnce(json({ recoveryCodes: [] }));
- const key = crypto.randomUUID();
+ await regenerateRecoveryCodes(crypto.randomUUID());
- await regenerateRecoveryCodes(key, crypto.randomUUID());
-
- const sent = to("/auth/two-factor/recovery-codes");
- expect(sent).toHaveLength(2);
- expect(sent.map((call) => header(call, "Idempotency-Key"))).toEqual([key, key]);
+ expect(to("/auth/two-factor/recovery-codes")).toHaveLength(2);
});
});
diff --git a/web/src/routes/account/Security.test.tsx b/web/src/routes/account/Security.test.tsx
index ea42d17c2..e9b96a0c8 100644
--- a/web/src/routes/account/Security.test.tsx
+++ b/web/src/routes/account/Security.test.tsx
@@ -147,7 +147,7 @@ describe("enrolment", () => {
await press(t("continueButton"), dialog());
expect(mockStepUp).toHaveBeenCalledWith(proof);
- expect(mockStart).toHaveBeenCalledWith(expect.any(String), grantToken);
+ 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/);
@@ -167,7 +167,7 @@ describe("enrolment", () => {
const code = typeCode();
await press(t("confirmButton"));
- expect(mockConfirm).toHaveBeenCalledWith(code, expect.any(String));
+ 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();
@@ -284,7 +284,7 @@ describe("an enrolled user's step-up actions", () => {
prove(true);
await press(t("turnOffButton"), dialog());
- expect(mockTurnOff).toHaveBeenCalledWith(expect.any(String), grantToken);
+ expect(mockTurnOff).toHaveBeenCalledWith(grantToken);
expect(await screen.findByText(t("turnedOffMessage"))).toBeInTheDocument();
expect(await screen.findByText(t("twoFactorOff"))).toBeInTheDocument();
});
@@ -395,76 +395,3 @@ describe("the step-up proof", () => {
expect(codeField()).toHaveValue("");
});
});
-
-// Each write keeps its key across a failure, so a retry replays it, and takes
-// a new one after a success.
-describe("idempotency keys", () => {
- const failure = () => new ApiError(503, "Service.Unavailable", "Try later.");
-
- const writes: Record> = { start: mockStart, regenerate: mockRegenerate, "turn-off": mockTurnOff };
- const answers: Record unknown> = {
- start: () => enrolmentFor(), regenerate: () => ({ recoveryCodes: freshCodes() }), "turn-off": () => undefined,
- };
-
- it.each([
- ["start", OFF, "setUpButton", "continueButton"],
- ["regenerate", ON, "regenerateButton", "regenerateButton"],
- ["turn-off", ON, "turnOffButton", "turnOffButton"],
- ] as const)("%s reuses its key after a failure and rotates it after a success", async (name, status, openKey, submitKey) => {
- await renderAccount(status);
- const write = writes[name]!;
- const ok = answers[name]!;
- const open = () => t(openKey);
- const submit = () => t(submitKey);
- write.mockRejectedValueOnce(failure()).mockResolvedValueOnce(ok()).mockResolvedValueOnce(ok());
- const attempt = async (reopen: boolean) => {
- if (reopen) await press(open());
- prove(status.enabled);
- await press(submit(), dialog());
- };
-
- await attempt(true);
- await within(dialog()).findByRole("alert");
- await attempt(false);
- await waitFor(() => expect(write).toHaveBeenCalledTimes(2));
- if (name === "start") await press(i18n.t("common:cancel"));
- if (name === "regenerate") {
- fireEvent.click(screen.getByRole("checkbox", { name: t("savedCheckbox") }));
- await press(t("doneButton"));
- }
- await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
- await attempt(true);
- await waitFor(() => expect(write).toHaveBeenCalledTimes(3));
-
- const keys = write.mock.calls.map((call: unknown[]) => call[0]);
- expect(keys[1]).toBe(keys[0]);
- expect(keys[2]).not.toBe(keys[1]);
- });
-
- it("confirm reuses its key after a wrong code and rotates it after a success", async () => {
- await renderAccount(OFF);
- await enrol();
- mockConfirm
- .mockRejectedValueOnce(new ApiError(400, "Auth.EnrolmentCodeIncorrect", "Wrong.", { extensions: { attemptsLeft: 4 } }))
- .mockResolvedValueOnce({ recoveryCodes: freshCodes() });
- typeCode();
- await press(t("confirmButton"));
- await screen.findByRole("alert");
- typeCode();
- await press(t("confirmButton"));
- fireEvent.click(await screen.findByRole("checkbox", { name: t("savedCheckbox") }));
- await press(t("doneButton"));
-
- mockStart.mockResolvedValueOnce(enrolmentFor());
- await press(t("setUpButton"));
- prove(false);
- await press(t("continueButton"), dialog());
- mockConfirm.mockResolvedValueOnce({ recoveryCodes: undefined });
- typeCode();
- await press(t("confirmButton"));
-
- const keys = mockConfirm.mock.calls.map((call) => call[1]);
- expect(keys[1]).toBe(keys[0]);
- expect(keys[2]).not.toBe(keys[1]);
- });
-});
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index 716303a65..cd4aee4cd 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -8,7 +8,6 @@ import { useAuth } from "../../auth/useAuth";
import { useDialogAction } from "../../components/useDialogAction";
import { useLatestLoad } from "../../components/useLatestLoad";
import i18n from "../../i18n";
-import { useIdempotencyKeys } from "../sales/useIdempotencyKeys";
// #1277 — the Security section's two-factor authentication. Start,
// Regenerate and Turn off each step up in a dialog first; confirm is the
@@ -43,7 +42,6 @@ export function useTwoFactor() {
const status = useLatestLoad([], getTwoFactorStatus);
const dialog = useDialogAction(SCOPES);
const { busy, run, openDialog, dismissDialog } = dialog;
- const { keyFor, clearKey } = useIdempotencyKeys();
const [flow, setFlow] = useState(SUMMARY);
const [action, setAction] = useState(null);
const [proof, setProof] = useState(NO_PROOF);
@@ -76,27 +74,23 @@ export function useTwoFactor() {
async function send(next: ProofAction, token: string, current: () => boolean) {
if (next === "start") {
const replacing = status.data?.enabled ?? false;
- const enrolment = await startTwoFactor(keyFor(next), token);
- clearKey(next);
+ const enrolment = await startTwoFactor(token);
if (!current()) return;
setCode("");
openDialog("confirm");
setFlow({ step: "scan", enrolment, replacing });
} else if (next === "regenerate") {
- const { recoveryCodes } = await regenerateRecoveryCodes(keyFor(next), token).catch((err: unknown) => {
+ const { recoveryCodes } = await regenerateRecoveryCodes(token).catch((err: unknown) => {
// The status was stale (#1277 contract item 8): reload it.
if (!isProblem(err, 409, "Auth.TwoFactorNotEnabled")) throw err;
- clearKey(next);
status.retry();
throw new Error(i18n.t("account:regenerateNotEnabled"));
});
- clearKey(next);
status.retry();
if (!current()) return;
setFlow({ step: "codes", codes: recoveryCodes, regenerated: true });
} else {
- await turnOffTwoFactor(keyFor(next), token);
- clearKey(next);
+ await turnOffTwoFactor(token);
status.retry();
if (!current()) return;
setMessage(i18n.t("account:turnedOffMessage"));
@@ -128,7 +122,7 @@ export function useTwoFactor() {
setCode("");
let recoveryCodes: string[] | undefined;
try {
- ({ recoveryCodes } = await confirmTwoFactor(typed, keyFor("confirm")));
+ ({ recoveryCodes } = await confirmTwoFactor(typed));
} catch (err) {
// The fifth wrong code ended the enrolment, and every later confirm
// answers 409: either way the user starts again.
@@ -136,11 +130,9 @@ export function useTwoFactor() {
const reason = isProblem(err, 409, "Auth.EnrolmentExpired") ? "expired"
: isProblem(err, 400, "Auth.EnrolmentCodeIncorrect") && attemptsLeft === 0 ? "attempts" : null;
if (reason === null) throw incorrect(err, attemptsLeft);
- clearKey("confirm");
if (current()) setFlow({ step: "restart", replacing, reason });
return;
}
- clearKey("confirm");
status.retry();
if (!current()) return;
if (recoveryCodes) {
From 9b91847a61e6265bbb62d7ce0fd0b69195d5898a Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 14:30:48 +0000
Subject: [PATCH 07/45] fix(web): start enrolment again after a stale session's
confirm
Confirm's 401 Auth.CredentialsSuperseded offered Try again, which could never work: the token is stale and the pending enrolment is bound to the old epoch. It now goes to the restart step, whose Start again steps up afresh. Start, Regenerate and Turn off keep the try-again message, because their retry steps up first.
Refs #1277
---
web/src/routes/account/Security.test.tsx | 2 ++
web/src/routes/account/useTwoFactor.ts | 7 ++++---
2 files changed, 6 insertions(+), 3 deletions(-)
diff --git a/web/src/routes/account/Security.test.tsx b/web/src/routes/account/Security.test.tsx
index e9b96a0c8..275e8bbca 100644
--- a/web/src/routes/account/Security.test.tsx
+++ b/web/src/routes/account/Security.test.tsx
@@ -202,6 +202,8 @@ describe("enrolment", () => {
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("setUpExpired")],
])("after %s, drops the QR code and starts again from a fresh step-up", async (_, err, text) => {
await renderAccount(OFF);
const { key } = await enrol();
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index cd4aee4cd..9a636cb87 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -125,9 +125,10 @@ export function useTwoFactor() {
({ recoveryCodes } = await confirmTwoFactor(typed));
} catch (err) {
// The fifth wrong code ended the enrolment, and every later confirm
- // answers 409: either way the user starts again.
+ // 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"
+ const reason = isProblem(err, 409, "Auth.EnrolmentExpired") || isProblem(err, 401, "Auth.CredentialsSuperseded") ? "expired"
: isProblem(err, 400, "Auth.EnrolmentCodeIncorrect") && attemptsLeft === 0 ? "attempts" : null;
if (reason === null) throw incorrect(err, attemptsLeft);
if (current()) setFlow({ step: "restart", replacing, reason });
@@ -158,7 +159,7 @@ export function useTwoFactor() {
// 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 stale(err);
+ if (!isProblem(err, 400, "Auth.EnrolmentCodeIncorrect")) return err;
return new Error(typeof attemptsLeft === "number"
? i18n.t("account:codeIncorrectAttempts", { count: attemptsLeft })
: i18n.t("account:codeIncorrect"));
From 82338de7175e00b143d515268691ce92492e30a3 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 14:34:00 +0000
Subject: [PATCH 08/45] fix(web): show new recovery codes in a dialog nothing
dismisses before they are saved
In-app navigation dropped the once-only codes: the sidebar, the bottom nav and Help left the page with no warning. The codes now open in the modal Dialog, full screen on a phone, with every close path disabled until 'I saved my recovery codes' is ticked. beforeunload still guards closing the tab, and sets returnValue too. Browser Back is not guarded.
Refs #1277
---
web/src/routes/AccountPage.tsx | 9 ++-
web/src/routes/account/Security.test.tsx | 22 ++++++++
web/src/routes/account/TwoFactorFlow.tsx | 70 +++++++++++++++---------
3 files changed, 71 insertions(+), 30 deletions(-)
diff --git a/web/src/routes/AccountPage.tsx b/web/src/routes/AccountPage.tsx
index 4887b4618..1ba99150f 100644
--- a/web/src/routes/AccountPage.tsx
+++ b/web/src/routes/AccountPage.tsx
@@ -21,7 +21,7 @@ import { SUPPORTED_LANGUAGES } from "../i18n";
import { roleLabel } from "../i18n/enums";
import { errText } from "../lib/errText";
import { ProofDialog, SecurityPanel } from "./account/SecurityPanel";
-import { TwoFactorFlow } from "./account/TwoFactorFlow";
+import { RecoveryCodesDialog, TwoFactorFlow } from "./account/TwoFactorFlow";
import { useTwoFactor } from "./account/useTwoFactor";
const MIN_LENGTH = 12;
@@ -79,9 +79,11 @@ export function AccountPage() {
});
}
- // #1277 — enrolment and new recovery codes take the page while they run.
+ // #1277 — enrolment takes the page while it runs; new recovery codes open
+ // over it in a locked dialog.
const proofDialog = ;
- if (twoFactorSection.flow.step !== "summary") return <>{proofDialog}>;
+ const { flow } = twoFactorSection;
+ if (flow.step === "scan" || flow.step === "restart") return <>{proofDialog}>;
return (
@@ -159,6 +161,7 @@ export function AccountPage() {
{proofDialog}
+ {flow.step === "codes" && }
diff --git a/web/src/routes/account/Security.test.tsx b/web/src/routes/account/Security.test.tsx
index 275e8bbca..bc0d31f27 100644
--- a/web/src/routes/account/Security.test.tsx
+++ b/web/src/routes/account/Security.test.tsx
@@ -183,6 +183,28 @@ describe("enrolment", () => {
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: "Close" })).toBeDisabled();
+ 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: "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")],
diff --git a/web/src/routes/account/TwoFactorFlow.tsx b/web/src/routes/account/TwoFactorFlow.tsx
index 326b2a999..80f5f9ecc 100644
--- a/web/src/routes/account/TwoFactorFlow.tsx
+++ b/web/src/routes/account/TwoFactorFlow.tsx
@@ -1,17 +1,17 @@
import { useEffect, useState } from "react";
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
-import { Alert, Box, Button, Checkbox, FormControlLabel, Link, Paper, Stack, TextField, Typography } from "@mui/material";
+import { Alert, Box, Button, Checkbox, DialogActions, FormControlLabel, Link, Paper, Stack, TextField, Typography } from "@mui/material";
import { BusyButton } from "../../components/BusyButton";
+import { Dialog } from "../../components/Dialog";
import { DialogError } from "../../components/DialogError";
import { saveBlob } from "../../lib/saveBlob";
import { useMe } from "../../session/SessionContext";
import { TwoFactorQr } from "./TwoFactorQr";
import type { Flow, TwoFactor } from "./useTwoFactor";
-// #1275 "Enrolment A" and "Recovery codes": the steps that replace the Account
-// page while they run, so the QR code, the key and the codes leave the screen
-// with the step that shows them.
+// #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;
@@ -21,7 +21,6 @@ export function TwoFactorFlow({ twoFactor }: { twoFactor: TwoFactor }) {
{flow.step === "scan" && }
{flow.step === "restart" && }
- {flow.step === "codes" && }
);
@@ -111,9 +110,12 @@ function RestartStep({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract<
);
}
-// Shown once: the codes are in this step's props and nowhere else, and Done
-// drops them. Closing the tab first asks the browser to confirm.
-function CodesStep({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract }) {
+// #1275 "Recovery codes", shown once: the codes are in this dialog's props and
+// nowhere else, and leaving drops them. 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. Closing the tab asks
+// the browser to confirm. Browser Back is not guarded.
+export function RecoveryCodesDialog({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract }) {
const { t } = useTranslation("account");
const me = useMe();
const { copy, notice, setNote } = useCopy();
@@ -121,7 +123,10 @@ function CodesStep({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract {
- const warn = (e: BeforeUnloadEvent) => e.preventDefault();
+ const warn = (e: BeforeUnloadEvent) => {
+ e.preventDefault();
+ e.returnValue = "";
+ };
window.addEventListener("beforeunload", warn);
return () => window.removeEventListener("beforeunload", warn);
}, []);
@@ -132,24 +137,35 @@ function CodesStep({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract
- {t("codesHeading")}
- {t("codesOn")}
- {flow.regenerated && {t("codesReplaced")}}
- {t("codesHint")}
-
- {flow.codes.map((c) =>
{c}
)}
-
-
-
-
+
+
);
}
From 0c32135006ba76e12b83a0d6b021ad5ad7a69969 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 14:34:10 +0000
Subject: [PATCH 09/45] test(web): pin that the recovery codes leave the hook's
state
Adapted from the round-1 runner's probe: leaving the codes step, and ending the session, both reset the flow to the bare summary, so no exit keeps the codes in hidden state. Each test goes red when the summary spreads the old flow.
Refs #1277
---
web/src/routes/account/useTwoFactor.test.tsx | 55 ++++++++++++++++++++
1 file changed, 55 insertions(+)
create mode 100644 web/src/routes/account/useTwoFactor.test.tsx
diff --git a/web/src/routes/account/useTwoFactor.test.tsx b/web/src/routes/account/useTwoFactor.test.tsx
new file mode 100644
index 000000000..c7ac7cdba
--- /dev/null
+++ b/web/src/routes/account/useTwoFactor.test.tsx
@@ -0,0 +1,55 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import type { FormEvent } from "react";
+import { useTwoFactor } from "./useTwoFactor";
+import { getTwoFactorStatus, regenerateRecoveryCodes } from "../../api/cluckwork";
+import { stepUp } from "../../api/client";
+
+// #1277 review W3 — the recovery codes leave the hook's state on every exit
+// from the codes step, not only the rendered page. Adapted from the round-1
+// runner's probe, which caught a summary that kept them.
+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(),
+}));
+
+beforeEach(() => {
+ auth.isAuthenticated = true;
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 10 });
+ vi.mocked(regenerateRecoveryCodes).mockResolvedValue({ recoveryCodes: [crypto.randomUUID()] });
+ vi.mocked(stepUp).mockResolvedValue({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" });
+});
+
+async function onCodesStep() {
+ const hook = renderHook(useTwoFactor);
+ await waitFor(() => expect(hook.result.current.status.data?.enabled).toBe(true));
+ act(() => hook.result.current.openProof("regenerate"));
+ act(() => hook.result.current.setProof({ password: crypto.randomUUID() }));
+ await act(async () => { await hook.result.current.onProof({ preventDefault() {} } as FormEvent); });
+ expect(hook.result.current.flow.step).toBe("codes");
+ return hook;
+}
+
+describe("the recovery codes' lifetime", () => {
+ it("ends when the user leaves the codes step", async () => {
+ const { result } = await onCodesStep();
+
+ act(() => result.current.leaveFlow());
+
+ expect(result.current.flow).toEqual({ step: "summary" });
+ });
+
+ it("ends when the session does", async () => {
+ const { result, rerender } = await onCodesStep();
+
+ auth.isAuthenticated = false;
+ rerender();
+
+ expect(result.current.flow).toEqual({ step: "summary" });
+ });
+});
From 69bb6bead3fa97296af79203b2a0d46fb9421cc8 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 14:35:21 +0000
Subject: [PATCH 10/45] fix(web): treat a 204 as a fresh pair only where
turn-off sends one
adoptingWrite returned undefined for every 204, so change-password and confirm resolved on an answer that carried no session, where change-password threw before. Only turn-off may now answer 204; from the others it throws. Turn-off's 204 also checks the session generation, so a logout in flight is not told two-factor was turned off.
Refs #1277
---
web/src/api/session.ts | 21 ++++++++++++++++-----
web/src/api/twoFactor.test.ts | 32 +++++++++++++++++++++++++++++++-
2 files changed, 47 insertions(+), 6 deletions(-)
diff --git a/web/src/api/session.ts b/web/src/api/session.ts
index 627fe71b5..0fdea1d56 100644
--- a/web/src/api/session.ts
+++ b/web/src/api/session.ts
@@ -276,7 +276,7 @@ export function confirmTwoFactor(code: string): Promise<{ recoveryCodes?: string
method: "POST",
headers: { "Idempotency-Key": newId() },
body: JSON.stringify({ code }),
- }).then((res) => ({ recoveryCodes: res?.recoveryCodes }));
+ }).then((res) => ({ recoveryCodes: res.recoveryCodes }));
}
// #1280 — 200 with a fresh pair when two-factor was on, 204 when it was not.
@@ -284,12 +284,17 @@ export async function turnOffTwoFactor(stepUpToken: string): Promise {
await adoptingWrite("/auth/two-factor", {
method: "DELETE",
headers: { "Idempotency-Key": newId(), [STEP_UP_HEADER]: stepUpToken },
- });
+ }, "noContentAllowed");
}
// A write whose answer rotates this farm's refresh cookie and hands this tab a
-// fresh pair; undefined for a 204, which rotates nothing.
-async function adoptingWrite(path: string, init: RequestInit): Promise {
+// 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, noContent: "noContentAllowed"): Promise;
+async function adoptingWrite(
+ path: string, init: RequestInit, noContent?: "noContentAllowed",
+): 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 and logs out before the answer
@@ -309,7 +314,13 @@ async function adoptingWrite(path: string, init:
if (sessionGeneration !== generation) throw new StaleSessionError();
return apiFetch(path, { ...init, signal }, { generation, signal });
});
- if (res === undefined) return undefined;
+ 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) {
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
index c76068205..7020a78de 100644
--- a/web/src/api/twoFactor.test.ts
+++ b/web/src/api/twoFactor.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { confirmTwoFactor, setOnTokensChanged, setOnUnauthenticated, STEP_UP_HEADER, turnOffTwoFactor } from "./client";
+import { changePassword, confirmTwoFactor, logout, setOnTokensChanged, setOnUnauthenticated, STEP_UP_HEADER, turnOffTwoFactor } from "./client";
import { getTwoFactorStatus, regenerateRecoveryCodes, startTwoFactor } from "./cluckwork";
import { clearAccessToken, clearBoundAccount, getAccessToken, getBoundAccountId, setAccessToken } from "../auth/tokenStore";
import { freshCode } from "../test/codes";
@@ -102,6 +102,36 @@ describe("turnOffTwoFactor", () => {
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.toThrow();
+ });
+});
+
+// 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();
+ expect(getAccessToken()).toBe("at1");
+ });
});
// #1280 review — the 401 means the session went stale after the grant was
From 5fe1a37c292e91d7b2375fcbace1ca043b546613 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 14:35:52 +0000
Subject: [PATCH 11/45] fix(web): draw the QR code at exactly level M
uqr's boostEcc is off by default; QR_OPTIONS now says so, and G2.6 asserts it, so a later default change cannot raise the level the record measured.
Refs #1277
---
web/src/routes/account/TwoFactorQr.test.ts | 2 +-
web/src/routes/account/TwoFactorQr.tsx | 7 ++++---
2 files changed, 5 insertions(+), 4 deletions(-)
diff --git a/web/src/routes/account/TwoFactorQr.test.ts b/web/src/routes/account/TwoFactorQr.test.ts
index fa102ba1d..2f842f471 100644
--- a/web/src/routes/account/TwoFactorQr.test.ts
+++ b/web/src/routes/account/TwoFactorQr.test.ts
@@ -20,7 +20,7 @@ describe("G2.6: the worst-case otpauth URI", () => {
});
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.ecc).toBe("M");
+ 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
index c29dc79cc..ad7071dc9 100644
--- a/web/src/routes/account/TwoFactorQr.tsx
+++ b/web/src/routes/account/TwoFactorQr.tsx
@@ -2,9 +2,10 @@ import { useMemo } from "react";
import { Box } from "@mui/material";
import { encode } from "uqr";
-// #1274 decision 21 — level M, as the worst-case URI was measured against
-// (G2.6), and the four-module quiet zone the QR specification asks for.
-export const QR_OPTIONS = { ecc: "M", border: 4 } as const;
+// #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.
From 5214230c5349dc78a59512d64706054149a70811 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 14:37:04 +0000
Subject: [PATCH 12/45] refactor(web): word the step-up dialog from the fact
its fields read
The dialog took Set up or Replace from the status read and its code field from the session's two_factor claim. Both now come from the claim, so the words and the fields cannot disagree; the summary keeps the status, which alone carries the codes left. The copy table becomes three plain branches.
Refs #1277
---
web/src/routes/account/SecurityPanel.tsx | 25 +++++++++++-------------
web/src/routes/account/useTwoFactor.ts | 5 +++--
2 files changed, 14 insertions(+), 16 deletions(-)
diff --git a/web/src/routes/account/SecurityPanel.tsx b/web/src/routes/account/SecurityPanel.tsx
index c3756b65d..e3ccf7bbb 100644
--- a/web/src/routes/account/SecurityPanel.tsx
+++ b/web/src/routes/account/SecurityPanel.tsx
@@ -82,22 +82,19 @@ function Row({ children, action }: { children: ReactNode; action?: ReactNode })
);
}
-const TITLES = {
- start: { title: "setUpTitle", replaceTitle: "replaceTitle", body: "setUpBody", replaceBody: "replaceBody", submit: "continueButton" },
- regenerate: { title: "regenerateTitle", body: "regenerateBody", submit: "regenerateButton" },
- "turn-off": { title: "turnOffTitle", body: "turnOffBody", submit: "turnOffButton" },
-} as const;
-
-function copyFor(action: ProofAction, replacing: boolean) {
- const entry = TITLES[action];
- return "replaceTitle" in entry && replacing
- ? { title: entry.replaceTitle, body: entry.replaceBody, submit: entry.submit }
- : entry;
+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.
+// 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");
@@ -105,8 +102,8 @@ export function ProofDialog({ twoFactor }: { twoFactor: TwoFactor }) {
const { t: tc } = useTranslation("common");
const { twoFactor: enrolled } = useAuth();
const me = useMe();
- const { action, proof, setProof, closeProof, onProof, status, dialog: { busy, isPending, errors } } = twoFactor;
- const copy = action && copyFor(action, status.data?.enabled ?? false);
+ const { action, proof, setProof, closeProof, onProof, dialog: { busy, isPending, errors } } = twoFactor;
+ const copy = action && copyFor(action, enrolled);
return (
} />
+ } />
+
+
+
+
+ ,
+ );
+ }
+
+ it("keeps the codes and their dialog through repeated Back, and lets Back go once they are saved", async () => {
+ const codes = freshCodes();
+ vi.mocked(confirmTwoFactor).mockResolvedValue({ recoveryCodes: codes });
+ renderAtAccount();
+ await toScan();
+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: t("confirmButton") })); });
+ await screen.findByRole("dialog", { name: t("codesHeading") });
+
+ for (const _ of [1, 2]) await act(async () => { window.history.back(); await new Promise((r) => setTimeout(r, 50)); });
+
+ expect(window.location.pathname).toBe("/account");
+ expect(screen.getByRole("dialog", { name: t("codesHeading") })).toBeInTheDocument();
+ expect(screen.getByText(codes[0]!)).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("checkbox", { name: t("savedCheckbox") }));
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
+ await act(async () => { window.history.back(); await new Promise((r) => setTimeout(r, 50)); });
+
+ await waitFor(() => expect(screen.getByText("Elsewhere")).toBeInTheDocument());
+ });
+
+ it("asks before the tab closes until the codes are saved, and not after", async () => {
+ vi.mocked(confirmTwoFactor).mockResolvedValue({ recoveryCodes: freshCodes() });
+ renderAtAccount();
+ await toScan();
+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: t("confirmButton") })); });
+ await screen.findByRole("dialog", { name: t("codesHeading") });
+ const closing = () => {
+ const event = new Event("beforeunload", { cancelable: true });
+ window.dispatchEvent(event);
+ return event.defaultPrevented;
+ };
+
+ expect(closing()).toBe(true);
+ fireEvent.click(screen.getByRole("checkbox", { name: t("savedCheckbox") }));
+ expect(closing()).toBe(false);
+ });
+});
diff --git a/web/src/routes/account/TwoFactorFlow.tsx b/web/src/routes/account/TwoFactorFlow.tsx
index 80f5f9ecc..e2112967f 100644
--- a/web/src/routes/account/TwoFactorFlow.tsx
+++ b/web/src/routes/account/TwoFactorFlow.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useState } from "react";
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Alert, Box, Button, Checkbox, DialogActions, FormControlLabel, Link, Paper, Stack, TextField, Typography } from "@mui/material";
@@ -113,24 +113,15 @@ function RestartStep({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract<
// #1275 "Recovery codes", shown once: the codes are in this dialog's props and
// nowhere else, and leaving drops them. 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. Closing the tab asks
-// the browser to confirm. Browser Back is not guarded.
+// keeps the sidebar, the bottom nav and Help out of reach. useTwoFactor holds
+// Back and closing the tab until "saved" is ticked (MC3).
export function RecoveryCodesDialog({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract }) {
const { t } = useTranslation("account");
const me = useMe();
const { copy, notice, setNote } = useCopy();
- const [saved, setSaved] = useState(false);
+ const { codesSaved: saved, setCodesSaved: setSaved } = twoFactor;
const text = flow.codes.join("\n");
- useEffect(() => {
- const warn = (e: BeforeUnloadEvent) => {
- e.preventDefault();
- e.returnValue = "";
- };
- window.addEventListener("beforeunload", warn);
- return () => window.removeEventListener("beforeunload", warn);
- }, []);
-
const download = () => {
saveBlob(new Blob([`${t("codesFileTitle", { email: me?.email ?? "" })}\n\n${text}\n`], { type: "text/plain" }), "cluckwork-recovery-codes.txt");
setNote({ text: t("codesDownloaded"), ok: true });
diff --git a/web/src/routes/account/useHistoryHold.ts b/web/src/routes/account/useHistoryHold.ts
new file mode 100644
index 000000000..c82be91e4
--- /dev/null
+++ b/web/src/routes/account/useHistoryHold.ts
@@ -0,0 +1,29 @@
+import { useEffect } from "react";
+
+const SENTINEL = "cluckworkHold";
+const onSentinel = () => (window.history.state as Record | null)?.[SENTINEL] === true;
+
+// #1277 MC3 — while held, Back stays on the page: a sentinel entry sits on top
+// of this one, and a Back that pops it pushes it again. It copies the router's
+// own state, so the router sees the same location and nothing remounts.
+// Closing the tab asks the browser to confirm. Letting go pops the sentinel,
+// so history is left as it was.
+export function useHistoryHold(held: boolean) {
+ useEffect(() => {
+ if (!held) return;
+ const push = () => window.history.pushState({ ...(window.history.state as object | null), [SENTINEL]: true }, "");
+ const onPop = () => { if (!onSentinel()) push(); };
+ const onUnload = (e: BeforeUnloadEvent) => {
+ e.preventDefault();
+ e.returnValue = "";
+ };
+ push();
+ window.addEventListener("popstate", onPop);
+ window.addEventListener("beforeunload", onUnload);
+ return () => {
+ window.removeEventListener("popstate", onPop);
+ window.removeEventListener("beforeunload", onUnload);
+ if (onSentinel()) window.history.back();
+ };
+ }, [held]);
+}
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index 9265a2227..6dc756951 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -7,7 +7,9 @@ import type { StepUpProof } from "../../api/client";
import { useAuth } from "../../auth/useAuth";
import { useDialogAction } from "../../components/useDialogAction";
import { useLatestLoad } from "../../components/useLatestLoad";
+import { useShellLock } from "../../components/ShellLock";
import i18n from "../../i18n";
+import { useHistoryHold } from "./useHistoryHold";
// #1277 — the Security section's two-factor authentication. Start,
// Regenerate and Turn off each step up in a dialog first; confirm is the
@@ -47,6 +49,14 @@ export function useTwoFactor() {
const [proof, setProof] = useState(NO_PROOF);
const [code, setCode] = useState("");
const [message, setMessage] = useState(null);
+ const [codesSaved, setCodesSaved] = useState(false);
+
+ // #1277 MC3 (maintainer, 2026-11-05: "Block both"): confirm and regenerate
+ // hand out codes once, and unsaved codes exist only here, so the nav and
+ // Back stay on the page until they are settled and saved.
+ const confirming = dialog.isPending("confirm");
+ useShellLock(confirming);
+ useHistoryHold(confirming || dialog.isPending("regenerate") || (flow.step === "codes" && !codesSaved));
// #308 — a proof, a code, a key or a recovery code never outlives the session.
useEffect(() => {
@@ -89,6 +99,7 @@ export function useTwoFactor() {
});
status.retry();
if (!current()) return;
+ setCodesSaved(false);
setFlow({ step: "codes", codes: recoveryCodes, regenerated: true });
} else {
await turnOffTwoFactor(token);
@@ -138,6 +149,7 @@ export function useTwoFactor() {
status.retry();
if (!current()) return;
if (recoveryCodes) {
+ setCodesSaved(false);
setFlow({ step: "codes", codes: recoveryCodes, regenerated: false });
} else {
setFlow(SUMMARY);
@@ -153,7 +165,7 @@ export function useTwoFactor() {
}
return {
- status, flow, action, proof, setProof, code, setCode, message, dialog,
+ status, flow, action, proof, setProof, code, setCode, message, dialog, codesSaved, setCodesSaved,
openProof, closeProof, onProof, onConfirm, leaveFlow,
};
}
From 9bbe2192e88c2786791438636284c6c375ed3c83 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 16:06:06 +0000
Subject: [PATCH 19/45] fix(web): say why the recovery-codes dialog does not
close, and return focus
The locked dialog gave no reason it would not close. It now says 'Save the codes, then tick the box to finish.' in en, es and tl, as its accessible description, which leaves the codes list out. Done, or Escape once saved, returns focus to the Security section instead of , because the trigger that opened the dialog is gone.
Refs #1277
---
web/src/i18n/en.ts | 1 +
web/src/i18n/es.ts | 1 +
web/src/i18n/tl.ts | 1 +
web/src/routes/account/Security.test.tsx | 7 +++++--
web/src/routes/account/SecurityPanel.tsx | 4 +++-
web/src/routes/account/TwoFactorFlow.tsx | 16 +++++++++++++---
6 files changed, 24 insertions(+), 6 deletions(-)
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 6a441bc44..85ec4284d 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -356,6 +356,7 @@ export const en = {
downloadButton: "Download codes",
codesDownloaded: "Download started. Check the file before you leave.",
codesFileTitle: "Cluckwork recovery codes for {{email}}",
+ codesLockedHint: "Save the codes, then tick the box to finish.",
savedCheckbox: "I saved my recovery codes somewhere safe.",
doneButton: "Done",
replacedMessage: "Your new authenticator app is set up. The old one no longer works.",
diff --git a/web/src/i18n/es.ts b/web/src/i18n/es.ts
index f5f2fa248..7aa65f986 100644
--- a/web/src/i18n/es.ts
+++ b/web/src/i18n/es.ts
@@ -287,6 +287,7 @@ export const es = {
downloadButton: "Descargar códigos",
codesDownloaded: "Descarga iniciada. Revise el archivo antes de salir.",
codesFileTitle: "Códigos de recuperación de Cluckwork para {{email}}",
+ codesLockedHint: "Guarde los códigos y luego marque la casilla para terminar.",
savedCheckbox: "Guardé mis códigos de recuperación en un lugar seguro.",
doneButton: "Listo",
replacedMessage: "Su nueva aplicación de autenticación está configurada. La anterior ya no funciona.",
diff --git a/web/src/i18n/tl.ts b/web/src/i18n/tl.ts
index 663cccc89..5d360bb72 100644
--- a/web/src/i18n/tl.ts
+++ b/web/src/i18n/tl.ts
@@ -296,6 +296,7 @@ export const tl = {
downloadButton: "I-download ang mga code",
codesDownloaded: "Nagsimula ang download. Tingnan ang file bago ka umalis.",
codesFileTitle: "Mga recovery code ng Cluckwork para kay {{email}}",
+ codesLockedHint: "I-save ang mga code, tapos lagyan ng tsek ang kahon para matapos.",
savedCheckbox: "Na-save ko ang aking mga recovery code sa ligtas na lugar.",
doneButton: "Tapos na",
replacedMessage: "Naka-set up na ang bago mong authenticator app. Hindi na gumagana ang luma.",
diff --git a/web/src/routes/account/Security.test.tsx b/web/src/routes/account/Security.test.tsx
index bc0d31f27..921f50c26 100644
--- a/web/src/routes/account/Security.test.tsx
+++ b/web/src/routes/account/Security.test.tsx
@@ -179,6 +179,7 @@ describe("enrolment", () => {
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();
});
@@ -194,12 +195,14 @@ describe("enrolment", () => {
await press(t("confirmButton"));
const codes = await screen.findByRole("dialog", { name: t("codesHeading") });
- expect(within(codes).getByRole("button", { name: "Close" })).toBeDisabled();
+ 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: "Close" })).toBeEnabled();
+ 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();
diff --git a/web/src/routes/account/SecurityPanel.tsx b/web/src/routes/account/SecurityPanel.tsx
index ca63e3d71..71945d087 100644
--- a/web/src/routes/account/SecurityPanel.tsx
+++ b/web/src/routes/account/SecurityPanel.tsx
@@ -15,6 +15,8 @@ import { StatusDot } from "../dashboard/StatusDot";
import { LOW_RECOVERY_CODES } from "./useTwoFactor";
import type { ProofAction, TwoFactor } from "./useTwoFactor";
+export const SECURITY_SUMMARY_ID = "account-security";
+
// #1275 "Account": the status, the recovery codes left, Regenerate and Turn
// off together in one accordion.
export function SecurityPanel({ twoFactor }: { twoFactor: TwoFactor }) {
@@ -25,7 +27,7 @@ export function SecurityPanel({ twoFactor }: { twoFactor: TwoFactor }) {
return (
- }>
+ }>
{t("securityHeading")}
diff --git a/web/src/routes/account/TwoFactorFlow.tsx b/web/src/routes/account/TwoFactorFlow.tsx
index e2112967f..b7c2a8ad0 100644
--- a/web/src/routes/account/TwoFactorFlow.tsx
+++ b/web/src/routes/account/TwoFactorFlow.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useId, useState } from "react";
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Alert, Box, Button, Checkbox, DialogActions, FormControlLabel, Link, Paper, Stack, TextField, Typography } from "@mui/material";
@@ -8,6 +8,7 @@ import { DialogError } from "../../components/DialogError";
import { saveBlob } from "../../lib/saveBlob";
import { useMe } from "../../session/SessionContext";
import { TwoFactorQr } from "./TwoFactorQr";
+import { SECURITY_SUMMARY_ID } from "./SecurityPanel";
import type { Flow, TwoFactor } from "./useTwoFactor";
// #1275 "Enrolment A": the steps that replace the Account page while they run,
@@ -119,7 +120,14 @@ export function RecoveryCodesDialog({ twoFactor, flow }: { twoFactor: TwoFactor;
const { t } = useTranslation("account");
const me = useMe();
const { copy, notice, setNote } = useCopy();
+ const hintId = useId();
const { codesSaved: saved, setCodesSaved: setSaved } = twoFactor;
+ // The trigger that opened this dialog is gone by now, so focus returns to
+ // the Security section instead of falling to .
+ const done = () => {
+ twoFactor.leaveFlow();
+ requestAnimationFrame(() => document.getElementById(SECURITY_SUMMARY_ID)?.focus());
+ };
const text = flow.codes.join("\n");
const download = () => {
@@ -131,12 +139,13 @@ export function RecoveryCodesDialog({ twoFactor, flow }: { twoFactor: TwoFactor;
From edfbf3a75ab90cba82d0bb3adfdf9ab83884b565 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 16:06:55 +0000
Subject: [PATCH 20/45] fix(web): tell a stale session's confirm why the set-up
ended
The restart step said the set-up had expired when the session had changed under confirm. It now says 'Your sign-in changed, so this set-up ended.', in en, es and tl.
Refs #1277
---
web/src/i18n/en.ts | 1 +
web/src/i18n/es.ts | 1 +
web/src/i18n/tl.ts | 1 +
web/src/routes/account/Security.test.tsx | 2 +-
web/src/routes/account/TwoFactorFlow.tsx | 4 +++-
web/src/routes/account/useTwoFactor.ts | 5 +++--
6 files changed, 10 insertions(+), 4 deletions(-)
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 85ec4284d..930df80c2 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -343,6 +343,7 @@ export const en = {
codeIncorrectAttempts_one: "That code did not work. Try the next code in your app. {{count}} try left.",
codeIncorrectAttempts_other: "That code did not work. Try the next code in your app. {{count}} tries left.",
setUpExpired: "This set-up expired. Start again to get a new QR code.",
+ setUpSessionChanged: "Your sign-in changed, so this set-up ended. Start again to get a new QR code.",
setUpTooManyAttempts: "Too many wrong codes. Start again to get a new QR code.",
startAgainButton: "Start again",
codesHeading: "Save your recovery codes",
diff --git a/web/src/i18n/es.ts b/web/src/i18n/es.ts
index 7aa65f986..9b6c4f41c 100644
--- a/web/src/i18n/es.ts
+++ b/web/src/i18n/es.ts
@@ -274,6 +274,7 @@ export const es = {
codeIncorrectAttempts_one: "Ese código no funcionó. Pruebe el siguiente código de su aplicación. Queda {{count}} intento.",
codeIncorrectAttempts_other: "Ese código no funcionó. Pruebe el siguiente código de su aplicación. Quedan {{count}} intentos.",
setUpExpired: "Esta configuración caducó. Empiece de nuevo para obtener un código QR nuevo.",
+ setUpSessionChanged: "Su inicio de sesión cambió, así que esta configuración terminó. Empiece de nuevo para obtener un código QR nuevo.",
setUpTooManyAttempts: "Demasiados códigos incorrectos. Empiece de nuevo para obtener un código QR nuevo.",
startAgainButton: "Empezar de nuevo",
codesHeading: "Guarde sus códigos de recuperación",
diff --git a/web/src/i18n/tl.ts b/web/src/i18n/tl.ts
index 5d360bb72..4af5d2452 100644
--- a/web/src/i18n/tl.ts
+++ b/web/src/i18n/tl.ts
@@ -283,6 +283,7 @@ export const tl = {
codeIncorrectAttempts_one: "Hindi gumana ang code na iyon. Subukan ang susunod na code sa iyong app. {{count}} subok na lang.",
codeIncorrectAttempts_other: "Hindi gumana ang code na iyon. Subukan ang susunod na code sa iyong app. {{count}} subok na lang.",
setUpExpired: "Nag-expire ang set-up na ito. Magsimula ulit para makakuha ng bagong QR code.",
+ setUpSessionChanged: "Nagbago ang iyong sign-in, kaya natapos ang set-up na ito. Magsimula ulit para makakuha ng bagong QR code.",
setUpTooManyAttempts: "Sobrang daming maling code. Magsimula ulit para makakuha ng bagong QR code.",
startAgainButton: "Magsimula ulit",
codesHeading: "I-save ang iyong mga recovery code",
diff --git a/web/src/routes/account/Security.test.tsx b/web/src/routes/account/Security.test.tsx
index 921f50c26..8cd9c9e2d 100644
--- a/web/src/routes/account/Security.test.tsx
+++ b/web/src/routes/account/Security.test.tsx
@@ -228,7 +228,7 @@ describe("enrolment", () => {
["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("setUpExpired")],
+ ["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();
diff --git a/web/src/routes/account/TwoFactorFlow.tsx b/web/src/routes/account/TwoFactorFlow.tsx
index b7c2a8ad0..0a5764919 100644
--- a/web/src/routes/account/TwoFactorFlow.tsx
+++ b/web/src/routes/account/TwoFactorFlow.tsx
@@ -29,6 +29,8 @@ export function TwoFactorFlow({ twoFactor }: { twoFactor: TwoFactor }) {
const heading = (replacing: boolean) => (replacing ? "replaceHeading" : "enrolHeading");
+const RESTART_REASONS = { expired: "setUpExpired", attempts: "setUpTooManyAttempts", session: "setUpSessionChanged" } as const;
+
// Copy and download feedback, announced in one live region.
function useCopy() {
const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);
@@ -102,7 +104,7 @@ function RestartStep({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract<
return (
{t(heading(flow.replacing))}
- {t(flow.reason === "expired" ? "setUpExpired" : "setUpTooManyAttempts")}
+ {t(RESTART_REASONS[flow.reason])}
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index 6dc756951..675d4c4ad 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -25,7 +25,7 @@ export const LOW_RECOVERY_CODES = 2;
export type Flow =
| { step: "summary" }
| { step: "scan"; enrolment: EnrolmentStart; replacing: boolean }
- | { step: "restart"; replacing: boolean; reason: "expired" | "attempts" }
+ | { step: "restart"; replacing: boolean; reason: "expired" | "attempts" | "session" }
| { step: "codes"; codes: string[]; regenerated: boolean };
const SUMMARY: Flow = { step: "summary" };
@@ -140,7 +140,8 @@ export function useTwoFactor() {
// 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") || isProblem(err, 401, "Auth.CredentialsSuperseded") ? "expired"
+ 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 });
From 10f2b2ff716f81a81368616d4e4d79095026763c Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 16:08:05 +0000
Subject: [PATCH 21/45] docs(web): fix the antecedents in the step-up and
Security text
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
'On Account, Security, Set up asks' read as a list of four; it is now 'Under Account › Security, Set up asks', in the repo's bold-each-step style, in en, es and tl. 'These actions on the Users screen' pointed at nothing and becomes 'Some actions'. The glossary's step-up entry no longer opens on an Owner access token while its last sentence says any user steps up on the Account page.
Refs #1277
---
specs/product/GLOSSARY.md | 4 ++--
web/src/i18n/en.ts | 12 ++++++------
web/src/i18n/es.ts | 12 ++++++------
web/src/i18n/tl.ts | 12 ++++++------
web/src/routes/HelpPage.test.tsx | 4 ++--
5 files changed, 22 insertions(+), 22 deletions(-)
diff --git a/specs/product/GLOSSARY.md b/specs/product/GLOSSARY.md
index fb4fb72ac..d50c4c999 100644
--- a/specs/product/GLOSSARY.md
+++ b/specs/product/GLOSSARY.md
@@ -1543,8 +1543,8 @@ 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, #1277)** — a fresh proof of identity
-required, on top of a normal valid Owner access token, before these Users-screen
-actions: **creating any user**, **resetting any user's password**,
+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
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 930df80c2..85d426f05 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -3369,7 +3369,7 @@ export const en = {
// #308/#356/#360 — deliberately does NOT mention "grant"/"token" —
// that's internal mechanism, not user-facing language.
signingInStepUp:
- "These actions on the Users screen ask you to re-enter your current password "
+ "Some actions on the Users screen ask you to re-enter your current password "
+ "right there in the dialog: creating any user, resetting any user's password, changing any user's role, "
+ "changing a login email, disabling a user, re-enabling a user, resetting a user's two-factor authentication, "
+ "assigning a worker to a flock, and "
@@ -3378,7 +3378,7 @@ export const en = {
+ "When two-factor authentication is on for your account, these actions, Allow for a "
+ "connected app and Change password also ask for an Authenticator code or recovery "
+ "code. Each code works once, so for a second action straight after, wait for the next code. "
- + "On Account, Security, Set up asks for your password, and "
+ + "Under Account › Security, Set up asks for your password, and "
+ "Replace authenticator app, Regenerate and Turn off ask "
+ "for your password and a code.",
signingInAppAddress:
@@ -4307,7 +4307,7 @@ export const en = {
+ "screen asks you to re-enter your current password right there in the dialog. It confirms it's really "
+ "you before handing out — or taking away — access. Display-name changes do not ask again. "
+ "With two-factor authentication on, the dialog also asks for a code from your authenticator app or a recovery code. "
- + "On Account, Security, Set up asks for your password, and Replace authenticator app, Regenerate and Turn off "
+ + "Under Account › Security, Set up asks for your password, and Replace authenticator app, Regenerate and Turn off "
+ "ask for your password and a code.",
glossarySomethingWentWrongScreenTerm: "\"Something went wrong\" screen",
glossarySomethingWentWrongScreenDef:
@@ -4623,7 +4623,7 @@ export const en = {
glossaryTwoFactorAuthTerm: "Two-factor authentication",
glossaryTwoFactorAuthDef:
"Signing in with your password and a second proof from your phone: a code from your authenticator app, "
- + "or a recovery code without the phone. Turn it on in Account, Security, with Set up. Turning it on signs "
+ + "or a recovery code without the phone. Turn it on in Account › Security, with Set up. Turning it on signs "
+ "out your other devices and connected apps.",
glossaryAuthenticatorAppTerm: "Authenticator app",
glossaryAuthenticatorAppDef:
@@ -4636,10 +4636,10 @@ export const en = {
glossaryRecoveryCodeTerm: "Recovery code",
glossaryRecoveryCodeDef:
"One of ten codes you get once, when you turn on two-factor authentication, for when you can't use your "
- + "phone. Each works once. Account, Security, shows how many are left, and Regenerate replaces the set.",
+ + "phone. Each works once. Account › Security shows how many are left, and Regenerate replaces the set.",
glossaryTurnOffTwoFactorTerm: "Turn off two-factor authentication",
glossaryTurnOffTwoFactorDef:
- "Removing your own second factor, with Turn off in Account, Security. Your authenticator app and recovery "
+ "Removing your own second factor, with Turn off in Account › Security. Your authenticator app and recovery "
+ "codes stop working, your other devices and connected apps are signed out, and you sign in with your "
+ "password only.",
diff --git a/web/src/i18n/es.ts b/web/src/i18n/es.ts
index 9b6c4f41c..b6d431700 100644
--- a/web/src/i18n/es.ts
+++ b/web/src/i18n/es.ts
@@ -2618,7 +2618,7 @@ export const es = {
+ "incorrectos.",
// #308/#356/#360 (machine-drafted, pending native review)
signingInStepUp:
- "Estas acciones en la pantalla Usuarios le piden volver a ingresar su contraseña "
+ "Algunas acciones en la pantalla Usuarios le piden volver a ingresar su contraseña "
+ "actual directamente en el diálogo: crear cualquier usuario, restablecer la contraseña de cualquier "
+ "usuario, cambiar el rol de cualquier usuario, cambiar un correo de inicio de sesión, deshabilitar un usuario, "
+ "volver a habilitar un usuario, restablecer la autenticación en dos pasos de un usuario, asignar un "
@@ -2629,7 +2629,7 @@ export const es = {
+ "para una aplicación conectada y Cambiar contraseña piden también un Código de "
+ "autenticación o código de recuperación. Cada código funciona una vez, así que para una segunda "
+ "acción justo después, espere el siguiente código. "
- + "En Cuenta, Seguridad, Configurar pide su contraseña, y "
+ + "En Cuenta › Seguridad, Configurar pide su contraseña, y "
+ "Reemplazar aplicación de autenticación, Regenerar y "
+ "Desactivar piden su contraseña y un código.",
signingInAppAddress:
@@ -3613,7 +3613,7 @@ export const es = {
+ "a ingresar su contraseña actual directamente en el diálogo. Esto confirma que realmente es usted antes "
+ "de otorgar — o retirar — acceso. Los cambios de nombre para mostrar no vuelven a pedirla. "
+ "Con la autenticación en dos pasos activada, el diálogo también pide un código de su aplicación de autenticación o un código de recuperación. "
- + "En Cuenta, Seguridad, Configurar pide su contraseña, y Reemplazar aplicación de autenticación, Regenerar y "
+ + "En Cuenta › Seguridad, Configurar pide su contraseña, y Reemplazar aplicación de autenticación, Regenerar y "
+ "Desactivar piden su contraseña y un código.",
glossarySomethingWentWrongScreenTerm: "Pantalla \"Algo salió mal\"",
glossarySomethingWentWrongScreenDef:
@@ -3964,7 +3964,7 @@ export const es = {
glossaryTwoFactorAuthTerm: "Autenticación en dos pasos",
glossaryTwoFactorAuthDef:
"Iniciar sesión con su contraseña y una segunda prueba de su teléfono: un código de su aplicación de "
- + "autenticación, o un código de recuperación sin el teléfono. Actívela en Cuenta, Seguridad, con "
+ + "autenticación, o un código de recuperación sin el teléfono. Actívela en Cuenta › Seguridad, con "
+ "Configurar. Al activarla se cierra la sesión en sus otros dispositivos y aplicaciones conectadas.",
glossaryAuthenticatorAppTerm: "Aplicación de autenticación",
glossaryAuthenticatorAppDef:
@@ -3977,11 +3977,11 @@ export const es = {
glossaryRecoveryCodeTerm: "Código de recuperación",
glossaryRecoveryCodeDef:
"Uno de diez códigos que recibe una vez, al activar la autenticación en dos pasos, para cuando no puede "
- + "usar su teléfono. Cada uno funciona una vez. Cuenta, Seguridad, muestra cuántos quedan, y Regenerar "
+ + "usar su teléfono. Cada uno funciona una vez. Cuenta › Seguridad muestra cuántos quedan, y Regenerar "
+ "reemplaza el juego.",
glossaryTurnOffTwoFactorTerm: "Desactivar la autenticación en dos pasos",
glossaryTurnOffTwoFactorDef:
- "Quitar su propio segundo factor, con Desactivar en Cuenta, Seguridad. Su aplicación de autenticación y "
+ "Quitar su propio segundo factor, con Desactivar en Cuenta › Seguridad. Su aplicación de autenticación y "
+ "sus códigos de recuperación dejan de funcionar, se cierra la sesión en sus otros dispositivos y "
+ "aplicaciones conectadas, e inicia sesión solo con su contraseña.",
diff --git a/web/src/i18n/tl.ts b/web/src/i18n/tl.ts
index 4af5d2452..4c079a6e1 100644
--- a/web/src/i18n/tl.ts
+++ b/web/src/i18n/tl.ts
@@ -2721,7 +2721,7 @@ export const tl = {
+ "para sa isang connected app at ang Palitan ang password ay humihingi rin ng Authenticator "
+ "code o recovery code. Isang beses lang gumagana ang bawat code, kaya para sa pangalawang aksyon "
+ "kaagad pagkatapos, hintayin ang susunod na code. "
- + "Sa Account, Seguridad, hinihingi ng I-set up ang iyong "
+ + "Sa Account › Seguridad, hinihingi ng I-set up ang iyong "
+ "password, at hinihingi ng Palitan ang authenticator app, Gumawa ulit at "
+ "I-off ang iyong password at isang code.",
signingInAppAddress:
@@ -3743,7 +3743,7 @@ export const tl = {
+ "mong password mismo sa dialog. Kinukumpirma nito na ikaw talaga bago magbigay — o mag-alis — ng access. "
+ "Hindi muling hinihingi ito sa mga pagbabago ng display name. "
+ "Kapag naka-on ang two-factor authentication, humihingi rin ang dialog ng code mula sa iyong authenticator app o isang recovery code. "
- + "Sa Account, Seguridad, hinihingi ng I-set up ang iyong password, at hinihingi ng Palitan ang authenticator app, "
+ + "Sa Account › Seguridad, hinihingi ng I-set up ang iyong password, at hinihingi ng Palitan ang authenticator app, "
+ "Gumawa ulit at I-off ang iyong password at isang code.",
glossarySomethingWentWrongScreenTerm: "Screen na \"Something went wrong\"",
glossarySomethingWentWrongScreenDef:
@@ -4104,7 +4104,7 @@ export const tl = {
glossaryTwoFactorAuthTerm: "Two-factor authentication",
glossaryTwoFactorAuthDef:
"Pag-sign in gamit ang iyong password at pangalawang patunay mula sa iyong phone: isang code mula sa "
- + "iyong authenticator app, o isang recovery code kung wala ang phone. I-on ito sa Account, Seguridad, "
+ + "iyong authenticator app, o isang recovery code kung wala ang phone. I-on ito sa Account › Seguridad, "
+ "gamit ang I-set up. Kapag in-on ito, masa-sign out ang iba mo pang device at mga connected app.",
glossaryAuthenticatorAppTerm: "Authenticator app",
glossaryAuthenticatorAppDef:
@@ -4117,11 +4117,11 @@ export const tl = {
glossaryRecoveryCodeTerm: "Recovery code",
glossaryRecoveryCodeDef:
"Isa sa sampung code na isang beses mong makukuha, kapag in-on mo ang two-factor authentication, para sa "
- + "oras na hindi mo magamit ang iyong phone. Isang beses gumagana ang bawat isa. Ipinapakita ng Account, "
- + "Seguridad, kung ilan ang natitira, at pinapalitan ng Gumawa ulit ang buong set.",
+ + "oras na hindi mo magamit ang iyong phone. Isang beses gumagana ang bawat isa. Ipinapakita ng Account › "
+ + "Seguridad kung ilan ang natitira, at pinapalitan ng Gumawa ulit ang buong set.",
glossaryTurnOffTwoFactorTerm: "I-off ang two-factor authentication",
glossaryTurnOffTwoFactorDef:
- "Pag-alis ng sarili mong pangalawang factor, gamit ang I-off sa Account, Seguridad. Hihinto sa paggana "
+ "Pag-alis ng sarili mong pangalawang factor, gamit ang I-off sa Account › Seguridad. Hihinto sa paggana "
+ "ang iyong authenticator app at mga recovery code, masa-sign out ang iba mo pang device at mga connected "
+ "app, at password lang ang gagamitin mo sa pag-sign in.",
diff --git a/web/src/routes/HelpPage.test.tsx b/web/src/routes/HelpPage.test.tsx
index 4d6516cfc..d07ddb474 100644
--- a/web/src/routes/HelpPage.test.tsx
+++ b/web/src/routes/HelpPage.test.tsx
@@ -398,7 +398,7 @@ describe("HelpPage", () => {
// 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(/These 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);
@@ -409,7 +409,7 @@ describe("HelpPage", () => {
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(/Set up asks for your password, and Replace authenticator app, Regenerate and Turn off ask for your password and a code/i);
+ 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);
From 629f263b861b58db84caf32d854c1b658a277191 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 16:08:38 +0000
Subject: [PATCH 22/45] docs(web): drop the one-caller claim from
fullScreenOnPhone
The recovery-codes dialog is a second caller, so Dialog's JSDoc and BottomNav's comment no longer say the More menu is the only one.
Refs #1277
---
web/src/components/BottomNav.tsx | 8 ++++----
web/src/components/Dialog.tsx | 4 ++--
2 files changed, 6 insertions(+), 6 deletions(-)
diff --git a/web/src/components/BottomNav.tsx b/web/src/components/BottomNav.tsx
index 1f7dcfc87..bf9a203ec 100644
--- a/web/src/components/BottomNav.tsx
+++ b/web/src/components/BottomNav.tsx
@@ -28,10 +28,10 @@ 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
+// `Dialog` component #827 shipped, rendering `fullScreen` below 900px — form
+// dialogs stay centred and sized to their content (owner, 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.
diff --git a/web/src/components/Dialog.tsx b/web/src/components/Dialog.tsx
index a833fd3e7..2dd28bf0b 100644
--- a/web/src/components/Dialog.tsx
+++ b/web/src/components/Dialog.tsx
@@ -116,8 +116,8 @@ interface DialogProps {
/**
* Whether this dialog takes the whole screen below 900px. Off by default:
* form dialogs and confirmations alike stay a centred dialog sized to their
- * content at every width. The phone More menu (`BottomNav.tsx`) is the one
- * caller that turns it on, because a twenty-link menu needs the height.
+ * content at every width. A dialog that needs the whole height turns it on:
+ * the phone More menu (`BottomNav.tsx`), and the recovery codes (#1277).
*/
fullScreenOnPhone?: boolean;
/** Fixed footer, outside the scrolling body and its picker overlays. */
From 5a85fa5d3b8ad8ca533246cc21dd79faa57ae1a1 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 16:09:12 +0000
Subject: [PATCH 23/45] test(web): walk the hook's whole result for the codes,
and group the plain-401 cases
The codes-lifetime tests now look for the code anywhere in the hook's result, not only in its flow, after checking it is there while the codes show. The two expired-token cases move out of the CredentialsSuperseded block into their own.
Refs #1277
---
web/src/api/twoFactor.test.ts | 3 +++
web/src/routes/account/useTwoFactor.test.tsx | 8 +++++++-
2 files changed, 10 insertions(+), 1 deletion(-)
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
index fdc66dcb6..0352bba81 100644
--- a/web/src/api/twoFactor.test.ts
+++ b/web/src/api/twoFactor.test.ts
@@ -164,7 +164,10 @@ describe("a stale session's 401 Auth.CredentialsSuperseded", () => {
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
diff --git a/web/src/routes/account/useTwoFactor.test.tsx b/web/src/routes/account/useTwoFactor.test.tsx
index c7ac7cdba..3c51f4603 100644
--- a/web/src/routes/account/useTwoFactor.test.tsx
+++ b/web/src/routes/account/useTwoFactor.test.tsx
@@ -18,10 +18,13 @@ 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: [crypto.randomUUID()] });
+ vi.mocked(regenerateRecoveryCodes).mockResolvedValue({ recoveryCodes: [code] });
vi.mocked(stepUp).mockResolvedValue({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" });
});
@@ -32,6 +35,7 @@ async function onCodesStep() {
act(() => hook.result.current.setProof({ password: crypto.randomUUID() }));
await act(async () => { await hook.result.current.onProof({ preventDefault() {} } as FormEvent); });
expect(hook.result.current.flow.step).toBe("codes");
+ expect(JSON.stringify(hook.result.current)).toContain(code);
return hook;
}
@@ -42,6 +46,7 @@ describe("the recovery codes' lifetime", () => {
act(() => result.current.leaveFlow());
expect(result.current.flow).toEqual({ step: "summary" });
+ expect(JSON.stringify(result.current)).not.toContain(code);
});
it("ends when the session does", async () => {
@@ -51,5 +56,6 @@ describe("the recovery codes' lifetime", () => {
rerender();
expect(result.current.flow).toEqual({ step: "summary" });
+ expect(JSON.stringify(result.current)).not.toContain(code);
});
});
From 4324128ce2c5376901cb51e6a8d7680896db2102 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 17:02:36 +0000
Subject: [PATCH 24/45] fix(web): keep unsaved recovery codes in a slot above
the routes
MC3's sentinel and inert shell still lost the codes in a browser: the skip link remounted Account, and history.go(-2) passed the one-entry sentinel. The maintainer chose to keep the codes above the pages instead. RecoveryCodesProvider, inside AuthProvider and around the router, holds the unsaved set ({ codes, regenerated, saved, email }) and renders the locked dialog. A confirm or regenerate that settles after its page is gone still lands there, so no navigation drops the codes; the slot clears when the session ends and drops a late set whose session generation has passed. saved is part of the value, so a new set starts unticked, and beforeunload is armed while it is false. useHistoryHold, ShellLock and AppLayout's inert wrappers are gone, so Sign out stays reachable during a stalled confirm.
Refs #1277
---
web/src/App.tsx | 5 +
web/src/api/client.ts | 2 +-
web/src/api/session.ts | 4 +
web/src/components/ShellLock.tsx | 15 -
web/src/routes/AccountPage.tsx | 9 +-
web/src/routes/AppLayout.tsx | 17 +-
.../routes/account/Security.leaving.test.tsx | 141 --------
web/src/routes/account/Security.test.tsx | 9 +-
web/src/routes/account/SecurityPanel.tsx | 3 +-
web/src/routes/account/TwoFactorFlow.tsx | 84 +----
web/src/routes/account/recoveryCodes.test.tsx | 336 ++++++++++++++++++
web/src/routes/account/recoveryCodes.tsx | 150 ++++++++
web/src/routes/account/useHistoryHold.ts | 29 --
web/src/routes/account/useTwoFactor.test.tsx | 43 +--
web/src/routes/account/useTwoFactor.ts | 49 ++-
web/src/test/renderWithProviders.tsx | 3 +
16 files changed, 550 insertions(+), 349 deletions(-)
delete mode 100644 web/src/components/ShellLock.tsx
delete mode 100644 web/src/routes/account/Security.leaving.test.tsx
create mode 100644 web/src/routes/account/recoveryCodes.test.tsx
create mode 100644 web/src/routes/account/recoveryCodes.tsx
delete mode 100644 web/src/routes/account/useHistoryHold.ts
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 4263c7b86..f9dc9d4fa 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 MC4 — 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.ts b/web/src/api/client.ts
index 0b38e5eee..0ef56be04 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -1,6 +1,6 @@
export { STEP_UP_HEADER } from "./request";
export { apiGet, apiPost, apiPut, apiPutBytes, apiDelete, apiGetBlob, apiFetch, restoreSession } from "./refresh";
-export { login, completeSecondFactor, changePassword, confirmTwoFactor, turnOffTwoFactor, stepUp, logout, NO_PROOF } from "./session";
+export { login, completeSecondFactor, changePassword, confirmTwoFactor, turnOffTwoFactor, stepUp, logout, NO_PROOF, currentSessionGeneration } from "./session";
export type { LoginOutcome, StepUpProof } from "./session";
export { setOnUnauthenticated, setOnTokensChanged } from "./sessionState";
export { getLastTraceId } from "./trace";
diff --git a/web/src/api/session.ts b/web/src/api/session.ts
index c8179b2bc..50979b26a 100644
--- a/web/src/api/session.ts
+++ b/web/src/api/session.ts
@@ -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,
diff --git a/web/src/components/ShellLock.tsx b/web/src/components/ShellLock.tsx
deleted file mode 100644
index 612bbe8dc..000000000
--- a/web/src/components/ShellLock.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import { createContext, useContext, useEffect } from "react";
-
-// #1277 MC3 — a screen holds the app shell (the rail and the bottom nav) inert
-// while a write the user must not walk away from is in flight. AppLayout
-// counts the holders, so two screens' holds never release each other's.
-export const ShellLockContext = createContext<(delta: 1 | -1) => void>(() => {});
-
-export function useShellLock(locked: boolean) {
- const adjust = useContext(ShellLockContext);
- useEffect(() => {
- if (!locked) return;
- adjust(1);
- return () => adjust(-1);
- }, [locked, adjust]);
-}
diff --git a/web/src/routes/AccountPage.tsx b/web/src/routes/AccountPage.tsx
index 1ba99150f..41019b367 100644
--- a/web/src/routes/AccountPage.tsx
+++ b/web/src/routes/AccountPage.tsx
@@ -21,7 +21,7 @@ import { SUPPORTED_LANGUAGES } from "../i18n";
import { roleLabel } from "../i18n/enums";
import { errText } from "../lib/errText";
import { ProofDialog, SecurityPanel } from "./account/SecurityPanel";
-import { RecoveryCodesDialog, TwoFactorFlow } from "./account/TwoFactorFlow";
+import { TwoFactorFlow } from "./account/TwoFactorFlow";
import { useTwoFactor } from "./account/useTwoFactor";
const MIN_LENGTH = 12;
@@ -79,11 +79,11 @@ export function AccountPage() {
});
}
- // #1277 — enrolment takes the page while it runs; new recovery codes open
- // over it in a locked dialog.
+ // #1277 — enrolment takes the page while it runs. New recovery codes open in
+ // the slot above the routes (account/recoveryCodes.tsx).
const proofDialog = ;
const { flow } = twoFactorSection;
- if (flow.step === "scan" || flow.step === "restart") return <>{proofDialog}>;
+ if (flow.step !== "summary") return <>{proofDialog}>;
return (
@@ -161,7 +161,6 @@ export function AccountPage() {
{proofDialog}
- {flow.step === "codes" && }
diff --git a/web/src/routes/AppLayout.tsx b/web/src/routes/AppLayout.tsx
index 10ae5a50b..7b9166ad1 100644
--- a/web/src/routes/AppLayout.tsx
+++ b/web/src/routes/AppLayout.tsx
@@ -1,4 +1,4 @@
-import { Fragment, Suspense, useCallback, useEffect, useState } from "react";
+import { Fragment, Suspense, useEffect } from "react";
import { NavLink, Outlet, useLocation, useNavigate } from "react-router";
import { LogOut, RefreshCw } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -11,7 +11,6 @@ import { BottomNav } from "../components/BottomNav";
import { useMissedAnnouncement } from "../components/useMissedAnnouncement";
import { ErrorBoundary } from "../components/ErrorBoundary";
import { FarmBrand } from "../components/FarmBrand";
-import { ShellLockContext } from "../components/ShellLock";
import { useFarm } from "../farm/useFarm";
import { reopenUpdate, useIsUpdateWaiting } from "../pwa/updateStore";
import { navGroups, tabEntries } from "./nav";
@@ -72,20 +71,12 @@ export function AppLayout() {
navigate("/login", { replace: true });
}
- // #1277 MC3 — screens that must not be left mid-write hold the shell inert.
- const [shellLocks, setShellLocks] = useState(0);
- const adjustShellLock = useCallback((delta: 1 | -1) => setShellLocks((n) => n + delta), []);
- const shellInert = shellLocks > 0 || undefined;
-
return (
-
{/* First focusable element: lets a keyboard/screen-reader user jump past
the nav links straight to the screen content (#182, Task 7). */}
{t("skipToContent")}
- {/* display: contents, as SessionContext's splash wrapper: it only carries inert. */}
-
` (the `complementary` landmark, ax.ts / the e2e `nav`
@@ -151,7 +142,6 @@ export function AppLayout() {
)}
-
{/* Carries the warning the banner below could not announce because a
@@ -199,10 +189,7 @@ export function AppLayout() {
-
-
-
+
-
);
}
diff --git a/web/src/routes/account/Security.leaving.test.tsx b/web/src/routes/account/Security.leaving.test.tsx
deleted file mode 100644
index 2e3a8ab8d..000000000
--- a/web/src/routes/account/Security.leaving.test.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
-import { BrowserRouter, Route, Routes } from "react-router";
-import { AccountPage } from "../AccountPage";
-import { AppLayout } from "../AppLayout";
-import { renderWithProviders } from "../../test/renderWithProviders";
-import { farmState } from "../../test/fixtures";
-import { freshCode } from "../../test/codes";
-import { setStoredToken } from "../../test/jwt";
-import { AuthProvider } from "../../auth/AuthContext";
-import { FarmContext } from "../../farm/FarmContext";
-import { MeContext } from "../../session/SessionContext";
-import { getTwoFactorStatus, listMyConnectedApps, startTwoFactor } from "../../api/cluckwork";
-import { confirmTwoFactor, stepUp } from "../../api/client";
-import i18n from "../../i18n";
-
-// #1277 MC3 (maintainer, 2026-11-05: "Block both"): nothing leaves the page
-// while confirm is in flight, and Back does not drop recovery codes that are
-// not saved yet. Closing the tab is left to beforeunload.
-vi.mock("../../api/cluckwork", async (importOriginal) => ({
- ...await importOriginal(),
- getTwoFactorStatus: vi.fn(),
- startTwoFactor: 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): string => i18n.t(`account:${key}` as "account:heading");
-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));
-
-beforeEach(() => {
- vi.resetAllMocks();
- vi.mocked(listMyConnectedApps).mockResolvedValue([]);
- vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: false, recoveryCodesLeft: 0 });
- vi.mocked(stepUp).mockResolvedValue({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" });
- const key = freshKey();
- vi.mocked(startTwoFactor).mockResolvedValue({ key, otpauthUri: `otpauth://totp/Cluckwork:${EMAIL}?secret=${key}` });
-});
-
-async function toScan() {
- await screen.findByRole("heading", { name: t("twoFactorHeading") }, { timeout: 3000 }).catch((e: unknown) => { screen.debug(undefined, 4000); throw e; });
- await act(async () => { fireEvent.click(screen.getByRole("button", { name: t("setUpButton") })); });
- fireEvent.change(within(screen.getByRole("dialog")).getByLabelText(/Your current password/), { target: { value: crypto.randomUUID() } });
- await act(async () => { fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: t("continueButton") })); });
- await screen.findByRole("img", { name: t("qrLabel") });
- fireEvent.change(screen.getByLabelText(new RegExp(t("codeLabel"))), { target: { value: freshCode() } });
-}
-
-describe("while confirm is in flight", () => {
- it("makes the rail and the bottom nav inert, and frees them when it settles", async () => {
- let answer!: (value: { recoveryCodes?: string[] }) => void;
- vi.mocked(confirmTwoFactor).mockReturnValue(new Promise((resolve) => { answer = resolve; }));
- renderWithProviders(
- }>} />,
- { route: "/account", token: { sub: "u1", role: "Worker" } },
- );
- await toScan();
- const rail = () => screen.getByRole("navigation", { name: "Primary", hidden: true });
- const tabs = () => screen.getByRole("navigation", { name: "Sections", hidden: true });
- expect(rail().closest("[inert]")).toBeNull();
-
- await act(async () => { fireEvent.click(screen.getByRole("button", { name: t("confirmButton") })); });
-
- expect(rail().closest("[inert]")).not.toBeNull();
- expect(tabs().closest("[inert]")).not.toBeNull();
- await act(async () => { answer({ recoveryCodes: undefined }); });
- await waitFor(() => expect(rail().closest("[inert]")).toBeNull());
- expect(tabs().closest("[inert]")).toBeNull();
- });
-});
-
-describe("Back with recovery codes not saved yet", () => {
- // A real BrowserRouter over jsdom's history: Back to "/" would unmount the
- // Account page, and the codes with it.
- function renderAtAccount() {
- window.history.replaceState(null, "", "/");
- window.history.pushState(null, "", "/account");
- setStoredToken({ sub: "u1", role: "Worker" });
- return render(
-
-
-
-
-
- Elsewhere} />
- } />
-
-
-
-
- ,
- );
- }
-
- it("keeps the codes and their dialog through repeated Back, and lets Back go once they are saved", async () => {
- const codes = freshCodes();
- vi.mocked(confirmTwoFactor).mockResolvedValue({ recoveryCodes: codes });
- renderAtAccount();
- await toScan();
- await act(async () => { fireEvent.click(screen.getByRole("button", { name: t("confirmButton") })); });
- await screen.findByRole("dialog", { name: t("codesHeading") });
-
- for (const _ of [1, 2]) await act(async () => { window.history.back(); await new Promise((r) => setTimeout(r, 50)); });
-
- expect(window.location.pathname).toBe("/account");
- expect(screen.getByRole("dialog", { name: t("codesHeading") })).toBeInTheDocument();
- expect(screen.getByText(codes[0]!)).toBeInTheDocument();
-
- fireEvent.click(screen.getByRole("checkbox", { name: t("savedCheckbox") }));
- await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
- await act(async () => { window.history.back(); await new Promise((r) => setTimeout(r, 50)); });
-
- await waitFor(() => expect(screen.getByText("Elsewhere")).toBeInTheDocument());
- });
-
- it("asks before the tab closes until the codes are saved, and not after", async () => {
- vi.mocked(confirmTwoFactor).mockResolvedValue({ recoveryCodes: freshCodes() });
- renderAtAccount();
- await toScan();
- await act(async () => { fireEvent.click(screen.getByRole("button", { name: t("confirmButton") })); });
- await screen.findByRole("dialog", { name: t("codesHeading") });
- const closing = () => {
- const event = new Event("beforeunload", { cancelable: true });
- window.dispatchEvent(event);
- return event.defaultPrevented;
- };
-
- expect(closing()).toBe(true);
- fireEvent.click(screen.getByRole("checkbox", { name: t("savedCheckbox") }));
- expect(closing()).toBe(false);
- });
-});
diff --git a/web/src/routes/account/Security.test.tsx b/web/src/routes/account/Security.test.tsx
index 8cd9c9e2d..f6e3fb84e 100644
--- a/web/src/routes/account/Security.test.tsx
+++ b/web/src/routes/account/Security.test.tsx
@@ -8,6 +8,7 @@ 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";
@@ -390,9 +391,11 @@ describe("the step-up proof", () => {
mustChangePassword: false, twoFactor: true, unauthenticatedReason: null,
login: vi.fn(), completeSecondFactor: vi.fn(), logout: vi.fn(),
}}>
-
-
-
+
+
+
+
+
);
diff --git a/web/src/routes/account/SecurityPanel.tsx b/web/src/routes/account/SecurityPanel.tsx
index 71945d087..907c7622d 100644
--- a/web/src/routes/account/SecurityPanel.tsx
+++ b/web/src/routes/account/SecurityPanel.tsx
@@ -12,11 +12,10 @@ import { DialogError } from "../../components/DialogError";
import { StepUpProofFields } from "../../components/StepUpProofFields";
import { useMe } from "../../session/SessionContext";
import { StatusDot } from "../dashboard/StatusDot";
+import { SECURITY_SUMMARY_ID } from "./recoveryCodes";
import { LOW_RECOVERY_CODES } from "./useTwoFactor";
import type { ProofAction, TwoFactor } from "./useTwoFactor";
-export const SECURITY_SUMMARY_ID = "account-security";
-
// #1275 "Account": the status, the recovery codes left, Regenerate and Turn
// off together in one accordion.
export function SecurityPanel({ twoFactor }: { twoFactor: TwoFactor }) {
diff --git a/web/src/routes/account/TwoFactorFlow.tsx b/web/src/routes/account/TwoFactorFlow.tsx
index 0a5764919..6b25ef666 100644
--- a/web/src/routes/account/TwoFactorFlow.tsx
+++ b/web/src/routes/account/TwoFactorFlow.tsx
@@ -1,14 +1,9 @@
-import { useId, useState } from "react";
-import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
-import { Alert, Box, Button, Checkbox, DialogActions, FormControlLabel, Link, Paper, Stack, TextField, Typography } from "@mui/material";
+import { Alert, Box, Button, Link, Paper, Stack, TextField, Typography } from "@mui/material";
import { BusyButton } from "../../components/BusyButton";
-import { Dialog } from "../../components/Dialog";
import { DialogError } from "../../components/DialogError";
-import { saveBlob } from "../../lib/saveBlob";
-import { useMe } from "../../session/SessionContext";
+import { useCopy } from "./recoveryCodes";
import { TwoFactorQr } from "./TwoFactorQr";
-import { SECURITY_SUMMARY_ID } from "./SecurityPanel";
import type { Flow, TwoFactor } from "./useTwoFactor";
// #1275 "Enrolment A": the steps that replace the Account page while they run,
@@ -31,21 +26,6 @@ const heading = (replacing: boolean) => (replacing ? "replaceHeading" : "enrolHe
const RESTART_REASONS = { expired: "setUpExpired", attempts: "setUpTooManyAttempts", session: "setUpSessionChanged" } as const;
-// Copy and download feedback, announced in one live region.
-function useCopy() {
- const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);
- // Started inside the promise: a plain-http origin has no clipboard at all.
- const copy = (text: string, done: string, failed: string) =>
- Promise.resolve().then(() => navigator.clipboard.writeText(text))
- .then(() => setNote({ text: done, ok: true }), () => setNote({ text: failed, ok: false }));
- const notice: ReactNode = (
-
- {note && {note.text}}
-
- );
- return { copy, notice, setNote };
-}
-
function ScanStep({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract }) {
const { t } = useTranslation("account");
const { t: tc } = useTranslation("common");
@@ -112,63 +92,3 @@ function RestartStep({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract<
);
}
-
-// #1275 "Recovery codes", shown once: the codes are in this dialog's props and
-// nowhere else, and leaving drops them. 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. useTwoFactor holds
-// Back and closing the tab until "saved" is ticked (MC3).
-export function RecoveryCodesDialog({ twoFactor, flow }: { twoFactor: TwoFactor; flow: Extract }) {
- const { t } = useTranslation("account");
- const me = useMe();
- const { copy, notice, setNote } = useCopy();
- const hintId = useId();
- const { codesSaved: saved, setCodesSaved: setSaved } = twoFactor;
- // The trigger that opened this dialog is gone by now, so focus returns to
- // the Security section instead of falling to .
- const done = () => {
- twoFactor.leaveFlow();
- requestAnimationFrame(() => document.getElementById(SECURITY_SUMMARY_ID)?.focus());
- };
- const text = flow.codes.join("\n");
-
- const download = () => {
- saveBlob(new Blob([`${t("codesFileTitle", { email: me?.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/recoveryCodes.test.tsx b/web/src/routes/account/recoveryCodes.test.tsx
new file mode 100644
index 000000000..ffa6d939d
--- /dev/null
+++ b/web/src/routes/account/recoveryCodes.test.tsx
@@ -0,0 +1,336 @@
+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 { setStoredToken } from "../../test/jwt";
+import { AuthProvider } from "../../auth/AuthContext";
+import { FarmContext } from "../../farm/FarmContext";
+import { MeContext } from "../../session/SessionContext";
+import { getTwoFactorStatus, listMyConnectedApps, regenerateRecoveryCodes, startTwoFactor } from "../../api/cluckwork";
+import { ApiError, confirmTwoFactor, setOnUnauthenticated, stepUp } from "../../api/client";
+import { logout as endSessionHere } from "../../api/session";
+import i18n from "../../i18n";
+
+// #1277 MC4 (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)} />
+ >
+ );
+}
+
+// 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(
+
+
+
+
+
+
+ Login page} />
+ }>
+ }>
+ 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.
+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" },
+ "the skip link": { go: () => fireEvent.click(skipLink()), lands: null },
+} 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 })); });
+}
+
+async function confirmPending() {
+ const answer = deferred<{ recoveryCodes?: string[] }>();
+ vi.mocked(confirmTwoFactor).mockReturnValue(answer.promise);
+ 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() } });
+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: t("confirmButton") })); });
+ expect(confirmTwoFactor).toHaveBeenCalledTimes(1);
+ return answer;
+}
+
+async function regeneratePending() {
+ const answer = deferred<{ recoveryCodes: string[] }>();
+ vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 1 });
+ vi.mocked(regenerateRecoveryCodes).mockReturnValue(answer.promise);
+ renderApp("/account", true);
+ const regenerate = await screen.findByRole("button", { name: t("regenerateButton") }, { timeout: 3000 });
+ await act(async () => { fireEvent.click(regenerate); });
+ 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(); });
+ if (lands) await screen.findByText(lands);
+}
+
+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 and web storage. 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 })].join("\n");
+ expect(readable).toContain("Login page");
+ for (const code of codes) expect(readable).not.toContain(code);
+}
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.stubGlobal("fetch", vi.fn(async () => 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("1. 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("2. 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("3. 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("4. 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("5. 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("6. closing the tab", () => {
+ const closing = () => {
+ const event = new Event("beforeunload", { cancelable: true });
+ window.dispatchEvent(event);
+ return event.defaultPrevented;
+ };
+
+ 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(closing()).toBe(true);
+ fireEvent.click(within(dialog).getByRole("checkbox", { name: t("savedCheckbox") }));
+ expect(closing()).toBe(false);
+ await act(async () => { fireEvent.click(within(dialog).getByRole("button", { name: t("doneButton") })); });
+ expect(closing()).toBe(false);
+ });
+});
+
+describe("7. 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"));
+ });
+});
diff --git a/web/src/routes/account/recoveryCodes.tsx b/web/src/routes/account/recoveryCodes.tsx
new file mode 100644
index 000000000..bbf01d005
--- /dev/null
+++ b/web/src/routes/account/recoveryCodes.tsx
@@ -0,0 +1,150 @@
+import { createContext, useCallback, useContext, useEffect, useId, 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 } from "../../api/client";
+import { useAuth } from "../../auth/useAuth";
+import { Dialog } from "../../components/Dialog";
+import { saveBlob } from "../../lib/saveBlob";
+
+// #1277 MC4 (maintainer, 2026-11-05: "Keep codes above pages"): recovery codes
+// that are shown once live here, above the routes, until the user saves them.
+// 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 the session.
+// In memory only: never in storage, a URL or a log.
+export interface UnsavedRecoveryCodes {
+ 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;
+}
+
+type Hold = (codes: readonly string[], set: { regenerated: boolean; email: string; generation: number }) => void;
+
+const RecoveryCodesContext = createContext(null);
+
+export const SECURITY_SUMMARY_ID = "account-security";
+const MAIN_CONTENT_ID = "main-content";
+
+// Shows a set the server just handed out. `generation` is the session's when
+// the request was sent: a set that lands after that session ended is dropped.
+export function useHoldRecoveryCodes(): Hold {
+ const hold = useContext(RecoveryCodesContext);
+ if (!hold) throw new Error("useHoldRecoveryCodes needs a RecoveryCodesProvider above it.");
+ return hold;
+}
+
+export function RecoveryCodesProvider({ children }: { children: ReactNode }) {
+ const { isAuthenticated } = useAuth();
+ const [held, setHeld] = useState(null);
+ const authenticated = useRef(isAuthenticated);
+
+ // #308 — the codes end with the session that received them.
+ useEffect(() => {
+ authenticated.current = isAuthenticated;
+ if (!isAuthenticated) setHeld(null);
+ }, [isAuthenticated]);
+
+ const unsaved = held !== null && !held.saved;
+ useEffect(() => {
+ if (!unsaved) return;
+ const warn = (e: BeforeUnloadEvent) => {
+ e.preventDefault();
+ e.returnValue = "";
+ };
+ window.addEventListener("beforeunload", warn);
+ return () => window.removeEventListener("beforeunload", warn);
+ }, [unsaved]);
+
+ const hold = useCallback((codes, { regenerated, email, generation }) => {
+ if (!authenticated.current || generation !== currentSessionGeneration()) return;
+ setHeld({ codes, regenerated, email, saved: false });
+ }, []);
+
+ // 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 = () => {
+ setHeld(null);
+ requestAnimationFrame(() => (document.getElementById(SECURITY_SUMMARY_ID) ?? document.getElementById(MAIN_CONTENT_ID))?.focus());
+ };
+
+ return (
+
+ {children}
+ {held && (
+ setHeld((h) => h && { ...h, saved })} onDone={done} />
+ )}
+
+ );
+}
+
+// Copy and download feedback, announced in one live region.
+export function useCopy() {
+ const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);
+ // Started inside the promise: a plain-http origin has no clipboard at all.
+ const copy = (text: string, done: string, failed: string) =>
+ Promise.resolve().then(() => navigator.clipboard.writeText(text))
+ .then(() => setNote({ text: done, ok: true }), () => setNote({ text: failed, ok: false }));
+ const notice: ReactNode = (
+
+ {note && {note.text}}
+
+ );
+ return { copy, notice, setNote };
+}
+
+// #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: UnsavedRecoveryCodes;
+ 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/useHistoryHold.ts b/web/src/routes/account/useHistoryHold.ts
deleted file mode 100644
index c82be91e4..000000000
--- a/web/src/routes/account/useHistoryHold.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { useEffect } from "react";
-
-const SENTINEL = "cluckworkHold";
-const onSentinel = () => (window.history.state as Record | null)?.[SENTINEL] === true;
-
-// #1277 MC3 — while held, Back stays on the page: a sentinel entry sits on top
-// of this one, and a Back that pops it pushes it again. It copies the router's
-// own state, so the router sees the same location and nothing remounts.
-// Closing the tab asks the browser to confirm. Letting go pops the sentinel,
-// so history is left as it was.
-export function useHistoryHold(held: boolean) {
- useEffect(() => {
- if (!held) return;
- const push = () => window.history.pushState({ ...(window.history.state as object | null), [SENTINEL]: true }, "");
- const onPop = () => { if (!onSentinel()) push(); };
- const onUnload = (e: BeforeUnloadEvent) => {
- e.preventDefault();
- e.returnValue = "";
- };
- push();
- window.addEventListener("popstate", onPop);
- window.addEventListener("beforeunload", onUnload);
- return () => {
- window.removeEventListener("popstate", onPop);
- window.removeEventListener("beforeunload", onUnload);
- if (onSentinel()) window.history.back();
- };
- }, [held]);
-}
diff --git a/web/src/routes/account/useTwoFactor.test.tsx b/web/src/routes/account/useTwoFactor.test.tsx
index 3c51f4603..e1eeb554a 100644
--- a/web/src/routes/account/useTwoFactor.test.tsx
+++ b/web/src/routes/account/useTwoFactor.test.tsx
@@ -1,13 +1,15 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
-import { act, renderHook, waitFor } from "@testing-library/react";
+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 review W3 — the recovery codes leave the hook's state on every exit
-// from the codes step, not only the rendered page. Adapted from the round-1
-// runner's probe, which caught a summary that kept them.
+// #1277 W3, then MC4 — 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) => ({
@@ -28,34 +30,17 @@ beforeEach(() => {
vi.mocked(stepUp).mockResolvedValue({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" });
});
-async function onCodesStep() {
- const hook = renderHook(useTwoFactor);
- await waitFor(() => expect(hook.result.current.status.data?.enabled).toBe(true));
- act(() => hook.result.current.openProof("regenerate"));
- act(() => hook.result.current.setProof({ password: crypto.randomUUID() }));
- await act(async () => { await hook.result.current.onProof({ preventDefault() {} } as FormEvent); });
- expect(hook.result.current.flow.step).toBe("codes");
- expect(JSON.stringify(hook.result.current)).toContain(code);
- return hook;
-}
+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() }));
-describe("the recovery codes' lifetime", () => {
- it("ends when the user leaves the codes step", async () => {
- const { result } = await onCodesStep();
+ await act(async () => { await result.current.onProof({ preventDefault() {} } as FormEvent); });
- act(() => result.current.leaveFlow());
-
- expect(result.current.flow).toEqual({ step: "summary" });
+ expect(await screen.findByText(code)).toBeInTheDocument();
expect(JSON.stringify(result.current)).not.toContain(code);
- });
-
- it("ends when the session does", async () => {
- const { result, rerender } = await onCodesStep();
-
- auth.isAuthenticated = false;
- rerender();
-
expect(result.current.flow).toEqual({ step: "summary" });
- expect(JSON.stringify(result.current)).not.toContain(code);
});
});
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index 675d4c4ad..a62fe756a 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -2,14 +2,14 @@ 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 { ApiError, confirmTwoFactor, currentSessionGeneration, 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 { useShellLock } from "../../components/ShellLock";
import i18n from "../../i18n";
-import { useHistoryHold } from "./useHistoryHold";
+import { useMe } from "../../session/SessionContext";
+import { useHoldRecoveryCodes } 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
@@ -20,13 +20,13 @@ 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, the URI and the recovery codes live only in
-// the step that shows them, and leave with it.
+// 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" }
- | { step: "codes"; codes: string[]; regenerated: boolean };
+ | { step: "restart"; replacing: boolean; reason: "expired" | "attempts" | "session" };
const SUMMARY: Flow = { step: "summary" };
@@ -49,14 +49,8 @@ export function useTwoFactor() {
const [proof, setProof] = useState(NO_PROOF);
const [code, setCode] = useState("");
const [message, setMessage] = useState(null);
- const [codesSaved, setCodesSaved] = useState(false);
-
- // #1277 MC3 (maintainer, 2026-11-05: "Block both"): confirm and regenerate
- // hand out codes once, and unsaved codes exist only here, so the nav and
- // Back stay on the page until they are settled and saved.
- const confirming = dialog.isPending("confirm");
- useShellLock(confirming);
- useHistoryHold(confirming || dialog.isPending("regenerate") || (flow.step === "codes" && !codesSaved));
+ const holdCodes = useHoldRecoveryCodes();
+ const email = useMe()?.email ?? "";
// #308 — a proof, a code, a key or a recovery code never outlives the session.
useEffect(() => {
@@ -81,7 +75,7 @@ export function useTwoFactor() {
if (action) dismissDialog(action);
}
- async function send(next: ProofAction, token: string, current: () => boolean) {
+ async function send(next: ProofAction, token: string, current: () => boolean, generation: number) {
if (next === "start") {
// As the dialog does: replacing means the session proved two factors.
const replacing = enrolled;
@@ -97,10 +91,11 @@ export function useTwoFactor() {
status.retry();
throw new Error(i18n.t("account:regenerateNotEnabled"));
});
+ // Before the current() check: the codes are shown even if the user has
+ // left this page, because the old set no longer works.
+ holdCodes(recoveryCodes, { regenerated: true, email, generation });
status.retry();
if (!current()) return;
- setCodesSaved(false);
- setFlow({ step: "codes", codes: recoveryCodes, regenerated: true });
} else {
await turnOffTwoFactor(token);
status.retry();
@@ -117,11 +112,12 @@ export function useTwoFactor() {
if (!next || busy) return;
setMessage(null);
await run(next, async (current) => {
+ const generation = currentSessionGeneration();
const entered = proof;
setProof(NO_PROOF);
const token = (await stepUp(entered)).token;
if (!current()) return;
- await send(next, token, current).catch((err: unknown) => { throw stale(err); });
+ await send(next, token, current, generation).catch((err: unknown) => { throw stale(err); });
}, { dialog: next });
}
@@ -130,6 +126,7 @@ export function useTwoFactor() {
if (flow.step !== "scan" || busy) return;
const { replacing } = flow;
await run("confirm", async (current) => {
+ const generation = currentSessionGeneration();
const typed = code;
setCode("");
let recoveryCodes: string[] | undefined;
@@ -147,15 +144,13 @@ export function useTwoFactor() {
if (current()) setFlow({ step: "restart", replacing, reason });
return;
}
+ // Before the current() check, as regenerate does: the user is enrolled
+ // now, so the codes are shown wherever the user has gone.
+ if (recoveryCodes) holdCodes(recoveryCodes, { regenerated: false, email, generation });
status.retry();
if (!current()) return;
- if (recoveryCodes) {
- setCodesSaved(false);
- setFlow({ step: "codes", codes: recoveryCodes, regenerated: false });
- } else {
- setFlow(SUMMARY);
- setMessage(i18n.t("account:replacedMessage"));
- }
+ setFlow(SUMMARY);
+ if (!recoveryCodes) setMessage(i18n.t("account:replacedMessage"));
});
}
@@ -166,7 +161,7 @@ export function useTwoFactor() {
}
return {
- status, flow, action, proof, setProof, code, setCode, message, dialog, codesSaved, setCodesSaved,
+ status, flow, action, proof, setProof, code, setCode, message, dialog,
openProof, closeProof, onProof, onConfirm, leaveFlow,
};
}
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}
+ ,
);
From e520b1956360c7cc643465be9837e57332feefc1 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 17:03:06 +0000
Subject: [PATCH 25/45] fix(web): focus the content from the skip link instead
of navigating
Following the skip link's #main-content href wrote a history entry with no state, which gave the location a new key, so the keyed ErrorBoundary remounted the screen and dropped whatever it held. The link now prevents its default and focuses #main-content, which already takes focus, so no history entry is written and the screen keeps its state.
Refs #1277
---
web/src/routes/AppLayout.tsx | 8 +++++++-
web/src/routes/account/recoveryCodes.test.tsx | 20 +++++++++++++++++++
2 files changed, 27 insertions(+), 1 deletion(-)
diff --git a/web/src/routes/AppLayout.tsx b/web/src/routes/AppLayout.tsx
index 7b9166ad1..1c793f1e9 100644
--- a/web/src/routes/AppLayout.tsx
+++ b/web/src/routes/AppLayout.tsx
@@ -75,7 +75,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 review — 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")?.focus();
+ }}>{t("skipToContent")} {
await waitFor(() => expect(document.activeElement?.id).toBe("main-content"));
});
});
+
+// 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");
+ });
+});
From d3bbfcb57929683355b694fdc325382e014352ed Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 17:03:42 +0000
Subject: [PATCH 26/45] refactor(web): pass sendWithRefresh the predicate it
acts on
resendable: (err) => !isUnresendable(...) read as a double negative; the option is now unresendable and takes isUnresendable as it is. BottomNav's comment loses its stub line and credits the maintainer, not the owner.
Refs #1277
---
web/src/api/refresh.ts | 6 +++---
web/src/components/BottomNav.tsx | 8 ++++----
2 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/web/src/api/refresh.ts b/web/src/api/refresh.ts
index 3ce5dc3d4..1184fdbd6 100644
--- a/web/src/api/refresh.ts
+++ b/web/src/api/refresh.ts
@@ -321,7 +321,7 @@ export async function apiFetch(
throw new StaleSessionError();
return sendWithRefresh((bearer) => raw(path, init, bearer), token, {
held: heldAuthCookieLock,
- resendable: (err) => !isUnresendable(path, init, err),
+ unresendable: (err) => isUnresendable(path, init, err),
});
}
@@ -338,7 +338,7 @@ function endSession(err: ApiError): never {
async function sendWithRefresh(
send: (token: string) => Promise,
token: string,
- { held, resendable = () => true }: { held?: HeldAuthCookieLock; resendable?: (err: ApiError) => boolean } = {},
+ { 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
@@ -347,7 +347,7 @@ async function sendWithRefresh(
try {
return await send(token);
} catch (err) {
- if (!(err instanceof ApiError) || err.status !== 401 || !resendable(err)) throw err;
+ if (!(err instanceof ApiError) || err.status !== 401 || unresendable(err)) throw err;
if (superseded()) throw new StaleSessionError();
let refreshed: string;
try {
diff --git a/web/src/components/BottomNav.tsx b/web/src/components/BottomNav.tsx
index bf9a203ec..eb33aff61 100644
--- a/web/src/components/BottomNav.tsx
+++ b/web/src/components/BottomNav.tsx
@@ -29,10 +29,10 @@ const MORE_VALUE = "__more__";
// `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 — form
-// dialogs stay centred and sized to their content (owner, 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 —
+// 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({
From c33d3913eb041176b969e1a9c806c8d6bf51c865 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 17:04:16 +0000
Subject: [PATCH 27/45] docs(web): say the recovery codes stay on screen until
saved
The Security Help now adds that the codes stay on screen, even on another page, until the user ticks that they saved them, in en, es and tl.
Refs #1277
---
web/src/i18n/en.ts | 1 +
web/src/i18n/es.ts | 3 ++-
web/src/i18n/tl.ts | 4 +++-
3 files changed, 6 insertions(+), 2 deletions(-)
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 85d426f05..9fff7f150 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -4089,6 +4089,7 @@ export const en = {
accountSecurity:
"Security turns on two-factor authentication with Set up: scan the QR "
+ "code with your authenticator app, enter its code, then save the ten recovery codes it shows once. "
+ + "They stay on screen, even if you go to another page, until you tick that you saved them. "
+ "Once it's on, Regenerate replaces your recovery codes, Replace authenticator "
+ "app moves Cluckwork to a new phone, and Turn off removes it. Set up asks "
+ "for your password first, and the other three for your password and a code. Turning it on, replacing the app and turning it off sign out your "
diff --git a/web/src/i18n/es.ts b/web/src/i18n/es.ts
index b6d431700..65d0e40cc 100644
--- a/web/src/i18n/es.ts
+++ b/web/src/i18n/es.ts
@@ -3378,7 +3378,8 @@ export const es = {
accountSecurity:
"Seguridad activa la autenticación en dos pasos con Configurar: escanee "
+ "el código QR con su aplicación de autenticación, ingrese su código y guarde los diez códigos de "
- + "recuperación que muestra una sola vez. Una vez activada, Regenerar reemplaza sus "
+ + "recuperación que muestra una sola vez. "
+ + "Siguen en pantalla, aunque vaya a otra página, hasta que marque que los guardó. Una vez activada, Regenerar reemplaza sus "
+ "códigos de recuperación, Reemplazar aplicación de autenticación pasa Cluckwork a un "
+ "teléfono nuevo y Desactivar la quita. Configurar pide antes su contraseña, y los otros tres su contraseña y un código. "
+ "Activarla, reemplazar la aplicación y desactivarla cierran la sesión en sus otros dispositivos y "
diff --git a/web/src/i18n/tl.ts b/web/src/i18n/tl.ts
index 4c079a6e1..779945a84 100644
--- a/web/src/i18n/tl.ts
+++ b/web/src/i18n/tl.ts
@@ -3498,7 +3498,9 @@ export const tl = {
accountSecurity:
"Ino-on ng Seguridad ang two-factor authentication gamit ang I-set up: "
+ "i-scan ang QR code gamit ang iyong authenticator app, ilagay ang code nito, tapos i-save ang sampung "
- + "recovery code na isang beses lang nitong ipapakita. Kapag naka-on na, pinapalitan ng Gumawa "
+ + "recovery code na isang beses lang nitong ipapakita. "
+ + "Mananatili ang mga ito sa screen, kahit pumunta ka sa ibang page, hanggang lagyan mo ng tsek na na-save "
+ + "mo ang mga ito. Kapag naka-on na, pinapalitan ng Gumawa "
+ "ulit ang iyong mga recovery code, inililipat ng Palitan ang authenticator app "
+ "ang Cluckwork sa bagong phone, at inaalis ito ng I-off. Hinihingi muna ng I-set up "
+ "ang iyong password, at ng tatlo pa ang iyong password at isang code. Ang pag-on, pagpapalit ng app at pag-off ay nagsa-sign out sa iba "
From ab2fb3f566c2bfc252da17b1cfea3a950d991a67 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Thu, 5 Nov 2026 17:07:11 +0000
Subject: [PATCH 28/45] fix(web): show the focused skip link above the docked
rail
At desktop widths the skip link opened at z-index 1000 under MUI's drawer layer (1200), so a keyboard user focused a link they could not see; Chromium's hit test landed on the rail's brand name. It now sits at 1250, above the drawer and below the modal layer, and a stylesheet test pins it between the two theme values. The defect is older than this branch; the round-3 skip-link probe found it.
Refs #1277
---
web/src/styles.skip-link.test.ts | 30 ++++++++++++++++++++++++++++++
web/src/styles/dialogs.css | 4 +++-
2 files changed, 33 insertions(+), 1 deletion(-)
create mode 100644 web/src/styles.skip-link.test.ts
diff --git a/web/src/styles.skip-link.test.ts b/web/src/styles.skip-link.test.ts
new file mode 100644
index 000000000..264ce066d
--- /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 review — 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..ce636a977 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 review). */
+ z-index: 1250;
background: var(--brand);
color: var(--on-brand);
padding: 0.6rem 1rem;
From 366f19341446bd4239fe7a40a3912d50499c12b3 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 02:10:58 +0000
Subject: [PATCH 29/45] fix(web): let the recovery-codes slot own the request
that issues them
A reload or a tab close while confirm or regenerate was in flight went ahead
with no prompt: the slot armed beforeunload only for codes already shown, so
the server enrolled the user or replaced the set and the codes were never seen.
The slot now owns the request too. expect() hands a code-issuing request a
ticket and reads the session generation before the step-up proof; deliver
shows the set only while that ticket is live in the same session; release runs
from a finally. beforeunload is armed while a ticket is out or the set is
unsaved, and a session end clears both.
expect() refuses while a ticket is out or a set is held, and the slot's busy
flag disables Set up, Replace and Regenerate, so only one request issues codes
at a time and a late answer can no longer overwrite a valid set. The dialog is
keyed on its set.
A regenerate answer without recoveryCodes now shows an error instead of
throwing. useCopy moves to components/, the main-content id is one constant,
and the slot's set type is private as HeldRecoveryCodes. The skip-link rows
leave the ways-to-leave tables, and the no-codes walk also reads the URL and
the history entry.
Refs #1277
---
web/src/components/useCopy.tsx | 18 ++
web/src/i18n/en.ts | 1 +
web/src/i18n/es.ts | 1 +
web/src/i18n/tl.ts | 1 +
web/src/lib/mainContent.ts | 3 +
web/src/routes/AppLayout.tsx | 7 +-
web/src/routes/account/SecurityPanel.tsx | 10 +-
web/src/routes/account/TwoFactorFlow.tsx | 2 +-
web/src/routes/account/recoveryCodes.test.tsx | 187 ++++++++++++++++--
web/src/routes/account/recoveryCodes.tsx | 118 ++++++-----
web/src/routes/account/useTwoFactor.ts | 90 +++++----
11 files changed, 338 insertions(+), 100 deletions(-)
create mode 100644 web/src/components/useCopy.tsx
create mode 100644 web/src/lib/mainContent.ts
diff --git a/web/src/components/useCopy.tsx b/web/src/components/useCopy.tsx
new file mode 100644
index 000000000..0abcf565e
--- /dev/null
+++ b/web/src/components/useCopy.tsx
@@ -0,0 +1,18 @@
+import { useState } from "react";
+import type { ReactNode } from "react";
+import { Alert, Box } from "@mui/material";
+
+// Copy and download feedback, announced in one live region.
+export function useCopy() {
+ const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);
+ // Started inside the promise: a plain-http origin has no clipboard at all.
+ const copy = (text: string, done: string, failed: string) =>
+ Promise.resolve().then(() => navigator.clipboard.writeText(text))
+ .then(() => setNote({ text: done, ok: true }), () => setNote({ text: failed, ok: false }));
+ const notice: ReactNode = (
+
+ {note && {note.text}}
+
+ );
+ return { copy, notice, setNote };
+}
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 9fff7f150..1031be959 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -362,6 +362,7 @@ export const en = {
doneButton: "Done",
replacedMessage: "Your new authenticator app is set up. The old one no longer works.",
turnedOffMessage: "Two-factor authentication is off.",
+ codesMissing: "Something went wrong, and no recovery codes arrived. Regenerate them to get a new set.",
regenerateNotEnabled: "Two-factor authentication is not on for your account, so it has no recovery codes to replace.",
sessionChanged: "Your sign-in changed while this was sent, so nothing changed. Try again.",
},
diff --git a/web/src/i18n/es.ts b/web/src/i18n/es.ts
index 65d0e40cc..db9646cf9 100644
--- a/web/src/i18n/es.ts
+++ b/web/src/i18n/es.ts
@@ -293,6 +293,7 @@ export const es = {
doneButton: "Listo",
replacedMessage: "Su nueva aplicación de autenticación está configurada. La anterior ya no funciona.",
turnedOffMessage: "La autenticación en dos pasos está desactivada.",
+ codesMissing: "Algo salió mal y no llegaron códigos de recuperación. Regenérelos para obtener un juego nuevo.",
regenerateNotEnabled: "La autenticación en dos pasos no está activada en su cuenta, así que no tiene códigos de recuperación que reemplazar.",
sessionChanged: "Su inicio de sesión cambió mientras se enviaba esto, así que no cambió nada. Inténtelo de nuevo.",
},
diff --git a/web/src/i18n/tl.ts b/web/src/i18n/tl.ts
index 779945a84..e267f403c 100644
--- a/web/src/i18n/tl.ts
+++ b/web/src/i18n/tl.ts
@@ -302,6 +302,7 @@ export const tl = {
doneButton: "Tapos na",
replacedMessage: "Naka-set up na ang bago mong authenticator app. Hindi na gumagana ang luma.",
turnedOffMessage: "Naka-off na ang two-factor authentication.",
+ codesMissing: "May nangyaring mali, at walang dumating na recovery code. Gumawa ulit para makakuha ng bagong set.",
regenerateNotEnabled: "Hindi naka-on ang two-factor authentication sa iyong account, kaya wala itong recovery code na papalitan.",
sessionChanged: "Nagbago ang iyong sign-in habang ipinapadala ito, kaya walang nagbago. Subukan ulit.",
},
diff --git a/web/src/lib/mainContent.ts b/web/src/lib/mainContent.ts
new file mode 100644
index 000000000..5f5ba5d8e
--- /dev/null
+++ b/web/src/lib/mainContent.ts
@@ -0,0 +1,3 @@
+// The id of the app shell's : the skip link's target, and where focus
+// goes when the control that had it is gone.
+export const MAIN_CONTENT_ID = "main-content";
diff --git a/web/src/routes/AppLayout.tsx b/web/src/routes/AppLayout.tsx
index 1c793f1e9..85d53d1f5 100644
--- a/web/src/routes/AppLayout.tsx
+++ b/web/src/routes/AppLayout.tsx
@@ -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";
@@ -78,9 +79,9 @@ export function AppLayout() {
{/* #1277 review — 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")?.focus();
+ document.getElementById(MAIN_CONTENT_ID)?.focus();
}}>{t("skipToContent")}
-
+
{/* 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.
diff --git a/web/src/routes/account/SecurityPanel.tsx b/web/src/routes/account/SecurityPanel.tsx
index 907c7622d..7ab3713c4 100644
--- a/web/src/routes/account/SecurityPanel.tsx
+++ b/web/src/routes/account/SecurityPanel.tsx
@@ -12,7 +12,7 @@ import { DialogError } from "../../components/DialogError";
import { StepUpProofFields } from "../../components/StepUpProofFields";
import { useMe } from "../../session/SessionContext";
import { StatusDot } from "../dashboard/StatusDot";
-import { SECURITY_SUMMARY_ID } from "./recoveryCodes";
+import { SECURITY_SUMMARY_ID, useRecoveryCodesSlot } from "./recoveryCodes";
import { LOW_RECOVERY_CODES } from "./useTwoFactor";
import type { ProofAction, TwoFactor } from "./useTwoFactor";
@@ -22,6 +22,8 @@ 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.
+ const { busy } = useRecoveryCodesSlot();
const low = state?.enabled && state.recoveryCodesLeft <= LOW_RECOVERY_CODES;
return (
@@ -40,7 +42,7 @@ export function SecurityPanel({ twoFactor }: { twoFactor: TwoFactor }) {
)}
{state && (
- openProof("start")}>{t("setUpButton")}}>
+ openProof("start")}>{t("setUpButton")}}>
{t("twoFactorHeading")}{t("twoFactorHint")}
{state.enabled
@@ -51,13 +53,13 @@ export function SecurityPanel({ twoFactor }: { twoFactor: TwoFactor }) {
{state && !state.enabled && {t("twoFactorOffHint")}}
{state?.enabled && (
<>
- openProof("regenerate")}>{t("regenerateButton")}}>
+ openProof("regenerate")}>{t("regenerateButton")}}>
{t("recoveryCodesHeading")}{t("recoveryCodesLeft", { count: state.recoveryCodesLeft })}{t("recoveryCodesCaption")}
{low && {t("recoveryCodesLow", { count: state.recoveryCodesLeft })}}
- openProof("start")}>{t("replaceButton")}}>
+ openProof("start")}>{t("replaceButton")}}>
{t("replaceHint")} openProof("turn-off")}>{t("turnOffButton")}}>
diff --git a/web/src/routes/account/TwoFactorFlow.tsx b/web/src/routes/account/TwoFactorFlow.tsx
index 6b25ef666..b77bb667d 100644
--- a/web/src/routes/account/TwoFactorFlow.tsx
+++ b/web/src/routes/account/TwoFactorFlow.tsx
@@ -2,7 +2,7 @@ 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 "./recoveryCodes";
+import { useCopy } from "../../components/useCopy";
import { TwoFactorQr } from "./TwoFactorQr";
import type { Flow, TwoFactor } from "./useTwoFactor";
diff --git a/web/src/routes/account/recoveryCodes.test.tsx b/web/src/routes/account/recoveryCodes.test.tsx
index c5d467532..4ccbdc9cb 100644
--- a/web/src/routes/account/recoveryCodes.test.tsx
+++ b/web/src/routes/account/recoveryCodes.test.tsx
@@ -8,8 +8,9 @@ import { ProtectedRoute } from "../ProtectedRoute";
import { RecoveryCodesProvider } from "./recoveryCodes";
import { farmState } from "../../test/fixtures";
import { freshCode } from "../../test/codes";
-import { setStoredToken } from "../../test/jwt";
+import { makeToken, setStoredToken } from "../../test/jwt";
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";
@@ -62,6 +63,17 @@ function FormScreen() {
);
}
+// The login route, with a way to sign in again through the real AuthProvider.
+function LoginPage() {
+ const { login } = useAuth();
+ return (
+ <>
+
Login page
+
+ >
+ );
+}
+
// 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) {
@@ -76,7 +88,7 @@ function renderApp(path: string, enrolled: boolean) {
- Login page} />
+ } />
}>
}>
Elsewhere} />
@@ -97,12 +109,12 @@ function renderApp(path: string, enrolled: boolean) {
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.
+// 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" },
- "the skip link": { go: () => fireEvent.click(skipLink()), lands: null },
} as const;
async function proveAndSubmit(submit: string, enrolled: boolean) {
@@ -126,13 +138,18 @@ async function confirmPending() {
return answer;
}
-async function regeneratePending() {
- const answer = deferred<{ recoveryCodes: string[] }>();
+// A regenerate whose step-up, or whose answer, the test settles by hand.
+async function regenerateOpen() {
vi.mocked(getTwoFactorStatus).mockResolvedValue({ enabled: true, recoveryCodesLeft: 1 });
- vi.mocked(regenerateRecoveryCodes).mockReturnValue(answer.promise);
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;
@@ -141,9 +158,14 @@ async function regeneratePending() {
async function leave(how: keyof typeof LEAVE) {
const { go, lands } = LEAVE[how];
await act(async () => { go(); });
- if (lands) await screen.findByText(lands);
+ 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);
@@ -157,17 +179,24 @@ const sessionEnds = async (title: string) => {
await act(async () => { onUnauthenticated(title); });
};
-// Every place the page could still hold a code: the DOM and web storage. The
-// floor is the login page itself, so the walk read a live document.
+// 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 })].join("\n");
+ 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);
}
beforeEach(() => {
vi.resetAllMocks();
- vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 204 })));
+ // 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" }));
@@ -335,6 +364,140 @@ describe("7. focus after Done", () => {
});
});
+const tabCloseAsks = () => {
+ const event = new Event("beforeunload", { cancelable: true });
+ window.dispatchEvent(event);
+ return event.defaultPrevented;
+};
+
+describe("P1. 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("P2. 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 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("P3. what the slot still holds", () => {
+ 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" })); });
+
+ 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) the session is read before the step-up proof is awaited", 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" }); });
+
+ await waitFor(() => expect(regenerateRecoveryCodes).toHaveBeenCalledTimes(1));
+ 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({} as { recoveryCodes: string[] });
+ 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);
+ });
+});
+
// 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.
diff --git a/web/src/routes/account/recoveryCodes.tsx b/web/src/routes/account/recoveryCodes.tsx
index bbf01d005..aced07865 100644
--- a/web/src/routes/account/recoveryCodes.tsx
+++ b/web/src/routes/account/recoveryCodes.tsx
@@ -1,18 +1,24 @@
-import { createContext, useCallback, useContext, useEffect, useId, useRef, useState } from "react";
+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 } 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 MC4 (maintainer, 2026-11-05: "Keep codes above pages"): recovery codes
-// that are shown once live here, above the routes, until the user saves them.
-// 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 the session.
-// In memory only: never in storage, a URL or a log.
-export interface UnsavedRecoveryCodes {
+// 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 (MC5, 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.
@@ -21,85 +27,105 @@ export interface UnsavedRecoveryCodes {
email: string;
}
-type Hold = (codes: readonly string[], set: { regenerated: boolean; email: string; generation: number }) => void;
+// 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 {
+ 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;
+ // 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);
+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";
-const MAIN_CONTENT_ID = "main-content";
-// Shows a set the server just handed out. `generation` is the session's when
-// the request was sent: a set that lands after that session ended is dropped.
-export function useHoldRecoveryCodes(): Hold {
- const hold = useContext(RecoveryCodesContext);
- if (!hold) throw new Error("useHoldRecoveryCodes needs a RecoveryCodesProvider above it.");
- return hold;
+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();
- const [held, setHeld] = useState(null);
- const authenticated = useRef(isAuthenticated);
+ // 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 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 codes end with the session that received them.
- useEffect(() => {
- authenticated.current = isAuthenticated;
- if (!isAuthenticated) setHeld(null);
+ // #308 — the set, and the request it waits on, end with this tab's session.
+ // A layout effect, so a late answer cannot land before it runs.
+ useLayoutEffect(() => {
+ if (isAuthenticated) return;
+ put(null);
+ putPending(null);
}, [isAuthenticated]);
- const unsaved = held !== null && !held.saved;
+ const asks = pending !== null || (held !== null && !held.saved);
useEffect(() => {
- if (!unsaved) return;
+ if (!asks) return;
const warn = (e: BeforeUnloadEvent) => {
e.preventDefault();
e.returnValue = "";
};
window.addEventListener("beforeunload", warn);
return () => window.removeEventListener("beforeunload", warn);
- }, [unsaved]);
+ }, [asks]);
- const hold = useCallback((codes, { regenerated, email, generation }) => {
- if (!authenticated.current || generation !== currentSessionGeneration()) return;
- setHeld({ codes, regenerated, email, saved: false });
+ const expect = useCallback((): Delivery | null => {
+ 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 {
+ deliver: (codes, { regenerated, email }) => {
+ if (current()) put({ id: ticket, codes, regenerated, email, saved: false });
+ },
+ release: () => {
+ if (pendingRef.current === ticket) putPending(null);
+ },
+ };
}, []);
// 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 = () => {
- setHeld(null);
+ put(null);
requestAnimationFrame(() => (document.getElementById(SECURITY_SUMMARY_ID) ?? document.getElementById(MAIN_CONTENT_ID))?.focus());
};
+ const slot = useMemo(() => ({ busy: pending !== null || held !== null, expect }), [pending, held, expect]);
return (
-
+
{children}
{held && (
- setHeld((h) => h && { ...h, saved })} onDone={done} />
+ put(heldRef.current && { ...heldRef.current, saved })} onDone={done} />
)}
);
}
-// Copy and download feedback, announced in one live region.
-export function useCopy() {
- const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);
- // Started inside the promise: a plain-http origin has no clipboard at all.
- const copy = (text: string, done: string, failed: string) =>
- Promise.resolve().then(() => navigator.clipboard.writeText(text))
- .then(() => setNote({ text: done, ok: true }), () => setNote({ text: failed, ok: false }));
- const notice: ReactNode = (
-
- {note && {note.text}}
-
- );
- return { copy, notice, setNote };
-}
-
// #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: UnsavedRecoveryCodes;
+ held: HeldRecoveryCodes;
onSaved: (saved: boolean) => void;
onDone: () => void;
}) {
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index a62fe756a..5a7eb4ddf 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -2,14 +2,15 @@ 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, currentSessionGeneration, NO_PROOF, stepUp, turnOffTwoFactor } from "../../api/client";
+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 { useHoldRecoveryCodes } from "./recoveryCodes";
+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
@@ -49,7 +50,7 @@ export function useTwoFactor() {
const [proof, setProof] = useState(NO_PROOF);
const [code, setCode] = useState("");
const [message, setMessage] = useState(null);
- const holdCodes = useHoldRecoveryCodes();
+ const slot = useRecoveryCodesSlot();
const email = useMe()?.email ?? "";
// #308 — a proof, a code, a key or a recovery code never outlives the session.
@@ -75,7 +76,7 @@ export function useTwoFactor() {
if (action) dismissDialog(action);
}
- async function send(next: ProofAction, token: string, current: () => boolean, generation: number) {
+ async function send(next: ProofAction, token: string, current: () => boolean, delivery: Delivery | null) {
if (next === "start") {
// As the dialog does: replacing means the session proved two factors.
const replacing = enrolled;
@@ -91,9 +92,14 @@ export function useTwoFactor() {
status.retry();
throw new Error(i18n.t("account:regenerateNotEnabled"));
});
+ // The old set no longer works, so a broken answer is said, not shown.
+ if (!Array.isArray(recoveryCodes)) {
+ status.retry();
+ throw new Error(i18n.t("account:codesMissing"));
+ }
// Before the current() check: the codes are shown even if the user has
// left this page, because the old set no longer works.
- holdCodes(recoveryCodes, { regenerated: true, email, generation });
+ delivery?.deliver(recoveryCodes, { regenerated: true, email });
status.retry();
if (!current()) return;
} else {
@@ -112,12 +118,19 @@ export function useTwoFactor() {
if (!next || busy) return;
setMessage(null);
await run(next, async (current) => {
- const generation = currentSessionGeneration();
- const entered = proof;
- setProof(NO_PROOF);
- const token = (await stepUp(entered)).token;
- if (!current()) return;
- await send(next, token, current, generation).catch((err: unknown) => { throw stale(err); });
+ // Taken before the step-up proof, so the slot reads the session then,
+ // and released however the request ends.
+ const delivery = next === "regenerate" ? slot.expect() : null;
+ if (next === "regenerate" && delivery === null) return;
+ try {
+ const entered = proof;
+ setProof(NO_PROOF);
+ const token = (await stepUp(entered)).token;
+ if (!current()) return;
+ await send(next, token, current, delivery).catch((err: unknown) => { throw stale(err); });
+ } finally {
+ delivery?.release();
+ }
}, { dialog: next });
}
@@ -126,34 +139,43 @@ export function useTwoFactor() {
if (flow.step !== "scan" || busy) return;
const { replacing } = flow;
await run("confirm", async (current) => {
- const generation = currentSessionGeneration();
- const typed = code;
- setCode("");
- let recoveryCodes: string[] | undefined;
+ const delivery = slot.expect();
+ if (delivery === null) return;
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;
+ await confirmWith(delivery, current, replacing);
+ } finally {
+ delivery.release();
}
- // Before the current() check, as regenerate does: the user is enrolled
- // now, so the codes are shown wherever the user has gone.
- if (recoveryCodes) holdCodes(recoveryCodes, { regenerated: false, email, generation });
- status.retry();
- if (!current()) return;
- setFlow(SUMMARY);
- if (!recoveryCodes) setMessage(i18n.t("account:replacedMessage"));
});
}
+ 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;
+ }
+ // Before the current() check, as regenerate does: the user is enrolled
+ // now, so the codes are shown wherever the user has gone.
+ if (recoveryCodes) delivery.deliver(recoveryCodes, { regenerated: false, email });
+ status.retry();
+ if (!current()) return;
+ setFlow(SUMMARY);
+ if (!recoveryCodes) setMessage(i18n.t("account:replacedMessage"));
+ }
+
function leaveFlow() {
dismissDialog("confirm");
setCode("");
From fa0b11798694ca8fcf2a10a372bd69b2b6e244e9 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 02:11:14 +0000
Subject: [PATCH 30/45] test(web): hold recovery codes across route changes in
the app's own tree
The slot tests built their own copy of the provider tree, so keying the real RecoveryCodesProvider on the route in App.tsx passed every test and lost the codes in Chromium. This test renders App itself, holds a regenerated set, goes to Help and back, and finds the same codes still on screen. The remount mutation turns it red.
Refs #1277
---
web/src/App.recoveryCodes.test.tsx | 73 ++++++++++++++++++++++++++++++
1 file changed, 73 insertions(+)
create mode 100644 web/src/App.recoveryCodes.test.tsx
diff --git a/web/src/App.recoveryCodes.test.tsx b/web/src/App.recoveryCodes.test.tsx
new file mode 100644
index 000000000..2284389cc
--- /dev/null
+++ b/web/src/App.recoveryCodes.test.tsx
@@ -0,0 +1,73 @@
+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 { clearAccessToken } from "./auth/tokenStore";
+import { setStoredToken } from "./test/jwt";
+import { freshCode } from "./test/codes";
+import i18n from "./i18n";
+
+// #1277 review P3 (e) — the slot holds codes across route changes in the tree
+// App.tsx really builds, not in a test's copy of it: keying or moving the
+// provider under the router would remount it and drop the set.
+vi.mock("./session/SessionContext", async (importOriginal) => ({
+ ...await importOriginal(),
+ SessionProvider: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock("./pwa/UpdatePrompt", () => ({ UpdatePrompt: () => null }));
+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" });
+ // Any request this test does not mock answers empty, not with the suite's
+ // default 401, which would end the session.
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 204 })));
+ window.history.replaceState(null, "", "/");
+ window.history.pushState(null, "", "/account");
+});
+
+afterEach(() => {
+ clearAccessToken();
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe("the app's own provider tree", () => {
+ it("keeps unsaved recovery codes on screen through two route changes", async () => {
+ 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") });
+
+ 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"));
+
+ const dialog = screen.getByRole("dialog", { name: t("codesHeading") });
+ expect(within(dialog).getAllByRole("listitem").map((li) => li.textContent)).toEqual(codes);
+ }, 20_000);
+});
From d960d9d5a88cf9cf1492a833d1671c736eea3d32 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 02:57:04 +0000
Subject: [PATCH 31/45] fix(web): send no regenerate once its session has
ended, and keep the status fresh
A regenerate whose step-up proof landed while the user was signing out still
went out: Account stays mounted until POST /auth/logout answers, so the server
replaced the set and deliver dropped the only copy. Delivery now has live(),
and nothing is sent after the proof unless the request is still the slot's
active one in the same session.
The status is reloaded whenever the slot's busy flag changes, so a request
that settled while Account was gone, or after the user came back, shows its
count or its on state. The reloads after deliver, after a 409 and after a
missing set go; release reaches them through busy. Turn off is now disabled
while busy too, so a late set never lands on a disabled factor.
recoveryCodes is optional on the regenerate type, as on the wire, and a first
enrolment's confirm without codes says codesMissing instead of passing
silently. Tests cover each, plus regenerate's release on a refused proof, an
abandoned proof, an unmounted refusal and an unmounted delivery, and a
request from an ended session that cannot end the next one's. The comments on
the layout effect and expect() say only what holds.
Refs #1277
---
web/src/api/cluckwork/twoFactor.ts | 3 +-
web/src/routes/account/Security.test.tsx | 3 +-
web/src/routes/account/SecurityPanel.tsx | 5 +-
web/src/routes/account/recoveryCodes.test.tsx | 171 ++++++++++++++++--
web/src/routes/account/recoveryCodes.tsx | 11 +-
web/src/routes/account/useTwoFactor.ts | 53 +++---
6 files changed, 201 insertions(+), 45 deletions(-)
diff --git a/web/src/api/cluckwork/twoFactor.ts b/web/src/api/cluckwork/twoFactor.ts
index 5ce7e1fce..8e6cc3438 100644
--- a/web/src/api/cluckwork/twoFactor.ts
+++ b/web/src/api/cluckwork/twoFactor.ts
@@ -23,5 +23,6 @@ export const getTwoFactorStatus = (signal?: AbortSignal) => apiGet
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 });
+ apiPost<{ recoveryCodes?: string[] }>("/auth/two-factor/recovery-codes", undefined, undefined, { [STEP_UP_HEADER]: stepUpToken });
diff --git a/web/src/routes/account/Security.test.tsx b/web/src/routes/account/Security.test.tsx
index f6e3fb84e..e93c0b55f 100644
--- a/web/src/routes/account/Security.test.tsx
+++ b/web/src/routes/account/Security.test.tsx
@@ -297,7 +297,8 @@ describe("an enrolled user's step-up actions", () => {
await press(t("regenerateButton"), dialog());
expect(await within(dialog()).findByRole("alert")).toHaveTextContent(t("regenerateNotEnabled"));
- expect(mockStatus).toHaveBeenCalledTimes(2);
+ // 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 () => {
diff --git a/web/src/routes/account/SecurityPanel.tsx b/web/src/routes/account/SecurityPanel.tsx
index 7ab3713c4..d40e01e15 100644
--- a/web/src/routes/account/SecurityPanel.tsx
+++ b/web/src/routes/account/SecurityPanel.tsx
@@ -22,7 +22,8 @@ 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.
+ // 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.
const { busy } = useRecoveryCodesSlot();
const low = state?.enabled && state.recoveryCodesLeft <= LOW_RECOVERY_CODES;
@@ -62,7 +63,7 @@ export function SecurityPanel({ twoFactor }: { twoFactor: TwoFactor }) {
openProof("start")}>{t("replaceButton")}}>
{t("replaceHint")}
- openProof("turn-off")}>{t("turnOffButton")}}>
+ openProof("turn-off")}>{t("turnOffButton")}}>
{t("turnOffHint")}
>
diff --git a/web/src/routes/account/recoveryCodes.test.tsx b/web/src/routes/account/recoveryCodes.test.tsx
index 4ccbdc9cb..afd7b6289 100644
--- a/web/src/routes/account/recoveryCodes.test.tsx
+++ b/web/src/routes/account/recoveryCodes.test.tsx
@@ -9,6 +9,7 @@ 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";
@@ -191,6 +192,12 @@ function expectNoCodesAnywhere(codes: string[]) {
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.
@@ -318,22 +325,16 @@ describe("5. a second set of codes in one mount", () => {
});
describe("6. closing the tab", () => {
- const closing = () => {
- const event = new Event("beforeunload", { cancelable: true });
- window.dispatchEvent(event);
- return event.defaultPrevented;
- };
-
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(closing()).toBe(true);
+ expect(tabCloseAsks()).toBe(true);
fireEvent.click(within(dialog).getByRole("checkbox", { name: t("savedCheckbox") }));
- expect(closing()).toBe(false);
+ expect(tabCloseAsks()).toBe(false);
await act(async () => { fireEvent.click(within(dialog).getByRole("button", { name: t("doneButton") })); });
- expect(closing()).toBe(false);
+ expect(tabCloseAsks()).toBe(false);
});
});
@@ -364,12 +365,6 @@ describe("7. focus after Done", () => {
});
});
-const tabCloseAsks = () => {
- const event = new Event("beforeunload", { cancelable: true });
- window.dispatchEvent(event);
- return event.defaultPrevented;
-};
-
describe("P1. 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();
@@ -419,6 +414,15 @@ describe("P2. one code-issuing request at a time", () => {
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");
@@ -441,6 +445,7 @@ describe("P3. what the slot still holds", () => {
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);
@@ -455,7 +460,7 @@ describe("P3. what the slot still holds", () => {
expect(codesDialog()).toBeNull();
});
- it("(c) the session is read before the step-up proof is awaited", async () => {
+ 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() });
@@ -465,8 +470,9 @@ describe("P3. what the slot still holds", () => {
await act(async () => { await endSessionHere(); });
await act(async () => { proof.resolve({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" }); });
- await waitFor(() => expect(regenerateRecoveryCodes).toHaveBeenCalledTimes(1));
+ expect(regenerateRecoveryCodes).not.toHaveBeenCalled();
expect(codesDialog()).toBeNull();
+ expect(tabCloseAsks()).toBe(false);
});
it("(d) Done empties the slot, which frees Regenerate again", async () => {
@@ -487,7 +493,7 @@ describe("P3. what the slot still holds", () => {
describe("a regenerate answer without codes", () => {
it("shows an error in its dialog and holds nothing", async () => {
- vi.mocked(regenerateRecoveryCodes).mockResolvedValue({} as { recoveryCodes: string[] });
+ vi.mocked(regenerateRecoveryCodes).mockResolvedValue({});
await regenerateOpen();
await proveAndSubmit(t("regenerateButton"), true);
@@ -498,6 +504,135 @@ describe("a regenerate answer without codes", () => {
});
});
+describe("S2. the status after coming back to Account", () => {
+ 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") })); });
+ }
+
+ 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("S4a. 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);
+
+ await leave("a single Back");
+ await act(async () => { proof.resolve({ token: crypto.randomUUID(), expiresAt: "2099-01-01T00:00:00Z" }); });
+
+ 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("S4b. 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("S5. 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);
+ });
+});
+
// 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.
diff --git a/web/src/routes/account/recoveryCodes.tsx b/web/src/routes/account/recoveryCodes.tsx
index aced07865..74824f2e4 100644
--- a/web/src/routes/account/recoveryCodes.tsx
+++ b/web/src/routes/account/recoveryCodes.tsx
@@ -30,6 +30,8 @@ interface HeldRecoveryCodes {
// 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;
}
@@ -68,7 +70,9 @@ export function RecoveryCodesProvider({ children }: { children: ReactNode }) {
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.
- // A layout effect, so a late answer cannot land before it runs.
+ // 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);
@@ -86,13 +90,18 @@ export function RecoveryCodesProvider({ children }: { children: ReactNode }) {
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 => {
+ // 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 });
},
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index 5a7eb4ddf..c7aad3aea 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -42,7 +42,6 @@ function stale(err: unknown): unknown {
export function useTwoFactor() {
const { isAuthenticated, twoFactor: enrolled } = useAuth();
- const status = useLatestLoad([], getTwoFactorStatus);
const dialog = useDialogAction(SCOPES);
const { busy, run, openDialog, dismissDialog } = dialog;
const [flow, setFlow] = useState(SUMMARY);
@@ -51,6 +50,9 @@ export function useTwoFactor() {
const [code, setCode] = useState("");
const [message, setMessage] = useState(null);
const slot = useRecoveryCodesSlot();
+ // #1277 review S2 — reloaded whenever the slot starts or ends a request or
+ // a set, so a request that settled while this page was gone still shows.
+ const status = useLatestLoad([slot.busy], getTwoFactorStatus);
const email = useMe()?.email ?? "";
// #308 — a proof, a code, a key or a recovery code never outlives the session.
@@ -76,7 +78,7 @@ export function useTwoFactor() {
if (action) dismissDialog(action);
}
- async function send(next: ProofAction, token: string, current: () => boolean, delivery: Delivery | null) {
+ async function send(next: ProofAction, token: string, current: () => boolean) {
if (next === "start") {
// As the dialog does: replacing means the session proved two factors.
const replacing = enrolled;
@@ -85,23 +87,6 @@ export function useTwoFactor() {
setCode("");
openDialog("confirm");
setFlow({ step: "scan", enrolment, replacing });
- } else if (next === "regenerate") {
- const { recoveryCodes } = await regenerateRecoveryCodes(token).catch((err: unknown) => {
- // The status was stale (#1277 contract item 8): reload it.
- if (!isProblem(err, 409, "Auth.TwoFactorNotEnabled")) throw err;
- status.retry();
- throw new Error(i18n.t("account:regenerateNotEnabled"));
- });
- // The old set no longer works, so a broken answer is said, not shown.
- if (!Array.isArray(recoveryCodes)) {
- status.retry();
- throw new Error(i18n.t("account:codesMissing"));
- }
- // Before the current() 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 });
- status.retry();
- if (!current()) return;
} else {
await turnOffTwoFactor(token);
status.retry();
@@ -112,6 +97,24 @@ export function useTwoFactor() {
dismissDialog(next);
}
+ async function regenerate(token: string, current: () => boolean, delivery: Delivery) {
+ // Either refusal reloads the status through the slot: release ends the
+ // request, busy changes, 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 (!Array.isArray(recoveryCodes)) throw new Error(i18n.t("account:codesMissing"));
+ // Before the current() 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 (!current()) return;
+ setAction(null);
+ dismissDialog("regenerate");
+ }
+
async function onProof(e: FormEvent) {
e.preventDefault();
const next = action;
@@ -126,8 +129,12 @@ export function useTwoFactor() {
const entered = proof;
setProof(NO_PROOF);
const token = (await stepUp(entered)).token;
- if (!current()) return;
- await send(next, token, current, delivery).catch((err: unknown) => { throw stale(err); });
+ // #1277 review S1 — 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 !== null && !delivery.live())) return;
+ await (delivery !== null ? regenerate(token, current, delivery) : send(next, token, current))
+ .catch((err: unknown) => { throw stale(err); });
} finally {
delivery?.release();
}
@@ -167,10 +174,12 @@ export function useTwoFactor() {
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 && !Array.isArray(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 (recoveryCodes) delivery.deliver(recoveryCodes, { regenerated: false, email });
- status.retry();
if (!current()) return;
setFlow(SUMMARY);
if (!recoveryCodes) setMessage(i18n.t("account:replacedMessage"));
From 170253d049fb452ac624ee23d48aceb2c2588064 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 02:57:19 +0000
Subject: [PATCH 32/45] test(web): pin the slot's contract and its place above
the shell
A slot-contract test pins that expect() refuses while a set is held, saved or not, below the UI that disables its triggers. The App-tree test gains a /connect case, which a slot moved inside the shell would fail, and fails on any request outside the one it expects instead of answering it with an empty 204. Its comment now says what it proves: SessionProvider is stubbed.
Refs #1277
---
web/src/App.recoveryCodes.test.tsx | 71 ++++++++++++++-----
.../account/recoveryCodes.slot.test.tsx | 26 +++++++
2 files changed, 79 insertions(+), 18 deletions(-)
create mode 100644 web/src/routes/account/recoveryCodes.slot.test.tsx
diff --git a/web/src/App.recoveryCodes.test.tsx b/web/src/App.recoveryCodes.test.tsx
index 2284389cc..2b58a52c1 100644
--- a/web/src/App.recoveryCodes.test.tsx
+++ b/web/src/App.recoveryCodes.test.tsx
@@ -9,9 +9,10 @@ import { setStoredToken } from "./test/jwt";
import { freshCode } from "./test/codes";
import i18n from "./i18n";
-// #1277 review P3 (e) — the slot holds codes across route changes in the tree
-// App.tsx really builds, not in a test's copy of it: keying or moving the
-// provider under the router would remount it and drop the set.
+// #1277 review P3 (e), S4 (c) — 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,
@@ -35,9 +36,13 @@ beforeEach(() => {
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" });
- // Any request this test does not mock answers empty, not with the suite's
- // default 401, which would end the session.
- vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 204 })));
+ // 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");
});
@@ -48,18 +53,31 @@ afterEach(() => {
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 = 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") });
+ 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"]')!); });
@@ -67,7 +85,24 @@ describe("the app's own provider tree", () => {
await act(async () => { window.history.back(); });
await waitFor(() => expect(window.location.pathname).toBe("/account"));
- const dialog = screen.getByRole("dialog", { name: t("codesHeading") });
- expect(within(dialog).getAllByRole("listitem").map((li) => li.textContent)).toEqual(codes);
+ 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"));
+ await waitFor(() => 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/routes/account/recoveryCodes.slot.test.tsx b/web/src/routes/account/recoveryCodes.slot.test.tsx
new file mode 100644
index 000000000..b26868842
--- /dev/null
+++ b/web/src/routes/account/recoveryCodes.slot.test.tsx
@@ -0,0 +1,26 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, renderHook, screen } from "@testing-library/react";
+import { RecoveryCodesProvider, useRecoveryCodesSlot } from "./recoveryCodes";
+
+// #1277 review S4 (d) — 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.
+// Adapted from the round-5 runner's slot probe.
+const auth = vi.hoisted(() => ({ isAuthenticated: true }));
+vi.mock("../../auth/useAuth", () => ({ useAuth: () => auth }));
+
+beforeEach(() => { auth.isAuthenticated = true; });
+
+describe("expect()", () => {
+ 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(); });
+ });
+});
From b24e649b26d7a101c2d3ae37fc53e42309554709 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 04:08:12 +0000
Subject: [PATCH 33/45] fix(web): authenticate nothing and issue no codes while
sign-out is in flight
Pressing Confirm code after Sign out, while POST /auth/logout was still out,
enrolled the user and then dropped the codes: logout had cleared the token and
bumped the generation, but the page stayed signed in, expect() handed out a
fresh ticket, and currentAccessToken silently refreshed from the live cookie.
Set up and Turn off could send the same way after a proof, and a status read
could put a token back.
The session module now owns a sign-out-in-flight state, set on the first line
of logout() and cleared in its finally, success or failure. While it holds,
refreshTokens refuses with StaleSessionError, so currentAccessToken answers a
plain 401 with no teardown and sendWithRefresh rethrows the original 401, and
the slot's expect() hands out no ticket. One place, the token path, enforces
it for every request.
The status reloads each time a code-issuing request settles, from a counter
the slot bumps in release(), and whenever the session's two_factor claim
changes, so a Turn off that answers after the user came back shows Off. Set
up, Replace, Regenerate and Turn off stay disabled while the status reloads,
so stale data never offers an action. send() is typed on "start" |
"turn-off" and onProof dispatches on next, with the step-up proof in prove().
An empty recoveryCodes list counts as missing.
Refs #1277
---
web/src/api/client.ts | 2 +-
web/src/api/refresh.ts | 5 +-
web/src/api/session.ts | 10 ++
web/src/api/twoFactor.test.ts | 48 ++++++
web/src/routes/UsersPage.test.tsx | 2 +-
web/src/routes/account/SecurityPanel.tsx | 4 +-
web/src/routes/account/recoveryCodes.test.tsx | 147 ++++++++++++++++--
web/src/routes/account/recoveryCodes.tsx | 13 +-
web/src/routes/account/useTwoFactor.ts | 59 ++++---
9 files changed, 252 insertions(+), 38 deletions(-)
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index 0ef56be04..4fc8da78b 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -1,6 +1,6 @@
export { STEP_UP_HEADER } from "./request";
export { apiGet, apiPost, apiPut, apiPutBytes, apiDelete, apiGetBlob, apiFetch, restoreSession } from "./refresh";
-export { login, completeSecondFactor, changePassword, confirmTwoFactor, turnOffTwoFactor, stepUp, logout, NO_PROOF, currentSessionGeneration } from "./session";
+export { login, completeSecondFactor, changePassword, confirmTwoFactor, turnOffTwoFactor, stepUp, logout, NO_PROOF, currentSessionGeneration, isSigningOut } from "./session";
export type { LoginOutcome, StepUpProof } from "./session";
export { setOnUnauthenticated, setOnTokensChanged } from "./sessionState";
export { getLastTraceId } from "./trace";
diff --git a/web/src/api/refresh.ts b/web/src/api/refresh.ts
index 1184fdbd6..9a216a79c 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 { isSigningOut, sessionGeneration, settledLogin } from "./session";
import { newId } from "../lib/ids";
import { rawBlob } from "./request";
import type { HeldAuthCookieLock } from "./authCookieLock";
@@ -173,6 +173,9 @@ async function executeHeldRefresh(
}
export async function refreshTokens(heldLock?: HeldAuthCookieLock): Promise {
+ // #1277 review T1 — a session being signed out gets no new token. Its
+ // callers treat this as a superseded session: no teardown, no resend.
+ if (isSigningOut()) throw new StaleSessionError();
// changePassword owns the cross-tab auth lock while apiFetch performs its
// normal 401 refresh-and-retry. Web Locks are not reentrant, so execute that
// nested refresh directly under the lock already held by the caller. Keep
diff --git a/web/src/api/session.ts b/web/src/api/session.ts
index 50979b26a..b6a7e04a7 100644
--- a/web/src/api/session.ts
+++ b/web/src/api/session.ts
@@ -371,7 +371,15 @@ export async function stepUp(proof: StepUpProof): Promise<{ token: string; expir
return noteCode(apiPost<{ token: string; expiresAt: string }>("/auth/step-up", body), proof.code);
}
+// #1277 review T1 — set from the first line of logout() until its request
+// settles, success or failure. The token is already gone, but the page stays
+// signed in until then: while this holds, refreshTokens refuses, so no request
+// authenticates, and the recovery-codes slot starts no code-issuing work.
+let signingOut = false;
+export const isSigningOut = () => signingOut;
+
export async function logout(): Promise {
+ signingOut = true;
// #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 —
@@ -417,5 +425,7 @@ export async function logout(): Promise {
// #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);
+ } finally {
+ signingOut = false;
}
}
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
index 0352bba81..e6c91a54e 100644
--- a/web/src/api/twoFactor.test.ts
+++ b/web/src/api/twoFactor.test.ts
@@ -191,3 +191,51 @@ describe("an expired token's plain 401", () => {
expect(to("/auth/two-factor/recovery-codes")).toHaveLength(2);
});
});
+
+// #1277 review T1 — from the moment sign-out starts until its request settles,
+// the token path refreshes nothing, so no request can authenticate.
+describe("while sign-out is in flight", () => {
+ 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));
+ // A refresh would succeed, so only the refusal keeps it from happening.
+ fetchMock.mockResolvedValue(pair(token("acct-S")));
+ return async (res: Response | Error = new Response(null, { status: 204 })) => { finish(res); await done; };
+ }
+
+ 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) => {
+ const settle = 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();
+ await settle();
+ });
+
+ it.each([
+ ["answers", new Response(null, { status: 204 })],
+ ["fails", new TypeError("offline")],
+ ] as const)("ends when the sign-out request %s, and the next read refreshes again", async (_, answer) => {
+ const quiet = vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const settle = await signOutHeld();
+ await settle(answer);
+ fetchMock.mockReset();
+ fetchMock.mockResolvedValueOnce(pair(token("acct-S"))).mockResolvedValueOnce(json({ enabled: false, recoveryCodesLeft: 0 }));
+
+ await expect(getTwoFactorStatus()).resolves.toEqual({ enabled: false, recoveryCodesLeft: 0 });
+
+ expect(to("/auth/refresh")).toHaveLength(1);
+ quiet.mockRestore();
+ });
+});
diff --git a/web/src/routes/UsersPage.test.tsx b/web/src/routes/UsersPage.test.tsx
index f2486d47d..ac22b89c2 100644
--- a/web/src/routes/UsersPage.test.tsx
+++ b/web/src/routes/UsersPage.test.tsx
@@ -4275,7 +4275,7 @@ describe("UsersPage step-up with two-factor authentication (#1279)", () => {
// 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", "useTwoFactor.onProof"]);
+ 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/SecurityPanel.tsx b/web/src/routes/account/SecurityPanel.tsx
index d40e01e15..e81fb5070 100644
--- a/web/src/routes/account/SecurityPanel.tsx
+++ b/web/src/routes/account/SecurityPanel.tsx
@@ -24,7 +24,9 @@ export function SecurityPanel({ twoFactor }: { twoFactor: 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.
- const { busy } = useRecoveryCodesSlot();
+ // 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 (
diff --git a/web/src/routes/account/recoveryCodes.test.tsx b/web/src/routes/account/recoveryCodes.test.tsx
index afd7b6289..11bb227c8 100644
--- a/web/src/routes/account/recoveryCodes.test.tsx
+++ b/web/src/routes/account/recoveryCodes.test.tsx
@@ -15,7 +15,8 @@ import { useAuth } from "../../auth/useAuth";
import { FarmContext } from "../../farm/FarmContext";
import { MeContext } from "../../session/SessionContext";
import { getTwoFactorStatus, listMyConnectedApps, regenerateRecoveryCodes, startTwoFactor } from "../../api/cluckwork";
-import { ApiError, confirmTwoFactor, setOnUnauthenticated, stepUp } from "../../api/client";
+import type { TwoFactorStatus } from "../../api/cluckwork";
+import { ApiError, confirmTwoFactor, logout, setOnTokensChanged, setOnUnauthenticated, stepUp } from "../../api/client";
import { logout as endSessionHere } from "../../api/session";
import i18n from "../../i18n";
@@ -125,15 +126,20 @@ async function proveAndSubmit(submit: string, enrolled: boolean) {
await act(async () => { fireEvent.click(within(dialog).getByRole("button", { name: submit })); });
}
-async function confirmPending() {
- const answer = deferred<{ recoveryCodes?: string[] }>();
- vi.mocked(confirmTwoFactor).mockReturnValue(answer.promise);
+// 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;
@@ -504,13 +510,112 @@ describe("a regenerate answer without codes", () => {
});
});
-describe("S2. the status after coming back to Account", () => {
- 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") })); });
- }
+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("T2. 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("T3. the status while it reloads after a request settles", () => {
+ it("keeps Set up disabled behind Done until the first enrolment's status arrives", async () => {
+ const answer = await confirmPending();
+ const status = deferred();
+ vi.mocked(getTwoFactorStatus).mockReturnValueOnce(status.promise);
+
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+ await saveAndDone();
+
+ expect(screen.getByRole("button", { name: t("setUpButton") })).toBeDisabled();
+ await act(async () => { status.resolve({ enabled: true, recoveryCodesLeft: 10 }); });
+ expect(await screen.findByText(t("twoFactorOn"))).toBeInTheDocument();
+ });
+
+ it("keeps Regenerate disabled beside the old count until the new one arrives", async () => {
+ const answer = await regeneratePending();
+ const status = deferred();
+ vi.mocked(getTwoFactorStatus).mockReturnValueOnce(status.promise);
+
+ await act(async () => { answer.resolve({ recoveryCodes: freshCodes() }); });
+ await saveAndDone();
+
+ // hidden: the closing dialogs may still mark the page aria-hidden.
+ const regenerate = () => screen.getByRole("button", { name: t("regenerateButton"), hidden: true });
+ expect(screen.getByText(t("recoveryCodesLeft", { count: 1 }))).toBeInTheDocument();
+ expect(regenerate()).toBeDisabled();
+ await act(async () => { status.resolve({ enabled: true, recoveryCodesLeft: 10 }); });
+ expect(await screen.findByText(t("recoveryCodesLeft", { count: 10 }))).toBeInTheDocument();
+ expect(regenerate()).toBeEnabled();
+ });
+});
+
+describe("T6. 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("S2. 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");
@@ -633,6 +738,28 @@ describe("S5. a first enrolment's answer without codes", () => {
});
});
+describe("T1. Sign out while the set-up step is open", () => {
+ it("leaves Confirm code sending nothing until sign-out settles, 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.
diff --git a/web/src/routes/account/recoveryCodes.tsx b/web/src/routes/account/recoveryCodes.tsx
index 74824f2e4..6d68420b6 100644
--- a/web/src/routes/account/recoveryCodes.tsx
+++ b/web/src/routes/account/recoveryCodes.tsx
@@ -2,7 +2,7 @@ import { createContext, useCallback, useContext, useEffect, useId, useLayoutEffe
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Alert, Box, Button, Checkbox, DialogActions, FormControlLabel, Stack, Typography } from "@mui/material";
-import { currentSessionGeneration } from "../../api/client";
+import { currentSessionGeneration, isSigningOut } from "../../api/client";
import { useAuth } from "../../auth/useAuth";
import { Dialog } from "../../components/Dialog";
import { useCopy } from "../../components/useCopy";
@@ -39,6 +39,8 @@ export interface Delivery {
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;
@@ -63,6 +65,7 @@ export function RecoveryCodesProvider({ children }: { children: ReactNode }) {
// 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);
@@ -93,6 +96,8 @@ export function RecoveryCodesProvider({ children }: { children: ReactNode }) {
// 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 review T1 — no code-issuing work starts once sign-out has begun.
+ if (isSigningOut()) 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;
@@ -106,7 +111,9 @@ export function RecoveryCodesProvider({ children }: { children: ReactNode }) {
if (current()) put({ id: ticket, codes, regenerated, email, saved: false });
},
release: () => {
- if (pendingRef.current === ticket) putPending(null);
+ if (pendingRef.current !== ticket) return;
+ putPending(null);
+ setSettled((n) => n + 1);
},
};
}, []);
@@ -118,7 +125,7 @@ export function RecoveryCodesProvider({ children }: { children: ReactNode }) {
requestAnimationFrame(() => (document.getElementById(SECURITY_SUMMARY_ID) ?? document.getElementById(MAIN_CONTENT_ID))?.focus());
};
- const slot = useMemo(() => ({ busy: pending !== null || held !== null, expect }), [pending, held, expect]);
+ const slot = useMemo(() => ({ busy: pending !== null || held !== null, settled, expect }), [pending, held, settled, expect]);
return (
{children}
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index c7aad3aea..d1158734b 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -50,9 +50,11 @@ export function useTwoFactor() {
const [code, setCode] = useState("");
const [message, setMessage] = useState(null);
const slot = useRecoveryCodesSlot();
- // #1277 review S2 — reloaded whenever the slot starts or ends a request or
- // a set, so a request that settled while this page was gone still shows.
- const status = useLatestLoad([slot.busy], getTwoFactorStatus);
+ // #1277 review T2, T3 — 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.
+ 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.
@@ -78,7 +80,7 @@ export function useTwoFactor() {
if (action) dismissDialog(action);
}
- async function send(next: ProofAction, token: string, current: () => boolean) {
+ 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;
@@ -97,46 +99,58 @@ export function useTwoFactor() {
dismissDialog(next);
}
- async function regenerate(token: string, current: () => boolean, delivery: Delivery) {
+ // 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, busy changes, and the status reads again.
+ // 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 (!Array.isArray(recoveryCodes)) throw new Error(i18n.t("account:codesMissing"));
- // Before the current() check: the codes are shown even if the user has
- // left this page, because the old set no longer works.
+ 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 (!current()) return;
+ 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 = next === "regenerate" ? slot.expect() : null;
- if (next === "regenerate" && delivery === null) return;
+ const delivery = slot.expect();
+ if (delivery === null) return;
try {
- const entered = proof;
- setProof(NO_PROOF);
- const token = (await stepUp(entered)).token;
+ const token = await prove();
// #1277 review S1 — 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 !== null && !delivery.live())) return;
- await (delivery !== null ? regenerate(token, current, delivery) : send(next, token, current))
- .catch((err: unknown) => { throw stale(err); });
+ if (!current() || !delivery.live()) return;
+ await regenerate(token, current, delivery).catch((err: unknown) => { throw stale(err); });
} finally {
- delivery?.release();
+ delivery.release();
}
}, { dialog: next });
}
@@ -176,10 +190,10 @@ export function useTwoFactor() {
}
// 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 && !Array.isArray(recoveryCodes)) throw new Error(i18n.t("account:codesMissing"));
+ 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 (recoveryCodes) delivery.deliver(recoveryCodes, { regenerated: false, email });
+ if (isCodeSet(recoveryCodes)) delivery.deliver(recoveryCodes, { regenerated: false, email });
if (!current()) return;
setFlow(SUMMARY);
if (!recoveryCodes) setMessage(i18n.t("account:replacedMessage"));
@@ -197,6 +211,9 @@ export function useTwoFactor() {
};
}
+// 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;
From e214c4de9a17612bf71a6e11918bad715bc0b2c3 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 04:08:30 +0000
Subject: [PATCH 34/45] test(web): wait for the Connect page itself, and pin
expect()'s pending refusal
The App-tree /connect case could go Back before the lazy Connect page mounted, and a prewarmed chunk made it fail on the page's real consent request. askConsent is now mocked to wait forever, and the test waits for the page's loading status before it checks the codes and goes Back; the strict request allow-list stays. The slot-contract test adds a second expect() while the first request is pending, beside the held-set case.
Refs #1277
---
web/src/App.recoveryCodes.test.tsx | 13 ++++++++++++-
web/src/routes/account/recoveryCodes.slot.test.tsx | 10 ++++++++++
2 files changed, 22 insertions(+), 1 deletion(-)
diff --git a/web/src/App.recoveryCodes.test.tsx b/web/src/App.recoveryCodes.test.tsx
index 2b58a52c1..5802ccff3 100644
--- a/web/src/App.recoveryCodes.test.tsx
+++ b/web/src/App.recoveryCodes.test.tsx
@@ -4,6 +4,7 @@ import { act, fireEvent, render, screen, waitFor, within } from "@testing-librar
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";
@@ -18,6 +19,12 @@ vi.mock("./session/SessionContext", async (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(),
@@ -97,7 +104,11 @@ describe("the app's own provider tree", () => {
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
});
await waitFor(() => expect(window.location.pathname).toBe("/connect"));
- await waitFor(() => expect(screen.queryByRole("navigation", { name: i18n.t("nav:primaryNavAriaLabel"), hidden: true })).toBeNull());
+ // 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 });
+ 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"));
diff --git a/web/src/routes/account/recoveryCodes.slot.test.tsx b/web/src/routes/account/recoveryCodes.slot.test.tsx
index b26868842..d59fa38f8 100644
--- a/web/src/routes/account/recoveryCodes.slot.test.tsx
+++ b/web/src/routes/account/recoveryCodes.slot.test.tsx
@@ -11,6 +11,16 @@ vi.mock("../../auth/useAuth", () => ({ useAuth: () => auth }));
beforeEach(() => { auth.isAuthenticated = true; });
describe("expect()", () => {
+ 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(() => {
From 299cac6edbbc9dc9e67605b62d7858c326c15f76 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 05:19:03 +0000
Subject: [PATCH 35/45] fix(web): keep a tab signed out from sign-out until the
next sign-in
The sign-out refusal was a boolean cleared in logout's finally, so two
overlapping sign-outs unblocked each other, and the refusal ended a task
before the app left the page. It is now keyed to the generation logout()
bumps to: the tab refuses every refresh while the generation still equals
it, so a failed or answered revoke changes nothing, and only the next
sign-in, which bumps the generation, ends it. An explicit login and the
settledLogin() retry that rides it stay allowed. The check moved to the top
of executeRefresh, where every refresh sends, so a refresh queued behind the
cross-tab lock, a session restore and a download all refuse there.
resetSignOutForTests() clears it between tests, beside clearAccessToken(),
because tests seed tokens instead of signing in.
The revoke now gives up after the refresh timeout, so a server that never
answers no longer keeps the tab half signed out, and both Sign out buttons
are disabled while a sign-out is in flight.
Refs #1277
---
web/src/api/client.ts | 2 +-
web/src/api/refresh.ts | 9 +-
web/src/api/session.ts | 30 ++++--
web/src/api/twoFactor.test.ts | 122 +++++++++++++++++++---
web/src/components/BottomNav.tsx | 6 +-
web/src/routes/AppLayout.signOut.test.tsx | 33 ++++++
web/src/routes/AppLayout.tsx | 10 +-
web/src/routes/account/recoveryCodes.tsx | 4 +-
web/src/test/setup.ts | 2 +
9 files changed, 185 insertions(+), 33 deletions(-)
create mode 100644 web/src/routes/AppLayout.signOut.test.tsx
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index 4fc8da78b..4df270086 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -1,6 +1,6 @@
export { STEP_UP_HEADER } from "./request";
export { apiGet, apiPost, apiPut, apiPutBytes, apiDelete, apiGetBlob, apiFetch, restoreSession } from "./refresh";
-export { login, completeSecondFactor, changePassword, confirmTwoFactor, turnOffTwoFactor, stepUp, logout, NO_PROOF, currentSessionGeneration, isSigningOut } 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/refresh.ts b/web/src/api/refresh.ts
index 9a216a79c..f205670a9 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 { isSigningOut, 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 review T1, U1 — 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, no resend.
+ 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
@@ -173,9 +177,6 @@ async function executeHeldRefresh(
}
export async function refreshTokens(heldLock?: HeldAuthCookieLock): Promise {
- // #1277 review T1 — a session being signed out gets no new token. Its
- // callers treat this as a superseded session: no teardown, no resend.
- if (isSigningOut()) throw new StaleSessionError();
// changePassword owns the cross-tab auth lock while apiFetch performs its
// normal 401 refresh-and-retry. Web Locks are not reentrant, so execute that
// nested refresh directly under the lock already held by the caller. Keep
diff --git a/web/src/api/session.ts b/web/src/api/session.ts
index b6a7e04a7..14be2fee2 100644
--- a/web/src/api/session.ts
+++ b/web/src/api/session.ts
@@ -371,15 +371,22 @@ export async function stepUp(proof: StepUpProof): Promise<{ token: string; expir
return noteCode(apiPost<{ token: string; expiresAt: string }>("/auth/step-up", body), proof.code);
}
-// #1277 review T1 — set from the first line of logout() until its request
-// settles, success or failure. The token is already gone, but the page stays
-// signed in until then: while this holds, refreshTokens refuses, so no request
-// authenticates, and the recovery-codes slot starts no code-issuing work.
-let signingOut = false;
-export const isSigningOut = () => signingOut;
+// #1277 review T1, U1 — the generation logout() bumped to. Until the next
+// sign-in bumps past it, 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. An explicit login,
+// and the settledLogin() retry that rides it, bump the generation and so are
+// not refused. A failed revoke leaves the tab signed out all the same.
+let signedOutAt: number | null = null;
+export const isSignedOut = () => signedOutAt === sessionGeneration;
+
+// 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 {
+ signedOutAt = null;
+}
export async function logout(): Promise {
- signingOut = true;
// #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 —
@@ -391,6 +398,7 @@ export async function logout(): Promise {
// instead of only being
// discarded on arrival by the generation check in refreshTokens().
sessionGeneration++;
+ signedOutAt = sessionGeneration;
abortInFlightAuthCookieOperation?.();
// #336/#532 — capture BEFORE clearing: the bearer identifies the actor and
// the farm binding selects this tab's refresh cookie. The clears below are
@@ -402,6 +410,10 @@ 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();
+ // #1277 review U2 — a server that never answers must not keep this tab
+ // half signed out: the revoke gives up after the refresh timeout.
+ const giveUp = new AbortController();
+ const gaveUp = setTimeout(() => giveUp.abort(), REFRESH_TIMEOUT_MS);
try {
// Cookie-authenticated: the HttpOnly refresh cookie rides along and the CSRF
// header satisfies the check. Always fires — JS can't read the HttpOnly
@@ -416,7 +428,7 @@ export async function logout(): Promise {
if (accountId !== null) headers[ACCOUNT_HEADER] = accountId;
await raw(
"/auth/logout",
- { method: "POST", headers },
+ { method: "POST", headers, signal: giveUp.signal },
bearer ?? undefined,
);
} catch (err) {
@@ -426,6 +438,6 @@ export async function logout(): Promise {
// logged, never the (already-cleared) token itself.
console.error("logout: server-side session revoke failed", err);
} finally {
- signingOut = false;
+ clearTimeout(gaveUp);
}
}
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
index e6c91a54e..1a9d88209 100644
--- a/web/src/api/twoFactor.test.ts
+++ b/web/src/api/twoFactor.test.ts
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { changePassword, confirmTwoFactor, logout, setOnTokensChanged, setOnUnauthenticated, STEP_UP_HEADER, turnOffTwoFactor } from "./client";
+import { apiGetBlob, changePassword, confirmTwoFactor, 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";
@@ -192,9 +194,14 @@ describe("an expired token's plain 401", () => {
});
});
-// #1277 review T1 — from the moment sign-out starts until its request settles,
-// the token path refreshes nothing, so no request can authenticate.
-describe("while sign-out is in flight", () => {
+// #1277 review T1, U1 — 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) => {
@@ -202,40 +209,131 @@ describe("while sign-out is in flight", () => {
}));
const done = logout();
await vi.waitFor(() => expect(to("/auth/logout")).toHaveLength(1));
- // A refresh would succeed, so only the refusal keeps it from happening.
- fetchMock.mockResolvedValue(pair(token("acct-S")));
- return async (res: Response | Error = new Response(null, { status: 204 })) => { finish(res); await done; };
+ 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 () => {
+ fetchMock.mockReturnValue(new Promise(() => undefined));
+
+ void logout();
+
+ 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) => {
- const settle = await signOutHeld();
+ 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();
- await settle();
+ });
+
+ 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)("ends when the sign-out request %s, and the next read refreshes again", async (_, answer) => {
+ ] 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);
const settle = await signOutHeld();
await settle(answer);
+ held = null;
+
+ await expect(getTwoFactorStatus()).rejects.toMatchObject({ status: 401 });
+
+ expect(to("/auth/refresh")).toHaveLength(0);
+ 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();
+ 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);
+ first();
+ await a;
+ });
+
+ 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);
+ });
+
+ 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-S"))).mockResolvedValueOnce(json({ enabled: false, recoveryCodesLeft: 0 }));
+ fetchMock
+ .mockResolvedValueOnce(pair(token("acct-L")))
+ .mockResolvedValueOnce(json({ enabled: false, recoveryCodesLeft: 0 }));
+
+ await login({ farmCode: "farm", email: "a@example.test", password: crypto.randomUUID() });
+ expect(isSignedOut()).toBe(false);
await expect(getTwoFactorStatus()).resolves.toEqual({ enabled: false, recoveryCodesLeft: 0 });
+ });
+});
- expect(to("/auth/refresh")).toHaveLength(1);
+// #1277 review U2 — a sign-out the server never answers still ends locally.
+describe("a sign-out the server never answers", () => {
+ afterEach(() => { vi.useRealTimers(); });
+
+ it("gives up on its request after the refresh timeout", async () => {
+ vi.useFakeTimers();
+ const quiet = vi.spyOn(console, "error").mockImplementation(() => undefined);
+ fetchMock.mockImplementation((_url: string, init: RequestInit) => new Promise((_, reject) => {
+ init.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));
+ }));
+ 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);
quiet.mockRestore();
});
});
diff --git a/web/src/components/BottomNav.tsx b/web/src/components/BottomNav.tsx
index eb33aff61..e2910755f 100644
--- a/web/src/components/BottomNav.tsx
+++ b/web/src/components/BottomNav.tsx
@@ -36,11 +36,13 @@ const MORE_VALUE = "__more__";
// #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 = false,
}: {
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")}
)}
-
)}
- }
+ }
sx={{ justifyContent: "flex-start", width: "100%" }}>
{t("signOut")}
@@ -196,7 +200,7 @@ export function AppLayout() {
-
+
);
}
diff --git a/web/src/routes/account/recoveryCodes.tsx b/web/src/routes/account/recoveryCodes.tsx
index 6d68420b6..e17f2def7 100644
--- a/web/src/routes/account/recoveryCodes.tsx
+++ b/web/src/routes/account/recoveryCodes.tsx
@@ -2,7 +2,7 @@ import { createContext, useCallback, useContext, useEffect, useId, useLayoutEffe
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Alert, Box, Button, Checkbox, DialogActions, FormControlLabel, Stack, Typography } from "@mui/material";
-import { currentSessionGeneration, isSigningOut } from "../../api/client";
+import { currentSessionGeneration, isSignedOut } from "../../api/client";
import { useAuth } from "../../auth/useAuth";
import { Dialog } from "../../components/Dialog";
import { useCopy } from "../../components/useCopy";
@@ -97,7 +97,7 @@ export function RecoveryCodesProvider({ children }: { children: ReactNode }) {
// callback never closes over a render's state.
const expect = useCallback((): Delivery | null => {
// #1277 review T1 — no code-issuing work starts once sign-out has begun.
- if (isSigningOut()) return null;
+ 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;
diff --git a/web/src/test/setup.ts b/web/src/test/setup.ts
index 0e48a2d95..56353fea7 100644
--- a/web/src/test/setup.ts
+++ b/web/src/test/setup.ts
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, expect, vi } from "vitest";
import { cleanup } from "@testing-library/react";
import { createFakeIndexedDb } from "./fakeIndexedDb";
import { clearAccessToken } from "../auth/tokenStore";
+import { resetSignOutForTests } from "../api/session";
import { ledgerCellStyles } from "./ledgerCellStyles";
Element.prototype.scrollIntoView ??= vi.fn();
@@ -32,6 +33,7 @@ afterEach(() => {
cleanup();
vi.unstubAllGlobals();
clearAccessToken();
+ 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.
From 476f92b1a1713d9fc8c14b112551c47106571529 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 05:19:21 +0000
Subject: [PATCH 36/45] test(web): pin the status reloads, each button's gate
and the empty confirm
The status reload test now counts its loads: one at mount, one when the request settles, none at Done, with the fresh count read at once. One table test holds the settle reload open at Done for Set up, Regenerate, Replace authenticator app and Turn off. A failed or aborted status read says so and Try again loads it. A confirm with an empty set opens no codes dialog for a first enrolment or a replacement. The slot's contract gains a sign-out case, the /connect check waits for askConsent, and the groups are named by behaviour. The hook says why Turn off still calls status.retry() and why both reload triggers stay.
Refs #1277
---
web/src/App.recoveryCodes.test.tsx | 2 +-
.../account/recoveryCodes.slot.test.tsx | 16 +++
web/src/routes/account/recoveryCodes.test.tsx | 112 ++++++++++++------
web/src/routes/account/useTwoFactor.ts | 5 +-
4 files changed, 100 insertions(+), 35 deletions(-)
diff --git a/web/src/App.recoveryCodes.test.tsx b/web/src/App.recoveryCodes.test.tsx
index 5802ccff3..2384c1f4c 100644
--- a/web/src/App.recoveryCodes.test.tsx
+++ b/web/src/App.recoveryCodes.test.tsx
@@ -107,7 +107,7 @@ describe("the app's own provider tree", () => {
// 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 });
- expect(askConsent).toHaveBeenCalled();
+ 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(); });
diff --git a/web/src/routes/account/recoveryCodes.slot.test.tsx b/web/src/routes/account/recoveryCodes.slot.test.tsx
index d59fa38f8..f4c3f018b 100644
--- a/web/src/routes/account/recoveryCodes.slot.test.tsx
+++ b/web/src/routes/account/recoveryCodes.slot.test.tsx
@@ -1,6 +1,7 @@
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 review S4 (d) — 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.
@@ -11,6 +12,21 @@ 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(() => {
diff --git a/web/src/routes/account/recoveryCodes.test.tsx b/web/src/routes/account/recoveryCodes.test.tsx
index 11bb227c8..ef5890c26 100644
--- a/web/src/routes/account/recoveryCodes.test.tsx
+++ b/web/src/routes/account/recoveryCodes.test.tsx
@@ -219,7 +219,7 @@ beforeEach(() => {
afterEach(() => vi.unstubAllGlobals());
-describe("1. while confirm is in flight", () => {
+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();
@@ -231,7 +231,7 @@ describe("1. while confirm is in flight", () => {
});
});
-describe("2. while the codes are unsaved", () => {
+describe("while the codes are unsaved", () => {
const STAY = {
"a nav click": async () => { await leave("a nav click"); },
"Back": async () => { await leave("a single Back"); },
@@ -255,7 +255,7 @@ describe("2. while the codes are unsaved", () => {
});
});
-describe("3. while regenerate is in flight", () => {
+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();
@@ -268,7 +268,7 @@ describe("3. while regenerate is in flight", () => {
});
});
-describe("4. when the session ends", () => {
+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();
@@ -308,7 +308,7 @@ describe("4. when the session ends", () => {
});
});
-describe("5. a second set of codes in one mount", () => {
+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 });
@@ -330,7 +330,7 @@ describe("5. a second set of codes in one mount", () => {
});
});
-describe("6. closing the tab", () => {
+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() }); });
@@ -344,7 +344,7 @@ describe("6. closing the tab", () => {
});
});
-describe("7. focus after Done", () => {
+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") }));
@@ -371,7 +371,7 @@ describe("7. focus after Done", () => {
});
});
-describe("P1. closing the tab while a code-issuing request is in flight", () => {
+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);
@@ -409,7 +409,7 @@ describe("P1. closing the tab while a code-issuing request is in flight", () =>
});
});
-describe("P2. one code-issuing request at a time", () => {
+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");
@@ -439,7 +439,7 @@ describe("P2. one code-issuing request at a time", () => {
});
});
-describe("P3. what the slot still holds", () => {
+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();
@@ -516,7 +516,7 @@ async function saveAndDone() {
await act(async () => { fireEvent.click(within(dialog).getByRole("button", { name: t("doneButton") })); });
}
-describe("T2. a Turn off that answers after the user came back", () => {
+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;
@@ -546,39 +546,85 @@ describe("T2. a Turn off that answers after the user came back", () => {
});
});
-describe("T3. the status while it reloads after a request settles", () => {
- it("keeps Set up disabled behind Done until the first enrolment's status arrives", async () => {
- const answer = await confirmPending();
+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(screen.getByRole("button", { name: t("setUpButton") })).toBeDisabled();
- await act(async () => { status.resolve({ enabled: true, recoveryCodesLeft: 10 }); });
- expect(await screen.findByText(t("twoFactorOn"))).toBeInTheDocument();
+ 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("keeps Regenerate disabled beside the old count until the new one arrives", async () => {
+ 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();
- // hidden: the closing dialogs may still mark the page aria-hidden.
- const regenerate = () => screen.getByRole("button", { name: t("regenerateButton"), hidden: true });
- expect(screen.getByText(t("recoveryCodesLeft", { count: 1 }))).toBeInTheDocument();
- expect(regenerate()).toBeDisabled();
- await act(async () => { status.resolve({ enabled: true, recoveryCodesLeft: 10 }); });
- expect(await screen.findByText(t("recoveryCodesLeft", { count: 10 }))).toBeInTheDocument();
- expect(regenerate()).toBeEnabled();
+ 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],
+ ["a replacement", true],
+ ] as const)("opens no codes dialog for %s", async (_, replacing) => {
+ 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();
+ if (!replacing) expect(await screen.findByRole("alert")).toHaveTextContent(t("codesMissing"));
});
});
-describe("T6. the status after a refused regenerate", () => {
+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();
@@ -615,7 +661,7 @@ describe("T6. the status after a refused regenerate", () => {
});
});
-describe("S2. the status after coming back to Account", () => {
+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");
@@ -641,7 +687,7 @@ describe("S2. the status after coming back to Account", () => {
});
});
-describe("S4a. regenerate's request ends on every path", () => {
+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();
@@ -698,7 +744,7 @@ describe("S4a. regenerate's request ends on every path", () => {
});
});
-describe("S4b. a request from an ended session", () => {
+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");
@@ -726,7 +772,7 @@ describe("S4b. a request from an ended session", () => {
});
});
-describe("S5. a first enrolment's answer without 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();
@@ -738,8 +784,8 @@ describe("S5. a first enrolment's answer without codes", () => {
});
});
-describe("T1. Sign out while the set-up step is open", () => {
- it("leaves Confirm code sending nothing until sign-out settles, and no codes appear", async () => {
+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")
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index d1158734b..47f995738 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -53,7 +53,8 @@ export function useTwoFactor() {
// #1277 review T2, T3 — 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.
+ // 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 ?? "";
@@ -91,6 +92,8 @@ export function useTwoFactor() {
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"));
From 678f298611aa8770dc7903fde1d4e6fe72164c87 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 06:45:38 +0000
Subject: [PATCH 37/45] fix(web): end a sign-out only at a sign-in that
commits, and never abort the revoke
#1277 review round 8, V1 and V2.
V1: the sign-out intent is a flag set on logout()'s first line. Only
performLogin clears it, where the login's own answer commits its tokens.
A generation bump is not a sign-in. A login abandoned at its deadline,
or one whose rollback is skipped, used to end the refusal, so a queued
refresh could restore the cookie with no login request sent.
refreshTokens now refuses up front, and executeRefresh still refuses
where every refresh sends.
V2: logout no longer aborts its request. The server revokes under the
request's cancellation token, so an abort could cancel the revoke. The
wait ends at the refresh timeout through a timer race, and the request
carries no signal.
The test setup imports the session module inside afterEach, so a test
file's vi.mock of the token path still takes effect.
---
web/src/api/refresh.ts | 4 +-
web/src/api/session.ts | 74 ++++++++++++-------------
web/src/api/twoFactor.test.ts | 100 ++++++++++++++++++++++++++++------
web/src/test/setup.ts | 7 ++-
4 files changed, 125 insertions(+), 60 deletions(-)
diff --git a/web/src/api/refresh.ts b/web/src/api/refresh.ts
index f205670a9..11078651b 100644
--- a/web/src/api/refresh.ts
+++ b/web/src/api/refresh.ts
@@ -40,7 +40,7 @@ class RefreshAdoptionRefusedError extends Error {
async function executeRefresh(generation: number, signal?: AbortSignal): Promise {
// #1277 review T1, U1 — 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, no resend.
+ // 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.
@@ -185,6 +185,8 @@ export async function refreshTokens(heldLock?: HeldAuthCookieLock): Promise("/auth/step-up", body), proof.code);
}
-// #1277 review T1, U1 — the generation logout() bumped to. Until the next
-// sign-in bumps past it, 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. An explicit login,
-// and the settledLogin() retry that rides it, bump the generation and so are
-// not refused. A failed revoke leaves the tab signed out all the same.
-let signedOutAt: number | null = null;
-export const isSignedOut = () => signedOutAt === sessionGeneration;
+// #1277 review T1, U1, V1 — 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 {
- signedOutAt = null;
+ signOutIntent = false;
}
export async function logout(): Promise {
@@ -392,13 +393,11 @@ export async function logout(): Promise {
// 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++;
- signedOutAt = sessionGeneration;
abortInFlightAuthCookieOperation?.();
// #336/#532 — capture BEFORE clearing: the bearer identifies the actor and
// the farm binding selects this tab's refresh cookie. The clears below are
@@ -410,34 +409,29 @@ 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();
- // #1277 review U2 — a server that never answers must not keep this tab
- // half signed out: the revoke gives up after the refresh timeout.
- const giveUp = new AbortController();
- const gaveUp = setTimeout(() => giveUp.abort(), REFRESH_TIMEOUT_MS);
- 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, signal: giveUp.signal },
- 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;
+ const revoke = raw("/auth/logout", { method: "POST", headers }, bearer ?? undefined).catch((err: unknown) => {
// 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);
- } finally {
- clearTimeout(gaveUp);
- }
+ });
+ // #1277 review U2, V2 — a server that never answers must not keep this tab
+ // half signed out, so the wait ends at the refresh timeout. The request is
+ // never aborted: the server revokes under the request's own cancellation
+ // token, so an abort could cancel the revoke itself.
+ let gaveUp: ReturnType | undefined;
+ await Promise.race([revoke, new Promise((resolve) => { gaveUp = setTimeout(resolve, REFRESH_TIMEOUT_MS); })]);
+ clearTimeout(gaveUp);
}
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
index 1a9d88209..11b92356a 100644
--- a/web/src/api/twoFactor.test.ts
+++ b/web/src/api/twoFactor.test.ts
@@ -215,9 +215,11 @@ describe("after sign-out starts", () => {
}
it("refuses from its first line, before any await", async () => {
- fetchMock.mockReturnValue(new Promise(() => undefined));
+ let finish!: () => void;
+ fetchMock.mockImplementationOnce(() => new Promise((resolve) => { finish = () => resolve(new Response(null, { status: 204 })); }));
- void logout();
+ const done = logout();
+ held = async () => { finish(); await done; };
expect(isSignedOut()).toBe(true);
});
@@ -253,14 +255,17 @@ describe("after sign-out starts", () => {
["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);
- const settle = await signOutHeld();
- await settle(answer);
- held = null;
+ try {
+ const settle = await signOutHeld();
+ await settle(answer);
+ held = null;
- await expect(getTwoFactorStatus()).rejects.toMatchObject({ status: 401 });
+ await expect(getTwoFactorStatus()).rejects.toMatchObject({ status: 401 });
- expect(to("/auth/refresh")).toHaveLength(0);
- quiet.mockRestore();
+ 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 () => {
@@ -269,6 +274,7 @@ describe("after sign-out starts", () => {
.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")));
@@ -276,8 +282,6 @@ describe("after sign-out starts", () => {
expect(to("/auth/refresh")).toHaveLength(0);
expect(to("/auth/two-factor/start")).toHaveLength(0);
- first();
- await a;
});
it("refuses a refresh that was queued behind the cross-tab lock before sign-out", async () => {
@@ -300,6 +304,70 @@ describe("after sign-out starts", () => {
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 queued 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({ farmCode: "farm", email: "a@example.test", password: crypto.randomUUID() }).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("refuses the refresh an older write's 401 would supply, and does not resend the write", async () => {
+ vi.useFakeTimers();
+ let answer!: (res: Response) => void;
+ fetchMock.mockImplementation(async (url: string) => (url.endsWith("/auth/logout") ? new Response(null, { status: 204 })
+ : url.endsWith("/auth/refresh") ? pair(token("acct-W"))
+ : 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({ farmCode: "farm", email: "a@example.test", password: crypto.randomUUID() }).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();
@@ -320,12 +388,9 @@ describe("after sign-out starts", () => {
describe("a sign-out the server never answers", () => {
afterEach(() => { vi.useRealTimers(); });
- it("gives up on its request after the refresh timeout", async () => {
+ it("stops waiting at the refresh timeout, and never aborts the revoke", async () => {
vi.useFakeTimers();
- const quiet = vi.spyOn(console, "error").mockImplementation(() => undefined);
- fetchMock.mockImplementation((_url: string, init: RequestInit) => new Promise((_, reject) => {
- init.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));
- }));
+ fetchMock.mockImplementation(() => new Promise(() => undefined));
let ended = false;
void logout().then(() => { ended = true; });
@@ -334,6 +399,9 @@ describe("a sign-out the server never answers", () => {
await vi.advanceTimersByTimeAsync(1);
expect(ended).toBe(true);
- quiet.mockRestore();
+ // The server revokes under the request's own cancellation token, so an
+ // aborted request could leave the session live.
+ const [, init] = to("/auth/logout")[0]!;
+ expect(init.signal?.aborted ?? false).toBe(false);
});
});
diff --git a/web/src/test/setup.ts b/web/src/test/setup.ts
index 56353fea7..914b65950 100644
--- a/web/src/test/setup.ts
+++ b/web/src/test/setup.ts
@@ -6,7 +6,6 @@ import { afterEach, beforeEach, expect, vi } from "vitest";
import { cleanup } from "@testing-library/react";
import { createFakeIndexedDb } from "./fakeIndexedDb";
import { clearAccessToken } from "../auth/tokenStore";
-import { resetSignOutForTests } from "../api/session";
import { ledgerCellStyles } from "./ledgerCellStyles";
Element.prototype.scrollIntoView ??= vi.fn();
@@ -26,14 +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();
- resetSignOutForTests();
+ // 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.
From dbb69bdf6b7274efb1eaee5f27ffe72d51cc976d Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 06:45:52 +0000
Subject: [PATCH 38/45] test(web): pin Sign out in the More menu while a
sign-out is in flight
#1277 review round 8, V3. After a reopen, the More menu's Sign out stays
disabled and sends no second revoke. The comment names the rail and the
More menu.
---
web/src/routes/AppLayout.signOut.test.tsx | 36 +++++++++++++++++++++--
web/src/routes/AppLayout.tsx | 4 +--
2 files changed, 36 insertions(+), 4 deletions(-)
diff --git a/web/src/routes/AppLayout.signOut.test.tsx b/web/src/routes/AppLayout.signOut.test.tsx
index 2e517301b..2c493ee3a 100644
--- a/web/src/routes/AppLayout.signOut.test.tsx
+++ b/web/src/routes/AppLayout.signOut.test.tsx
@@ -5,8 +5,9 @@ import { renderWithProviders } from "../test/renderWithProviders";
import i18n from "../i18n";
import { AppLayout } from "./AppLayout";
-// #1277 review U2 — one sign-out at a time: while its request is out, Sign out
-// is disabled and a second press sends nothing.
+// #1277 review U2, V3 — one sign-out at a time: while its request is out, Sign
+// out is disabled in the rail and the More menu, and a second press sends
+// nothing.
describe("Sign out while a sign-out is in flight", () => {
it("is disabled, sends one revoke, and the app reaches the login page when it answers", async () => {
let answer!: () => void;
@@ -30,4 +31,35 @@ describe("Sign out while a sign-out is in flight", () => {
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;
+ 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 360d3c8be..8e3d4557a 100644
--- a/web/src/routes/AppLayout.tsx
+++ b/web/src/routes/AppLayout.tsx
@@ -67,8 +67,8 @@ export function AppLayout() {
document.title = active ? `${t(active.labelKey)}${t("titleSuffix")}` : "Cluckwork";
}, [groups, location.pathname, t]);
- // #1277 review U2 — one sign-out at a time: both Sign out buttons stay
- // disabled until it lands.
+ // #1277 review U2 — 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);
From fe914bce65a84601db82972d655ff287cbb61c95 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 06:46:07 +0000
Subject: [PATCH 39/45] fix(web): say a replacement is set up when its answer
has no codes
#1277 review round 8, V4 and a small item. A replacement that answers an
empty set now shows the replaced message. The empty-confirm test asserts
the message for each case. A new test checks that a step-up proof from
before a sign-out sends no regenerate after a newer sign-in.
---
web/src/routes/account/recoveryCodes.test.tsx | 28 +++++++++++++++----
web/src/routes/account/useTwoFactor.ts | 2 +-
2 files changed, 24 insertions(+), 6 deletions(-)
diff --git a/web/src/routes/account/recoveryCodes.test.tsx b/web/src/routes/account/recoveryCodes.test.tsx
index ef5890c26..62fceb27b 100644
--- a/web/src/routes/account/recoveryCodes.test.tsx
+++ b/web/src/routes/account/recoveryCodes.test.tsx
@@ -17,7 +17,7 @@ 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 { logout as endSessionHere } from "../../api/session";
+import { isSignedOut, login as signInHere, logout as endSessionHere } from "../../api/session";
import i18n from "../../i18n";
// #1277 MC4 (maintainer, 2026-11-05: "Keep codes above pages"): unsaved
@@ -481,6 +481,24 @@ describe("what the slot holds after a request ends", () => {
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);
+
+ 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() }); });
@@ -603,9 +621,9 @@ describe("the status while it reloads after a request settles", () => {
describe("a confirm answer with an empty set", () => {
it.each([
- ["a first enrolment", false],
- ["a replacement", true],
- ] as const)("opens no codes dialog for %s", async (_, replacing) => {
+ ["a first enrolment", false, "codesMissing"],
+ ["a replacement", true, "replacedMessage"],
+ ] as const)("opens no codes dialog for %s, and says what happened", async (_, replacing, 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 });
@@ -620,7 +638,7 @@ describe("a confirm answer with an empty set", () => {
await act(async () => { answer.resolve({ recoveryCodes: [] }); });
expect(codesDialog()).toBeNull();
- if (!replacing) expect(await screen.findByRole("alert")).toHaveTextContent(t("codesMissing"));
+ expect(await screen.findByText(t(said))).toBeInTheDocument();
});
});
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index 47f995738..afec2b496 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -199,7 +199,7 @@ export function useTwoFactor() {
if (isCodeSet(recoveryCodes)) delivery.deliver(recoveryCodes, { regenerated: false, email });
if (!current()) return;
setFlow(SUMMARY);
- if (!recoveryCodes) setMessage(i18n.t("account:replacedMessage"));
+ if (!isCodeSet(recoveryCodes)) setMessage(i18n.t("account:replacedMessage"));
}
function leaveFlow() {
From 21384b76861ae3e11f42b51f300605d8589ce2cb Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 08:16:28 +0000
Subject: [PATCH 40/45] fix(web): abort the sign-out request at its deadline,
so a late answer keeps a newer cookie
#1277 review round 9, W1, W2 and W3.
W1: a revoke that answered after the 15 s deadline carried a Set-Cookie
that deleted the farm's refresh cookie by name. By then the cookie could
belong to a newer sign-in. logout now aborts its request at the
deadline, and the browser drops the late answer. The server finishes
the revoke anyway, because Logout no longer cancels these writes when
the client goes away. This reverses round 8's V2.
W2: new tests check the sign-out at each sign-in outcome. A refused
password, the second-factor challenge, or a sign-in that a later
sign-out superseded leaves refresh refused. The code step's commit ends
the sign-out.
W3: a new test checks that a signed-out refresh queues nothing, so an
abandoned sign-in gives its generation back.
The older-write test's resend now answers, so a mutant fails on an
assertion and not on the test timeout.
---
web/src/api/session.ts | 16 +++--
web/src/api/twoFactor.test.ts | 125 +++++++++++++++++++++++++++++-----
2 files changed, 116 insertions(+), 25 deletions(-)
diff --git a/web/src/api/session.ts b/web/src/api/session.ts
index 5bb71b9b5..a64e2c4f2 100644
--- a/web/src/api/session.ts
+++ b/web/src/api/session.ts
@@ -420,18 +420,20 @@ export async function logout(): Promise {
// AllowAnonymous, and it is exempt from the Idempotency-Key requirement.
const headers: Record = { [CSRF_HEADER]: "1" };
if (accountId !== null) headers[ACCOUNT_HEADER] = accountId;
- const revoke = raw("/auth/logout", { method: "POST", headers }, bearer ?? undefined).catch((err: unknown) => {
+ // #1277 review W1 — 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. The server finishes the revoke even so: Logout
+ // ignores the client's abort for these writes (MC6). This reverses V2,
+ // which kept the request open because the server used to cancel with it.
+ 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) => {
// 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);
});
- // #1277 review U2, V2 — a server that never answers must not keep this tab
- // half signed out, so the wait ends at the refresh timeout. The request is
- // never aborted: the server revokes under the request's own cancellation
- // token, so an abort could cancel the revoke itself.
- let gaveUp: ReturnType | undefined;
- await Promise.race([revoke, new Promise((resolve) => { gaveUp = setTimeout(resolve, REFRESH_TIMEOUT_MS); })]);
clearTimeout(gaveUp);
}
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
index 11b92356a..c4b26090d 100644
--- a/web/src/api/twoFactor.test.ts
+++ b/web/src/api/twoFactor.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { apiGetBlob, changePassword, confirmTwoFactor, isSignedOut, login, logout, restoreSession, setOnTokensChanged, setOnUnauthenticated, STEP_UP_HEADER, turnOffTwoFactor } from "./client";
+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";
@@ -324,7 +324,7 @@ describe("after sign-out starts", () => {
}
}
- it("refuses a refresh queued behind it, and adopts no token", async () => {
+ 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();
@@ -343,11 +343,31 @@ describe("after sign-out starts", () => {
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({ farmCode: "farm", email: "a@example.test", password: crypto.randomUUID() }).catch(() => undefined);
+ 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(afterDeadline).toBe(signedOut);
+ });
+
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;
+ 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);
@@ -356,7 +376,7 @@ describe("after sign-out starts", () => {
const signIn = login({ farmCode: "farm", email: "a@example.test", password: crypto.randomUUID() }).catch(() => undefined);
await vi.advanceTimersByTimeAsync(0);
- answer(json({ title: "Unauthorized" }, 401));
+ answer!(json({ title: "Unauthorized" }, 401));
await vi.advanceTimersByTimeAsync(REFRESH_TIMEOUT_MS);
await signIn;
await drain(turns);
@@ -384,24 +404,93 @@ describe("after sign-out starts", () => {
});
});
+// #1277 review W2 — 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 credentials = () => ({ farmCode: "farm", email: "a@example.test", password: crypto.randomUUID() });
+ const challenge = () => json({ title: "Auth.SecondFactorRequired", challenge: crypto.randomUUID(), challengeExpiresAt: "2099-01-01T00:00:00Z" }, 401);
+ const answering = (login: () => Response | Promise) => fetchMock.mockImplementation(async (url: string) =>
+ (url.endsWith("/auth/login") ? login() : url.endsWith("/auth/logout") ? new Response(null, { status: 204 }) : pair(token("acct-I"))));
+
+ it("a refused password leaves refresh refused", async () => {
+ answering(() => json({ title: "Unauthorized" }, 401));
+ await logout();
+
+ await expect(login(credentials())).rejects.toMatchObject({ status: 401 });
+
+ 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();
+ const outcome = await login(credentials());
+ if (outcome.kind !== "secondFactor") throw new Error("expected the code step");
+
+ await completeSecondFactor(outcome.challenge, 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 review U2 — 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 never aborts the revoke", async () => {
+ it("stops waiting at the refresh timeout, and aborts the revoke so its late answer cannot land", async () => {
vi.useFakeTimers();
- fetchMock.mockImplementation(() => new Promise(() => undefined));
- 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);
- // The server revokes under the request's own cancellation token, so an
- // aborted request could leave the session live.
- const [, init] = to("/auth/logout")[0]!;
- expect(init.signal?.aborted ?? false).toBe(false);
+ const quiet = vi.spyOn(console, "error").mockImplementation(() => undefined);
+ // As fetch does: the request rejects when its signal aborts, and not before.
+ fetchMock.mockImplementation((_url: string, init: RequestInit) => new Promise((_, reject) => {
+ init.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));
+ }));
+ 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);
+ } finally {
+ quiet.mockRestore();
+ }
});
});
From af9ab431e46146dcc3cd9c673894e39e30e19e3e Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 08:16:42 +0000
Subject: [PATCH 41/45] test(web): require BottomNav's signingOut, and tighten
the sign-out and codes tests
#1277 review round 9, small items.
- BottomNav's signingOut prop is required, so a call site that drops it
fails to compile.
- The More-menu test answers only a revoke that was sent, so a first
press that sends nothing fails on its own assertion.
- Test (e) checks that the proof was asked for, and says why it signs
out through the session module.
- The empty-confirm cases check the role of the region that holds each
message.
---
web/src/components/BottomNav.test.tsx | 2 +-
web/src/components/BottomNav.tsx | 4 ++--
.../pwa/UpdatePrompt.menuAction.integration.test.tsx | 2 +-
web/src/routes/AppLayout.signOut.test.tsx | 4 ++--
web/src/routes/account/recoveryCodes.test.tsx | 12 ++++++++----
5 files changed, 14 insertions(+), 10 deletions(-)
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 e2910755f..0e01de627 100644
--- a/web/src/components/BottomNav.tsx
+++ b/web/src/components/BottomNav.tsx
@@ -36,13 +36,13 @@ const MORE_VALUE = "__more__";
// #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, signingOut = false,
+ groups, tabs, onLogout, signingOut,
}: {
groups: NavGroup[];
tabs: NavEntry[];
onLogout: () => void;
// A sign-out is in flight: Sign out waits for it.
- signingOut?: boolean;
+ signingOut: boolean;
}) {
const { t } = useTranslation("nav");
const [moreOpen, setMoreOpen] = useState(false);
diff --git a/web/src/pwa/UpdatePrompt.menuAction.integration.test.tsx b/web/src/pwa/UpdatePrompt.menuAction.integration.test.tsx
index 2f08fd6f7..0cdf0bd83 100644
--- a/web/src/pwa/UpdatePrompt.menuAction.integration.test.tsx
+++ b/web/src/pwa/UpdatePrompt.menuAction.integration.test.tsx
@@ -32,7 +32,7 @@ function Harness() {
return (
-
+
);
}
diff --git a/web/src/routes/AppLayout.signOut.test.tsx b/web/src/routes/AppLayout.signOut.test.tsx
index 2c493ee3a..061496eaf 100644
--- a/web/src/routes/AppLayout.signOut.test.tsx
+++ b/web/src/routes/AppLayout.signOut.test.tsx
@@ -33,7 +33,7 @@ describe("Sign out while a sign-out is in flight", () => {
});
it("keeps the More menu's Sign out disabled after the menu reopens", async () => {
- let answer!: () => void;
+ 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" } })));
@@ -58,7 +58,7 @@ describe("Sign out while a sign-out is in flight", () => {
expect(vi.mocked(fetch).mock.calls.filter(([input]) => String(input).endsWith("/auth/logout"))).toHaveLength(1);
} finally {
- await act(async () => { answer(); });
+ await act(async () => { answer?.(); });
}
await waitFor(() => expect(screen.getByText("Login page")).toBeInTheDocument());
});
diff --git a/web/src/routes/account/recoveryCodes.test.tsx b/web/src/routes/account/recoveryCodes.test.tsx
index 62fceb27b..9a2aa1b23 100644
--- a/web/src/routes/account/recoveryCodes.test.tsx
+++ b/web/src/routes/account/recoveryCodes.test.tsx
@@ -488,6 +488,10 @@ describe("what the slot holds after a request ends", () => {
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() });
@@ -621,9 +625,9 @@ describe("the status while it reloads after a request settles", () => {
describe("a confirm answer with an empty set", () => {
it.each([
- ["a first enrolment", false, "codesMissing"],
- ["a replacement", true, "replacedMessage"],
- ] as const)("opens no codes dialog for %s, and says what happened", async (_, replacing, said) => {
+ ["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 });
@@ -638,7 +642,7 @@ describe("a confirm answer with an empty set", () => {
await act(async () => { answer.resolve({ recoveryCodes: [] }); });
expect(codesDialog()).toBeNull();
- expect(await screen.findByText(t(said))).toBeInTheDocument();
+ expect((await screen.findByText(t(said))).closest(`[role="${role}"]`)).not.toBeNull();
});
});
From 19627793a2c9d82f4e1df1f3e1eb08e00204ec5d Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 14:16:29 +0000
Subject: [PATCH 42/45] fix(web): log a planned sign-out abort as a give-up,
and test every sign-in outcome
#1277 review round 10, X1 to X4 and the small items.
- X1: the logout comment now says what holds. Once the request reaches
the handler, the server finishes the revoke. A request that never
arrives revokes nothing. The comment names the backend changes it
depends on.
- X2: one table walks the password and code-step sign-ins, each
answering 400, 401, 429, 500 or a network error. Each must leave
refresh refused with no token. The challenge, commit and superseded
cases stay.
- X3: a revoke that answers in time is never aborted later.
- X4: the abort at the deadline logs "stopped waiting" as a warning,
not "revoke failed". A real failure is still logged as an error.
- The generation test checks the bump while the sign-in is queued, and
that no refresh was sent.
---
web/src/api/session.ts | 22 +++++---
web/src/api/twoFactor.test.ts | 95 ++++++++++++++++++++++++++++-------
2 files changed, 93 insertions(+), 24 deletions(-)
diff --git a/web/src/api/session.ts b/web/src/api/session.ts
index a64e2c4f2..f83095c72 100644
--- a/web/src/api/session.ts
+++ b/web/src/api/session.ts
@@ -420,15 +420,25 @@ export async function logout(): Promise {
// AllowAnonymous, and it is exempt from the Idempotency-Key requirement.
const headers: Record = { [CSRF_HEADER]: "1" };
if (accountId !== null) headers[ACCOUNT_HEADER] = accountId;
- // #1277 review W1 — 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. The server finishes the revoke even so: Logout
- // ignores the client's abort for these writes (MC6). This reverses V2,
- // which kept the request open because the server used to cancel with it.
+ // #1277 review W1, X1 — 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. Once the request reaches the handler, the
+ // server finishes the revoke anyway: the backend half of #1277 runs Logout's
+ // writes with CancellationToken.None (MC6) and resolves the flock scope
+ // without the request's token (N2). A request that never arrives revokes
+ // nothing. The browser then keeps the revoked cookie, and the backend marks
+ // logout revocations so reusing it fails quietly instead of tripping #176's
+ // replay rule (MC7). This reverses V2, which kept the request open because
+ // the server used to cancel with it.
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) => {
+ // X4 — the abort above is ours, not a failure.
+ if (giveUp.signal.aborted) {
+ 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 —
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
index c4b26090d..b5bcb4db4 100644
--- a/web/src/api/twoFactor.test.ts
+++ b/web/src/api/twoFactor.test.ts
@@ -17,6 +17,7 @@ const token = (accountId: string) =>
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;
@@ -329,7 +330,7 @@ describe("after sign-out starts", () => {
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({ farmCode: "farm", email: "a@example.test", password: crypto.randomUUID() }).then(() => "signed in", () => "abandoned");
+ const signIn = login(credentials()).then(() => "signed in", () => "abandoned");
await vi.advanceTimersByTimeAsync(0);
const parked = refreshTokens().then(() => "adopted", () => "refused");
@@ -349,7 +350,8 @@ describe("after sign-out starts", () => {
await logout();
const signedOut = currentSessionGeneration();
const turns = lockHeldElsewhere();
- const signIn = login({ farmCode: "farm", email: "a@example.test", password: crypto.randomUUID() }).catch(() => undefined);
+ const signIn = login(credentials()).catch(() => undefined);
+ const whileQueued = currentSessionGeneration();
await vi.advanceTimersByTimeAsync(0);
const parked = refreshTokens().catch(() => undefined);
@@ -359,7 +361,9 @@ describe("after sign-out starts", () => {
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 () => {
@@ -373,7 +377,7 @@ describe("after sign-out starts", () => {
await vi.advanceTimersByTimeAsync(0);
await logout();
const turns = lockHeldElsewhere();
- const signIn = login({ farmCode: "farm", email: "a@example.test", password: crypto.randomUUID() }).catch(() => undefined);
+ const signIn = login(credentials()).catch(() => undefined);
await vi.advanceTimersByTimeAsync(0);
answer!(json({ title: "Unauthorized" }, 401));
@@ -397,7 +401,7 @@ describe("after sign-out starts", () => {
.mockResolvedValueOnce(pair(token("acct-L")))
.mockResolvedValueOnce(json({ enabled: false, recoveryCodesLeft: 0 }));
- await login({ farmCode: "farm", email: "a@example.test", password: crypto.randomUUID() });
+ await login(credentials());
expect(isSignedOut()).toBe(false);
await expect(getTwoFactorStatus()).resolves.toEqual({ enabled: false, recoveryCodesLeft: 0 });
@@ -407,22 +411,43 @@ describe("after sign-out starts", () => {
// #1277 review W2 — 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 credentials = () => ({ farmCode: "farm", email: "a@example.test", password: crypto.randomUUID() });
const challenge = () => json({ title: "Auth.SecondFactorRequired", challenge: crypto.randomUUID(), challengeExpiresAt: "2099-01-01T00:00:00Z" }, 401);
- const answering = (login: () => Response | Promise) => fetchMock.mockImplementation(async (url: string) =>
- (url.endsWith("/auth/login") ? login() : url.endsWith("/auth/logout") ? new Response(null, { status: 204 }) : pair(token("acct-I"))));
-
- it("a refused password leaves refresh refused", async () => {
- answering(() => json({ title: "Unauthorized" }, 401));
- await logout();
+ // 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"))));
+ const refusedSignIns = [
+ ["the password", "/auth/login", () => login(credentials())],
+ ["the code step", "/auth/login/second-factor", async () => {
+ const outcome = await login(credentials());
+ if (outcome.kind !== "secondFactor") throw new Error("expected the code step");
+ return completeSecondFactor(outcome.challenge, freshCode());
+ }],
+ ] as const;
+ const failures = [
+ ["400", () => json({ title: "Validation failed" }, 400)],
+ ["401", () => json({ title: "Unauthorized" }, 401)],
+ ["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(login(credentials())).rejects.toMatchObject({ status: 401 });
+ await expect(signIn()).rejects.toBeDefined();
- expect(isSignedOut()).toBe(true);
- await expect(refreshTokens()).rejects.toBeInstanceOf(StaleSessionError);
- expect(to("/auth/refresh")).toHaveLength(0);
- expect(getAccessToken()).toBeNull();
- });
+ 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);
@@ -471,7 +496,8 @@ describe("a sign-out the server never answers", () => {
it("stops waiting at the refresh timeout, and aborts the revoke so its late answer cannot land", async () => {
vi.useFakeTimers();
- const quiet = vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const failed = vi.spyOn(console, "error");
+ const stopped = vi.spyOn(console, "warn").mockImplementation(() => undefined);
// As fetch does: the request rejects when its signal aborts, and not before.
fetchMock.mockImplementation((_url: string, init: RequestInit) => new Promise((_, reject) => {
init.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));
@@ -489,8 +515,41 @@ describe("a sign-out the server never answers", () => {
// 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();
+ }
+ });
+
+ // X3 — 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();
}
});
+
+ it("still logs a revoke that failed", async () => {
+ const failed = vi.spyOn(console, "error").mockImplementation(() => undefined);
+ try {
+ fetchMock.mockRejectedValue(new TypeError("Failed to fetch"));
+
+ await logout();
+
+ expect(failed).toHaveBeenCalledWith("logout: server-side session revoke failed", expect.any(TypeError));
+ } finally {
+ failed.mockRestore();
+ }
+ });
});
From 410b89c99b2f7f78aab90a6ed4b4ef9332402771 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 15:32:00 +0000
Subject: [PATCH 43/45] fix(web): call a sign-out a give-up only when this
tab's abort caused it
#1277 review round 11, Y1, Y2 and the small items.
- Y1: logout warns "stopped waiting" only when the caught error is the
abort signal's own reason. fetch rejects with that reason, so identity
proves this tab's abort caused the error. A 500 whose body was still
arriving at the deadline, and an abort from elsewhere, are logged as
failed revokes.
- Y2: one table checks that each kind of failure is logged once as an
error and never as a give-up: a network error, a 500, a foreign abort
and a stalled 500.
- The sign-in table adds a suspended farm's 401 and a 403. Each row
checks that its request went out, and the code step shares one
helper.
- Code comments name the behaviour and cite the issue, not review
labels. The logout comment splits the two outcomes: a request that
reaches the server is revoked and fails quietly on reuse; one that
never arrives leaves the session live.
---
web/src/App.tsx | 2 +-
web/src/api/refresh.ts | 6 +--
web/src/api/session.ts | 32 +++++++++-------
web/src/api/twoFactor.test.ts | 49 +++++++++++++++++-------
web/src/routes/AppLayout.tsx | 4 +-
web/src/routes/account/recoveryCodes.tsx | 6 +--
web/src/routes/account/useTwoFactor.ts | 4 +-
7 files changed, 64 insertions(+), 39 deletions(-)
diff --git a/web/src/App.tsx b/web/src/App.tsx
index f9dc9d4fa..9078874dc 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -59,7 +59,7 @@ export function App() {
applied from this device's cache before anyone signs in (#586). */}
- {/* #1277 MC4 — above every route, so no navigation drops recovery
+ {/* #1277 — above every route, so no navigation drops recovery
codes that are not saved yet; it clears when the session ends. */}
diff --git a/web/src/api/refresh.ts b/web/src/api/refresh.ts
index 11078651b..415eec5c3 100644
--- a/web/src/api/refresh.ts
+++ b/web/src/api/refresh.ts
@@ -38,7 +38,7 @@ class RefreshAdoptionRefusedError extends Error {
}
async function executeRefresh(generation: number, signal?: AbortSignal): Promise {
- // #1277 review T1, U1 — checked where every refresh sends, so one queued
+ // #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();
@@ -185,7 +185,7 @@ export async function refreshTokens(heldLock?: HeldAuthCookieLock): Promise(
if (isTransientRefreshFailure(refreshErr)) throw refreshErr;
endSession(err);
}
- // #1277 review — the refresh worked, so the resend answers for the request
+ // #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.
diff --git a/web/src/api/session.ts b/web/src/api/session.ts
index f83095c72..9e66ffad4 100644
--- a/web/src/api/session.ts
+++ b/web/src/api/session.ts
@@ -372,7 +372,7 @@ export async function stepUp(proof: StepUpProof): Promise<{ token: string; expir
return noteCode(apiPost<{ token: string; expiresAt: string }>("/auth/step-up", body), proof.code);
}
-// #1277 review T1, U1, V1 — set by logout(), and cleared only where a login's
+// #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
@@ -420,22 +420,26 @@ export async function logout(): Promise {
// AllowAnonymous, and it is exempt from the Idempotency-Key requirement.
const headers: Record = { [CSRF_HEADER]: "1" };
if (accountId !== null) headers[ACCOUNT_HEADER] = accountId;
- // #1277 review W1, X1 — 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. Once the request reaches the handler, the
- // server finishes the revoke anyway: the backend half of #1277 runs Logout's
- // writes with CancellationToken.None (MC6) and resolves the flock scope
- // without the request's token (N2). A request that never arrives revokes
- // nothing. The browser then keeps the revoked cookie, and the backend marks
- // logout revocations so reusing it fails quietly instead of tripping #176's
- // replay rule (MC7). This reverses V2, which kept the request open because
- // the server used to cancel with it.
+ // #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) => {
- // X4 — the abort above is ours, not a failure.
- if (giveUp.signal.aborted) {
+ // 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;
}
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
index b5bcb4db4..224163ade 100644
--- a/web/src/api/twoFactor.test.ts
+++ b/web/src/api/twoFactor.test.ts
@@ -418,17 +418,23 @@ describe("the sign-out intent at each sign-in outcome", () => {
: 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 () => {
- const outcome = await login(credentials());
- if (outcome.kind !== "secondFactor") throw new Error("expected the code step");
- return completeSecondFactor(outcome.challenge, freshCode());
- }],
+ ["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"))],
@@ -442,6 +448,7 @@ describe("the sign-out intent at each sign-in outcome", () => {
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);
@@ -464,10 +471,8 @@ describe("the sign-out intent at each sign-in outcome", () => {
it("the code step's commit ends it, and refresh sends again", async () => {
answering(challenge);
await logout();
- const outcome = await login(credentials());
- if (outcome.kind !== "secondFactor") throw new Error("expected the code step");
- await completeSecondFactor(outcome.challenge, freshCode());
+ await completeSecondFactor(await codeStep(), freshCode());
expect(isSignedOut()).toBe(false);
await expect(refreshTokens()).resolves.toEqual(expect.any(String));
@@ -498,9 +503,10 @@ describe("a sign-out the server never answers", () => {
vi.useFakeTimers();
const failed = vi.spyOn(console, "error");
const stopped = vi.spyOn(console, "warn").mockImplementation(() => undefined);
- // As fetch does: the request rejects when its signal aborts, and not before.
+ // 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(new DOMException("aborted", "AbortError")));
+ init.signal?.addEventListener("abort", () => reject(init.signal!.reason));
}));
try {
let ended = false;
@@ -540,16 +546,31 @@ describe("a sign-out the server never answers", () => {
}
});
- it("still logs a revoke that failed", async () => {
+ // 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.mockRejectedValue(new TypeError("Failed to fetch"));
+ fetchMock.mockImplementation(answer);
- await logout();
+ const done = logout();
+ await vi.advanceTimersByTimeAsync(REFRESH_TIMEOUT_MS);
+ await done;
- expect(failed).toHaveBeenCalledWith("logout: server-side session revoke failed", expect.any(TypeError));
+ expect(failed).toHaveBeenCalledOnce();
+ expect(stopped).not.toHaveBeenCalled();
} finally {
failed.mockRestore();
+ stopped.mockRestore();
}
});
});
diff --git a/web/src/routes/AppLayout.tsx b/web/src/routes/AppLayout.tsx
index 8e3d4557a..47e45c390 100644
--- a/web/src/routes/AppLayout.tsx
+++ b/web/src/routes/AppLayout.tsx
@@ -67,7 +67,7 @@ export function AppLayout() {
document.title = active ? `${t(active.labelKey)}${t("titleSuffix")}` : "Cluckwork";
}, [groups, location.pathname, t]);
- // #1277 review U2 — one sign-out at a time: Sign out in the rail and the
+ // #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() {
@@ -80,7 +80,7 @@ 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). */}
- {/* #1277 review — focused in place, not followed: a fragment navigation
+ {/* #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. */}
{
diff --git a/web/src/routes/account/recoveryCodes.tsx b/web/src/routes/account/recoveryCodes.tsx
index e17f2def7..56af60221 100644
--- a/web/src/routes/account/recoveryCodes.tsx
+++ b/web/src/routes/account/recoveryCodes.tsx
@@ -9,12 +9,12 @@ import { useCopy } from "../../components/useCopy";
import { MAIN_CONTENT_ID } from "../../lib/mainContent";
import { saveBlob } from "../../lib/saveBlob";
-// #1277 MC4 (maintainer, 2026-11-05: "Keep codes above pages"): recovery codes
+// #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 (MC5, a known limit, as on every other screen). In memory
+// 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.
@@ -96,7 +96,7 @@ export function RecoveryCodesProvider({ children }: { children: ReactNode }) {
// 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 review T1 — no code-issuing work starts once sign-out has begun.
+ // #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.
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index afec2b496..2dab96cfa 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -50,7 +50,7 @@ export function useTwoFactor() {
const [code, setCode] = useState("");
const [message, setMessage] = useState(null);
const slot = useRecoveryCodesSlot();
- // #1277 review T2, T3 — reloaded each time a code-issuing request settles,
+ // #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
@@ -147,7 +147,7 @@ export function useTwoFactor() {
if (delivery === null) return;
try {
const token = await prove();
- // #1277 review S1 — a session that ended during the proof sends
+ // #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;
From b99cc9096921dbe9c43a6c56f9f04333ae62edd0 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 17:00:50 +0000
Subject: [PATCH 44/45] chore(web): tidy the two-factor branch's comments
#1277. Comments only; no behaviour changes.
- Rewrap the comments left ragged when their review labels were
removed, in refresh.ts, session.ts, AppLayout.tsx and useTwoFactor.ts.
- Drop the remaining review labels and review-process notes from the
branch's comments: the skip-link z-index note, and the test headers
in the two-factor, sign-out, slot, hook, App and resend suites.
---
web/src/App.recoveryCodes.test.tsx | 6 +++---
web/src/api/client.test.ts | 7 +++----
web/src/api/refresh.ts | 6 +++---
web/src/api/session.ts | 8 ++++----
web/src/api/twoFactor.test.ts | 12 ++++++------
web/src/routes/AppLayout.signOut.test.tsx | 5 ++---
web/src/routes/AppLayout.tsx | 4 ++--
web/src/routes/account/recoveryCodes.slot.test.tsx | 5 ++---
web/src/routes/account/recoveryCodes.test.tsx | 2 +-
web/src/routes/account/useTwoFactor.test.tsx | 4 ++--
web/src/routes/account/useTwoFactor.ts | 9 ++++-----
web/src/styles.skip-link.test.ts | 2 +-
web/src/styles/dialogs.css | 2 +-
13 files changed, 34 insertions(+), 38 deletions(-)
diff --git a/web/src/App.recoveryCodes.test.tsx b/web/src/App.recoveryCodes.test.tsx
index 2384c1f4c..4a9b1be2d 100644
--- a/web/src/App.recoveryCodes.test.tsx
+++ b/web/src/App.recoveryCodes.test.tsx
@@ -10,9 +10,9 @@ import { setStoredToken } from "./test/jwt";
import { freshCode } from "./test/codes";
import i18n from "./i18n";
-// #1277 review P3 (e), S4 (c) — 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
+// #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(),
diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts
index e40571f6a..b0418dd75 100644
--- a/web/src/api/client.test.ts
+++ b/web/src/api/client.test.ts
@@ -199,10 +199,9 @@ describe("apiFetch — no in-memory token", () => {
});
});
-// #1277 review — 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. Adapted from the
-// round-2 runner's matrix.
+// #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) => {
diff --git a/web/src/api/refresh.ts b/web/src/api/refresh.ts
index 415eec5c3..c6187538a 100644
--- a/web/src/api/refresh.ts
+++ b/web/src/api/refresh.ts
@@ -38,9 +38,9 @@ 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.
+ // #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.
diff --git a/web/src/api/session.ts b/web/src/api/session.ts
index 9e66ffad4..2d8bc7503 100644
--- a/web/src/api/session.ts
+++ b/web/src/api/session.ts
@@ -372,10 +372,10 @@ 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
+// #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;
diff --git a/web/src/api/twoFactor.test.ts b/web/src/api/twoFactor.test.ts
index 224163ade..1a87911ba 100644
--- a/web/src/api/twoFactor.test.ts
+++ b/web/src/api/twoFactor.test.ts
@@ -195,8 +195,8 @@ describe("an expired token's plain 401", () => {
});
});
-// #1277 review T1, U1 — from the moment sign-out starts until the next sign-in,
-// no refresh sends, so no request can get a new token.
+// #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; });
@@ -408,8 +408,8 @@ describe("after sign-out starts", () => {
});
});
-// #1277 review W2 — only a sign-in whose answer commits its tokens ends a
-// sign-out; a refused, challenged or superseded one leaves the tab refused.
+// #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.
@@ -495,7 +495,7 @@ describe("the sign-out intent at each sign-in outcome", () => {
});
});
-// #1277 review U2 — a sign-out the server never answers still ends locally.
+// #1277 — a sign-out the server never answers still ends locally.
describe("a sign-out the server never answers", () => {
afterEach(() => { vi.useRealTimers(); });
@@ -529,7 +529,7 @@ describe("a sign-out the server never answers", () => {
}
});
- // X3 — a revoke that answers in time is never aborted later.
+ // 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);
diff --git a/web/src/routes/AppLayout.signOut.test.tsx b/web/src/routes/AppLayout.signOut.test.tsx
index 061496eaf..5aa2ccd61 100644
--- a/web/src/routes/AppLayout.signOut.test.tsx
+++ b/web/src/routes/AppLayout.signOut.test.tsx
@@ -5,9 +5,8 @@ import { renderWithProviders } from "../test/renderWithProviders";
import i18n from "../i18n";
import { AppLayout } from "./AppLayout";
-// #1277 review U2, V3 — one sign-out at a time: while its request is out, Sign
-// out is disabled in the rail and the More menu, and a second press sends
-// nothing.
+// #1277 — one sign-out at a time: while its request is out, Sign out is
+// disabled in the rail and the More menu, and a second press sends nothing.
describe("Sign out while a sign-out is in flight", () => {
it("is disabled, sends one revoke, and the app reaches the login page when it answers", async () => {
let answer!: () => void;
diff --git a/web/src/routes/AppLayout.tsx b/web/src/routes/AppLayout.tsx
index 47e45c390..ffd7cce84 100644
--- a/web/src/routes/AppLayout.tsx
+++ b/web/src/routes/AppLayout.tsx
@@ -67,8 +67,8 @@ 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.
+ // #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);
diff --git a/web/src/routes/account/recoveryCodes.slot.test.tsx b/web/src/routes/account/recoveryCodes.slot.test.tsx
index f4c3f018b..728c25f9b 100644
--- a/web/src/routes/account/recoveryCodes.slot.test.tsx
+++ b/web/src/routes/account/recoveryCodes.slot.test.tsx
@@ -3,9 +3,8 @@ import { act, fireEvent, renderHook, screen } from "@testing-library/react";
import { RecoveryCodesProvider, useRecoveryCodesSlot } from "./recoveryCodes";
import { logout } from "../../api/session";
-// #1277 review S4 (d) — 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.
-// Adapted from the round-5 runner's slot probe.
+// #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 }));
diff --git a/web/src/routes/account/recoveryCodes.test.tsx b/web/src/routes/account/recoveryCodes.test.tsx
index 9a2aa1b23..b0534f76a 100644
--- a/web/src/routes/account/recoveryCodes.test.tsx
+++ b/web/src/routes/account/recoveryCodes.test.tsx
@@ -20,7 +20,7 @@ import { ApiError, confirmTwoFactor, logout, setOnTokensChanged, setOnUnauthenti
import { isSignedOut, login as signInHere, logout as endSessionHere } from "../../api/session";
import i18n from "../../i18n";
-// #1277 MC4 (maintainer, 2026-11-05: "Keep codes above pages"): unsaved
+// #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,
diff --git a/web/src/routes/account/useTwoFactor.test.tsx b/web/src/routes/account/useTwoFactor.test.tsx
index e1eeb554a..bf401bdd1 100644
--- a/web/src/routes/account/useTwoFactor.test.tsx
+++ b/web/src/routes/account/useTwoFactor.test.tsx
@@ -6,8 +6,8 @@ import { RecoveryCodesProvider } from "./recoveryCodes";
import { getTwoFactorStatus, regenerateRecoveryCodes } from "../../api/cluckwork";
import { stepUp } from "../../api/client";
-// #1277 W3, then MC4 — the hook hands new recovery codes to the slot above
-// the routes and never keeps them itself. JSON.stringify sees only the
+// #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 }));
diff --git a/web/src/routes/account/useTwoFactor.ts b/web/src/routes/account/useTwoFactor.ts
index 2dab96cfa..a052c00e7 100644
--- a/web/src/routes/account/useTwoFactor.ts
+++ b/web/src/routes/account/useTwoFactor.ts
@@ -50,8 +50,8 @@ export function useTwoFactor() {
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
+ // #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.
@@ -147,9 +147,8 @@ export function useTwoFactor() {
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.
+ // #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 {
diff --git a/web/src/styles.skip-link.test.ts b/web/src/styles.skip-link.test.ts
index 264ce066d..f95bd9331 100644
--- a/web/src/styles.skip-link.test.ts
+++ b/web/src/styles.skip-link.test.ts
@@ -4,7 +4,7 @@ import type { Rule } from "postcss";
import { createTheme } from "@mui/material/styles";
import { readStylesheet } from "./test/stylesheet";
-// #1277 review — the focused skip link opens over the docked rail. Chromium
+// #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());
diff --git a/web/src/styles/dialogs.css b/web/src/styles/dialogs.css
index ce636a977..75a6f9a63 100644
--- a/web/src/styles/dialogs.css
+++ b/web/src/styles/dialogs.css
@@ -107,7 +107,7 @@
top: -3rem;
left: 0.75rem;
/* Above MUI's drawer layer (1200), where the docked rail paints over it,
- and below its modal layer (1300) (#1277 review). */
+ and below its modal layer (1300) (#1277). */
z-index: 1250;
background: var(--brand);
color: var(--on-brand);
From 70a3d577b200adbea52c30a64ee369a5638d0087 Mon Sep 17 00:00:00 2001
From: mforce <3101827+mforce@users.noreply.github.com>
Date: Fri, 6 Nov 2026 22:31:08 +0000
Subject: [PATCH 45/45] fix(web): end a screen's dialog sessions in the commit
that removes it
#1277. A step-up proof that resolves after the user leaves a screen must
not send its write. useDialogSession ended the screen's sessions in a
passive effect cleanup. React may run that a task after the commit that
removes the screen, and a proof landing in between still passed
current(). On Regenerate, that sent a regenerate the user had walked away
from: the old recovery codes stopped working without the user asking. The
reset now runs in a layout effect cleanup, during that commit.
The abandoned-by-Back test now resolves the proof in the first microtask
after the next page appears, so it fails whenever the reset lags the
commit. With the reset delayed by one task, the test fails every run;
the test it replaces passed against that delay.
---
web/src/components/useDialogSession.ts | 8 +++++---
web/src/routes/account/recoveryCodes.test.tsx | 14 +++++++++++++-
2 files changed, 18 insertions(+), 4 deletions(-)
diff --git a/web/src/components/useDialogSession.ts b/web/src/components/useDialogSession.ts
index db523a49d..ed58a3bb7 100644
--- a/web/src/components/useDialogSession.ts
+++ b/web/src/components/useDialogSession.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef } from "react";
+import { useCallback, useLayoutEffect, useRef } from "react";
export interface DialogSession {
/**
@@ -55,9 +55,11 @@ export function useDialogSession(): DialogSession {
const sessions = useRef