Files
NianAIGC/lib/server/auth/session-cookie.ts
2026-07-03 11:25:25 +08:00

46 lines
1.4 KiB
TypeScript

import type { NextResponse } from "next/server";
import { SESSION_COOKIE_NAME, shouldUseSecureAuthCookie } from "@/lib/auth/config";
import { chunkCookieValue, chunkedCookieName, chunkedCookieNames } from "@/lib/auth/session";
const MAX_SESSION_COOKIE_CHUNKS = 20;
type CookieResponse = Pick<NextResponse, "cookies">;
export function setSessionCookieValue(
response: CookieResponse,
requestUrl: string,
value: string,
expires: Date
) {
const chunks = chunkCookieValue(value);
const options = {
httpOnly: true,
sameSite: "lax" as const,
secure: shouldUseSecureAuthCookie(requestUrl),
path: "/",
expires
};
chunks.forEach((chunk, index) => {
response.cookies.set(chunkedCookieName(SESSION_COOKIE_NAME, index), chunk, options);
});
for (let index = chunks.length; index < MAX_SESSION_COOKIE_CHUNKS; index += 1) {
response.cookies.set(chunkedCookieName(SESSION_COOKIE_NAME, index), "", clearSessionCookieOptions(requestUrl));
}
}
export function clearSessionCookieValues(response: CookieResponse, requestUrl: string) {
for (const name of chunkedCookieNames(SESSION_COOKIE_NAME, MAX_SESSION_COOKIE_CHUNKS)) {
response.cookies.set(name, "", clearSessionCookieOptions(requestUrl));
}
}
function clearSessionCookieOptions(requestUrl: string) {
return {
httpOnly: true,
sameSite: "lax" as const,
secure: shouldUseSecureAuthCookie(requestUrl),
path: "/",
maxAge: 0
};
}