diff --git a/apps/docs/content/docs/platform/two-factor-authentication.mdx b/apps/docs/content/docs/platform/two-factor-authentication.mdx index 0f49f25855d..84cf46387fe 100644 --- a/apps/docs/content/docs/platform/two-factor-authentication.mdx +++ b/apps/docs/content/docs/platform/two-factor-authentication.mdx @@ -21,7 +21,7 @@ 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 @@ -29,7 +29,7 @@ Use a backup code when your authenticator app isn't available. Select **Use a ba ## 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. 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. diff --git a/apps/sim/app/(auth)/login/login-form.tsx b/apps/sim/app/(auth)/login/login-form.tsx index f7889b07309..90403bf1a4a 100644 --- a/apps/sim/app/(auth)/login/login-form.tsx +++ b/apps/sim/app/(auth)/login/login-form.tsx @@ -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' diff --git a/apps/sim/app/(auth)/signup/signup-form.tsx b/apps/sim/app/(auth)/signup/signup-form.tsx index 8b30a4255ee..1fcd98f3044 100644 --- a/apps/sim/app/(auth)/signup/signup-form.tsx +++ b/apps/sim/app/(auth)/signup/signup-form.tsx @@ -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' diff --git a/apps/sim/app/(auth)/verify/use-verification.ts b/apps/sim/app/(auth)/verify/use-verification.ts index 09770ada907..b2382f95c9d 100644 --- a/apps/sim/app/(auth)/verify/use-verification.ts +++ b/apps/sim/app/(auth)/verify/use-verification.ts @@ -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' diff --git a/apps/sim/app/api/desktop/auth/handoff/route.test.ts b/apps/sim/app/api/desktop/auth/handoff/route.test.ts index d890d180aa7..f4958a2f720 100644 --- a/apps/sim/app/api/desktop/auth/handoff/route.test.ts +++ b/apps/sim/app/api/desktop/auth/handoff/route.test.ts @@ -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') @@ -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 }) }) @@ -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) diff --git a/apps/sim/app/api/desktop/auth/handoff/route.ts b/apps/sim/app/api/desktop/auth/handoff/route.ts index 2f62344e971..ee0f7b30315 100644 --- a/apps/sim/app/api/desktop/auth/handoff/route.ts +++ b/apps/sim/app/api/desktop/auth/handoff/route.ts @@ -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) { /** diff --git a/apps/sim/components/two-factor/index.ts b/apps/sim/components/two-factor/index.ts index a11de440876..c466a733440 100644 --- a/apps/sim/components/two-factor/index.ts +++ b/apps/sim/components/two-factor/index.ts @@ -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, diff --git a/apps/sim/components/two-factor/utils.ts b/apps/sim/components/two-factor/utils.ts index 6e974c89568..83d16dac362 100644 --- a/apps/sim/components/two-factor/utils.ts +++ b/apps/sim/components/two-factor/utils.ts @@ -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 @@ -75,7 +83,9 @@ const ERROR_MESSAGES: Record = { 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.', } diff --git a/apps/sim/lib/auth/auth.ts b/apps/sim/lib/auth/auth.ts index 23468c5e059..c331e16edde 100644 --- a/apps/sim/lib/auth/auth.ts +++ b/apps/sim/lib/auth/auth.ts @@ -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' @@ -2041,13 +2042,13 @@ async function getSessionImpl() { type ResolvedSession = Awaited> /** - * 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. * @@ -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 } diff --git a/apps/sim/lib/auth/constants.ts b/apps/sim/lib/auth/constants.ts index d012c383671..714810bfd1b 100644 --- a/apps/sim/lib/auth/constants.ts +++ b/apps/sim/lib/auth/constants.ts @@ -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' + +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' diff --git a/apps/sim/lib/auth/desktop-handoff.ts b/apps/sim/lib/auth/desktop-handoff.ts index 40a321a0243..34a48ee12ed 100644 --- a/apps/sim/lib/auth/desktop-handoff.ts +++ b/apps/sim/lib/auth/desktop-handoff.ts @@ -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 @@ -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 { +export async function createDesktopHandoffToken({ + userId, + createdAt, +}: AuthorizingSession): Promise { 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({ diff --git a/apps/sim/lib/auth/two-factor/guard.integration.ts b/apps/sim/lib/auth/two-factor/guard.integration.ts index 4bdb278c3ac..7519c0a95ef 100644 --- a/apps/sim/lib/auth/two-factor/guard.integration.ts +++ b/apps/sim/lib/auth/two-factor/guard.integration.ts @@ -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 @@ -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' @@ -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( @@ -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) @@ -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() diff --git a/apps/sim/lib/auth/two-factor/guard.ts b/apps/sim/lib/auth/two-factor/guard.ts index a6a7fd0ab2f..e38bf95548e 100644 --- a/apps/sim/lib/auth/two-factor/guard.ts +++ b/apps/sim/lib/auth/two-factor/guard.ts @@ -18,11 +18,14 @@ import { z } from 'zod' import { TWO_FACTOR_ISSUER, 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_INCOMPLETE_ERROR_CODE, + TWO_FACTOR_SETUP_REQUIRED_ERROR_CODE, + TWO_FACTOR_SETUP_REQUIRED_MESSAGE, } from '@/lib/auth/constants' -import { revokeUserOAuthGrants } from '@/lib/auth/oauth-access-token' import { isSsoCallbackPath } from '@/lib/auth/sso/callback-provider' import { recordTwoFactorAudit } from '@/lib/auth/two-factor/audit' import { @@ -123,10 +126,12 @@ export async function assertTwoFactorAllowsSession( userId, path, }) - throw new APIError('FORBIDDEN', { - code: TWO_FACTOR_REQUIRED_ERROR_CODE, - message: TWO_FACTOR_REQUIRED_MESSAGE, - }) + throw new APIError( + 'FORBIDDEN', + state.enabled + ? { code: TWO_FACTOR_REQUIRED_ERROR_CODE, message: TWO_FACTOR_REQUIRED_MESSAGE } + : { code: TWO_FACTOR_SETUP_REQUIRED_ERROR_CODE, message: TWO_FACTOR_SETUP_REQUIRED_MESSAGE } + ) } type AuthMiddlewareContext = Parameters[0]>[0] @@ -333,6 +338,16 @@ async function assertStepUpCode( }) } +/** Whether the user's enrollment is inside a lockout from repeated wrong codes. */ +async function isLocked(userId: string): Promise { + const [row] = await db + .select({ lockedUntil: twoFactor.lockedUntil }) + .from(twoFactor) + .where(eq(twoFactor.userId, userId)) + .limit(1) + return Boolean(row?.lockedUntil && row.lockedUntil.getTime() > Date.now()) +} + const STEP_UP_PATHS = new Set([ '/two-factor/enable', '/two-factor/disable', @@ -429,8 +444,7 @@ export function twoFactorGuardPlugin() { where: [{ field: 'userId', value: target.id }], }) await ctx.context.internalAdapter.updateUser(target.id, { twoFactorEnabled: false }) - await revokeAllUserSessions(target.id) - await revokeUserOAuthGrants(target.id) + await revokeAllUserSessions(target.id, { revokeOAuthGrants: true }) await forgetTrustedDevices(target.id) logger.warn('Platform administrator reset two-factor authentication', { actorUserId: actor.id, @@ -595,8 +609,8 @@ export function twoFactorGuardPlugin() { const state = await getTwoFactorState(userId) if (ctx.path === '/two-factor/disable' && state.required) { throw new APIError('FORBIDDEN', { - code: TWO_FACTOR_REQUIRED_ERROR_CODE, - message: 'Your organization requires two-factor authentication.', + code: TWO_FACTOR_REQUIRED_BY_ORGANIZATION_ERROR_CODE, + message: TWO_FACTOR_REQUIRED_BY_ORGANIZATION_MESSAGE, }) } if (!state.enabled) { @@ -686,6 +700,13 @@ export function twoFactorGuardPlugin() { metadata: { secondFactor, statusCode: returned.statusCode }, request, }) + /** + * The plugin locks the account on the failure that spends its budget, which + * still answers as a wrong code; later attempts answer 429 without counting. + */ + if (returned.statusCode === 401 && (await isLocked(record.value))) { + await recordTwoFactorAudit({ event: 'locked', userId: record.value, request }) + } } } return diff --git a/apps/sim/lib/auth/two-factor/policy.ts b/apps/sim/lib/auth/two-factor/policy.ts index 7dfe5fdb5b2..ca21f1fe9a4 100644 --- a/apps/sim/lib/auth/two-factor/policy.ts +++ b/apps/sim/lib/auth/two-factor/policy.ts @@ -6,7 +6,7 @@ import { isOrganizationFeatureEntitled } from '@/lib/billing/core/subscription' import type { DbOrTx } from '@/lib/db/types' /** How long an organization's two-factor requirement is served from process memory. */ -export const TWO_FACTOR_POLICY_CACHE_TTL_MS = 60 * 1000 +const TWO_FACTOR_POLICY_CACHE_TTL_MS = 60 * 1000 /** * Read on every session read, so it is cached per organization. The ceiling is a memory backstop: diff --git a/apps/sim/lib/organizations/members/revocation.ts b/apps/sim/lib/organizations/members/revocation.ts index 65bea701233..1aa1480ffc3 100644 --- a/apps/sim/lib/organizations/members/revocation.ts +++ b/apps/sim/lib/organizations/members/revocation.ts @@ -1,6 +1,7 @@ import { db } from '@sim/db' import { apiKey, member, organization, session as sessionTable } from '@sim/db/schema' import { and, eq, isNull, ne, sql } from 'drizzle-orm' +import { revokeUserOAuthGrants } from '@/lib/auth/oauth-access-token' import { invalidateMembershipCache, invalidateSecurityPolicyVersionCache, @@ -66,27 +67,31 @@ export async function revokeUserSessionsTx( * the next request; someone in no organization has no cookie-cache version to move, and only the * cache's own lifetime bounds a cookie they already hold. Impersonation sessions are spared either * way. Membership is read inside the transaction, so a concurrent join or leave cannot leave the - * wrong organization's version unbumped. + * wrong organization's version unbumped. With `revokeOAuthGrants`, the user's OAuth grants end in + * the same transaction, so a connected app cannot outlive the sessions it was authorized from. */ -export async function revokeAllUserSessions(userId: string): Promise { +export async function revokeAllUserSessions( + userId: string, + options: { revokeOAuthGrants?: boolean } = {} +): Promise { const { organizationId, revoked } = await db.transaction(async (tx) => { const [membership] = await tx .select({ organizationId: member.organizationId }) .from(member) .where(eq(member.userId, userId)) .limit(1) - if (membership) { - const result = await revokeUserSessionsTx(tx, { - userId, - organizationId: membership.organizationId, - }) - return { organizationId: membership.organizationId, revoked: result.revoked } - } - const deleted = await tx - .delete(sessionTable) - .where(and(eq(sessionTable.userId, userId), isNull(sessionTable.impersonatedBy))) - .returning({ id: sessionTable.id }) - return { organizationId: null, revoked: deleted.length } + const revoked = membership + ? (await revokeUserSessionsTx(tx, { userId, organizationId: membership.organizationId })) + .revoked + : ( + await tx + .delete(sessionTable) + .where(and(eq(sessionTable.userId, userId), isNull(sessionTable.impersonatedBy))) + .returning({ id: sessionTable.id }) + ).length + /** After the sessions: a grant issued concurrently then fails its session reference. */ + if (options.revokeOAuthGrants) await revokeUserOAuthGrants(userId, tx) + return { organizationId: membership?.organizationId ?? null, revoked } }) if (organizationId) invalidateAfterSessionRevocation({ userId, organizationId }) return { revoked }