Skip to content

Commit 86c5eb5

Browse files
authored
fix(auth): pass the same secret the production guard checks to Better Auth (#163)
1 parent eaebd75 commit 86c5eb5

2 files changed

Lines changed: 90 additions & 4 deletions

File tree

‎__tests__/auth.test.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2+
3+
vi.mock('@/database/mongoose', () => ({
4+
connectToDatabase: vi.fn().mockResolvedValue({
5+
connection: { db: {} },
6+
}),
7+
isWorkersRuntime: () => false,
8+
}));
9+
10+
vi.mock('@/lib/nodemailer/reset-password', () => ({
11+
sendPasswordResetEmail: vi.fn(),
12+
}));
13+
14+
describe('Better Auth secret resolution and production guard', () => {
15+
const originalEnv = { ...process.env };
16+
const setNodeEnv = (val: string) => {
17+
(process.env as Record<string, string | undefined>).NODE_ENV = val;
18+
};
19+
20+
beforeEach(() => {
21+
vi.resetModules();
22+
process.env = { ...originalEnv };
23+
});
24+
25+
afterEach(() => {
26+
process.env = { ...originalEnv };
27+
});
28+
29+
it('uses BETTER_AUTH_SECRET when only BETTER_AUTH_SECRET is configured', async () => {
30+
setNodeEnv('production');
31+
process.env.BETTER_AUTH_SECRET = 'better-auth-secret-32-chars-long-12345';
32+
delete process.env.AUTH_SECRET;
33+
34+
const { getAuth } = await import('@/lib/better-auth/auth');
35+
const auth = await getAuth();
36+
37+
expect(auth.options.secret).toBe('better-auth-secret-32-chars-long-12345');
38+
});
39+
40+
it('falls back to AUTH_SECRET when only AUTH_SECRET is configured', async () => {
41+
setNodeEnv('production');
42+
delete process.env.BETTER_AUTH_SECRET;
43+
process.env.AUTH_SECRET = 'auth-secret-fallback-32-chars-long-12345';
44+
45+
const { getAuth } = await import('@/lib/better-auth/auth');
46+
const auth = await getAuth();
47+
48+
expect(auth.options.secret).toBe('auth-secret-fallback-32-chars-long-12345');
49+
});
50+
51+
it('prefers BETTER_AUTH_SECRET over AUTH_SECRET when both are configured', async () => {
52+
setNodeEnv('production');
53+
process.env.BETTER_AUTH_SECRET = 'preferred-better-auth-secret-32-chars';
54+
process.env.AUTH_SECRET = 'secondary-auth-secret-32-chars-long';
55+
56+
const { getAuth } = await import('@/lib/better-auth/auth');
57+
const auth = await getAuth();
58+
59+
expect(auth.options.secret).toBe('preferred-better-auth-secret-32-chars');
60+
});
61+
62+
it('rejects in production when neither secret is configured', async () => {
63+
setNodeEnv('production');
64+
delete process.env.BETTER_AUTH_SECRET;
65+
delete process.env.AUTH_SECRET;
66+
67+
const { getAuth } = await import('@/lib/better-auth/auth');
68+
await expect(getAuth()).rejects.toThrow('BETTER_AUTH_SECRET must be set in production');
69+
});
70+
71+
it('preserves existing behaviour in development without either variable', async () => {
72+
setNodeEnv('development');
73+
delete process.env.BETTER_AUTH_SECRET;
74+
delete process.env.AUTH_SECRET;
75+
76+
const { getAuth } = await import('@/lib/better-auth/auth');
77+
const auth = await getAuth();
78+
79+
expect(auth).toBeDefined();
80+
expect(auth.options.secret).toBeUndefined();
81+
});
82+
});

‎lib/better-auth/auth.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@ import { resolveLocale } from "@/i18n/locale";
1010

1111
type MongoDb = Parameters<typeof mongodbAdapter>[0];
1212

13+
const resolveAuthSecret = () => process.env.BETTER_AUTH_SECRET || process.env.AUTH_SECRET;
14+
1315
// Typed from the real config, so additional user fields (country, ...) show up in session types
14-
const createAuth = (database: MongoDb) => betterAuth({
16+
const createAuth = (database: MongoDb, secret: string | undefined = resolveAuthSecret()) => betterAuth({
1517
database: mongodbAdapter(database),
16-
secret: process.env.BETTER_AUTH_SECRET,
18+
secret,
1719
baseURL: process.env.BETTER_AUTH_URL,
1820
// Onboarding answers live on the user so the profile page can show and edit them
1921
user: {
@@ -88,9 +90,11 @@ export const getAuth = async () => {
8890
// createConnection; caching the instance would point a later request at dead sockets.
8991
if (!isWorkersRuntime() && authInstance) return authInstance;
9092

93+
const secret = resolveAuthSecret();
94+
9195
// Without a secret better-auth falls back to a public default anyone could forge sessions with (1.7 refuses it in
9296
// production too); fail here first, before connecting. Checked on first use, not at import, so `next build` needs no secrets.
93-
if (process.env.NODE_ENV === 'production' && !process.env.BETTER_AUTH_SECRET && !process.env.AUTH_SECRET) {
97+
if (process.env.NODE_ENV === 'production' && !secret) {
9498
throw new Error('BETTER_AUTH_SECRET must be set in production');
9599
}
96100

@@ -100,7 +104,7 @@ export const getAuth = async () => {
100104
throw new Error("MongoDB connection not found!");
101105
}
102106

103-
const instance = createAuth(database);
107+
const instance = createAuth(database, secret);
104108
if (!isWorkersRuntime()) authInstance = instance;
105109
return instance;
106110
}

0 commit comments

Comments
 (0)