Skip to content

Commit b5bfa74

Browse files
authored
feat(auth): email users when their two-factor changes; fix consent scope list inset (#10739)
1 parent 68b6a2a commit b5bfa74

13 files changed

Lines changed: 224 additions & 21 deletions

File tree

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,13 @@ Organization owners and admins open **Settings → Organization → Security** a
5050

5151
API keys are not affected. They keep working whether or not their owner has 2FA.
5252

53+
## Email notifications
54+
55+
Sim emails you whenever two-factor authentication on your account is turned on, turned off, reset by an administrator, or switched to a new authenticator app. If you didn't make the change, reset your password from the sign-in page and contact your administrator.
56+
5357
## Audit log
5458

55-
Turning 2FA on or off, regenerating backup codes, an administrator reset, a lockout after repeated incorrect codes, and each sign-in completed or rejected at the code step appear in the [audit log](/platform/enterprise/audit-logs). A sign-in is recorded as successful only after the code is accepted.
59+
Turning 2FA on or off, changing your authenticator app, regenerating backup codes, an administrator reset, a lockout after repeated incorrect codes, and each sign-in completed or rejected at the code step appear in the [audit log](/platform/enterprise/audit-logs). A sign-in is recorded as successful only after the code is accepted.
5660

5761
<Callout type="info">
5862
If your organization signs in through [single sign-on](/platform/enterprise/sso), your identity provider can already enforce MFA. Requiring 2FA in Sim as well asks members for a Sim code after the identity provider's sign-in.

‎apps/sim/app/(auth)/oauth/consent/consent-view.tsx‎

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -141,21 +141,24 @@ export function OAuthConsentView({
141141
onSwitch={changeAccount}
142142
/>
143143
<div className='au:space-y-[var(--auth-group-gap)]'>
144+
{/* The inset is on a div: the Auth root resets list padding outside the utilities layer. */}
144145
{scopes.length > 0 && (
145-
<ul className='au:space-y-2 au:px-2'>
146-
{scopes.map((item) => (
147-
<li
148-
key={item}
149-
className='au:flex au:items-start au:gap-2 au:text-[var(--auth-primary)] au:text-body'
150-
>
151-
<AuthIcon
152-
name='check'
153-
className='au:mt-[3px] au:size-4 au:shrink-0 au:text-[var(--auth-secondary)]'
154-
/>
155-
<span>{OAUTH_SCOPE_DESCRIPTIONS[item]}</span>
156-
</li>
157-
))}
158-
</ul>
146+
<div className='au:px-2'>
147+
<ul className='au:space-y-2'>
148+
{scopes.map((item) => (
149+
<li
150+
key={item}
151+
className='au:flex au:items-start au:gap-2 au:text-[var(--auth-primary)] au:text-body'
152+
>
153+
<AuthIcon
154+
name='check'
155+
className='au:mt-[3px] au:size-4 au:shrink-0 au:text-[var(--auth-secondary)]'
156+
/>
157+
<span>{OAUTH_SCOPE_DESCRIPTIONS[item]}</span>
158+
</li>
159+
))}
160+
</ul>
161+
</div>
159162
)}
160163
{!isCli && destination && (
161164
<p className='au:break-words au:text-[var(--auth-secondary)] au:text-caption'>

‎apps/sim/components/emails/auth/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@ export { ExistingAccountEmail } from './existing-account-email'
22
export { OnboardingFollowupEmail } from './onboarding-followup-email'
33
export { OTPVerificationEmail } from './otp-verification-email'
44
export { ResetPasswordEmail } from './reset-password-email'
5+
export { type TwoFactorChange, TwoFactorChangedEmail } from './two-factor-changed-email'
56
export { WelcomeEmail } from './welcome-email'
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { Text } from '@react-email/components'
2+
import { baseStyles } from '@/components/emails/_styles'
3+
import { EmailButton, EmailLayout } from '@/components/emails/components'
4+
import { getBaseUrl } from '@/lib/core/utils/urls'
5+
6+
/** What happened to the account's second factor. */
7+
export type TwoFactorChange = 'enabled' | 'changed' | 'disabled' | 'reset'
8+
9+
interface TwoFactorChangedEmailProps {
10+
username?: string
11+
change: TwoFactorChange
12+
}
13+
14+
const COPY: Record<TwoFactorChange, { preview: string; body: string }> = {
15+
enabled: {
16+
preview: 'Two-factor authentication is on for your Sim account',
17+
body: 'Two-factor authentication was turned on for your Sim account. Signing in now asks for a code from your authenticator app.',
18+
},
19+
changed: {
20+
preview: 'Your Sim authenticator app was changed',
21+
body: 'The authenticator app for your Sim account was changed. Codes from your previous app and your previous backup codes no longer work.',
22+
},
23+
disabled: {
24+
preview: 'Two-factor authentication is off for your Sim account',
25+
body: 'Two-factor authentication was turned off for your Sim account. Signing in no longer asks for a code.',
26+
},
27+
reset: {
28+
preview: 'An administrator reset two-factor authentication on your Sim account',
29+
body: 'An administrator reset two-factor authentication on your Sim account and signed you out everywhere. If your organization requires two-factor authentication, you’ll set it up again the next time you sign in.',
30+
},
31+
}
32+
33+
/**
34+
* Tells the account owner that their second factor changed. Sent for every change, so someone
35+
* whose session was taken over learns that their two-factor authentication was removed or
36+
* replaced, even if they never look at the audit log.
37+
*/
38+
export function TwoFactorChangedEmail({ username = '', change }: TwoFactorChangedEmailProps) {
39+
const { preview, body } = COPY[change]
40+
41+
return (
42+
<EmailLayout preview={preview} showUnsubscribe={false}>
43+
<Text style={baseStyles.greeting}>Hello {username},</Text>
44+
<Text style={baseStyles.paragraph}>{body}</Text>
45+
46+
<EmailButton href={`${getBaseUrl()}/login`}>Sign In</EmailButton>
47+
48+
<div style={baseStyles.divider} />
49+
50+
<Text style={baseStyles.footnote}>
51+
If you didn’t make this change, reset your password from the sign-in page right away and
52+
contact your administrator or Sim support.
53+
</Text>
54+
</EmailLayout>
55+
)
56+
}
57+
58+
export default TwoFactorChangedEmail

‎apps/sim/components/emails/render.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import {
55
OnboardingFollowupEmail,
66
OTPVerificationEmail,
77
ResetPasswordEmail,
8+
type TwoFactorChange,
9+
TwoFactorChangedEmail,
810
WelcomeEmail,
911
} from '@/components/emails/auth'
1012
import {
@@ -64,6 +66,13 @@ export async function renderExistingAccountEmail(username: string): Promise<stri
6466
return await render(ExistingAccountEmail({ username }))
6567
}
6668

69+
export async function renderTwoFactorChangedEmail(
70+
username: string,
71+
change: TwoFactorChange
72+
): Promise<string> {
73+
return await render(TwoFactorChangedEmail({ username, change }))
74+
}
75+
6776
export async function renderPasswordResetEmail(
6877
username: string,
6978
resetLink: string

‎apps/sim/components/emails/subjects.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ export type EmailSubjectType =
88
| 'forget-password'
99
| 'reset-password'
1010
| 'existing-account'
11+
| 'two-factor-enabled'
12+
| 'two-factor-changed'
13+
| 'two-factor-disabled'
14+
| 'two-factor-reset'
1115
| 'invitation'
1216
| 'enterprise-owner-invitation'
1317
| 'batch-invitation'
@@ -49,6 +53,14 @@ export function getEmailSubject(type: EmailSubjectType): string {
4953
return `Reset your Sim password`
5054
case 'existing-account':
5155
return `Sign-up attempt with your Sim email`
56+
case 'two-factor-enabled':
57+
return `Two-factor authentication turned on for your Sim account`
58+
case 'two-factor-changed':
59+
return `Your Sim authenticator app was changed`
60+
case 'two-factor-disabled':
61+
return `Two-factor authentication turned off for your Sim account`
62+
case 'two-factor-reset':
63+
return `Two-factor authentication reset on your Sim account`
5264
case 'invitation':
5365
return `You've been invited to join a team on Sim`
5466
case 'enterprise-owner-invitation':

‎apps/sim/lib/auth/two-factor/audit.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const logger = createLogger('TwoFactorAudit')
88

99
type TwoFactorAuditEvent =
1010
| 'enabled'
11+
| 'changed'
1112
| 'disabled'
1213
| 'backup_codes_regenerated'
1314
| 'reset'
@@ -20,6 +21,10 @@ const EVENTS: Record<TwoFactorAuditEvent, { action: AuditActionType; description
2021
action: AuditAction.AUTH_TWO_FACTOR_ENABLED,
2122
description: 'Turned on two-factor authentication',
2223
},
24+
changed: {
25+
action: AuditAction.AUTH_TWO_FACTOR_CHANGED,
26+
description: 'Changed two-factor authenticator app',
27+
},
2328
disabled: {
2429
action: AuditAction.AUTH_TWO_FACTOR_DISABLED,
2530
description: 'Turned off two-factor authentication',

‎apps/sim/lib/auth/two-factor/guard.integration.ts‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
verification,
1313
} from '@sim/db/schema'
1414
import { emailMailerMock, emailMailerMockFns } from '@sim/testing/mocks/email-mailer.mock'
15-
import { emailTemplatesMock } from '@sim/testing/mocks/email-templates.mock'
15+
import { emailTemplatesMock, emailTemplatesMockFns } from '@sim/testing/mocks/email-templates.mock'
1616
import { posthogServerMock } from '@sim/testing/mocks/posthog-server.mock'
1717
import { generateId } from '@sim/utils/id'
1818
import { createEmailVerificationToken } from 'better-auth/api'
@@ -323,6 +323,7 @@ describe('two-factor authentication in PostgreSQL', () => {
323323
const organizationId = await createOrganization([{ userId: fixture.id, role: 'member' }])
324324
await setRequirement(organizationId, true)
325325

326+
emailTemplatesMockFns.mockRenderTwoFactorChangedEmail.mockClear()
326327
const { response, cookie } = await signInWithPassword(fixture.email)
327328
expect(await response.json()).toMatchObject({
328329
twoFactorRedirect: true,
@@ -348,6 +349,9 @@ describe('two-factor authentication in PostgreSQL', () => {
348349
)
349350
expect(verified.status).toBe(200)
350351
expect(await sessionCount(fixture.id)).toBe(1)
352+
expect(
353+
emailTemplatesMockFns.mockRenderTwoFactorChangedEmail.mock.calls.map((call) => call[1])
354+
).toEqual(['enabled'])
351355
const [row] = await db
352356
.select({ enabled: user.twoFactorEnabled })
353357
.from(user)
@@ -549,6 +553,40 @@ describe('two-factor authentication in PostgreSQL', () => {
549553
expect((await readAs(owner.id, owner.email)).membersWithoutTwoFactor).toBe(2)
550554
})
551555

556+
it('emails the owner when their second factor is turned on, changed, turned off or reset', async () => {
557+
const fixture = await createUser()
558+
const operator = await createUser()
559+
const renderChange = emailTemplatesMockFns.mockRenderTwoFactorChangedEmail
560+
renderChange.mockClear()
561+
emailMailerMockFns.mockSendEmail.mockClear()
562+
563+
const { totpURI, cookie } = await enroll(fixture.email)
564+
const replaced = await auth.handler(
565+
request('/two-factor/enable', { password, code: await currentCode(totpURI) }, cookie)
566+
)
567+
const next = (await replaced.json()) as { totpURI: string }
568+
await auth.handler(
569+
request('/two-factor/verify-totp', { code: await currentCode(next.totpURI) }, cookie)
570+
)
571+
await auth.handler(
572+
request('/two-factor/disable', { password, code: await currentCode(next.totpURI) }, cookie)
573+
)
574+
await db.update(user).set({ role: 'admin' }).where(eq(user.id, operator.id))
575+
const { cookie: adminCookie } = await signInWithPassword(operator.email)
576+
await auth.handler(request('/admin/reset-two-factor', { userId: fixture.id }, adminCookie))
577+
578+
expect(renderChange.mock.calls.map((call) => call[1])).toEqual([
579+
'enabled',
580+
'changed',
581+
'disabled',
582+
'reset',
583+
])
584+
const recipients = emailMailerMockFns.mockSendEmail.mock.calls.map(
585+
(call) => (call[0] as { to: string }).to
586+
)
587+
expect(recipients).toEqual([fixture.email, fixture.email, fixture.email, fixture.email])
588+
})
589+
552590
it('lets only a platform administrator reset someone else’s two-factor', async () => {
553591
const fixture = await createUser()
554592
const operator = await createUser()

‎apps/sim/lib/auth/two-factor/guard.ts‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
mintEnrollment,
3232
type StoredTwoFactor,
3333
} from '@/lib/auth/two-factor/codes'
34+
import { notifyTwoFactorChange } from '@/lib/auth/two-factor/notify'
3435
import { getTwoFactorState, needsTwoFactorSetup } from '@/lib/auth/two-factor/policy'
3536
import type { DbOrTx } from '@/lib/db/types'
3637

@@ -440,6 +441,7 @@ export function twoFactorGuardPlugin() {
440441
actorUserId: actor.id,
441442
request: requestOf(ctx),
442443
})
444+
await notifyTwoFactorChange(target.id, 'reset')
443445
return ctx.json({ success: true })
444446
}
445447
),
@@ -556,6 +558,7 @@ export function twoFactorGuardPlugin() {
556558
metadata: { requiredByOrganization: true },
557559
request: requestOf(ctx),
558560
})
561+
await notifyTwoFactorChange(pending.userId, 'enabled')
559562
}),
560563
},
561564
{
@@ -701,17 +704,30 @@ export function twoFactorGuardPlugin() {
701704
.update(twoFactor)
702705
.set({ verified: false })
703706
.where(eq(twoFactor.userId, userId))
707+
/**
708+
* Replacing an enrolled authenticator retires the old one here, whether or not the
709+
* new one is ever confirmed, so this is when the owner hears about it. A first
710+
* enrollment is reported when its code is proven instead.
711+
*/
712+
if ((await getTwoFactorState(userId)).enabled) {
713+
await recordTwoFactorAudit({ event: 'changed', userId, request })
714+
await notifyTwoFactorChange(userId, 'changed')
715+
}
704716
return
705717
}
706718
if (ctx.path === '/two-factor/verify-totp') {
719+
/** Only a first enrollment re-issues the session; confirming a replacement does not. */
720+
if (!ctx.context.newSession) return
707721
await recordTwoFactorAudit({ event: 'enabled', userId, request })
722+
await notifyTwoFactorChange(userId, 'enabled')
708723
return
709724
}
710-
await recordTwoFactorAudit({
711-
event: ctx.path === '/two-factor/disable' ? 'disabled' : 'backup_codes_regenerated',
712-
userId,
713-
request,
714-
})
725+
if (ctx.path === '/two-factor/disable') {
726+
await recordTwoFactorAudit({ event: 'disabled', userId, request })
727+
await notifyTwoFactorChange(userId, 'disabled')
728+
return
729+
}
730+
await recordTwoFactorAudit({ event: 'backup_codes_regenerated', userId, request })
715731
}),
716732
},
717733
],
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { db } from '@sim/db'
2+
import { user } from '@sim/db/schema'
3+
import { createLogger } from '@sim/logger'
4+
import { eq } from 'drizzle-orm'
5+
import {
6+
type EmailSubjectType,
7+
getEmailSubject,
8+
renderTwoFactorChangedEmail,
9+
type TwoFactorChange,
10+
} from '@/components/emails'
11+
import { sendEmail } from '@/lib/messaging/email/mailer'
12+
import { getFromEmailAddress } from '@/lib/messaging/email/utils'
13+
14+
const logger = createLogger('TwoFactorNotify')
15+
16+
const SUBJECTS: Record<TwoFactorChange, EmailSubjectType> = {
17+
enabled: 'two-factor-enabled',
18+
changed: 'two-factor-changed',
19+
disabled: 'two-factor-disabled',
20+
reset: 'two-factor-reset',
21+
}
22+
23+
/**
24+
* Emails the account owner that their second factor changed, so a change they did not make —
25+
* someone with their session removing or replacing it, or an administrator reset — reaches them
26+
* directly. Never throws: the change has already happened, and a failed email must not report it
27+
* as failed.
28+
*/
29+
export async function notifyTwoFactorChange(userId: string, change: TwoFactorChange) {
30+
try {
31+
const [owner] = await db
32+
.select({ name: user.name, email: user.email })
33+
.from(user)
34+
.where(eq(user.id, userId))
35+
.limit(1)
36+
if (!owner?.email) return
37+
38+
const result = await sendEmail({
39+
to: owner.email,
40+
subject: getEmailSubject(SUBJECTS[change]),
41+
html: await renderTwoFactorChangedEmail(owner.name ?? '', change),
42+
from: getFromEmailAddress(),
43+
emailType: 'transactional',
44+
})
45+
if (!result.success) {
46+
logger.warn('Two-factor change email was not sent', { userId, change })
47+
}
48+
} catch (error) {
49+
logger.error('Failed to send two-factor change email', { userId, change, error })
50+
}
51+
}

0 commit comments

Comments
 (0)