From df842757896a9f851e9c3f3989af92b86fb8e71f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 16:35:00 -0600 Subject: [PATCH 1/4] fix(auth): read the two-factor requirement fresh at sign-in, sweep OAuth grants, end cached sessions on reset --- apps/sim/lib/auth/auth.ts | 22 ++-- .../lib/auth/two-factor/guard.integration.ts | 100 +++++++++++++++++- apps/sim/lib/auth/two-factor/guard.ts | 31 +++++- apps/sim/lib/auth/two-factor/policy.ts | 50 ++++++--- 4 files changed, 175 insertions(+), 28 deletions(-) diff --git a/apps/sim/lib/auth/auth.ts b/apps/sim/lib/auth/auth.ts index 02580df56e1..b38a1c36dcf 100644 --- a/apps/sim/lib/auth/auth.ts +++ b/apps/sim/lib/auth/auth.ts @@ -2045,9 +2045,17 @@ type ResolvedSession = Awaited> * 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; 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. + * Better Auth's own endpoints, and the member's OAuth grants go with it, since an MCP client + * authorized from that session would otherwise 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. + * + * A requirement that cannot be read leaves the session as it is. This is a sweep behind the + * controls that fail closed — sign-in refuses an unenrolled member, and turning the requirement on + * revokes their sessions and grants at once — while treating a session as signed out here starts + * the app's stale-session recovery, which signs the person out: a database blip would end sessions + * that comply. The next request that can read the requirement sweeps the session. */ export async function enforceTwoFactorRequirement( session: ResolvedSession @@ -2059,22 +2067,19 @@ export async function enforceTwoFactorRequirement( if (user.twoFactorEnabled === true) return session /** Platform-admin impersonation stays available for supporting a member who cannot enroll. */ if (current.impersonatedBy) return session + /** Swallows a failed read as "no organization", the same leave-it-be answer the catch gives. */ const organizationId = await getMemberOrganizationId(session.user.id) try { if (!(await isTwoFactorRequiredForOrganization(organizationId))) return session /** The cookie cache may predate an enrollment; only a fresh read can condemn the session. */ if (!needsTwoFactorSetup(await getTwoFactorState(session.user.id))) return session } catch (error) { - /** - * Fails closed for this request only: a member whose requirement cannot be read is treated as - * signed out, without revoking a session that may well be compliant. - */ logger.error('Could not check the organization two-factor requirement', { userId: session.user.id, organizationId, error, }) - return null + return session } logger.warn('Revoking a session that does not meet its organization two-factor requirement', { @@ -2082,6 +2087,7 @@ export async function enforceTwoFactorRequirement( organizationId, }) await db.delete(schema.session).where(eq(schema.session.id, session.session.id)) + await revokeUserOAuthGrants(session.user.id) return null } diff --git a/apps/sim/lib/auth/two-factor/guard.integration.ts b/apps/sim/lib/auth/two-factor/guard.integration.ts index f04e563743b..f45e067c9b7 100644 --- a/apps/sim/lib/auth/two-factor/guard.integration.ts +++ b/apps/sim/lib/auth/two-factor/guard.integration.ts @@ -5,6 +5,8 @@ import { account, auditLog, member, + oauthClient, + oauthTokenFamily, organization, session, twoFactor, @@ -32,7 +34,9 @@ vi.mock('@/lib/posthog/server', () => posthogServerMock) 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 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 let setOrganizationTwoFactorPolicy: typeof import('@/lib/organizations/application/two-factor-policy').setOrganizationTwoFactorPolicy let passwordHash: string @@ -41,9 +45,11 @@ describe('two-factor authentication in PostgreSQL', () => { const password = 'Two-factor-fixture-password-only-41!' beforeAll(async () => { - ;({ auth } = await import('@/lib/auth/auth')) + ;({ auth, enforceTwoFactorRequirement } = await import('@/lib/auth/auth')) ;({ prepareSessionForCreation } = await import('@/lib/auth/session-hooks')) - ;({ invalidateTwoFactorPolicyCache } = await import('@/lib/auth/two-factor/policy')) + ;({ invalidateTwoFactorPolicyCache, isTwoFactorRequiredForOrganization } = await import( + '@/lib/auth/two-factor/policy' + )) ;({ readOrganizationTwoFactorPolicy, setOrganizationTwoFactorPolicy } = await import( '@/lib/organizations/application/two-factor-policy' )) @@ -359,6 +365,23 @@ describe('two-factor authentication in PostgreSQL', () => { expect(row?.enabled).toBe(true) }) + it('challenges enrollment at sign-in even while this instance caches the requirement as off', async () => { + const fixture = await createUser() + const organizationId = await createOrganization([{ userId: fixture.id, role: 'member' }]) + /** Another instance turned it on: this process still caches "not required" for the TTL. */ + expect(await isTwoFactorRequiredForOrganization(organizationId)).toBe(false) + await db + .update(organization) + .set({ requireTwoFactor: true }) + .where(eq(organization.id, organizationId)) + + const { response } = await signInWithPassword(fixture.email) + + expect(await response.json()).toMatchObject({ twoFactorSetupRequired: true }) + expect(await sessionCount(fixture.id)).toBe(0) + invalidateTwoFactorPolicyCache(organizationId) + }) + it('never lets a first factor alone replace an existing enrollment', async () => { const fixture = await createUser() await enroll(fixture.email) @@ -587,6 +610,79 @@ 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 () => { + const fixture = await createUser() + const organizationId = await createOrganization([{ userId: fixture.id, role: 'member' }]) + const { cookie } = await signInWithPassword(fixture.email) + const [current] = await db + .select({ id: session.id }) + .from(session) + .where(eq(session.userId, fixture.id)) + .limit(1) + if (!current) throw new Error('session missing') + const clientId = generateId() + const now = new Date() + await db.insert(oauthClient).values({ + id: clientId, + clientId, + name: 'Two-factor sweep fixture', + public: true, + tokenEndpointAuthMethod: 'none', + grantTypes: ['authorization_code', 'refresh_token'], + redirectUris: ['http://127.0.0.1/callback'], + }) + try { + await db.insert(oauthTokenFamily).values({ + id: generateId(), + clientId, + userId: fixture.id, + sessionId: current.id, + createdAt: now, + expiresAt: new Date(now.getTime() + 86_400_000), + }) + await setRequirement(organizationId, true) + + const swept = await enforceTwoFactorRequirement( + await auth.api.getSession({ headers: new Headers({ cookie }) }) + ) + + expect(swept).toBeNull() + expect(await sessionCount(fixture.id)).toBe(0) + const [grants] = await db + .select({ total: count() }) + .from(oauthTokenFamily) + .where(eq(oauthTokenFamily.userId, fixture.id)) + expect(grants?.total).toBe(0) + } finally { + await db.delete(oauthClient).where(eq(oauthClient.id, clientId)) + } + }) + + it('signs an administrator-reset member out of cached sessions as well', async () => { + const fixture = await createUser() + const operator = await createUser() + const organizationId = await createOrganization([{ userId: fixture.id, role: 'member' }]) + await enroll(fixture.email) + const [before] = await db + .select({ version: organization.securityPolicyVersion }) + .from(organization) + .where(eq(organization.id, organizationId)) + await db.update(user).set({ role: 'admin' }).where(eq(user.id, operator.id)) + const { cookie: adminCookie } = await signInWithPassword(operator.email) + + const reset = await auth.handler( + request('/admin/reset-two-factor', { userId: fixture.id }, adminCookie) + ) + + expect(reset.status).toBe(200) + expect(await sessionCount(fixture.id)).toBe(0) + const [after] = await db + .select({ version: organization.securityPolicyVersion }) + .from(organization) + .where(eq(organization.id, organizationId)) + expect(after?.version).toBe((before?.version ?? 0) + 1) + }) + it('lets only a platform administrator reset someone else’s two-factor', 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 02f3aaa3a94..452765b2af0 100644 --- a/apps/sim/lib/auth/two-factor/guard.ts +++ b/apps/sim/lib/auth/two-factor/guard.ts @@ -1,6 +1,6 @@ import { createHMAC } from '@better-auth/utils/hmac' import { db } from '@sim/db' -import { twoFactor, verification } from '@sim/db/schema' +import { member, twoFactor, verification } from '@sim/db/schema' import { createLogger } from '@sim/logger' import type { BetterAuthPlugin } from 'better-auth' import { @@ -34,6 +34,10 @@ import { import { notifyTwoFactorChange } from '@/lib/auth/two-factor/notify' import { getTwoFactorState, needsTwoFactorSetup } from '@/lib/auth/two-factor/policy' import type { DbOrTx } from '@/lib/db/types' +import { + invalidateAfterSessionRevocation, + revokeUserSessionsTx, +} from '@/lib/organizations/members/revocation' const logger = createLogger('TwoFactorGuard') @@ -332,6 +336,29 @@ async function assertStepUpCode( }) } +/** + * Ends every session a user holds, including what their browser still has cached. A member's + * sessions go through the same revocation as removal and suspension, which also moves their + * organization's cookie-cache version so a cached cookie re-reads the database on its next request + * instead of authenticating for up to five more minutes. Someone in no organization has no version + * to move; their sessions are deleted and only the cookie cache's own lifetime bounds the rest. + */ +async function signOutEverywhere(ctx: AuthMiddlewareContext, userId: string): Promise { + const [membership] = await db + .select({ organizationId: member.organizationId }) + .from(member) + .where(eq(member.userId, userId)) + .limit(1) + if (!membership) { + await ctx.context.internalAdapter.deleteUserSessions(userId) + return + } + await db.transaction((tx) => + revokeUserSessionsTx(tx, { userId, organizationId: membership.organizationId }) + ) + invalidateAfterSessionRevocation({ userId, organizationId: membership.organizationId }) +} + const STEP_UP_PATHS = new Set([ '/two-factor/enable', '/two-factor/disable', @@ -428,7 +455,7 @@ export function twoFactorGuardPlugin() { where: [{ field: 'userId', value: target.id }], }) await ctx.context.internalAdapter.updateUser(target.id, { twoFactorEnabled: false }) - await ctx.context.internalAdapter.deleteUserSessions(target.id) + await signOutEverywhere(ctx, target.id) await revokeUserOAuthGrants(target.id) await forgetTrustedDevices(target.id) logger.warn('Platform administrator reset two-factor authentication', { diff --git a/apps/sim/lib/auth/two-factor/policy.ts b/apps/sim/lib/auth/two-factor/policy.ts index 33bdebbca54..dfb76a53009 100644 --- a/apps/sim/lib/auth/two-factor/policy.ts +++ b/apps/sim/lib/auth/two-factor/policy.ts @@ -18,33 +18,49 @@ const requirementCache = new LRUCache({ }) /** - * Whether an organization requires its members to use two-factor authentication. On Sim Cloud the - * stored setting enforces only while the organization is on Enterprise, the plan that shows the - * setting: an organization that downgrades stops enforcing rather than being held to a setting - * its administrators can no longer see or turn off. Self-hosted deployments always enforce it. + * Whether an organization requires its members to use two-factor authentication, read from the + * database. On Sim Cloud the stored setting enforces only while the organization is on Enterprise, + * the plan that shows the setting: an organization that downgrades stops enforcing rather than + * being held to a setting its administrators can no longer see or turn off. Self-hosted + * deployments always enforce it. * * A failed entitlement read throws rather than answering "not required": a permissive answer - * would let a sign-in skip enrollment, and would be cached for the whole TTL. + * would let a sign-in skip enrollment. */ -export async function isTwoFactorRequiredForOrganization( +async function readTwoFactorRequirement( organizationId: string | null | undefined, - executor: DbOrTx = db + executor: DbOrTx ): Promise { if (!organizationId) return false - /** Uncommitted reads must neither consume nor populate the shared cache. */ - const cached = isPrimaryPoolClient(executor) ? requirementCache.get(organizationId) : undefined - if (cached !== undefined) return cached - const [row] = await executor .select({ requireTwoFactor: organization.requireTwoFactor }) .from(organization) .where(eq(organization.id, organizationId)) .limit(1) - const required = + return ( row?.requireTwoFactor === true && (await isOrganizationFeatureEntitled(organizationId, true, executor, { onError: 'throw' })) + ) +} + +/** + * {@link readTwoFactorRequirement} through a per-process cache, for the check that runs on every + * session read. A requirement turned on reaches it within the TTL on other instances; sign-in and + * second-factor changes read fresh through {@link getTwoFactorState} instead. + */ +export async function isTwoFactorRequiredForOrganization( + organizationId: string | null | undefined, + executor: DbOrTx = db +): Promise { + if (!organizationId) return false + + /** Uncommitted reads must neither consume nor populate the shared cache. */ + const cached = isPrimaryPoolClient(executor) ? requirementCache.get(organizationId) : undefined + if (cached !== undefined) return cached + + const required = await readTwoFactorRequirement(organizationId, executor) if (isPrimaryPoolClient(executor)) requirementCache.set(organizationId, required) return required } @@ -65,9 +81,11 @@ export interface TwoFactorState { } /** - * Reads a user's two-factor state fresh from the database. Used where a session is being created - * or a sign-in challenged, where a stale cached answer would be a bypass. Users belong to at most - * one organization, the same assumption every other membership policy makes. + * Reads a user's two-factor state fresh from the database, the organization's requirement + * included. Used where a session is being created, a sign-in challenged or a second factor + * changed, where a cached answer from before an administrator turned the requirement on would let + * a member through without enrolling. Users belong to at most one organization, the same + * assumption every other membership policy makes. */ export async function getTwoFactorState( userId: string, @@ -82,7 +100,7 @@ export async function getTwoFactorState( return { enabled: row?.enabled === true, - required: await isTwoFactorRequiredForOrganization(row?.organizationId, executor), + required: await readTwoFactorRequirement(row?.organizationId, executor), } } From 60bc91b57f82fad1f3f28b91c372e9034462051b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 16:37:46 -0600 Subject: [PATCH 2/4] improvement(auth): share the sign-out-everywhere revocation, read two-factor state in one query --- apps/sim/lib/auth/auth.ts | 6 +-- apps/sim/lib/auth/two-factor/guard.ts | 32 ++--------- apps/sim/lib/auth/two-factor/policy.ts | 53 +++++++++++-------- .../lib/organizations/members/revocation.ts | 35 +++++++++++- 4 files changed, 71 insertions(+), 55 deletions(-) diff --git a/apps/sim/lib/auth/auth.ts b/apps/sim/lib/auth/auth.ts index b38a1c36dcf..49496510ad0 100644 --- a/apps/sim/lib/auth/auth.ts +++ b/apps/sim/lib/auth/auth.ts @@ -2045,9 +2045,9 @@ type ResolvedSession = Awaited> * 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, since an MCP client - * authorized from that session would otherwise 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 + * 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 * goes through this — `getSession` and the desktop pages that read the session directly to bypass * the cookie cache. * diff --git a/apps/sim/lib/auth/two-factor/guard.ts b/apps/sim/lib/auth/two-factor/guard.ts index 452765b2af0..a6a7fd0ab2f 100644 --- a/apps/sim/lib/auth/two-factor/guard.ts +++ b/apps/sim/lib/auth/two-factor/guard.ts @@ -1,6 +1,6 @@ import { createHMAC } from '@better-auth/utils/hmac' import { db } from '@sim/db' -import { member, twoFactor, verification } from '@sim/db/schema' +import { twoFactor, verification } from '@sim/db/schema' import { createLogger } from '@sim/logger' import type { BetterAuthPlugin } from 'better-auth' import { @@ -34,10 +34,7 @@ import { import { notifyTwoFactorChange } from '@/lib/auth/two-factor/notify' import { getTwoFactorState, needsTwoFactorSetup } from '@/lib/auth/two-factor/policy' import type { DbOrTx } from '@/lib/db/types' -import { - invalidateAfterSessionRevocation, - revokeUserSessionsTx, -} from '@/lib/organizations/members/revocation' +import { revokeAllUserSessions } from '@/lib/organizations/members/revocation' const logger = createLogger('TwoFactorGuard') @@ -336,29 +333,6 @@ async function assertStepUpCode( }) } -/** - * Ends every session a user holds, including what their browser still has cached. A member's - * sessions go through the same revocation as removal and suspension, which also moves their - * organization's cookie-cache version so a cached cookie re-reads the database on its next request - * instead of authenticating for up to five more minutes. Someone in no organization has no version - * to move; their sessions are deleted and only the cookie cache's own lifetime bounds the rest. - */ -async function signOutEverywhere(ctx: AuthMiddlewareContext, userId: string): Promise { - const [membership] = await db - .select({ organizationId: member.organizationId }) - .from(member) - .where(eq(member.userId, userId)) - .limit(1) - if (!membership) { - await ctx.context.internalAdapter.deleteUserSessions(userId) - return - } - await db.transaction((tx) => - revokeUserSessionsTx(tx, { userId, organizationId: membership.organizationId }) - ) - invalidateAfterSessionRevocation({ userId, organizationId: membership.organizationId }) -} - const STEP_UP_PATHS = new Set([ '/two-factor/enable', '/two-factor/disable', @@ -455,7 +429,7 @@ export function twoFactorGuardPlugin() { where: [{ field: 'userId', value: target.id }], }) await ctx.context.internalAdapter.updateUser(target.id, { twoFactorEnabled: false }) - await signOutEverywhere(ctx, target.id) + await revokeAllUserSessions(target.id) await revokeUserOAuthGrants(target.id) await forgetTrustedDevices(target.id) logger.warn('Platform administrator reset two-factor authentication', { diff --git a/apps/sim/lib/auth/two-factor/policy.ts b/apps/sim/lib/auth/two-factor/policy.ts index dfb76a53009..162e786156d 100644 --- a/apps/sim/lib/auth/two-factor/policy.ts +++ b/apps/sim/lib/auth/two-factor/policy.ts @@ -18,37 +18,30 @@ const requirementCache = new LRUCache({ }) /** - * Whether an organization requires its members to use two-factor authentication, read from the - * database. On Sim Cloud the stored setting enforces only while the organization is on Enterprise, - * the plan that shows the setting: an organization that downgrades stops enforcing rather than - * being held to a setting its administrators can no longer see or turn off. Self-hosted - * deployments always enforce it. + * Whether a stored requirement enforces. On Sim Cloud it does only while the organization is on + * Enterprise, the plan that shows the setting: an organization that downgrades stops enforcing + * rather than being held to a setting its administrators can no longer see or turn off. + * Self-hosted deployments always enforce it. The plan is read only when the setting is on. * * A failed entitlement read throws rather than answering "not required": a permissive answer * would let a sign-in skip enrollment. */ -async function readTwoFactorRequirement( - organizationId: string | null | undefined, +async function enforcesRequirement( + organizationId: string, + requireTwoFactor: boolean, executor: DbOrTx ): Promise { - if (!organizationId) return false - - const [row] = await executor - .select({ requireTwoFactor: organization.requireTwoFactor }) - .from(organization) - .where(eq(organization.id, organizationId)) - .limit(1) - return ( - row?.requireTwoFactor === true && + requireTwoFactor && (await isOrganizationFeatureEntitled(organizationId, true, executor, { onError: 'throw' })) ) } /** - * {@link readTwoFactorRequirement} through a per-process cache, for the check that runs on every - * session read. A requirement turned on reaches it within the TTL on other instances; sign-in and - * second-factor changes read fresh through {@link getTwoFactorState} instead. + * Whether an organization requires its members to use two-factor authentication, through a + * per-process cache, for the check that runs on every session read. A requirement turned on + * reaches it within the TTL on other instances; sign-in and second-factor changes read fresh + * through {@link getTwoFactorState} instead. */ export async function isTwoFactorRequiredForOrganization( organizationId: string | null | undefined, @@ -60,7 +53,16 @@ export async function isTwoFactorRequiredForOrganization( const cached = isPrimaryPoolClient(executor) ? requirementCache.get(organizationId) : undefined if (cached !== undefined) return cached - const required = await readTwoFactorRequirement(organizationId, executor) + const [row] = await executor + .select({ requireTwoFactor: organization.requireTwoFactor }) + .from(organization) + .where(eq(organization.id, organizationId)) + .limit(1) + const required = await enforcesRequirement( + organizationId, + row?.requireTwoFactor === true, + executor + ) if (isPrimaryPoolClient(executor)) requirementCache.set(organizationId, required) return required } @@ -92,15 +94,22 @@ export async function getTwoFactorState( executor: DbOrTx = db ): Promise { const [row] = await executor - .select({ enabled: user.twoFactorEnabled, organizationId: member.organizationId }) + .select({ + enabled: user.twoFactorEnabled, + organizationId: member.organizationId, + requireTwoFactor: organization.requireTwoFactor, + }) .from(user) .leftJoin(member, eq(member.userId, user.id)) + .leftJoin(organization, eq(organization.id, member.organizationId)) .where(eq(user.id, userId)) .limit(1) return { enabled: row?.enabled === true, - required: await readTwoFactorRequirement(row?.organizationId, executor), + required: row?.organizationId + ? await enforcesRequirement(row.organizationId, row.requireTwoFactor === true, executor) + : false, } } diff --git a/apps/sim/lib/organizations/members/revocation.ts b/apps/sim/lib/organizations/members/revocation.ts index 89b8f14b048..65bea701233 100644 --- a/apps/sim/lib/organizations/members/revocation.ts +++ b/apps/sim/lib/organizations/members/revocation.ts @@ -1,4 +1,5 @@ -import { apiKey, organization, session as sessionTable } from '@sim/db/schema' +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 { invalidateMembershipCache, @@ -59,6 +60,38 @@ export async function revokeUserSessionsTx( return { revoked: deleted.length } } +/** + * Ends every session a user holds, whether or not they belong to an organization. A member goes + * through {@link revokeUserSessionsTx}, so their cached session cookies re-read the database on + * 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. + */ +export async function revokeAllUserSessions(userId: string): 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 } + }) + if (organizationId) invalidateAfterSessionRevocation({ userId, organizationId }) + return { revoked } +} + /** * Drops the caches that make a revocation visible to the next request. * From dbb3ff51fd4818241a21e3d351490c0462ca0923 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 16:40:02 -0600 Subject: [PATCH 3/4] improvement(auth): assert two-factor review fixes on behavior, trim restating comment --- .../lib/auth/two-factor/guard.integration.ts | 17 +++++------------ apps/sim/lib/auth/two-factor/policy.ts | 2 +- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/apps/sim/lib/auth/two-factor/guard.integration.ts b/apps/sim/lib/auth/two-factor/guard.integration.ts index f45e067c9b7..4bdb278c3ac 100644 --- a/apps/sim/lib/auth/two-factor/guard.integration.ts +++ b/apps/sim/lib/auth/two-factor/guard.integration.ts @@ -374,12 +374,12 @@ describe('two-factor authentication in PostgreSQL', () => { .update(organization) .set({ requireTwoFactor: true }) .where(eq(organization.id, organizationId)) + expect(await isTwoFactorRequiredForOrganization(organizationId)).toBe(false) const { response } = await signInWithPassword(fixture.email) expect(await response.json()).toMatchObject({ twoFactorSetupRequired: true }) expect(await sessionCount(fixture.id)).toBe(0) - invalidateTwoFactorPolicyCache(organizationId) }) it('never lets a first factor alone replace an existing enrollment', async () => { @@ -661,12 +661,9 @@ describe('two-factor authentication in PostgreSQL', () => { it('signs an administrator-reset member out of cached sessions as well', async () => { const fixture = await createUser() const operator = await createUser() - const organizationId = await createOrganization([{ userId: fixture.id, role: 'member' }]) - await enroll(fixture.email) - const [before] = await db - .select({ version: organization.securityPolicyVersion }) - .from(organization) - .where(eq(organization.id, organizationId)) + await createOrganization([{ userId: fixture.id, role: 'member' }]) + const { cookie } = await enroll(fixture.email) + expect(await auth.api.getSession({ headers: new Headers({ cookie }) })).not.toBeNull() await db.update(user).set({ role: 'admin' }).where(eq(user.id, operator.id)) const { cookie: adminCookie } = await signInWithPassword(operator.email) @@ -676,11 +673,7 @@ describe('two-factor authentication in PostgreSQL', () => { expect(reset.status).toBe(200) expect(await sessionCount(fixture.id)).toBe(0) - const [after] = await db - .select({ version: organization.securityPolicyVersion }) - .from(organization) - .where(eq(organization.id, organizationId)) - expect(after?.version).toBe((before?.version ?? 0) + 1) + expect(await auth.api.getSession({ headers: new Headers({ cookie }) })).toBeNull() }) it('lets only a platform administrator reset someone else’s two-factor', async () => { diff --git a/apps/sim/lib/auth/two-factor/policy.ts b/apps/sim/lib/auth/two-factor/policy.ts index 162e786156d..7dfe5fdb5b2 100644 --- a/apps/sim/lib/auth/two-factor/policy.ts +++ b/apps/sim/lib/auth/two-factor/policy.ts @@ -21,7 +21,7 @@ const requirementCache = new LRUCache({ * Whether a stored requirement enforces. On Sim Cloud it does only while the organization is on * Enterprise, the plan that shows the setting: an organization that downgrades stops enforcing * rather than being held to a setting its administrators can no longer see or turn off. - * Self-hosted deployments always enforce it. The plan is read only when the setting is on. + * Self-hosted deployments always enforce it. * * A failed entitlement read throws rather than answering "not required": a permissive answer * would let a sign-in skip enrollment. From 741095b6ef93c6ebf77cf9258d11a9e647c1917b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 16:53:04 -0600 Subject: [PATCH 4/4] fix(auth): end a swept session and its OAuth grants in one transaction --- apps/sim/lib/auth/auth.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/sim/lib/auth/auth.ts b/apps/sim/lib/auth/auth.ts index 49496510ad0..23468c5e059 100644 --- a/apps/sim/lib/auth/auth.ts +++ b/apps/sim/lib/auth/auth.ts @@ -2086,8 +2086,11 @@ export async function enforceTwoFactorRequirement( userId: session.user.id, organizationId, }) - await db.delete(schema.session).where(eq(schema.session.id, session.session.id)) - await revokeUserOAuthGrants(session.user.id) + /** 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) + }) return null }