This commit is contained in:
eric
2026-03-12 19:52:34 -05:00
parent 4a223cd788
commit e5d080c202
18 changed files with 635 additions and 158 deletions

View File

@@ -1,11 +0,0 @@
/**
* 根据请求 host 返回 Cookie domain。
* localhost 时不设 domain生产环境用根域实现跨站 SSO。
*/
export function getAuthCookieDomain(request: { headers: { get: (name: string) => string | null } }): string | undefined {
const envDomain = process.env.AUTH_COOKIE_DOMAIN;
if (envDomain) return envDomain;
const host = request.headers.get("host") ?? "";
if (host.includes("localhost") || host.startsWith("127.0.0.1")) return undefined;
return process.env.AUTH_COOKIE_DOMAIN || ".hackrobot.cn";
}

33
app/lib/auth-cookie.ts Normal file
View File

@@ -0,0 +1,33 @@
/**
* 认证 Cookie 配置
* 生产: AUTH_COOKIE_DOMAIN 实现跨子域 SSO
* 本地 IP: 自动设置 domain 实现多端口共享3000/3001/3002
*/
const COOKIE_NAME = "pb_session";
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
export { COOKIE_NAME, COOKIE_MAX_AGE };
export function getHostFromRequest(request: { headers: { get: (k: string) => string | null } }): string {
const host = request.headers.get("host") || request.headers.get("x-forwarded-host") || "";
return host.split(",")[0].trim().replace(/:\d+$/, "");
}
export function getCookieOptions(clear = false, requestHost?: string) {
const isProd = process.env.NODE_ENV === "production";
const domain = process.env.AUTH_COOKIE_DOMAIN?.trim();
const opts: Record<string, unknown> = {
path: "/",
maxAge: clear ? 0 : COOKIE_MAX_AGE,
secure: isProd,
sameSite: "lax" as const,
httpOnly: true,
};
if (domain && isProd) {
opts.domain = domain;
} else if (!isProd && requestHost && /^(\d{1,3}\.){3}\d{1,3}$/.test(requestHost)) {
opts.domain = requestHost;
}
return opts;
}