Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(auth): support sharing auth cookies across subdomains (#18200)

Innei0070127ec0c8
diff --git a/src/libs/better-auth/define-config.test.ts b/src/libs/better-auth/define-config.test.ts
index c981a6db069..9cc965e213e 100644
--- a/src/libs/better-auth/define-config.test.ts
+++ b/src/libs/better-auth/define-config.test.ts
@@ -1,12 +1,18 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-const mocks = vi.hoisted(() => ({
- betterAuth: vi.fn((options) => options),
- clearMismatchedOIDCSession: vi.fn(),
- EnvHttpProxyAgent: vi.fn((options) => ({ options })),
- serverDB: {},
- setGlobalDispatcher: vi.fn(),
-}));
+const mocks = vi.hoisted(() => {
+ const authHandler = vi.fn(async () => new Response(null));
+
+ return {
+ appEnv: { APP_URL: 'https://example.com' },
+ authHandler,
+ betterAuth: vi.fn((options) => ({ ...options, handler: authHandler })),
+ clearMismatchedOIDCSession: vi.fn(),
+ EnvHttpProxyAgent: vi.fn((options) => ({ options })),
+ serverDB: {},
+ setGlobalDispatcher: vi.fn(),
+ };
+});
vi.mock('@better-auth/expo', () => ({
expo: vi.fn(() => ({ id: 'expo' })),
@@ -55,9 +61,7 @@ vi.mock('undici', () => ({
}));
vi.mock('@/envs/app', () => ({
- appEnv: {
- APP_URL: 'https://example.com',
- },
+ appEnv: mocks.appEnv,
}));
vi.mock('@/envs/auth', () => ({
@@ -110,12 +114,20 @@ vi.mock('@/server/services/user', () => ({
UserService: vi.fn(),
}));
+const createResponseWithCookie = (cookie: string) => {
+ const response = new Response(null);
+ response.headers.append('set-cookie', cookie);
+
+ return response;
+};
+
describe('defineConfig', () => {
const originalEnv = process.env;
beforeEach(() => {
vi.clearAllMocks();
vi.resetModules();
+ mocks.appEnv.APP_URL = 'https://example.com';
process.env = { ...originalEnv, NODE_ENV: 'test' };
delete process.env.HTTP_PROXY;
delete process.env.http_proxy;
@@ -207,4 +219,78 @@ describe('defineConfig', () => {
expect(mergeLocalNoProxy('*')).toBe('*');
});
+
+ it('should keep auth cookies host-only when no cookie domain is given', async () => {
+ const { defineConfig } = await import('./define-config');
+
+ defineConfig({ plugins: [] });
+ const [options] = mocks.betterAuth.mock.lastCall!;
+
+ expect(options.advanced.crossSubDomainCookies).toBeUndefined();
+ });
+
+ it.each([['https://app.example.com'], ['https://example.com']])(
+ 'should share auth cookies across subdomains when APP_URL %s is under the cookie domain',
+ async (appUrl) => {
+ mocks.appEnv.APP_URL = appUrl;
+ const { defineConfig } = await import('./define-config');
+
+ defineConfig({ cookieDomain: '.example.com', plugins: [] });
+ const [options] = mocks.betterAuth.mock.lastCall!;
+
+ expect(options.advanced.crossSubDomainCookies).toEqual({
+ domain: '.example.com',
+ enabled: true,
+ });
+ },
+ );
+
+ it.each([['https://preview-branch.vercel.app'], ['http://localhost:3010']])(
+ 'should ignore a cookie domain that APP_URL %s does not belong to',
+ async (appUrl) => {
+ mocks.appEnv.APP_URL = appUrl;
+ const { defineConfig } = await import('./define-config');
+
+ defineConfig({ cookieDomain: '.example.com', plugins: [] });
+ const [options] = mocks.betterAuth.mock.lastCall!;
+
+ expect(options.advanced.crossSubDomainCookies).toBeUndefined();
+ },
+ );
+
+ it('should expire the legacy host-only twin of every domain-scoped cookie', async () => {
+ mocks.appEnv.APP_URL = 'https://app.example.com';
+ mocks.authHandler.mockResolvedValueOnce(
+ createResponseWithCookie(
+ '__Secure-better-auth.session_token=token; Path=/; Domain=.example.com; HttpOnly; Secure; SameSite=Lax',
+ ),
+ );
+ const { defineConfig } = await import('./define-config');
+
+ const auth = defineConfig({ cookieDomain: '.example.com', plugins: [] });
+ const response = await auth.handler(
+ new Request('https://app.example.com/api/auth/get-session'),
+ );
+
+ expect(response.headers.getSetCookie()).toEqual([
+ '__Secure-better-auth.session_token=token; Path=/; Domain=.example.com; HttpOnly; Secure; SameSite=Lax',
+ '__Secure-better-auth.session_token=; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax; HttpOnly; Secure',
+ ]);
+ });
+
+ it('should leave cookies alone when no cookie domain is configured', async () => {
+ mocks.authHandler.mockResolvedValueOnce(
+ createResponseWithCookie('__Secure-better-auth.session_token=token; Path=/; Secure'),
+ );
+ const { defineConfig } = await import('./define-config');
+
+ const auth = defineConfig({ plugins: [] });
+ const response = await auth.handler(
+ new Request('https://app.example.com/api/auth/get-session'),
+ );
+
+ expect(response.headers.getSetCookie()).toEqual([
+ '__Secure-better-auth.session_token=token; Path=/; Secure',
+ ]);
+ });
});
diff --git a/src/libs/better-auth/define-config.ts b/src/libs/better-auth/define-config.ts
index af2e816adb0..97f7d18ca85 100644
--- a/src/libs/better-auth/define-config.ts
+++ b/src/libs/better-auth/define-config.ts
@@ -23,6 +23,7 @@ import {
import { emailWhitelist } from '@/libs/better-auth/plugins/email-whitelist';
import { initBetterAuthSSOProviders } from '@/libs/better-auth/sso';
import { createSecondaryStorage, getTrustedOrigins } from '@/libs/better-auth/utils/config';
+import { expireLegacyHostOnlyCookies } from '@/libs/better-auth/utils/host-only-cookies';
import { parseSSOProviders } from '@/libs/better-auth/utils/server';
import { clearMismatchedOIDCSession } from '@/libs/oidc-provider/session-cleanup';
import { EmailService } from '@/server/services/email';
@@ -94,6 +95,25 @@ const getPasskeyOrigins = (): string[] | undefined => {
return undefined;
}
};
+/**
+ * Browsers silently drop a cookie whose `Domain` the current host is not a member of.
+ * Applying a production domain on a preview deployment (`*.vercel.app`) or localhost would
+ * therefore erase every auth cookie instead of widening it, so fall back to host-only there.
+ */
+const resolveCookieDomain = (cookieDomain?: string): string | undefined => {
+ if (!cookieDomain) return undefined;
+
+ const base = cookieDomain.replace(/^\./, '');
+ try {
+ const { hostname } = new URL(appEnv.APP_URL);
+ if (hostname !== base && !hostname.endsWith(`.${base}`)) return undefined;
+ } catch {
+ return undefined;
+ }
+
+ return cookieDomain;
+};
+
const MAGIC_LINK_EXPIRES_IN = 900;
// OTP expiration time (in seconds) - 5 minutes for mobile OTP verification
const OTP_EXPIRES_IN = 300;
@@ -103,10 +123,17 @@ const enabledSSOProviders = parseSSOProviders(authEnv.AUTH_SSO_PROVIDERS);
const { socialProviders, genericOAuthProviders } = initBetterAuthSSOProviders();
interface CustomBetterAuthOptions {
+ /**
+ * Share auth cookies across every subdomain of this domain (e.g. `.example.com`).
+ * Omit to keep cookies host-only.
+ */
+ cookieDomain?: string;
plugins: BetterAuthPlugin[];
}
export function defineConfig(customOptions: CustomBetterAuthOptions) {
+ const cookieDomain = resolveCookieDomain(customOptions.cookieDomain);
+
const options = {
account: {
accountLinking: {
@@ -266,6 +293,9 @@ export function defineConfig(customOptions: CustomBetterAuthOptions) {
socialProviders,
advanced: {
+ ...(cookieDomain && {
+ crossSubDomainCookies: { domain: cookieDomain, enabled: true },
+ }),
database: {
/**
* Align Better Auth user IDs with our shared idGenerator for consistency.
@@ -357,5 +387,12 @@ export function defineConfig(customOptions: CustomBetterAuthOptions) {
],
} satisfies BetterAuthOptions;
- return betterAuth(options);
+ const instance = betterAuth(options);
+ if (!cookieDomain) return instance;
+
+ const handleRequest = instance.handler;
+ instance.handler = async (request) =>
+ expireLegacyHostOnlyCookies(request, await handleRequest(request), cookieDomain);
+
+ return instance;
}
diff --git a/src/libs/better-auth/utils/host-only-cookies.test.ts b/src/libs/better-auth/utils/host-only-cookies.test.ts
new file mode 100644
index 00000000000..161acbc153c
--- /dev/null
+++ b/src/libs/better-auth/utils/host-only-cookies.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest';
+
+import { expireLegacyHostOnlyCookies } from './host-only-cookies';
+
+const SESSION_TOKEN = '__Secure-better-auth.session_token';
+const EXPIRED = 'Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT';
+
+const createRequest = (headers: HeadersInit = {}) =>
+ new Request('https://app.example.com/api/auth/get-session', { headers });
+
+const createResponse = (setCookies: string[]) => {
+ const response = new Response(null);
+ for (const cookie of setCookies) response.headers.append('set-cookie', cookie);
+
+ return response;
+};
+
+const run = (setCookies: string[], headers?: HeadersInit) =>
+ expireLegacyHostOnlyCookies(
+ createRequest(headers),
+ createResponse(setCookies),
+ '.example.com',
+ ).headers.getSetCookie();
+
+describe('expireLegacyHostOnlyCookies', () => {
+ it('mirrors the attributes of the domain-scoped cookie minus its domain', () => {
+ expect(
+ run([`${SESSION_TOKEN}=token; Path=/; Domain=.example.com; HttpOnly; Secure; SameSite=Lax`]),
+ ).toEqual([
+ `${SESSION_TOKEN}=token; Path=/; Domain=.example.com; HttpOnly; Secure; SameSite=Lax`,
+ `${SESSION_TOKEN}=; Path=/; ${EXPIRED}; SameSite=Lax; HttpOnly; Secure`,
+ ]);
+ });
+
+ it('expires the host-only twin when sign-out clears the domain-scoped cookie', () => {
+ expect(
+ run([`${SESSION_TOKEN}=; Max-Age=0; Path=/; Domain=.example.com; HttpOnly; Secure`]),
+ ).toEqual([
+ `${SESSION_TOKEN}=; Max-Age=0; Path=/; Domain=.example.com; HttpOnly; Secure`,
+ `${SESSION_TOKEN}=; Path=/; ${EXPIRED}; HttpOnly; Secure`,
+ ]);
+ });
+
+ it('matches the configured domain regardless of a leading dot or casing', () => {
+ expect(run([`${SESSION_TOKEN}=token; Path=/; Domain=Example.com`])).toEqual([
+ `${SESSION_TOKEN}=token; Path=/; Domain=Example.com`,
+ `${SESSION_TOKEN}=; Path=/; ${EXPIRED}`,
+ ]);
+ });
+
+ it('covers every domain-scoped cookie once', () => {
+ expect(
+ run([
+ `${SESSION_TOKEN}=token; Path=/; Domain=.example.com`,
+ `${SESSION_TOKEN}=token; Path=/; Domain=.example.com`,
+ '__Secure-better-auth.session_data=data; Path=/; Domain=.example.com',
+ ]),
+ ).toEqual([
+ `${SESSION_TOKEN}=token; Path=/; Domain=.example.com`,
+ `${SESSION_TOKEN}=token; Path=/; Domain=.example.com`,
+ '__Secure-better-auth.session_data=data; Path=/; Domain=.example.com',
+ `${SESSION_TOKEN}=; Path=/; ${EXPIRED}`,
+ '__Secure-better-auth.session_data=; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT',
+ ]);
+ });
+
+ it('ignores cookies that are host-only or scoped to another domain', () => {
+ const setCookies = [
+ `${SESSION_TOKEN}=token; Path=/; Secure`,
+ 'analytics=1; Path=/; Domain=.other.com',
+ ];
+
+ expect(run(setCookies)).toEqual(setCookies);
+ });
+
+ it('skips native clients that store cookies without a domain', () => {
+ const setCookies = [`${SESSION_TOKEN}=token; Path=/; Domain=.example.com; Secure`];
+
+ expect(run(setCookies, { 'expo-origin': 'com.lobehub.app://' })).toEqual(setCookies);
+ });
+});
diff --git a/src/libs/better-auth/utils/host-only-cookies.ts b/src/libs/better-auth/utils/host-only-cookies.ts
new file mode 100644
index 00000000000..d99f8d0c27b
--- /dev/null
+++ b/src/libs/better-auth/utils/host-only-cookies.ts
@@ -0,0 +1,70 @@
+const EXPIRED_COOKIE_DATE = 'Thu, 01 Jan 1970 00:00:00 GMT';
+const EXPO_ORIGIN_HEADER = 'expo-origin';
+
+interface ParsedSetCookie {
+ attributes: Map<string, string>;
+ name: string;
+}
+
+const parseSetCookie = (header: string): ParsedSetCookie | undefined => {
+ const [pair, ...rest] = header.split(';');
+ const separator = pair.indexOf('=');
+ if (separator < 1) return undefined;
+
+ const attributes = new Map<string, string>();
+ for (const attribute of rest) {
+ const index = attribute.indexOf('=');
+ const key = (index === -1 ? attribute : attribute.slice(0, index)).trim().toLowerCase();
+ if (key) attributes.set(key, index === -1 ? '' : attribute.slice(index + 1).trim());
+ }
+
+ return { attributes, name: pair.slice(0, separator).trim() };
+};
+
+const toHostOnlyExpiry = ({ attributes, name }: ParsedSetCookie): string => {
+ const parts = [
+ `${name}=`,
+ `Path=${attributes.get('path') || '/'}`,
+ 'Max-Age=0',
+ `Expires=${EXPIRED_COOKIE_DATE}`,
+ ];
+
+ const sameSite = attributes.get('samesite');
+ if (sameSite) parts.push(`SameSite=${sameSite}`);
+ if (attributes.has('httponly')) parts.push('HttpOnly');
+ if (attributes.has('secure')) parts.push('Secure');
+
+ return parts.join('; ');
+};
+
+// Switching to `crossSubDomainCookies` only adds a `Domain` attribute, the cookie name stays the
+// same. Browsers key cookies by (name, domain, path), so a cookie written before the switch lives
+// on as a separate host-only twin that sorts first in the `Cookie` header and shadows the new
+// domain-wide one — sign-out cannot reach it either, since it expires the domain-scoped copy only.
+// Expiring the twin next to every domain-scoped write keeps the two from ever coexisting.
+export const expireLegacyHostOnlyCookies = (
+ request: Request,
+ response: Response,
+ cookieDomain: string,
+): Response => {
+ // `@better-auth/expo` keeps cookies in a name-keyed store with no domain, where this expiry would
+ // instead delete the token the same response just issued.
+ if (request.headers.has(EXPO_ORIGIN_HEADER)) return response;
+
+ const base = cookieDomain.replace(/^\./, '').toLowerCase();
+ const expiries = new Map<string, string>();
+
+ for (const header of response.headers.getSetCookie()) {
+ const parsed = parseSetCookie(header);
+ if (!parsed || expiries.has(parsed.name)) continue;
+
+ const domain = parsed.attributes.get('domain')?.replace(/^\./, '').toLowerCase();
+ if (domain !== base) continue;
+
+ expiries.set(parsed.name, toHostOnlyExpiry(parsed));
+ }
+
+ for (const header of expiries.values()) response.headers.append('set-cookie', header);
+
+ return response;
+};