Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/sim/app/(auth)/signup/signup-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { usePostHog } from 'posthog-js/react'
import { trackFreebuffConversion } from '@/lib/analytics/freebuff'
import { trackGoogleEvent } from '@/lib/analytics/google'
import { client, useSession } from '@/lib/auth/client'
import { DISPOSABLE_EMAIL_ERROR_CODE, DISPOSABLE_EMAIL_MESSAGE } from '@/lib/auth/constants'
import { useTrackingConsent } from '@/lib/consent/tracking-consent'
import { getEnv, isFalsy } from '@/lib/core/config/env'
import { isSsoEnabled } from '@/lib/core/config/env-flags'
Expand Down Expand Up @@ -301,6 +302,9 @@ function SignupFormContent({
if (ctx.error.code?.includes('USER_ALREADY_EXISTS')) {
errorCode = 'user_already_exists'
setEmailError('An account with this email already exists. Please sign in instead.')
} else if (ctx.error.code === DISPOSABLE_EMAIL_ERROR_CODE) {
errorCode = 'disposable_email'
setEmailError(DISPOSABLE_EMAIL_MESSAGE)
} else if (
ctx.error.code?.includes('BAD_REQUEST') ||
ctx.error.message?.includes('Email and password sign up is not enabled')
Expand Down
16 changes: 3 additions & 13 deletions apps/sim/lib/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,11 @@ import { stableExternalAccountId } from '@/lib/auth/connectors/account-id'
import { buildConnectorProviders } from '@/lib/auth/connectors/providers'
import {
applyRegistrationGate,
DISPOSABLE_EMAIL_ERROR_CODE,
DISPOSABLE_EMAIL_MESSAGE,
getRequestedSignInProviderId,
isSignInProviderAllowed,
} from '@/lib/auth/constants'
import { getAuthDatabase } from '@/lib/auth/database-context'
import { refuseDisposableAccountEmail } from '@/lib/auth/disposable-email-gate'
import {
type AuthenticationSecurityAuditSnapshot,
captureAuthenticationSecurityAudit,
Expand Down Expand Up @@ -153,7 +152,6 @@ import {
processCredentialDraft,
refuseConflictingCredentialReconnect,
} from '@/lib/credentials/draft-processor'
import { isDisposableEmail } from '@/lib/messaging/email/disposable'
import { sendEmail } from '@/lib/messaging/email/mailer'
import { getFromEmailAddress, getPersonalEmailFrom } from '@/lib/messaging/email/utils'
import { quickValidateEmail } from '@/lib/messaging/email/validation'
Expand Down Expand Up @@ -359,20 +357,12 @@ export const auth = betterAuth({
databaseHooks: {
user: {
create: {
before: async (user) => {
before: async (user, context) => {
const accessControl = await getAccessControlConfig()
if (isEmailBlockedByAccessControl(user.email, accessControl)) {
throw new Error('Sign-ups from this email are not allowed.')
}
if (isHosted && (await isDisposableEmail(user.email))) {
logger.warn('Refusing account creation for a disposable email domain', {
domain: user.email.split('@')[1],
})
throw new APIError('FORBIDDEN', {
code: DISPOSABLE_EMAIL_ERROR_CODE,
message: DISPOSABLE_EMAIL_MESSAGE,
})
}
if (isHosted) await refuseDisposableAccountEmail(user.email, context?.path)
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
return { data: user }
},
after: async (user, context) => {
Expand Down
83 changes: 83 additions & 0 deletions apps/sim/lib/auth/disposable-email-gate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { betterAuth } from 'better-auth'
import { memoryAdapter } from 'better-auth/adapters/memory'
import { admin } from 'better-auth/plugins'
import { describe, expect, it } from 'vitest'
import { DISPOSABLE_EMAIL_ERROR_CODE } from '@/lib/auth/constants'
import { refuseDisposableAccountEmail } from '@/lib/auth/disposable-email-gate'
import { configuredSsoPlugin } from '@/lib/auth/sso/plugin'

/**
* A real Better Auth instance wired the way `auth.ts` wires the gate, so the endpoint path each
* creation path reports to `databaseHooks.user.create.before` is Better Auth's, not an assumption.
*/
function createAuth() {
return betterAuth({
baseURL: 'http://localhost:3000',
secret: 'disposable-email-gate-test-secret-0123456789',
database: memoryAdapter({ user: [], session: [], account: [], verification: [] }),
emailAndPassword: { enabled: true },
plugins: [admin()],
databaseHooks: {
user: {
create: {
before: async (user, context) => {
await refuseDisposableAccountEmail(user.email, context?.path)
return { data: user }
},
},
},
},
})
}

const password = 'correct-horse-battery-staple'

describe('refuseDisposableAccountEmail', () => {
it('refuses a self-service email signup from a disposable domain', async () => {
const auth = createAuth()
await expect(
auth.api.signUpEmail({ body: { email: 'jane@mailinator.com', password, name: 'Jane' } })
).rejects.toMatchObject({ body: { code: DISPOSABLE_EMAIL_ERROR_CODE } })
})

it('admits a self-service email signup from a company under a public suffix', async () => {
const auth = createAuth()
const result = await auth.api.signUpEmail({
body: { email: 'jane@company.msk.ru', password, name: 'Jane' },
})
expect(result.user.email).toBe('jane@company.msk.ru')
})

/** SCIM provisioning creates accounts through the admin plugin's server-side `createUser`. */
it('admits a directory-provisioned account whatever its domain', async () => {
const auth = createAuth()
const result = await auth.api.createUser({
body: { email: 'jane@mailinator.com', name: 'Jane' },
})
expect(result.user.email).toBe('jane@mailinator.com')
})

/**
* Better Auth dispatches with an endpoint's declared path, so the SSO plugin's own callback
* endpoints name the paths a just-in-time creation reports. No IdP is driven here.
*/
const { callbackSSO, callbackSSOShared, callbackSSOSAML, acsEndpoint } =
configuredSsoPlugin.endpoints
it.each([callbackSSO.path, callbackSSOShared.path, callbackSSOSAML.path, acsEndpoint.path])(
'admits any domain at the SSO plugin callback path %s',
async (path) => {
await expect(
refuseDisposableAccountEmail('jane@mailinator.com', path)
).resolves.toBeUndefined()
}
)

it.each([undefined, '/sign-up/email', '/callback/:id', '/oauth2/callback/:providerId'])(
'refuses a disposable domain created at %s',
async (path) => {
await expect(refuseDisposableAccountEmail('jane@mailinator.com', path)).rejects.toMatchObject(
{ body: { code: DISPOSABLE_EMAIL_ERROR_CODE } }
)
}
)
})
48 changes: 48 additions & 0 deletions apps/sim/lib/auth/disposable-email-gate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { createLogger } from '@sim/logger'
import { APIError } from 'better-auth/api'
import { DISPOSABLE_EMAIL_ERROR_CODE, DISPOSABLE_EMAIL_MESSAGE } from '@/lib/auth/constants'
import { isSsoCallbackPath } from '@/lib/auth/sso/callback-provider'
import { emailDomain, isDisposableEmail } from '@/lib/messaging/email/disposable'

const logger = createLogger('DisposableEmailGate')

/**
* The admin plugin's endpoint, which SCIM provisioning calls server-side. Over HTTP it requires a
* platform admin's session, so either way an account created here was not self-service.
*/
const ADMIN_CREATE_USER_PATH = '/admin/create-user'

/**
* Whether the account is being created on behalf of an organization: SCIM provisioning, or
* just-in-time creation at an SSO callback (Sim admits SSO only through a provider whose domain
* the organization verified). The organization vouches for the identity, so a throwaway inbox is
* not the risk, while a false positive breaks provisioning (a refused SCIM create is retried by
* the IdP indefinitely).
*/
function isOrganizationProvisioned(path: string | undefined): boolean {
return path !== undefined && (path === ADMIN_CREATE_USER_PATH || isSsoCallbackPath(path))
}

/**
* Refuses self-service account creation from a disposable email domain, throwing the
* `DISPOSABLE_EMAIL` error the signup form and OAuth error page recognize.
*
* @param path - the Better Auth endpoint the creation runs under (`context?.path` in
* `databaseHooks.user.create.before`), which tells organization provisioning apart from signup.
*/
export async function refuseDisposableAccountEmail(
email: string,
path: string | undefined
): Promise<void> {
if (isOrganizationProvisioned(path)) return
if (!(await isDisposableEmail(email))) return

logger.warn('Refusing account creation for a disposable email domain', {
domain: emailDomain(email),
path,
})
throw new APIError('FORBIDDEN', {
code: DISPOSABLE_EMAIL_ERROR_CODE,
message: DISPOSABLE_EMAIL_MESSAGE,
})
}
Loading
Loading