fix(auth): an invitation never registers over a live session

`POST /api/auth/register` read no session at all, so a request carrying a valid
`healthlog_session` was handled exactly like an anonymous one and the
unconditional `createSession` at the end replaced the caller's cookie with the
new account's. An admin opening his own invite link to check it was signed out
of his admin account and into a stranger's onboarding, his previous session row
still valid server-side and no longer reachable.

The route now resolves the optional session first and refuses with 409
`already_authenticated`, before the rate-limit bucket is spent and before the
invitation is consumed, so a signed-in visitor neither burns a use nor locks
the door for the person the invitation is for. The register page renders an
explaining panel with a sign-out button in place of the form, so nobody has to
fill three inputs to discover the refusal; signing out returns to the same
invitation rather than to the login screen. Copy lands in all seven locales.
This commit is contained in:
Marc-André Bombeck committed 2026-09-11 09:15:11 +02:00
1 parent cfca84a294
commit ce3c844a58
11 files changed
+373 -4

No files matched your search

@@ -0,0 +1,115 @@
/**
* An invitation opened from inside a live session.
*
* `POST /api/auth/register` refuses that with 409 `already_authenticated`
* (see `src/app/api/auth/register/__tests__/route.test.ts`). The page must not
* make the visitor discover it by filling the form: a signed-in caller gets an
* explanation and a way out instead of three inputs that cannot succeed.
*
* SSR-only, per project convention (node environment, no DOM, no
* `@testing-library/react`), so what is asserted is the PAINT — which branch
* the page rendered. The sign-out click itself is driven in
* `e2e/invite-registration.spec.ts`.
*
* Mutation check, run: drop the `isAuthenticated` branch → the two signed-in
* cases go red naming the form inputs they found, the anonymous case stays
* green.
*/
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
const authRef = {
value: {
user: null as { username: string } | null,
isAuthenticated: false,
isLoading: false,
},
};
const inviteRef = { value: null as string | null };
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn() }),
useSearchParams: () => ({
get: (key: string) => (key === "invite" ? inviteRef.value : null),
}),
}));
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => authRef.value,
clearCachesForSessionEnd: vi.fn(),
}));
import RegisterPage from "../page";
const TOKEN = `hlv_${"a".repeat(64)}`;
function render(): string {
return renderToStaticMarkup(
<QueryClientProvider client={new QueryClient()}>
<I18nProvider initialLocale="en">
<RegisterPage />
</I18nProvider>
</QueryClientProvider>,
);
}
function anonymous(invite: string | null): string {
authRef.value = { user: null, isAuthenticated: false, isLoading: false };
inviteRef.value = invite;
return render();
}
function signedIn(invite: string | null, username = "marc"): string {
authRef.value = {
user: { username },
isAuthenticated: true,
isLoading: false,
};
inviteRef.value = invite;
return render();
}
describe("register page — an invitation cannot be accepted from a live session", () => {
it("renders the form for an anonymous visitor holding an invitation", () => {
const markup = anonymous(TOKEN);
expect(markup).toContain('data-testid="register-invite-banner"');
expect(markup).toContain('id="username"');
expect(markup).not.toContain('data-testid="register-already-signed-in"');
});
it("replaces the form with the explaining panel for a signed-in visitor", () => {
const markup = signedIn(TOKEN);
expect(markup).toContain('data-testid="register-already-signed-in"');
expect(markup).not.toContain('id="username"');
expect(markup).not.toContain('id="password"');
});
it("names the account the visitor is signed in as", () => {
const markup = signedIn(TOKEN, "grandma");
expect(markup).toContain("grandma");
});
it("offers the way out", () => {
const markup = signedIn(TOKEN);
expect(markup).toContain('data-testid="register-sign-out"');
});
it("explains the same thing without an invitation in the URL", () => {
// Reaching /auth/register signed in is the same dead end with or without
// a token — the form below could only ever answer 409.
const markup = signedIn(null);
expect(markup).toContain('data-testid="register-already-signed-in"');
});
it("holds the panel back while the session question is unanswered", () => {
// Fail closed the other way round: an unresolved `/api/auth/me` must not
// flash "you are already signed in" at somebody who is not.
authRef.value = { user: null, isAuthenticated: false, isLoading: true };
inviteRef.value = TOKEN;
const markup = render();
expect(markup).not.toContain('data-testid="register-already-signed-in"');
});
});
+89 -2
View File
@@ -3,7 +3,7 @@
import { useId, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { Loader2, MailOpen, UserPlus } from "lucide-react";
import { Loader2, LogOut, MailOpen, UserPlus } from "lucide-react";
import { Logo } from "@/components/ui/logo";
import Link from "next/link";
import { Button } from "@/components/ui/button";
@@ -13,7 +13,8 @@ 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, apiPost } from "@/lib/api/api-fetch";
import { ApiError, apiFetchRaw, apiPost } from "@/lib/api/api-fetch";
import { clearCachesForSessionEnd, useAuth } from "@/hooks/use-auth";
export default function RegisterPage() {
const router = useRouter();
@@ -23,6 +24,15 @@ export default function RegisterPage() {
// admits the invited user; an open instance simply ignores it.
const inviteToken = searchParams.get("invite");
const queryClient = useQueryClient();
// v1.38.19 — an invitation creates a NEW account, so it cannot be accepted
// from inside a live session; `POST /api/auth/register` refuses one with
// 409 `already_authenticated`. Rendering the form anyway would let the
// visitor discover that by filling it in. `isLoading` holds the panel back
// until the session question is actually answered — failing closed the
// other way round would flash "you are already signed in" at somebody who
// is not.
const { user, isAuthenticated, isLoading: authLoading } = useAuth();
const [signingOut, setSigningOut] = useState(false);
const [email, setEmail] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
@@ -69,6 +79,83 @@ export default function RegisterPage() {
}
}
async function handleSignOut() {
setError(null);
setSigningOut(true);
try {
await apiFetchRaw("/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.
clearCachesForSessionEnd(queryClient);
// Back to this page, invitation intact — NOT to the login screen the
// generic logout goes to. The point of the trip is to accept the
// invitation, and the token only rides the URL.
router.replace(
inviteToken
? `/auth/register?invite=${encodeURIComponent(inviteToken)}`
: "/auth/register",
);
router.refresh();
} catch {
setError(t("common.networkError"));
} finally {
setSigningOut(false);
}
}
if (isAuthenticated && !authLoading) {
return (
<div className="w-full max-w-sm">
<div className="border-border bg-card rounded-xl border p-6 shadow-lg shadow-black/20 sm:p-8">
<div
className="flex flex-col items-center gap-3 text-center"
data-testid="register-already-signed-in"
>
<div className="bg-primary/10 flex h-12 w-12 items-center justify-center rounded-lg">
<Logo className="text-primary" size={28} />
</div>
<h1 className="text-xl font-bold tracking-tight">
{t("auth.alreadySignedIn.title")}
</h1>
<p className="text-muted-foreground text-sm">
{t("auth.alreadySignedIn.body", {
username: user?.username ?? "",
})}
</p>
</div>
{error && (
<div
role="alert"
aria-live="polite"
className="bg-destructive/10 text-destructive mt-6 rounded-lg p-3 text-sm"
>
{error}
</div>
)}
<Button
type="button"
size="lg"
className="mt-8 min-h-11 w-full"
onClick={handleSignOut}
disabled={signingOut}
aria-busy={signingOut || undefined}
data-testid="register-sign-out"
>
{signingOut ? (
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" />
) : (
<LogOut className="h-4 w-4" />
)}
{t("auth.alreadySignedIn.signOut")}
</Button>
</div>
</div>
);
}
return (
<div className="w-full max-w-sm">
{/* v1.4.27 MB7 / CF-61 — drop `p-8` to `p-6 sm:p-8` so the