Skip to content

Commit efae888

Browse files
authored
fix(auth): two-factor final audit fixes (#10750)
* fix(auth): keep handed-over desktop sessions from counting as fresh, sign out swept members everywhere, audit sign-in lockouts * improvement(auth): revoke grants after sessions, tighten the final-audit tests * improvement(auth): share the organization two-factor refusal message
1 parent d69cfb6 commit efae888

15 files changed

Lines changed: 182 additions & 55 deletions

File tree

‎apps/docs/content/docs/platform/two-factor-authentication.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,15 @@ When you sign in on a device, you can choose **Don't ask again on this device fo
2121

2222
## Change your authenticator app
2323

24-
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.
24+
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.
2525

2626
## Backup codes
2727

2828
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.
2929

3030
## Turn off 2FA
3131

32-
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.
32+
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.
3333

3434
<Callout type="info">
3535
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.

‎apps/sim/app/(auth)/login/login-form.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { createLogger } from '@sim/logger'
66
import { getErrorMessage } from '@sim/utils/errors'
77
import { normalizeEmail } from '@sim/utils/string'
88
import { useRouter, useSearchParams } from 'next/navigation'
9-
import { buildTwoFactorPagePath, readTwoFactorChallenge } from '@/components/two-factor/utils'
9+
import { buildTwoFactorPagePath, readTwoFactorChallenge } from '@/components/two-factor'
1010
import { requestJson } from '@/lib/api/client/request'
1111
import { forgetPasswordContract } from '@/lib/api/contracts'
1212
import { client } from '@/lib/auth/client'

‎apps/sim/app/(auth)/signup/signup-form.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { Turnstile, type TurnstileInstance } from '@marsidev/react-turnstile'
55
import { createLogger } from '@sim/logger'
66
import { useRouter, useSearchParams } from 'next/navigation'
77
import { usePostHog } from 'posthog-js/react'
8-
import { buildTwoFactorPagePath, readTwoFactorChallenge } from '@/components/two-factor/utils'
8+
import { buildTwoFactorPagePath, readTwoFactorChallenge } from '@/components/two-factor'
99
import { trackGoogleEvent } from '@/lib/analytics/google'
1010
import { client, useSession } from '@/lib/auth/client'
1111
import { DISPOSABLE_EMAIL_ERROR_CODE, DISPOSABLE_EMAIL_MESSAGE } from '@/lib/auth/constants'

‎apps/sim/app/(auth)/verify/use-verification.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { useEffect, useState } from 'react'
44
import { createLogger } from '@sim/logger'
55
import { normalizeEmail } from '@sim/utils/string'
66
import { useSearchParams } from 'next/navigation'
7-
import { buildTwoFactorPagePath, readTwoFactorChallenge } from '@/components/two-factor/utils'
7+
import { buildTwoFactorPagePath, readTwoFactorChallenge } from '@/components/two-factor'
88
import { client, useSession } from '@/lib/auth/client'
99
import { SSO_REQUIRED_ERROR_CODE } from '@/lib/auth/constants'
1010
import { validateCallbackUrl } from '@/lib/core/security/input-validation'

‎apps/sim/app/api/desktop/auth/handoff/route.test.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ const { mockGetSession, mockCreateSession, mockCreateVerificationValue } = authM
1616

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

2021
function request() {
2122
return createMockRequest('POST', undefined, {}, 'http://localhost:3000/api/desktop/auth/handoff')
@@ -26,7 +27,7 @@ describe('POST /api/desktop/auth/handoff', () => {
2627
mockEnforceIpRateLimit.mockResolvedValue(null)
2728
mockGetSession.mockResolvedValue({
2829
user: { id: 'user-1' },
29-
session: { token: BROWSER_SESSION_TOKEN },
30+
session: { token: BROWSER_SESSION_TOKEN, createdAt: BROWSER_SIGNED_IN_AT },
3031
})
3132
mockCreateSession.mockResolvedValue({ id: 'session-2', token: DESKTOP_SESSION_TOKEN })
3233
})
@@ -38,9 +39,12 @@ describe('POST /api/desktop/auth/handoff', () => {
3839
const response = await POST(request())
3940

4041
expect(response.status).toBe(200)
41-
expect(mockCreateSession).toHaveBeenCalledWith('user-1', false, {
42-
userAgent: 'Sim Desktop',
43-
})
42+
expect(mockCreateSession).toHaveBeenCalledWith(
43+
'user-1',
44+
false,
45+
{ userAgent: 'Sim Desktop', createdAt: BROWSER_SIGNED_IN_AT },
46+
true
47+
)
4448
expect(mockCreateVerificationValue).toHaveBeenCalledTimes(1)
4549
const verification = mockCreateVerificationValue.mock.calls[0][0]
4650
expect(verification.value).toBe(DESKTOP_SESSION_TOKEN)

‎apps/sim/app/api/desktop/auth/handoff/route.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,10 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
4343
}
4444

4545
try {
46-
const token = await createDesktopHandoffToken(session.user.id)
46+
const token = await createDesktopHandoffToken({
47+
userId: session.user.id,
48+
createdAt: new Date(session.session.createdAt),
49+
})
4750
return NextResponse.json({ token })
4851
} catch (error) {
4952
/**

‎apps/sim/components/two-factor/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
export {
22
BACKUP_CODE_MAX_LENGTH,
33
BACKUP_CODES_HINT,
4+
buildTwoFactorPagePath,
45
describeTwoFactorError,
56
isExpiredTwoFactorChallenge,
67
normalizeBackupCode,
78
normalizeStepUpCode,
89
normalizeTotpCode,
910
readTotpSecret,
11+
readTwoFactorChallenge,
1012
readTwoFactorErrorCode,
1113
TOTP_CODE_LENGTH,
1214
type TwoFactorEnrollment,

‎apps/sim/components/two-factor/utils.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
import { isRecordLike } from '@sim/utils/object'
2-
import { TWO_FACTOR_PAGE_PATH } from '@/lib/auth/constants'
2+
import {
3+
TWO_FACTOR_PAGE_PATH,
4+
TWO_FACTOR_REQUIRED_BY_ORGANIZATION_ERROR_CODE,
5+
TWO_FACTOR_REQUIRED_BY_ORGANIZATION_MESSAGE,
6+
TWO_FACTOR_REQUIRED_ERROR_CODE,
7+
TWO_FACTOR_REQUIRED_MESSAGE,
8+
TWO_FACTOR_SETUP_REQUIRED_ERROR_CODE,
9+
TWO_FACTOR_SETUP_REQUIRED_MESSAGE,
10+
} from '@/lib/auth/constants'
311

412
/** Digits in an authenticator app code. */
513
export const TOTP_CODE_LENGTH = 6
@@ -75,7 +83,9 @@ const ERROR_MESSAGES: Record<string, string> = {
7583
TWO_FACTOR_SETUP_INCOMPLETE: 'Finish setting up your authenticator app to continue.',
7684
TWO_FACTOR_ALREADY_VERIFIED: 'Two-factor authentication is already set up.',
7785
TWO_FACTOR_ALREADY_ENABLED: 'Two-factor authentication is already set up. Enter a code.',
78-
TWO_FACTOR_REQUIRED: 'Your organization requires two-factor authentication.',
86+
[TWO_FACTOR_REQUIRED_ERROR_CODE]: TWO_FACTOR_REQUIRED_MESSAGE,
87+
[TWO_FACTOR_SETUP_REQUIRED_ERROR_CODE]: TWO_FACTOR_SETUP_REQUIRED_MESSAGE,
88+
[TWO_FACTOR_REQUIRED_BY_ORGANIZATION_ERROR_CODE]: TWO_FACTOR_REQUIRED_BY_ORGANIZATION_MESSAGE,
7989
INVALID_PASSWORD: 'Incorrect password.',
8090
SESSION_NOT_FRESH: 'For your security, sign out and sign back in, then try again.',
8191
}

‎apps/sim/lib/auth/auth.ts‎

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ import { fetchSalesforceInstanceUrl } from '@/lib/oauth/salesforce-instance.serv
200200
import { extractSlackTeamId, fanOutSlackTokenChain } from '@/lib/oauth/slack'
201201
import { getCanonicalScopesForProvider } from '@/lib/oauth/utils'
202202
import { joinInstanceOrganization } from '@/lib/organizations/instance-org'
203+
import { revokeAllUserSessions } from '@/lib/organizations/members/revocation'
203204
import { capabilityRefusal } from '@/lib/permission-groups/capability-assertions'
204205
import { isCapabilityWithheldForUser } from '@/lib/permission-groups/user-scope.server'
205206
import { captureServerEvent, getPostHogClient } from '@/lib/posthog/server'
@@ -2041,13 +2042,13 @@ async function getSessionImpl() {
20412042
type ResolvedSession = Awaited<ReturnType<typeof auth.api.getSession>>
20422043

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

‎apps/sim/lib/auth/constants.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,18 @@ export const TWO_FACTOR_REQUIRED_ERROR_CODE = 'TWO_FACTOR_REQUIRED'
116116
export const TWO_FACTOR_REQUIRED_MESSAGE =
117117
'This account uses two-factor authentication. Sign in again to enter your code.'
118118

119+
/** A session refused because the member's organization requires two-factor they have not set up. */
120+
export const TWO_FACTOR_SETUP_REQUIRED_ERROR_CODE = 'TWO_FACTOR_SETUP_REQUIRED'
121+
122+
export const TWO_FACTOR_SETUP_REQUIRED_MESSAGE =
123+
'Your organization requires two-factor authentication. Sign in again to set it up.'
124+
125+
/** Turning two-factor off, refused because the member's organization requires it. */
126+
export const TWO_FACTOR_REQUIRED_BY_ORGANIZATION_ERROR_CODE = 'TWO_FACTOR_REQUIRED_BY_ORGANIZATION'
127+
128+
export const TWO_FACTOR_REQUIRED_BY_ORGANIZATION_MESSAGE =
129+
'Your organization requires two-factor authentication.'
130+
119131
/** A backup code offered before a required enrollment proved the authenticator app. */
120132
export const TWO_FACTOR_SETUP_INCOMPLETE_ERROR_CODE = 'TWO_FACTOR_SETUP_INCOMPLETE'
121133

0 commit comments

Comments
 (0)