feat(auth): implement cross-subdomain cookie support with dynamic domain resolution

This commit is contained in:
2026-03-12 00:16:27 +08:00
parent 103c86e14d
commit fb0d135a79

View File

@@ -8,6 +8,16 @@ import { passkey } from "@better-auth/passkey";
const webOrigin = process.env.WEB_ORIGIN ?? "http://localhost:3000"; const webOrigin = process.env.WEB_ORIGIN ?? "http://localhost:3000";
const rpID = new URL(webOrigin).hostname; const rpID = new URL(webOrigin).hostname;
// 从 WEB_ORIGIN 的主机名推导父域(如 csms.uniiem.com → .uniiem.com
// 用于跨子域共享 session cookie本地开发时返回 undefined 不启用。
function getParentDomain(hostname: string): string | undefined {
if (hostname === "localhost" || /^\d/.test(hostname)) return undefined;
const parts = hostname.split(".");
return parts.length >= 3 ? "." + parts.slice(1).join(".") : undefined;
}
const cookieDomain = process.env.COOKIE_DOMAIN ?? getParentDomain(rpID);
export const auth = betterAuth({ export const auth = betterAuth({
database: drizzleAdapter(useDrizzle(), { database: drizzleAdapter(useDrizzle(), {
provider: "pg", provider: "pg",
@@ -35,8 +45,8 @@ export const auth = betterAuth({
], ],
advanced: { advanced: {
cookiePrefix: "helios_auth", cookiePrefix: "helios_auth",
crossSubdomainCookies: process.env.COOKIE_DOMAIN crossSubdomainCookies: cookieDomain
? { enabled: true, domain: process.env.COOKIE_DOMAIN } ? { enabled: true, domain: cookieDomain }
: { enabled: false }, : { enabled: false },
}, },
}); });