Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/mobile/components/security/MfaSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
10 changes: 7 additions & 3 deletions apps/mobile/lib/security/AppLockProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
) {
Comment on lines +172 to +175

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear the background timestamp while signed out

If the app is backgrounded and restored while userId is null, this condition skips the only statement that clears backgroundAt. After the user signs in, a later inactive → active transition—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 👍 / 👎.

const away = Date.now() - backgroundAt.current;
backgroundAt.current = null;
if (!lockTimedOut(away, timeoutRef.current)) return;
++generation.current;
Expand Down
2 changes: 1 addition & 1 deletion apps/web/components/security/MfaSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const errorText = (cause: unknown) => {
};

function Qr({ qr }: { qr: Setup['qr'] }) {
const pad = 2;
const pad = 4;
return (
<svg
role="img"
Expand Down
18 changes: 16 additions & 2 deletions apps/web/lib/security/useSessionLabel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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]);
}
42 changes: 25 additions & 17 deletions convex/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -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, {
Expand All @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep TOTP sign-in independent of email delivery

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 👍 / 👎.

Expand All @@ -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;
},
});
Expand Down
68 changes: 60 additions & 8 deletions convex/authEmailChallenges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,30 +93,82 @@ 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
)
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;
},
});

Expand Down
30 changes: 24 additions & 6 deletions convex/mfa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.`,
);
},
});
Expand Down Expand Up @@ -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.`,
);
},
});

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 } : {}),
});
Expand Down
19 changes: 9 additions & 10 deletions convex/security.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fall back to active sessions for sign-in alerts

When another valid session has not yet created a sessionDevices row—such as an older client or a client whose best-effort touchSession call failed—priorDevice is null and this new sign-in produces no security alert. The client hooks swallow touch failures, and mobile does not retry, whereas the replaced authSessions predicate detected this case; retain the historical-device check but also treat another active session as prior account use.

Useful? React with 👍 / 👎.

await createNotification(
ctx,
user._id,
Expand Down
15 changes: 12 additions & 3 deletions convex/users/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() },
Expand Down Expand Up @@ -133,24 +134,32 @@ export const search = query({
},
});

const GROUP_PROFILE_SEARCH_MAX_CANDIDATES = 1_000;

export const searchGroupProfiles = query({
args: { query: v.string() },
handler: async (ctx, args) => {
const current = await getOptionalUser(ctx);
if (!current) return [];
const searchTerm = normalizeUsername(args.query);
if (!/^[a-z0-9_]{2,32}$/.test(searchTerm)) return [];
const users = await ctx.db
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(20);
.take(GROUP_PROFILE_SEARCH_MAX_CANDIDATES);
const visible: Doc<'users'>[] = [];
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(
users.map(async (user) => ({
visible.map(async (user) => ({
id: user._id,
displayName: user.displayName ?? user.name ?? 'Finapp user',
username: user.username,
Expand Down
Loading
Loading