⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix(auth): enforce email verification on sign-up (#360)
Egor Vasilyev50dfa20bebad
diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex 82cfaf78..1d78fe36 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -268,9 +268,11 @@ export const app = new Elysia()const emailEnabled = await hasConfiguredEmailProvider();return {registration: settings.registration,- // Both are only usable when the instance can actually send mail.+ // Only usable when the instance can actually send mail.magicLink: settings.magicLink && emailEnabled,- requireEmailVerification: settings.requireEmailVerification && emailEnabled,+ // Cleared together with the mail provider, so the raw setting is what the+ // sign-up endpoint enforces.+ requireEmailVerification: settings.requireEmailVerification,emailEnabled,// Whether the email/password form is offered at all. The api refuses to turn// it off while no provider below is usable, so this is never false alone.diff --git a/apps/api/src/modules/god/__tests__/integration/god-email-verification.test.ts b/apps/api/src/modules/god/__tests__/integration/god-email-verification.test.tsnew file mode 100644index 00000000..119fca81--- /dev/null+++ b/apps/api/src/modules/god/__tests__/integration/god-email-verification.test.ts@@ -0,0 +1,133 @@+import { beforeEach, describe, expect, it } from 'bun:test';+import { setAuthSettings } from '@repo/auth';+import { api, app, authedApi } from '#tests/helpers/app';+import { resetDb } from '#tests/helpers/db';+import { addUser, setup, type Actor } from '../helpers';++const PASSWORD = 'test-password-123';++// The password endpoints live behind the better-auth catch-all, which Eden Treaty+// does not model, so they are driven through the app handler directly.+function authRequest(path: string, body: object) {+ return app.handle(+ new Request(`http://localhost/api/auth${path}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ }),+ );+}++function signUp(email: string) {+ return authRequest('/sign-up/email', { email, password: PASSWORD, name: 'Someone' });+}++function signIn(email: string) {+ return authRequest('/sign-in/email', { email, password: PASSWORD });+}++// The Cookie header a browser would send back after this response; empty when the+// response set no session.+function cookieOf(response: Response): string {+ return response.headers+ .getSetCookie()+ .map((c) => c.split(';')[0])+ .join('; ');+}++// Port 1 is deliberately unreachable: the confirmation mail sign-up sends is best+// effort, and a refused connection is what keeps it from waiting on a DNS lookup.+const smtpProvider = {+ smtp: {+ enabled: true,+ host: '127.0.0.1',+ port: 1,+ encryption: 'none' as const,+ username: '',+ timeout: 1,+ },+ resend: { enabled: false },+ from: '[email protected]',+};++async function requireVerification(god: Actor): Promise<void> {+ await god.api.god['email-settings'].put(smtpProvider);+ const res = await god.api.god['auth-settings'].put({ requireEmailVerification: true });+ expect(res.status).toBe(200);+}++describe('email verification', () => {+ beforeEach(resetDb);++ it('opens no session at sign-up while a confirmed address is required', async () => {+ const { god } = await setup();+ await requireVerification(god);++ const res = await signUp('[email protected]');++ expect(res.status).toBe(200);+ expect(((await res.json()) as { token: string | null }).token).toBeNull();+ expect((await authedApi(cookieOf(res)).projects.get()).status).toBe(401);+ expect((await signIn('[email protected]')).status).toBe(403);+ expect((await api['auth-config'].get()).data).toMatchObject({+ requireEmailVerification: true,+ });+ });++ it('keeps open sessions working and lets a confirmed account sign in', async () => {+ const { god } = await setup();+ const member = await addUser({ email: '[email protected]' });+ await requireVerification(god);++ expect((await god.api.god['auth-settings'].get()).status).toBe(200);+ expect((await member.api.projects.get()).status).toBe(200);+ expect((await signIn(member.email)).status).toBe(403);++ await god.api.god.users({ userId: member.id })['verify-email'].post();++ const res = await signIn(member.email);+ expect(res.status).toBe(200);+ expect((await authedApi(cookieOf(res)).projects.get()).status).toBe(200);+ });++ it('signs up straight into a session while no confirmation is required', async () => {+ await setup();++ const res = await signUp('[email protected]');++ expect(res.status).toBe(200);+ expect((await authedApi(cookieOf(res)).projects.get()).status).toBe(200);+ });++ // The api never writes this state, but the gate must not depend on the provider:+ // the requirement is cleared with it, not lifted while it is missing.+ it('enforces the requirement without a mail provider', async () => {+ await setup();+ await setAuthSettings({ requireEmailVerification: true });++ const res = await signUp('[email protected]');++ expect((await authedApi(cookieOf(res)).projects.get()).status).toBe(401);+ expect((await signIn('[email protected]')).status).toBe(403);+ });++ it('drops the requirement when the mail provider is removed', async () => {+ const { god } = await setup();+ await requireVerification(god);++ const removed = await god.api.god['email-settings'].put({+ ...smtpProvider,+ smtp: { ...smtpProvider.smtp, enabled: false },+ });++ expect(removed.status).toBe(200);+ expect((await god.api.god['auth-settings'].get()).data).toMatchObject({+ requireEmailVerification: false,+ });+ expect((await api['auth-config'].get()).data).toMatchObject({+ requireEmailVerification: false,+ });+ const res = await signUp('[email protected]');+ expect((await authedApi(cookieOf(res)).projects.get()).status).toBe(200);+ });+});diff --git a/apps/web/src/features/auth/components/register/AuthRegisterForm.tsx b/apps/web/src/features/auth/components/register/AuthRegisterForm.tsxindex 2ec28306..8ee6dec1 100644--- a/apps/web/src/features/auth/components/register/AuthRegisterForm.tsx+++ b/apps/web/src/features/auth/components/register/AuthRegisterForm.tsx@@ -15,12 +15,7 @@ import AuthFormHeader from '../AuthFormHeader';import AuthMessagePanel from '../AuthMessagePanel';import AuthRegisterPasswordFields from './AuthRegisterPasswordFields';import AuthRegisterProviders from './AuthRegisterProviders';-import {- signInWithGoogle,- signInWithOidc,- signOutUnverified,- signUpWithEmail,-} from '../../services/auth.service';+import { signInWithGoogle, signInWithOidc, signUpWithEmail } from '../../services/auth.service';import { useAuthAction } from '../../hooks/useAuthAction';import { useAuthConfig } from '@/services/authConfig.service';@@ -45,14 +40,12 @@ export default function AuthRegisterForm() {setError(t('errors.passwordsDoNotMatch'));return;}- // With confirmation required, sign-up still opens a session (autoSignIn), so it- // is dropped right away: the account exists but stays unusable until the link in- // the email is opened.+ // With confirmation required, sign-up opens no session: the account exists but+ // stays unusable until the link in the email is opened.if (needsConfirmation) {run(async () => {await signUpWithEmail({ email, password });- await signOutUnverified();setAwaitingConfirmation(true);},{ redirect: false },diff --git a/apps/web/src/features/auth/services/auth.service.ts b/apps/web/src/features/auth/services/auth.service.tsindex 34654526..bea77097 100644--- a/apps/web/src/features/auth/services/auth.service.ts+++ b/apps/web/src/features/auth/services/auth.service.ts@@ -1,7 +1,6 @@import {signIn,signUp,- signOut,requestPasswordReset,resetPassword,sendVerificationEmail,@@ -43,9 +42,10 @@ export async function signInWithPassword(input: {throw new Error(message);}-// autoSignIn (set in @repo/auth) signs the user in right after sign-up. The display-// name is derived from the email; the planner does not use it yet. callbackURL is-// where the confirmation link lands when the instance sends one.+// autoSignIn (set in @repo/auth) signs the user in right after sign-up, unless the+// instance requires a confirmed address, in which case no session is opened. The+// display name is derived from the email; the planner does not use it yet.+// callbackURL is where the confirmation link lands when the instance sends one.//// On an invite-only instance the API rejects the sign-up unless the address has a// pending project invite, and the thrown message says so.@@ -103,13 +103,6 @@ export async function resendVerificationEmail(email: string): Promise<void> {if (result.error) throw new Error(result.error.message ?? '');}-// Drops the session created by autoSignIn right after sign-up, used when the-// instance requires a confirmed address: the account exists but must not be usable-// until the link in the email is opened.-export async function signOutUnverified(): Promise<void> {- await signOut();-}-// Starts the Google round trip. Unlike every other call here this one navigates away// instead of returning a result: better-auth redirects to Google, and Google comes// back to the API callback, which then sends the browser to one of these two URLs.diff --git a/apps/web/src/lib/api/endpoints/settings.ts b/apps/web/src/lib/api/endpoints/settings.tsindex b42094a8..5750c434 100644--- a/apps/web/src/lib/api/endpoints/settings.ts+++ b/apps/web/src/lib/api/endpoints/settings.ts@@ -64,9 +64,10 @@ export type StorageSettingsPatch = Partial<StorageSettings>;// command left out keeps the binding from the layer below.export type HotkeyOverrides = Record<string, string>;-// What the sign-in and sign-up screens read before there is a session. magicLink,-// requireEmailVerification and google are already resolved against their provider by-// the API, so a screen can trust them without checking the credentials itself.+// What the sign-in and sign-up screens read before there is a session. magicLink and+// google are already resolved against their provider by the API, and+// requireEmailVerification is cleared when the mail provider is removed, so a screen+// can trust them without checking the credentials itself.export interface PublicAuthConfig {registration: RegistrationMode;magicLink: boolean;diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.mdindex a9c5d2ec..61f0e776 100644--- a/packages/auth/AGENTS.md+++ b/packages/auth/AGENTS.md@@ -3,9 +3,9 @@The **server-side** better-auth instance. Consumed by `apps/api`. See root `AGENTS.md`.- `src/index.ts` — `export const auth = betterAuth({...})` with the Drizzle adapter- (`provider: "pg"`) over `@repo/db`. Email+password enabled (no email confirmation:- `requireEmailVerification: false`, `autoSignIn: true`), plus the WebAuthn passkey- plugin (`@better-auth/passkey`).+ (`provider: "pg"`) over `@repo/db`. Email+password enabled (`autoSignIn: true`;+ whether the address has to be confirmed first is an instance setting, see below),+ plus the WebAuthn passkey plugin (`@better-auth/passkey`).- Exports `auth`, `USER_ROLES` / `UserRole`, `generateUsername` (the SCIM module derives ahandle with the same rule), `getSessionFromHeaders`, plus `Auth` / `Session` types.- `emailAndPassword.revokeSessionsOnPasswordReset` is `true`: a reset ends every session@@ -41,12 +41,18 @@ table and god mode has no invite section — do not add one.`hooks.before` gates `/sign-up/email` (closed → 403, invite → no pending invite forthat address → 403) and holds back `/sign-in/email` for an unconfirmed address while-verification is required **and** a mail provider is configured — without one the-address can never be confirmed, so the gate lifts instead of locking the account out.-That is the same condition the public `/auth-config` reports, so the sign-in screen-and the gate never disagree. Because both read the settings per request,-`emailAndPassword.requireEmailVerification` stays `false` in the static config — do-not flip it to `true`.+verification is required. The requirement never outlives the mail provider: the api+refuses to turn it on without one, and `setEmailSettings` clears it when the provider+is removed, so the setting alone is what the gate, the sign-up endpoint and the+public `/auth-config` read — none of them checks the provider again.++`emailAndPassword.requireEmailVerification` is a getter over a module variable that+`hooks.before` refreshes from the setting on every password endpoint. better-auth+reads the option off the options object when `/sign-up/email` decides whether to+open a session, so this is what makes a required confirmation answer sign-up with+`token: null` and no cookie instead of a working session. Do not replace the getter+with a static value: `true` would lock every account out the moment the setting is+turned off, and `false` hands an unconfirmed sign-up a session.Authentication email (`src/mail.ts`) goes out through `@repo/mailer` and is besteffort: with no provider configured it logs and returns false rather than failing the@@ -55,9 +61,9 @@ link. Every link must carry a `callbackURL`/`redirectTo` on the **web** originhandler runs on the API origin, so a link built without one lands the reader on theAPI, which renders nothing. The web app passes them in `features/auth/services`.-`autoSignIn` opens a session even when confirmation is required (the static config-cannot depend on the setting), so the web sign-up drops that session and shows a-"confirm your email" screen instead.+With confirmation required, sign-up returns the user and no session; the web sign-up+shows a "confirm your email" screen instead of entering the app, and the link opens+the session (`autoSignInAfterVerification`).## Username@@ -83,9 +89,9 @@ session, and a username comes from the address, so it would tell a stranger whicaddresses are registered.The sign-in screen has one field for both identifiers and picks the endpoint by whether-what was typed contains an "@". `/sign-in/username` checks only the static-`emailAndPassword.requireEmailVerification`, which is `false` here, so the instance-verification gate in `hooks.before` covers that path as well as `/sign-in/email`.+what was typed contains an "@". The instance verification gate in `hooks.before`+covers `/sign-in/username` as well as `/sign-in/email`, and runs before the plugin's+own check of `emailAndPassword.requireEmailVerification`.## Generic OIDCdiff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsindex d373c159..75b8cd50 100644--- a/packages/auth/src/index.ts+++ b/packages/auth/src/index.ts@@ -1,5 +1,5 @@import { randomInt } from 'node:crypto';-import { db, defaultMemberPermissions, hasConfiguredEmailProvider } from '@repo/db';+import { db, defaultMemberPermissions } from '@repo/db';import { eq, sql, type SQL } from 'drizzle-orm';import { betterAuth } from 'better-auth';import { createAuthMiddleware, APIError } from 'better-auth/api';@@ -153,6 +153,13 @@ async function resolveTrustedProviders(request?: Request): Promise<string[]> {return trustProviderEmails ? ['google', OIDC_PROVIDER_ID] : [];}+// Whether a new account has to confirm its address before it gets a session. An+// instance setting, read in `hooks.before` on every password endpoint and served to+// better-auth through the getter on `emailAndPassword` below: sign-up reads the+// option off the options object at the moment it decides whether to open a session,+// so a getter is what lets the stored setting reach a config that is built once.+let verificationRequired = false;+// The endpoints of the email/password form, including the two the magic link uses.// Turning password authentication off refuses all of them, so a link issued before// the switch was flipped cannot still be redeemed. Passkey sign-in is not here: a@@ -279,10 +286,12 @@ export const auth = betterAuth({emailAndPassword: {enabled: true,- // Whether a new account must confirm its address is an instance setting, read- // per request in the hooks below, so it stays false here (a static true would- // lock out every account the moment the setting is flipped off).- requireEmailVerification: false,+ // While this is true, sign-up answers without a session and a duplicate address+ // gets the same answer as a new one; sign-in of an unconfirmed account is+ // refused in the hook below before better-auth's own check runs.+ get requireEmailVerification() {+ return verificationRequired;+ },autoSignIn: true,// A reset is how a stolen password is dealt with, so every session opened with// the old one ends with it. The signed-in change-password form sends@@ -376,6 +385,7 @@ export const auth = betterAuth({// Read here so the two sign-in endpoints, which also go through the// verification gate below, make one query instead of two.const passwordSettings = PASSWORD_PATHS.has(ctx.path) ? await getAuthSettings() : null;+ if (passwordSettings) verificationRequired = passwordSettings.requireEmailVerification;// The api will not let the switch be turned off while no OAuth provider is// configured, so this cannot leave an instance with no way in.if (passwordSettings && !passwordSettings.emailPassword) {@@ -421,11 +431,6 @@ export const auth = betterAuth({if (ctx.path === '/sign-in/email' || ctx.path === '/sign-in/username') {const settings = passwordSettings ?? (await getAuthSettings());if (!settings.requireEmailVerification) return;- // Holding an account back is only fair while a confirmation link can still- // be sent: with the mail provider gone, an unconfirmed account has no way- // out and the gate would lock it forever. This is the same condition the- // public /auth-config reports, so the sign-in screen and the gate agree.- if (!(await hasConfiguredEmailProvider())) return;const body = ctx.body as { email?: string; username?: string } | undefined;const identifier =ctx.path === '/sign-in/email'diff --git a/packages/auth/src/instance.ts b/packages/auth/src/instance.tsindex 9f3e8317..2fc282e3 100644--- a/packages/auth/src/instance.ts+++ b/packages/auth/src/instance.ts@@ -12,7 +12,7 @@ import {type InstanceEmailConfig,} from '@repo/db';import { and, eq } from 'drizzle-orm';-import type { SmtpConfig } from '@repo/mailer';+import { hasEmailProvider, type SmtpConfig } from '@repo/mailer';// Instance-wide authentication settings: who may register, whether email has to be// confirmed, which sign-in methods are offered, the mail provider used for@@ -41,8 +41,9 @@ export type RegistrationMode = (typeof REGISTRATION_MODES)[number];export interface AuthSettings {registration: RegistrationMode;- // Require a confirmed email address before the account can sign in. Needs a mail- // provider, so the api rejects turning it on while none is configured.+ // Require a confirmed email address before the account gets a session. Needs a+ // mail provider: the api rejects turning it on while none is configured, and+ // setEmailSettings clears it when the provider is removed.requireEmailVerification: boolean;// Offer sign-in by emailed link alongside the password.magicLink: boolean;@@ -170,6 +171,11 @@ export async function setEmailSettings(patch: InstanceEmailPatch): Promise<Instaconst next = await resolveEmailConfig(patch);const redacted = toEmailDto(next);await writeSecret(INSTANCE_EMAIL_SECRET_KEY, next, redacted);+ // Without a provider no confirmation link can be sent, so the requirement goes+ // with it rather than locking every new account out.+ if (!hasEmailProvider(next) && (await getAuthSettings()).requireEmailVerification) {+ await setAuthSettings({ requireEmailVerification: false });+ }return redacted;}