Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
π Make host-only cookie deletions survive the Next.js cookie merge (#2843)
Luke Vellad5a08c2ea130
diff --git a/apps/web/src/app/[locale]/(auth)/components/already-logged-in.tsx b/apps/web/src/app/[locale]/(auth)/components/already-logged-in.tsxindex 51cc070e5..23c70ee3f 100644--- a/apps/web/src/app/[locale]/(auth)/components/already-logged-in.tsx+++ b/apps/web/src/app/[locale]/(auth)/components/already-logged-in.tsx@@ -1,5 +1,4 @@import { buttonVariants } from "@rallly/ui";-import Link from "next/link";import { Trans } from "react-i18next/TransWithoutContext";import { getTranslation } from "@/i18n/server";import { validateRedirectUrl } from "@/lib/utils/redirect";@@ -10,6 +9,7 @@ import {AuthPageHeader,AuthPageTitle,} from "./auth-page";+import { SessionCookieCleanup } from "./session-cookie-cleanup";import { SignOutButton } from "./sign-out-button";/**@@ -27,6 +27,7 @@ export async function AlreadyLoggedIn({ redirectTo }: { redirectTo?: string }) {return (<AuthPageContainer>+ <SessionCookieCleanup /><AuthPageHeader><AuthPageTitle><Trans@@ -47,7 +48,12 @@ export async function AlreadyLoggedIn({ redirectTo }: { redirectTo?: string }) {</AuthPageHeader><AuthPageContent><div className="grid gap-3">- <Link+ {/* Plain anchor, not <Link>: the router cache can hold a stale+ redirect for the destination (the / β /login bounce that+ brought the user here), which a soft navigation replays+ without consulting the server. A document navigation always+ sends the current cookies. */}+ <aclassName={buttonVariants({ variant: "primary", size: "xl" })}href={validateRedirectUrl(redirectTo) ?? "/"}>@@ -57,7 +63,7 @@ export async function AlreadyLoggedIn({ redirectTo }: { redirectTo?: string }) {i18nKey="alreadyLoggedInContinue"defaults="Continue"/>- </Link>+ </a><SignOutButton /></div></AuthPageContent>diff --git a/apps/web/src/app/[locale]/(auth)/components/session-cookie-cleanup.tsx b/apps/web/src/app/[locale]/(auth)/components/session-cookie-cleanup.tsxnew file mode 100644index 000000000..97648f661--- /dev/null+++ b/apps/web/src/app/[locale]/(auth)/components/session-cookie-cleanup.tsx@@ -0,0 +1,21 @@+"use client";++import React from "react";+import { authClient } from "@/lib/auth-client";++// A user wedged by a shadowed session cookie bounces between / and the+// "already signed in" interstitial without ever making a better-auth+// request, so the server side host-only-cookie-cleanup healing never gets+// a chance to run β page renders can't write cookies. One get-session+// round trip from the interstitial gives it that chance: when the Cookie+// header carries a duplicate session token the response deletes the+// host-only shadows, and otherwise it's a cheap no-op. Mounted only on+// the interstitial β the one page a wedged user reliably lands on β to+// keep get-session traffic off the ordinary login flow.+export function SessionCookieCleanup() {+ React.useEffect(() => {+ void authClient.getSession();+ }, []);++ return null;+}diff --git a/apps/web/src/lib/auth-plugins/host-only-cookie-cleanup.test.ts b/apps/web/src/lib/auth-plugins/host-only-cookie-cleanup.test.tsnew file mode 100644index 000000000..84c62dc93--- /dev/null+++ b/apps/web/src/lib/auth-plugins/host-only-cookie-cleanup.test.ts@@ -0,0 +1,106 @@+import { describe, expect, it, vi } from "vitest";++vi.mock("@/env", () => ({+ env: { NEXT_PUBLIC_COOKIE_DOMAIN: ".rallly.test" },+}));++import { hostOnlyCookieCleanup } from "./host-only-cookie-cleanup";++const SESSION_TOKEN = "__Secure-better-auth.session_token";+const SESSION_DATA = "__Secure-better-auth.session_data";++const cookieAttributes = {+ domain: ".rallly.test",+ path: "/",+ httpOnly: true,+ secure: true,+ sameSite: "lax",+};++async function runHandler({+ path,+ cookieHeader,+ responseSetCookie,+}: {+ path: string;+ cookieHeader?: string;+ responseSetCookie?: string;+}) {+ // biome-ignore lint/style/noNonNullAssertion: the plugin always defines this hook+ const { handler } = hostOnlyCookieCleanup.hooks!.after![0];++ const responseHeaders = new Headers();+ if (responseSetCookie) {+ responseHeaders.append("set-cookie", responseSetCookie);+ }++ const result = (await handler({+ path,+ headers: new Headers(cookieHeader ? { cookie: cookieHeader } : {}),+ context: {+ authCookies: {+ sessionToken: { name: SESSION_TOKEN, attributes: cookieAttributes },+ sessionData: { name: SESSION_DATA, attributes: cookieAttributes },+ },+ responseHeaders,+ },+ returnHeaders: true,+ } as never)) as { headers: Headers };++ return result.headers.getSetCookie();+}++describe("hostOnlyCookieCleanup", () => {+ it("does nothing when there is no new session and no shadowed cookie", async () => {+ const cookies = await runHandler({+ path: "/get-session",+ cookieHeader: `${SESSION_TOKEN}=abc.def`,+ });++ expect(cookies).toEqual([]);+ });++ it("clears host-only cookies when the session token is shadowed", async () => {+ const cookies = await runHandler({+ path: "/get-session",+ cookieHeader: `${SESSION_TOKEN}=; ${SESSION_TOKEN}=abc.def`,+ });++ expect(cookies).toHaveLength(2);+ expect(cookies[0]).toContain(`${SESSION_TOKEN}=;`);+ expect(cookies[1]).toContain(`${SESSION_DATA}=;`);+ });++ it("clears host-only cookies when a response sets a new session token", async () => {+ const cookies = await runHandler({+ path: "/sign-in/email-otp",+ responseSetCookie: `${SESSION_TOKEN}=new.token; Max-Age=5184000; Domain=.rallly.test; Path=/; HttpOnly; Secure; SameSite=Lax`,+ });++ expect(cookies).toHaveLength(2);+ });++ it("always clears host-only cookies on sign-out", async () => {+ const cookies = await runHandler({ path: "/sign-out" });++ expect(cookies).toHaveLength(2);+ });++ describe("deletion cookie attributes", () => {+ // Next.js re-serializes better-auth's Set-Cookie headers on some+ // paths (the cookies() merge in route handlers and server actions)+ // and drops Max-Age: 0 on the floor β an empty-value cookie without+ // an expiry is a *session* cookie, so the "deletion" used to mint the+ // very host-only shadow it was meant to clear. Expires survives that+ // pipeline, so every deletion must carry both.+ it("carries Max-Age=0 and an epoch Expires, without a Domain", async () => {+ const cookies = await runHandler({ path: "/sign-out" });++ for (const cookie of cookies) {+ expect(cookie).toContain("Max-Age=0");+ expect(cookie).toContain("Expires=Thu, 01 Jan 1970 00:00:00 GMT");+ expect(cookie).not.toContain("Domain=");+ }+ });+ });+});diff --git a/apps/web/src/lib/auth-plugins/host-only-cookie-cleanup.ts b/apps/web/src/lib/auth-plugins/host-only-cookie-cleanup.tsindex 4676a2948..201fa2431 100644--- a/apps/web/src/lib/auth-plugins/host-only-cookie-cleanup.ts+++ b/apps/web/src/lib/auth-plugins/host-only-cookie-cleanup.ts@@ -56,7 +56,18 @@ export const hostOnlyCookieCleanup: BetterAuthPlugin = {ctx.context.authCookies.sessionData,]) {const { domain: _, ...attributes } = cookie.attributes;- ctx.setCookie(cookie.name, "", { ...attributes, maxAge: 0 });+ // maxAge: 0 alone is not a reliable deletion: Next.js+ // re-serializes Set-Cookie headers on the cookies() merge path+ // and drops the falsy zero, turning the "deletion" into an+ // empty host-only *session* cookie β a shadow that outlives+ // every later deletion attempt and wedges the login redirect+ // loop this plugin exists to prevent. Expires survives that+ // pipeline, so send both.+ ctx.setCookie(cookie.name, "", {+ ...attributes,+ maxAge: 0,+ expires: new Date(0),+ });}}),},