snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
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 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,94 @@
import { Box, Accordion, AccordionItem, ButtonGroup, Button, Callout } from '@rocket.chat/fuselage';
import { Page, PageHeader, PageScrollableContentWithShadow, PageFooter } from '@rocket.chat/ui-client';
import { useSetting, useTranslation, useUser } from '@rocket.chat/ui-contexts';
import { useId } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import ChangePassword from './ChangePassword';
import EndToEnd from './EndToEnd';
import TwoFactorEmail from './TwoFactorEmail';
import TwoFactorTOTP from './TwoFactorTOTP';
import { useRequire2faSetup } from '../../hooks/useRequire2faSetup';
const passwordDefaultValues = { password: '', confirmationPassword: '' };
const AccountSecurityPage = () => {
const t = useTranslation();
const user = useUser();
const isEmail2FAAvailableForOAuth = useSetting('Accounts_twoFactorAuthentication_email_available_for_OAuth_users');
const isOAuthUser = user?.isOAuthUser;
const isEmail2FAAllowed = !isOAuthUser || isEmail2FAAvailableForOAuth;
const methods = useForm({
defaultValues: passwordDefaultValues,
mode: 'all',
});
const {
reset,
formState: { isDirty },
} = methods;
const twoFactorEnabled = useSetting('Accounts_TwoFactorAuthentication_Enabled');
const twoFactorTOTP = useSetting('Accounts_TwoFactorAuthentication_By_TOTP_Enabled');
const twoFactorByEmailEnabled = useSetting('Accounts_TwoFactorAuthentication_By_Email_Enabled');
const e2eEnabled = useSetting('E2E_Enable');
const allowPasswordChange = useSetting('Accounts_AllowPasswordChange');
const showEmailTwoFactor = twoFactorByEmailEnabled && isEmail2FAAllowed;
const passwordFormId = useId();
const require2faSetup = useRequire2faSetup();
return (
<Page>
<PageHeader title={t('Security')} />
<PageScrollableContentWithShadow>
<Box maxWidth='x600' width='full' alignSelf='center' color='default'>
{allowPasswordChange && (
<FormProvider {...methods}>
<Accordion>
<AccordionItem title={t('Password')} defaultExpanded={!require2faSetup}>
<ChangePassword id={passwordFormId} />
</AccordionItem>
</Accordion>
</FormProvider>
)}
<Accordion>
{(twoFactorTOTP || showEmailTwoFactor) && twoFactorEnabled && (
<AccordionItem defaultExpanded={require2faSetup} title={t('Two Factor Authentication')}>
{require2faSetup && (
<Callout type='warning' title={t('Enable_two-factor_authentication')} marginBlockEnd='24px'>
{t('Enable_two-factor_authentication_callout_description')}
</Callout>
)}
{twoFactorTOTP && <TwoFactorTOTP />}
{showEmailTwoFactor && <TwoFactorEmail />}
</AccordionItem>
)}
{e2eEnabled && (
<AccordionItem
title={t('End-to-end_encryption')}
aria-label={t('End-to-end_encryption')}
defaultExpanded={!twoFactorEnabled}
data-qa-type='e2e-encryption-section'
>
<EndToEnd />
</AccordionItem>
)}
</Accordion>
</Box>
</PageScrollableContentWithShadow>
<PageFooter isDirty={isDirty}>
<ButtonGroup>
<Button onClick={() => reset(passwordDefaultValues)}>{t('Cancel')}</Button>
<Button form={passwordFormId} primary disabled={!isDirty} type='submit'>
{t('Save_changes')}
</Button>
</ButtonGroup>
</PageFooter>
</Page>
);
};
export default AccountSecurityPage;

View File

@@ -0,0 +1,20 @@
import { useSetting } from '@rocket.chat/ui-contexts';
import AccountSecurityPage from './AccountSecurityPage';
import NotAuthorizedPage from '../../notAuthorized/NotAuthorizedPage';
const AccountSecurityRoute = () => {
const isTwoFactorEnabled = useSetting('Accounts_TwoFactorAuthentication_Enabled');
const isE2EEnabled = useSetting('E2E_Enable');
const allowPasswordChange = useSetting('Accounts_AllowPasswordChange');
const canViewSecurity = isTwoFactorEnabled || isE2EEnabled || allowPasswordChange;
if (!canViewSecurity) {
return <NotAuthorizedPage />;
}
return <AccountSecurityPage />;
};
export default AccountSecurityRoute;

View File

@@ -0,0 +1,33 @@
import { Box, CodeSnippet } from '@rocket.chat/fuselage';
import { useClipboard } from '@rocket.chat/fuselage-hooks';
import { GenericModal } from '@rocket.chat/ui-client';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
export type BackupCodesModalProps = {
codes: string[];
onClose: () => void;
};
const BackupCodesModal = ({ codes, onClose }: BackupCodesModalProps) => {
const { t } = useTranslation();
const codesText = useMemo(() => codes.join(' '), [codes]);
const { copy, hasCopied } = useClipboard(codesText);
return (
<GenericModal title={t('Backup_codes')} onCancel={onClose} cancelText={t('Close')}>
<Box marginBlock={8} withRichContent>
{t('Make_sure_you_have_a_copy_of_your_codes_1')}
</Box>
<CodeSnippet buttonText={hasCopied ? t('Copied') : t('Copy')} buttonDisabled={hasCopied} onClick={() => copy()} marginBlockStart={8}>
{codesText}
</CodeSnippet>
<Box marginBlock={8} withRichContent>
{t('Make_sure_you_have_a_copy_of_your_codes_2')}
</Box>
</GenericModal>
);
};
export default BackupCodesModal;

View File

@@ -0,0 +1,201 @@
import { Box, Field, FieldError, FieldGroup, FieldHint, FieldLabel, FieldRow, PasswordInput, Button } from '@rocket.chat/fuselage';
import { PasswordVerifierList } from '@rocket.chat/ui-client';
import { useToastMessageDispatch, usePasswordPolicy } from '@rocket.chat/ui-contexts';
import { useMutation } from '@tanstack/react-query';
import { useEffect, useId } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { Trans, useTranslation } from 'react-i18next';
import { e2e } from '../../../lib/e2ee/rocketchat.e2e';
import { useE2EEState } from '../../room/hooks/useE2EEState';
const PASSPHRASE_POLICY = Object.freeze({
enabled: true,
minLength: 30,
mustContainAtLeastOneLowercase: true,
mustContainAtLeastOneUppercase: true,
mustContainAtLeastOneNumber: true,
mustContainAtLeastOneSpecialCharacter: true,
forbidRepeatingCharacters: false,
});
const useKeysExist = () => {
const state = useE2EEState();
return state === 'READY' || state === 'SAVE_PASSWORD';
};
const useValidatePassphrase = (passphrase: string) => {
const validate = usePasswordPolicy(PASSPHRASE_POLICY);
return validate(passphrase);
};
const useChangeE2EPasswordMutation = () => {
return useMutation({
mutationFn: async (newPassword: string) => {
await e2e.changePassword(newPassword);
},
});
};
const defaultValues = {
passphrase: '',
confirmationPassphrase: '',
};
export const ChangePassphrase = () => {
const { t } = useTranslation();
const dispatchToastMessage = useToastMessageDispatch();
const uniqueId = useId();
const passphraseId = `passphrase-${uniqueId}`;
const passphraseHintId = `${passphraseId}-hint`;
const passphraseErrorId = `${passphraseId}-error`;
const confirmPassphraseId = `confirm-passphrase-${uniqueId}`;
const confirmPassphraseErrorId = `${confirmPassphraseId}-error`;
const passphraseVerifierId = `verifier-${uniqueId}`;
const e2ePasswordExplanationId = `explanation-${uniqueId}`;
const {
watch,
formState: { errors, isValid },
handleSubmit,
reset,
resetField,
control,
trigger,
} = useForm({
defaultValues,
mode: 'all',
});
const { passphrase, confirmationPassphrase } = watch();
const { validations, valid } = useValidatePassphrase(passphrase);
useEffect(() => {
if (!valid) {
resetField('confirmationPassphrase');
return;
}
if (confirmationPassphrase) {
const validateConfirmation = async () => {
await trigger('confirmationPassphrase');
};
void validateConfirmation();
}
}, [valid, confirmationPassphrase, resetField, trigger]);
const keysExist = useKeysExist();
const updatePassword = useChangeE2EPasswordMutation();
const handleSave = async ({ passphrase }: { passphrase: string }) => {
try {
await updatePassword.mutateAsync(passphrase);
dispatchToastMessage({ type: 'success', message: t('Encryption_key_saved_successfully') });
reset();
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
};
return (
<>
<Box is='p' fontScale='p1' id={e2ePasswordExplanationId}>
<Trans i18nKey='E2E_Encryption_Password_Explanation' />
</Box>
<Box marginBlockStart={36} width='full'>
<Box is='h3' fontScale='h4' marginBlockEnd={12}>
{t('Change_E2EE_password')}
</Box>
<FieldGroup width='full'>
<Field>
<FieldLabel htmlFor={passphraseId}>{t('New_E2EE_password')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='passphrase'
rules={{
required: t('Required_field', { field: t('New_E2EE_password') }),
validate: () => (valid ? true : t('Password_must_meet_the_complexity_requirements')),
}}
render={({ field }) => (
<PasswordInput
{...field}
id={passphraseId}
error={errors.passphrase?.message}
disabled={!keysExist}
aria-describedby={[
e2ePasswordExplanationId,
keysExist ? passphraseVerifierId : passphraseHintId,
errors.passphrase && passphraseErrorId,
]
.filter(Boolean)
.join(' ')}
aria-invalid={errors.passphrase ? 'true' : 'false'}
/>
)}
/>
</FieldRow>
{errors.passphrase && (
<FieldError aria-live='assertive' id={passphraseErrorId}>
{errors.passphrase.message}
</FieldError>
)}
{keysExist ? (
<PasswordVerifierList id={passphraseVerifierId} validations={validations} />
) : (
<FieldHint id={passphraseHintId}>
<Trans i18nKey='Enter_current_E2EE_password_to_set_new'>
To set a new password, first
<Box
is='a'
href='#'
onClick={async (e) => {
e.preventDefault();
await e2e.decodePrivateKeyFlow();
}}
>
enter your current E2EE password.
</Box>
</Trans>
</FieldHint>
)}
</Field>
{valid && (
<Field>
<FieldLabel htmlFor={confirmPassphraseId}>{t('Confirm_new_E2EE_password')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='confirmationPassphrase'
rules={{
required: t('Required_field', { field: t('Confirm_password') }),
validate: (value) => (passphrase !== value ? t('Passwords_do_not_match') : true),
}}
render={({ field }) => (
<PasswordInput
{...field}
id={confirmPassphraseId}
error={errors.confirmationPassphrase?.message}
flexGrow={1}
disabled={!keysExist || !valid}
aria-required={passphrase ? 'true' : 'false'}
aria-invalid={errors.confirmationPassphrase ? 'true' : 'false'}
aria-describedby={errors.confirmationPassphrase ? confirmPassphraseErrorId : undefined}
/>
)}
/>
</FieldRow>
{errors.confirmationPassphrase && (
<FieldError aria-live='assertive' id={confirmPassphraseErrorId} role='alert'>
{errors.confirmationPassphrase.message}
</FieldError>
)}
</Field>
)}
</FieldGroup>
<Button primary disabled={!(keysExist && valid && isValid)} onClick={handleSubmit(handleSave)} marginBlockStart={12}>
{t('Save_changes')}
</Button>
</Box>
</>
);
};

View File

@@ -0,0 +1,133 @@
import { Box, Field, FieldError, FieldGroup, FieldHint, FieldLabel, FieldRow, PasswordInput } from '@rocket.chat/fuselage';
import { PasswordVerifier, useValidatePassword } from '@rocket.chat/ui-client';
import { useEndpoint, useToastMessageDispatch } from '@rocket.chat/ui-contexts';
import type { AllHTMLAttributes } from 'react';
import { useId } from 'react';
import { Controller, useFormContext } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useAllowPasswordChange } from './useAllowPasswordChange';
type PasswordFieldValues = { password: string; confirmationPassword: string };
function getAriaDescribedbyForPassword(
passwordVerifierId: string,
passwordId: string,
allowPasswordChange: boolean,
passwordError: boolean,
) {
const error = !allowPasswordChange || passwordError;
return [passwordVerifierId, !allowPasswordChange && `${passwordId}-hint`, error && `${passwordId}-error`].filter(Boolean).join(' ');
}
const ChangePassword = (props: AllHTMLAttributes<HTMLFormElement>) => {
const { t } = useTranslation();
const dispatchToastMessage = useToastMessageDispatch();
const passwordId = useId();
const confirmPasswordId = useId();
const passwordVerifierId = useId();
const {
watch,
formState: { errors },
handleSubmit,
reset,
control,
} = useFormContext<PasswordFieldValues>();
const password = watch('password');
const passwordIsValid = useValidatePassword(password);
const { allowPasswordChange } = useAllowPasswordChange();
const updatePassword = useEndpoint('POST', '/v1/users.updateOwnBasicInfo');
const handleSave = async ({ password }: { password?: string }) => {
try {
await updatePassword({
data: {
newPassword: password,
},
});
dispatchToastMessage({ type: 'success', message: t('Password_changed_successfully') });
reset();
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
};
return (
<Box {...props} is='form' autoComplete='off' onSubmit={handleSubmit(handleSave)}>
<FieldGroup>
<Field>
<FieldLabel htmlFor={passwordId}>{t('New_password')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='password'
rules={{
required: t('Required_field', { field: t('New_password') }),
validate: () => (password?.length && !passwordIsValid ? t('Password_must_meet_the_complexity_requirements') : true),
}}
render={({ field }) => (
<PasswordInput
{...field}
id={passwordId}
error={errors.password?.message}
flexGrow={1}
disabled={!allowPasswordChange}
aria-describedby={getAriaDescribedbyForPassword(
passwordVerifierId,
passwordId,
!!allowPasswordChange,
!!errors?.password,
)}
aria-invalid={errors.password ? 'true' : 'false'}
/>
)}
/>
</FieldRow>
{!allowPasswordChange && <FieldHint id={`${passwordId}-hint`}>{t('Password_Change_Disabled')}</FieldHint>}
{errors?.password && (
<FieldError aria-live='assertive' id={`${passwordId}-error`}>
{errors.password.message}
</FieldError>
)}
{allowPasswordChange && <PasswordVerifier password={password} id={passwordVerifierId} />}
</Field>
<Field>
<FieldLabel htmlFor={confirmPasswordId}>{t('Confirm_password')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='confirmationPassword'
rules={{
required: t('Required_field', { field: t('Confirm_password') }),
validate: (confirmationPassword) => (password !== confirmationPassword ? t('Passwords_do_not_match') : true),
}}
render={({ field }) => (
<PasswordInput
{...field}
id={confirmPasswordId}
error={errors.confirmationPassword?.message}
flexGrow={1}
disabled={!allowPasswordChange || !passwordIsValid}
aria-required={password !== '' ? 'true' : 'false'}
aria-invalid={errors.confirmationPassword ? 'true' : 'false'}
aria-describedby={errors.confirmationPassword ? `${confirmPasswordId}-error` : undefined}
/>
)}
/>
</FieldRow>
{errors.confirmationPassword && (
<FieldError aria-live='assertive' id={`${confirmPasswordId}-error`}>
{errors.confirmationPassword.message}
</FieldError>
)}
</Field>
</FieldGroup>
</Box>
);
};
export default ChangePassword;

View File

@@ -0,0 +1,16 @@
import { Box, Divider } from '@rocket.chat/fuselage';
import { ChangePassphrase } from './ChangePassphrase';
import { ResetPassphrase } from './ResetPassphrase';
const EndToEnd = () => {
return (
<Box display='flex' flexDirection='column' alignItems='flex-start'>
<ChangePassphrase />
<Divider marginBlock={36} width='full' />
<ResetPassphrase />
</Box>
);
};
export default EndToEnd;

View File

@@ -0,0 +1,20 @@
import { Box, Button } from '@rocket.chat/fuselage';
import { useTranslation } from 'react-i18next';
import { useResetE2EPasswordMutation } from '../../hooks/useResetE2EPasswordMutation';
export const ResetPassphrase = () => {
const { t } = useTranslation();
const resetE2EPassword = useResetE2EPasswordMutation();
return (
<>
<Box is='h4' fontScale='h4' marginBlockEnd={12}>
{t('Reset_E2EE_password')}
</Box>
<Box is='p' fontScale='p1' marginBlockEnd={12}>
{t('Reset_E2EE_password_description')}
</Box>
<Button onClick={() => resetE2EPassword.mutate()}>{t('Reset_E2EE_password')}</Button>
</>
);
};

View File

@@ -0,0 +1,54 @@
import { Box, Field, FieldLabel, FieldRow, Margins, ToggleSwitch } from '@rocket.chat/fuselage';
import { useToastMessageDispatch, useUser } from '@rocket.chat/ui-contexts';
import type { ComponentProps, ChangeEvent } from 'react';
import { useCallback, useId } from 'react';
import { useTranslation } from 'react-i18next';
import { useEndpointMutation } from '../../../hooks/useEndpointMutation';
const TwoFactorEmail = (props: ComponentProps<typeof Box>) => {
const { t } = useTranslation();
const user = useUser();
const emailId = useId();
const isEnabled = user?.services?.email2fa?.enabled;
const dispatchToastMessage = useToastMessageDispatch();
const { mutateAsync: enable2faAction } = useEndpointMutation('POST', '/v1/users.2fa.enableEmail', {
onSuccess: () => {
dispatchToastMessage({ type: 'success', message: t('Two-factor_authentication_enabled') });
},
});
const { mutateAsync: disable2faAction } = useEndpointMutation('POST', '/v1/users.2fa.disableEmail', {
onSuccess: () => {
dispatchToastMessage({ type: 'success', message: t('Two-factor_authentication_disabled') });
},
});
const handleEnable = useCallback(
async (e: ChangeEvent<HTMLInputElement>) => {
if (e.currentTarget.checked) {
await enable2faAction();
} else {
await disable2faAction();
}
},
[disable2faAction, enable2faAction],
);
return (
<Box display='flex' flexDirection='column' alignItems='flex-start' marginBlockStart={16} {...props}>
<Margins blockEnd={8}>
<Field>
<FieldRow>
<FieldLabel htmlFor={emailId}>{t('Two-factor_authentication_email')}</FieldLabel>
<ToggleSwitch id={emailId} checked={isEnabled} onChange={handleEnable} />
</FieldRow>
</Field>
</Margins>
</Box>
);
};
export default TwoFactorEmail;

View File

@@ -0,0 +1,187 @@
import { Box, Button, TextInput, Margins, Field, FieldRow, FieldLabel, ToggleSwitch } from '@rocket.chat/fuselage';
import { useStableCallback, useSafely } from '@rocket.chat/fuselage-hooks';
import { useSetModal, useToastMessageDispatch, useUser, useEndpoint } from '@rocket.chat/ui-contexts';
import type { ComponentPropsWithoutRef, ChangeEvent } from 'react';
import { useState, useCallback, useEffect, useId } from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import qrcode from 'yaqrcode';
import BackupCodesModal from './BackupCodesModal';
import TextCopy from '../../../components/TextCopy';
import TwoFactorTotpModal from '../../../components/TwoFactorModal/TwoFactorTotpModal';
type TwoFactorTOTPFormData = {
authCode: string;
};
export type TwoFactorTOTPProps = ComponentPropsWithoutRef<typeof Box>;
const isInvalidTotpError = (error: unknown): boolean => {
const { error: errorCode, errorType } = (error ?? {}) as { error?: string; errorType?: string };
return errorCode === 'invalid-totp' || errorType === 'invalid-totp';
};
const TwoFactorTOTP = (props: TwoFactorTOTPProps) => {
const { t } = useTranslation();
const dispatchToastMessage = useToastMessageDispatch();
const user = useUser();
const setModal = useSetModal();
const enableTotpFn = useEndpoint('POST', '/v1/users.enableTotp');
const disableTotpFn = useEndpoint('POST', '/v1/users.disableTotp');
const verifyCodeFn = useEndpoint('POST', '/v1/users.validateTotp');
const checkCodesRemainingFn = useEndpoint('GET', '/v1/users.totpCodesRemaining');
const regenerateCodesFn = useEndpoint('POST', '/v1/users.regenerateTotpCodes');
const [registeringTotp, setRegisteringTotp] = useSafely(useState(false));
const [qrCode, setQrCode] = useSafely(useState<string>());
const [totpSecret, setTotpSecret] = useSafely(useState<string>());
const [codesRemaining, setCodesRemaining] = useSafely(useState(0));
const { register, handleSubmit } = useForm<TwoFactorTOTPFormData>({ defaultValues: { authCode: '' } });
const totpEnabled = user?.services?.totp?.enabled;
const closeModal = useCallback(() => setModal(null), [setModal]);
useEffect(() => {
const updateCodesRemaining = async (): Promise<void | boolean> => {
if (!totpEnabled) {
return false;
}
const result = await checkCodesRemainingFn();
setCodesRemaining(result.remaining);
};
updateCodesRemaining();
}, [checkCodesRemainingFn, setCodesRemaining, totpEnabled]);
const enableTotp = useStableCallback(async () => {
try {
const result = await enableTotpFn();
setTotpSecret(result.secret);
setQrCode(qrcode(result.url, { size: 200 }));
setRegisteringTotp(true);
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
});
const disableTotp = useStableCallback(async () => {
if (!totpEnabled) {
setRegisteringTotp(false);
return;
}
const onDisable = async (authCode: string): Promise<void> => {
try {
const { disabled } = await disableTotpFn({ code: authCode });
if (!disabled) {
dispatchToastMessage({ type: 'error', message: t('Invalid_two_factor_code') });
return;
}
dispatchToastMessage({ type: 'success', message: t('Two-factor_authentication_disabled') });
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
closeModal();
};
setModal(<TwoFactorTotpModal onConfirm={onDisable} onClose={closeModal} />);
});
const handleToggleTotp = useStableCallback(async (e: ChangeEvent<HTMLInputElement>) => {
if (e.currentTarget?.checked) {
void enableTotp();
} else {
void disableTotp();
}
});
const totpId = useId();
const totpCodeId = useId();
const handleVerifyCode = useCallback(
async ({ authCode }: TwoFactorTOTPFormData) => {
try {
const result = await verifyCodeFn({ code: authCode });
setRegisteringTotp(false);
setModal(<BackupCodesModal codes={result.codes} onClose={closeModal} />);
dispatchToastMessage({ type: 'success', message: t('Two-factor_authentication_enabled') });
} catch (error) {
if (isInvalidTotpError(error)) {
return dispatchToastMessage({ type: 'error', message: t('Invalid_two_factor_code') });
}
dispatchToastMessage({ type: 'error', message: error });
}
},
[closeModal, dispatchToastMessage, setModal, t, verifyCodeFn, setRegisteringTotp],
);
const handleRegenerateCodes = useCallback(() => {
const onRegenerate = async (authCode: string): Promise<void> => {
try {
const { codes } = await regenerateCodesFn({ code: authCode });
setModal(<BackupCodesModal codes={codes} onClose={closeModal} />);
} catch (error) {
if (isInvalidTotpError(error)) {
return dispatchToastMessage({ type: 'error', message: t('Invalid_two_factor_code') });
}
dispatchToastMessage({ type: 'error', message: error });
}
};
setModal(<TwoFactorTotpModal onDismiss={() => undefined} onConfirm={onRegenerate} onClose={closeModal} />);
}, [closeModal, dispatchToastMessage, setModal, regenerateCodesFn, t]);
return (
<Box display='flex' flexDirection='column' alignItems='flex-start' {...props}>
<Margins blockEnd={8}>
<Field>
<FieldRow>
<FieldLabel htmlFor={totpId}>{t('Two-factor_authentication_via_TOTP')}</FieldLabel>
<ToggleSwitch id={totpId} checked={registeringTotp || totpEnabled} onChange={handleToggleTotp} />
</FieldRow>
</Field>
{!totpEnabled && registeringTotp && (
<>
<Box>{t('Scan_QR_code')}</Box>
<Box>{t('Scan_QR_code_alternative_s')}</Box>
<TextCopy text={totpSecret || ''} />
<Box marginInlineStart='-16px' marginBlock='-16px' is='img' size='x200' src={qrCode} aria-hidden='true' />
<Field>
<FieldLabel htmlFor={totpCodeId}>{t('Enter_code_provided_by_authentication_app')}</FieldLabel>
<FieldRow>
<TextInput id={totpCodeId} marginInlineEnd='8px' {...register('authCode')} />
<Button primary onClick={handleSubmit(handleVerifyCode)}>
{t('Verify')}
</Button>
</FieldRow>
</Field>
</>
)}
{totpEnabled && (
<>
<Box fontScale='p2m' marginBlockStart={8}>
{t('Backup_codes')}
</Box>
<Box color='font-secondary-info'>{t('You_have_n_codes_remaining', { number: codesRemaining })}</Box>
<Button onClick={handleRegenerateCodes}>{t('Regenerate_codes')}</Button>
</>
)}
</Margins>
</Box>
);
};
export default TwoFactorTOTP;

View File

@@ -0,0 +1,16 @@
import { useSetting, useUser } from '@rocket.chat/ui-contexts';
export const useAllowPasswordChange = () => {
const user = useUser();
let allowPasswordChange = useSetting('Accounts_AllowPasswordChange');
const allowOAuthPasswordChange = useSetting('Accounts_AllowPasswordChangeForOAuthUsers');
const hasLocalPassword = Boolean(user?.services?.password?.exists);
if (allowPasswordChange && !allowOAuthPasswordChange) {
allowPasswordChange = hasLocalPassword;
}
return { allowPasswordChange, hasLocalPassword };
};