Repository navigation
fix(auth): harden MFA and session lifecycle #284
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
8655f21
aafdb1e
557dbe0
362b940
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -52,10 +52,10 @@ type TwoFactorStart = | |
| | { status: 'verification-required'; email: string } | ||
| | { status: 'two-factor-disabled'; email: string } | ||
| | { | ||
| status: 'code-sent' | 'code-required'; | ||
| status: 'code-sent'; | ||
| challengeId: string; | ||
| methods: TwoFactorMethods; | ||
| preferred: 'totp' | 'email'; | ||
| preferred: 'email'; | ||
| }; | ||
|
|
||
| export const requestEmailTwoFactor = action({ | ||
|
|
@@ -96,17 +96,6 @@ export const requestEmailTwoFactor = action({ | |
| const methods = { totp: factors.totp, email: true, recovery: factors.recoveryRemaining > 0 }; | ||
| const challengeId = randomChallengeId(); | ||
| const challengeIdHash = await sha256(challengeId); | ||
| if (factors.totp) { | ||
| // Authenticator app first: no email unless the person asks for one. | ||
| await ctx.runMutation(internal.authEmailChallenges.create, { | ||
| userId: user._id, | ||
| challengeIdHash, | ||
| codeHash: await sha256(`${challengeId}:${randomChallengeId()}`), | ||
| now: Date.now(), | ||
| emailSent: false, | ||
| }); | ||
| return { status: 'code-required' as const, challengeId, methods, preferred: 'totp' as const }; | ||
| } | ||
| const code = generateOtp(); | ||
| const codeHash = await sha256(`${challengeId}:${code}`); | ||
| const { email } = await ctx.runMutation(internal.authEmailChallenges.create, { | ||
|
|
@@ -116,6 +105,8 @@ export const requestEmailTwoFactor = action({ | |
| now: Date.now(), | ||
| }); | ||
| try { | ||
| // Send an email fallback even when TOTP is enabled, for still-supported clients that only | ||
| // know the original email-code flow. Current clients can still choose the authenticator app. | ||
| await sendTwoFactorEmail(email, code); | ||
| } catch (error) { | ||
| await ctx.runMutation(internal.authEmailChallenges.revoke, { challengeIdHash }); | ||
|
Comment on lines
110
to
112
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When the email provider is unavailable, this awaited fallback send throws and the catch revokes the challenge before a TOTP-enabled user receives its ID. The previous TOTP path created a challenge without sending email, so this change makes authenticator and recovery-code sign-in unavailable during any email outage even though neither method needs email; for accounts with those factors, keep the fallback send best-effort or still return a usable challenge when delivery fails. Useful? React with 👍 / 👎. |
||
|
|
@@ -132,13 +123,30 @@ export const sendTwoFactorEmailCode = action({ | |
| if (!/^[0-9a-f]{64}$/.test(challengeId)) throw new ConvexError({ code: 'CHALLENGE_EXPIRED' }); | ||
| const code = generateOtp(); | ||
| const challengeIdHash = await sha256(challengeId); | ||
| const target = await ctx.runMutation(internal.authEmailChallenges.rotateCode, { | ||
| const codeHash = await sha256(`${challengeId}:${code}`); | ||
| const reservedAt = Date.now(); | ||
| const reservation = await ctx.runMutation(internal.authEmailChallenges.reserveCodeResend, { | ||
| challengeIdHash, | ||
| codeHash: await sha256(`${challengeId}:${code}`), | ||
| now: reservedAt, | ||
| }); | ||
| if (!reservation) throw new ConvexError({ code: 'CHALLENGE_EXPIRED' }); | ||
| try { | ||
| await sendTwoFactorEmail(reservation.email, code); | ||
| } catch (error) { | ||
| await ctx.runMutation(internal.authEmailChallenges.releaseCodeResend, { | ||
| challengeIdHash, | ||
| reservedAt: reservation.reservedAt, | ||
| previousEmailSentAt: reservation.previousEmailSentAt, | ||
| }); | ||
| throw error; | ||
| } | ||
| const finished = await ctx.runMutation(internal.authEmailChallenges.finishCodeResend, { | ||
| challengeIdHash, | ||
| codeHash, | ||
| reservedAt: reservation.reservedAt, | ||
| now: Date.now(), | ||
| }); | ||
| if (!target) throw new ConvexError({ code: 'CHALLENGE_EXPIRED' }); | ||
| await sendTwoFactorEmail(target.email, code); | ||
| if (!finished) throw new ConvexError({ code: 'CHALLENGE_EXPIRED' }); | ||
| return null; | ||
| }, | ||
| }); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -168,7 +168,7 @@ export const touchSession = mutation({ | |
| .withIndex('by_session', (q) => q.eq('sessionId', sessionId)) | ||
| .unique(); | ||
| if (existing) { | ||
| if (now - existing.lastSeenAt > TOUCH_EVERY_MS || existing.label !== clean) | ||
| if (now - existing.lastSeenAt >= TOUCH_EVERY_MS || existing.label !== clean) | ||
| await ctx.db.patch(existing._id, { lastSeenAt: now, label: clean, platform }); | ||
| return null; | ||
| } | ||
|
|
@@ -180,15 +180,14 @@ export const touchSession = mutation({ | |
| createdAt: now, | ||
| lastSeenAt: now, | ||
| }); | ||
| // Alert on a new device when another device was already signed in. | ||
| const others = await ctx.db | ||
| .query('authSessions') | ||
| .withIndex('userId', (q) => q.eq('userId', user._id)) | ||
| .collect(); | ||
| const otherActive = others.some( | ||
| (session) => session._id !== sessionId && session.expirationTime > now, | ||
| ); | ||
| if (otherActive && (await privacyFor(ctx, user._id)).signInAlerts) | ||
| // A prior device record distinguishes a returning account from its first-ever sign-in, | ||
| // even when its session is no longer live. | ||
| const priorDevice = await ctx.db | ||
| .query('sessionDevices') | ||
| .withIndex('by_user', (q) => q.eq('userId', user._id)) | ||
| .filter((q) => q.neq(q.field('sessionId'), sessionId)) | ||
| .first(); | ||
| if (priorDevice && (await privacyFor(ctx, user._id)).signInAlerts) | ||
|
Comment on lines
+186
to
+190
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When another valid session has not yet created a Useful? React with 👍 / 👎. |
||
| await createNotification( | ||
| ctx, | ||
| user._id, | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If the app is backgrounded and restored while
userIdis null, this condition skips the only statement that clearsbackgroundAt. After the user signs in, a laterinactive → activetransition—such as opening and dismissing a system overlay—uses that stale pre-sign-in timestamp and can immediately relock the returning user's app or invalidate an in-flight device unlock. Clear the timestamp whenever the app becomes active, while applying the timeout only when a user is present.Useful? React with 👍 / 👎.