fix(auth): leave nothing of the last account behind on any sign-in

Only the password and passkey success path cleared the offline copies
on this device. A session that ended by expiry reached the sign-in page
without any wipe, and single sign-on and both profile take-over paths
started the next account on top of the previous one's IndexedDB
snapshot and worker caches.

The shell now clears those copies on every /auth/* page once
/api/auth/me answers 401 or 403: once per signed-out stretch, never on
an answer without a verdict. Single sign-on and the take-over by single
sign-on clear them before leaving for the identity provider, and
registration and the password take-over start from an empty query cache
like the sign-in page does.
This commit is contained in:
Marc-André Bombeck committed 2026-11-11 21:10:38 +01:00
1 parent aae029d94e
commit 75b879279f
8 files changed
+378 -23

No files matched your search

@@ -0,0 +1,52 @@
/**
* The sign-in page, driven by its buttons.
*
* Single sign-on leaves the page for the identity provider and the session
* starts on the way back, so the previous account's offline copies have to
* be gone before the page is left.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { stubFetch } from "../../../../../tests/browser/fetch-stub";
import { renderWithApp } from "../../../../../tests/browser/render";
const clearOffline = vi.hoisted(() => vi.fn(async () => {}));
const loadDocument = vi.hoisted(() => vi.fn());
vi.mock("@/lib/pwa/query-persister", () => ({
clearOfflineCachesForSessionEnd: clearOffline,
}));
vi.mock("@/lib/navigation/load-document", () => ({ loadDocument }));
import LoginPage from "../page";
beforeEach(() => {
stubFetch()
.on("GET", "/api/auth/registration-status", {
data: { registrationEnabled: false, sessionCookieSecure: false },
})
.on("GET", "/api/auth/oidc/status", {
data: { enabled: true, buttonLabel: "Example ID", only: false },
});
});
afterEach(() => {
clearOffline.mockClear();
loadDocument.mockClear();
});
describe("sign-in page, single sign-on", () => {
it("clears the offline copies before leaving for the identity provider", async () => {
const { screen } = await renderWithApp(<LoginPage />, { user: null });
await screen.getByRole("button", { name: "Example ID" }).click();
await expect.poll(() => loadDocument.mock.calls.length).toBe(1);
expect(loadDocument.mock.calls[0][0]).toMatch(
/^\/api\/auth\/oidc\/login\?/,
);
expect(clearOffline).toHaveBeenCalledTimes(1);
expect(clearOffline.mock.invocationCallOrder[0]).toBeLessThan(
loadDocument.mock.invocationCallOrder[0],
);
});
});
+7 -11
View File
@@ -176,12 +176,14 @@ export default function LoginPage() {
staleTime: 60 * 1000,
});
function handleOidcLogin() {
async function handleOidcLogin() {
const params = new URLSearchParams({ next: getRedirectTarget() });
if (clientTransport) {
params.set("client_proto", clientTransport.protocol);
params.set("client_host", clientTransport.host);
}
// The session starts on the way back; the last account's copies go first.
await clearOfflineCachesForSessionEnd();
loadDocument(`/api/auth/oidc/login?${params}`);
}
@@ -226,15 +228,9 @@ export default function LoginPage() {
// stale `["auth","me"]`, so the shell refetches it fresh on mount and the
// former explicit `invalidateQueries({ queryKey: auth() })` is redundant.
queryClient.clear();
// Belt-and-suspenders to match the session-END wipe (logout / 401-expiry):
// also drop the OFFLINE layers — the IndexedDB query snapshot and the SW
// data/page caches — so a previous account's persisted dashboard never
// lingers on disk for the new session. The restore is already per-account
// bound, but a fresh login on a shared browser should leave nothing of the
// prior account behind. Order is clear → prefetch → navigate: the wipe is
// started here (best-effort, like logout) before the prefetch warms THIS
// user's data, and the persister's 1 s debounce gives the single IDB delete
// ample headroom to land before the new snapshot is written.
// The offline layers too, as at every session end. Started before the
// prefetch; the persister's 1 s debounce lets the delete land before the
// new account's snapshot is written.
void clearOfflineCachesForSessionEnd();
const target = getRedirectTarget();
if (target === "/" && isDashboardSnapshotEnabled()) {
@@ -464,7 +460,7 @@ export default function LoginPage() {
<InsecureTransportBanner verdict={verdict} />
{oidcStatus?.enabled && (
<Button
onClick={handleOidcLogin}
onClick={() => void handleOidcLogin()}
variant={oidcStatus.only ? "default" : "outline"}
className="min-h-11 w-full"
size="lg"
@@ -0,0 +1,44 @@
/**
* The registration page, driven by its form.
*
* A new account starts from an empty cache, like every other sign-in: the
* client cache outlives the navigation, and nothing read before the account
* existed belongs to it.
*/
import { describe, expect, it } from "vitest";
import { page } from "vitest/browser";
import { queryKeys } from "@/lib/query-keys";
import { stubFetch } from "../../../../../tests/browser/fetch-stub";
import { renderWithApp } from "../../../../../tests/browser/render";
import RegisterPage from "../page";
async function fill(selector: string, value: string): Promise<void> {
await page.elementLocator(document.querySelector(selector)!).fill(value);
}
describe("registration page", () => {
it("starts the new account from an empty cache", async () => {
const api = stubFetch()
.on("GET", "/api/auth/me", { status: 401, error: "Unauthorized" })
.on("POST", "/api/auth/register", { data: { id: "new-account" } });
window.history.replaceState(null, "", "/auth/register");
const { screen, queryClient } = await renderWithApp(<RegisterPage />, {
user: null,
});
// Left over from whoever used this browser before.
queryClient.setQueryData(queryKeys.dashboardSnapshot(), { stale: true });
await fill("#email", "new@example.com");
await fill("#username", "newcomer");
await fill("#password", "a long enough passphrase");
await screen.getByRole("button", { name: "Sign up" }).click();
await expect.poll(() => window.location.pathname).toBe("/");
expect(api.calls("POST", "/api/auth/register")).toHaveLength(1);
expect(queryClient.getQueryData(queryKeys.dashboardSnapshot())).toBe(
undefined,
);
});
});
+1 -2
View File
@@ -12,7 +12,6 @@ import { Label } from "@/components/ui/label";
import { PasswordStrength } from "@/components/ui/password-strength";
import { useTranslations } from "@/lib/i18n/context";
import { detectBrowserTimezone } from "@/lib/tz/format";
import { queryKeys } from "@/lib/query-keys";
import { ApiError, apiFetchRaw, apiPost } from "@/lib/api/api-fetch";
import { clearCachesForSessionEnd, useAuth } from "@/hooks/use-auth";
@@ -74,7 +73,7 @@ export default function RegisterPage() {
...(inviteToken ? { inviteToken } : {}),
});
await queryClient.invalidateQueries({ queryKey: queryKeys.auth() });
queryClient.clear(); // nothing cached before belongs to the new account
router.push("/");
} catch (err) {
setError(