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: 2 additions & 2 deletions apps/docs/content/docs/platform/two-factor-authentication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ When you sign in on a device, you can choose **Don't ask again on this device fo

## Change your authenticator app

Select **Change authenticator app** and enter a current code from your app or a backup code. Your old app and backup codes stop working right away. Scan the new QR code, save the new backup codes, and enter a code from the new app to finish. Until you finish, only the new backup codes sign you in.
Select **Change authenticator app** and enter a current code from your app or a backup code, plus your password if your account has one. Your old app and backup codes stop working right away. Scan the new QR code, save the new backup codes, and enter a code from the new app to finish. Until you finish, only the new backup codes sign you in.

## Backup codes

Use a backup code when your authenticator app isn't available. Select **Use a backup code instead** on the code screen. To get a new set, select **Regenerate backup codes** in settings; this replaces every earlier code.

## Turn off 2FA

Select **Turn off** in settings and enter a current code from your app or a backup code. If your organization requires 2FA, you can't turn it off.
Select **Turn off** in settings and enter a current code from your app or a backup code, plus your password if your account has one. If your organization requires 2FA, you can't turn it off.

<Callout type="info">
Turning off 2FA, regenerating backup codes, or setting up a new authenticator always needs a current code, so someone with access to a signed-in browser can't remove your second factor.
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/app/(auth)/login/login-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { normalizeEmail } from '@sim/utils/string'
import { useRouter, useSearchParams } from 'next/navigation'
import { buildTwoFactorPagePath, readTwoFactorChallenge } from '@/components/two-factor/utils'
import { buildTwoFactorPagePath, readTwoFactorChallenge } from '@/components/two-factor'
import { requestJson } from '@/lib/api/client/request'
import { forgetPasswordContract } from '@/lib/api/contracts'
import { client } from '@/lib/auth/client'
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/app/(auth)/signup/signup-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Turnstile, type TurnstileInstance } from '@marsidev/react-turnstile'
import { createLogger } from '@sim/logger'
import { useRouter, useSearchParams } from 'next/navigation'
import { usePostHog } from 'posthog-js/react'
import { buildTwoFactorPagePath, readTwoFactorChallenge } from '@/components/two-factor/utils'
import { buildTwoFactorPagePath, readTwoFactorChallenge } from '@/components/two-factor'
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'
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/app/(auth)/verify/use-verification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useEffect, useState } from 'react'
import { createLogger } from '@sim/logger'
import { normalizeEmail } from '@sim/utils/string'
import { useSearchParams } from 'next/navigation'
import { buildTwoFactorPagePath, readTwoFactorChallenge } from '@/components/two-factor/utils'
import { buildTwoFactorPagePath, readTwoFactorChallenge } from '@/components/two-factor'
import { client, useSession } from '@/lib/auth/client'
import { SSO_REQUIRED_ERROR_CODE } from '@/lib/auth/constants'
import { validateCallbackUrl } from '@/lib/core/security/input-validation'
Expand Down
12 changes: 8 additions & 4 deletions apps/sim/app/api/desktop/auth/handoff/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const { mockGetSession, mockCreateSession, mockCreateVerificationValue } = authM

const BROWSER_SESSION_TOKEN = 'browser-session-token'
const DESKTOP_SESSION_TOKEN = 'desktop-session-token'
const BROWSER_SIGNED_IN_AT = new Date('2026-01-01T00:00:00Z')

function request() {
return createMockRequest('POST', undefined, {}, 'http://localhost:3000/api/desktop/auth/handoff')
Expand All @@ -26,7 +27,7 @@ describe('POST /api/desktop/auth/handoff', () => {
mockEnforceIpRateLimit.mockResolvedValue(null)
mockGetSession.mockResolvedValue({
user: { id: 'user-1' },
session: { token: BROWSER_SESSION_TOKEN },
session: { token: BROWSER_SESSION_TOKEN, createdAt: BROWSER_SIGNED_IN_AT },
})
mockCreateSession.mockResolvedValue({ id: 'session-2', token: DESKTOP_SESSION_TOKEN })
})
Expand All @@ -38,9 +39,12 @@ describe('POST /api/desktop/auth/handoff', () => {
const response = await POST(request())

expect(response.status).toBe(200)
expect(mockCreateSession).toHaveBeenCalledWith('user-1', false, {
userAgent: 'Sim Desktop',
})
expect(mockCreateSession).toHaveBeenCalledWith(
'user-1',
false,
{ userAgent: 'Sim Desktop', createdAt: BROWSER_SIGNED_IN_AT },
true
)
expect(mockCreateVerificationValue).toHaveBeenCalledTimes(1)
const verification = mockCreateVerificationValue.mock.calls[0][0]
expect(verification.value).toBe(DESKTOP_SESSION_TOKEN)
Expand Down
5 changes: 4 additions & 1 deletion apps/sim/app/api/desktop/auth/handoff/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
}

try {
const token = await createDesktopHandoffToken(session.user.id)
const token = await createDesktopHandoffToken({
userId: session.user.id,
createdAt: new Date(session.session.createdAt),
})
return NextResponse.json({ token })
} catch (error) {
/**
Expand Down
2 changes: 2 additions & 0 deletions apps/sim/components/two-factor/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
export {
BACKUP_CODE_MAX_LENGTH,
BACKUP_CODES_HINT,
buildTwoFactorPagePath,
describeTwoFactorError,
isExpiredTwoFactorChallenge,
normalizeBackupCode,
normalizeStepUpCode,
normalizeTotpCode,
readTotpSecret,
readTwoFactorChallenge,
readTwoFactorErrorCode,
TOTP_CODE_LENGTH,
type TwoFactorEnrollment,
Expand Down
14 changes: 12 additions & 2 deletions apps/sim/components/two-factor/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { isRecordLike } from '@sim/utils/object'
import { TWO_FACTOR_PAGE_PATH } from '@/lib/auth/constants'
import {
TWO_FACTOR_PAGE_PATH,
TWO_FACTOR_REQUIRED_BY_ORGANIZATION_ERROR_CODE,
TWO_FACTOR_REQUIRED_BY_ORGANIZATION_MESSAGE,
TWO_FACTOR_REQUIRED_ERROR_CODE,
TWO_FACTOR_REQUIRED_MESSAGE,
TWO_FACTOR_SETUP_REQUIRED_ERROR_CODE,
TWO_FACTOR_SETUP_REQUIRED_MESSAGE,
} from '@/lib/auth/constants'

/** Digits in an authenticator app code. */
export const TOTP_CODE_LENGTH = 6
Expand Down Expand Up @@ -75,7 +83,9 @@ const ERROR_MESSAGES: Record<string, string> = {
TWO_FACTOR_SETUP_INCOMPLETE: 'Finish setting up your authenticator app to continue.',
TWO_FACTOR_ALREADY_VERIFIED: 'Two-factor authentication is already set up.',
TWO_FACTOR_ALREADY_ENABLED: 'Two-factor authentication is already set up. Enter a code.',
TWO_FACTOR_REQUIRED: 'Your organization requires two-factor authentication.',
[TWO_FACTOR_REQUIRED_ERROR_CODE]: TWO_FACTOR_REQUIRED_MESSAGE,
[TWO_FACTOR_SETUP_REQUIRED_ERROR_CODE]: TWO_FACTOR_SETUP_REQUIRED_MESSAGE,
[TWO_FACTOR_REQUIRED_BY_ORGANIZATION_ERROR_CODE]: TWO_FACTOR_REQUIRED_BY_ORGANIZATION_MESSAGE,
INVALID_PASSWORD: 'Incorrect password.',
SESSION_NOT_FRESH: 'For your security, sign out and sign back in, then try again.',
}
Expand Down
21 changes: 9 additions & 12 deletions apps/sim/lib/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ import { fetchSalesforceInstanceUrl } from '@/lib/oauth/salesforce-instance.serv
import { extractSlackTeamId, fanOutSlackTokenChain } from '@/lib/oauth/slack'
import { getCanonicalScopesForProvider } from '@/lib/oauth/utils'
import { joinInstanceOrganization } from '@/lib/organizations/instance-org'
import { revokeAllUserSessions } from '@/lib/organizations/members/revocation'
import { capabilityRefusal } from '@/lib/permission-groups/capability-assertions'
import { isCapabilityWithheldForUser } from '@/lib/permission-groups/user-scope.server'
import { captureServerEvent, getPostHogClient } from '@/lib/posthog/server'
Expand Down Expand Up @@ -2041,13 +2042,13 @@ async function getSessionImpl() {
type ResolvedSession = Awaited<ReturnType<typeof auth.api.getSession>>

/**
* Ends a session whose user's organization requires two-factor authentication they have not set
* up. Sign-in already refuses such a session, so this catches the ones that predate the
* requirement or the membership: someone who joined, or whose organization turned the requirement
* on, while signed in. Revoking rather than only hiding it means the session also stops working on
* Better Auth's own endpoints, and the member's OAuth grants go with it so an MCP client
* authorized from the session does not outlive it; the app's stale-session recovery then sends
* them to sign in, where they are asked to enroll. Every server read of the current session
* Signs out a member whose organization requires two-factor authentication they have not set up.
* Sign-in already refuses such a session, so this catches the ones that predate the requirement or
* the membership: someone who joined, or whose organization turned the requirement on, while
* signed in. Every one of their sessions and OAuth grants ends together, through the same
* revocation as removal and suspension, so cached session cookies re-read the database at once and
* an MCP client authorized from a session does not outlive it; the app's stale-session recovery
* then sends them to sign in, where they are asked to enroll. Every server read of the current session
* goes through this — `getSession` and the desktop pages that read the session directly to bypass
* the cookie cache.
*
Expand Down Expand Up @@ -2086,11 +2087,7 @@ export async function enforceTwoFactorRequirement(
userId: session.user.id,
organizationId,
})
/** Together, so a failed grant revocation cannot leave the grants behind a deleted session. */
await db.transaction(async (tx) => {
await tx.delete(schema.session).where(eq(schema.session.id, session.session.id))
await revokeUserOAuthGrants(session.user.id, tx)
})
await revokeAllUserSessions(session.user.id, { revokeOAuthGrants: true })
return null
}

Expand Down
12 changes: 12 additions & 0 deletions apps/sim/lib/auth/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,18 @@ export const TWO_FACTOR_REQUIRED_ERROR_CODE = 'TWO_FACTOR_REQUIRED'
export const TWO_FACTOR_REQUIRED_MESSAGE =
'This account uses two-factor authentication. Sign in again to enter your code.'

/** A session refused because the member's organization requires two-factor they have not set up. */
export const TWO_FACTOR_SETUP_REQUIRED_ERROR_CODE = 'TWO_FACTOR_SETUP_REQUIRED'

export const TWO_FACTOR_SETUP_REQUIRED_MESSAGE =
'Your organization requires two-factor authentication. Sign in again to set it up.'

/** Turning two-factor off, refused because the member's organization requires it. */
export const TWO_FACTOR_REQUIRED_BY_ORGANIZATION_ERROR_CODE = 'TWO_FACTOR_REQUIRED_BY_ORGANIZATION'
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved

export const TWO_FACTOR_REQUIRED_BY_ORGANIZATION_MESSAGE =
'Your organization requires two-factor authentication.'

/** A backup code offered before a required enrollment proved the authenticator app. */
export const TWO_FACTOR_SETUP_INCOMPLETE_ERROR_CODE = 'TWO_FACTOR_SETUP_INCOMPLETE'

Expand Down
31 changes: 25 additions & 6 deletions apps/sim/lib/auth/desktop-handoff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,21 @@ const HANDOFF_TOKEN_TTL_MS = 3 * 60 * 1000
*/
const DESKTOP_SESSION_USER_AGENT = 'Sim Desktop'

/** The browser session authorizing a desktop sign-in. */
interface AuthorizingSession {
userId: string
/** When that session's user signed in. */
createdAt: Date
}

/**
* Mints a one-time token that signs the desktop app in as `userId` on a session
* of its own.
* Mints a one-time token that signs the desktop app in on a session of its own.
*
* The desktop session keeps the authorizing session's sign-in time rather than
* starting a new one. It is handed over, not earned by signing in again, so it
* must not look like a fresh sign-in to the check that asks for one (turning on
* two-factor authentication without a password) or restart an organization's
* maximum session lifetime, which is measured from that time.
*
* Better Auth's `generateOneTimeToken` binds the token to the *calling* session
* row, and `/one-time-token/verify` then hands that same row's cookie to
Expand All @@ -52,11 +64,18 @@ const DESKTOP_SESSION_USER_AGENT = 'Sim Desktop'
* does, and what RFC 8252 assumes of a native app: sign-out, revocation, and
* expiry apply to one surface at a time.
*/
export async function createDesktopHandoffToken(userId: string): Promise<string> {
export async function createDesktopHandoffToken({
userId,
createdAt,
}: AuthorizingSession): Promise<string> {
const ctx = await auth.$context
const desktopSession = await ctx.internalAdapter.createSession(userId, false, {
userAgent: DESKTOP_SESSION_USER_AGENT,
})
/** `overrideAll`: Better Auth otherwise stamps a new session with the current time. */
const desktopSession = await ctx.internalAdapter.createSession(
userId,
false,
{ userAgent: DESKTOP_SESSION_USER_AGENT, createdAt },
true
)

const token = generateShortId(HANDOFF_TOKEN_LENGTH)
await ctx.internalAdapter.createVerificationValue({
Expand Down
56 changes: 55 additions & 1 deletion apps/sim/lib/auth/two-factor/guard.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ describe('two-factor authentication in PostgreSQL', () => {
let auth: typeof import('@/lib/auth/auth').auth
let prepareSessionForCreation: typeof import('@/lib/auth/session-hooks').prepareSessionForCreation
let enforceTwoFactorRequirement: typeof import('@/lib/auth/auth').enforceTwoFactorRequirement
let createDesktopHandoffToken: typeof import('@/lib/auth/desktop-handoff').createDesktopHandoffToken
let invalidateTwoFactorPolicyCache: typeof import('@/lib/auth/two-factor/policy').invalidateTwoFactorPolicyCache
let isTwoFactorRequiredForOrganization: typeof import('@/lib/auth/two-factor/policy').isTwoFactorRequiredForOrganization
let readOrganizationTwoFactorPolicy: typeof import('@/lib/organizations/application/two-factor-policy').readOrganizationTwoFactorPolicy
Expand All @@ -46,6 +47,7 @@ describe('two-factor authentication in PostgreSQL', () => {

beforeAll(async () => {
;({ auth, enforceTwoFactorRequirement } = await import('@/lib/auth/auth'))
;({ createDesktopHandoffToken } = await import('@/lib/auth/desktop-handoff'))
;({ prepareSessionForCreation } = await import('@/lib/auth/session-hooks'))
;({ invalidateTwoFactorPolicyCache, isTwoFactorRequiredForOrganization } = await import(
'@/lib/auth/two-factor/policy'
Expand Down Expand Up @@ -415,6 +417,9 @@ describe('two-factor authentication in PostgreSQL', () => {
request('/two-factor/disable', { password, code: await currentCode(totpURI) }, cookie)
)
expect(whileRequired.status).toBe(403)
expect(await whileRequired.json()).toMatchObject({
code: 'TWO_FACTOR_REQUIRED_BY_ORGANIZATION',
})

await setRequirement(organizationId, false)
const allowed = await auth.handler(
Expand Down Expand Up @@ -610,10 +615,12 @@ describe('two-factor authentication in PostgreSQL', () => {
expect(recipients).toEqual([fixture.email, fixture.email, fixture.email, fixture.email])
})

it('ends an unenrolled member’s session and OAuth grants once their organization requires it', async () => {
it('ends an unenrolled member’s sessions and OAuth grants once their organization requires it', async () => {
const fixture = await createUser()
const organizationId = await createOrganization([{ userId: fixture.id, role: 'member' }])
await signInWithPassword(fixture.email)
const { cookie } = await signInWithPassword(fixture.email)
expect(await sessionCount(fixture.id)).toBe(2)
const [current] = await db
.select({ id: session.id })
.from(session)
Expand Down Expand Up @@ -658,6 +665,53 @@ describe('two-factor authentication in PostgreSQL', () => {
}
})

it('keeps a handed-over desktop session from counting as a fresh sign-in', async () => {
const fixture = await createUser()
await db.delete(account).where(eq(account.userId, fixture.id))
const signedInLongAgo = new Date(Date.now() - 60 * 60 * 1000)

const token = await createDesktopHandoffToken({
userId: fixture.id,
createdAt: signedInLongAgo,
})
const redeemed = await auth.handler(request('/one-time-token/verify', { token }))
expect(redeemed.status).toBe(200)
const desktopCookie = cookieHeader(redeemed)
.split('; ')
.filter((entry) => !entry.includes('session_data'))
.join('; ')
const enable = await auth.handler(request('/two-factor/enable', {}, desktopCookie))

expect(enable.status).toBe(403)
expect(await enable.json()).toMatchObject({ code: 'SESSION_NOT_FRESH' })
})

it('audits the lockout when repeated wrong sign-in codes lock the account', async () => {
const fixture = await createUser()
await enroll(fixture.email)
await db.delete(session).where(eq(session.userId, fixture.id))
await db.delete(auditLog).where(eq(auditLog.resourceId, fixture.id))

for (let challenge = 0; challenge < 2; challenge++) {
const { cookie } = await signInWithPassword(fixture.email)
for (let attempt = 0; attempt < 5; attempt++) {
await auth.handler(request('/two-factor/verify-totp', { code: '000000' }, cookie))
}
}

const { cookie } = await signInWithPassword(fixture.email)
const afterLock = await auth.handler(
request('/two-factor/verify-totp', { code: '000000' }, cookie)
)
expect(afterLock.status).toBe(429)
await expect
.poll(async () => (await auditActions(fixture.id)).map((row) => row.action))
.toContain('auth.two_factor_locked')
expect(
(await auditActions(fixture.id)).filter((row) => row.action === 'auth.two_factor_locked')
).toHaveLength(1)
})

it('signs an administrator-reset member out of cached sessions as well', async () => {
const fixture = await createUser()
const operator = await createUser()
Expand Down
Loading
Loading