Skip to content

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

TypeScript fluxerfluxerapp

feat(api): rate-limit and domain-check new email change codes

Hampus222c43316f34
diff --git a/fluxer_api/src/api/auth/AuthEmail.ts b/fluxer_api/src/api/auth/AuthEmail.ts
index b247f5efd..df8fc55b3 100644
--- a/fluxer_api/src/api/auth/AuthEmail.ts
+++ b/fluxer_api/src/api/auth/AuthEmail.ts
@@ -2,9 +2,9 @@
import type {ApiContext} from '@app/api/ApiContext';
import * as AuthUtility from '@app/api/auth/AuthUtility';
+import {confirmEmailOwnership} from '@app/api/auth/EmailOwnership';
import {createEmailVerificationToken} from '@app/api/BrandedTypes';
import type {User} from '@app/api/models/User';
-import {dispatchUserUpdate} from '@app/api/user/UserMappers';
import * as RandomUtils from '@app/api/utils/RandomUtils';
import {createRateLimitError} from '@app/api/utils/RateLimitUtils';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
@@ -12,7 +12,7 @@ import type {VerifyEmailRequest} from '@fluxer/schema/src/domains/auth/AuthSchem
import {ms} from 'itty-time';
export async function verifyEmail(ctx: ApiContext, data: VerifyEmailRequest): Promise<boolean> {
- const {users, gateway} = ctx.services;
+ const {users} = ctx.services;
const tokenData = await users.getEmailVerificationToken(data.token);
if (!tokenData) {
return false;
@@ -29,9 +29,8 @@ export async function verifyEmail(ctx: ApiContext, data: VerifyEmailRequest): Pr
) {
return false;
}
- const updatedUser = await users.patchUpsert(user.id, {email_verified: true, email_bounced: false}, user.toRow());
+ await confirmEmailOwnership(ctx, user);
await users.deleteEmailVerificationToken(data.token);
- await dispatchUserUpdate(gateway, updatedUser);
return true;
}
@@ -61,5 +60,5 @@ export async function sendVerificationEmail(ctx: ApiContext, params: {user: User
user_id: user.id,
email,
});
- await emailService.sendEmailVerification(email, user.username, token, user.locale);
+ await emailService.send('email_verification', email, {verificationToken: token}, user.locale);
}
diff --git a/fluxer_api/src/api/auth/EmailBlocklist.ts b/fluxer_api/src/api/auth/EmailBlocklist.ts
index 8e1a8c661..98bef34b9 100644
--- a/fluxer_api/src/api/auth/EmailBlocklist.ts
+++ b/fluxer_api/src/api/auth/EmailBlocklist.ts
@@ -6,8 +6,12 @@ import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidat
const adminRepository = new AdminRepository();
+export async function isEmailBlocklisted(email: string): Promise<boolean> {
+ return adminRepository.isEmailBanned(email.trim());
+}
+
export async function assertEmailNotBlocklisted(email: string, field: string): Promise<void> {
- if (await adminRepository.isEmailBanned(email.trim())) {
+ if (await isEmailBlocklisted(email)) {
throw InputValidationError.fromCode(field, ValidationErrorCodes.INVALID_EMAIL_ADDRESS);
}
}
diff --git a/fluxer_api/src/api/auth/tests/EmailChangeFlow.test.ts b/fluxer_api/src/api/auth/tests/EmailChangeFlow.test.ts
index 1362647a8..230f8e4f9 100644
--- a/fluxer_api/src/api/auth/tests/EmailChangeFlow.test.ts
+++ b/fluxer_api/src/api/auth/tests/EmailChangeFlow.test.ts
@@ -11,9 +11,11 @@ import {
loginUser,
type TestAccount,
} from '@app/api/auth/tests/AuthTestUtils';
+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
interface EmailChangeStartResponse {
@@ -126,9 +128,6 @@ describe('Email change flow', () => {
await harness.reset();
await clearTestEmails(harness);
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
afterAll(async () => {
await harness?.shutdown();
});
@@ -297,6 +296,77 @@ describe('Email change flow', () => {
.execute();
expect(updated.email).toBe(newEmail);
});
+ async function verifyOriginal(account: TestAccount): Promise<{ticket: string; originalProof: string}> {
+ const startResp = await startEmailChange(harness, account, account.password);
+ const originalEmail = findLastTestEmail(
+ await listTestEmails(harness, {recipient: account.email}),
+ 'email_change_original',
+ );
+ const originalProof = await verifyOriginalEmailChange(
+ harness,
+ account,
+ startResp.ticket,
+ originalEmail!.metadata!.code!,
+ account.password,
+ );
+ return {ticket: startResp.ticket, originalProof};
+ }
+
+ it('refuses a new address stored on another account, confirmed or not', async () => {
+ const owner = await createTestAccount(harness);
+ const holder = await createBuilderWithoutAuth<{token: string}>(harness)
+ .post('/auth/register')
+ .body({username: 'pendingholder', consent: true, date_of_birth: '1995-05-05'})
+ .execute();
+ const unconfirmed = `integration-held-${Date.now()}@example.com`;
+ await createBuilder(harness, holder.token).post('/users/@me/claim').body({email: unconfirmed}).execute();
+ const account = await createTestAccount(harness);
+ for (const taken of [owner.email, unconfirmed]) {
+ const {ticket, originalProof} = await verifyOriginal(account);
+ const {json} = await createBuilder<{errors: Array<{path: string; code: string}>}>(harness, account.token)
+ .post('/users/@me/email-change/request-new')
+ .body({ticket, new_email: taken, original_proof: originalProof, password: account.password})
+ .expect(400, 'INVALID_FORM_BODY')
+ .executeWithResponse();
+ expect(json.errors).toEqual([
+ expect.objectContaining({path: 'new_email', code: ValidationErrorCodes.EMAIL_ALREADY_IN_USE}),
+ ]);
+ expect(findLastTestEmail(await listTestEmails(harness, {recipient: taken}), 'email_change_new')).toBeNull();
+ }
+ });
+
+ it('refuses a new address outside the allowed email domains', async () => {
+ const account = await createTestAccount(harness);
+ await getInstanceConfigRepository().setRegistrationConfig({allowed_email_domains: ['example.com']});
+ const outside = `integration-outside-${Date.now()}@elsewhere.test`;
+ const {ticket, originalProof} = await verifyOriginal(account);
+ const {json} = await createBuilder<{errors: Array<{path: string; code: string}>}>(harness, account.token)
+ .post('/users/@me/email-change/request-new')
+ .body({ticket, new_email: outside, original_proof: originalProof, password: account.password})
+ .expect(400, 'INVALID_FORM_BODY')
+ .executeWithResponse();
+ expect(json.errors).toEqual([
+ expect.objectContaining({path: 'new_email', code: ValidationErrorCodes.EMAIL_DOMAIN_NOT_ALLOWED}),
+ ]);
+ expect(findLastTestEmail(await listTestEmails(harness, {recipient: outside}), 'email_change_new')).toBeNull();
+ });
+
+ it('refuses to claim an account with an address outside the allowed email domains', async () => {
+ await getInstanceConfigRepository().setRegistrationConfig({allowed_email_domains: ['example.com']});
+ const holder = await createBuilderWithoutAuth<{token: string}>(harness)
+ .post('/auth/register')
+ .body({username: 'outsideclaimer', consent: true, date_of_birth: '1995-05-05'})
+ .execute();
+ const {json} = await createBuilder<{errors: Array<{path: string; code: string}>}>(harness, holder.token)
+ .post('/users/@me/claim')
+ .body({email: `integration-claim-${Date.now()}@elsewhere.test`})
+ .expect(400, 'INVALID_FORM_BODY')
+ .executeWithResponse();
+ expect(json.errors).toEqual([
+ expect.objectContaining({path: 'email', code: ValidationErrorCodes.EMAIL_DOMAIN_NOT_ALLOWED}),
+ ]);
+ });
+
it('applies email changes for users who have ever purchased and syncs their Stripe customer', async () => {
const account = await createTestAccount(harness);
await createBuilderWithoutAuth(harness)
@@ -346,46 +416,6 @@ describe('Email change flow', () => {
expect(updated.has_ever_purchased).toBe(true);
expect(addJob).toHaveBeenCalledWith('syncStripeCustomerEmail', {userId: account.userId});
});
- it('applies ordinary claimed email changes', async () => {
- const account = await createTestAccount(harness);
- const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');
- const startResp = await startEmailChange(harness, account, account.password);
- const emails = await listTestEmails(harness, {recipient: account.email});
- const originalEmail = findLastTestEmail(emails, 'email_change_original');
- expect(startResp.require_original).toBe(true);
- expect(originalEmail?.metadata?.code).toBeDefined();
- const originalProof = await verifyOriginalEmailChange(
- harness,
- account,
- startResp.ticket,
- originalEmail!.metadata!.code!,
- account.password,
- );
- const newEmail = `integration-plain-${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 token = await verifyNewEmailChange(
- harness,
- account,
- startResp.ticket,
- newEmailData!.metadata!.code!,
- originalProof,
- account.password,
- );
- const updated = await createBuilder<UserPrivateResponse>(harness, account.token)
- .patch('/users/@me')
- .body({
- email_token: token,
- password: account.password,
- })
- .expect(200)
- .execute();
- expect(updated.email).toBe(newEmail);
- expect(updated.verified).toBe(true);
- expect(addJob).not.toHaveBeenCalledWith('syncStripeCustomerEmail', expect.anything());
- });
it('requires MFA (not password) for email_token apply when user has TOTP enabled', async () => {
const account = await createTestAccount(harness);
const secret = createTotpSecret();
@@ -448,7 +478,13 @@ describe('Email change flow', () => {
.expect(403, 'SUDO_MODE_REQUIRED')
.execute();
expect(noSudoResp.has_mfa).toBe(true);
- expect(noSudoResp.methods).toEqual({totp: true, webauthn: false, backup_codes: true});
+ expect(noSudoResp.methods).toEqual({
+ totp: true,
+ webauthn: false,
+ backup_codes: true,
+ email_code: false,
+ password: false,
+ });
const passwordOnlyResp = await createBuilder<{
code: string;
has_mfa?: boolean;
@@ -463,7 +499,13 @@ describe('Email change flow', () => {
.expect(403, 'SUDO_MODE_REQUIRED')
.execute();
expect(passwordOnlyResp.has_mfa).toBe(true);
- expect(passwordOnlyResp.methods).toEqual({totp: true, webauthn: false, backup_codes: true});
+ expect(passwordOnlyResp.methods).toEqual({
+ totp: true,
+ webauthn: false,
+ backup_codes: true,
+ email_code: false,
+ password: false,
+ });
const updated = await createBuilder<UserPrivateResponse>(harness, mfaAccount.token)
.patch('/users/@me')
.body({
@@ -535,7 +577,13 @@ describe('Email change flow', () => {
.expect(403, 'SUDO_MODE_REQUIRED')
.execute();
expect(noSudoResp.has_mfa).toBe(true);
- expect(noSudoResp.methods).toEqual({totp: true, webauthn: false, backup_codes: true});
+ expect(noSudoResp.methods).toEqual({
+ totp: true,
+ webauthn: false,
+ backup_codes: true,
+ email_code: false,
+ password: false,
+ });
const passwordOnlyResp = await createBuilder<{
code: string;
has_mfa?: boolean;
@@ -550,7 +598,13 @@ describe('Email change flow', () => {
.expect(403, 'SUDO_MODE_REQUIRED')
.execute();
expect(passwordOnlyResp.has_mfa).toBe(true);
- expect(passwordOnlyResp.methods).toEqual({totp: true, webauthn: false, backup_codes: true});
+ expect(passwordOnlyResp.methods).toEqual({
+ totp: true,
+ webauthn: false,
+ backup_codes: true,
+ email_code: false,
+ password: false,
+ });
const updated = await createBuilder<UserPrivateResponse>(harness, mfaAccount.token)
.post('/users/@me/email-change/apply')
.body({
@@ -563,52 +617,6 @@ describe('Email change flow', () => {
expect(updated.email).toBe(newEmail);
expect(updated.mfa_enabled).toBe(true);
});
- it('dedicated apply endpoint succeeds with password for non-MFA users', async () => {
- const account = await createTestAccount(harness);
- const startResp = await startEmailChange(harness, account, account.password);
- const emails = await listTestEmails(harness, {recipient: account.email});
- const originalEmail = findLastTestEmail(emails, 'email_change_original');
- const originalProof = await verifyOriginalEmailChange(
- harness,
- account,
- startResp.ticket,
- originalEmail!.metadata!.code!,
- account.password,
- );
- const newEmail = `integration-apply-nomfa-${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');
- const emailToken = await verifyNewEmailChange(
- harness,
- account,
- startResp.ticket,
- newEmailData!.metadata!.code!,
- originalProof,
- account.password,
- );
- const noSudoResp = await createBuilder<{
- code: string;
- has_mfa?: boolean;
- methods?: {
- totp?: boolean;
- webauthn?: boolean;
- backup_codes?: boolean;
- };
- }>(harness, account.token)
- .post('/users/@me/email-change/apply')
- .body({email_token: emailToken})
- .expect(403, 'SUDO_MODE_REQUIRED')
- .execute();
- expect(noSudoResp.has_mfa).toBe(false);
- expect(noSudoResp.methods).toEqual({totp: false, webauthn: false, backup_codes: false});
- const updated = await createBuilder<UserPrivateResponse>(harness, account.token)
- .post('/users/@me/email-change/apply')
- .body({email_token: emailToken, password: account.password})
- .expect(200)
- .execute();
- expect(updated.email).toBe(newEmail);
- });
it('e2e: reporter scenario — MFA user with TOTP completes "Use Different Email" recovery without sudo loop', async () => {
const account = await createTestAccount(harness);
const secret = createTotpSecret();
@@ -671,7 +679,13 @@ describe('Email change flow', () => {
.expect(403, 'SUDO_MODE_REQUIRED')
.execute();
expect(discovery.has_mfa).toBe(true);
- expect(discovery.methods).toEqual({totp: true, webauthn: false, backup_codes: true});
+ expect(discovery.methods).toEqual({
+ totp: true,
+ webauthn: false,
+ backup_codes: true,
+ email_code: false,
+ password: false,
+ });
const applied = await createBuilder<UserPrivateResponse>(harness, mfaAccount.token)
.post('/users/@me/email-change/apply')
.body({
diff --git a/fluxer_api/src/api/user/services/EmailChangeService.ts b/fluxer_api/src/api/user/services/EmailChangeService.ts
index d653931ec..e86b700ad 100644
--- a/fluxer_api/src/api/user/services/EmailChangeService.ts
+++ b/fluxer_api/src/api/user/services/EmailChangeService.ts
@@ -2,10 +2,14 @@
import {randomUUID} from 'node:crypto';
import type {ApiContext} from '@app/api/ApiContext';
+import {assertEmailSendAllowed, budgetEnvFor, recordEmailSend} from '@app/api/auth/AccountBudgets';
+import {normalizeEmailKey} from '@app/api/auth/AccountCodes';
import * as AuthPassword from '@app/api/auth/AuthPassword';
+import {assertInstanceAcceptsEmailDomain} from '@app/api/auth/AuthRegistration';
import {assertEmailNotBlocklisted} from '@app/api/auth/EmailBlocklist';
import type {User} from '@app/api/models/User';
import {enqueueStripeCustomerEmailSync} from '@app/api/stripe/StripeCustomer';
+import {getAccountTier} from '@app/api/user/AccountTier';
import type {EmailChangeRepository} from '@app/api/user/repositories/auth/EmailChangeRepository';
import {
assertChangeCooldown,
@@ -13,6 +17,7 @@ import {
generateChangeVerificationCode,
getActiveChangeTicketForUser,
} from '@app/api/user/services/UserChangeChallengeUtils';
+import {AccountTiers} from '@fluxer/constants/src/AccountTierConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {AccessDeniedError} from '@fluxer/errors/src/domains/core/AccessDeniedError';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
@@ -51,7 +56,7 @@ export class EmailChangeService {
async start(user: User): Promise<StartEmailChangeResult> {
const {email, rateLimit} = this.apiContext.services;
- const isUnclaimed = user.isUnclaimedAccount();
+ const isUnclaimed = getAccountTier(user) === AccountTiers.UNCLAIMED;
const hasEmail = !!user.email;
if (!hasEmail && !isUnclaimed) {
throw InputValidationError.fromCode('email', ValidationErrorCodes.MUST_HAVE_EMAIL_TO_CHANGE_IT);
@@ -71,7 +76,7 @@ export class EmailChangeService {
originalCode = generateChangeVerificationCode();
originalCodeExpiresAt = new Date(now.getTime() + this.ORIGINAL_CODE_TTL_MS);
originalCodeSentAt = now;
- await email.sendEmailChangeOriginal(user.email!, user.username, originalCode, user.locale);
+ await email.send('email_change_original', user.email, {code: originalCode}, user.locale);
}
const originalProof = requireOriginal ? null : randomUUID();
await this.repo.createTicket({
@@ -120,7 +125,7 @@ export class EmailChangeService {
const now = new Date();
const originalCode = generateChangeVerificationCode();
const originalCodeExpiresAt = new Date(now.getTime() + this.ORIGINAL_CODE_TTL_MS);
- await email.sendEmailChangeOriginal(row.original_email, user.username, originalCode, user.locale);
+ await email.send('email_change_original', row.original_email, {code: originalCode}, user.locale);
row.original_code = originalCode;
row.original_code_sent_at = now;
row.original_code_expires_at = originalCodeExpiresAt;
@@ -160,9 +165,10 @@ export class EmailChangeService {
ticket: string,
newEmail: string,
originalProof: string,
+ clientIp: string,
newPassword?: string,
): Promise<RequestNewEmailResult> {
- const {email, emailDnsValidation, users, rateLimit} = this.apiContext.services;
+ const {emailDnsValidation, users, rateLimit} = this.apiContext.services;
const row = await getActiveChangeTicketForUser(this.repo, ticket, user.id);
if (!row.original_verified || !row.original_proof) {
throw InputValidationError.fromCode('ticket', ValidationErrorCodes.ORIGINAL_EMAIL_MUST_BE_VERIFIED_FIRST);
@@ -178,6 +184,7 @@ export class EmailChangeService {
throw InputValidationError.fromCode('new_email', ValidationErrorCodes.NEW_EMAIL_MUST_BE_DIFFERENT);
}
await assertEmailNotBlocklisted(trimmedEmail, 'new_email');
+ await assertInstanceAcceptsEmailDomain(trimmedEmail, 'new_email');
const hasValidDns = await emailDnsValidation.hasValidDnsRecords(trimmedEmail);
if (!hasValidDns) {
throw InputValidationError.fromCode('new_email', ValidationErrorCodes.EMAIL_DOMAIN_CANNOT_RECEIVE_MAIL);
@@ -198,7 +205,7 @@ export class EmailChangeService {
const now = new Date();
const newCode = generateChangeVerificationCode();
const newCodeExpiresAt = new Date(now.getTime() + this.NEW_CODE_TTL_MS);
- await email.sendEmailChangeNew(trimmedEmail, user.username, newCode, user.locale);
+ await this.sendNewEmailCode(user, trimmedEmail, newCode, clientIp);
row.new_email = trimmedEmail;
row.new_code = newCode;
row.new_code_sent_at = now;
@@ -214,8 +221,8 @@ export class EmailChangeService {
};
}
- async resendNew(user: User, ticket: string): Promise<void> {
- const {email, rateLimit} = this.apiContext.services;
+ async resendNew(user: User, ticket: string, clientIp: string): Promise<void> {
+ const {rateLimit} = this.apiContext.services;
const row = await getActiveChangeTicketForUser(this.repo, ticket, user.id);
if (!row.new_email) {
throw InputValidationError.fromCode('ticket', ValidationErrorCodes.NO_NEW_EMAIL_REQUESTED);
@@ -229,7 +236,7 @@ export class EmailChangeService {
const now = new Date();
const newCode = generateChangeVerificationCode();
const newCodeExpiresAt = new Date(now.getTime() + this.NEW_CODE_TTL_MS);
- await email.sendEmailChangeNew(row.new_email, user.username, newCode, user.locale);
+ await this.sendNewEmailCode(user, row.new_email, newCode, clientIp);
row.new_code = newCode;
row.new_code_sent_at = now;
row.new_code_expires_at = newCodeExpiresAt;
@@ -237,6 +244,19 @@ export class EmailChangeService {
await this.repo.updateTicket(row);
}
+ private async sendNewEmailCode(user: User, newEmail: string, code: string, clientIp: string): Promise<void> {
+ const {email} = this.apiContext.services;
+ const budget = budgetEnvFor(this.apiContext.services, null);
+ const emailKey = normalizeEmailKey(newEmail);
+ await assertEmailSendAllowed(budget, {
+ emailKey,
+ requester: 'unknown',
+ clientIp,
+ });
+ await email.send('email_change_new', newEmail, {code}, user.locale);
+ await recordEmailSend(budget, {emailKey, requester: 'unknown'});
+ }
+
async verifyNew(user: User, ticket: string, code: string, originalProof: string): Promise<string> {
const row = await getActiveChangeTicketForUser(this.repo, ticket, user.id);
if (!row.original_verified || !row.original_proof) {
@@ -286,18 +306,18 @@ export class EmailChangeService {
await this.repo.deleteToken(token);
}
- async requestBouncedNewEmail(user: User, newEmail: string): Promise<RequestNewEmailResult> {
+ async requestBouncedNewEmail(user: User, newEmail: string, clientIp: string): Promise<RequestNewEmailResult> {
this.ensureBouncedEmailRecoveryAllowed(user);
const startResult = await this.start(user);
if (startResult.require_original || !startResult.original_proof) {
throw InputValidationError.fromCode('ticket', ValidationErrorCodes.ORIGINAL_EMAIL_MUST_BE_VERIFIED_FIRST);
}
- return await this.requestNewEmail(user, startResult.ticket, newEmail, startResult.original_proof);
+ return await this.requestNewEmail(user, startResult.ticket, newEmail, startResult.original_proof, clientIp);
}
- async resendBouncedNew(user: User, ticket: string): Promise<void> {
+ async resendBouncedNew(user: User, ticket: string, clientIp: string): Promise<void> {
this.ensureBouncedEmailRecoveryAllowed(user);
- await this.resendNew(user, ticket);
+ await this.resendNew(user, ticket, clientIp);
}
async verifyBouncedNew(user: User, ticket: string, code: string): Promise<User> {