Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat: sign-in, sign-up, password reset and 2FA run on better-auth (#608)

Carl-Gerhard Lindesvärd2611277552d0
diff --git a/AGENTS.md b/AGENTS.md
index 5285f831d..bd3f946f0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -113,9 +113,9 @@ curl -sS -X POST "$API_URL/track" \
# Management API (root client)
curl -sS "$API_URL/manage/projects" -H "openpanel-client-id: $ROOT_ID" -H "openpanel-client-secret: $ROOT_SECRET"
-# tRPC as the seeded user: sign in, keep the `session` cookie, call any procedure
-curl -sS -c cookies.txt -X POST "$API_URL/trpc/auth.signInEmail" -H 'content-type: application/json' \
- -d '{"json":{"email":"[email protected]","password":"openpanel"}}'
+# tRPC as the seeded user: sign in through better-auth, keep its cookie, call any procedure
+curl -sS -c cookies.txt -X POST "$API_URL/api/auth/sign-in/email" -H 'content-type: application/json' \
+ -H "origin: $DASHBOARD_URL" -d '{"email":"[email protected]","password":"openpanel"}'
curl -sS -b cookies.txt "$API_URL/trpc/organization.list"
# The product's MCP (streamable HTTP; url with token is `.seed.json` → mcp.url)
diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.ts
index 751b81041..575bff153 100644
--- a/apps/api/src/config/env.ts
+++ b/apps/api/src/config/env.ts
@@ -756,6 +756,12 @@ function deriveDashboardUrl(raw: RawEnv): string {
return raw.DASHBOARD_URL ?? '';
}
+function deriveDashboardOrigins(raw: RawEnv): string[] {
+ return [deriveDashboardUrl(raw), ...splitTokens(raw.API_CORS_ORIGINS)].filter(
+ Boolean
+ );
+}
+
/** The Kafka transport's knobs, including the producer's three throughput ones. */
function deriveKafkaConfig(raw: RawEnv): CoreConfig['kafka'] {
return {
@@ -851,6 +857,7 @@ function deriveCoreConfig(raw: RawEnv): CoreConfig {
},
auth: {
secret: raw.AUTH_SECRET ?? (raw.COOKIE_SECRET || undefined),
+ trustedOrigins: deriveDashboardOrigins(raw),
allowRegistration:
raw.ALLOW_REGISTRATION === undefined
? undefined
@@ -1016,7 +1023,6 @@ const envSchema = rawSchema
checkProfileBackfillProjectsHaveAFlag(raw, ctx);
})
.transform((raw): Config => {
- const dashboardUrl = deriveDashboardUrl(raw);
return {
ROLE: raw.ROLE,
LOG_LEVEL: raw.LOG_LEVEL,
@@ -1031,10 +1037,7 @@ const envSchema = rawSchema
SHUTDOWN_FORCE_EXIT_MS: raw.SHUTDOWN_FORCE_EXIT_MS,
REDIS_CACHE_COMMAND_TIMEOUT_MS: raw.REDIS_CACHE_COMMAND_TIMEOUT_MS,
INGEST_DEAD_LETTER_MAX_ENTRIES: raw.INGEST_DEAD_LETTER_MAX_ENTRIES,
- dashboardOrigins: [
- dashboardUrl,
- ...splitTokens(raw.API_CORS_ORIGINS),
- ].filter(Boolean),
+ dashboardOrigins: deriveDashboardOrigins(raw),
verboseClientIds: splitTokens(raw.ENABLE_VERBOSE_LOGGING),
listen: raw.API_HOST
? { port: raw.API_PORT, hostname: raw.API_HOST }
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index da1b9a4b2..7ba5757b4 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -187,7 +187,12 @@ function buildDeps(): AppDeps {
producers,
logger,
config: config.core,
- auth: createAuth({ db, config: config.core, logger }),
+ auth: createAuth({
+ db,
+ config: config.core,
+ logger,
+ redis: getRedisCache(),
+ }),
};
}
diff --git a/apps/start/e2e/auth-helpers.ts b/apps/start/e2e/auth-helpers.ts
index 0b3d2df2b..a7cdbf2c2 100644
--- a/apps/start/e2e/auth-helpers.ts
+++ b/apps/start/e2e/auth-helpers.ts
@@ -2,7 +2,12 @@ import { execFileSync } from 'node:child_process';
import { createHmac } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
-import type { Locator, Page, Response } from '@playwright/test';
+import type {
+ APIRequestContext,
+ Locator,
+ Page,
+ Response,
+} from '@playwright/test';
export const FRESH_CONTEXT = { cookies: [], origins: [] };
export const SHOTS_DIR = 'test-results/auth/shots';
@@ -14,11 +19,10 @@ const TOTP_OFFSET_MODULUS = 16;
const TOTP_SIGN_BIT = 2 ** 31;
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
-// The API allows 3 `auth.signInEmail` calls per 30s for the whole local stack
-// (every loopback client shares one bucket) and answers the 4th with a 5 minute
-// block that doubles on each repeat. Spacing our own attempts keeps a run under
+// better-auth allows 3 sign-in or sign-up calls per 10s per client IP, and
+// every local browser shares one. Spacing our own attempts keeps a run under
// it; the timestamp lives in a file because a failed test restarts the worker.
-const SIGN_IN_SPACING_MS = 11_000;
+const SIGN_IN_SPACING_MS = 4000;
const SIGN_IN_CLOCK_FILE = 'test-results/auth/.last-sign-in';
const TOO_MANY_REQUESTS = 429;
@@ -43,18 +47,53 @@ export async function submitSignIn(
await page.getByLabel('Email').fill(credentials.email);
await page.getByLabel('Password', { exact: true }).fill(credentials.password);
const answer = page.waitForResponse((response) =>
- response.url().includes('/trpc/auth.signInEmail')
+ response.url().includes(SIGN_IN_PATH)
);
await page.getByRole('button', { name: 'Sign in', exact: true }).click();
const response = await answer;
if (response.status() === TOO_MANY_REQUESTS) {
throw new Error(
- 'auth.signInEmail is rate limited (shared bucket). Wait for the block to expire and rerun.'
+ 'Sign-in is rate limited (shared bucket). Wait 10 seconds and rerun.'
);
}
return response;
}
+export const SIGN_IN_PATH = '/api/auth/sign-in/email';
+
+/** A JSON call to better-auth, from the dashboard's origin as the browser makes it. */
+export function authPost(
+ request: APIRequestContext,
+ path: string,
+ data: unknown
+) {
+ return request.post(`${apiUrl()}/api/auth${path}`, {
+ data,
+ headers: { origin: process.env.DASHBOARD_URL ?? '' },
+ });
+}
+
+/** Signs up through better-auth, spaced like a sign-in. */
+export async function signUpWithEmail(
+ request: APIRequestContext,
+ user: {
+ email: string;
+ password: string;
+ firstName?: string;
+ lastName?: string;
+ }
+) {
+ await waitForSignInSlot();
+ const firstName = user.firstName ?? 'E2E';
+ const lastName = user.lastName ?? 'Auth';
+ return authPost(request, '/sign-up/email', {
+ ...user,
+ firstName,
+ lastName,
+ name: `${firstName} ${lastName}`,
+ });
+}
+
export function toast(page: Page, text: string | RegExp): Locator {
return page.locator('[data-sonner-toast]').filter({ hasText: text });
}
diff --git a/apps/start/e2e/auth-login.spec.ts b/apps/start/e2e/auth-login.spec.ts
index 39d34ca21..5154857be 100644
--- a/apps/start/e2e/auth-login.spec.ts
+++ b/apps/start/e2e/auth-login.spec.ts
@@ -7,6 +7,7 @@ import {
gotoHydrated,
hasHorizontalOverflow,
SHOTS_DIR,
+ SIGN_IN_PATH,
submitSignIn,
toast,
waitForHydration,
@@ -19,7 +20,7 @@ test.use({ storageState: FRESH_CONTEXT });
test.describe.configure({ timeout: 120_000 });
const MOBILE_VIEWPORT = { width: 390, height: 844 };
-const SIGN_IN_REQUEST = '/trpc/auth.signInEmail';
+const SESSION_COOKIE = 'openpanel.session_token';
const DEV_SIGN_IN_REQUEST = '/trpc/auth.signInDev';
test('signed-out visitors are sent to /login from every protected route', async ({
@@ -58,7 +59,7 @@ test('the login form validates before it calls the API', async ({ page }) => {
const issues = watchIssues(page);
let signInRequests = 0;
page.on('request', (request) => {
- if (request.url().includes(SIGN_IN_REQUEST)) {
+ if (request.url().includes(SIGN_IN_PATH)) {
signInRequests += 1;
}
});
@@ -100,9 +101,9 @@ test('a wrong password and an unknown email are both refused', async ({
email: seed.user.email,
password: 'definitely-not-the-password',
});
- // 400, not 401: the dashboard reads any 401 as "signed out" and redirects.
- expect(wrongPassword.status()).toBe(400);
- await expect(toast(page, 'Incorrect email or password')).toBeVisible();
+ // better-auth's 401 goes to the form, not through the tRPC "signed out" handler.
+ expect(wrongPassword.status()).toBe(401);
+ await expect(toast(page, 'Invalid email or password')).toBeVisible();
await expect(page).toHaveURL(/\/login$/);
await page.screenshot({ path: `${SHOTS_DIR}/login-wrong-password.png` });
@@ -114,8 +115,8 @@ test('a wrong password and an unknown email are both refused', async ({
await expect(page).toHaveURL(/\/login$/);
expect(
(await page.context().cookies()).map((cookie) => cookie.name)
- ).not.toContain('session');
- expect(issues.unexpected([/auth\.signInEmail/])).toEqual([]);
+ ).not.toContain(SESSION_COOKIE);
+ expect(issues.unexpected([/api\/auth\/sign-in/])).toEqual([]);
});
test('sign in, land on the organization, then log out from the profile menu', async ({
@@ -136,7 +137,7 @@ test('sign in, land on the organization, then log out from the profile menu', as
});
const cookies = await context.cookies();
- const session = cookies.find((cookie) => cookie.name === 'session');
+ const session = cookies.find((cookie) => cookie.name === SESSION_COOKIE);
expect(session).toMatchObject({
httpOnly: true,
secure: true,
@@ -169,15 +170,14 @@ test('sign in, land on the organization, then log out from the profile menu', as
await expect(page.getByText('Used last time')).toBeVisible();
await page.screenshot({ path: `${SHOTS_DIR}/login-used-last-time.png` });
const afterLogout = (await context.cookies()).map((cookie) => cookie.name);
- expect(afterLogout).not.toContain('session');
+ expect(afterLogout).not.toContain(SESSION_COOKIE);
await page.goto(`/${seed.organizationId}`);
await expect(page).toHaveURL(/\/login$/);
// The server forgot the session too: replaying the old cookie is anonymous.
- const replay = await request.get(
- `${new URL(response.url()).origin}/trpc/auth.session`,
- { headers: { cookie: `session=${session?.value}` } }
- );
+ const replay = await request.get(`${apiUrl()}/trpc/auth.session`, {
+ headers: { cookie: `${SESSION_COOKIE}=${session?.value}` },
+ });
expect((await replay.json()).result.data.json.userId).toBeNull();
expect(issues.unexpected()).toEqual([]);
});
@@ -247,7 +247,7 @@ test('the dev login button signs in with one click when DEV_LOGIN is set', async
timeout: 20_000,
});
expect((await context.cookies()).map((cookie) => cookie.name)).toContain(
- 'session'
+ SESSION_COOKIE
);
expect(issues.unexpected()).toEqual([]);
});
diff --git a/apps/start/e2e/auth-onboarding.spec.ts b/apps/start/e2e/auth-onboarding.spec.ts
index 331e00035..2d21d47cf 100644
--- a/apps/start/e2e/auth-onboarding.spec.ts
+++ b/apps/start/e2e/auth-onboarding.spec.ts
@@ -11,6 +11,7 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import type { BrowserContext, Page } from '@playwright/test';
import {
apiUrl,
+ authPost,
FRESH_CONTEXT,
gotoHydrated,
hasHorizontalOverflow,
@@ -20,6 +21,7 @@ import {
totpCode,
trackEvent,
waitForHydration,
+ waitForSignInSlot,
watchIssues,
wrongTotpCode,
} from './auth-helpers';
@@ -34,8 +36,10 @@ const RUN_ID = Date.now();
const MOBILE_VIEWPORT = { width: 390, height: 844 };
const DESKTOP_VIEWPORT = { width: 1280, height: 720 };
const RECOVERY_CODE_COUNT = 10;
-const RECOVERY_CODE_PATTERN = /[A-Z2-9]{5}-[A-Z2-9]{5}/g;
-const TOTP_SECRET_PATTERN = /[A-Z2-7]{32}/;
+const RECOVERY_CODE_PATTERN = /\b[A-Za-z0-9]{5}-[A-Za-z0-9]{5}\b/g;
+const TOTP_SECRET_PATTERN = /[A-Z2-7]{32,}/;
+const SESSION_COOKIE = 'openpanel.session_token';
+const RECOVERY_PLACEHOLDER = 'AbCdE-fGhIj';
const FRAMEWORK_COUNT = 17;
const WEBSITE_FRAMEWORK_COUNT = 8;
const EVENT_ARRIVAL_TIMEOUT_MS = 45_000;
@@ -99,12 +103,13 @@ function otpInput(scope: Page | ReturnType<Page['getByRole']>) {
return scope.locator('input[data-input-otp]');
}
+/** better-auth keeps the token in the identifier of a `verifications` row. */
function resetTokenFor(email: string): string {
const databaseUrl = (process.env.DATABASE_URL ?? '').split('?')[0] ?? '';
return execFileSync('psql', [
databaseUrl,
'-Atc',
- `select rp.id from reset_password rp join accounts a on a.id = rp."accountId" join users u on u.id = a."userId" where u.email = '${email}'`,
+ `select substring(v.identifier from length('reset-password:') + 1) from verifications v join users u on u.id = v.value where u.email = '${email}' and v.identifier like 'reset-password:%' order by v."createdAt" desc limit 1`,
])
.toString()
.trim();
@@ -128,7 +133,7 @@ test('sign-up validates every field before it calls the API', async ({
const issues = watchIssues(page);
let signUpRequests = 0;
page.on('request', (request) => {
- if (request.url().includes('/trpc/auth.signUpEmail')) {
+ if (request.url().includes('/api/auth/sign-up/email')) {
signUpRequests += 1;
}
});
@@ -176,7 +181,9 @@ test('sign up creates the account and opens the project step', async ({
// No organization yet: `/` forwards to the project step.
await expect(page).toHaveURL(/\/onboarding\/project$/, { timeout: 20_000 });
const cookies = await context.cookies();
- expect(cookies.find((cookie) => cookie.name === 'session')).toMatchObject({
+ expect(
+ cookies.find((cookie) => cookie.name === SESSION_COOKIE)
+ ).toMatchObject({
httpOnly: true,
secure: true,
sameSite: 'Lax',
@@ -623,8 +630,20 @@ test('email preferences save per category and survive a reload', async ({
expect(issues.unexpected()).toEqual([]);
});
-// A wrong code must not be a 401: the dashboard treats every 401 as "session
-// gone" and hard-navigates to /login.
+/** Opens the setup modal and gets past its password step. */
+async function startTwoFactorSetup(page: Page, password: string) {
+ await page.getByRole('button', { name: 'Enable' }).click();
+ const dialog = page.getByRole('dialog');
+ await dialog.getByPlaceholder('Your password').fill(password);
+ await dialog.getByRole('button', { name: 'Continue' }).click();
+ await expect(dialog.getByAltText('Authenticator QR code')).toBeVisible();
+ const secret = (await dialog.innerText()).match(TOTP_SECRET_PATTERN)?.[0];
+ if (!secret) {
+ throw new Error('The setup modal did not show a secret to type manually.');
+ }
+ return { dialog, secret };
+}
+
test('a mistyped code while enabling two-factor keeps the setup open', async ({
page,
context,
@@ -632,14 +651,10 @@ test('a mistyped code while enabling two-factor keeps the setup open', async ({
}) => {
const state = await continueAsUser(context, baseURL);
await gotoHydrated(page, `/${state.organizationId}/account/two-factor`);
- await page.getByRole('button', { name: 'Enable' }).click();
- const dialog = page.getByRole('dialog');
- await expect(dialog.getByAltText('Authenticator QR code')).toBeVisible();
- const secret =
- (await dialog.innerText()).match(TOTP_SECRET_PATTERN)?.[0] ?? '';
+ const { dialog, secret } = await startTwoFactorSetup(page, state.password);
await otpInput(dialog).fill(wrongTotpCode(secret));
await dialog.getByRole('button', { name: 'Enable' }).click();
- await expect(toast(page, 'Invalid code')).toBeVisible();
+ await expect(toast(page, /invalid/i)).toBeVisible();
await expect(dialog.getByAltText('Authenticator QR code')).toBeVisible();
await expect(page).toHaveURL(/\/account\/two-factor$/);
});
@@ -658,15 +673,9 @@ test('two-factor can be enabled and its recovery codes regenerated', async ({
page.getByText('Two-factor authentication is disabled.')
).toBeVisible();
- await page.getByRole('button', { name: 'Enable' }).click();
- const dialog = page.getByRole('dialog');
- await expect(dialog.getByAltText('Authenticator QR code')).toBeVisible();
+ const { dialog, secret } = await startTwoFactorSetup(page, state.password);
const enable = dialog.getByRole('button', { name: 'Enable' });
await expect(enable).toBeDisabled();
- const secret = (await dialog.innerText()).match(TOTP_SECRET_PATTERN)?.[0];
- if (!secret) {
- throw new Error('The setup modal did not show a secret to type manually.');
- }
await page.screenshot({ path: `${SHOTS_DIR}/two-factor-setup.png` });
await otpInput(dialog).fill(totpCode(secret));
@@ -684,14 +693,13 @@ test('two-factor can be enabled and its recovery codes regenerated', async ({
await expect(
page.getByText('Two-factor authentication is enabled.')
).toBeVisible();
- await expect(
- page.getByText(`${RECOVERY_CODE_COUNT} recovery codes remaining`)
- ).toBeVisible();
+ // Enabling issues a new session; keep the one later tests continue with.
+ await rememberCookies(context);
await page.getByRole('button', { name: 'Regenerate recovery codes' }).click();
const regenerate = dialog.getByRole('button', { name: 'Regenerate' });
await expect(regenerate).toBeDisabled();
- await otpInput(dialog).fill(totpCode(secret));
+ await dialog.getByPlaceholder('Your password').fill(state.password);
await regenerate.click();
await expect(dialog.getByText('New recovery codes')).toBeVisible();
const newCodes =
@@ -705,8 +713,6 @@ test('two-factor can be enabled and its recovery codes regenerated', async ({
expect(issues.unexpected()).toEqual([]);
});
-// The same on /verify: a 401 would send the visitor back to /login without
-// ever showing "Invalid code".
test('a mistyped code on /verify says so and lets the visitor try again', async ({
page,
}) => {
@@ -717,7 +723,7 @@ test('a mistyped code on /verify says so and lets the visitor try again', async
await expect(page).toHaveURL(/\/verify$/);
await waitForHydration(page);
await otpInput(page).fill(wrongTotpCode(state.totpSecret ?? ''));
- await expect(toast(page, 'Invalid code')).toBeVisible();
+ await expect(toast(page, /invalid/i)).toBeVisible();
await expect(page).toHaveURL(/\/verify$/);
});
@@ -745,7 +751,7 @@ test('signing in asks for the authenticator code', async ({
await expect(page).toHaveURL(/\/verify$/);
// The password alone is not a session.
expect((await context.cookies()).map((cookie) => cookie.name)).not.toContain(
- 'session'
+ SESSION_COOKIE
);
await page.goto(`/${state.organizationId}`);
await expect(page).toHaveURL(/\/login$/);
@@ -755,7 +761,7 @@ test('signing in asks for the authenticator code', async ({
await page
.getByRole('button', { name: 'Use a recovery code instead' })
.click();
- await expect(page.getByPlaceholder('ABCDE-FGHIJ')).toBeVisible();
+ await expect(page.getByPlaceholder(RECOVERY_PLACEHOLDER)).toBeVisible();
await page
.getByRole('button', { name: 'Use authenticator app instead' })
.click();
@@ -765,14 +771,15 @@ test('signing in asks for the authenticator code', async ({
timeout: 20_000,
});
expect((await context.cookies()).map((cookie) => cookie.name)).toContain(
- 'session'
+ SESSION_COOKIE
);
- expect(issues.unexpected()).toEqual([]);
+ expect(issues.unexpected([/two-factor\/verify/])).toEqual([]);
});
test('a recovery code signs in once and is then used up', async ({
page,
context,
+ request,
}) => {
const state = readState();
const recoveryCode = state.recoveryCodes?.[0];
@@ -785,31 +792,28 @@ test('a recovery code signs in once and is then used up', async ({
await page
.getByRole('button', { name: 'Use a recovery code instead' })
.click();
- // Typed in lower case: codes are case-insensitive.
- await page
- .getByPlaceholder('ABCDE-FGHIJ')
- .fill((recoveryCode ?? '').toLowerCase());
- await page.getByPlaceholder('ABCDE-FGHIJ').press('Enter');
+ await page.getByPlaceholder(RECOVERY_PLACEHOLDER).fill(recoveryCode ?? '');
+ await page.getByPlaceholder(RECOVERY_PLACEHOLDER).press('Enter');
await expect(page).toHaveURL(new RegExp(`/${state.organizationId}$`), {
timeout: 20_000,
});
await rememberCookies(context);
- await page.goto(`/${state.organizationId}/account/two-factor`);
- await expect(
- page.getByText(`${RECOVERY_CODE_COUNT - 1} recovery codes remaining`)
- ).toBeVisible();
-
- // The same code is refused the second time.
- const reuse = await page.request.post(`${apiUrl()}/trpc/auth.totpDisable`, {
- data: { json: { code: recoveryCode } },
+ // The same code is refused the second time, on a fresh password sign-in.
+ await waitForSignInSlot();
+ const signIn = await authPost(request, '/sign-in/email', {
+ email: state.email,
+ password: state.password,
});
- expect(reuse.status()).toBe(400);
- expect((await reuse.json()).error.json.message).toBe('Invalid code');
+ expect((await signIn.json()).twoFactorRedirect).toBe(true);
+ const reuse = await authPost(request, '/two-factor/verify-backup-code', {
+ code: recoveryCode,
+ });
+ expect(reuse.status()).toBeGreaterThanOrEqual(400);
expect(issues.unexpected()).toEqual([]);
});
-test('two-factor can be disabled with an authenticator code', async ({
+test('two-factor can be disabled with the password', async ({
page,
context,
baseURL,
@@ -826,20 +830,20 @@ test('two-factor can be disabled with an authenticator code', async ({
await expect(dialog).toBeHidden();
await page.getByRole('button', { name: 'Disable' }).click();
- await dialog
- .getByPlaceholder('123456 or ABCDE-FGHIJ')
- .fill(totpCode(state.totpSecret ?? ''));
+ await dialog.getByPlaceholder('Your password').fill(state.password);
await disable.click();
await expect(toast(page, 'Two-factor authentication disabled')).toBeVisible();
await expect(
page.getByText('Two-factor authentication is disabled.')
).toBeVisible();
writeState({ totpSecret: undefined, recoveryCodes: undefined });
+ await rememberCookies(context);
expect(issues.unexpected()).toEqual([]);
});
test('a reset link sets a new password and works only once', async ({
page,
+ request,
}) => {
test.skip(
!canReadDatabase(),
@@ -860,7 +864,7 @@ test('a reset link sets a new password and works only once', async ({
).toBeVisible();
const token = resetTokenFor(state.email);
- expect(token).toMatch(/^pw_/);
+ expect(token.length).toBeGreaterThan(0);
const newPassword = `pw-${RUN_ID}-second`;
await gotoHydrated(page, `/reset-password?token=${token}`);
await page.getByLabel('New password').fill(newPassword);
@@ -879,10 +883,11 @@ test('a reset link sets a new password and works only once', async ({
timeout: 20_000,
});
- const reuse = await page.request.post(`${apiUrl()}/trpc/auth.resetPassword`, {
- data: { json: { token, password: 'yet-another-password' } },
+ const reuse = await authPost(request, '/reset-password', {
+ token,
+ newPassword: 'yet-another-password',
});
- expect(reuse.status()).toBe(404);
+ expect(reuse.status()).toBe(400);
expect(issues.unexpected()).toEqual([]);
});
@@ -895,7 +900,7 @@ test('deleting the account needs the typed confirmation and ends the session', a
const state = await continueAsUser(context, baseURL);
const issues = watchIssues(page);
const sessionCookie = state.cookies.find(
- (cookie) => cookie.name === 'session'
+ (cookie) => cookie.name === SESSION_COOKIE
);
try {
await page.setViewportSize(DESKTOP_VIEWPORT);
@@ -920,13 +925,13 @@ test('deleting the account needs the typed confirmation and ends the session', a
// Never leave the throwaway user behind when the modal is what broke.
await request.post(`${apiUrl()}/trpc/user.delete`, {
data: {},
- headers: { cookie: `session=${sessionCookie?.value}` },
+ headers: { cookie: `${SESSION_COOKIE}=${sessionCookie?.value}` },
});
}
}
const session = await request.get(`${apiUrl()}/trpc/auth.session`, {
- headers: { cookie: `session=${sessionCookie?.value}` },
+ headers: { cookie: `${SESSION_COOKIE}=${sessionCookie?.value}` },
});
expect((await session.json()).result.data.json.userId).toBeNull();
expect(issues.unexpected()).toEqual([]);
diff --git a/apps/start/e2e/auth-recovery.spec.ts b/apps/start/e2e/auth-recovery.spec.ts
index 2e3bff302..6c87d0ac0 100644
--- a/apps/start/e2e/auth-recovery.spec.ts
+++ b/apps/start/e2e/auth-recovery.spec.ts
@@ -15,7 +15,7 @@ test.use({ storageState: FRESH_CONTEXT });
// The dev server hydrates slowly when several suites share it.
test.describe.configure({ timeout: 90_000 });
-const RESET_REQUEST = '/trpc/auth.resetPassword';
+const RESET_REQUEST = '/api/auth/reset-password';
const UNKNOWN_TOKEN = 'pw_e2e-does-not-exist';
test('the forgot password modal validates and answers the same for an unknown email', async ({
@@ -37,7 +37,7 @@ test('the forgot password modal validates and answers the same for an unknown em
await email.fill('not-an-email');
await dialog.getByRole('button', { name: 'Continue' }).click();
- await expect(dialog.getByText('Issues')).toBeVisible();
+ await expect(dialog.getByText('Invalid email address')).toBeVisible();
await page.screenshot({ path: `${SHOTS_DIR}/forgot-password-invalid.png` });
await dialog.getByRole('button', { name: 'Cancel' }).click();
@@ -82,14 +82,12 @@ test('/reset-password refuses an unknown token and keeps the visitor on the page
response.url().includes(RESET_REQUEST)
);
await page.getByLabel('New password').press('Enter');
- expect((await answer).status()).toBe(404);
- await expect(toast(page, 'Reset password not found')).toBeVisible();
+ expect((await answer).status()).toBe(400);
+ await expect(toast(page, /invalid token/i)).toBeVisible();
await expect(page).toHaveURL(/\/reset-password\?token=/);
- expect(issues.unexpected([/auth\.resetPassword/])).toEqual([]);
+ expect(issues.unexpected([/api\/auth\/reset-password/])).toEqual([]);
});
-// Open defect: the password input is rendered without the `error` prop, so a
-// too-short password makes the button do nothing.
test('/reset-password tells the visitor when the new password is too short', async ({
page,
}) => {
@@ -102,8 +100,8 @@ test('/reset-password tells the visitor when the new password is too short', asy
await gotoHydrated(page, `/reset-password?token=${UNKNOWN_TOKEN}`);
await page.getByLabel('New password').fill('short');
await page.getByRole('button', { name: 'Reset password' }).click();
+ await expect(page.getByText('Use at least 8 characters')).toBeVisible();
expect(resetRequests).toBe(0);
- await expect(page.getByText('Issues')).toBeVisible();
});
test('/unsubscribe with missing or malformed parameters shows a friendly page', async ({
diff --git a/apps/start/e2e/auth-session.spec.ts b/apps/start/e2e/auth-session.spec.ts
index a6027aee3..6314dd544 100644
--- a/apps/start/e2e/auth-session.spec.ts
+++ b/apps/start/e2e/auth-session.spec.ts
@@ -3,9 +3,11 @@
import {
apiUrl,
+ authPost,
FRESH_CONTEXT,
gotoHydrated,
SHOTS_DIR,
+ signUpWithEmail,
submitSignIn,
waitForSignInSlot,
} from './auth-helpers';
@@ -74,21 +76,13 @@ test('a password with a trailing space signs in after signing up with it', async
}) => {
const email = `e2e-auth-space-${Date.now()}@example.com`;
const password = 'spaced-password-1 ';
- const signUp = await request.post(`${apiUrl()}/trpc/auth.signUpEmail`, {
- data: {
- json: {
- firstName: 'E2E',
- lastName: 'Auth',
- email,
- password,
- },
- },
- });
+ const signUp = await signUpWithEmail(request, { email, password });
expect(signUp.status()).toBe(200);
try {
await waitForSignInSlot();
- const signIn = await request.post(`${apiUrl()}/trpc/auth.signInEmail`, {
- data: { json: { email, password } },
+ const signIn = await authPost(request, '/sign-in/email', {
+ email,
+ password,
});
expect(signIn.status()).toBe(200);
} finally {
@@ -100,8 +94,6 @@ test('a password with a trailing space signs in after signing up with it', async
}
});
-// Sign-in still issues the legacy `session` cookie; the first request after it
-// hands out better-auth's, which must keep the user signed in on its own.
test("a signed-in browser gets better-auth's cookie and stays signed in on it alone", async ({
page,
context,
diff --git a/apps/start/e2e/settings-access.spec.ts b/apps/start/e2e/settings-access.spec.ts
index e9a8e7843..3cb298226 100644
--- a/apps/start/e2e/settings-access.spec.ts
+++ b/apps/start/e2e/settings-access.spec.ts
@@ -1,4 +1,5 @@
import type { APIRequestContext } from '@playwright/test';
+import { signUpWithEmail } from './auth-helpers';
import { expect, test } from './fixtures';
import {
anonymousApi,
@@ -90,13 +91,13 @@ test.beforeAll(async ({ seed }) => {
project = await createThrowawayProject(admin, organizationId, 'access');
// A real account that is not a member of the seeded organization.
- const signedUp = await trpcMutation(outsider, 'auth.signUpEmail', {
+ const signedUp = await signUpWithEmail(outsider, {
firstName: 'E2E',
lastName: 'Outsider',
email: `e2e-settings-outsider-${Date.now()}@openpanel.local`,
password: OUTSIDER_PASSWORD,
});
- expect(signedUp.status, signedUp.errorMessage).toBe(200);
+ expect(signedUp.status(), await signedUp.text()).toBe(200);
});
test.afterAll(async () => {
diff --git a/apps/start/e2e/sweep-failures.spec.ts b/apps/start/e2e/sweep-failures.spec.ts
index d52c4e789..4808c3edd 100644
--- a/apps/start/e2e/sweep-failures.spec.ts
+++ b/apps/start/e2e/sweep-failures.spec.ts
@@ -208,9 +208,6 @@ test.describe('failed and slow api calls', () => {
if (route.request().method() !== 'POST') {
return route.continue();
}
- if (route.request().url().includes('auth.extendSession')) {
- return route.continue();
- }
intercepted++;
return failWith500(route);
});
diff --git a/apps/start/e2e/verify-a-org.spec.ts b/apps/start/e2e/verify-a-org.spec.ts
index 0506fc3cf..0822237f3 100644
--- a/apps/start/e2e/verify-a-org.spec.ts
+++ b/apps/start/e2e/verify-a-org.spec.ts
@@ -1,4 +1,5 @@
import { request as playwrightRequest } from '@playwright/test';
+import { signUpWithEmail } from './auth-helpers';
import { expect, test } from './fixtures';
import {
API_URL,
@@ -22,12 +23,13 @@ test('cancelling an organization deletion keeps a project that was already sched
ignoreHTTPSErrors: true,
baseURL: API_URL,
});
- await trpcMutation(owner, 'auth.signUpEmail', {
+ const signedUp = await signUpWithEmail(owner, {
firstName: 'E2E',
lastName: 'VerifyA',
email: `e2e-verify-a-${stamp}@example.com`,
password: PASSWORD,
});
+ expect(signedUp.status()).toBe(200);
const project = {
domain: null,
cors: [],
diff --git a/apps/start/package.json b/apps/start/package.json
index a78493f89..c24aea932 100644
--- a/apps/start/package.json
+++ b/apps/start/package.json
@@ -100,6 +100,7 @@
"@visx/shape": "4.0.1-alpha.0",
"@visx/zoom": "4.0.1-alpha.0",
"ai": "7.0.144",
+ "better-auth": "1.7.10",
"bind-event-listener": "3.0.0",
"class-variance-authority": "0.7.1",
"clsx": "2.1.1",
@@ -133,6 +134,7 @@
"nuqs": "2.5.2",
"prisma-error-enum": "0.1.3",
"pushmodal": "1.0.3",
+ "qrcode": "1.5.4",
"ramda": "0.29.1",
"random-animal-name": "0.1.1",
"rc-virtual-list": "3.14.5",
@@ -192,6 +194,7 @@
"@types/lodash.debounce": "4.0.9",
"@types/lodash.isequal": "4.5.8",
"@types/lodash.throttle": "4.1.9",
+ "@types/qrcode": "1.5.6",
"@types/ramda": "0.31.0",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
diff --git a/apps/start/src/components/auth/reset-password-form.tsx b/apps/start/src/components/auth/reset-password-form.tsx
index 67ceab64f..d5af63a3e 100644
--- a/apps/start/src/components/auth/reset-password-form.tsx
+++ b/apps/start/src/components/auth/reset-password-form.tsx
@@ -8,27 +8,27 @@ import type { z } from 'zod';
import { Button } from '../ui/button';
import { AuthHeading } from './auth-shell';
import { PasswordInput } from './password-input';
-import { useTRPC } from '@/integrations/trpc/react';
+import { unwrap, useAuthClient } from '@/integrations/auth/client';
const validator = zResetPassword;
type IForm = z.infer<typeof validator>;
export function ResetPasswordForm({ token }: { token: string }) {
const navigate = useNavigate();
- const trpc = useTRPC();
- const mutation = useMutation(
- trpc.auth.resetPassword.mutationOptions({
- onSuccess() {
- toast.success('Password reset successfully');
- navigate({
- to: '/login',
- });
- },
- onError(error) {
- toast.error(error.message);
- },
- })
- );
+ const authClient = useAuthClient();
+ const mutation = useMutation({
+ mutationFn: ({ token, password }: IForm) =>
+ unwrap(authClient.resetPassword({ token, newPassword: password })),
+ onSuccess() {
+ toast.success('Password reset successfully');
+ navigate({
+ to: '/login',
+ });
+ },
+ onError(error) {
+ toast.error(error.message);
+ },
+ });
const form = useForm<IForm>({
resolver: zodResolver(validator),
diff --git a/apps/start/src/components/auth/sign-in-dev.tsx b/apps/start/src/components/auth/sign-in-dev.tsx
index fb8ba6bb0..38c1291d8 100644
--- a/apps/start/src/components/auth/sign-in-dev.tsx
+++ b/apps/start/src/components/auth/sign-in-dev.tsx
@@ -10,7 +10,7 @@ export function SignInDev({ inviteId }: { inviteId?: string }) {
const mutation = useMutation(
trpc.auth.signInDev.mutationOptions({
onSuccess(data) {
- if (data.type === 'totp_required') {
+ if (data.type === 'two_factor') {
window.location.href = '/verify';
return;
}
diff --git a/apps/start/src/components/auth/sign-in-email-form.tsx b/apps/start/src/components/auth/sign-in-email-form.tsx
index ab2d2956c..4866a9046 100644
--- a/apps/start/src/components/auth/sign-in-email-form.tsx
+++ b/apps/start/src/components/auth/sign-in-email-form.tsx
@@ -1,5 +1,8 @@
import { zodResolver } from '@hookform/resolvers/zod';
-import { zSignInEmail } from '@openpanel/core/modules/auth/auth.constants';
+import {
+ INVITE_HEADER,
+ zSignInEmail,
+} from '@openpanel/core/modules/auth/auth.constants';
import { useMutation } from '@tanstack/react-query';
import {
type SubmitErrorHandler,
@@ -12,7 +15,7 @@ import { InputWithLabel } from '../forms/input-with-label';
import { Button } from '../ui/button';
import { LastUsedBadge } from './last-used-badge';
import { PasswordInput } from './password-input';
-import { useTRPC } from '@/integrations/trpc/react';
+import { unwrap, useAuthClient } from '@/integrations/auth/client';
import { pushModal } from '@/modals';
import { failureReason, trackFunnel } from '@/utils/funnel-tracking';
@@ -26,30 +29,32 @@ export function SignInEmailForm({
isLastUsed?: boolean;
inviteId?: string;
}) {
- const trpc = useTRPC();
- const mutation = useMutation(
- trpc.auth.signInEmail.mutationOptions({
- async onSuccess(data) {
- trackFunnel('auth_signin_succeeded', {
- provider: 'email',
- totpRequired: data.type === 'totp_required',
- });
- if (data.type === 'totp_required') {
- window.location.href = '/verify';
- return;
- }
- toast.success('Successfully signed in');
- window.location.href = '/';
- },
- onError(error) {
- trackFunnel('auth_signin_failed', {
- provider: 'email',
- reason: failureReason(error),
- });
- toast.error(error.message);
- },
- })
- );
+ const authClient = useAuthClient();
+ const mutation = useMutation({
+ mutationFn: (values: IForm) =>
+ unwrap(
+ authClient.signIn.email(values, {
+ headers: inviteId ? { [INVITE_HEADER]: inviteId } : undefined,
+ })
+ ),
+ onSuccess(data) {
+ const totpRequired = 'twoFactorRedirect' in data;
+ trackFunnel('auth_signin_succeeded', { provider: 'email', totpRequired });
+ if (totpRequired) {
+ window.location.href = '/verify';
+ return;
+ }
+ toast.success('Successfully signed in');
+ window.location.href = '/';
+ },
+ onError(error) {
+ trackFunnel('auth_signin_failed', {
+ provider: 'email',
+ reason: failureReason(error),
+ });
+ toast.error(error.message);
+ },
+ });
const form = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
@@ -63,10 +68,7 @@ export function SignInEmailForm({
provider: 'email',
isLastUsed: Boolean(isLastUsed),
});
- mutation.mutate({
- ...values,
- inviteId,
- });
+ mutation.mutate(values);
};
const onInvalid: SubmitErrorHandler<IForm> = (errors) => {
trackFunnel('auth_form_invalid', {
diff --git a/apps/start/src/components/auth/sign-in-oauth.tsx b/apps/start/src/components/auth/sign-in-oauth.tsx
index 8cdf6941e..cc7f34966 100644
--- a/apps/start/src/components/auth/sign-in-oauth.tsx
+++ b/apps/start/src/components/auth/sign-in-oauth.tsx
@@ -2,7 +2,8 @@ import { useMutation } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Button } from '../ui/button';
import { LastUsedBadge } from './last-used-badge';
-import { useTRPC } from '@/integrations/trpc/react';
+import { useAppContext } from '@/hooks/use-app-context';
+import { unwrap, useAuthClient } from '@/integrations/auth/client';
import { failureReason, trackFunnel } from '@/utils/funnel-tracking';
export type OAuthProvider = 'google' | 'github';
@@ -65,23 +66,27 @@ export function SignInOAuth({
inviteId?: string;
isLastUsed?: boolean;
}) {
- const trpc = useTRPC();
- const mutation = useMutation(
- trpc.auth.signInOAuth.mutationOptions({
- onSuccess(res) {
- if (res.url) {
- window.location.href = res.url;
- }
- },
- onError(error) {
- trackFunnel(
- type === 'sign-in' ? 'auth_signin_failed' : 'auth_signup_failed',
- { provider, reason: failureReason(error) }
- );
- toast.error(error.message);
- },
- })
- );
+ const authClient = useAuthClient();
+ const { dashboardUrl } = useAppContext();
+ const mutation = useMutation({
+ // better-auth sends the browser to the provider itself.
+ mutationFn: () =>
+ unwrap(
+ authClient.signIn.social({
+ provider,
+ callbackURL: dashboardUrl,
+ errorCallbackURL: `${dashboardUrl}/login`,
+ additionalData: inviteId ? { inviteId } : undefined,
+ })
+ ),
+ onError(error) {
+ trackFunnel(
+ type === 'sign-in' ? 'auth_signin_failed' : 'auth_signup_failed',
+ { provider, reason: failureReason(error) }
+ );
+ toast.error(error.message);
+ },
+ });
const verb = type === 'sign-in' ? 'Sign in' : 'Sign up';
return (
<div className="relative">
@@ -94,7 +99,7 @@ export function SignInOAuth({
provider,
isLastUsed: Boolean(isLastUsed),
});
- mutation.mutate({ provider, inviteId });
+ mutation.mutate();
}}
size="xl"
variant="outline"
diff --git a/apps/start/src/components/auth/sign-up-email-form.tsx b/apps/start/src/components/auth/sign-up-email-form.tsx
index c391e3760..603814373 100644
--- a/apps/start/src/components/auth/sign-up-email-form.tsx
+++ b/apps/start/src/components/auth/sign-up-email-form.tsx
@@ -1,5 +1,8 @@
import { zodResolver } from '@hookform/resolvers/zod';
-import { zSignUpEmail } from '@openpanel/core/modules/auth/auth.constants';
+import {
+ INVITE_HEADER,
+ zSignUpEmail,
+} from '@openpanel/core/modules/auth/auth.constants';
import { useMutation } from '@tanstack/react-query';
import {
type SubmitErrorHandler,
@@ -11,7 +14,7 @@ import type { z } from 'zod';
import { InputWithLabel } from '../forms/input-with-label';
import { Button } from '../ui/button';
import { PasswordInput } from './password-input';
-import { useTRPC } from '@/integrations/trpc/react';
+import { unwrap, useAuthClient } from '@/integrations/auth/client';
import { failureReason, trackFunnel } from '@/utils/funnel-tracking';
const validator = zSignUpEmail;
@@ -22,35 +25,43 @@ export function SignUpEmailForm({
}: {
inviteId: string | undefined;
}) {
- const trpc = useTRPC();
- const mutation = useMutation(
- trpc.auth.signUpEmail.mutationOptions({
- async onSuccess() {
- trackFunnel('auth_signup_succeeded', {
- provider: 'email',
- hasInvite: Boolean(inviteId),
- });
- toast.success('Successfully signed up');
- window.location.href = '/';
- },
- onError(error) {
- trackFunnel('auth_signup_failed', {
- provider: 'email',
- reason: failureReason(error),
- });
- toast.error(error.message);
- },
- })
- );
+ const authClient = useAuthClient();
+ const mutation = useMutation({
+ mutationFn: ({ firstName, lastName, email, password }: IForm) =>
+ unwrap(
+ authClient.signUp.email(
+ {
+ email,
+ password,
+ name: `${firstName} ${lastName}`,
+ firstName,
+ lastName,
+ },
+ { headers: inviteId ? { [INVITE_HEADER]: inviteId } : undefined }
+ )
+ ),
+ onSuccess() {
+ trackFunnel('auth_signup_succeeded', {
+ provider: 'email',
+ hasInvite: Boolean(inviteId),
+ });
+ toast.success('Successfully signed up');
+ window.location.href = '/';
+ },
+ onError(error) {
+ trackFunnel('auth_signup_failed', {
+ provider: 'email',
+ reason: failureReason(error),
+ });
+ toast.error(error.message);
+ },
+ });
const form = useForm<IForm>({
resolver: zodResolver(validator),
});
const onSubmit: SubmitHandler<IForm> = (values) => {
trackFunnel('auth_provider_clicked', { page: 'signup', provider: 'email' });
- mutation.mutate({
- ...values,
- inviteId,
- });
+ mutation.mutate(values);
};
const onInvalid: SubmitErrorHandler<IForm> = (errors) => {
trackFunnel('auth_form_invalid', {
diff --git a/apps/start/src/hooks/use-session-extension.ts b/apps/start/src/hooks/use-session-extension.ts
deleted file mode 100644
index 92e74b2e9..000000000
--- a/apps/start/src/hooks/use-session-extension.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { useMutation } from '@tanstack/react-query';
-import { useRouteContext } from '@tanstack/react-router';
-import { useEffect, useRef } from 'react';
-import { useTRPC } from '@/integrations/trpc/react';
-
-export function useSessionExtension() {
- const trpc = useTRPC();
- const context = useRouteContext({
- from: '__root__',
- });
- const extendMutation = useMutation(trpc.auth.extendSession.mutationOptions());
- const intervalRef = useRef<NodeJS.Timeout>(null);
- const session = context.session?.session;
-
- useEffect(() => {
- if (!session) {
- return;
- }
-
- const extendSessionFn = () => extendMutation.mutate();
-
- intervalRef.current = setInterval(
- () => {
- extendMutation.mutate();
- },
- 1000 * 60 * 5
- );
-
- // Delay initial call a bit to prioritize other requests
- const timer = setTimeout(() => extendSessionFn(), 5000);
-
- return () => {
- clearTimeout(timer);
- if (intervalRef.current) {
- clearInterval(intervalRef.current);
- }
- };
- }, [session]);
-}
diff --git a/apps/start/src/integrations/auth/client.ts b/apps/start/src/integrations/auth/client.ts
new file mode 100644
index 000000000..b97c83000
--- /dev/null
+++ b/apps/start/src/integrations/auth/client.ts
@@ -0,0 +1,49 @@
+import {
+ inferAdditionalFields,
+ twoFactorClient,
+} from 'better-auth/client/plugins';
+import { createAuthClient } from 'better-auth/react';
+import { useMemo } from 'react';
+import { useAppContext } from '@/hooks/use-app-context';
+
+const AUTH_PATH = '/api/auth';
+
+function createDashboardAuthClient(apiUrl: string) {
+ return createAuthClient({
+ baseURL: `${apiUrl}${AUTH_PATH}`,
+ fetchOptions: { credentials: 'include' },
+ plugins: [
+ twoFactorClient(),
+ inferAdditionalFields({
+ user: {
+ firstName: { type: 'string', required: false },
+ lastName: { type: 'string', required: false },
+ },
+ }),
+ ],
+ });
+}
+
+export type AuthClient = ReturnType<typeof createDashboardAuthClient>;
+
+export function useAuthClient(): AuthClient {
+ const { apiUrl } = useAppContext();
+ return useMemo(() => createDashboardAuthClient(apiUrl), [apiUrl]);
+}
+
+interface AuthResult<T> {
+ data: T | null;
+ error: { message?: string; code?: string } | null;
+}
+
+/** better-auth answers `{ data, error }`; react-query wants a throw. */
+export async function unwrap<T>(request: Promise<AuthResult<T>>): Promise<T> {
+ const { data, error } = await request;
+ if (error) {
+ throw new Error(error.message || error.code || 'Something went wrong');
+ }
+ if (data === null) {
+ throw new Error('Something went wrong');
+ }
+ return data;
+}
diff --git a/apps/start/src/modals/disable-two-factor.tsx b/apps/start/src/modals/disable-two-factor.tsx
index 2a8c4d3ab..53cc4ae08 100644
--- a/apps/start/src/modals/disable-two-factor.tsx
+++ b/apps/start/src/modals/disable-two-factor.tsx
@@ -6,48 +6,51 @@ import { ModalContent, ModalHeader } from './Modal/Container';
import { Button } from '@/components/ui/button';
import { DialogFooter } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
+import { unwrap, useAuthClient } from '@/integrations/auth/client';
import { useTRPC } from '@/integrations/trpc/react';
export default function DisableTwoFactor() {
const trpc = useTRPC();
+ const authClient = useAuthClient();
const queryClient = useQueryClient();
- const [code, setCode] = useState('');
+ const [password, setPassword] = useState('');
- const mutation = useMutation(
- trpc.auth.totpDisable.mutationOptions({
- onSuccess: () => {
- toast.success('Two-factor authentication disabled');
- queryClient.invalidateQueries(trpc.auth.totpStatus.pathFilter());
- popModal();
- },
- onError: (error) => {
- toast.error(error.message);
- setCode('');
- },
- })
- );
+ const mutation = useMutation({
+ mutationFn: () => unwrap(authClient.twoFactor.disable({ password })),
+ onSuccess: () => {
+ toast.success('Two-factor authentication disabled');
+ queryClient.invalidateQueries(trpc.auth.twoFactorStatus.pathFilter());
+ popModal();
+ },
+ onError: (error) => {
+ toast.error(error.message);
+ setPassword('');
+ },
+ });
return (
<ModalContent>
<ModalHeader
- text="Enter a code from your authenticator app, or a recovery code, to confirm."
+ text="Enter your password to confirm."
title="Disable two-factor authentication"
/>
<Input
- autoCapitalize="characters"
+ aria-label="Password"
+ autoComplete="current-password"
autoFocus
- onChange={(e) => setCode(e.target.value)}
- placeholder="123456 or ABCDE-FGHIJ"
- value={code}
+ onChange={(e) => setPassword(e.target.value)}
+ placeholder="Your password"
+ type="password"
+ value={password}
/>
<DialogFooter>
<Button onClick={() => popModal()} variant="secondary">
Cancel
</Button>
<Button
- disabled={!code.trim()}
+ disabled={!password}
loading={mutation.isPending}
- onClick={() => mutation.mutate({ code })}
+ onClick={() => mutation.mutate()}
variant="destructive"
>
Disable
diff --git a/apps/start/src/modals/regenerate-recovery-codes.tsx b/apps/start/src/modals/regenerate-recovery-codes.tsx
index 5580362b0..d5c2b09c0 100644
--- a/apps/start/src/modals/regenerate-recovery-codes.tsx
+++ b/apps/start/src/modals/regenerate-recovery-codes.tsx
@@ -5,31 +5,29 @@ import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
import { Button } from '@/components/ui/button';
import { DialogFooter } from '@/components/ui/dialog';
-import {
- InputOTP,
- InputOTPGroup,
- InputOTPSlot,
-} from '@/components/ui/input-otp';
+import { Input } from '@/components/ui/input';
+import { unwrap, useAuthClient } from '@/integrations/auth/client';
import { useTRPC } from '@/integrations/trpc/react';
export default function RegenerateRecoveryCodes() {
const trpc = useTRPC();
+ const authClient = useAuthClient();
const queryClient = useQueryClient();
- const [code, setCode] = useState('');
+ const [password, setPassword] = useState('');
const [newCodes, setNewCodes] = useState<string[] | null>(null);
- const mutation = useMutation(
- trpc.auth.totpRegenerateRecoveryCodes.mutationOptions({
- onSuccess: (data) => {
- setNewCodes(data.recoveryCodes);
- queryClient.invalidateQueries(trpc.auth.totpStatus.pathFilter());
- },
- onError: (error) => {
- toast.error(error.message);
- setCode('');
- },
- })
- );
+ const mutation = useMutation({
+ mutationFn: () =>
+ unwrap(authClient.twoFactor.generateBackupCodes({ password })),
+ onSuccess: (data) => {
+ setNewCodes(data.backupCodes);
+ queryClient.invalidateQueries(trpc.auth.twoFactorStatus.pathFilter());
+ },
+ onError: (error) => {
+ toast.error(error.message);
+ setPassword('');
+ },
+ });
if (newCodes) {
return (
@@ -66,29 +64,26 @@ export default function RegenerateRecoveryCodes() {
return (
<ModalContent>
<ModalHeader
- text="Enter a code from your authenticator app to generate a fresh set of recovery codes."
+ text="Enter your password to generate a fresh set of recovery codes."
title="Regenerate recovery codes"
/>
- <div className="col items-center gap-2">
- <InputOTP maxLength={6} onChange={setCode} value={code}>
- <InputOTPGroup>
- <InputOTPSlot index={0} />
- <InputOTPSlot index={1} />
- <InputOTPSlot index={2} />
- <InputOTPSlot index={3} />
- <InputOTPSlot index={4} />
- <InputOTPSlot index={5} />
- </InputOTPGroup>
- </InputOTP>
- </div>
+ <Input
+ aria-label="Password"
+ autoComplete="current-password"
+ autoFocus
+ onChange={(e) => setPassword(e.target.value)}
+ placeholder="Your password"
+ type="password"
+ value={password}
+ />
<DialogFooter>
<Button onClick={() => popModal()} variant="secondary">
Cancel
</Button>
<Button
- disabled={code.length !== 6}
+ disabled={!password}
loading={mutation.isPending}
- onClick={() => mutation.mutate({ code })}
+ onClick={() => mutation.mutate()}
>
Regenerate
</Button>
diff --git a/apps/start/src/modals/request-reset-password.tsx b/apps/start/src/modals/request-reset-password.tsx
index 2b25d14e6..cd0f5f879 100644
--- a/apps/start/src/modals/request-reset-password.tsx
+++ b/apps/start/src/modals/request-reset-password.tsx
@@ -1,7 +1,6 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { zRequestResetPassword } from '@openpanel/core/modules/auth/auth.constants';
import { useMutation } from '@tanstack/react-query';
-import { useRouter } from '@tanstack/react-router';
import { SendIcon } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
@@ -11,38 +10,44 @@ import { ModalContent, ModalHeader } from './Modal/Container';
import { InputWithLabel } from '@/components/forms/input-with-label';
import { Button } from '@/components/ui/button';
import { DialogFooter } from '@/components/ui/dialog';
-import { handleError, useTRPC } from '@/integrations/trpc/react';
+import { useAppContext } from '@/hooks/use-app-context';
+import { unwrap, useAuthClient } from '@/integrations/auth/client';
const validation = zRequestResetPassword;
type IForm = z.infer<typeof validation>;
-type Props = {
+interface Props {
email?: string;
-};
+}
export default function RequestPasswordReset({ email }: Props) {
- const router = useRouter();
const form = useForm<IForm>({
resolver: zodResolver(validation),
defaultValues: {
email: email ?? '',
},
});
- const trpc = useTRPC();
- const mutation = useMutation(
- trpc.auth.requestResetPassword.mutationOptions({
- onSuccess() {
- toast.success('You should receive an email shortly!');
- popModal();
- },
- onError: handleError,
- })
- );
+ const authClient = useAuthClient();
+ const { dashboardUrl } = useAppContext();
+ const mutation = useMutation({
+ mutationFn: ({ email }: IForm) =>
+ unwrap(
+ authClient.requestPasswordReset({
+ email,
+ redirectTo: `${dashboardUrl}/reset-password`,
+ })
+ ),
+ onSuccess() {
+ toast.success('You should receive an email shortly!');
+ popModal();
+ },
+ onError(error) {
+ toast.error(error.message);
+ },
+ });
const onSubmit = form.handleSubmit((values) => {
- mutation.mutate({
- email: values.email,
- });
+ mutation.mutate(values);
});
return (
diff --git a/apps/start/src/modals/setup-two-factor.tsx b/apps/start/src/modals/setup-two-factor.tsx
index fd9edf811..f36202ba6 100644
--- a/apps/start/src/modals/setup-two-factor.tsx
+++ b/apps/start/src/modals/setup-two-factor.tsx
@@ -1,66 +1,91 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { DownloadIcon } from 'lucide-react';
-import { useEffect, useState } from 'react';
+import QRCode from 'qrcode';
+import { useState } from 'react';
import { toast } from 'sonner';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
import CopyInput from '@/components/forms/copy-input';
import { Button } from '@/components/ui/button';
import { DialogFooter } from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
import {
InputOTP,
InputOTPGroup,
InputOTPSlot,
} from '@/components/ui/input-otp';
import { Label } from '@/components/ui/label';
-import { handleError, useTRPC } from '@/integrations/trpc/react';
+import { unwrap, useAuthClient } from '@/integrations/auth/client';
+import { useTRPC } from '@/integrations/trpc/react';
+
+const QR_SIZE = 240;
+
+interface Enrollment {
+ qrDataUrl: string;
+ secret: string;
+ backupCodes: string[];
+}
+
+async function toEnrollment(
+ totpURI: string,
+ backupCodes: string[]
+): Promise<Enrollment> {
+ return {
+ qrDataUrl: await QRCode.toDataURL(totpURI, { margin: 1, width: QR_SIZE }),
+ secret: new URL(totpURI).searchParams.get('secret') ?? '',
+ backupCodes,
+ };
+}
export default function SetupTwoFactor() {
const trpc = useTRPC();
+ const authClient = useAuthClient();
const queryClient = useQueryClient();
- const [step, setStep] = useState<'scan' | 'recovery'>('scan');
- const [code, setCode] = useState('');
- const [setupData, setSetupData] = useState<{
- qrDataUrl: string;
- secret: string;
- } | null>(null);
- const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
-
- const setupMutation = useMutation(
- trpc.auth.totpSetup.mutationOptions({
- onSuccess: (data) => {
- setSetupData({ qrDataUrl: data.qrDataUrl, secret: data.secret });
- },
- onError: handleError,
- })
+ const [step, setStep] = useState<'password' | 'scan' | 'recovery'>(
+ 'password'
);
+ const [password, setPassword] = useState('');
+ const [code, setCode] = useState('');
+ const [enrollment, setEnrollment] = useState<Enrollment | null>(null);
- const enableMutation = useMutation(
- trpc.auth.totpEnable.mutationOptions({
- onSuccess: (data) => {
- setRecoveryCodes(data.recoveryCodes);
- setStep('recovery');
- queryClient.invalidateQueries(trpc.auth.totpStatus.pathFilter());
- },
- onError: (error) => {
- toast.error(error.message);
- setCode('');
- },
- })
- );
+ const enableMutation = useMutation({
+ mutationFn: async () => {
+ const data = await unwrap(authClient.twoFactor.enable({ password }));
+ if (data.method !== 'totp') {
+ throw new Error('Authenticator apps are not available');
+ }
+ return toEnrollment(data.totpURI, data.backupCodes);
+ },
+ onSuccess: (data) => {
+ setEnrollment(data);
+ setStep('scan');
+ },
+ onError: (error) => {
+ toast.error(error.message);
+ setPassword('');
+ },
+ });
- useEffect(() => {
- setupMutation.mutate();
- }, []);
+ const verifyMutation = useMutation({
+ mutationFn: () => unwrap(authClient.twoFactor.verifyTotp({ code })),
+ onSuccess: () => {
+ setStep('recovery');
+ queryClient.invalidateQueries(trpc.auth.twoFactorStatus.pathFilter());
+ },
+ onError: (error) => {
+ toast.error(error.message);
+ setCode('');
+ },
+ });
- if (step === 'recovery') {
+ if (step === 'recovery' && enrollment) {
return (
<ModalContent>
<ModalHeader
text="Store these somewhere safe. Each can be used once if you lose access to your authenticator. You won't see them again."
title="Save your recovery codes"
/>
- <RecoveryCodesBlock codes={recoveryCodes} />
+ <RecoveryCodesBlock codes={enrollment.backupCodes} />
<DialogFooter>
<Button onClick={() => popModal()}>I've saved my codes</Button>
</DialogFooter>
@@ -68,37 +93,30 @@ export default function SetupTwoFactor() {
);
}
- return (
- <ModalContent>
- <ModalHeader
- text="Scan the QR code with your authenticator app, then enter the 6-digit code to enable."
- title="Set up two-factor authentication"
- />
-
- {setupMutation.isPending || !setupData ? (
- <div className="center-center min-h-[260px]">
- <span className="text-muted-foreground text-sm">
- Generating secret…
- </span>
- </div>
- ) : (
+ if (step === 'scan' && enrollment) {
+ return (
+ <ModalContent>
+ <ModalHeader
+ text="Scan the QR code with your authenticator app, then enter the 6-digit code to enable."
+ title="Set up two-factor authentication"
+ />
<div className="col gap-4">
<img
alt="Authenticator QR code"
className="rounded-md border border-border"
- height={240}
- src={setupData.qrDataUrl}
- width={240}
+ height={QR_SIZE}
+ src={enrollment.qrDataUrl}
+ width={QR_SIZE}
/>
<CopyInput
className="w-full"
label="Can't scan? Enter this secret manually"
- value={setupData.secret}
+ value={enrollment.secret}
/>
<div className="col w-full gap-2">
<Label className="mb-1">Verification code</Label>
<InputOTP
- disabled={enableMutation.isPending}
+ disabled={verifyMutation.isPending}
maxLength={6}
onChange={setCode}
value={code}
@@ -114,18 +132,47 @@ export default function SetupTwoFactor() {
</InputOTP>
</div>
</div>
- )}
+ <DialogFooter>
+ <Button onClick={() => popModal()} variant="secondary">
+ Cancel
+ </Button>
+ <Button
+ disabled={code.length !== 6}
+ loading={verifyMutation.isPending}
+ onClick={() => verifyMutation.mutate()}
+ >
+ Enable
+ </Button>
+ </DialogFooter>
+ </ModalContent>
+ );
+ }
+ return (
+ <ModalContent>
+ <ModalHeader
+ text="Enter your password to start setting up an authenticator app."
+ title="Set up two-factor authentication"
+ />
+ <Input
+ aria-label="Password"
+ autoComplete="current-password"
+ autoFocus
+ onChange={(e) => setPassword(e.target.value)}
+ placeholder="Your password"
+ type="password"
+ value={password}
+ />
<DialogFooter>
<Button onClick={() => popModal()} variant="secondary">
Cancel
</Button>
<Button
- disabled={code.length !== 6}
+ disabled={!password}
loading={enableMutation.isPending}
- onClick={() => enableMutation.mutate({ code })}
+ onClick={() => enableMutation.mutate()}
>
- Enable
+ Continue
</Button>
</DialogFooter>
</ModalContent>
diff --git a/apps/start/src/routes/__root.tsx b/apps/start/src/routes/__root.tsx
index d6e3585ea..67b78c5cb 100644
--- a/apps/start/src/routes/__root.tsx
+++ b/apps/start/src/routes/__root.tsx
@@ -22,7 +22,6 @@ import { Providers } from '@/components/providers';
import { ThemeScriptOnce } from '@/components/theme-provider';
import { LinkButton } from '@/components/ui/button';
import { getCookiesFn } from '@/hooks/use-cookie-store';
-import { useSessionExtension } from '@/hooks/use-session-extension';
import type { RouterOutputs } from '@/trpc/client';
import { op } from '@/utils/op';
@@ -115,8 +114,6 @@ function OpIdentify() {
}
function RootDocument({ children }: { children: React.ReactNode }) {
- useSessionExtension();
-
return (
<html lang="en" suppressHydrationWarning>
<head>
diff --git a/apps/start/src/routes/_app.$organizationId.account._tabs.two-factor.tsx b/apps/start/src/routes/_app.$organizationId.account._tabs.two-factor.tsx
index 526d275de..e49c6d224 100644
--- a/apps/start/src/routes/_app.$organizationId.account._tabs.two-factor.tsx
+++ b/apps/start/src/routes/_app.$organizationId.account._tabs.two-factor.tsx
@@ -1,6 +1,6 @@
import { useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
-import { ShieldCheckIcon, ShieldOffIcon } from 'lucide-react';
+import { ShieldAlertIcon, ShieldCheckIcon, ShieldOffIcon } from 'lucide-react';
import FullPageLoadingState from '@/components/full-page-loading-state';
import { Button } from '@/components/ui/button';
import { Widget, WidgetBody, WidgetHead } from '@/components/widget';
@@ -16,7 +16,7 @@ export const Route = createFileRoute(
function Component() {
const trpc = useTRPC();
- const status = useSuspenseQuery(trpc.auth.totpStatus.queryOptions());
+ const status = useSuspenseQuery(trpc.auth.twoFactorStatus.queryOptions());
return (
<Widget className="w-full max-w-screen-md">
@@ -31,20 +31,26 @@ function Component() {
</p>
{status.data.enabled ? (
- <EnabledView
- enabledAt={status.data.enabledAt!}
- remainingRecoveryCodes={status.data.remainingRecoveryCodes}
- />
+ <EnabledView />
) : (
- <DisabledView hasEmailProvider={status.data.hasEmailProvider} />
+ <DisabledView
+ hasPassword={status.data.hasPassword}
+ wasReset={status.data.wasReset}
+ />
)}
</WidgetBody>
</Widget>
);
}
-function DisabledView({ hasEmailProvider }: { hasEmailProvider: boolean }) {
- if (!hasEmailProvider) {
+function DisabledView({
+ hasPassword,
+ wasReset,
+}: {
+ hasPassword: boolean;
+ wasReset: boolean;
+}) {
+ if (!hasPassword) {
return (
<div className="col gap-2 rounded-md border border-border bg-def-100 px-4 py-3 text-sm">
<div className="row items-center gap-2">
@@ -61,25 +67,35 @@ function DisabledView({ hasEmailProvider }: { hasEmailProvider: boolean }) {
}
return (
- <div className="row items-center justify-between rounded-md border border-border bg-def-100 px-4 py-3">
- <div className="row items-center gap-2 text-sm">
- <ShieldOffIcon className="size-4 text-muted-foreground" />
- <span>Two-factor authentication is disabled.</span>
+ <>
+ {wasReset && (
+ <div className="col gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm">
+ <div className="row items-center gap-2">
+ <ShieldAlertIcon className="size-4 text-amber-500" />
+ <span>Set up two-factor authentication again</span>
+ </div>
+ <p className="text-muted-foreground">
+ We moved sign-in to a new system, and authenticator codes set up
+ before the move no longer work there. Two-factor is off until you
+ enable it again; remove the old OpenPanel entry from your
+ authenticator app first.
+ </p>
+ </div>
+ )}
+ <div className="row items-center justify-between rounded-md border border-border bg-def-100 px-4 py-3">
+ <div className="row items-center gap-2 text-sm">
+ <ShieldOffIcon className="size-4 text-muted-foreground" />
+ <span>Two-factor authentication is disabled.</span>
+ </div>
+ <Button onClick={() => pushModal('SetupTwoFactor')} size="sm">
+ Enable
+ </Button>
</div>
- <Button onClick={() => pushModal('SetupTwoFactor')} size="sm">
- Enable
- </Button>
- </div>
+ </>
);
}
-function EnabledView({
- enabledAt,
- remainingRecoveryCodes,
-}: {
- enabledAt: Date;
- remainingRecoveryCodes: number;
-}) {
+function EnabledView() {
return (
<>
<div className="row items-center justify-between rounded-md border border-border bg-def-100 px-4 py-3">
@@ -87,14 +103,7 @@ function EnabledView({
<div className="center-center size-10 rounded-full bg-emerald-500/10">
<ShieldCheckIcon className="size-4 text-emerald-500" />
</div>
- <div className="col gap-1">
- <span>Two-factor authentication is enabled.</span>
- <span className="text-muted-foreground text-xs">
- Enabled {new Date(enabledAt).toLocaleString()} ·{' '}
- {remainingRecoveryCodes} recovery code
- {remainingRecoveryCodes === 1 ? '' : 's'} remaining
- </span>
- </div>
+ <span>Two-factor authentication is enabled.</span>
</div>
</div>
diff --git a/apps/start/src/routes/_login.login.tsx b/apps/start/src/routes/_login.login.tsx
index 2eba06139..edec6ef94 100644
--- a/apps/start/src/routes/_login.login.tsx
+++ b/apps/start/src/routes/_login.login.tsx
@@ -14,6 +14,24 @@ import { useTRPC } from '@/integrations/trpc/react';
import { trackFunnel } from '@/utils/funnel-tracking';
import { createTitle, PAGE_TITLES } from '@/utils/title';
+// Codes better-auth puts in `?error=` after a Google/GitHub sign-in, when it
+// sends no description of its own.
+const OAUTH_ERROR_MESSAGES: Record<string, string> = {
+ account_not_linked:
+ 'Please sign in using your original authentication method',
+ state_mismatch:
+ 'The sign-in took too long or was opened in another tab. Try again.',
+ email_not_found: 'Your provider did not share a verified email address',
+ unable_to_get_user_info:
+ 'We could not get a verified email address from your provider. Verify your email with Google or GitHub and try again.',
+};
+
+function signInErrorMessage(error: string, description?: string): string {
+ return (
+ description || OAUTH_ERROR_MESSAGES[error] || error.replaceAll('_', ' ')
+ );
+}
+
export const Route = createFileRoute('/_login/login')({
component: LoginPage,
head: () => ({
@@ -24,6 +42,7 @@ export const Route = createFileRoute('/_login/login')({
}),
validateSearch: z.object({
error: z.string().optional(),
+ error_description: z.string().optional(),
correlationId: z.string().optional(),
inviteId: z.string().optional(),
}),
@@ -35,7 +54,12 @@ export const Route = createFileRoute('/_login/login')({
});
function LoginPage() {
- const { error, correlationId, inviteId } = Route.useSearch();
+ const {
+ error,
+ error_description: errorDescription,
+ correlationId,
+ inviteId,
+ } = Route.useSearch();
const trpc = useTRPC();
const { data: providers } = useSuspenseQuery(
trpc.auth.providers.queryOptions()
@@ -72,7 +96,7 @@ function LoginPage() {
<AlertCircle className="h-4 w-4" />
<AlertTitle>Could not sign you in</AlertTitle>
<AlertDescription>
- <p>{error}</p>
+ <p>{signInErrorMessage(error, errorDescription)}</p>
{correlationId && (
<p className="mt-2">
Reference: {correlationId}.{' '}
diff --git a/apps/start/src/routes/_login.verify.tsx b/apps/start/src/routes/_login.verify.tsx
index 728e50231..1aa45ffbe 100644
--- a/apps/start/src/routes/_login.verify.tsx
+++ b/apps/start/src/routes/_login.verify.tsx
@@ -10,7 +10,7 @@ import {
InputOTPGroup,
InputOTPSlot,
} from '@/components/ui/input-otp';
-import { useTRPC } from '@/integrations/trpc/react';
+import { unwrap, useAuthClient } from '@/integrations/auth/client';
import { createTitle, PAGE_TITLES } from '@/utils/title';
export const Route = createFileRoute('/_login/verify')({
@@ -24,22 +24,26 @@ export const Route = createFileRoute('/_login/verify')({
});
function VerifyPage() {
- const trpc = useTRPC();
+ const authClient = useAuthClient();
const [mode, setMode] = useState<'totp' | 'recovery'>('totp');
const [code, setCode] = useState('');
- const mutation = useMutation(
- trpc.auth.signInTotp.mutationOptions({
- onSuccess() {
- toast.success('Signed in');
- window.location.href = '/';
- },
- onError(error) {
- toast.error(error.message);
- setCode('');
- },
- })
- );
+ const mutation = useMutation({
+ mutationFn: ({ code: value }: { code: string }) =>
+ unwrap(
+ mode === 'totp'
+ ? authClient.twoFactor.verifyTotp({ code: value })
+ : authClient.twoFactor.verifyBackupCode({ code: value.trim() })
+ ),
+ onSuccess() {
+ toast.success('Signed in');
+ window.location.href = '/';
+ },
+ onError(error) {
+ toast.error(error.message);
+ setCode('');
+ },
+ });
const canSubmit =
mode === 'totp' ? code.length === 6 : code.trim().length > 0;
@@ -90,11 +94,11 @@ function VerifyPage() {
) : (
<Input
aria-label="Recovery code"
- autoCapitalize="characters"
+ autoCapitalize="off"
autoFocus
disabled={mutation.isPending}
onChange={(e) => setCode(e.target.value)}
- placeholder="ABCDE-FGHIJ"
+ placeholder="AbCdE-fGhIj"
size="xl"
value={code}
/>
diff --git a/bun.lock b/bun.lock
index 331825626..575512108 100644
--- a/bun.lock
+++ b/bun.lock
@@ -176,6 +176,7 @@
"@visx/shape": "4.0.1-alpha.0",
"@visx/zoom": "4.0.1-alpha.0",
"ai": "7.0.144",
+ "better-auth": "1.7.10",
"bind-event-listener": "3.0.0",
"class-variance-authority": "0.7.1",
"clsx": "2.1.1",
@@ -209,6 +210,7 @@
"nuqs": "2.5.2",
"prisma-error-enum": "0.1.3",
"pushmodal": "1.0.3",
+ "qrcode": "1.5.4",
"ramda": "0.29.1",
"random-animal-name": "0.1.1",
"rc-virtual-list": "3.14.5",
@@ -268,6 +270,7 @@
"@types/lodash.debounce": "4.0.9",
"@types/lodash.isequal": "4.5.8",
"@types/lodash.throttle": "4.1.9",
+ "@types/qrcode": "1.5.6",
"@types/ramda": "0.31.0",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
@@ -327,7 +330,6 @@
"@openpanel/shared": "workspace:*",
"@oslojs/crypto": "1.0.1",
"@oslojs/encoding": "1.1.0",
- "@oslojs/otp": "1.1.0",
"@slack/bolt": "3.21.4",
"@slack/oauth": "3.0.1",
"@trpc/server": "11.6.0",
@@ -349,7 +351,6 @@
"pino-pretty": "catalog:",
"prisma-error-enum": "0.1.3",
"prom-client": "15.1.3",
- "qrcode": "1.5.4",
"ramda": "0.29.1",
"short-unique-id": "5.0.3",
"superjson": "2.2.2",
@@ -361,7 +362,6 @@
"@clickhouse/client": "1.18.5",
"@openpanel/tsconfig": "workspace:*",
"@types/js-yaml": "4.0.9",
- "@types/qrcode": "1.5.6",
"@types/ramda": "0.31.0",
"@types/unzipper": "0.10.11",
"@types/uuid": "10.0.0",
@@ -1862,8 +1862,6 @@
"@oslojs/jwt": ["@oslojs/[email protected]", "", { "dependencies": { "@oslojs/encoding": "0.4.1" } }, "sha512-bLE7BtHrURedCn4Mco3ma9L4Y1GR2SMBuIvjWr7rmQ4/W/4Jy70TIAgZ+0nIlk0xHz1vNP8x8DCns45Sb2XRbg=="],
- "@oslojs/otp": ["@oslojs/[email protected]", "", { "dependencies": { "@oslojs/binary": "1.0.0", "@oslojs/crypto": "1.0.0", "@oslojs/encoding": "1.0.0" } }, "sha512-tpdxlnCLcY6IZLLqH8kGD8PSvIVyev/+Gbglgvrk9e4YzgKO7+7FL8NWBofL7LZI6MgQ1HnNUuotRG6t1JJ0dg=="],
-
"@oxc-minify/binding-android-arm64": ["@oxc-minify/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-pknM+ttJTwRr7ezn1v5K+o2P4RRjLAzKI10bjVDPybwWQ544AZW6jxm7/YDgF2yUbWEV9o7cAQPkIUOmCiW8vg=="],
"@oxc-minify/binding-darwin-arm64": ["@oxc-minify/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BDLiH41ZctNND38+GCEL3ZxFn9j7qMZJLrr6SLWMt8xlG4Sl64xTkZ0zeUy4RdVEatKKZdrRIhFZ2e5wPDQT6Q=="],
@@ -6332,10 +6330,6 @@
"@oslojs/jwt/@oslojs/encoding": ["@oslojs/[email protected]", "", {}, "sha512-hkjo6MuIK/kQR5CrGNdAPZhS01ZCXuWDRJ187zh6qqF2+yMHZpD9fAYpX8q2bOO6Ryhl3XpCT6kUX76N8hhm4Q=="],
- "@oslojs/otp/@oslojs/crypto": ["@oslojs/[email protected]", "", { "dependencies": { "@oslojs/asn1": "1.0.0", "@oslojs/binary": "1.0.0" } }, "sha512-dVz8TkkgYdr3tlwxHd7SCYGxoN7ynwHLA0nei/Aq9C+ERU0BK+U8+/3soEzBUxUNKYBf42351DyJUZ2REla50w=="],
-
- "@oslojs/otp/@oslojs/encoding": ["@oslojs/[email protected]", "", {}, "sha512-dyIB0SdZgMm5BhGwdSp8rMxEFIopLKxDG1vxIBaiogyom6ZqH2aXPb6DEC2WzOOWKdPSq1cxdNeRx2wAn1Z+ZQ=="],
-
"@oxc-minify/binding-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, "sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q=="],
"@oxc-parser/binding-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, "sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q=="],
diff --git a/packages/core/package.json b/packages/core/package.json
index 443925505..57eef1533 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -39,7 +39,6 @@
"@openpanel/shared": "workspace:*",
"@oslojs/crypto": "1.0.1",
"@oslojs/encoding": "1.1.0",
- "@oslojs/otp": "1.1.0",
"@slack/bolt": "3.21.4",
"@slack/oauth": "3.0.1",
"@trpc/server": "11.6.0",
@@ -61,7 +60,6 @@
"pino-pretty": "catalog:",
"prisma-error-enum": "0.1.3",
"prom-client": "15.1.3",
- "qrcode": "1.5.4",
"ramda": "0.29.1",
"short-unique-id": "5.0.3",
"superjson": "2.2.2",
@@ -73,7 +71,6 @@
"@clickhouse/client": "1.18.5",
"@openpanel/tsconfig": "workspace:*",
"@types/js-yaml": "4.0.9",
- "@types/qrcode": "1.5.6",
"@types/ramda": "0.31.0",
"@types/unzipper": "0.10.11",
"@types/uuid": "10.0.0",
diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts
index 2336e6368..1e8162761 100644
--- a/packages/core/src/config.ts
+++ b/packages/core/src/config.ts
@@ -30,6 +30,8 @@ export interface AuthConfig {
* changing it signs everyone out. Unset leaves only legacy sessions.
*/
secret: string | undefined;
+ /** DASHBOARD_URL plus API_CORS_ORIGINS: who may call `/api/auth`. */
+ trustedOrigins: string[];
/**
* `undefined` means the variable is unset, which is what cloud runs and what
* makes registration unconditionally open — distinct from an explicit
diff --git a/packages/core/src/http/cors.ts b/packages/core/src/http/cors.ts
index 3d8d03476..40cd280d3 100644
--- a/packages/core/src/http/cors.ts
+++ b/packages/core/src/http/cors.ts
@@ -13,6 +13,7 @@ import { cors } from '@elysiajs/cors';
/** The allowlist of private-route prefixes. */
export const CORS_PRIVATE_PATHS = [
'/trpc',
+ '/api/auth',
'/live',
'/webhook',
'/oauth',
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 6c9f4a8ae..77c5ebf45 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -106,9 +106,6 @@ export {
Arctic,
cookieOptions,
createAuthService,
- deleteSessionTokenCookie,
- githubClient,
- googleClient,
googleGscClient,
parseCookieDomain,
} from './modules/auth/auth.service';
diff --git a/packages/core/src/modules/auth/auth.constants.test.ts b/packages/core/src/modules/auth/auth.constants.test.ts
index f553ffc2d..52abed2cd 100644
--- a/packages/core/src/modules/auth/auth.constants.test.ts
+++ b/packages/core/src/modules/auth/auth.constants.test.ts
@@ -1,6 +1,5 @@
// The ceilings exist so an input cannot choose how much work the server does:
-// a password reaches argon2, a recovery code reaches it ten times, and an
-// inviteId is written into a Set-Cookie header. These assert the bound fires
+// a password reaches argon2. These assert the bound fires
// and, just as importantly, that an ordinary value still passes.
import { describe, expect, test } from 'bun:test';
@@ -13,7 +12,6 @@ import {
zSignInShare,
zSignUpEmail,
zTotpCode,
- zTotpOrRecoveryCode,
} from './auth.constants';
const long = (n: number) => 'a'.repeat(n);
@@ -59,14 +57,6 @@ describe('the TOTP inputs are bounded', () => {
expect(zTotpCode.parse('123 456')).toBe('123456');
});
- // This one decides ten sequential argon2 verifies in consumeRecoveryCode.
- test('a recovery code is capped', () => {
- expect(zTotpOrRecoveryCode.safeParse('abcd-efgh').success).toBe(true);
- expect(zTotpOrRecoveryCode.safeParse(long(MAX_TOKEN + 1)).success).toBe(
- false
- );
- });
-
test('a huge TOTP code is refused before the regex runs over it', () => {
expect(zTotpCode.safeParse(long(MAX_TOKEN + 1)).success).toBe(false);
});
diff --git a/packages/core/src/modules/auth/auth.constants.ts b/packages/core/src/modules/auth/auth.constants.ts
index c80e7af81..8dbb8dc9a 100644
--- a/packages/core/src/modules/auth/auth.constants.ts
+++ b/packages/core/src/modules/auth/auth.constants.ts
@@ -9,6 +9,9 @@ import {
export const zProvider = z.enum(['email', 'google', 'github']);
+/** Carries an invite through an email sign-in or sign-up to `/api/auth`. */
+export const INVITE_HEADER = 'x-openpanel-invite';
+
/**
* `hashPassword` hands this straight to argon2, so the ceiling is what stops a
* caller choosing how much work the server does. 128 is far above any password
@@ -32,7 +35,6 @@ const zPersonName = z.string().trim().min(1).max(MAX_NAME);
export const zSignInEmail = z.object({
email: zEmail.min(1),
password: zPassword,
- inviteId: zShortId.nullish(),
});
export type ISignInEmail = z.infer<typeof zSignInEmail>;
@@ -43,7 +45,6 @@ export const zSignUpEmail = z.object({
lastName: zPersonName,
email: zEmail,
password: zPassword,
- inviteId: zShortId.nullish(),
});
export type ISignUpEmail = z.infer<typeof zSignUpEmail>;
@@ -58,8 +59,6 @@ export const zRequestResetPassword = z.object({
});
export type IRequestResetPassword = z.infer<typeof zRequestResetPassword>;
-// Bounded before the transform: the strip and the regex below both run over
-// whatever arrives.
export const zTotpCode = z
.string()
.max(MAX_TOKEN)
@@ -67,15 +66,6 @@ export const zTotpCode = z
.refine((v) => /^\d{6}$/.test(v), { message: 'Enter a 6-digit code' });
export type ITotpCode = z.infer<typeof zTotpCode>;
-// A recovery code is checked against all ten stored hashes in turn, so this one
-// input decides ten argon2 verifies.
-export const zTotpOrRecoveryCode = z
- .string()
- .min(1)
- .max(MAX_TOKEN)
- .transform((v) => v.trim());
-export type ITotpOrRecoveryCode = z.infer<typeof zTotpOrRecoveryCode>;
-
export const zSignInShare = z.object({
password: z.string().min(1).max(MAX_PASSWORD),
shareId: zShortId.min(1),
diff --git a/packages/core/src/modules/auth/auth.routes.ts b/packages/core/src/modules/auth/auth.routes.ts
index a976e4303..941b071ec 100644
--- a/packages/core/src/modules/auth/auth.routes.ts
+++ b/packages/core/src/modules/auth/auth.routes.ts
@@ -1,123 +1,87 @@
-import { redirect } from 'elysia';
-import { z } from 'zod';
+import type { IpHeaderConfig } from '../../config';
import { defineRoutes } from '../../http/define';
-import { MAX_TOKEN } from '../../shared/limits.constants';
+import { getTrustedIpFromHeaders } from '../../shared/get-client-ip';
import {
- assertOAuthState,
- completeOAuthCallback,
- fetchGithubOAuthUser,
- fetchGoogleOAuthUser,
- OAuthCallbackError,
-} from './auth.service';
-import { AUTH_BASE_PATH } from './src/better-auth';
+ AUTH_BASE_PATH,
+ type Auth,
+ TRUSTED_IP_HEADER,
+} from './src/better-auth';
-// Anyone can call this URL directly, so both values are attacker-controlled.
-const callbackQuery = z.object({
- code: z.string().max(MAX_TOKEN),
- state: z.string().max(MAX_TOKEN),
-});
+/** The part of Bun's server Elysia hands a route: the peer address. */
+interface SocketAddressSource {
+ requestIP(request: Request): { address: string } | null;
+}
-/** Only used to make the URL parseable when DASHBOARD_URL is not set. */
-const FALLBACK_ORIGIN = 'http://localhost';
+interface ForwardOptions {
+ ipHeaders: IpHeaderConfig;
+ socketIp: string | undefined;
+ pathname?: string;
+}
-function loginErrorRedirect(
- dashboardUrl: string,
- message: string,
- correlationId: string
-) {
- const url = new URL('/login', dashboardUrl || FALLBACK_ORIGIN);
- url.searchParams.set('error', message);
- url.searchParams.set('correlationId', correlationId);
- return redirect(url.toString());
+/**
+ * better-auth's rate limiter keys on one header we set ourselves, so a caller
+ * cannot pick its own bucket through `x-forwarded-for`.
+ */
+function withTrustedIp(
+ request: Request,
+ { ipHeaders, socketIp, pathname }: ForwardOptions
+): Request {
+ const url = new URL(request.url);
+ if (pathname) {
+ url.pathname = pathname;
+ }
+ const headers = new Headers(request.headers);
+ const { ip } = getTrustedIpFromHeaders(ipHeaders, request.headers, socketIp);
+ headers.delete(TRUSTED_IP_HEADER);
+ if (ip) {
+ headers.set(TRUSTED_IP_HEADER, ip);
+ }
+ return new Request(url.toString(), {
+ method: request.method,
+ headers,
+ body: request.body,
+ redirect: 'manual',
+ });
}
-export const authRoutes = defineRoutes((app, deps) =>
- app
- .all(
- `${AUTH_BASE_PATH}/*`,
- ({ request }) =>
- deps.auth?.handler(request) ??
- new Response('Not Found', { status: 404 }),
- { parse: 'none', detail: { hide: true } }
- )
- .get(
- '/oauth/github/callback',
- async ({ query, ctx }) => {
- const storedState = ctx.cookies.get('github_oauth_state') ?? null;
- const inviteId = ctx.cookies.get('inviteId');
+function handle(
+ auth: Auth | null,
+ request: Request,
+ options: ForwardOptions
+): Promise<Response> | Response {
+ if (!auth) {
+ return new Response('Not Found', { status: 404 });
+ }
+ return auth.handler(withTrustedIp(request, options));
+}
- try {
- assertOAuthState('github', query.state, storedState);
- const oauthUser = await fetchGithubOAuthUser(ctx.config, query.code);
- await completeOAuthCallback(ctx, {
- provider: 'github',
- oauthUser,
- inviteId,
- setCookie: ctx.setCookie,
- logger: ctx.logger,
- });
- ctx.setCookie('github_oauth_state', '', { maxAge: 0 });
- return redirect(ctx.config.dashboardUrl);
- } catch (error) {
- ctx.logger.error({ err: error }, 'GitHub OAuth callback error');
- ctx.setCookie('github_oauth_state', '', { maxAge: 0 });
- const message =
- error instanceof OAuthCallbackError
- ? error.message
- : 'An error occurred';
- return loginErrorRedirect(
- ctx.config.dashboardUrl,
- message,
- ctx.requestId
- );
- }
- },
- { query: callbackQuery, detail: { hide: true } }
- )
+// The redirect URIs registered at Google and GitHub point at the legacy
+// `/oauth/<provider>/callback` paths; serving them means nobody has to change
+// their OAuth app.
+export const authRoutes = defineRoutes((app, deps) => {
+ const forward = (
+ {
+ request,
+ server,
+ }: { request: Request; server: SocketAddressSource | null },
+ pathname?: string
+ ) =>
+ handle(deps.auth, request, {
+ ipHeaders: deps.config.ipHeaders,
+ socketIp: server?.requestIP(request)?.address,
+ pathname,
+ });
+ const route = { parse: 'none', detail: { hide: true } } as const;
+ return app
+ .all(`${AUTH_BASE_PATH}/*`, (context) => forward(context), route)
.get(
'/oauth/google/callback',
- async ({ query, ctx }) => {
- const storedState = ctx.cookies.get('google_oauth_state') ?? null;
- const codeVerifier = ctx.cookies.get('google_code_verifier') ?? null;
- const inviteId = ctx.cookies.get('inviteId');
-
- try {
- assertOAuthState('google', query.state, storedState);
- if (!codeVerifier) {
- throw new OAuthCallbackError('Missing oauth parameters', {
- codeVerifier: false,
- });
- }
- const oauthUser = await fetchGoogleOAuthUser(
- ctx.config,
- query.code,
- codeVerifier
- );
- await completeOAuthCallback(ctx, {
- provider: 'google',
- oauthUser,
- inviteId,
- setCookie: ctx.setCookie,
- logger: ctx.logger,
- });
- ctx.setCookie('google_oauth_state', '', { maxAge: 0 });
- ctx.setCookie('google_code_verifier', '', { maxAge: 0 });
- return redirect(ctx.config.dashboardUrl);
- } catch (error) {
- ctx.logger.error({ err: error }, 'Google OAuth callback error');
- ctx.setCookie('google_oauth_state', '', { maxAge: 0 });
- ctx.setCookie('google_code_verifier', '', { maxAge: 0 });
- const message =
- error instanceof OAuthCallbackError
- ? error.message
- : 'An error occurred';
- return loginErrorRedirect(
- ctx.config.dashboardUrl,
- message,
- ctx.requestId
- );
- }
- },
- { query: callbackQuery, detail: { hide: true } }
+ (context) => forward(context, `${AUTH_BASE_PATH}/callback/google`),
+ route
)
-);
+ .get(
+ '/oauth/github/callback',
+ (context) => forward(context, `${AUTH_BASE_PATH}/callback/github`),
+ route
+ );
+});
diff --git a/packages/core/src/modules/auth/auth.rpc.test.ts b/packages/core/src/modules/auth/auth.rpc.test.ts
index 70eaff811..0be5374d8 100644
--- a/packages/core/src/modules/auth/auth.rpc.test.ts
+++ b/packages/core/src/modules/auth/auth.rpc.test.ts
@@ -138,41 +138,13 @@ test('signInDev is refused when DEV_LOGIN is not configured', async () => {
});
});
-test('totpStatus rejects an unauthenticated caller', async () => {
+test('twoFactorStatus rejects an unauthenticated caller', async () => {
const caller = await anonCaller();
- await expect(caller.totpStatus()).rejects.toMatchObject({
+ await expect(caller.twoFactorStatus()).rejects.toMatchObject({
code: 'UNAUTHORIZED',
});
});
-test('totpSetup rejects an unauthenticated caller', async () => {
- const caller = await anonCaller();
- await expect(caller.totpSetup()).rejects.toMatchObject({
- code: 'UNAUTHORIZED',
- });
-});
-
-test('totpEnable rejects an unauthenticated caller before checking a code', async () => {
- const caller = await anonCaller();
- await expect(caller.totpEnable({ code: '123456' })).rejects.toMatchObject({
- code: 'UNAUTHORIZED',
- });
-});
-
-test('totpDisable rejects an unauthenticated caller before checking a code', async () => {
- const caller = await anonCaller();
- await expect(caller.totpDisable({ code: '123456' })).rejects.toMatchObject({
- code: 'UNAUTHORIZED',
- });
-});
-
-test('totpRegenerateRecoveryCodes rejects an unauthenticated caller', async () => {
- const caller = await anonCaller();
- await expect(
- caller.totpRegenerateRecoveryCodes({ code: '123456' })
- ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
-});
-
test('session returns the caller session unauthenticated (no login required)', async () => {
const caller = await anonCaller();
await expect(caller.session()).resolves.toEqual(EMPTY_SESSION);
diff --git a/packages/core/src/modules/auth/auth.rpc.ts b/packages/core/src/modules/auth/auth.rpc.ts
index 3d760f8df..ff30c4e56 100644
--- a/packages/core/src/modules/auth/auth.rpc.ts
+++ b/packages/core/src/modules/auth/auth.rpc.ts
@@ -1,7 +1,6 @@
-// `enforceAccess` only sees a top-level `projectId` / `organizationId`, so
-// anything resolved from another id needs its own explicit check in the handler.
+// Sign-in, sign-up, password reset and two-factor are better-auth's
+// (`/api/auth/*`); what stays here reads the session or is not a sign-in.
-import { z } from 'zod';
import type { Session } from '../../context';
import {
createRateLimitMiddleware,
@@ -10,34 +9,13 @@ import {
publicProcedure,
} from '../../rpc/base';
import { enforceRateLimit } from '../../rpc/rate-limit';
+import { zSignInDev, zSignInShare } from './auth.constants';
import {
- zProvider,
- zRequestResetPassword,
- zResetPassword,
- zSignInDev,
- zSignInEmail,
- zSignInShare,
- zSignUpEmail,
- zTotpCode,
- zTotpOrRecoveryCode,
-} from './auth.constants';
-import {
- disableTotp,
- enableTotp,
- extendSessionCookie,
getConfiguredProviders,
- getTotpStatus,
- regenerateTotpRecoveryCodes,
- requestPasswordReset,
- resetPasswordWithToken,
- setupTotp,
+ getTwoFactorStatus,
signInToShare,
signInWithDevLogin,
- signInWithEmail,
- signInWithTotp,
signOutUser,
- signUpWithEmail,
- startOAuthSignIn,
} from './auth.service';
const rateLimit = createRateLimitMiddleware(enforceRateLimit);
@@ -61,91 +39,25 @@ export const authRouter = createTRPCRouter({
getConfiguredProviders(ctx.config)
),
+ /** Ends either kind of session and clears both cookies. */
signOut: publicProcedure.mutation(async ({ ctx }) => {
await signOutUser(ctx, ctx.setCookie, ctx.session?.session?.id);
}),
- signInOAuth: publicProcedure
- .input(z.object({ provider: zProvider, inviteId: z.string().nullish() }))
- .mutation(({ input, ctx }) => startOAuthSignIn(ctx, input, ctx.setCookie)),
-
- signUpEmail: publicProcedure
- .use(rateLimit({ max: 5, windowMs: 60_000 }))
- .input(zSignUpEmail)
- .mutation(({ input, ctx }) => signUpWithEmail(ctx, input, ctx.setCookie)),
-
- signInEmail: publicProcedure
- .use(rateLimit({ max: 3, windowMs: 30_000 }))
- .input(zSignInEmail)
- .mutation(({ input, ctx }) =>
- signInWithEmail(ctx, input, ctx.setCookie, ctx.logger)
- ),
-
/** One click on a local box; `DEV_LOGIN` cannot be set in production. */
signInDev: publicProcedure
.use(rateLimit({ max: 10, windowMs: 60_000 }))
.input(zSignInDev)
.mutation(({ input, ctx }) =>
- signInWithDevLogin(ctx, input, ctx.setCookie, ctx.logger)
+ signInWithDevLogin(ctx, input, ctx.headers, ctx.setCookie)
),
- signInTotp: publicProcedure
- .use(rateLimit({ max: 5, windowMs: 60_000 }))
- .input(z.object({ code: zTotpOrRecoveryCode }))
- .mutation(({ input, ctx }) =>
- signInWithTotp(ctx, input, ctx.cookies, ctx.setCookie, ctx.logger)
- ),
-
- totpStatus: protectedProcedure.query(({ ctx }) =>
- getTotpStatus(ctx, ctx.session.userId)
+ twoFactorStatus: protectedProcedure.query(({ ctx }) =>
+ getTwoFactorStatus(ctx, ctx.session.userId)
),
- totpSetup: protectedProcedure.mutation(({ ctx }) =>
- setupTotp(ctx, ctx.session.userId)
- ),
-
- totpEnable: protectedProcedure
- .use(rateLimit({ max: 5, windowMs: 60_000 }))
- .input(z.object({ code: zTotpCode }))
- .mutation(({ input, ctx }) =>
- enableTotp(ctx, ctx.session.userId, input.code)
- ),
-
- totpDisable: protectedProcedure
- .use(rateLimit({ max: 5, windowMs: 60_000 }))
- .input(z.object({ code: zTotpOrRecoveryCode }))
- .mutation(({ input, ctx }) =>
- disableTotp(ctx, ctx.session.userId, input.code)
- ),
-
- totpRegenerateRecoveryCodes: protectedProcedure
- .use(rateLimit({ max: 3, windowMs: 60_000 }))
- .input(z.object({ code: zTotpCode }))
- .mutation(({ input, ctx }) =>
- regenerateTotpRecoveryCodes(ctx, ctx.session.userId, input.code)
- ),
-
- resetPassword: publicProcedure
- .use(rateLimit({ max: 3, windowMs: 60_000 }))
- .input(zResetPassword)
- .mutation(({ input, ctx }) => resetPasswordWithToken(ctx, input)),
-
- requestResetPassword: publicProcedure
- .use(rateLimit({ max: 3, windowMs: 60_000 }))
- .input(zRequestResetPassword)
- .mutation(({ input, ctx }) => requestPasswordReset(ctx, input)),
-
session: publicProcedure.query(({ ctx }) => withoutSessionToken(ctx.session)),
- extendSession: publicProcedure.mutation(({ ctx }) =>
- extendSessionCookie(
- ctx,
- ctx.cookies,
- Boolean(ctx.session.session),
- ctx.setCookie
- )
- ),
-
signInShare: publicProcedure
.use(rateLimit({ max: 3, windowMs: 30_000 }))
.input(zSignInShare)
diff --git a/packages/core/src/modules/auth/auth.service.access.test.ts b/packages/core/src/modules/auth/auth.service.access.test.ts
index 80492ff7d..3ab6a8e98 100644
--- a/packages/core/src/modules/auth/auth.service.access.test.ts
+++ b/packages/core/src/modules/auth/auth.service.access.test.ts
@@ -178,8 +178,7 @@ test('getOrganizationAccess reports the stored role, the old spellings by their
}
const readAs: [stored: string, role: string][] = [
- ['org:admin', 'admin'],
- ['org:member', 'member'],
+ ['org:admin', 'member'],
['superuser', 'member'],
];
for (const [stored, role] of readAs) {
diff --git a/packages/core/src/modules/auth/auth.service.test.ts b/packages/core/src/modules/auth/auth.service.test.ts
deleted file mode 100644
index 5a5917867..000000000
--- a/packages/core/src/modules/auth/auth.service.test.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-// A wrong or stale second factor must not answer UNAUTHORIZED: the dashboard
-// reads every 401 as "signed out" and sends the user to /login mid-challenge.
-
-import { expect, test } from 'bun:test';
-import { encrypt } from '@openpanel/shared/server';
-import { testCoreConfig } from '../../../test/config-fixture';
-import type { ServiceDeps } from '../../services';
-import { signInWithEmail, signInWithTotp } from './auth.service';
-import { hashPassword } from './src/password';
-import { generateTotpSecret } from './src/totp';
-
-const ENCRYPTION_KEY = 'a'.repeat(64);
-const CHALLENGE_ID = '2fa_test';
-const CHALLENGE_COOKIE = '2fa_challenge';
-const USER_ID = 'user_test';
-const HOUR_MS = 60 * 60 * 1000;
-const noop = () => undefined;
-const logger = { error: noop };
-
-function depsWith(db: Record<string, unknown>): ServiceDeps {
- return {
- db,
- config: testCoreConfig({ encryptionKey: ENCRYPTION_KEY }),
- } as unknown as ServiceDeps;
-}
-
-function cookies(values: Record<string, string>) {
- return { get: (name: string) => values[name] };
-}
-
-function totpDb(challengeExpiresAt: Date) {
- return {
- twoFactorChallenge: {
- findUnique: () =>
- Promise.resolve({
- id: CHALLENGE_ID,
- userId: USER_ID,
- expiresAt: challengeExpiresAt,
- }),
- delete: () => Promise.resolve(),
- },
- userTotp: {
- findUnique: () =>
- Promise.resolve({
- userId: USER_ID,
- enabledAt: new Date(),
- secret: encrypt(ENCRYPTION_KEY, generateTotpSecret()),
- recoveryCodes: [],
- }),
- },
- };
-}
-
-test('signing in with a code but no challenge cookie is a bad request', async () => {
- await expect(
- signInWithTotp(depsWith({}), { code: '123456' }, cookies({}), noop, logger)
- ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
-});
-
-test('an expired two-factor challenge is a bad request', async () => {
- const db = totpDb(new Date(Date.now() - HOUR_MS));
- await expect(
- signInWithTotp(
- depsWith(db),
- { code: '123456' },
- cookies({ [CHALLENGE_COOKIE]: CHALLENGE_ID }),
- noop,
- logger
- )
- ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
-});
-
-test('a wrong two-factor code is a bad request, not unauthorized', async () => {
- const db = totpDb(new Date(Date.now() + HOUR_MS));
- await expect(
- signInWithTotp(
- depsWith(db),
- { code: '000000' },
- cookies({ [CHALLENGE_COOKIE]: CHALLENGE_ID }),
- noop,
- logger
- )
- ).rejects.toMatchObject({ code: 'BAD_REQUEST', message: 'Invalid code' });
-});
-
-test('a password with edge whitespace signs in exactly as it was set', async () => {
- const password = ' spaced password ';
- const account = { id: 'acc_test', password: await hashPassword(password) };
- const db = {
- user: {
- findFirst: () => Promise.resolve({ id: USER_ID, accounts: [account] }),
- },
- userTotp: { findUnique: () => Promise.resolve(null) },
- session: { create: () => Promise.resolve() },
- };
- const deps = depsWith(db);
-
- await expect(
- signInWithEmail(
- deps,
- { email: '[email protected]', password: password.trim() },
- noop,
- logger
- )
- ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
- await expect(
- signInWithEmail(deps, { email: '[email protected]', password }, noop, logger)
- ).resolves.toEqual({ type: 'email' });
-});
diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.ts
index e69fb1037..5a7f2f44e 100644
--- a/packages/core/src/modules/auth/auth.service.ts
+++ b/packages/core/src/modules/auth/auth.service.ts
@@ -1,5 +1,4 @@
import type { Session } from '@openpanel/db/src/prisma-client';
-import { z } from 'zod';
import type { CoreConfig } from '../../config';
import type { ServiceDeps, Services } from '../../services';
import {
@@ -17,69 +16,28 @@ import {
normalizeOrganizationRole,
type OrganizationRole,
} from '../organization/organization.constants';
+import { INVITE_HEADER } from './auth.constants';
import { type AccessChecks, createAccessChecks } from './src/access';
import {
type AuthSessionResult,
deleteAuthSessionCookie,
getAuthSession,
+ type PasswordSignInResult,
+ signInWithPassword,
upgradeLegacySession,
} from './src/better-auth';
-import {
- deleteSessionTokenCookie,
- setLastAuthProviderCookie,
- setSessionTokenCookie,
-} from './src/cookie';
+import { deleteSessionTokenCookie } from './src/cookie';
import { parseCookieDomain } from './src/cookie-domain';
-import { Arctic, githubClient, googleClient } from './src/oauth';
import { hashPassword, verifyPasswordHash } from './src/password';
-import {
- decodeSessionToken,
- generateSessionToken,
- hashSessionToken,
-} from './src/token';
-import {
- buildOtpauthUrl,
- consumeRecoveryCode,
- generateQrDataUrl,
- generateRecoveryCodes,
- generateTotpSecret,
- hashRecoveryCodes,
- normalizeRecoveryCode,
- verifyTotpCode,
-} from './src/totp';
+import { decodeSessionToken, hashSessionToken } from './src/token';
// Re-exported from source: the imports above are also used by
// `createAuthService`, so re-exporting them would trip `noExportedImports`.
export { COOKIE_MAX_AGE, cookieOptions } from './src/constants';
-export {
- deleteSessionTokenCookie,
- setLastAuthProviderCookie,
- setSessionTokenCookie,
-} from './src/cookie';
export { parseCookieDomain } from './src/cookie-domain';
export type { OAuth2Tokens } from './src/oauth';
-export {
- Arctic,
- githubClient,
- googleClient,
- googleGscClient,
-} from './src/oauth';
+export { Arctic, googleGscClient } from './src/oauth';
export { hashPassword, verifyPasswordHash } from './src/password';
-export {
- decodeSessionToken,
- generateSessionToken,
- hashSessionToken,
-} from './src/token';
-export {
- buildOtpauthUrl,
- consumeRecoveryCode,
- generateQrDataUrl,
- generateRecoveryCodes,
- generateTotpSecret,
- hashRecoveryCodes,
- normalizeRecoveryCode,
- verifyTotpCode,
-} from './src/totp';
/** The ladder contract this module binds and `createAuthService` satisfies. */
type ProjectAccessChecks = AccessChecks<IProjectAccess>;
@@ -187,23 +145,10 @@ export function createAuthService(
return validateSessionToken(deps, token);
}
- function setSessionCookie(
- setCookie: ISetCookie,
- token: string,
- expiresAt: Date
- ): void {
- setSessionTokenCookie(deps.config, setCookie, token, expiresAt);
- }
-
- function setAuthProviderCookie(
- setCookie: ISetCookie,
- provider: string
- ): void {
- setLastAuthProviderCookie(deps.config, setCookie, provider);
- }
-
- function clearSessionCookie(setCookie: ISetCookie): void {
+ /** Both cookies: a legacy session also carries better-auth's once upgraded. */
+ function clearSessionCookies(setCookie: ISetCookie): void {
deleteSessionTokenCookie(deps.config, setCookie);
+ deleteAuthSessionCookie(deps.config, setCookie);
}
function getSession(
@@ -250,28 +195,13 @@ export function createAuthService(
getClientAccess,
hashPassword,
verifyPasswordHash,
- generateSessionToken,
decodeSessionToken,
hashSessionToken,
- generateTotpSecret,
- buildOtpauthUrl,
- generateQrDataUrl,
- verifyTotpCode,
- generateRecoveryCodes,
- hashRecoveryCodes,
- normalizeRecoveryCode,
- consumeRecoveryCode,
- setSessionTokenCookie: setSessionCookie,
- setLastAuthProviderCookie: setAuthProviderCookie,
- deleteSessionTokenCookie: clearSessionCookie,
+ clearSessionCookies,
parseCookieDomain: cookieDomainForUrl,
};
}
-import { generateSecureId } from '@openpanel/shared';
-import { decrypt, encrypt } from '@openpanel/shared/server';
-import { sendEmail } from '../../clients/email';
-import type { Logger } from '../../logger';
import {
TRPCAccessError,
TRPCBadRequestError,
@@ -282,53 +212,14 @@ import {
createShareAccessToken,
shareAccessCookieName,
} from '../../shared/share-access';
-import { connectUserToOrganization } from '../organization/organization.service';
-import { getUserAccount, toDisplayName } from '../user/user.service';
import {
- createSession,
invalidateSession,
type SessionValidationResult,
validateSessionToken,
} from './src/login-session';
-import { getIsRegistrationAllowed } from './src/registration';
-const TWO_FACTOR_COOKIE = '2fa_challenge';
-const TWO_FACTOR_CHALLENGE_TTL_SECONDS = 5 * 60;
-const INVITE_COOKIE = 'inviteId';
-const RESET_PASSWORD_TTL_MS = 1000 * 60 * 10;
-/** better-auth's provider id for email and password accounts. */
const CREDENTIAL_PROVIDER = 'credential';
-export type AuthProvider = 'email' | 'google' | 'github';
-
-interface CookieReader {
- get(name: string): string | undefined;
-}
-
-/**
- * Best-effort consumption of an invite for a user that just authenticated.
- * Failures (expired/invalid invite) must not block the sign-in itself, so we
- * swallow and log the error instead of rethrowing.
- */
-async function consumeInviteForUser(
- deps: ServiceDeps,
- userId: string,
- inviteId: string,
- logger: Pick<Logger, 'error'>
-): Promise<void> {
- try {
- const user = await deps.db.user.findUniqueOrThrow({
- where: { id: userId },
- });
- await connectUserToOrganization(deps, { user, inviteId });
- } catch (error) {
- logger.error(
- { userId, inviteId, error },
- 'Failed to connect user to organization via invite'
- );
- }
-}
-
export async function signOutUser(
deps: ServiceDeps,
setCookie: ISetCookie,
@@ -341,15 +232,6 @@ export async function signOutUser(
}
}
-export interface StartOAuthSignInInput {
- provider: AuthProvider;
- inviteId?: string | null;
-}
-
-export type StartOAuthSignInResult =
- | { type: 'github'; url: string }
- | { type: 'google'; url: string };
-
export interface ConfiguredProviders {
google: boolean;
github: boolean;
@@ -383,522 +265,63 @@ export function getConfiguredProviders(
*/
export function signInWithDevLogin(
deps: ServiceDeps,
- input: SignInDevInput,
- setCookie: ISetCookie,
- logger: Pick<Logger, 'error'>
-): Promise<SignInEmailResult> {
+ input: { inviteId?: string | null },
+ headers: Headers,
+ setCookie: ISetCookie
+): Promise<PasswordSignInResult> {
const devLogin = deps.config.auth.devLogin;
- if (!devLogin) {
+ if (!(devLogin && deps.auth)) {
throw new TRPCBadRequestError(
'Dev login is not configured on this deployment'
);
}
- return signInWithEmail(
- deps,
- { ...devLogin, inviteId: input.inviteId },
- setCookie,
- logger
- );
-}
-
-export interface SignInDevInput {
- inviteId?: string | null;
-}
-
-/**
- * No registration check here. At this point we have no identity for the
- * caller — the IdP hasn't been hit yet — so we cannot tell a returning user
- * from a new sign-up. Gating here locks out every existing OAuth user as soon
- * as their session expires. The check lives in `completeOAuthCallback`, the
- * only place we know the user is new.
- */
-export function startOAuthSignIn(
- deps: ServiceDeps,
- input: StartOAuthSignInInput,
- setCookie: ISetCookie
-): StartOAuthSignInResult {
- // An unconfigured provider would otherwise yield a URL with an empty
- // `client_id`.
- const configured = getConfiguredProviders(deps.config);
- if (
- (input.provider === 'github' && !configured.github) ||
- (input.provider === 'google' && !configured.google)
- ) {
- throw new TRPCBadRequestError(
- `${input.provider} sign-in is not configured on this deployment`
- );
- }
-
+ const signInHeaders = new Headers(headers);
+ signInHeaders.delete(INVITE_HEADER);
if (input.inviteId) {
- setCookie('inviteId', input.inviteId, { maxAge: 60 * 10 });
- }
-
- if (input.provider === 'github') {
- const state = Arctic.generateState();
- const url = githubClient(deps.config).createAuthorizationURL(state, [
- 'user:email',
- 'user:read',
- ]);
- setCookie('github_oauth_state', state, { maxAge: 60 * 10 });
- return { type: 'github', url: url.toString() };
- }
-
- const state = Arctic.generateState();
- const codeVerifier = Arctic.generateCodeVerifier();
- const url = googleClient(deps.config).createAuthorizationURL(
- state,
- codeVerifier,
- ['openid', 'profile', 'email']
- );
- setCookie('google_oauth_state', state, { maxAge: 60 * 10 });
- setCookie('google_code_verifier', codeVerifier, { maxAge: 60 * 10 });
- return { type: 'google', url: url.toString() };
-}
-
-export interface SignUpEmailInput {
- firstName: string;
- lastName: string;
- email: string;
- password: string;
- inviteId?: string | null;
-}
-
-export async function signUpWithEmail(
- deps: ServiceDeps,
- input: SignUpEmailInput,
- setCookie: ISetCookie
-) {
- const isRegistrationAllowed = await getIsRegistrationAllowed(
- deps,
- input.inviteId
- );
- if (!isRegistrationAllowed) {
- throw new TRPCForbiddenError('Registrations are not allowed');
- }
-
- const existing = await getUserAccount(deps, {
- email: input.email,
- provider: CREDENTIAL_PROVIDER,
- });
- if (existing) {
- throw new TRPCNotFoundError('User already exists');
- }
-
- const userId = generateSecureId('user');
- const createdUser = await deps.db.user.create({
- data: {
- id: userId,
- email: input.email,
- firstName: input.firstName,
- lastName: input.lastName,
- name: toDisplayName(input.firstName, input.lastName),
- accounts: {
- create: {
- provider: CREDENTIAL_PROVIDER,
- accountId: userId,
- password: await hashPassword(input.password),
- },
- },
- },
- });
-
- if (input.inviteId) {
- await connectUserToOrganization(deps, {
- user: createdUser,
- inviteId: input.inviteId,
- });
- }
-
- const token = generateSessionToken();
- const session = await createSession(deps, token, createdUser.id);
- setSessionTokenCookie(deps.config, setCookie, token, session.expiresAt);
- return session;
-}
-
-export interface SignInEmailInput {
- email: string;
- password: string;
- inviteId?: string | null;
-}
-
-export type SignInEmailResult = { type: 'totp_required' } | { type: 'email' };
-
-export async function signInWithEmail(
- deps: ServiceDeps,
- input: SignInEmailInput,
- setCookie: ISetCookie,
- logger: Pick<Logger, 'error'>
-): Promise<SignInEmailResult> {
- const user = await getUserAccount(deps, {
- email: input.email,
- provider: CREDENTIAL_PROVIDER,
- });
-
- if (!user) {
- throw new TRPCNotFoundError('User does not exists');
- }
-
- // Anything but argon2 is a legacy row whose password was nulled.
- if (!user.account.password?.startsWith('$argon2')) {
- throw new TRPCBadRequestError(
- 'Reset your password, old password has expired'
- );
+ signInHeaders.set(INVITE_HEADER, input.inviteId);
}
-
- // Not trimmed: sign-up and reset hash the password as typed, so trimming
- // here would make a password with edge whitespace unusable.
- const validPassword = await verifyPasswordHash(
- user.account.password,
- input.password
+ return signInWithPassword(
+ deps.auth,
+ deps.config,
+ devLogin,
+ signInHeaders,
+ setCookie
);
- if (!validPassword) {
- throw new TRPCBadRequestError('Incorrect email or password');
- }
-
- const totp = await deps.db.userTotp.findUnique({
- where: { userId: user.id },
- });
- if (totp?.enabledAt) {
- const challengeId = generateSecureId('2fa');
- await deps.db.twoFactorChallenge.create({
- data: {
- id: challengeId,
- userId: user.id,
- expiresAt: new Date(
- Date.now() + TWO_FACTOR_CHALLENGE_TTL_SECONDS * 1000
- ),
- },
- });
- setCookie(TWO_FACTOR_COOKIE, challengeId, {
- maxAge: TWO_FACTOR_CHALLENGE_TTL_SECONDS,
- });
- // Carry the invite through the 2FA challenge so it can be consumed once
- // the user completes the second factor in `signInWithTotp`.
- if (input.inviteId) {
- setCookie(INVITE_COOKIE, input.inviteId, {
- maxAge: TWO_FACTOR_CHALLENGE_TTL_SECONDS,
- });
- }
- return { type: 'totp_required' };
- }
-
- const token = generateSessionToken();
- const session = await createSession(deps, token, user.id);
- setSessionTokenCookie(deps.config, setCookie, token, session.expiresAt);
- setLastAuthProviderCookie(deps.config, setCookie, 'email');
-
- if (input.inviteId) {
- await consumeInviteForUser(deps, user.id, input.inviteId, logger);
- }
-
- return { type: 'email' };
}
-export interface SignInTotpInput {
- code: string;
+export interface TwoFactorStatus {
+ enabled: boolean;
+ /** Two-factor is for password sign-ins; Google and GitHub run their own. */
+ hasPassword: boolean;
+ /** Had two-factor before sign-in moved to better-auth, and not since. */
+ wasReset: boolean;
}
-export async function signInWithTotp(
+export async function getTwoFactorStatus(
deps: ServiceDeps,
- input: SignInTotpInput,
- cookies: CookieReader,
- setCookie: ISetCookie,
- logger: Pick<Logger, 'error'>
-): Promise<{ type: 'email' }> {
- const challengeId = cookies.get(TWO_FACTOR_COOKIE);
- if (!challengeId) {
- throw new TRPCBadRequestError('No active two-factor challenge');
- }
-
- const challenge = await deps.db.twoFactorChallenge.findUnique({
- where: { id: challengeId },
- });
-
- if (!challenge || challenge.expiresAt < new Date()) {
- if (challenge) {
- await deps.db.twoFactorChallenge.delete({ where: { id: challenge.id } });
- }
- setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });
- throw new TRPCBadRequestError('Two-factor challenge has expired');
- }
-
- const totp = await deps.db.userTotp.findUnique({
- where: { userId: challenge.userId },
- });
- if (!totp?.enabledAt) {
- await deps.db.twoFactorChallenge.delete({ where: { id: challenge.id } });
- setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });
- throw new TRPCBadRequestError('Two-factor is not enabled');
- }
-
- const secret = decrypt(deps.config.encryptionKey, totp.secret);
- const isTotpCode = /^\d{6}$/.test(input.code.replace(/\s+/g, ''));
- let valid = false;
-
- if (isTotpCode) {
- valid = verifyTotpCode(secret, input.code);
- } else {
- const result = await consumeRecoveryCode({
- hashes: totp.recoveryCodes,
- input: input.code,
- });
- if (result.valid) {
- valid = true;
- await deps.db.userTotp.update({
- where: { userId: challenge.userId },
- data: { recoveryCodes: result.remaining },
- });
- }
- }
-
- if (!valid) {
- throw new TRPCBadRequestError('Invalid code');
- }
-
- await deps.db.twoFactorChallenge.delete({ where: { id: challenge.id } });
- setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });
-
- const token = generateSessionToken();
- const session = await createSession(deps, token, challenge.userId);
- setSessionTokenCookie(deps.config, setCookie, token, session.expiresAt);
- setLastAuthProviderCookie(deps.config, setCookie, 'email');
-
- const inviteId = cookies.get(INVITE_COOKIE);
- if (inviteId) {
- await consumeInviteForUser(deps, challenge.userId, inviteId, logger);
- setCookie(INVITE_COOKIE, '', { maxAge: 0 });
- }
-
- return { type: 'email' };
-}
-
-export async function getTotpStatus(deps: ServiceDeps, userId: string) {
- const [totp, emailAccount] = await Promise.all([
- deps.db.userTotp.findUnique({ where: { userId } }),
+ userId: string
+): Promise<TwoFactorStatus> {
+ const [user, credential, legacyTotp] = await Promise.all([
+ deps.db.user.findUniqueOrThrow({
+ where: { id: userId },
+ select: { twoFactorEnabled: true },
+ }),
deps.db.account.findFirst({
where: { userId, provider: CREDENTIAL_PROVIDER },
select: { id: true },
}),
+ deps.db.userTotp.findUnique({
+ where: { userId },
+ select: { enabledAt: true },
+ }),
]);
return {
- enabled: Boolean(totp?.enabledAt),
- enabledAt: totp?.enabledAt ?? null,
- remainingRecoveryCodes: totp?.recoveryCodes.length ?? 0,
- hasEmailProvider: Boolean(emailAccount),
+ enabled: user.twoFactorEnabled,
+ hasPassword: Boolean(credential),
+ wasReset: Boolean(legacyTotp?.enabledAt) && !user.twoFactorEnabled,
};
}
-export async function setupTotp(deps: ServiceDeps, userId: string) {
- const emailAccount = await deps.db.account.findFirst({
- where: { userId, provider: CREDENTIAL_PROVIDER },
- select: { id: true },
- });
- if (!emailAccount) {
- throw new TRPCBadRequestError(
- 'Two-factor authentication is only available for email/password sign-ins. Your account uses a social provider, which handles 2FA on its end.'
- );
- }
- const existing = await deps.db.userTotp.findUnique({ where: { userId } });
- if (existing?.enabledAt) {
- throw new TRPCBadRequestError(
- 'Two-factor is already enabled. Disable it first to re-configure.'
- );
- }
-
- const user = await deps.db.user.findUniqueOrThrow({
- where: { id: userId },
- select: { email: true },
- });
-
- const secret = generateTotpSecret();
- const otpauthUrl = buildOtpauthUrl({ secret, accountName: user.email });
- const qrDataUrl = await generateQrDataUrl(otpauthUrl);
-
- await deps.db.userTotp.upsert({
- where: { userId },
- create: {
- userId,
- secret: encrypt(deps.config.encryptionKey, secret),
- recoveryCodes: [],
- },
- update: {
- secret: encrypt(deps.config.encryptionKey, secret),
- recoveryCodes: [],
- enabledAt: null,
- },
- });
-
- return { otpauthUrl, qrDataUrl, secret };
-}
-
-export async function enableTotp(
- deps: ServiceDeps,
- userId: string,
- code: string
-) {
- const totp = await deps.db.userTotp.findUnique({ where: { userId } });
- if (!totp) {
- throw new TRPCNotFoundError('Start two-factor setup first');
- }
- if (totp.enabledAt) {
- throw new TRPCBadRequestError('Two-factor is already enabled');
- }
-
- const secret = decrypt(deps.config.encryptionKey, totp.secret);
- if (!verifyTotpCode(secret, code)) {
- throw new TRPCBadRequestError('Invalid code');
- }
-
- const recoveryCodes = generateRecoveryCodes();
- const hashed = await hashRecoveryCodes(recoveryCodes);
-
- await deps.db.userTotp.update({
- where: { userId },
- data: { enabledAt: new Date(), recoveryCodes: hashed },
- });
-
- return { recoveryCodes };
-}
-
-export async function disableTotp(
- deps: ServiceDeps,
- userId: string,
- code: string
-) {
- const totp = await deps.db.userTotp.findUnique({ where: { userId } });
- if (!totp?.enabledAt) {
- throw new TRPCBadRequestError('Two-factor is not enabled');
- }
-
- const secret = decrypt(deps.config.encryptionKey, totp.secret);
- const isTotpCode = /^\d{6}$/.test(code.replace(/\s+/g, ''));
- const valid = isTotpCode
- ? verifyTotpCode(secret, code)
- : (await consumeRecoveryCode({ hashes: totp.recoveryCodes, input: code }))
- .valid;
-
- if (!valid) {
- throw new TRPCBadRequestError('Invalid code');
- }
-
- await deps.db.userTotp.delete({ where: { userId } });
- await deps.db.twoFactorChallenge.deleteMany({ where: { userId } });
- return { disabled: true };
-}
-
-export async function regenerateTotpRecoveryCodes(
- deps: ServiceDeps,
- userId: string,
- code: string
-) {
- const totp = await deps.db.userTotp.findUnique({ where: { userId } });
- if (!totp?.enabledAt) {
- throw new TRPCBadRequestError('Two-factor is not enabled');
- }
- const secret = decrypt(deps.config.encryptionKey, totp.secret);
- if (!verifyTotpCode(secret, code)) {
- throw new TRPCBadRequestError('Invalid code');
- }
- const recoveryCodes = generateRecoveryCodes();
- const hashed = await hashRecoveryCodes(recoveryCodes);
- await deps.db.userTotp.update({
- where: { userId },
- data: { recoveryCodes: hashed },
- });
- return { recoveryCodes };
-}
-
-export interface ResetPasswordInput {
- token: string;
- password: string;
-}
-
-export async function resetPasswordWithToken(
- deps: ServiceDeps,
- input: ResetPasswordInput
-): Promise<true> {
- const resetPassword = await deps.db.resetPassword.findUnique({
- where: { id: input.token },
- });
-
- if (!resetPassword) {
- throw new TRPCNotFoundError('Reset password not found');
- }
- if (resetPassword.expiresAt < new Date()) {
- throw new TRPCNotFoundError('Reset password expired');
- }
-
- await deps.db.account.update({
- where: { id: resetPassword.accountId },
- data: { password: await hashPassword(input.password) },
- });
- await deps.db.resetPassword.delete({ where: { id: input.token } });
-
- return true;
-}
-
-export async function requestPasswordReset(
- deps: ServiceDeps,
- input: {
- email: string;
- }
-): Promise<true> {
- const user = await getUserAccount(deps, {
- email: input.email,
- provider: CREDENTIAL_PROVIDER,
- });
- // Deliberately not found-vs-found: always `true`, so the endpoint cannot be
- // used to enumerate registered emails.
- if (!user?.account.id) {
- return true;
- }
-
- await deps.db.resetPassword.deleteMany({
- where: { accountId: user.account.id },
- });
-
- const token = generateSecureId('pw');
- const expiresAt = new Date(Date.now() + RESET_PASSWORD_TTL_MS);
- await deps.db.resetPassword.create({
- data: { id: token, expiresAt, accountId: user.account.id },
- });
-
- await sendEmail('reset-password', {
- to: input.email,
- data: {
- url: `${deps.config.dashboardUrl}/reset-password?token=${token}`,
- },
- });
-
- return true;
-}
-
-export async function extendSessionCookie(
- deps: ServiceDeps,
- cookies: CookieReader,
- hasSession: boolean,
- setCookie: ISetCookie
-): Promise<{ extended: boolean; expiresAt?: Date }> {
- const token = cookies.get('session');
- if (!(hasSession && token)) {
- return { extended: false };
- }
-
- const session = await validateSessionToken(deps, token);
-
- if (session.session) {
- setSessionTokenCookie(
- deps.config,
- setCookie,
- token,
- session.session.expiresAt
- );
- return { extended: true, expiresAt: session.session.expiresAt };
- }
-
- return { extended: false };
-}
-
export interface SignInShareInput {
password: string;
shareId: string;
@@ -958,309 +381,3 @@ export async function signInToShare(
);
return true;
}
-
-export interface OAuthUser {
- id: string;
- email: string;
- firstName: string;
- lastName?: string;
-}
-
-/** Raised for every *expected* failure — the caller shows `.message` verbatim
- * in the `/login?error=` redirect. Anything else thrown is an unexpected bug
- * and the caller shows a generic message. */
-export class OAuthCallbackError extends Error {
- constructor(
- message: string,
- public readonly context?: Record<string, unknown>
- ) {
- super(message);
- this.name = 'OAuthCallbackError';
- }
-}
-
-async function fetchGithubEmail(accessToken: string): Promise<string | null> {
- const emailListRequest = new Request('https://api.github.com/user/emails');
- emailListRequest.headers.set('Authorization', `Bearer ${accessToken}`);
- const emailListResponse = await fetch(emailListRequest);
- const emailListResult: unknown = await emailListResponse.json();
- if (!Array.isArray(emailListResult) || emailListResult.length < 1) {
- return null;
- }
- let email: string | null = null;
- for (const emailRecord of emailListResult) {
- const emailParser = z.object({
- primary: z.boolean(),
- verified: z.boolean(),
- email: z.string(),
- });
- const emailResult = emailParser.safeParse(emailRecord);
- if (!emailResult.success) {
- continue;
- }
- if (emailResult.data.primary && emailResult.data.verified) {
- email = emailResult.data.email;
- }
- }
- return email;
-}
-
-export async function fetchGithubOAuthUser(
- config: CoreConfig,
- code: string
-): Promise<OAuthUser> {
- const tokens = await githubClient(config).validateAuthorizationCode(code);
- const accessToken = tokens.accessToken();
- const email = await fetchGithubEmail(accessToken);
- if (!email) {
- throw new OAuthCallbackError('GitHub email not found or not verified');
- }
-
- const userRequest = new Request('https://api.github.com/user');
- userRequest.headers.set('Authorization', `Bearer ${accessToken}`);
- const userResponse = await fetch(userRequest);
-
- const userSchema = z.object({
- id: z.number(),
- login: z.string(),
- name: z
- .string()
- .nullish()
- .transform((val) => val || ''),
- });
- const userJson = await userResponse.json();
- const userResult = userSchema.safeParse(userJson);
- if (!userResult.success) {
- throw new OAuthCallbackError('Error fetching Github user', {
- error: userResult.error,
- githubUser: userJson,
- });
- }
-
- return {
- id: String(userResult.data.id),
- email,
- firstName: userResult.data.name || userResult.data.login || '',
- };
-}
-
-export async function fetchGoogleOAuthUser(
- config: CoreConfig,
- code: string,
- codeVerifier: string
-): Promise<OAuthUser> {
- const tokens = await googleClient(config).validateAuthorizationCode(
- code,
- codeVerifier
- );
- const claims = Arctic.decodeIdToken(tokens.idToken());
-
- const claimsSchema = z.object({
- sub: z.string(),
- email: z.string(),
- email_verified: z.boolean(),
- given_name: z.string().optional(),
- family_name: z.string().optional(),
- });
- const claimsResult = claimsSchema.safeParse(claims);
- if (!claimsResult.success) {
- throw new OAuthCallbackError('Error fetching Google user', {
- error: claimsResult.error,
- claims,
- });
- }
- if (!claimsResult.data.email_verified) {
- throw new OAuthCallbackError('Email not verified with Google');
- }
-
- return {
- id: claimsResult.data.sub,
- email: claimsResult.data.email,
- firstName: claimsResult.data.given_name || '',
- lastName: claimsResult.data.family_name || '',
- };
-}
-
-/**
- * Checked by the caller BEFORE exchanging `code` for tokens, so a forged
- * `state` never costs an IdP round-trip.
- */
-export function assertOAuthState(
- provider: 'github' | 'google',
- state: string,
- storedState: string | null
-): void {
- if (!storedState || state !== storedState) {
- throw new OAuthCallbackError('OAuth state mismatch', {
- provider,
- hasStoredState: Boolean(storedState),
- });
- }
-}
-
-export interface CompleteOAuthCallbackInput {
- provider: 'github' | 'google';
- oauthUser: OAuthUser;
- inviteId: string | null | undefined;
- setCookie: ISetCookie;
- logger: Pick<Logger, 'error'>;
-}
-
-export async function completeOAuthCallback(
- deps: ServiceDeps,
- input: CompleteOAuthCallbackInput
-): Promise<void> {
- const { provider, oauthUser, inviteId, setCookie, logger } = input;
-
- const account = await deps.db.account.findFirst({
- where: {
- OR: [
- { provider, providerId: oauthUser.id },
- // During migration
- { provider, providerId: null, email: oauthUser.email },
- { provider: 'oauth', user: { email: oauthUser.email } },
- ],
- },
- });
-
- if (account) {
- await completeExistingOAuthUser(deps, {
- account,
- oauthUser,
- provider,
- inviteId,
- setCookie,
- logger,
- });
- return;
- }
-
- await completeNewOAuthUser(deps, {
- oauthUser,
- provider,
- inviteId,
- setCookie,
- logger,
- });
-}
-
-async function completeExistingOAuthUser(
- deps: ServiceDeps,
- {
- account,
- oauthUser,
- provider,
- inviteId,
- setCookie,
- logger,
- }: {
- account: { id: string; userId: string };
- oauthUser: OAuthUser;
- provider: 'github' | 'google';
- inviteId: string | null | undefined;
- setCookie: ISetCookie;
- logger: Pick<Logger, 'error'>;
- }
-) {
- const sessionToken = generateSessionToken();
- const session = await createSession(deps, sessionToken, account.userId);
-
- await deps.db.account.update({
- where: { id: account.id },
- data: {
- provider,
- providerId: oauthUser.id,
- accountId: oauthUser.id,
- email: oauthUser.email,
- },
- });
-
- if (inviteId) {
- await consumeInviteForUser(deps, account.userId, inviteId, logger);
- }
-
- setSessionTokenCookie(
- deps.config,
- setCookie,
- sessionToken,
- session.expiresAt
- );
- setLastAuthProviderCookie(deps.config, setCookie, provider);
-}
-
-async function completeNewOAuthUser(
- deps: ServiceDeps,
- {
- oauthUser,
- provider,
- inviteId,
- setCookie,
- logger,
- }: {
- oauthUser: OAuthUser;
- provider: 'github' | 'google';
- inviteId: string | null | undefined;
- setCookie: ISetCookie;
- logger: Pick<Logger, 'error'>;
- }
-) {
- const existingUser = await deps.db.user.findFirst({
- where: { email: oauthUser.email },
- });
- if (existingUser) {
- throw new OAuthCallbackError(
- 'Please sign in using your original authentication method',
- { existingUser, oauthUser, provider }
- );
- }
-
- // Enforce the self-hosting registration policy here rather than before the
- // IdP redirect — this is the first point where we know the user is new, so
- // returning users are never caught by it.
- if (!(await getIsRegistrationAllowed(deps, inviteId))) {
- // Deliberately no `oauthUser` here — this rejects people who are not
- // users, so their email and name shouldn't land in application logs.
- throw new OAuthCallbackError('Registrations are not allowed', {
- provider,
- inviteId,
- });
- }
-
- const user = await deps.db.user.create({
- data: {
- email: oauthUser.email,
- firstName: oauthUser.firstName,
- lastName: oauthUser.lastName,
- name: toDisplayName(oauthUser.firstName, oauthUser.lastName),
- emailVerified: true,
- accounts: {
- create: {
- provider,
- providerId: oauthUser.id,
- accountId: oauthUser.id,
- },
- },
- },
- });
-
- if (inviteId) {
- try {
- await connectUserToOrganization(deps, { user, inviteId });
- } catch (error) {
- logger.error(
- { error, inviteId, user },
- 'error connecting user to organization'
- );
- }
- }
-
- const sessionToken = generateSessionToken();
- const session = await createSession(deps, sessionToken, user.id);
- setSessionTokenCookie(
- deps.config,
- setCookie,
- sessionToken,
- session.expiresAt
- );
- setLastAuthProviderCookie(deps.config, setCookie, provider);
-}
diff --git a/packages/core/src/modules/auth/src/better-auth.test.ts b/packages/core/src/modules/auth/src/better-auth.test.ts
new file mode 100644
index 000000000..3a368e39a
--- /dev/null
+++ b/packages/core/src/modules/auth/src/better-auth.test.ts
@@ -0,0 +1,525 @@
+// The policies we hang on better-auth, run through its real handler against the
+// test database: who may register, where invites are consumed, what stays
+// unmounted.
+
+import { afterAll, beforeAll, expect, mock, test } from 'bun:test';
+import { testCoreConfig } from '../../../../test/config-fixture';
+import { testServiceDeps } from '../../../../test/service-deps';
+import type { ServiceDeps } from '../../../services';
+import { INVITE_HEADER } from '../auth.constants';
+
+const sentEmails: { template: string; to: string; url: string }[] = [];
+const sendEmail = mock(
+ (template: string, options: { to: string; data: { url: string } }) => {
+ sentEmails.push({ template, to: options.to, url: options.data.url });
+ return Promise.resolve();
+ }
+);
+mock.module('../../../clients/email', () => ({ sendEmail }));
+
+let createAuth: typeof import('./better-auth').createAuth;
+let hashPassword: typeof import('./password').hashPassword;
+let constants: typeof import('./better-auth');
+
+const PREFIX = 'ba-test';
+/** Creating and migrating the test databases on a fresh runner. */
+const BOOTSTRAP_TIMEOUT_MS = 30_000;
+const DASHBOARD_URL = 'http://dashboard.test';
+const ORG_ID = `${PREFIX}-org`;
+const PASSWORD = 'correct horse battery';
+const EXISTING_EMAIL = `${PREFIX}[email protected]`;
+const EXISTING_ID = `${PREFIX}-existing`;
+const TWO_FACTOR_EMAIL = `${PREFIX}[email protected]`;
+const TWO_FACTOR_ID = `${PREFIX}-2fa`;
+
+let deps: ServiceDeps;
+let ipCounter = 0;
+
+function authWith(auth: Partial<ServiceDeps['config']['auth']> = {}) {
+ const config = testCoreConfig({ dashboardUrl: DASHBOARD_URL });
+ const instance = createAuth({
+ db: deps.db,
+ logger: deps.logger,
+ redis: deps.redis,
+ config: {
+ ...config,
+ auth: {
+ ...config.auth,
+ secret: 'test-auth-secret-at-least-32-characters',
+ trustedOrigins: [DASHBOARD_URL],
+ ...auth,
+ },
+ },
+ });
+ if (!instance) {
+ throw new Error('createAuth returned null with a secret');
+ }
+ return instance;
+}
+
+/** A fresh client IP per call, so better-auth's sign-in limit never trips. */
+function call(
+ auth: ReturnType<typeof authWith>,
+ path: string,
+ body: unknown,
+ headers: Record<string, string> = {}
+): Promise<Response> {
+ ipCounter += 1;
+ return auth.handler(
+ new Request(`http://api.test${constants.AUTH_BASE_PATH}${path}`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ origin: DASHBOARD_URL,
+ [constants.TRUSTED_IP_HEADER]: `10.0.0.${ipCounter}`,
+ ...headers,
+ },
+ body: JSON.stringify(body),
+ })
+ );
+}
+
+function lastLoginCookie(response: Response): string | undefined {
+ const header = response.headers
+ .getSetCookie()
+ .find((cookie) => cookie.startsWith('last-auth-provider='));
+ return header?.slice('last-auth-provider='.length, header.indexOf(';'));
+}
+
+function cookieNames(response: Response): string[] {
+ return response.headers
+ .getSetCookie()
+ .filter((cookie) => !cookie.includes('Max-Age=0'))
+ .map((cookie) => cookie.slice(0, cookie.indexOf('=')));
+}
+
+async function createInvite(id: string, email: string) {
+ await deps.db.invite.create({
+ data: {
+ id,
+ email,
+ organizationId: ORG_ID,
+ createdById: EXISTING_ID,
+ role: 'viewer',
+ expiresAt: new Date(Date.now() + 60 * 60 * 1000),
+ },
+ });
+}
+
+function membership(userId: string) {
+ return deps.db.member.findFirst({
+ where: { organizationId: ORG_ID, userId },
+ select: { role: true },
+ });
+}
+
+async function cleanUp() {
+ await deps.db.organization.deleteMany({ where: { id: ORG_ID } });
+ await deps.db.user.deleteMany({
+ where: { email: { startsWith: `${PREFIX}-` } },
+ });
+}
+
+beforeAll(async () => {
+ // A fresh CI shard has no test databases until a suite creates them.
+ const { bootstrapTestDatabases } = await import(
+ '../../../../../../test/bootstrap-databases'
+ );
+ await bootstrapTestDatabases();
+ ({ createAuth } = await import('./better-auth'));
+ ({ hashPassword } = await import('./password'));
+ constants = await import('./better-auth');
+ deps = await testServiceDeps();
+ await cleanUp();
+ const hash = await hashPassword(PASSWORD);
+ for (const [id, email, twoFactorEnabled] of [
+ [EXISTING_ID, EXISTING_EMAIL, false],
+ [TWO_FACTOR_ID, TWO_FACTOR_EMAIL, true],
+ ] as const) {
+ await deps.db.user.create({
+ data: {
+ id,
+ email,
+ name: 'Ada',
+ twoFactorEnabled,
+ accounts: {
+ create: { provider: 'credential', accountId: id, password: hash },
+ },
+ },
+ });
+ }
+ await deps.db.twoFactor.create({
+ data: { userId: TWO_FACTOR_ID, secret: 'unused', backupCodes: 'unused' },
+ });
+ await deps.db.organization.create({
+ data: {
+ id: ORG_ID,
+ name: 'Better auth test',
+ createdByUserId: EXISTING_ID,
+ },
+ });
+}, BOOTSTRAP_TIMEOUT_MS);
+
+afterAll(cleanUp);
+
+test('sign-up creates a credential user with our hash and a joined name', async () => {
+ const email = `${PREFIX}[email protected]`;
+ const response = await call(authWith(), '/sign-up/email', {
+ email,
+ password: PASSWORD,
+ name: 'ignored',
+ firstName: 'Grace',
+ lastName: 'Hopper',
+ });
+
+ expect(response.status).toBe(200);
+ expect(cookieNames(response)).toContain(constants.AUTH_SESSION_COOKIE);
+ const user = await deps.db.user.findUniqueOrThrow({
+ where: { email },
+ include: { accounts: true },
+ });
+ expect(user.name).toBe('Grace Hopper');
+ expect(user.accounts[0]?.provider).toBe('credential');
+ expect(user.accounts[0]?.password?.startsWith('$argon2')).toBe(true);
+});
+
+test('sign-up is refused when registration is closed and there is no invite', async () => {
+ const email = `${PREFIX}[email protected]`;
+ const response = await call(
+ authWith({ allowRegistration: false }),
+ '/sign-up/email',
+ { email, password: PASSWORD, name: 'Closed' }
+ );
+
+ expect(response.status).toBe(403);
+ expect(await response.json()).toMatchObject({
+ code: 'REGISTRATION_NOT_ALLOWED',
+ });
+ expect(await deps.db.user.findUnique({ where: { email } })).toBeNull();
+});
+
+test('an invite opens closed registration and is consumed by the new user', async () => {
+ const email = `${PREFIX}[email protected]`;
+ await createInvite(`${PREFIX}-invite-signup`, email);
+
+ const response = await call(
+ authWith({ allowRegistration: false, allowInvitation: true }),
+ '/sign-up/email',
+ { email, password: PASSWORD, name: 'Invited' },
+ { [INVITE_HEADER]: `${PREFIX}-invite-signup` }
+ );
+
+ expect(response.status).toBe(200);
+ const user = await deps.db.user.findUniqueOrThrow({ where: { email } });
+ expect(await membership(user.id)).toEqual({ role: 'viewer' });
+ expect(
+ await deps.db.invite.findUnique({
+ where: { id: `${PREFIX}-invite-signup` },
+ })
+ ).toBeNull();
+});
+
+test('signing in with an invite joins the organization', async () => {
+ await createInvite(`${PREFIX}-invite-signin`, EXISTING_EMAIL);
+
+ const response = await call(
+ authWith(),
+ '/sign-in/email',
+ { email: EXISTING_EMAIL, password: PASSWORD },
+ { [INVITE_HEADER]: `${PREFIX}-invite-signin` }
+ );
+
+ expect(response.status).toBe(200);
+ expect(await membership(EXISTING_ID)).toEqual({ role: 'viewer' });
+});
+
+test('a password with edge whitespace signs in exactly as it was set', async () => {
+ const email = `${PREFIX}[email protected]`;
+ const auth = authWith();
+ await call(auth, '/sign-up/email', {
+ email,
+ password: ' spaced out ',
+ name: 'Spaces',
+ });
+
+ const trimmed = await call(auth, '/sign-in/email', {
+ email,
+ password: 'spaced out',
+ });
+ const exact = await call(auth, '/sign-in/email', {
+ email,
+ password: ' spaced out ',
+ });
+
+ expect(trimmed.status).toBe(401);
+ expect(exact.status).toBe(200);
+});
+
+test('a two-factor sign-in has no session yet and keeps the invite for the second step', async () => {
+ await createInvite(`${PREFIX}-invite-2fa`, TWO_FACTOR_EMAIL);
+
+ const response = await call(
+ authWith(),
+ '/sign-in/email',
+ { email: TWO_FACTOR_EMAIL, password: PASSWORD },
+ { [INVITE_HEADER]: `${PREFIX}-invite-2fa` }
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ twoFactorRedirect: true });
+ expect(cookieNames(response)).toContain('inviteId');
+ expect(cookieNames(response)).not.toContain(constants.AUTH_SESSION_COOKIE);
+ expect(await membership(TWO_FACTOR_ID)).toBeNull();
+});
+
+test('a reset link goes to the dashboard and its token sets the new password', async () => {
+ const auth = authWith();
+ sentEmails.length = 0;
+ await call(auth, '/request-password-reset', {
+ email: EXISTING_EMAIL,
+ redirectTo: `${DASHBOARD_URL}/reset-password`,
+ });
+
+ expect(sendEmail).toHaveBeenCalled();
+ const url = new URL(sentEmails[0]?.url ?? '');
+ expect(url.origin + url.pathname).toBe(`${DASHBOARD_URL}/reset-password`);
+ const token = url.searchParams.get('token');
+
+ const reset = await call(auth, '/reset-password', {
+ token,
+ newPassword: 'a brand new password',
+ });
+ const signIn = await call(auth, '/sign-in/email', {
+ email: EXISTING_EMAIL,
+ password: 'a brand new password',
+ });
+
+ expect(reset.status).toBe(200);
+ expect(signIn.status).toBe(200);
+});
+
+test('endpoints the dashboard does not use stay unmounted', async () => {
+ const auth = authWith();
+ for (const path of ['/list-sessions', '/update-user', '/delete-user']) {
+ expect((await call(auth, path, {})).status).toBe(404);
+ }
+});
+
+const GOOGLE = {
+ clientId: 'google-client',
+ clientSecret: 'google-secret',
+ redirectUri: 'http://api.test/oauth/google/callback',
+};
+
+function unsignedIdToken(claims: Record<string, unknown>): string {
+ const encode = (value: unknown) =>
+ Buffer.from(JSON.stringify(value)).toString('base64url');
+ return `${encode({ alg: 'none', typ: 'JWT' })}.${encode(claims)}.signature`;
+}
+
+/** Stubs Google's token endpoint so the callback sees this profile. */
+interface GoogleProfile {
+ sub: string;
+ email: string;
+ emailVerified?: boolean;
+}
+
+function stubGoogle({ emailVerified = true, ...profile }: GoogleProfile) {
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async (
+ input: Request | string | URL,
+ init?: RequestInit
+ ) => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (!url.startsWith('https://oauth2.googleapis.com/token')) {
+ return realFetch(input, init);
+ }
+ return Response.json({
+ access_token: 'access',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ id_token: unsignedIdToken({
+ ...profile,
+ email_verified: emailVerified,
+ given_name: 'Ada',
+ family_name: 'Lovelace',
+ iss: 'https://accounts.google.com',
+ aud: GOOGLE.clientId,
+ exp: Math.floor(Date.now() / 1000) + 3600,
+ }),
+ });
+ }) as typeof fetch;
+ return () => {
+ globalThis.fetch = realFetch;
+ };
+}
+
+/** Starts a Google sign-in, then answers its callback; returns where it lands. */
+async function googleSignIn(
+ auth: ReturnType<typeof authWith>,
+ profile: GoogleProfile,
+ additionalData?: Record<string, string>
+): Promise<{ location: URL; response: Response }> {
+ const start = await call(auth, '/sign-in/social', {
+ provider: 'google',
+ callbackURL: DASHBOARD_URL,
+ errorCallbackURL: `${DASHBOARD_URL}/login`,
+ additionalData,
+ });
+ const { url } = (await start.json()) as { url: string };
+ const state = new URL(url).searchParams.get('state') ?? '';
+ const cookie = start.headers
+ .getSetCookie()
+ .map((header) => header.slice(0, header.indexOf(';')))
+ .join('; ');
+ const restore = stubGoogle(profile);
+ try {
+ const response = await auth.handler(
+ new Request(
+ `http://api.test${constants.AUTH_BASE_PATH}/callback/google?code=code&state=${state}`,
+ { headers: { cookie, [constants.TRUSTED_IP_HEADER]: '10.1.0.1' } }
+ )
+ );
+ return {
+ response,
+ location: new URL(response.headers.get('location') ?? '', DASHBOARD_URL),
+ };
+ } finally {
+ restore();
+ }
+}
+
+test('Google sends the browser to the redirect URI registered at Google', async () => {
+ const start = await call(authWith({ google: GOOGLE }), '/sign-in/social', {
+ provider: 'google',
+ callbackURL: DASHBOARD_URL,
+ });
+ const { url } = (await start.json()) as { url: string };
+ expect(new URL(url).searchParams.get('redirect_uri')).toBe(
+ GOOGLE.redirectUri
+ );
+});
+
+test('a bulk-imported oauth user signing in with Google gets the account linked', async () => {
+ const email = `${PREFIX}[email protected]`;
+ const user = await deps.db.user.create({
+ data: {
+ email,
+ emailVerified: true,
+ accounts: { create: { provider: 'oauth' } },
+ },
+ });
+
+ const { location, response } = await googleSignIn(
+ authWith({ google: GOOGLE }),
+ {
+ sub: 'google-imported',
+ email,
+ }
+ );
+
+ expect(location.toString()).toBe(`${DASHBOARD_URL}/`);
+ expect(lastLoginCookie(response)).toBe('google');
+ const google = await deps.db.account.findFirst({
+ where: { userId: user.id, provider: 'google' },
+ });
+ expect(google?.accountId).toBe('google-imported');
+});
+
+test('a password-only user is not joined by a Google sign-in with the same email', async () => {
+ const { location } = await googleSignIn(authWith({ google: GOOGLE }), {
+ sub: 'google-existing',
+ email: EXISTING_EMAIL,
+ });
+
+ expect(location.pathname).toBe('/login');
+ expect(location.searchParams.get('error')).toBe('account_not_linked');
+ expect(
+ await deps.db.account.count({
+ where: { userId: EXISTING_ID, provider: 'google' },
+ })
+ ).toBe(0);
+});
+
+test('a new Google user is refused when registration is closed', async () => {
+ const email = `${PREFIX}[email protected]`;
+ const { location } = await googleSignIn(
+ authWith({ google: GOOGLE, allowRegistration: false }),
+ { sub: 'google-new', email }
+ );
+
+ expect(location.pathname).toBe('/login');
+ expect(location.searchParams.get('error')).toBe('REGISTRATION_NOT_ALLOWED');
+ expect(await deps.db.user.findUnique({ where: { email } })).toBeNull();
+});
+
+test('a Google sign-up carries its invite through the OAuth state', async () => {
+ const email = `${PREFIX}[email protected]`;
+ await createInvite(`${PREFIX}-invite-google`, email);
+
+ const { location, response } = await googleSignIn(
+ authWith({ google: GOOGLE, allowRegistration: false }),
+ { sub: 'google-invited', email },
+ { inviteId: `${PREFIX}-invite-google` }
+ );
+
+ expect(location.toString()).toBe(`${DASHBOARD_URL}/`);
+ expect(lastLoginCookie(response)).toBe('google');
+ const user = await deps.db.user.findUniqueOrThrow({ where: { email } });
+ expect(user.firstName).toBe('Ada');
+ expect(user.name).toBe('Ada Lovelace');
+ expect(await membership(user.id)).toEqual({ role: 'viewer' });
+});
+
+test('an unverified Google email does not join the user who owns it', async () => {
+ const email = `${PREFIX}[email protected]`;
+ const user = await deps.db.user.create({
+ data: {
+ email,
+ emailVerified: true,
+ accounts: { create: { provider: 'oauth' } },
+ },
+ });
+
+ const { location } = await googleSignIn(authWith({ google: GOOGLE }), {
+ sub: 'google-unverified-link',
+ email,
+ emailVerified: false,
+ });
+
+ expect(location.pathname).toBe('/login');
+ expect(location.searchParams.get('error')).toBe('unable_to_get_user_info');
+ expect(
+ await deps.db.account.count({
+ where: { userId: user.id, provider: 'google' },
+ })
+ ).toBe(0);
+});
+
+test('an unverified Google email cannot sign up', async () => {
+ const email = `${PREFIX}[email protected]`;
+ const { location } = await googleSignIn(authWith({ google: GOOGLE }), {
+ sub: 'google-unverified-new',
+ email,
+ emailVerified: false,
+ });
+
+ expect(location.searchParams.get('error')).toBe('unable_to_get_user_info');
+ expect(await deps.db.user.findUnique({ where: { email } })).toBeNull();
+});
+
+test('GitHub asks only for the scope users already granted', async () => {
+ const github = {
+ clientId: 'github-client',
+ clientSecret: 'github-secret',
+ redirectUri: 'http://api.test/oauth/github/callback',
+ };
+ const start = await call(authWith({ github }), '/sign-in/social', {
+ provider: 'github',
+ callbackURL: DASHBOARD_URL,
+ });
+ const { url } = (await start.json()) as { url: string };
+ const params = new URL(url).searchParams;
+ expect(params.get('scope')).toBe('user:email');
+ expect(params.get('redirect_uri')).toBe(github.redirectUri);
+});
diff --git a/packages/core/src/modules/auth/src/better-auth.ts b/packages/core/src/modules/auth/src/better-auth.ts
index cbc121e0f..d29480e60 100644
--- a/packages/core/src/modules/auth/src/better-auth.ts
+++ b/packages/core/src/modules/auth/src/better-auth.ts
@@ -1,56 +1,259 @@
-// better-auth, installed but inert: only `/get-session` answers over HTTP and
-// no flow creates users or sessions through it yet. What it does do is read
-// its own session cookie, which `resolveSession` hands out to legacy sessions
-// as they are used, so the switch of sign-in to better-auth signs nobody out.
+// Sign-in, sign-up, password reset and two-factor run on better-auth. Legacy
+// `session` cookies still resolve (see `http/session.ts`) and are handed
+// better-auth's cookie on the way out, until PR 4 drops them.
import type { Session, User } from '@openpanel/db/src/prisma-client';
import { APIError, type BetterAuthPlugin, betterAuth } from 'better-auth';
import { prismaAdapter } from 'better-auth/adapters/prisma';
+import { createAuthMiddleware, getOAuthState } from 'better-auth/api';
import { parseSetCookieHeader } from 'better-auth/cookies';
import { makeSignature } from 'better-auth/crypto';
+import type { OAuth2Tokens } from 'better-auth/oauth2';
+import { lastLoginMethod, twoFactor } from 'better-auth/plugins';
+import {
+ github as githubProvider,
+ google as googleProvider,
+} from 'better-auth/social-providers';
+import { sendEmail } from '../../../clients/email';
import type { CoreConfig } from '../../../config';
-import type { Db } from '../../../context';
+import type { Db, RedisClient } from '../../../context';
import type { Logger } from '../../../logger';
import type { ISetCookie } from '../../../shared/cookie';
+import { connectUserToOrganization } from '../../organization/organization.service';
+import { INVITE_HEADER } from '../auth.constants';
import { cookieOptions } from './constants';
import { hashPassword, verifyPasswordHash } from './password';
+import { getIsRegistrationAllowed } from './registration';
import { generateSessionToken } from './token';
export const AUTH_BASE_PATH = '/api/auth';
const COOKIE_PREFIX = 'openpanel';
/** `${COOKIE_PREFIX}.session_token`, which is how better-auth names it. */
export const AUTH_SESSION_COOKIE = `${COOKIE_PREFIX}.session_token`;
+/** Set by the HTTP mount from the trusted resolver; any incoming value is replaced. */
+export const TRUSTED_IP_HEADER = 'x-openpanel-trusted-ip';
+/** Holds the invite while a two-factor challenge is pending. */
+const INVITE_COOKIE = 'inviteId';
+/** Where a session can start, so where an invite is consumed. */
+const SIGN_IN_PATHS = ['/sign-in/', '/sign-up/', '/callback/', '/two-factor/'];
+const LAST_LOGIN_METHOD_COOKIE = 'last-auth-provider';
-// The legacy session's lifetime and renewal rule, so a session keeps its
-// expiry whichever cookie resolved it.
const SESSION_EXPIRES_IN_SECONDS = 60 * 60 * 24 * 30;
const SESSION_UPDATE_AGE_SECONDS = 60 * 60 * 24 * 15;
+const RESET_PASSWORD_TOKEN_SECONDS = 60 * 10;
+const TWO_FACTOR_CHALLENGE_SECONDS = 60 * 10;
+const LAST_LOGIN_METHOD_MAX_AGE_SECONDS = 60 * 60 * 24 * 365;
+const RATE_LIMIT_WINDOW_SECONDS = 60;
+const RATE_LIMIT_MAX = 100;
+const MIN_PASSWORD_LENGTH = 8;
+const KEY_MISSING = -2;
+const MAX_PASSWORD_LENGTH = 128;
-const OPEN_PATHS = new Set(['/get-session', '/ok']);
+/** What the dashboard calls. Everything else better-auth mounts answers 404. */
+const EXPOSED_PATHS = new Set([
+ '/ok',
+ '/error',
+ '/get-session',
+ '/sign-in/email',
+ '/sign-in/social',
+ '/sign-up/email',
+ '/sign-out',
+ '/request-password-reset',
+ '/reset-password',
+]);
+const EXPOSED_PREFIXES = ['/callback/', '/two-factor/'];
interface AuthDeps {
db: Db;
config: CoreConfig;
logger: Logger;
+ redis: RedisClient;
}
-/** Answers 404 for everything but the open paths until sign-in moves here. */
-const inertPlugin = {
- id: 'openpanel-inert',
+function isExposedPath(path: string): boolean {
+ return (
+ EXPOSED_PATHS.has(path) ||
+ EXPOSED_PREFIXES.some((prefix) => path.startsWith(prefix))
+ );
+}
+
+const exposedPathsPlugin = {
+ id: 'openpanel-exposed-paths',
onRequest: async (request: Request) => {
const path = new URL(request.url).pathname.slice(AUTH_BASE_PATH.length);
- if (OPEN_PATHS.has(path)) {
+ if (isExposedPath(path)) {
return;
}
return { response: new Response('Not Found', { status: 404 }) };
},
} satisfies BetterAuthPlugin;
-function buildAuth({ db, config, logger }: AuthDeps, secret: string) {
+interface InviteSource {
+ headers?: Headers;
+ getCookie: (name: string) => string | null | undefined;
+}
+
+/** The invite rides a header (email), the OAuth state (social) or a cookie (2FA). */
+async function readInviteId(ctx: InviteSource): Promise<string | undefined> {
+ const fromHeader = ctx.headers?.get(INVITE_HEADER);
+ if (fromHeader) {
+ return fromHeader;
+ }
+ const state = await getOAuthState().catch(() => null);
+ const fromState = state?.inviteId;
+ if (typeof fromState === 'string' && fromState) {
+ return fromState;
+ }
+ return ctx.getCookie(INVITE_COOKIE) ?? undefined;
+}
+
+function invitePlugin(deps: AuthDeps) {
+ return {
+ id: 'openpanel-invite',
+ hooks: {
+ after: [
+ {
+ matcher: (ctx: { path?: string }) =>
+ SIGN_IN_PATHS.some((prefix) => ctx.path?.startsWith(prefix)),
+ handler: createAuthMiddleware(async (ctx) => {
+ const inviteId = await readInviteId(ctx);
+ if (!inviteId) {
+ return;
+ }
+ const signedIn = ctx.context.newSession;
+ if (!signedIn) {
+ // A password sign-in that now waits for a second factor.
+ if (ctx.path === '/sign-in/email') {
+ ctx.setCookie(INVITE_COOKIE, inviteId, {
+ ...cookieOptions(deps.config),
+ maxAge: TWO_FACTOR_CHALLENGE_SECONDS,
+ });
+ }
+ return;
+ }
+ // Best effort: an expired invite must not undo the sign-in.
+ await connectUserToOrganization(deps, {
+ user: signedIn.user,
+ inviteId,
+ }).catch((error: unknown) => {
+ deps.logger.error(
+ { err: error, userId: signedIn.user.id, inviteId },
+ 'Failed to connect user to organization via invite'
+ );
+ });
+ if (ctx.getCookie(INVITE_COOKIE)) {
+ ctx.setCookie(INVITE_COOKIE, '', {
+ ...cookieOptions(deps.config),
+ maxAge: 0,
+ });
+ }
+ }),
+ },
+ ],
+ },
+ } satisfies BetterAuthPlugin;
+}
+
+/** One counter per key, shared by every API process. */
+function redisRateLimitStorage(redis: RedisClient) {
+ return {
+ consume: async (key: string, rule: { window: number; max: number }) => {
+ const redisKey = `rl:auth:${key}`;
+ const results = await redis
+ .pipeline()
+ .incr(redisKey)
+ .ttl(redisKey)
+ .exec();
+ const hits = Number(results?.[0]?.[1] ?? 1);
+ let ttl = Number(results?.[1]?.[1] ?? KEY_MISSING);
+ // The window opens on the first hit; a counter without an expiry would
+ // lock the caller out for good.
+ if (hits === 1 || ttl < 0) {
+ await redis.expire(redisKey, rule.window);
+ ttl = rule.window;
+ }
+ if (hits <= rule.max) {
+ return { allowed: true, retryAfter: null };
+ }
+ return { allowed: false, retryAfter: ttl };
+ },
+ };
+}
+
+interface ProviderUserInfo {
+ user: { emailVerified: boolean };
+}
+
+/**
+ * No user unless the provider verified the email, so nobody signs in or links
+ * on an address they never proved they own. better-auth turns `null` into
+ * `?error=unable_to_get_user_info`.
+ */
+function requireVerifiedEmail<T extends ProviderUserInfo>(
+ getUserInfo: (token: OAuth2Tokens) => Promise<T | null>
+) {
+ return async (token: OAuth2Tokens): Promise<T | null> => {
+ const info = await getUserInfo(token);
+ return info?.user.emailVerified ? info : null;
+ };
+}
+
+function socialProviders(config: CoreConfig) {
+ const { google, github } = config.auth;
+ const googleOptions = {
+ clientId: google.clientId,
+ clientSecret: google.clientSecret,
+ // The URI registered at Google; its legacy path forwards here.
+ redirectURI: google.redirectUri,
+ mapProfileToUser: (profile: {
+ given_name?: string;
+ family_name?: string;
+ }) => ({
+ firstName: profile.given_name ?? '',
+ lastName: profile.family_name ?? '',
+ }),
+ };
+ const githubOptions = {
+ clientId: github.clientId,
+ clientSecret: github.clientSecret,
+ redirectURI: github.redirectUri,
+ // What users already granted: profile reads need no scope, so asking for
+ // better-auth's default `read:user` would re-prompt every existing user.
+ disableDefaultScope: true,
+ scope: ['user:email'],
+ mapProfileToUser: (profile: { name?: string | null; login: string }) => ({
+ firstName: profile.name || profile.login,
+ lastName: '',
+ }),
+ };
+ return {
+ ...(google.clientId &&
+ google.redirectUri && {
+ google: {
+ ...googleOptions,
+ getUserInfo: requireVerifiedEmail(
+ googleProvider(googleOptions).getUserInfo
+ ),
+ },
+ }),
+ ...(github.clientId &&
+ github.redirectUri && {
+ github: {
+ ...githubOptions,
+ getUserInfo: requireVerifiedEmail(
+ githubProvider(githubOptions).getUserInfo
+ ),
+ },
+ }),
+ };
+}
+
+function buildAuth(deps: AuthDeps, secret: string) {
+ const { db, config, logger, redis } = deps;
return betterAuth({
secret,
basePath: AUTH_BASE_PATH,
- trustedOrigins: config.dashboardUrl ? [config.dashboardUrl] : [],
+ trustedOrigins: config.auth.trustedOrigins,
database: prismaAdapter(db, { provider: 'postgresql' }),
telemetry: { enabled: false },
logger: {
@@ -59,28 +262,71 @@ function buildAuth({ db, config, logger }: AuthDeps, secret: string) {
logger[log]({ args }, `better-auth: ${message}`);
},
},
+ onAPIError: { errorURL: `${config.dashboardUrl}/login` },
user: {
additionalFields: {
- firstName: { type: 'string', required: false, input: false },
- lastName: { type: 'string', required: false, input: false },
+ firstName: { type: 'string', required: false, input: true },
+ lastName: { type: 'string', required: false, input: true },
deletedAt: { type: 'date', required: false, input: false },
},
},
account: {
// Our column for the provider's name. `providerId` is the legacy IdP id.
fields: { providerId: 'provider' },
+ // A Google or GitHub sign-in (verified email only, see
+ // `requireVerifiedEmail`) joins the user who owns that email if that
+ // user is verified too. Password-only users are never verified, so never
+ // joined this way.
+ accountLinking: { enabled: true },
},
session: {
expiresIn: SESSION_EXPIRES_IN_SECONDS,
updateAge: SESSION_UPDATE_AGE_SECONDS,
},
+ socialProviders: socialProviders(config),
emailAndPassword: {
enabled: true,
- disableSignUp: true,
+ minPasswordLength: MIN_PASSWORD_LENGTH,
+ maxPasswordLength: MAX_PASSWORD_LENGTH,
+ resetPasswordTokenExpiresIn: RESET_PASSWORD_TOKEN_SECONDS,
password: {
hash: hashPassword,
verify: ({ hash, password }) => verifyPasswordHash(hash, password),
},
+ sendResetPassword: async ({ user, token }) => {
+ const url = new URL('/reset-password', config.dashboardUrl);
+ url.searchParams.set('token', token);
+ await sendEmail('reset-password', {
+ to: user.email,
+ data: { url: url.toString() },
+ });
+ },
+ },
+ databaseHooks: {
+ user: {
+ create: {
+ before: async (user, ctx) => {
+ const inviteId = ctx ? await readInviteId(ctx) : undefined;
+ if (!(await getIsRegistrationAllowed(deps, inviteId))) {
+ throw new APIError('FORBIDDEN', {
+ code: 'REGISTRATION_NOT_ALLOWED',
+ message: 'Registrations are not allowed',
+ });
+ }
+ const name = [user.firstName, user.lastName]
+ .filter(Boolean)
+ .join(' ')
+ .trim();
+ return { data: { ...user, name: name || user.name } };
+ },
+ },
+ },
+ },
+ rateLimit: {
+ enabled: true,
+ window: RATE_LIMIT_WINDOW_SECONDS,
+ max: RATE_LIMIT_MAX,
+ customStorage: redisRateLimitStorage(redis),
},
advanced: {
cookiePrefix: COOKIE_PREFIX,
@@ -88,8 +334,24 @@ function buildAuth({ db, config, logger }: AuthDeps, secret: string) {
// from the same options as the legacy cookie.
useSecureCookies: false,
defaultCookieAttributes: cookieOptions(config),
+ ipAddress: { ipAddressHeaders: [TRUSTED_IP_HEADER] },
},
- plugins: [inertPlugin],
+ plugins: [
+ exposedPathsPlugin,
+ twoFactor({
+ issuer: 'OpenPanel',
+ twoFactorCookieMaxAge: TWO_FACTOR_CHALLENGE_SECONDS,
+ }),
+ lastLoginMethod({
+ cookieName: LAST_LOGIN_METHOD_COOKIE,
+ maxAge: LAST_LOGIN_METHOD_MAX_AGE_SECONDS,
+ customResolveMethod: (ctx) =>
+ ctx.path.startsWith('/two-factor/') ? 'email' : null,
+ }),
+ // After `twoFactor`, so a sign-in still waiting for its second factor
+ // has no session yet and keeps the invite for later.
+ invitePlugin(deps),
+ ],
});
}
@@ -100,7 +362,7 @@ export function createAuth(deps: AuthDeps): Auth | null {
const secret = deps.config.auth.secret;
if (!secret) {
deps.logger.warn(
- 'AUTH_SECRET and COOKIE_SECRET are unset; better-auth is off and only legacy sessions resolve'
+ 'AUTH_SECRET and COOKIE_SECRET are unset; sign-in is unavailable and only legacy sessions resolve'
);
return null;
}
@@ -170,6 +432,7 @@ export async function getAuthSession(
image: user.image ?? null,
firstName: user.firstName ?? null,
lastName: user.lastName ?? null,
+ twoFactorEnabled: user.twoFactorEnabled ?? false,
deletedAt: user.deletedAt ?? null,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
@@ -187,6 +450,29 @@ export async function getAuthSession(
};
}
+export type PasswordSignInResult =
+ | { type: 'signed_in' }
+ | { type: 'two_factor' };
+
+/** A server-side email sign-in whose cookies go out through `setCookie`. */
+export async function signInWithPassword(
+ auth: Auth,
+ config: CoreConfig,
+ credentials: { email: string; password: string },
+ headers: Headers,
+ setCookie: ISetCookie
+): Promise<PasswordSignInResult> {
+ const result = await auth.api.signInEmail({
+ body: credentials,
+ headers,
+ returnHeaders: true,
+ });
+ forwardSetCookies(config, result.headers, setCookie);
+ return 'twoFactorRedirect' in result.response
+ ? { type: 'two_factor' }
+ : { type: 'signed_in' };
+}
+
/**
* The token better-auth knows this session by. It is its own random value, never
* the legacy cookie's: that cookie is unsigned, so storing it would let a
diff --git a/packages/core/src/modules/auth/src/cookie.ts b/packages/core/src/modules/auth/src/cookie.ts
index 989a96b67..3e441df50 100644
--- a/packages/core/src/modules/auth/src/cookie.ts
+++ b/packages/core/src/modules/auth/src/cookie.ts
@@ -2,31 +2,6 @@ import type { CoreConfig } from '../../../config';
import type { ISetCookie } from '../../../shared/cookie';
import { cookieOptions } from './constants';
-const LAST_AUTH_PROVIDER_MAX_AGE_SECONDS = 60 * 60 * 24 * 365;
-
-export function setSessionTokenCookie(
- config: CoreConfig,
- setCookie: ISetCookie,
- token: string,
- expiresAt: Date
-): void {
- setCookie('session', token, {
- maxAge: Math.floor((expiresAt.getTime() - Date.now()) / 1000),
- ...cookieOptions(config),
- });
-}
-
-export function setLastAuthProviderCookie(
- config: CoreConfig,
- setCookie: ISetCookie,
- provider: string
-): void {
- setCookie('last-auth-provider', provider, {
- maxAge: LAST_AUTH_PROVIDER_MAX_AGE_SECONDS,
- ...cookieOptions(config),
- });
-}
-
export function deleteSessionTokenCookie(
config: CoreConfig,
setCookie: ISetCookie
diff --git a/packages/core/src/modules/auth/src/login-session.ts b/packages/core/src/modules/auth/src/login-session.ts
index 80de96db4..e268cfc32 100644
--- a/packages/core/src/modules/auth/src/login-session.ts
+++ b/packages/core/src/modules/auth/src/login-session.ts
@@ -4,7 +4,7 @@
import type { Session, User } from '@openpanel/db/src/prisma-client';
import type { ServiceDeps } from '../../../services';
import { EMPTY_SESSION } from '../../../shared/session';
-import { decodeSessionToken, hashSessionToken } from './token';
+import { decodeSessionToken } from './token';
type LoginSessionDeps = Pick<ServiceDeps, 'db' | 'config'>;
@@ -17,27 +17,6 @@ export type SessionValidationResult =
| { session: Session; user: User; userId: string }
| { session: null; user: null; userId: null };
-export async function createSession(
- deps: LoginSessionDeps,
- token: string,
- userId: string
-): Promise<Session> {
- const session: Session = {
- id: hashSessionToken(token),
- token: null,
- userId,
- expiresAt: new Date(Date.now() + SESSION_TTL_MS),
- ipAddress: null,
- userAgent: null,
- createdAt: new Date(),
- updatedAt: new Date(),
- };
- await deps.db.session.create({
- data: session,
- });
- return session;
-}
-
export async function createDemoSession(
deps: LoginSessionDeps,
userId: string
diff --git a/packages/core/src/modules/auth/src/oauth.ts b/packages/core/src/modules/auth/src/oauth.ts
index 44d0a9c1d..24ba87c67 100644
--- a/packages/core/src/modules/auth/src/oauth.ts
+++ b/packages/core/src/modules/auth/src/oauth.ts
@@ -1,5 +1,4 @@
import * as Arctic from 'arctic';
-import { GitHub } from 'arctic';
import type { CoreConfig } from '../../../config';
export type { OAuth2Tokens } from 'arctic';
@@ -7,17 +6,6 @@ export type { OAuth2Tokens } from 'arctic';
// would trip `noExportedImports`.
export * as Arctic from 'arctic';
-// Built per call: an arctic client only holds credentials.
-export function githubClient(config: CoreConfig): GitHub {
- const { clientId, clientSecret, redirectUri } = config.auth.github;
- return new GitHub(clientId, clientSecret, redirectUri);
-}
-
-export function googleClient(config: CoreConfig): Arctic.Google {
- const { clientId, clientSecret, redirectUri } = config.auth.google;
- return new Arctic.Google(clientId, clientSecret, redirectUri);
-}
-
/** The same Google credentials, redirected at the Search Console callback. */
export function googleGscClient(config: CoreConfig): Arctic.Google {
const { clientId, clientSecret, redirectUri } = config.auth.googleGsc;
diff --git a/packages/core/src/modules/auth/src/totp.ts b/packages/core/src/modules/auth/src/totp.ts
deleted file mode 100644
index edbf98b43..000000000
--- a/packages/core/src/modules/auth/src/totp.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import crypto from 'node:crypto';
-import {
- decodeBase32IgnorePadding,
- encodeBase32UpperCaseNoPadding,
-} from '@oslojs/encoding';
-import { createTOTPKeyURI, verifyTOTPWithGracePeriod } from '@oslojs/otp';
-import qrcode from 'qrcode';
-import { hashPassword, verifyPasswordHash } from './password';
-
-const ISSUER = 'OpenPanel';
-const PERIOD_SECONDS = 30;
-const DIGITS = 6;
-// ±60s grace — ~2 windows on each side. Covers clock drift and the case where
-// an authenticator (e.g. 1Password autofill) emits a code that rolls over
-// between fill and submit.
-const GRACE_PERIOD_SECONDS = 60;
-
-export function generateTotpSecret(): string {
- const bytes = new Uint8Array(20);
- crypto.getRandomValues(bytes);
- return encodeBase32UpperCaseNoPadding(bytes);
-}
-
-export function buildOtpauthUrl({
- secret,
- accountName,
-}: {
- secret: string;
- accountName: string;
-}): string {
- const key = decodeBase32IgnorePadding(secret);
- return createTOTPKeyURI(ISSUER, accountName, key, PERIOD_SECONDS, DIGITS);
-}
-
-export async function generateQrDataUrl(otpauthUrl: string): Promise<string> {
- return qrcode.toDataURL(otpauthUrl, { margin: 1, width: 240 });
-}
-
-export function verifyTotpCode(secret: string, code: string): boolean {
- // Strip any non-digits — some authenticators emit codes like "123 456" or
- // "123-456"; paste-from-clipboard can also carry whitespace.
- const normalized = code.replace(/\D/g, '');
- if (normalized.length !== DIGITS) {
- return false;
- }
- const key = decodeBase32IgnorePadding(secret);
- return verifyTOTPWithGracePeriod(
- key,
- PERIOD_SECONDS,
- DIGITS,
- normalized,
- GRACE_PERIOD_SECONDS
- );
-}
-
-// Human-friendly 10-char code split with a dash: `ABCDE-FGHIJ`.
-// ~51 bits of entropy; argon2-hashed for storage.
-const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
-
-function randomRecoveryCode(): string {
- const bytes = new Uint8Array(10);
- crypto.getRandomValues(bytes);
- let out = '';
- for (let i = 0; i < bytes.length; i++) {
- out += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length];
- if (i === 4) {
- out += '-';
- }
- }
- return out;
-}
-
-export function generateRecoveryCodes(count = 10): string[] {
- return Array.from({ length: count }, randomRecoveryCode);
-}
-
-export async function hashRecoveryCodes(codes: string[]): Promise<string[]> {
- return Promise.all(
- codes.map((code) => hashPassword(normalizeRecoveryCode(code)))
- );
-}
-
-export function normalizeRecoveryCode(input: string): string {
- return input.trim().toUpperCase().replace(/\s+/g, '');
-}
-
-export async function consumeRecoveryCode({
- hashes,
- input,
-}: {
- hashes: string[];
- input: string;
-}): Promise<{ valid: boolean; remaining: string[] }> {
- const normalized = normalizeRecoveryCode(input);
- for (let i = 0; i < hashes.length; i++) {
- const hash = hashes[i]!;
- // Sequential verify is fine — argon2 is slow on purpose and the list is 10 entries.
- const matched = await verifyPasswordHash(hash, normalized);
- if (matched) {
- const remaining = hashes.slice(0, i).concat(hashes.slice(i + 1));
- return { valid: true, remaining };
- }
- }
- return { valid: false, remaining: hashes };
-}
diff --git a/packages/core/src/modules/organization/organization.constants.ts b/packages/core/src/modules/organization/organization.constants.ts
index 75c7df98c..f17d0186b 100644
--- a/packages/core/src/modules/organization/organization.constants.ts
+++ b/packages/core/src/modules/organization/organization.constants.ts
@@ -30,28 +30,25 @@ export type OrganizationRole = z.infer<typeof zOrganizationRole>;
export const zInvitableRole = z.enum(['admin', 'member', 'viewer']);
export type InvitableRole = z.infer<typeof zInvitableRole>;
-const ORGANIZATION_ADMIN_ROLES = [
+/** The roles that manage the organization, also for database filters. */
+export const ORGANIZATION_ADMIN_ROLES = [
'owner',
'admin',
] as const satisfies readonly OrganizationRole[];
-// The previous build still writes these while a rollout replaces it, after the
-// rename migration has run, so they are read for one more release; the next
-// release's migration renames them again.
-const ROLE_BY_LEGACY_ROLE: Record<string, OrganizationRole> = {
- 'org:admin': 'admin',
- 'org:member': 'member',
-};
-
-/** Every stored role that manages the organization, for database filters. */
-export const STORED_ADMIN_ROLES = [...ORGANIZATION_ADMIN_ROLES, 'org:admin'];
+/**
+ * For filters that delete or skip organizations: also the pre-rename spelling,
+ * which an install keeps until code migration 29 has run. A self-hosted
+ * upgrade can start its crons first, and a wrong "no admin" deletes the
+ * organization for good.
+ */
+export const STORED_ADMIN_ROLES: string[] = [
+ ...ORGANIZATION_ADMIN_ROLES,
+ 'org:admin',
+];
/** An unknown stored role reads as `member`, never as an admin. */
export function normalizeOrganizationRole(stored: string): OrganizationRole {
- const legacy = ROLE_BY_LEGACY_ROLE[stored];
- if (legacy) {
- return legacy;
- }
const parsed = zOrganizationRole.safeParse(stored);
return parsed.success ? parsed.data : 'member';
}
diff --git a/packages/core/src/modules/organization/organization.service.test.ts b/packages/core/src/modules/organization/organization.service.test.ts
index 58a56f9f1..5a5047c13 100644
--- a/packages/core/src/modules/organization/organization.service.test.ts
+++ b/packages/core/src/modules/organization/organization.service.test.ts
@@ -992,7 +992,8 @@ test('runDeleteCron is a no-op when nothing is due', async () => {
expect(organizationStore.has('org_healthy')).toBe(true);
});
-// The previous build still writes `org:admin` while a rollout replaces it.
+// An install keeps `org:admin` until code migration 29 has run, and its
+// crons can start first.
test('runDeleteCron keeps an organization whose only admin has the old role spelling', async () => {
organizationStore.set('org_rollout', makeOrganization({ id: 'org_rollout' }));
memberStore.set('member_1', {
diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.ts
index 2bf3f36c1..d33b7c1c1 100644
--- a/packages/core/src/modules/organization/organization.service.ts
+++ b/packages/core/src/modules/organization/organization.service.ts
@@ -18,6 +18,9 @@ import { chQuery } from '../../ch-query';
import { sendEmail } from '../../clients/email';
import { TRPCBadRequestError, TRPCNotFoundError } from '../../rpc/errors';
import type { ServiceDeps, Services } from '../../services';
+
+type MembershipDeps = Pick<ServiceDeps, 'db' | 'config'>;
+
import {
getOrganizationAccess,
getProjectAccess,
@@ -191,7 +194,7 @@ export async function getMembers(
}
function writeMemberProjects(
- deps: ServiceDeps,
+ deps: MembershipDeps,
memberId: string,
projectScope: ProjectScope,
grants: IProjectAccessGrant[]
@@ -223,7 +226,7 @@ function writeMemberProjects(
* concurrent request can cache the old answer again.
*/
async function clearMemberAccessCache(
- deps: ServiceDeps,
+ deps: MembershipDeps,
{ userId, organizationId }: { userId: string; organizationId: string }
): Promise<void> {
const projects = await deps.db.project.findMany({
@@ -239,12 +242,12 @@ async function clearMemberAccessCache(
}
export async function connectUserToOrganization(
- deps: ServiceDeps,
+ deps: MembershipDeps,
{
user,
inviteId,
}: {
- user: User;
+ user: Pick<User, 'id' | 'email'>;
inviteId: string;
}
) {
diff --git a/packages/core/src/modules/user/user.rpc.ts b/packages/core/src/modules/user/user.rpc.ts
index 235742481..06c145b50 100644
--- a/packages/core/src/modules/user/user.rpc.ts
+++ b/packages/core/src/modules/user/user.rpc.ts
@@ -18,7 +18,7 @@ export const userRouter = createTRPCRouter({
delete: protectedProcedure.mutation(async ({ ctx }) => {
const userId = ctx.session.userId;
await ctx.services.user.deleteUserAccount(userId);
- ctx.services.auth.deleteSessionTokenCookie(ctx.setCookie);
+ ctx.services.auth.clearSessionCookies(ctx.setCookie);
return true;
}),
diff --git a/packages/core/src/rpc/rate-limit.test.ts b/packages/core/src/rpc/rate-limit.test.ts
index 556140613..f13ee5804 100644
--- a/packages/core/src/rpc/rate-limit.test.ts
+++ b/packages/core/src/rpc/rate-limit.test.ts
@@ -31,15 +31,9 @@ describe('rate limit escalation', () => {
});
});
+// Sign-in, sign-up, reset and two-factor are better-auth's and throttled there.
const AUTH_LIMITS: Record<string, { max: number; windowMs: number }> = {
- signUpEmail: { max: 5, windowMs: 60_000 },
- signInEmail: { max: 3, windowMs: 30_000 },
- signInTotp: { max: 5, windowMs: 60_000 },
- totpEnable: { max: 5, windowMs: 60_000 },
- totpDisable: { max: 5, windowMs: 60_000 },
- totpRegenerateRecoveryCodes: { max: 3, windowMs: 60_000 },
- resetPassword: { max: 3, windowMs: 60_000 },
- requestResetPassword: { max: 3, windowMs: 60_000 },
+ signInDev: { max: 10, windowMs: 60_000 },
signInShare: { max: 3, windowMs: 30_000 },
};
diff --git a/packages/core/test/config-fixture.ts b/packages/core/test/config-fixture.ts
index aacba0dd0..c7ddc7f03 100644
--- a/packages/core/test/config-fixture.ts
+++ b/packages/core/test/config-fixture.ts
@@ -29,6 +29,7 @@ export function testCoreConfig(
},
auth: {
secret: undefined,
+ trustedOrigins: [],
allowRegistration: undefined,
allowInvitation: undefined,
github: { clientId: '', clientSecret: '', redirectUri: '' },
diff --git a/packages/core/test/rpc-fixtures.ts b/packages/core/test/rpc-fixtures.ts
index 37aa757ed..5c74babcb 100644
--- a/packages/core/test/rpc-fixtures.ts
+++ b/packages/core/test/rpc-fixtures.ts
@@ -67,6 +67,7 @@ export const TEST_SESSION: Session = {
name: null,
emailVerified: false,
image: null,
+ twoFactorEnabled: false,
firstName: null,
lastName: null,
createdAt: TEST_EPOCH,
diff --git a/packages/db/prisma/migrations/20261024090000_better_auth_two_factor/migration.sql b/packages/db/prisma/migrations/20261024090000_better_auth_two_factor/migration.sql
new file mode 100644
index 000000000..7f7f95fd7
--- /dev/null
+++ b/packages/db/prisma/migrations/20261024090000_better_auth_two_factor/migration.sql
@@ -0,0 +1,24 @@
+-- AlterTable
+ALTER TABLE "public"."users" ADD COLUMN "twoFactorEnabled" BOOLEAN NOT NULL DEFAULT false;
+
+-- CreateTable
+CREATE TABLE "public"."two_factor" (
+ "id" TEXT NOT NULL DEFAULT gen_random_uuid(),
+ "userId" TEXT NOT NULL,
+ "secret" TEXT NOT NULL,
+ "backupCodes" TEXT NOT NULL,
+ "verified" BOOLEAN NOT NULL DEFAULT true,
+ "failedVerificationCount" INTEGER NOT NULL DEFAULT 0,
+ "lockedUntil" TIMESTAMP(3),
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "two_factor_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "two_factor_userId_key" ON "public"."two_factor"("userId");
+
+-- AddForeignKey
+ALTER TABLE "public"."two_factor" ADD CONSTRAINT "two_factor_userId_fkey" FOREIGN KEY ("userId") REFERENCES "public"."users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index 9231fa65a..877e86fdd 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -153,6 +153,8 @@ model User {
name String?
emailVerified Boolean @default(false)
image String?
+ twoFactorEnabled Boolean @default(false)
+ twoFactor TwoFactor?
createdOrganizations Organization[] @relation("organizationCreatedBy")
subscriptions Organization[] @relation("subscriptionCreatedBy")
membership Member[]
@@ -183,6 +185,23 @@ model UserTotp {
@@map("user_totp")
}
+// better-auth's twoFactor plugin. `secret` and `backupCodes` are encrypted
+// with the auth secret.
+model TwoFactor {
+ id String @id @default(dbgenerated("gen_random_uuid()"))
+ userId String @unique
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ secret String
+ backupCodes String
+ verified Boolean @default(true)
+ failedVerificationCount Int @default(0)
+ lockedUntil DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+
+ @@map("two_factor")
+}
+
model TwoFactorChallenge {
id String @id
userId String
diff --git a/packages/db/src/code-migrations/30-better-auth-sign-in.test.ts b/packages/db/src/code-migrations/30-better-auth-sign-in.test.ts
new file mode 100644
index 000000000..eeb07668b
--- /dev/null
+++ b/packages/db/src/code-migrations/30-better-auth-sign-in.test.ts
@@ -0,0 +1,129 @@
+import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
+import { db } from '../prisma-client';
+import { up } from './30-better-auth-sign-in';
+
+const PREFIX = 'm30';
+const ORG_ID = `${PREFIX}-org`;
+
+const id = (name: string) => `${PREFIX}-${name}`;
+
+async function cleanUp() {
+ await db.organization.deleteMany({ where: { id: ORG_ID } });
+ await db.user.deleteMany({ where: { id: { startsWith: `${PREFIX}-` } } });
+}
+
+async function seed() {
+ await db.user.createMany({
+ data: [
+ { id: id('creator'), email: 'm30-creator@test' },
+ { id: id('mixed'), email: 'M30-Mixed@Test' },
+ { id: id('pair-google'), email: 'M30-Pair@test' },
+ { id: id('pair-github'), email: 'm30-pair@test' },
+ { id: id('imported'), email: 'm30-imported@test' },
+ { id: id('github-no-id'), email: 'm30-github-no-id@test' },
+ { id: id('password'), email: 'm30-password@test' },
+ ],
+ });
+ await db.account.createMany({
+ data: [
+ { userId: id('imported'), provider: 'oauth' },
+ { userId: id('github-no-id'), provider: 'github' },
+ { userId: id('password'), provider: 'credential', password: 'hash' },
+ ],
+ });
+ await db.organization.create({
+ data: { id: ORG_ID, name: 'M30', createdByUserId: id('creator') },
+ });
+ await db.member.createMany({
+ data: [
+ {
+ organizationId: ORG_ID,
+ userId: id('creator'),
+ email: 'm30-creator@test',
+ role: 'org:admin',
+ },
+ {
+ organizationId: ORG_ID,
+ userId: id('mixed'),
+ email: 'm30-mixed@test',
+ role: 'org:member',
+ },
+ ],
+ });
+ await db.invite.create({
+ data: {
+ id: id('invite'),
+ email: 'm30-invitee@test',
+ organizationId: ORG_ID,
+ createdById: id('creator'),
+ role: 'org:member',
+ expiresAt: new Date('2030-01-01T00:00:00Z'),
+ },
+ });
+}
+
+async function snapshot() {
+ const [users, members, invite] = await Promise.all([
+ db.user.findMany({
+ where: { id: { startsWith: `${PREFIX}-` } },
+ select: { id: true, email: true, emailVerified: true },
+ orderBy: { id: 'asc' },
+ }),
+ db.member.findMany({
+ where: { organizationId: ORG_ID },
+ select: { userId: true, role: true },
+ }),
+ db.invite.findUniqueOrThrow({
+ where: { id: id('invite') },
+ select: { role: true },
+ }),
+ ]);
+ return {
+ users: Object.fromEntries(users.map((user) => [user.id, user])),
+ roles: Object.fromEntries(
+ members.map((member) => [member.userId, member.role])
+ ),
+ inviteRole: invite.role,
+ };
+}
+
+describe('30-better-auth-sign-in', () => {
+ let after: Awaited<ReturnType<typeof snapshot>>;
+
+ beforeAll(async () => {
+ await cleanUp();
+ await seed();
+ await up();
+ after = await snapshot();
+ });
+
+ afterAll(cleanUp);
+
+ it('lowercases emails', () => {
+ expect(after.users[id('mixed')]?.email).toBe('m30-mixed@test');
+ });
+
+ it('leaves two users whose emails differ only in case untouched', () => {
+ expect(after.users[id('pair-google')]?.email).toBe('M30-Pair@test');
+ expect(after.users[id('pair-github')]?.email).toBe('m30-pair@test');
+ });
+
+ it('marks users with an OAuth account verified, including imported ones', () => {
+ expect(after.users[id('imported')]?.emailVerified).toBe(true);
+ expect(after.users[id('github-no-id')]?.emailVerified).toBe(true);
+ expect(after.users[id('password')]?.emailVerified).toBe(false);
+ });
+
+ it('renames roles written by older servers', () => {
+ expect(after.roles).toEqual({
+ [id('creator')]: 'owner',
+ [id('mixed')]: 'member',
+ });
+ expect(after.inviteRole).toBe('member');
+ });
+
+ it('changes nothing when run again', async () => {
+ await up();
+ expect(await snapshot()).toEqual(after);
+ });
+});
diff --git a/packages/db/src/code-migrations/30-better-auth-sign-in.ts b/packages/db/src/code-migrations/30-better-auth-sign-in.ts
new file mode 100644
index 000000000..90755f939
--- /dev/null
+++ b/packages/db/src/code-migrations/30-better-auth-sign-in.ts
@@ -0,0 +1,164 @@
+import { db } from '../prisma-client';
+import { getIsDry, printBoxMessage } from './helpers';
+
+/**
+ * Prepares users for signing in through better-auth.
+ *
+ * - Emails are lowercased: better-auth lowercases every address it looks up,
+ * so a stored `[email protected]` could no longer sign in. Two users whose emails
+ * differ only in case are left alone and listed; they are fixed by hand.
+ * - Users with a Google, GitHub or bulk-imported `oauth` account are marked
+ * email verified. better-auth links a Google/GitHub sign-in to an existing
+ * user by email only when that user is verified, which is how the imported
+ * `oauth` users and the accounts without an IdP id get their account.
+ * - Roles are renamed again (`org:admin` → `admin`, `org:member` → `member`,
+ * the creator's admin membership → `owner`): servers from before migration
+ * 29 kept writing the old names during that rollout.
+ *
+ * Idempotent: every statement only touches rows still in the old shape.
+ */
+
+interface Count {
+ count: bigint;
+}
+
+interface CaseCollision {
+ email: string;
+ userIds: string[];
+}
+
+const LEGACY_ROLES = ['org:admin', 'org:member'];
+const LINKABLE_PROVIDERS = ['google', 'github', 'oauth'];
+
+function toNumber(rows: Count[]): number {
+ return Number(rows[0]?.count ?? 0);
+}
+
+function findCaseCollisions() {
+ return db.$queryRaw<CaseCollision[]>`
+ SELECT lower(email) AS email, array_agg(id ORDER BY "createdAt") AS "userIds"
+ FROM users
+ GROUP BY lower(email)
+ HAVING COUNT(*) > 1
+ `;
+}
+
+async function countPending() {
+ const [emails, verified, roles, owners] = await Promise.all([
+ db.$queryRaw<Count[]>`
+ SELECT COUNT(*) AS count FROM users u
+ WHERE u.email <> lower(u.email) AND NOT EXISTS (
+ SELECT 1 FROM users o WHERE o.id <> u.id AND lower(o.email) = lower(u.email)
+ )
+ `.then(toNumber),
+ db.$queryRaw<Count[]>`
+ SELECT COUNT(*) AS count FROM users u
+ WHERE NOT u."emailVerified" AND EXISTS (
+ SELECT 1 FROM accounts a
+ WHERE a."userId" = u.id AND a.provider = ANY(${LINKABLE_PROVIDERS})
+ )
+ `.then(toNumber),
+ Promise.all([
+ db.member.count({ where: { role: { in: LEGACY_ROLES } } }),
+ db.invite.count({ where: { role: { in: LEGACY_ROLES } } }),
+ ]).then(([members, invites]) => members + invites),
+ db.$queryRaw<Count[]>`
+ SELECT COUNT(*) AS count FROM members m
+ JOIN organizations o ON o.id = m."organizationId"
+ WHERE m."userId" = o."createdByUserId"
+ AND m.role IN ('admin', 'org:admin')
+ `.then(toNumber),
+ ]);
+ return { emails, verified, roles, owners };
+}
+
+function lowercaseEmails() {
+ return db.$executeRaw`
+ UPDATE users u
+ SET email = lower(u.email)
+ WHERE u.email <> lower(u.email) AND NOT EXISTS (
+ SELECT 1 FROM users o WHERE o.id <> u.id AND lower(o.email) = lower(u.email)
+ )
+ `;
+}
+
+function markLinkableEmailsVerified() {
+ return db.$executeRaw`
+ UPDATE users u
+ SET "emailVerified" = true
+ WHERE NOT u."emailVerified" AND EXISTS (
+ SELECT 1 FROM accounts a
+ WHERE a."userId" = u.id AND a.provider = ANY(${LINKABLE_PROVIDERS})
+ )
+ `;
+}
+
+function renameMemberRoles() {
+ return db.$executeRaw`
+ UPDATE members
+ SET role = CASE role WHEN 'org:admin' THEN 'admin' ELSE 'member' END
+ WHERE role = ANY(${LEGACY_ROLES})
+ `;
+}
+
+function renameInviteRoles() {
+ return db.$executeRaw`
+ UPDATE invites
+ SET role = CASE role WHEN 'org:admin' THEN 'admin' ELSE 'member' END
+ WHERE role = ANY(${LEGACY_ROLES})
+ `;
+}
+
+function promoteCreatorsToOwner() {
+ return db.$executeRaw`
+ UPDATE members m
+ SET role = 'owner'
+ FROM organizations o
+ WHERE o.id = m."organizationId"
+ AND m."userId" = o."createdByUserId"
+ AND m.role = 'admin'
+ `;
+}
+
+function describeCollisions(collisions: CaseCollision[]): string[] {
+ return collisions.map(
+ (collision) => ` ${collision.email}: ${collision.userIds.join(', ')}`
+ );
+}
+
+export async function up() {
+ const [pending, collisions] = await Promise.all([
+ countPending(),
+ findCaseCollisions(),
+ ]);
+
+ if (getIsDry()) {
+ printBoxMessage('🧪 Dry run: better-auth sign-in', [
+ `Emails to lowercase: ${pending.emails}`,
+ `Users to mark email verified: ${pending.verified}`,
+ `Members and invites with a legacy role name: ${pending.roles}`,
+ `Creator memberships to make owner: ${pending.owners}`,
+ `Emails shared by users that differ only in case: ${collisions.length}`,
+ ...describeCollisions(collisions),
+ ]);
+ return;
+ }
+
+ const [emails, verified, memberRoles, inviteRoles, owners] =
+ await db.$transaction([
+ lowercaseEmails(),
+ markLinkableEmailsVerified(),
+ renameMemberRoles(),
+ renameInviteRoles(),
+ promoteCreatorsToOwner(),
+ ]);
+
+ printBoxMessage('✅ better-auth sign-in', [
+ `Emails lowercased: ${emails}`,
+ `Users marked email verified: ${verified}`,
+ `Roles renamed: ${memberRoles} members, ${inviteRoles} invites`,
+ `Creator memberships made owner: ${owners}`,
+ `Left for a manual fix, emails that differ only in case: ${collisions.length}`,
+ ...describeCollisions(collisions),
+ ]);
+}
diff --git a/self-hosting/cli/src/doctor/checks.ts b/self-hosting/cli/src/doctor/checks.ts
index 3ec31b109..75995233c 100644
--- a/self-hosting/cli/src/doctor/checks.ts
+++ b/self-hosting/cli/src/doctor/checks.ts
@@ -460,7 +460,7 @@ export const encryptionKey: Check = (install) => {
severity: 'error',
title: 'ENCRYPTION_KEY is not 64 hex characters',
detail:
- 'It guards stored credentials (2FA, Search Console, exports), so doctor will not replace an existing value.',
+ 'It guards stored credentials (Search Console, exports), so doctor will not replace an existing value.',
manual:
'Generate a replacement with `openssl rand -hex 32` only if you have nothing encrypted yet.',
};
@@ -470,7 +470,7 @@ export const encryptionKey: Check = (install) => {
severity: 'error',
title: 'ENCRYPTION_KEY is not set',
detail:
- 'Needed for 2FA, Google Search Console and export credentials; must match on api and worker.',
+ 'Needed for Google Search Console and export credentials; must match on api and worker.',
fix: (target) => target.env.set('ENCRYPTION_KEY', randomHex(32)),
};
};
@@ -483,7 +483,8 @@ export const cookieSecret: Check = (install) => {
id: 'env/cookie-secret',
severity: 'error',
title: 'COOKIE_SECRET is not set',
- detail: 'Signs unsubscribe links and unlocks password-protected shares.',
+ detail:
+ 'Without it (and without AUTH_SECRET) nobody can sign in. Also signs unsubscribe links and unlocks password-protected shares.',
fix: (target) => target.env.set('COOKIE_SECRET', randomHex(16)),
};
};