Files
upstream-mirror 30810eecd7
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 2s
snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
2026-09-16 01:21:02 +05:00

151 lines
4.3 KiB
TypeScript

import { isOAuthUser } from '@rocket.chat/core-typings';
import { Users } from '@rocket.chat/models';
import { Random } from '@rocket.chat/random';
import bcrypt from 'bcrypt';
import { Accounts } from 'meteor/accounts-base';
import type { ICodeCheck, IProcessInvalidCodeResult, TwoFactorUser } from './ICodeCheck';
import { settings } from '../../../settings';
import { i18n } from '../../i18n';
import * as Mailer from '../../notifications/email/api';
export class EmailCheck implements ICodeCheck {
public readonly name: string = 'email';
private getUserVerifiedEmails(user: TwoFactorUser): string[] {
if (!Array.isArray(user.emails)) {
return [];
}
return user.emails.filter(({ verified }) => verified).map((e) => e.address);
}
public isEnabled(user: TwoFactorUser): boolean {
if (!settings.get('Accounts_TwoFactorAuthentication_By_Email_Enabled')) {
return false;
}
if (!settings.get('Accounts_twoFactorAuthentication_email_available_for_OAuth_users') && isOAuthUser(user)) {
return false;
}
if (!user.services?.email2fa?.enabled) {
return false;
}
return this.getUserVerifiedEmails(user).length > 0;
}
private async send2FAEmail(address: string, random: string, user: TwoFactorUser): Promise<void> {
const language = user.language || settings.get('Language') || 'en';
const t = i18n.getFixedT(language);
await Mailer.send({
to: address,
from: settings.get('From_Email'),
subject: 'Authentication code',
replyTo: undefined,
data: {
code: random.replace(/^(\d{3})/, '$1-'),
},
headers: undefined,
text: `
${t('Here_is_your_authentication_code')}
__code__
${t('Do_not_provide_this_code_to_anyone')}
${t('If_you_didnt_try_to_login_in_your_account_please_ignore_this_email')}
`,
html: `
<p>${t('Here_is_your_authentication_code')}</p>
<p style="font-size: 30px;">
<b>__code__</b>
</p>
<p>${t('Do_not_provide_this_code_to_anyone')}</p>
<p>${t('If_you_didnt_try_to_login_in_your_account_please_ignore_this_email')}</p>
`,
});
}
public async verify(user: TwoFactorUser, codeFromEmail: string): Promise<boolean> {
if (!this.isEnabled(user)) {
return false;
}
if (!user.services?.emailCode) {
return false;
}
// Remove non digits
codeFromEmail = codeFromEmail.replace(/([^\d])/g, '');
const { code, expire } = user.services.emailCode;
if (expire < new Date()) {
return false;
}
if (await bcrypt.compare(codeFromEmail, code)) {
await Users.removeEmailCodeOfUserId(user._id);
return true;
}
await Users.incrementInvalidEmailCodeAttempt(user._id);
return false;
}
public async sendEmailCode(user: TwoFactorUser): Promise<void> {
const emails = this.getUserVerifiedEmails(user);
const random = Random._randomString(6, '0123456789');
const encryptedRandom = await bcrypt.hash(random, Accounts._bcryptRounds());
const expire = new Date();
const expirationInSeconds = parseInt(settings.get('Accounts_TwoFactorAuthentication_By_Email_Code_Expiration'), 10);
expire.setSeconds(expire.getSeconds() + expirationInSeconds);
await Users.addEmailCodeByUserId(user._id, encryptedRandom, expire);
for (const address of emails) {
await this.send2FAEmail(address, random, user);
}
}
public async processInvalidCode(user: TwoFactorUser): Promise<IProcessInvalidCodeResult> {
await Users.removeExpiredEmailCodeOfUserId(user._id);
// Generate new code if the there isn't any code with more than 5 minutes to expire
const expireWithDelta = new Date();
expireWithDelta.setMinutes(expireWithDelta.getMinutes() - 5);
const emails = this.getUserVerifiedEmails(user);
const emailOrUsername = user.username || emails[0];
const hasValidCode =
user.services?.emailCode?.expire &&
user.services?.emailCode?.expire > expireWithDelta &&
!(await this.maxFaildedAttemtpsReached(user));
if (hasValidCode) {
return {
emailOrUsername,
codeGenerated: false,
codeExpires: user.services?.emailCode?.expire,
};
}
await this.sendEmailCode(user);
return {
codeGenerated: true,
emailOrUsername,
};
}
public async maxFaildedAttemtpsReached(user: TwoFactorUser) {
const maxAttempts = settings.get<number>('Accounts_TwoFactorAuthentication_Max_Invalid_Email_Code_Attempts');
return Users.maxInvalidEmailCodeAttemptsReached(user._id, maxAttempts);
}
}