From 8655f216c329b5f9104403230401d599fe014e49 Mon Sep 17 00:00:00 2001 From: NeerajCodz Date: Fri, 27 Nov 2026 05:52:38 +0530 Subject: [PATCH 1/4] fix(security): restore the MFA QR quiet zone Fixes #275 --- apps/mobile/components/security/MfaSettings.tsx | 2 +- apps/web/components/security/MfaSettings.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/mobile/components/security/MfaSettings.tsx b/apps/mobile/components/security/MfaSettings.tsx index 529e4ed5..57ec8252 100644 --- a/apps/mobile/components/security/MfaSettings.tsx +++ b/apps/mobile/components/security/MfaSettings.tsx @@ -23,7 +23,7 @@ const errorText = (cause: unknown) => { }; function Qr({ qr }: { qr: Setup['qr'] }) { - const pad = 2; + const pad = 4; const box = qr.size + pad * 2; // theme-exempt: QR codes must be black on white to scan. return ( diff --git a/apps/web/components/security/MfaSettings.tsx b/apps/web/components/security/MfaSettings.tsx index d2a50c34..08df80ca 100644 --- a/apps/web/components/security/MfaSettings.tsx +++ b/apps/web/components/security/MfaSettings.tsx @@ -23,7 +23,7 @@ const errorText = (cause: unknown) => { }; function Qr({ qr }: { qr: Setup['qr'] }) { - const pad = 2; + const pad = 4; return ( Date: Fri, 27 Nov 2026 07:22:49 +0530 Subject: [PATCH 2/4] fix(auth): harden MFA and session lifecycle - Correct MFA challenge, enrollment, recovery, and session-security handling. - Fixes #264, #265, #266, #273, #274, #276, #277, and #278. --- apps/mobile/lib/security/AppLockProvider.tsx | 10 +- apps/web/lib/security/useSessionLabel.ts | 18 +- convex/auth.ts | 42 ++-- convex/authEmailChallenges.ts | 68 ++++- convex/mfa.ts | 30 ++- convex/security.ts | 19 +- convex/users/queries.ts | 35 ++- tests/convex/mfa.test.ts | 247 ++++++++++++++++++- tests/convex/security-privacy.test.ts | 109 +++++++- 9 files changed, 514 insertions(+), 64 deletions(-) diff --git a/apps/mobile/lib/security/AppLockProvider.tsx b/apps/mobile/lib/security/AppLockProvider.tsx index ad6be317..50eb613b 100644 --- a/apps/mobile/lib/security/AppLockProvider.tsx +++ b/apps/mobile/lib/security/AppLockProvider.tsx @@ -165,11 +165,15 @@ export function AppLockProvider({ const previous = activeState.current; activeState.current = next; if (next === 'background' && previous !== 'background') { - // Remember when we left; the lock decides on return (after the timeout). + // Preserve the start time through iOS's inactive state; evaluate it when active returns. backgroundAt.current = Date.now(); if (devicePromptInFlight.current) suppressNextPrompt.current = true; - } else if (next === 'active' && previous === 'background' && userId) { - const away = backgroundAt.current === null ? Infinity : Date.now() - backgroundAt.current; + } else if ( + next === 'active' && + userId && + backgroundAt.current !== null + ) { + const away = Date.now() - backgroundAt.current; backgroundAt.current = null; if (!lockTimedOut(away, timeoutRef.current)) return; ++generation.current; diff --git a/apps/web/lib/security/useSessionLabel.ts b/apps/web/lib/security/useSessionLabel.ts index 95077e5f..048ae6b6 100644 --- a/apps/web/lib/security/useSessionLabel.ts +++ b/apps/web/lib/security/useSessionLabel.ts @@ -4,6 +4,8 @@ import * as React from 'react'; import { useMutation } from 'convex/react'; import { api } from '@convex/_generated/api'; +// Slightly longer than touchSession's five-minute throttle so each tick refreshes activity. +const SESSION_HEARTBEAT_MS = 6 * 60_000; /** "Chrome on Windows", "Safari on iPhone"… from the user agent (best effort). */ export function browserLabel(userAgent: string): string { const browser = /Edg\//.test(userAgent) @@ -35,11 +37,23 @@ export function browserLabel(userAgent: string): string { return `${browser} on ${os}`; } -/** Labels this browser's session for Settings → Security → Devices (once per page load). */ +/** Labels this browser's session and keeps its last-active time fresh while the SPA is open. */ export function useSessionLabel(signedIn: boolean) { const touch = useMutation(api.security.touchSession); React.useEffect(() => { if (!signedIn) return; - touch({ platform: 'web', label: browserLabel(navigator.userAgent) }).catch(() => undefined); + const heartbeat = () => { + if (document.visibilityState !== 'visible') return; + void touch({ platform: 'web', label: browserLabel(navigator.userAgent) }).catch( + () => undefined, + ); + }; + heartbeat(); + const interval = window.setInterval(heartbeat, SESSION_HEARTBEAT_MS); + document.addEventListener('visibilitychange', heartbeat); + return () => { + window.clearInterval(interval); + document.removeEventListener('visibilitychange', heartbeat); + }; }, [signedIn, touch]); } diff --git a/convex/auth.ts b/convex/auth.ts index 5247ec58..f880dbe2 100644 --- a/convex/auth.ts +++ b/convex/auth.ts @@ -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 }); @@ -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; }, }); diff --git a/convex/authEmailChallenges.ts b/convex/authEmailChallenges.ts index cc1e56e7..e30141ae 100644 --- a/convex/authEmailChallenges.ts +++ b/convex/authEmailChallenges.ts @@ -93,17 +93,23 @@ export const consume = internalMutation({ }); /** - * Puts a new email code on an active challenge (when someone with an authenticator app asks for - * the email code instead). Returns the address to send it to, or null if the challenge is gone. + * Reserves an active challenge's email resend slot without replacing its current code. The slot + * is rolled back if delivery fails, so the existing code stays usable and a retry can proceed. */ -export const rotateCode = internalMutation({ - args: { challengeIdHash: v.string(), codeHash: v.string(), now: v.number() }, - handler: async (ctx, { challengeIdHash, codeHash, now }) => { +export const reserveCodeResend = internalMutation({ + args: { challengeIdHash: v.string(), now: v.number() }, + handler: async (ctx, { challengeIdHash, now }) => { const challenge = await ctx.db .query('authEmailChallenges') .withIndex('by_challenge', (query) => query.eq('challengeIdHash', challengeIdHash)) .unique(); - if (!challenge || challenge.consumedAt !== undefined || challenge.expiresAt <= now) return null; + if ( + !challenge || + challenge.consumedAt !== undefined || + challenge.expiresAt <= now || + challenge.attempts >= maxVerificationAttempts + ) + return null; if ( challenge.emailSentAt !== undefined && now - challenge.emailSentAt < minimumResendIntervalMs @@ -111,12 +117,58 @@ export const rotateCode = internalMutation({ throw new Error('TWO_FACTOR_RATE_LIMITED'); const user = await ctx.db.get(challenge.userId); if (!user?.email || user.deletedAt !== undefined) return null; + const previousEmailSentAt = challenge.emailSentAt ?? null; + await ctx.db.patch(challenge._id, { emailSentAt: now }); + return { email: user.email.toLowerCase(), reservedAt: now, previousEmailSentAt }; + }, +}); + +/** Makes a delivered resend code current only while its reservation is still active. */ +export const finishCodeResend = internalMutation({ + args: { + challengeIdHash: v.string(), + codeHash: v.string(), + reservedAt: v.number(), + now: v.number(), + }, + handler: async (ctx, { challengeIdHash, codeHash, reservedAt, now }) => { + const challenge = await ctx.db + .query('authEmailChallenges') + .withIndex('by_challenge', (query) => query.eq('challengeIdHash', challengeIdHash)) + .unique(); + if ( + !challenge || + challenge.consumedAt !== undefined || + challenge.expiresAt <= now || + challenge.attempts >= maxVerificationAttempts || + challenge.emailSentAt !== reservedAt + ) + return false; await ctx.db.patch(challenge._id, { codeHash, - emailSentAt: now, expiresAt: Math.max(challenge.expiresAt, now + challengeLifetimeMs), }); - return { email: user.email.toLowerCase() }; + return true; + }, +}); + +/** Releases a failed delivery's rate-limit reservation without touching the working code. */ +export const releaseCodeResend = internalMutation({ + args: { + challengeIdHash: v.string(), + reservedAt: v.number(), + previousEmailSentAt: v.union(v.number(), v.null()), + }, + handler: async (ctx, { challengeIdHash, reservedAt, previousEmailSentAt }) => { + const challenge = await ctx.db + .query('authEmailChallenges') + .withIndex('by_challenge', (query) => query.eq('challengeIdHash', challengeIdHash)) + .unique(); + if (!challenge || challenge.emailSentAt !== reservedAt) return false; + await ctx.db.patch(challenge._id, { + emailSentAt: previousEmailSentAt === null ? undefined : previousEmailSentAt, + }); + return true; }, }); diff --git a/convex/mfa.ts b/convex/mfa.ts index ea27fe4c..c4d28ad8 100644 --- a/convex/mfa.ts +++ b/convex/mfa.ts @@ -118,13 +118,18 @@ export const savePending = internalMutation({ export const activateTotp = internalMutation({ args: { userId: v.id('users'), + pendingSecret: v.string(), step: v.number(), recoveryHashes: v.optional(v.array(v.string())), }, - handler: async (ctx, { userId, step, recoveryHashes }) => { + handler: async (ctx, { userId, pendingSecret, step, recoveryHashes }) => { const row = await factorsRow(ctx, userId); - if (!row?.totpPendingSecret) throw new Error('TOTP_NOT_STARTED'); + if (!row?.totpPendingSecret || row.totpPendingSecret !== pendingSecret) + throw new Error('TOTP_ENROLLMENT_CHANGED'); const now = Date.now(); + const recoveryDetail = recoveryHashes + ? ` ${recoveryHashes.length} recovery code${recoveryHashes.length === 1 ? '' : 's'} were created and shown once.` + : ''; await upsert(ctx, userId, { totpSecret: row.totpPendingSecret, totpPendingSecret: undefined, @@ -142,7 +147,7 @@ export const activateTotp = internalMutation({ 'account', String(userId), 'Authenticator app turned on', - 'Sign-in now asks for a code from your authenticator app. If this wasn’t you, change your password and turn it off in Settings → Security.', + `Sign-in now asks for a code from your authenticator app.${recoveryDetail} If this wasn’t you, change your password and turn it off in Settings → Security.`, ); }, }); @@ -173,10 +178,22 @@ export const deactivateTotp = internalMutation({ export const replaceRecoveryCodes = internalMutation({ args: { userId: v.id('users'), hashes: v.array(v.string()) }, handler: async (ctx, { userId, hashes }) => { + const now = Date.now(); await upsert(ctx, userId, { recoveryCodes: hashes.map((hash) => ({ hash })), - recoveryCreatedAt: Date.now(), + recoveryCreatedAt: now, }); + const count = hashes.length; + await createNotification( + ctx, + userId, + `security:recovery-codes:${now}:${hashes[0] ?? 'empty'}`, + 'security', + 'account', + String(userId), + 'Recovery codes regenerated', + `${count} new recovery code${count === 1 ? '' : 's'} were created. Your previous codes no longer work; save the new codes now. They are shown only once.`, + ); }, }); @@ -208,11 +225,11 @@ export const recordFactorUse = internalMutation({ await createNotification( ctx, userId, - `security:recovery-used:${now}`, + `security:recovery-used:${recoveryHash}`, 'security', 'account', String(userId), - 'Recovery code used to sign in', + 'Recovery code used', `${left} recovery code${left === 1 ? '' : 's'} left. Make new ones in Settings → Security if you’re running low.`, ); return true; @@ -312,6 +329,7 @@ export const confirmTotp = action({ const fresh = factors.recoveryRemaining === 0 ? await hashedCodes(userId) : null; await ctx.runMutation(internal.mfa.activateTotp, { userId, + pendingSecret: factors.totpPendingSecret, step, ...(fresh ? { recoveryHashes: fresh.hashes } : {}), }); diff --git a/convex/security.ts b/convex/security.ts index 7cc93a42..3b82500d 100644 --- a/convex/security.ts +++ b/convex/security.ts @@ -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) await createNotification( ctx, user._id, diff --git a/convex/users/queries.ts b/convex/users/queries.ts index 326544ae..feaed0ed 100644 --- a/convex/users/queries.ts +++ b/convex/users/queries.ts @@ -5,6 +5,7 @@ import { v } from 'convex/values'; import { getOptionalUser } from '../shared/auth'; import { normalizeUsername, usernameProblem, type UsernameProblem } from './domain'; import { avatarUrlForUser } from '../avatars/helpers'; +import type { Doc } from '../_generated/dataModel'; export const loginEmailForUsername = internalQuery({ args: { username: v.string() }, @@ -133,6 +134,8 @@ export const search = query({ }, }); +const GROUP_PROFILE_SEARCH_PAGE_SIZE = 50; + export const searchGroupProfiles = query({ args: { query: v.string() }, handler: async (ctx, args) => { @@ -140,17 +143,29 @@ export const searchGroupProfiles = query({ if (!current) return []; const searchTerm = normalizeUsername(args.query); if (!/^[a-z0-9_]{2,32}$/.test(searchTerm)) return []; - const users = await ctx.db - .query('users') - .withIndex('by_username', (q) => - q.gte('username', searchTerm).lte('username', `${searchTerm}\uffff`), - ) - .filter((q) => - q.and(q.neq(q.field('_id'), current._id), q.eq(q.field('deletedAt'), undefined)), - ) - .take(20); + const visible: Doc<'users'>[] = []; + let cursor: string | null = null; + let isDone = false; + while (visible.length < 20 && !isDone) { + const page = await ctx.db + .query('users') + .withIndex('by_username', (q) => + q.gte('username', searchTerm).lte('username', `${searchTerm}\uffff`), + ) + .filter((q) => + q.and(q.neq(q.field('_id'), current._id), q.eq(q.field('deletedAt'), undefined)), + ) + .paginate({ numItems: GROUP_PROFILE_SEARCH_PAGE_SIZE, cursor }); + for (const user of page.page) { + if (user.username === searchTerm || (await privacyFor(ctx, user._id)).discoverable) + visible.push(user); + if (visible.length === 20) break; + } + cursor = page.continueCursor; + isDone = page.isDone; + } return Promise.all( - users.map(async (user) => ({ + visible.map(async (user) => ({ id: user._id, displayName: user.displayName ?? user.name ?? 'Finapp user', username: user.username, diff --git a/tests/convex/mfa.test.ts b/tests/convex/mfa.test.ts index 86d5a445..c1a62fbd 100644 --- a/tests/convex/mfa.test.ts +++ b/tests/convex/mfa.test.ts @@ -1,6 +1,9 @@ +import { generateKeyPairSync } from 'node:crypto'; +import { Scrypt } from 'lucia'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { convexTest } from 'convex-test'; import { api, internal } from '../../convex/_generated/api'; +import type { Id } from '../../convex/_generated/dataModel'; import schema from '../../convex/schema'; import { base32Decode, @@ -71,6 +74,7 @@ beforeEach(() => { }); afterEach(() => { vi.unstubAllEnvs(); + vi.unstubAllGlobals(); }); async function fixture() { @@ -85,6 +89,30 @@ async function fixture() { return { t, userId, me: t.withIdentity({ subject: `${userId}|session` }) }; } +async function sha256(value: string) { + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)); + return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join(''); +} + +async function createEmailChallenge( + t: ReturnType, + userId: Id<'users'>, + challengeId: string, + code: string, + previousSentAt?: number, +) { + const challengeIdHash = await sha256(challengeId); + const codeHash = await sha256(`${challengeId}:${code}`); + await t.mutation(internal.authEmailChallenges.create, { + userId, + challengeIdHash, + codeHash, + now: previousSentAt ?? Date.now(), + ...(previousSentAt === undefined ? { emailSent: false } : {}), + }); + return { challengeIdHash, codeHash }; +} + /** The current code for a started or active TOTP secret (decrypted the way the server does). */ async function codeFor( t: ReturnType, @@ -125,6 +153,29 @@ describe('authenticator app enrollment', () => { const notes = await t.run((ctx) => ctx.db.query('notifications').collect()); expect(notes.map((row) => row.title)).toContain('Authenticator app turned on'); + expect( + notes.find((row) => row.title === 'Authenticator app turned on')?.body, + ).toContain('10 recovery codes were created and shown once'); + }); + + it('cannot activate a replacement enrollment with a previously verified secret', async () => { + const { t, userId, me } = await fixture(); + await me.action(api.mfa.startTotp, {}); + const stalePendingSecret = (await t.run((ctx) => ctx.db.query('mfaFactors').first()))! + .totpPendingSecret!; + + await me.action(api.mfa.startTotp, {}); + await expect( + t.mutation(internal.mfa.activateTotp, { + userId, + pendingSecret: stalePendingSecret, + step: currentStep(), + }), + ).rejects.toThrow('TOTP_ENROLLMENT_CHANGED'); + + await expect( + me.action(api.mfa.confirmTotp, { code: await codeFor(t, userId, true) }), + ).resolves.toMatchObject({ recoveryCodes: expect.any(Array) }); }); it('needs a current code (not a replay) or a recovery code to change things, each usable once', async () => { @@ -145,7 +196,29 @@ describe('authenticator app enrollment', () => { await expect( me.action(api.mfa.regenerateRecoveryCodes, { code: fresh.recoveryCodes[0]! }), ).rejects.toThrow('INVALID_CODE'); - + const regeneratedNotes = await t.run((ctx) => + ctx.db + .query('notifications') + .filter((q) => q.eq(q.field('title'), 'Recovery codes regenerated')) + .collect(), + ); + expect(regeneratedNotes).toHaveLength(2); + expect(regeneratedNotes.map((row) => row.body)).toEqual([ + expect.stringContaining('10 new recovery codes'), + expect.stringContaining('10 new recovery codes'), + ]); + expect(regeneratedNotes.every((row) => row.body.includes('previous codes no longer work'))).toBe( + true, + ); + expect(regeneratedNotes.every((row) => row.body.includes('shown only once'))).toBe(true); + const usedNotes = await t.run((ctx) => + ctx.db + .query('notifications') + .filter((q) => q.eq(q.field('title'), 'Recovery code used')) + .collect(), + ); + expect(usedNotes).toHaveLength(2); + expect(usedNotes.every((row) => row.body.includes('9 recovery codes left'))).toBe(true); // Turning it off with the next code. await me.action(api.mfa.disableTotp, { code: await codeFor(t, userId, false, 1) }); expect(await me.query(api.mfa.status, {})).toMatchObject({ totp: false }); @@ -191,7 +264,160 @@ describe('sign-in challenges with other factors', () => { ).toBeNull(); }); - it('only sends the email code on request, rate-limited', async () => { + it('sends an email fallback for TOTP accounts supported by older email-only clients', async () => { + const { t, userId } = await fixture(); + const password = 'runtime-test-password'; + const secret = await new Scrypt().hash(password); + const now = Date.now(); + await t.run(async (ctx) => { + await ctx.db.insert('userSettings', { + userId, + currency: 'INR', + timezone: 'Asia/Kolkata', + firstDayOfWeek: 1, + financialMonthStart: 1, + language: 'en', + appearance: 'system', + notificationPreferences: {}, + appLockPreferences: { enabled: false, fallback: 'device-pin' }, + twoFactorEnabled: true, + updatedAt: now, + }); + await ctx.db.insert('mfaFactors', { + userId, + totpSecret: 'encrypted-secret', + totpConfirmedAt: now, + recoveryCodes: [], + updatedAt: now, + }); + await ctx.db.insert('authAccounts', { + userId, + provider: 'password', + providerAccountId: 'olive@example.com', + secret, + emailVerified: '1', + }); + }); + const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); + vi.stubEnv('AUTH_RESEND_KEY', 're_test_key'); + vi.stubEnv('AUTH_EMAIL_FROM', 'Finapp '); + vi.stubEnv('JWT_PRIVATE_KEY', privateKey.export({ type: 'pkcs8', format: 'pem' }).toString()); + vi.stubEnv('CONVEX_SITE_URL', 'https://unit-test.convex.site'); + const sendEmail = vi.fn().mockResolvedValue(new Response(null, { status: 200 })); + vi.stubGlobal('fetch', sendEmail); + + const challenge = await t.action(api.auth.requestEmailTwoFactor, { + identifier: 'olive@example.com', + password, + }); + expect(challenge).toMatchObject({ + status: 'code-sent', + preferred: 'email', + methods: { totp: true, email: true, recovery: false }, + }); + if (challenge.status !== 'code-sent') throw new Error('Expected an email fallback challenge.'); + + const payload = JSON.parse(sendEmail.mock.calls[0]![1]!.body as string); + const code = payload.text.match(/\b(\d{6})\b/)?.[1]; + expect(code).toMatch(/^\d{6}$/); + if (!code) throw new Error('The email did not contain a code.'); + const result = await t.action(api.auth.signIn, { + provider: 'password', + params: { + challengeId: challenge.challengeId, + code, + flow: 'twoFactorVerification', + }, + }); + expect(result.tokens).toBeTruthy(); + }); + + it('keeps the prior email code usable when resend delivery fails', async () => { + const { t, userId } = await fixture(); + const challengeId = 'a'.repeat(64); + const previousSentAt = Date.now() - 31_000; + const { challengeIdHash, codeHash } = await createEmailChallenge( + t, + userId, + challengeId, + '123456', + previousSentAt, + ); + vi.stubEnv('AUTH_RESEND_KEY', 're_test_key'); + vi.stubEnv('AUTH_EMAIL_FROM', 'Finapp '); + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue(new Response(null, { status: 503 })), + ); + + await expect(t.action(api.auth.sendTwoFactorEmailCode, { challengeId })).rejects.toThrow( + 'Email delivery failed (503).', + ); + const row = await t.run((ctx) => + ctx.db + .query('authEmailChallenges') + .withIndex('by_challenge', (query) => query.eq('challengeIdHash', challengeIdHash)) + .unique(), + ); + expect(row?.codeHash).toBe(codeHash); + expect(row?.emailSentAt).toBe(previousSentAt); + await expect( + t.mutation(internal.authEmailChallenges.consume, { + challengeIdHash, + codeHash, + now: Date.now(), + }), + ).resolves.toEqual({ userId }); + }); + + it('allows an immediate retry after failed resend delivery', async () => { + const { t, userId } = await fixture(); + const challengeId = 'b'.repeat(64); + const originalCode = '123456'; + const previousSentAt = Date.now() - 31_000; + const { challengeIdHash, codeHash: originalCodeHash } = await createEmailChallenge( + t, + userId, + challengeId, + originalCode, + previousSentAt, + ); + vi.stubEnv('AUTH_RESEND_KEY', 're_test_key'); + vi.stubEnv('AUTH_EMAIL_FROM', 'Finapp '); + const sendEmail = vi + .fn() + .mockResolvedValueOnce(new Response(null, { status: 503 })) + .mockResolvedValueOnce(new Response(null, { status: 200 })); + vi.stubGlobal('fetch', sendEmail); + + await expect(t.action(api.auth.sendTwoFactorEmailCode, { challengeId })).rejects.toThrow( + 'Email delivery failed (503).', + ); + await expect( + t.action(api.auth.sendTwoFactorEmailCode, { challengeId }), + ).resolves.toBeNull(); + + const payload = JSON.parse(sendEmail.mock.calls[1]![1]!.body as string); + const resentCode = payload.text.match(/\b(\d{6})\b/)?.[1]; + expect(resentCode).toMatch(/^\d{6}$/); + if (!resentCode) throw new Error('The email did not contain a code.'); + await expect( + t.mutation(internal.authEmailChallenges.consume, { + challengeIdHash, + codeHash: originalCodeHash, + now: Date.now(), + }), + ).resolves.toBeNull(); + await expect( + t.mutation(internal.authEmailChallenges.consume, { + challengeIdHash, + codeHash: await sha256(`${challengeId}:${resentCode}`), + now: Date.now(), + }), + ).resolves.toEqual({ userId }); + }); + + it('reserves and rate-limits an email code resend', async () => { const { t, userId } = await fixture(); const now = Date.now(); await t.mutation(internal.authEmailChallenges.create, { @@ -201,17 +427,26 @@ describe('sign-in challenges with other factors', () => { now, emailSent: false, }); + const reservation = await t.mutation(internal.authEmailChallenges.reserveCodeResend, { + challengeIdHash: 'h2', + now, + }); + expect(reservation).toEqual({ + email: 'olive@example.com', + reservedAt: now, + previousEmailSentAt: null, + }); expect( - await t.mutation(internal.authEmailChallenges.rotateCode, { + await t.mutation(internal.authEmailChallenges.finishCodeResend, { challengeIdHash: 'h2', codeHash: 'c1', + reservedAt: now, now, }), - ).toEqual({ email: 'olive@example.com' }); + ).toBe(true); await expect( - t.mutation(internal.authEmailChallenges.rotateCode, { + t.mutation(internal.authEmailChallenges.reserveCodeResend, { challengeIdHash: 'h2', - codeHash: 'c2', now: now + 5_000, }), ).rejects.toThrow('TWO_FACTOR_RATE_LIMITED'); diff --git a/tests/convex/security-privacy.test.ts b/tests/convex/security-privacy.test.ts index c081cae5..d9bdc56e 100644 --- a/tests/convex/security-privacy.test.ts +++ b/tests/convex/security-privacy.test.ts @@ -64,6 +64,57 @@ describe('privacy preferences', () => { expect(await alice().query(api.users.queries.search, { query: 'bob' })).toEqual([]); expect((await alice().query(api.users.queries.search, { query: 'bobby' })).length).toBe(1); }); + it('applies discoverability to group profile suggestions but allows an exact username', async () => { + const { alice, bob } = await fixture(); + await bob.mutation(api.security.updatePrivacy, { discoverable: false }); + expect(await alice().query(api.users.queries.searchGroupProfiles, { query: 'bo' })).toEqual([]); + expect( + (await alice().query(api.users.queries.searchGroupProfiles, { query: 'bobby' })).map( + (user) => user.username, + ), + ).toEqual(['bobby']); + }); + + + it('continues group-profile search past a page of hidden users', async () => { + const { t, alice, bob } = await fixture(); + await bob.mutation(api.security.updatePrivacy, { discoverable: false }); + await t.run(async (ctx) => { + const now = Date.now(); + const insertUser = async (username: string, email: string, discoverable: boolean) => { + const userId = await ctx.db.insert('users', { + email, + username, + displayName: username, + emailVerificationTime: now, + }); + if (!discoverable) + await ctx.db.insert('userSettings', { + userId, + currency: 'USD', + timezone: 'UTC', + firstDayOfWeek: 1, + financialMonthStart: 1, + language: 'en', + appearance: 'system', + notificationPreferences: {}, + appLockPreferences: {}, + updatedAt: now, + discoverable: false, + }); + }; + for (let index = 0; index < 55; index++) { + const username = `bobby_${String(index).padStart(3, '0')}`; + await insertUser(username, `${username}@example.com`, false); + } + await insertUser('bozz', 'bozz@example.com', true); + }); + expect( + (await alice().query(api.users.queries.searchGroupProfiles, { query: 'bo' })).map( + (user) => user.username, + ), + ).toEqual(['bozz']); + }); it('refuses friend requests when they are turned off', async () => { const { ids, alice, bob } = await fixture(); @@ -75,6 +126,62 @@ describe('privacy preferences', () => { }); describe('devices', () => { + it('alerts for a later sign-in after the prior session expires, but not the first sign-in', async () => { + const { t } = await fixture(); + const first = await t.run(async (ctx) => { + const now = Date.now(); + const userId = await ctx.db.insert('users', { + email: 'first-login@example.com', + username: 'first_login', + emailVerificationTime: now, + }); + const sessionId = await ctx.db.insert('authSessions', { + userId, + expirationTime: now + 86_400_000, + }); + return { userId, sessionId }; + }); + const asSession = (sessionId: typeof first.sessionId) => + t.withIdentity({ subject: `${first.userId}|${sessionId}` }); + + await asSession(first.sessionId).mutation(api.security.touchSession, { + platform: 'ios', + label: 'Safari on iPhone', + }); + expect( + await t.run(async (ctx) => + (await ctx.db.query('notifications').collect()).filter( + (row) => row.recipientId === first.userId, + ), + ), + ).toEqual([]); + + const nextSession = await t.run(async (ctx) => { + await ctx.db.patch(first.sessionId, { expirationTime: Date.now() - 1 }); + await ctx.db.delete(first.sessionId); + return ctx.db.insert('authSessions', { + userId: first.userId, + expirationTime: Date.now() + 86_400_000, + }); + }); + await asSession(nextSession).mutation(api.security.touchSession, { + platform: 'web', + label: 'Chrome on Windows', + }); + await asSession(nextSession).mutation(api.security.touchSession, { + platform: 'web', + label: 'Chrome on Windows', + }); + + const alerts = await t.run(async (ctx) => + (await ctx.db.query('notifications').collect()).filter( + (row) => row.recipientId === first.userId, + ), + ); + expect(alerts.map((row) => row.title)).toEqual(['New sign-in to your account']); + expect(alerts[0]?.body).toContain('Chrome on Windows signed in.'); + }); + it('lists active sessions with labels, marks this one, and alerts on a new device', async () => { const { t, ids, alice } = await fixture(); await alice(ids.laptop).mutation(api.security.touchSession, { @@ -90,10 +197,8 @@ describe('devices', () => { ['Chrome on Windows', 'web', true], ['Pixel 8', 'android', false], ]); - const alerts = await t.run((ctx) => ctx.db.query('notifications').collect()); expect(alerts.map((row) => [row.type, row.title])).toEqual([ ['security', 'New sign-in to your account'], - ['security', 'New sign-in to your account'], ]); expect(alerts.some((row) => row.body.startsWith('Pixel 8 signed in.'))).toBe(true); }); From 557dbe014b891b4ede621c488411314d3030b357 Mon Sep 17 00:00:00 2001 From: NeerajCodz Date: Fri, 27 Nov 2026 08:03:49 +0530 Subject: [PATCH 3/4] fix(auth): bound profile search and repair security test - Bound username-search candidates while retaining privacy filtering. - Restore the notification fixture used by the security assertion. --- convex/users/queries.ts | 34 +++++++++++---------------- tests/convex/security-privacy.test.ts | 5 ++++ 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/convex/users/queries.ts b/convex/users/queries.ts index feaed0ed..1f40bc08 100644 --- a/convex/users/queries.ts +++ b/convex/users/queries.ts @@ -134,7 +134,7 @@ export const search = query({ }, }); -const GROUP_PROFILE_SEARCH_PAGE_SIZE = 50; +const GROUP_PROFILE_SEARCH_MAX_CANDIDATES = 1_000; export const searchGroupProfiles = query({ args: { query: v.string() }, @@ -143,26 +143,20 @@ export const searchGroupProfiles = query({ if (!current) return []; const searchTerm = normalizeUsername(args.query); if (!/^[a-z0-9_]{2,32}$/.test(searchTerm)) return []; + const candidates = await ctx.db + .query('users') + .withIndex('by_username', (q) => + q.gte('username', searchTerm).lte('username', `${searchTerm}\uffff`), + ) + .filter((q) => + q.and(q.neq(q.field('_id'), current._id), q.eq(q.field('deletedAt'), undefined)), + ) + .take(GROUP_PROFILE_SEARCH_MAX_CANDIDATES); const visible: Doc<'users'>[] = []; - let cursor: string | null = null; - let isDone = false; - while (visible.length < 20 && !isDone) { - const page = await ctx.db - .query('users') - .withIndex('by_username', (q) => - q.gte('username', searchTerm).lte('username', `${searchTerm}\uffff`), - ) - .filter((q) => - q.and(q.neq(q.field('_id'), current._id), q.eq(q.field('deletedAt'), undefined)), - ) - .paginate({ numItems: GROUP_PROFILE_SEARCH_PAGE_SIZE, cursor }); - for (const user of page.page) { - if (user.username === searchTerm || (await privacyFor(ctx, user._id)).discoverable) - visible.push(user); - if (visible.length === 20) break; - } - cursor = page.continueCursor; - isDone = page.isDone; + for (const user of candidates) { + if (user.username === searchTerm || (await privacyFor(ctx, user._id)).discoverable) + visible.push(user); + if (visible.length === 20) break; } return Promise.all( visible.map(async (user) => ({ diff --git a/tests/convex/security-privacy.test.ts b/tests/convex/security-privacy.test.ts index d9bdc56e..f62ab128 100644 --- a/tests/convex/security-privacy.test.ts +++ b/tests/convex/security-privacy.test.ts @@ -197,6 +197,11 @@ describe('devices', () => { ['Chrome on Windows', 'web', true], ['Pixel 8', 'android', false], ]); + const alerts = await t.run(async (ctx) => + (await ctx.db.query('notifications').collect()).filter( + (row) => row.recipientId === ids.alice, + ), + ); expect(alerts.map((row) => [row.type, row.title])).toEqual([ ['security', 'New sign-in to your account'], ]); From 362b940d31946726283a4a54dfaa430df92c6f70 Mon Sep 17 00:00:00 2001 From: NeerajCodz Date: Fri, 27 Nov 2026 08:21:59 +0530 Subject: [PATCH 4/4] test(auth): filter sign-in alerts by user id - Query the fixture notifications using the seeded user id. --- tests/convex/security-privacy.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/convex/security-privacy.test.ts b/tests/convex/security-privacy.test.ts index f62ab128..dee8d69b 100644 --- a/tests/convex/security-privacy.test.ts +++ b/tests/convex/security-privacy.test.ts @@ -199,7 +199,7 @@ describe('devices', () => { ]); const alerts = await t.run(async (ctx) => (await ctx.db.query('notifications').collect()).filter( - (row) => row.recipientId === ids.alice, + (row) => row.recipientId === ids.aliceId, ), ); expect(alerts.map((row) => [row.type, row.title])).toEqual([