Merge branch 'fix/v1474-auth' into release/v1.47.4

# Conflicts:
#	src/__tests__/baselines/version-stamp-comments.json
This commit is contained in:
Marc-André Bombeck committed 2026-11-11 21:32:28 +01:00
commit 212ff9ee55
33 files changed
+1177 -151

No files matched your search

@@ -184,3 +184,30 @@ describe("POST /api/auth/login — OIDC_ONLY server-side enforcement", () => {
expect(res.status).toBe(401);
});
});
describe("POST /api/auth/login — per-address limit", () => {
const original = process.env.DEMO_MODE;
afterEach(() => {
if (original === undefined) delete process.env.DEMO_MODE;
else process.env.DEMO_MODE = original;
});
function limitAsked(): unknown {
const call = vi
.mocked(checkAuthSurfaceRateLimit)
.mock.calls.find((c) => c[1] === "auth:login");
return call?.[2];
}
it("allows five attempts per address on an ordinary instance", async () => {
delete process.env.DEMO_MODE;
await POST(makeRequest());
expect(limitAsked()).toBe(5);
});
it("allows thirty on a demo, whose one account everybody shares", async () => {
process.env.DEMO_MODE = "true";
await POST(makeRequest());
expect(limitAsked()).toBe(30);
});
});
+4 -4
View File
@@ -38,13 +38,13 @@ export const POST = apiHandler(async (request: NextRequest) => {
});
}
// v1.4.43 — `checkAuthSurfaceRateLimit` swaps to a tighter
// global bucket when the trust chain is misconfigured; otherwise it
// is byte-equivalent to the previous per-IP `auth:login:{ip}` key.
// Per IP, or one tighter shared bucket when the trust chain is
// misconfigured. A demo publishes its one account, and a class or an
// office behind one address tries it together: 5 locked them out.
const rl = await checkAuthSurfaceRateLimit(
request,
"auth:login",
5,
process.env.DEMO_MODE === "true" ? 30 : 5,
15 * 60 * 1000,
);
const ip = rl.ip ?? "unknown";
@@ -0,0 +1,73 @@
/**
* The language write on a demo.
*
* A demo is one published account every visitor signs into, so a visitor's
* language must not become the account's: the route answers as usual and
* sets the visitor's own cookie, but leaves the shared row alone.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/api-handler", async () => {
const actual =
await vi.importActual<typeof import("@/lib/api-handler")>(
"@/lib/api-handler",
);
return { ...actual, requireActorAuth: vi.fn() };
});
vi.mock("@/lib/db", () => ({ prisma: { user: { update: vi.fn() } } }));
vi.mock("next/headers", () => ({ cookies: vi.fn(async () => ({})) }));
vi.mock("@/lib/i18n/locale-cookie", () => ({ setLocaleCookie: vi.fn() }));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn().mockResolvedValue({ allowed: true }),
rateLimitHeaders: vi.fn(() => ({})),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
import { PUT } from "../route";
import { requireActorAuth } from "@/lib/api-handler";
import { prisma } from "@/lib/db";
import { setLocaleCookie } from "@/lib/i18n/locale-cookie";
const ORIGINAL_DEMO_MODE = process.env.DEMO_MODE;
function put(locale: string) {
return PUT(
new Request("http://localhost/api/auth/me/locale", {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ locale }),
}) as never,
);
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(requireActorAuth).mockResolvedValue({
user: { id: "demo-account", locale: "en" },
} as never);
});
afterEach(() => {
if (ORIGINAL_DEMO_MODE === undefined) delete process.env.DEMO_MODE;
else process.env.DEMO_MODE = ORIGINAL_DEMO_MODE;
});
describe("PUT /api/auth/me/locale", () => {
it("stores the language on the account", async () => {
delete process.env.DEMO_MODE;
const res = await put("de");
expect(res.status).toBe(200);
expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: "demo-account" },
data: { locale: "de" },
});
});
it("keeps a demo visitor's language in their own cookie only", async () => {
process.env.DEMO_MODE = "true";
const res = await put("de");
expect(res.status).toBe(200);
expect(prisma.user.update).not.toHaveBeenCalled();
expect(setLocaleCookie).toHaveBeenCalledWith(expect.anything(), "de");
});
});
+4 -2
View File
@@ -66,8 +66,10 @@ export const PUT = apiHandler(async (request: NextRequest) => {
}
// Idempotent: skip the write (and the annotation noise) when the column
// already matches — the mount-time backfill fires on every page load.
if (user.locale !== locale) {
// already matches — the mount-time backfill fires on every page load. A
// demo is one account every visitor shares, so there the choice stays in
// this visitor's cookie and never reaches the row the next visitor reads.
if (user.locale !== locale && process.env.DEMO_MODE !== "true") {
await prisma.user.update({
where: { id: user.id },
data: { locale },
@@ -0,0 +1,147 @@
/**
* 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. A sign-in that stays in the app replaces
* the sign-in page in the history, so Back does not show the form again.
* A refusal is said in the reader's language, never in the server's words.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { page } from "vitest/browser";
import {
stubFetch,
type FetchStub,
} from "../../../../../tests/browser/fetch-stub";
import { renderWithApp } from "../../../../../tests/browser/render";
import { recordHistory } from "../../../../../tests/browser/url";
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 { MfaLoginStep } from "@/components/auth/mfa-login-step";
import LoginPage from "../page";
let api: FetchStub;
beforeEach(() => {
api = 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],
);
});
});
describe("sign-in page, password", () => {
it("replaces itself with the page asked for", async () => {
api.on("POST", "/api/auth/login", { data: { id: "signed-in" } });
window.history.replaceState(null, "", "/auth/login?next=%2Fmood%3Fadd%3D1");
const history = recordHistory();
const { screen } = await renderWithApp(<LoginPage />, { user: null });
await screen.getByTestId("login-use-password").click();
await screen.getByTestId("login-email").fill("someone");
await page
.elementLocator(document.querySelector("#password")!)
.fill("a long enough passphrase");
await screen.getByTestId("login-password-submit").click();
await expect.poll(() => window.location.pathname).toBe("/mood");
expect(window.location.search).toBe("?add=1");
expect(history.pushes()).toEqual([]);
});
});
describe("sign-in refusals", () => {
async function signInWithPassword() {
const { screen } = await renderWithApp(<LoginPage />, { user: null });
await screen.getByTestId("login-use-password").click();
await screen.getByTestId("login-email").fill("someone");
await page
.elementLocator(document.querySelector("#password")!)
.fill("a long enough passphrase");
await screen.getByTestId("login-password-submit").click();
return screen;
}
it("says the sign-in failed instead of the server's words", async () => {
api.on("POST", "/api/auth/login", {
status: 401,
error: "Invalid credentials",
meta: { errorCode: "http.unauthenticated" },
});
const screen = await signInWithPassword();
await expect.element(screen.getByText("Login failed")).toBeVisible();
expect(document.body.textContent).not.toContain("Invalid credentials");
});
it("says to wait when the limit is reached", async () => {
api.on("POST", "/api/auth/login", {
status: 429,
error: "Too many login attempts. Please try again later.",
meta: { errorCode: "http.rate_limited" },
});
const screen = await signInWithPassword();
await expect
.element(
screen.getByText(
"Too many attempts. Wait a few minutes and try again.",
),
)
.toBeVisible();
});
it("does the same for the second factor", async () => {
api.on("POST", "/api/auth/mfa/verify", {
status: 401,
error: "Invalid code",
meta: { errorCode: "http.unauthenticated" },
});
const { screen } = await renderWithApp(
<MfaLoginStep
mfaTicket="ticket"
methods={["totp"]}
onSuccess={() => {}}
onCancel={() => {}}
/>,
{ user: null },
);
await screen.getByTestId("mfa-code-input").fill("123456");
await screen.getByTestId("mfa-code-submit").click();
await expect
.element(screen.getByText("Verification failed. Please try again."))
.toBeVisible();
expect(document.body.textContent).not.toContain("Invalid code");
});
});
+11 -18
View File
@@ -25,6 +25,7 @@ import { isDashboardSnapshotEnabled } from "@/lib/dashboard/snapshot-flag";
import { prefetchDashboardSnapshot } from "@/lib/queries/use-dashboard-snapshot";
import { clearOfflineCachesForSessionEnd } from "@/lib/pwa/query-persister";
import { sanitizeSameOriginPath } from "@/lib/url-safety";
import { localizedApiError } from "@/lib/api/localized-error";
import { formatDate } from "@/lib/format";
import {
InsecureTransportBanner,
@@ -176,12 +177,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,21 +229,15 @@ 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()) {
prefetchDashboardSnapshot(queryClient);
}
router.push(target);
router.replace(target);
}
async function handlePasskeyLogin() {
@@ -269,7 +266,7 @@ export default function LoginPage() {
// Route rejections carry the envelope error verbatim; everything
// else (WebAuthn ceremony failures) keeps the descriptive mapping.
if (err instanceof ApiError) {
setError(err.message || t("auth.loginFailed"));
setError(localizedApiError(err, t, "auth.loginFailed"));
} else {
const { key, params } = describePasskeyError(err);
setError(t(key, params));
@@ -313,11 +310,7 @@ export default function LoginPage() {
navigateAfterLogin();
} catch (err) {
if (noteRefusal(err)) return;
setError(
err instanceof ApiError && err.message
? err.message
: t("auth.loginFailed"),
);
setError(localizedApiError(err, t, "auth.loginFailed"));
} finally {
setLoading(false);
}
@@ -464,7 +457,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,109 @@
/**
* 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. The app replaces the page in the history, so Back
* does not show the form again.
*/
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 { recordHistory } from "../../../../../tests/browser/url";
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 history = recordHistory();
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(history.pushes()).toEqual([]);
expect(queryClient.getQueryData(queryKeys.dashboardSnapshot())).toBe(
undefined,
);
});
});
describe("registration page, already signed in", () => {
it("keeps the page and says so when the server refuses the sign-out", async () => {
const api = stubFetch().on("POST", "/api/auth/logout", {
status: 403,
error: "Demo mode: modifications are disabled",
meta: { demo: true, errorCode: "demo.readOnly" },
});
window.history.replaceState(null, "", "/auth/register?invite=hlv_x");
const { screen, queryClient } = await renderWithApp(<RegisterPage />, {
user: { username: "signed-in" },
});
await screen.getByTestId("register-sign-out").click();
await expect
.element(screen.getByText("Could not sign out. You are still signed in."))
.toBeVisible();
expect(api.calls("POST", "/api/auth/logout")).toHaveLength(1);
// Nothing was wiped and nobody was sent anywhere: the session is alive.
expect(queryClient.getQueryData(queryKeys.authMe())).toBeDefined();
expect(window.location.search).toBe("?invite=hlv_x");
});
});
describe("registration refusals", () => {
async function register(
response: Parameters<ReturnType<typeof stubFetch>["on"]>[2],
) {
stubFetch()
.on("GET", "/api/auth/me", { status: 401, error: "Unauthorized" })
.on("POST", "/api/auth/register", response);
const { screen } = await renderWithApp(<RegisterPage />, { user: null });
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();
return screen;
}
it("says the registration failed instead of the server's words", async () => {
const screen = await register({
status: 409,
error: "Username or email already taken",
meta: { errorCode: "http.conflict" },
});
await expect.element(screen.getByText("Registration failed")).toBeVisible();
expect(document.body.textContent).not.toContain("already taken");
});
it("shows the password feedback, which the server words for the reader", async () => {
const screen = await register({
status: 422,
error: "Füge ein oder zwei Wörter hinzu.",
meta: { errorCode: "http.invalid" },
});
await expect
.element(screen.getByText("Füge ein oder zwei Wörter hinzu."))
.toBeVisible();
});
});
+11 -13
View File
@@ -12,8 +12,8 @@ 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 { ApiError, apiFetch, apiPost } from "@/lib/api/api-fetch";
import { localizedApiError } from "@/lib/api/localized-error";
import { clearCachesForSessionEnd, useAuth } from "@/hooks/use-auth";
export default function RegisterPage() {
@@ -60,11 +60,8 @@ export default function RegisterPage() {
setLoading(true);
try {
// v1.4.25 — ship the browser-detected timezone with the
// signup payload. Server validates against the IANA list and
// falls back to the admin server-default if the value is
// bogus, so a tampered or proxied request can never poison
// the user's stored zone.
// The server checks the zone against the IANA list and falls back to
// its default, so a tampered value never reaches the account.
const timezone = detectBrowserTimezone();
await apiPost("/api/auth/register", {
email,
@@ -74,13 +71,14 @@ export default function RegisterPage() {
...(inviteToken ? { inviteToken } : {}),
});
await queryClient.invalidateQueries({ queryKey: queryKeys.auth() });
router.push("/");
queryClient.clear(); // nothing cached before belongs to the new account
router.replace("/");
} catch (err) {
// A 422 says what to fix (the password feedback comes localized).
setError(
err instanceof ApiError && err.message
err instanceof ApiError && err.status === 422 && err.message
? err.message
: t("auth.registerFailed"),
: localizedApiError(err, t, "auth.registerFailed"),
);
} finally {
setLoading(false);
@@ -91,7 +89,7 @@ export default function RegisterPage() {
setError(null);
setSigningOut(true);
try {
await apiFetchRaw("/api/auth/logout", { method: "POST" });
await apiFetch("/api/auth/logout", { method: "POST" });
// Same session-end wipe the shell and the menu do: the QueryClient
// outlives the navigation on this SPA and the health-data families are
// not user-scoped, so nothing may survive into the next account.
@@ -106,7 +104,7 @@ export default function RegisterPage() {
);
router.refresh();
} catch {
setError(t("common.networkError"));
setError(t("auth.signOutFailed"));
} finally {
setSigningOut(false);
}