Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(auth): claim revert links and backup codes on first use (#3537)

Hampus65faf056b9fd
diff --git a/fluxer_api/src/api/auth/AuthEmailRevert.ts b/fluxer_api/src/api/auth/AuthEmailRevert.ts
index 0cc6615e3..82a08078e 100644
--- a/fluxer_api/src/api/auth/AuthEmailRevert.ts
+++ b/fluxer_api/src/api/auth/AuthEmailRevert.ts
@@ -1,13 +1,17 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import crypto from 'node:crypto';
import type {ApiContext} from '@app/api/ApiContext';
import * as AuthPassword from '@app/api/auth/AuthPassword';
import * as AuthSession from '@app/api/auth/AuthSession';
import {revokeAllAuthSessions} from '@app/api/auth/AuthSessionRevocation';
import * as AuthUtility from '@app/api/auth/AuthUtility';
import {createEmailRevertToken} from '@app/api/BrandedTypes';
+import {Logger} from '@app/api/Logger';
+import {getKVClient} from '@app/api/middleware/ServiceRegistry';
import type {User} from '@app/api/models/User';
import {enqueueStripeCustomerEmailSync} from '@app/api/stripe/StripeCustomer';
+import {EMAIL_REVERT_TOKEN_TTL_SECONDS} from '@app/api/user/repositories/auth/TokenRepository';
import {dispatchUserUpdate} from '@app/api/user/UserMappers';
import {hashPassword} from '@app/api/utils/PasswordUtils';
import * as RandomUtils from '@app/api/utils/RandomUtils';
@@ -41,6 +45,24 @@ export async function issueEmailRevertToken(ctx: ApiContext, params: IssueEmailR
await email.sendEmailChangeRevert(trimmed, user.username, newEmail, token, user.locale);
}
+const EMAIL_REVERT_CLAIM_KEY_PREFIX = 'auth:email-revert:claimed:';
+
+function emailRevertClaimKey(token: string): string {
+ return `${EMAIL_REVERT_CLAIM_KEY_PREFIX}${crypto.createHash('sha256').update(token).digest('hex')}`;
+}
+
+function claimEmailRevertToken(token: string): Promise<boolean> {
+ return getKVClient().setnx(emailRevertClaimKey(token), '1', EMAIL_REVERT_TOKEN_TTL_SECONDS);
+}
+
+async function releaseEmailRevertTokenClaim(token: string): Promise<void> {
+ try {
+ await getKVClient().del(emailRevertClaimKey(token));
+ } catch (error) {
+ Logger.error({error}, 'Could not release the claim of an email revert token whose revert failed');
+ }
+}
+
export async function revertEmailChange(
ctx: ApiContext,
params: RevertEmailChangeParams,
@@ -63,20 +85,28 @@ export async function revertEmailChange(
if (await AuthPassword.isPasswordPwned(ctx, password)) {
throw InputValidationError.fromCode('password', ValidationErrorCodes.PASSWORD_IS_TOO_COMMON);
}
- const passwordHash = await hashPassword(password);
- const now = new Date();
- const updatedUser = await users.patchUpsert(
- user.id,
- {
- email: tokenData.email,
- email_verified: true,
- totp_secret: null,
- authenticator_types: null,
- password_hash: passwordHash,
- password_last_changed_at: now,
- },
- user.toRow(),
- );
+ if (!(await claimEmailRevertToken(token))) {
+ throw InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_REVERT_TOKEN);
+ }
+ let updatedUser: User;
+ try {
+ const passwordHash = await hashPassword(password);
+ updatedUser = await users.patchUpsert(
+ user.id,
+ {
+ email: tokenData.email,
+ email_verified: true,
+ totp_secret: null,
+ authenticator_types: null,
+ password_hash: passwordHash,
+ password_last_changed_at: new Date(),
+ },
+ user.toRow(),
+ );
+ } catch (error) {
+ await releaseEmailRevertTokenClaim(token);
+ throw error;
+ }
await users.deleteAllPasswordResetTokens(user.id);
await users.deleteEmailRevertToken(token);
await users.deleteAllMfaBackupCodes(user.id);
diff --git a/fluxer_api/src/api/auth/AuthMfa.ts b/fluxer_api/src/api/auth/AuthMfa.ts
index 264ddf7af..dd37ac7d4 100644
--- a/fluxer_api/src/api/auth/AuthMfa.ts
+++ b/fluxer_api/src/api/auth/AuthMfa.ts
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import crypto from 'node:crypto';
import type {ApiContext} from '@app/api/ApiContext';
import * as AuthUtility from '@app/api/auth/AuthUtility';
import {
@@ -151,6 +152,11 @@ export async function verifyMfaCode(ctx: ApiContext, params: VerifyMfaCodeParams
(bc) => !bc.consumed && constantTimeEquals(normalizeBackupCode(bc.code), normalizedCode),
);
if (backupCode) {
+ const hashedCode = crypto.createHash('sha256').update(normalizedCode).digest('hex');
+ const lockToken = await cache.acquireLock(`mfa-backup:${userId}:${hashedCode}`, seconds('90 seconds'));
+ if (!lockToken) {
+ return false;
+ }
await users.consumeMfaBackupCode(userId, backupCode.code);
return true;
}
diff --git a/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts b/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts
index 4427fef79..290417cdd 100644
--- a/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts
+++ b/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts
@@ -122,6 +122,45 @@ function uniquePassword(): string {
return `Sup3r-${Date.now()}-Pass!`;
}
+async function changeEmailAndGetRevertToken(harness: ApiTestHarness, account: TestAccount): Promise<string> {
+ const startResp = await startEmailChange(harness, account, account.password);
+ let originalProof: string;
+ if (startResp.require_original) {
+ const emails = await listTestEmails(harness, {recipient: account.email});
+ const originalEmail = findLastTestEmail(emails, 'email_change_original');
+ expect(originalEmail?.metadata?.code).toBeDefined();
+ const originalCode = originalEmail!.metadata!.code!;
+ originalProof = await verifyOriginalEmailChange(harness, account, startResp.ticket, originalCode, account.password);
+ } else {
+ originalProof = startResp.original_proof!;
+ }
+ const newEmail = `integration-revert-${Date.now()}@example.com`;
+ await requestNewEmailChange(harness, account, startResp.ticket, newEmail, originalProof, account.password);
+ const newEmails = await listTestEmails(harness, {recipient: newEmail});
+ const newEmailData = findLastTestEmail(newEmails, 'email_change_new');
+ expect(newEmailData?.metadata?.code).toBeDefined();
+ const newCode = newEmailData!.metadata!.code!;
+ const emailToken = await verifyNewEmailChange(
+ harness,
+ account,
+ startResp.ticket,
+ newCode,
+ originalProof,
+ account.password,
+ );
+ await createBuilder(harness, account.token)
+ .patch('/users/@me')
+ .body({
+ email_token: emailToken,
+ password: account.password,
+ })
+ .execute();
+ const revertEmails = await listTestEmails(harness, {recipient: account.email});
+ const revertEmail = findLastTestEmail(revertEmails, 'email_change_revert');
+ expect(revertEmail?.metadata?.token).toBeDefined();
+ return revertEmail!.metadata!.token!;
+}
+
describe('Email revert flow', () => {
let harness: ApiTestHarness;
beforeAll(async () => {
@@ -137,6 +176,20 @@ describe('Email revert flow', () => {
afterAll(async () => {
await harness?.shutdown();
});
+ it('accepts a revert token for only one of several concurrent reverts', async () => {
+ const account = await createTestAccount(harness);
+ const revertToken = await changeEmailAndGetRevertToken(harness, account);
+ const results = await Promise.all(
+ Array.from({length: 4}, () =>
+ createBuilderWithoutAuth(harness)
+ .post('/auth/email-revert')
+ .body({token: revertToken, password: uniquePassword()})
+ .executeRaw(),
+ ),
+ );
+ const statuses = results.map(({response}) => response.status).sort();
+ expect(statuses).toEqual([200, 400, 400, 400].sort());
+ });
it('restores original email and clears mfa', async () => {
const account = await createTestAccount(harness);
await createBuilderWithoutAuth(harness)
@@ -145,48 +198,7 @@ describe('Email revert flow', () => {
.expect(200)
.execute();
const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');
- const startResp = await startEmailChange(harness, account, account.password);
- let originalProof: string;
- if (startResp.require_original) {
- const emails = await listTestEmails(harness, {recipient: account.email});
- const originalEmail = findLastTestEmail(emails, 'email_change_original');
- expect(originalEmail?.metadata?.code).toBeDefined();
- const originalCode = originalEmail!.metadata!.code!;
- originalProof = await verifyOriginalEmailChange(
- harness,
- account,
- startResp.ticket,
- originalCode,
- account.password,
- );
- } else {
- originalProof = startResp.original_proof!;
- }
- const newEmail = `integration-revert-${Date.now()}@example.com`;
- await requestNewEmailChange(harness, account, startResp.ticket, newEmail, originalProof, account.password);
- const newEmails = await listTestEmails(harness, {recipient: newEmail});
- const newEmailData = findLastTestEmail(newEmails, 'email_change_new');
- expect(newEmailData?.metadata?.code).toBeDefined();
- const newCode = newEmailData!.metadata!.code!;
- const emailToken = await verifyNewEmailChange(
- harness,
- account,
- startResp.ticket,
- newCode,
- originalProof,
- account.password,
- );
- await createBuilder(harness, account.token)
- .patch('/users/@me')
- .body({
- email_token: emailToken,
- password: account.password,
- })
- .execute();
- const revertEmails = await listTestEmails(harness, {recipient: account.email});
- const revertEmail = findLastTestEmail(revertEmails, 'email_change_revert');
- expect(revertEmail?.metadata?.token).toBeDefined();
- const revertToken = revertEmail!.metadata!.token!;
+ const revertToken = await changeEmailAndGetRevertToken(harness, account);
const newPassword = uniquePassword();
addJob.mockClear();
const revertResp = await createBuilderWithoutAuth<EmailRevertResponse>(harness)
diff --git a/fluxer_api/src/api/auth/tests/MfaBackupCodeLogin.test.ts b/fluxer_api/src/api/auth/tests/MfaBackupCodeLogin.test.ts
index e24ace50e..3f11453de 100644
--- a/fluxer_api/src/api/auth/tests/MfaBackupCodeLogin.test.ts
+++ b/fluxer_api/src/api/auth/tests/MfaBackupCodeLogin.test.ts
@@ -168,6 +168,21 @@ describe('MFA backup code login', () => {
expect(consumed).toHaveLength(1);
expect(consumed[0]!.code).toBe(issued);
});
+ it('accepts a backup code for only one of several concurrent logins', async () => {
+ const account = await createTestAccount(harness);
+ const secret = createTotpSecret();
+ const codes = await enableTotp(harness, account, secret);
+ const tickets = await Promise.all(Array.from({length: 4}, () => startMfaLogin(harness, account)));
+ const results = await Promise.all(
+ tickets.map((ticket) =>
+ createBuilderWithoutAuth(harness).post('/auth/login/mfa/totp').body({ticket, code: codes[0]!}).executeRaw(),
+ ),
+ );
+ const statuses = results.map(({response}) => response.status).sort();
+ expect(statuses).toEqual(
+ [HTTP_STATUS.OK, HTTP_STATUS.BAD_REQUEST, HTTP_STATUS.BAD_REQUEST, HTTP_STATUS.BAD_REQUEST].sort(),
+ );
+ });
it('rejects empty and whitespace only backup codes', async () => {
const account = await createTestAccount(harness);
const secret = createTotpSecret();
diff --git a/fluxer_api/src/api/user/repositories/auth/TokenRepository.ts b/fluxer_api/src/api/user/repositories/auth/TokenRepository.ts
index 4c6aa2bb0..498105021 100644
--- a/fluxer_api/src/api/user/repositories/auth/TokenRepository.ts
+++ b/fluxer_api/src/api/user/repositories/auth/TokenRepository.ts
@@ -31,6 +31,7 @@ const FETCH_PASSWORD_RESET_TOKENS_BY_USER_CQL = PasswordResetTokensByUserId.sele
where: PasswordResetTokensByUserId.where.eq('user_id'),
});
export const PASSWORD_RESET_TOKEN_TTL_SECONDS = seconds('1 hour');
+export const EMAIL_REVERT_TOKEN_TTL_SECONDS = seconds('24 hours');
const FETCH_EMAIL_REVERT_TOKEN_CQL = EmailRevertTokens.selectCql({
where: EmailRevertTokens.where.eq('token_'),
@@ -97,7 +98,7 @@ export class TokenRepository {
}
async createEmailRevertToken(tokenData: EmailRevertTokenRow): Promise<EmailRevertToken> {
- await upsertOne(EmailRevertTokens.insertWithTtl(tokenData, seconds('24 hours')));
+ await upsertOne(EmailRevertTokens.insertWithTtl(tokenData, EMAIL_REVERT_TOKEN_TTL_SECONDS));
return new EmailRevertToken(tokenData);
}