diff --git a/src/const/commonConst.ts b/src/const/commonConst.ts index a6ba216..d459a23 100644 --- a/src/const/commonConst.ts +++ b/src/const/commonConst.ts @@ -5,3 +5,5 @@ export const FONT_SIZE = { } as const; export const ALLOW_REDIRECT = new Set(["complete", "screen", "quota"]); + +export const AUTH_COOKIE_MAX_AGE = 24 * 60 * 60; diff --git a/src/lib/auth-cookie.ts b/src/lib/auth-cookie.ts index a27332d..463697c 100644 --- a/src/lib/auth-cookie.ts +++ b/src/lib/auth-cookie.ts @@ -1,31 +1,33 @@ import "server-only"; - import { NextResponse } from "next/server"; +import { AUTH_COOKIE_MAX_AGE } from "@/const/commonConst"; import { serverEnv } from "@/lib/env.server"; import { CookieKeys } from "@/store/cookie/cookie-keys"; -export const setAuthCookie = (response: NextResponse, token: string) => { - const secure = serverEnv.ENV === "prod"; - const options = { - httpOnly: true, - secure, - sameSite: "lax", - path: "/", - } as const; +/** Issue/renew the normal-login cookie, or expire it when the token is empty. */ +export function setAuthCookie(response: NextResponse, token: string): void { + const production = serverEnv.ENV === "prod"; const domain = serverEnv.AUTH_COOKIE_DOMAIN; - response.cookies.set(CookieKeys.AuthToken, token, { - ...options, - ...(domain ? { domain } : {}), - maxAge: token ? 24 * 60 * 60 : 0, - }); + const options = { + httpOnly: true, + secure: production, + sameSite: "lax" as const, + path: "/", + }; + // Serialize each cookie separately: ResponseCookies indexes cookies by name, + // so setting the shared and host-only variants on one instance loses a header. + const append = (value: string, cookieDomain: string | undefined, maxAge: number) => { + const cookieResponse = new NextResponse(null); + cookieResponse.cookies.set(CookieKeys.AuthToken, value, { + ...options, + ...(cookieDomain ? { domain: cookieDomain } : {}), + maxAge, + }); + for (const header of cookieResponse.headers.getSetCookie()) + response.headers.append("Set-Cookie", header); + }; - if (domain) { - // Expire the legacy host-only cookie without replacing the shared cookie header. - const legacy = new NextResponse(); - legacy.cookies.set(CookieKeys.AuthToken, "", { ...options, maxAge: 0 }); - for (const cookie of legacy.headers.getSetCookie()) { - response.headers.append("Set-Cookie", cookie); - } - } -}; + if (domain) append("", undefined, 0); + append(token, domain, token ? AUTH_COOKIE_MAX_AGE : 0); +}