mv element.io @types __mocks__/ debian docker module_system/ playwright res src test webapp Dockerfile .dockerignore .eslintignore .stylelintrc.cjs babel.config.cjs recorder-worklet-loader.cjs .modernizr.json components.json config.json config.sample.json package.json project.json tsconfig.json tsconfig.module_system.json jest.config.ts playwright.config.ts webpack.config.ts build_config.sample.yaml apps/web/

mkdir apps/web/scripts
mv scripts/{cleanup.sh,ci_package.sh,copy-res.ts,deploy.py,package.sh} apps/web/scripts

And a couple of gitignore tweaks

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
This commit is contained in:
Michael Telatynski
2026-02-24 15:43:58 +00:00
parent e7509c92a1
commit 91a3cb03c1
3408 changed files with 28 additions and 32 deletions
@@ -0,0 +1,206 @@
/*
Copyright 2020-2024 New Vector Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React, { type JSX, type ReactNode } from "react";
import { Text, Heading, Button, Separator } from "@vector-im/compound-web";
import PopOutIcon from "@vector-im/compound-design-tokens/assets/web/icons/pop-out";
import { Flex } from "@element-hq/web-shared-components";
import { LinuxIcon, MacIcon, WindowsIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import SdkConfig from "../../SdkConfig";
import { _t } from "../../languageHandler";
// directly import the style here as this layer does not support rethemedex at this time so no matrix-react-sdk
// PostCSS variables will be accessible.
import "../../../res/css/structures/ErrorView.pcss";
interface IProps {
// both of these should already be internationalised
title: string;
messages?: string[];
footer?: ReactNode;
children?: ReactNode;
}
export const ErrorView: React.FC<IProps> = ({ title, messages, footer, children }) => {
return (
<div className="mx_ErrorView cpd-theme-light">
<img
className="mx_ErrorView_logo"
height="160"
src="themes/element/img/logos/element-app-logo.png"
alt="Element"
/>
<div className="mx_ErrorView_container">
<Heading size="md" weight="semibold">
{title}
</Heading>
{messages?.map((message) => (
<Text key={message} size="lg">
{message}
</Text>
))}
{children}
</div>
{footer}
</div>
);
};
const MobileAppLinks: React.FC<{
appleAppStoreUrl?: string;
googlePlayUrl?: string;
fdroidUrl?: string;
}> = ({ appleAppStoreUrl, googlePlayUrl, fdroidUrl }) => (
<Flex gap="var(--cpd-space-6x)" className="mx_ErrorView_flexContainer">
{appleAppStoreUrl && (
<a href={appleAppStoreUrl} target="_blank" rel="noreferrer noopener">
<img height="64" src="themes/element/img/download/apple.svg" alt="Apple App Store" />
</a>
)}
{googlePlayUrl && (
<a href={googlePlayUrl} target="_blank" rel="noreferrer noopener" key="android">
<img height="64" src="themes/element/img/download/google.svg" alt="Google Play Store" />
</a>
)}
{fdroidUrl && (
<a href={fdroidUrl} target="_blank" rel="noreferrer noopener" key="fdroid">
<img height="64" src="themes/element/img/download/fdroid.svg" alt="F-Droid" />
</a>
)}
</Flex>
);
const DesktopAppLinks: React.FC<{
macOsUrl?: string;
win64Url?: string;
win64ArmUrl?: string;
linuxUrl?: string;
}> = ({ macOsUrl, win64Url, win64ArmUrl, linuxUrl }) => {
return (
<Flex gap="var(--cpd-space-4x)" className="mx_ErrorView_flexContainer">
{macOsUrl && (
<Button as="a" href={macOsUrl} kind="secondary" Icon={MacIcon}>
{_t("incompatible_browser|macos")}
</Button>
)}
{win64Url && (
<Button as="a" href={win64Url} kind="secondary" Icon={WindowsIcon}>
{_t("incompatible_browser|windows_64bit")}
</Button>
)}
{win64ArmUrl && (
<Button as="a" href={win64ArmUrl} kind="secondary" Icon={WindowsIcon}>
{_t("incompatible_browser|windows_arm_64bit")}
</Button>
)}
{linuxUrl && (
<Button as="a" href={linuxUrl} kind="secondary" Icon={LinuxIcon}>
{_t("incompatible_browser|linux")}
</Button>
)}
</Flex>
);
};
const linkFactory =
(link: string) =>
(text: string): JSX.Element => (
<a href={link} target="_blank" rel="noreferrer noopener">
{text}
</a>
);
export const UnsupportedBrowserView: React.FC<{
onAccept?(this: void): void;
}> = ({ onAccept }) => {
const config = SdkConfig.get();
const brand = config.brand ?? "Element";
const hasDesktopBuilds =
config.desktop_builds?.available &&
(config.desktop_builds?.url_macos ||
config.desktop_builds?.url_win64 ||
config.desktop_builds?.url_win64arm ||
config.desktop_builds?.url_linux);
const hasMobileBuilds = Boolean(
config.mobile_builds?.ios || config.mobile_builds?.android || config.mobile_builds?.fdroid,
);
return (
<ErrorView
title={_t("incompatible_browser|title", { brand })}
messages={[
_t("incompatible_browser|description", {
brand,
detail: onAccept
? _t("incompatible_browser|detail_can_continue")
: _t("incompatible_browser|detail_no_continue"),
}),
]}
footer={
<>
{/* We render the apps in the footer as they are wider than the 520px container */}
{(hasDesktopBuilds || hasMobileBuilds) && <Separator />}
{hasDesktopBuilds && (
<>
<Heading as="h2" size="sm" weight="semibold">
{_t("incompatible_browser|use_desktop_heading", { brand })}
</Heading>
<DesktopAppLinks
macOsUrl={config.desktop_builds?.url_macos}
win64Url={config.desktop_builds?.url_win64}
win64ArmUrl={config.desktop_builds?.url_win64arm}
linuxUrl={config.desktop_builds?.url_linux}
/>
</>
)}
{hasMobileBuilds && (
<>
<Heading as="h2" size="sm" weight="semibold">
{hasDesktopBuilds
? _t("incompatible_browser|use_mobile_heading_after_desktop")
: _t("incompatible_browser|use_mobile_heading", { brand })}
</Heading>
<MobileAppLinks
appleAppStoreUrl={config.mobile_builds?.ios ?? undefined}
googlePlayUrl={config.mobile_builds?.android ?? undefined}
fdroidUrl={config.mobile_builds?.fdroid ?? undefined}
/>
</>
)}
</>
}
>
<Text size="lg">
{_t(
"incompatible_browser|supported_browsers",
{},
{
Chrome: linkFactory("https://google.com/chrome"),
Firefox: linkFactory("https://firefox.com"),
Edge: linkFactory("https://microsoft.com/edge"),
Safari: linkFactory("https://apple.com/safari"),
},
)}
</Text>
<Flex gap="var(--cpd-space-4x)" className="mx_ErrorView_flexContainer mx_ErrorView_buttons">
<Button Icon={PopOutIcon} kind="secondary" size="sm">
{_t("incompatible_browser|learn_more")}
</Button>
{onAccept && (
<Button kind="primary" size="sm" onClick={onAccept}>
{_t("incompatible_browser|continue")}
</Button>
)}
</Flex>
</ErrorView>
);
};
@@ -0,0 +1,67 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2020 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React from "react";
import BaseDialog from "../../../../components/views/dialogs/BaseDialog";
import Spinner from "../../../../components/views/elements/Spinner";
import DialogButtons from "../../../../components/views/elements/DialogButtons";
import dis from "../../../../dispatcher/dispatcher";
import { _t } from "../../../../languageHandler";
import SettingsStore from "../../../../settings/SettingsStore";
import EventIndexPeg from "../../../../indexing/EventIndexPeg";
import { Action } from "../../../../dispatcher/actions";
import { SettingLevel } from "../../../../settings/SettingLevel";
interface IProps {
onFinished: (success?: boolean) => void;
}
interface IState {
disabling: boolean;
}
/*
* Allows the user to disable the Event Index.
*/
export default class DisableEventIndexDialog extends React.Component<IProps, IState> {
public constructor(props: IProps) {
super(props);
this.state = {
disabling: false,
};
}
private onDisable = async (): Promise<void> => {
this.setState({
disabling: true,
});
await SettingsStore.setValue("enableEventIndexing", null, SettingLevel.DEVICE, false);
await EventIndexPeg.deleteEventIndex();
this.props.onFinished(true);
dis.fire(Action.ViewUserSettings);
};
public render(): React.ReactNode {
return (
<BaseDialog onFinished={this.props.onFinished} title={_t("common|are_you_sure")}>
{_t("settings|security|message_search_disable_warning")}
{this.state.disabling ? <Spinner /> : <div />}
<DialogButtons
primaryButton={_t("action|disable")}
onPrimaryButtonClick={this.onDisable}
primaryButtonClass="danger"
cancelButtonClass="warning"
onCancel={this.props.onFinished}
disabled={this.state.disabling}
/>
</BaseDialog>
);
}
}
@@ -0,0 +1,190 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2020, 2021 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React, { type ChangeEvent } from "react";
import { type Room } from "matrix-js-sdk/src/matrix";
import { _t } from "../../../../languageHandler";
import SdkConfig from "../../../../SdkConfig";
import SettingsStore from "../../../../settings/SettingsStore";
import Modal from "../../../../Modal";
import { formatBytes, formatCountLong } from "../../../../utils/FormattingUtils";
import EventIndexPeg from "../../../../indexing/EventIndexPeg";
import { SettingLevel } from "../../../../settings/SettingLevel";
import Field from "../../../../components/views/elements/Field";
import BaseDialog from "../../../../components/views/dialogs/BaseDialog";
import DialogButtons from "../../../../components/views/elements/DialogButtons";
import { type IIndexStats } from "../../../../indexing/BaseEventIndexManager";
interface IProps {
onFinished(): void;
}
interface IState {
/** Size of the event index, in bytes. */
eventIndexSize: number;
/** Number of events currently indexed in the event index. */
eventCount: number;
/** Number of rooms currently mentioned in the event index. */
eventIndexRoomCount: number;
/** Number of rooms awaiting crawling by the EventIndex. */
crawlingRoomsCount: number;
/** Number of encrypted rooms known by the MatrixClient. */
roomCount: number;
/** Room currently being crawled by the EventIndex. */
currentRoom: string | null;
/** Time to sleep between crawlwer passes, in milliseconds. */
crawlerSleepTime: number;
}
/*
* Allows the user to introspect the event index state and disable it.
*/
export default class ManageEventIndexDialog extends React.Component<IProps, IState> {
public constructor(props: IProps) {
super(props);
this.state = {
eventIndexSize: 0,
eventCount: 0,
eventIndexRoomCount: 0,
crawlingRoomsCount: 0,
roomCount: 0,
currentRoom: null,
crawlerSleepTime: SettingsStore.getValueAt(SettingLevel.DEVICE, "crawlerSleepTime"),
};
}
public updateCurrentRoom = async (room: Room | null): Promise<void> => {
const eventIndex = EventIndexPeg.get();
if (!eventIndex) return;
let stats: IIndexStats | undefined;
try {
stats = await eventIndex.getStats();
} catch {
// This call may fail if sporadically, not a huge issue as we will
// try later again and probably succeed.
return;
}
let currentRoom: string | null = null;
if (room) currentRoom = room.name;
const roomStats = eventIndex.crawlingRooms();
const crawlingRoomsCount = roomStats.crawlingRooms.size;
const roomCount = roomStats.totalRooms.size;
this.setState({
eventIndexSize: stats?.size ?? 0,
eventCount: stats?.eventCount ?? 0,
eventIndexRoomCount: stats?.roomCount ?? 0,
crawlingRoomsCount: crawlingRoomsCount,
roomCount: roomCount,
currentRoom: currentRoom,
});
};
public componentWillUnmount(): void {
const eventIndex = EventIndexPeg.get();
if (eventIndex !== null) {
eventIndex.removeListener("changedCheckpoint", this.updateCurrentRoom);
}
}
public async componentDidMount(): Promise<void> {
const eventIndex = EventIndexPeg.get();
if (eventIndex !== null) {
eventIndex.on("changedCheckpoint", this.updateCurrentRoom);
const room = eventIndex.currentRoom();
await this.updateCurrentRoom(room);
}
}
private onDisable = async (): Promise<void> => {
const DisableEventIndexDialog = (await import("./DisableEventIndexDialog")).default;
Modal.createDialog(DisableEventIndexDialog, undefined, undefined, /* priority = */ false, /* static = */ true);
};
private onCrawlerSleepTimeChange = (e: ChangeEvent<HTMLInputElement>): void => {
this.setState({ crawlerSleepTime: parseInt(e.target.value, 10) });
SettingsStore.setValue("crawlerSleepTime", null, SettingLevel.DEVICE, e.target.value);
};
public render(): React.ReactNode {
const brand = SdkConfig.get().brand;
let crawlerState;
if (this.state.currentRoom === null) {
crawlerState = _t("settings|security|message_search_indexing_idle");
} else {
crawlerState = _t("settings|security|message_search_indexing", { currentRoom: this.state.currentRoom });
}
const doneRooms = Math.max(0, this.state.eventIndexRoomCount - this.state.crawlingRoomsCount);
const eventIndexingSettings = (
<div>
{_t("settings|security|message_search_intro", {
brand,
})}
<div className="mx_SettingsTab_subsectionText">
{crawlerState}
<br />
{_t("settings|security|message_search_space_used")} {formatBytes(this.state.eventIndexSize, 0)}
<br />
{_t("settings|security|message_search_indexed_messages")} {formatCountLong(this.state.eventCount)}
<br />
{_t("settings|security|message_search_indexed_rooms")}{" "}
{_t("settings|security|message_search_room_progress", {
doneRooms: formatCountLong(doneRooms),
totalRooms: formatCountLong(this.state.roomCount),
})}{" "}
<br />
{_t("settings|security|message_search_pending_rooms", {
pendingRooms: formatCountLong(this.state.crawlingRoomsCount),
})}
<br />
<Field
label={_t("settings|security|message_search_sleep_time")}
type="number"
value={this.state.crawlerSleepTime.toString()}
onChange={this.onCrawlerSleepTimeChange}
/>
</div>
</div>
);
return (
<BaseDialog
className="mx_ManageEventIndexDialog"
onFinished={this.props.onFinished}
title={_t("settings|security|message_search_section")}
>
{eventIndexingSettings}
<DialogButtons
primaryButton={_t("action|done")}
onPrimaryButtonClick={this.props.onFinished}
primaryButtonClass="primary"
cancelButton={_t("action|disable")}
onCancel={this.onDisable}
cancelButtonClass="danger"
/>
</BaseDialog>
);
}
}
@@ -0,0 +1,714 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2019, 2020 , 2023 The Matrix.org Foundation C.I.C.
Copyright 2018, 2019 New Vector Ltd
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React, { type JSX, createRef } from "react";
import FileSaver from "file-saver";
import { logger } from "matrix-js-sdk/src/logger";
import { type AuthDict } from "matrix-js-sdk/src/matrix";
import { type GeneratedSecretStorageKey } from "matrix-js-sdk/src/crypto-api";
import classNames from "classnames";
import CheckmarkIcon from "@vector-im/compound-design-tokens/assets/web/icons/check";
import { MatrixClientPeg } from "../../../../MatrixClientPeg";
import { _t, _td } from "../../../../languageHandler";
import Modal from "../../../../Modal";
import { copyNode } from "../../../../utils/strings";
import { SSOAuthEntry } from "../../../../components/views/auth/InteractiveAuthEntryComponents";
import PassphraseField from "../../../../components/views/auth/PassphraseField";
import StyledRadioButton from "../../../../components/views/elements/StyledRadioButton";
import AccessibleButton from "../../../../components/views/elements/AccessibleButton";
import DialogButtons from "../../../../components/views/elements/DialogButtons";
import InlineSpinner from "../../../../components/views/elements/InlineSpinner";
import { ModuleRunner } from "../../../../modules/ModuleRunner";
import type Field from "../../../../components/views/elements/Field";
import BaseDialog from "../../../../components/views/dialogs/BaseDialog";
import Spinner from "../../../../components/views/elements/Spinner";
import InteractiveAuthDialog from "../../../../components/views/dialogs/InteractiveAuthDialog";
import { type IValidationResult } from "../../../../components/views/elements/Validation";
import PassphraseConfirmField from "../../../../components/views/auth/PassphraseConfirmField";
import { initialiseDehydrationIfEnabled } from "../../../../utils/device/dehydration";
enum SecureBackupSetupMethod {
Key = "key",
Passphrase = "passphrase",
}
// I made a mistake while converting this and it has to be fixed!
enum Phase {
Loading = "loading",
LoadError = "load_error",
ChooseKeyPassphrase = "choose_key_passphrase",
Passphrase = "passphrase",
PassphraseConfirm = "passphrase_confirm",
ShowKey = "show_key",
Storing = "storing",
Stored = "stored",
ConfirmSkip = "confirm_skip",
}
const PASSWORD_MIN_SCORE = 4; // So secure, many characters, much complex, wow, etc, etc.
interface IProps {
forceReset?: boolean;
onFinished(ok?: boolean): void;
}
interface IState {
phase: Phase;
passPhrase: string;
passPhraseValid: boolean;
passPhraseConfirm: string;
copied: boolean;
downloaded: boolean;
setPassphrase: boolean;
passPhraseKeySelected: string;
error?: boolean;
}
/**
* Walks the user through the process of creating a 4S passphrase and bootstrapping secret storage.
*
* If the user already has a key backup, follows a "migration" flow (aka "Upgrade your encryption") which
* prompts the user to enter their backup decryption password (a Curve25519 private key, possibly derived
* from a passphrase), and uses that as the (AES) 4S encryption key.
*
* @deprecated send the user to EncryptionUserSettingsTab instead
*/
export default class CreateSecretStorageDialog extends React.PureComponent<IProps, IState> {
public static defaultProps: Partial<IProps> = {
forceReset: false,
};
private recoveryKey?: GeneratedSecretStorageKey;
private recoveryKeyNode = createRef<HTMLElement>();
private passphraseField = createRef<Field>();
public constructor(props: IProps) {
super(props);
const keyFromCustomisations = ModuleRunner.instance.extensions.cryptoSetup.createSecretStorageKey();
const phase = keyFromCustomisations ? Phase.Loading : Phase.ChooseKeyPassphrase;
this.state = {
phase,
passPhrase: "",
passPhraseValid: false,
passPhraseConfirm: "",
copied: false,
downloaded: false,
setPassphrase: false,
passPhraseKeySelected: SecureBackupSetupMethod.Key,
};
}
public componentDidMount(): void {
const keyFromCustomisations = ModuleRunner.instance.extensions.cryptoSetup.createSecretStorageKey();
if (keyFromCustomisations) this.initExtension(keyFromCustomisations);
}
private initExtension(keyFromCustomisations: Uint8Array<ArrayBuffer>): void {
logger.log("CryptoSetupExtension: Created key via extension, jumping to bootstrap step");
this.recoveryKey = {
privateKey: keyFromCustomisations,
};
this.bootstrapSecretStorage();
}
private onKeyPassphraseChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({
passPhraseKeySelected: e.target.value,
});
};
private onChooseKeyPassphraseFormSubmit = async (): Promise<void> => {
if (this.state.passPhraseKeySelected === SecureBackupSetupMethod.Key) {
this.recoveryKey = await MatrixClientPeg.safeGet().getCrypto()!.createRecoveryKeyFromPassphrase();
this.setState({
copied: false,
downloaded: false,
setPassphrase: false,
phase: Phase.ShowKey,
});
} else {
this.setState({
copied: false,
downloaded: false,
phase: Phase.Passphrase,
});
}
};
private onCopyClick = (): void => {
const successful = copyNode(this.recoveryKeyNode.current);
if (successful) {
this.setState({
copied: true,
});
}
};
private onDownloadClick = (): void => {
if (!this.recoveryKey) return;
const blob = new Blob([this.recoveryKey.encodedPrivateKey!], {
type: "text/plain;charset=us-ascii",
});
FileSaver.saveAs(blob, "security-key.txt");
this.setState({
downloaded: true,
});
};
private doBootstrapUIAuth = async (makeRequest: (authData: AuthDict) => Promise<void>): Promise<void> => {
const dialogAesthetics = {
[SSOAuthEntry.PHASE_PREAUTH]: {
title: _t("auth|uia|sso_title"),
body: _t("auth|uia|sso_preauth_body"),
continueText: _t("auth|sso"),
continueKind: "primary",
},
[SSOAuthEntry.PHASE_POSTAUTH]: {
title: _t("encryption|confirm_encryption_setup_title"),
body: _t("encryption|confirm_encryption_setup_body"),
continueText: _t("action|confirm"),
continueKind: "primary",
},
};
const { finished } = Modal.createDialog(InteractiveAuthDialog, {
title: _t("encryption|bootstrap_title"),
matrixClient: MatrixClientPeg.safeGet(),
makeRequest,
aestheticsForStagePhases: {
[SSOAuthEntry.LOGIN_TYPE]: dialogAesthetics,
[SSOAuthEntry.UNSTABLE_LOGIN_TYPE]: dialogAesthetics,
},
});
const [confirmed] = await finished;
if (!confirmed) {
throw new Error("Cross-signing key upload auth canceled");
}
};
private bootstrapSecretStorage = async (): Promise<void> => {
const cli = MatrixClientPeg.safeGet();
const crypto = cli.getCrypto()!;
const { forceReset } = this.props;
let backupInfo;
// First, unless we know we want to do a reset, we see if there is an existing key backup
if (!forceReset) {
try {
this.setState({ phase: Phase.Loading });
backupInfo = await crypto.getKeyBackupInfo();
} catch (e) {
logger.error("Error fetching backup data from server", e);
this.setState({ phase: Phase.LoadError });
return;
}
}
this.setState({
phase: Phase.Storing,
error: undefined,
});
try {
if (forceReset) {
/* Resetting cross-signing requires secret storage to be reset
* (otherwise it will try to store the cross-signing keys in the
* old secret storage, and may prompt for the old key, which is
* probably not available), and resetting key backup requires
* cross-signing to be reset (so that the new backup can be
* signed by the new cross-signing key). So we reset secret
* storage first, then cross-signing, then key backup.
*/
logger.log("Forcing secret storage reset");
await crypto.bootstrapSecretStorage({
createSecretStorageKey: async () => this.recoveryKey!,
setupNewSecretStorage: true,
});
logger.log("Resetting key backup");
await crypto.resetKeyBackup();
} else {
// For password authentication users after 2020-09, this cross-signing
// step will be a no-op since it is now setup during registration or login
// when needed. We should keep this here to cover other cases such as:
// * Users with existing sessions prior to 2020-09 changes
// * SSO authentication users which require interactive auth to upload
// keys (and also happen to skip all post-authentication flows at the
// moment via token login)
await crypto.bootstrapCrossSigning({
authUploadDeviceSigningKeys: this.doBootstrapUIAuth,
});
await crypto.bootstrapSecretStorage({
createSecretStorageKey: async () => this.recoveryKey!,
setupNewKeyBackup: !backupInfo,
});
}
await initialiseDehydrationIfEnabled(cli, { createNewKey: true });
this.setState({
phase: Phase.Stored,
});
} catch (e) {
this.setState({ error: true });
logger.error("Error bootstrapping secret storage", e);
}
};
private onCancel = (): void => {
this.props.onFinished(false);
};
private onLoadRetryClick = (): void => {
this.bootstrapSecretStorage();
};
private onShowKeyContinueClick = (): void => {
this.bootstrapSecretStorage();
};
private onCancelClick = (): void => {
this.setState({ phase: Phase.ConfirmSkip });
};
private onGoBackClick = (): void => {
this.setState({ phase: Phase.ChooseKeyPassphrase });
};
private onPassPhraseNextClick = async (e: React.FormEvent): Promise<void> => {
e.preventDefault();
if (!this.passphraseField.current) return; // unmounting
await this.passphraseField.current.validate({ allowEmpty: false });
if (!this.passphraseField.current.state.valid) {
this.passphraseField.current.focus();
this.passphraseField.current.validate({ allowEmpty: false, focused: true });
return;
}
this.setState({ phase: Phase.PassphraseConfirm });
};
private onPassPhraseConfirmNextClick = async (e: React.FormEvent): Promise<void> => {
e.preventDefault();
if (this.state.passPhrase !== this.state.passPhraseConfirm) return;
this.recoveryKey = await MatrixClientPeg.safeGet()
.getCrypto()!
.createRecoveryKeyFromPassphrase(this.state.passPhrase);
this.setState({
copied: false,
downloaded: false,
setPassphrase: true,
phase: Phase.ShowKey,
});
};
private onSetAgainClick = (): void => {
this.setState({
passPhrase: "",
passPhraseValid: false,
passPhraseConfirm: "",
phase: Phase.Passphrase,
});
};
private onPassPhraseValidate = (result: IValidationResult): void => {
this.setState({
passPhraseValid: !!result.valid,
});
};
private onPassPhraseChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({
passPhrase: e.target.value,
});
};
private onPassPhraseConfirmChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({
passPhraseConfirm: e.target.value,
});
};
private renderOptionKey(): JSX.Element {
return (
<StyledRadioButton
key={SecureBackupSetupMethod.Key}
value={SecureBackupSetupMethod.Key}
name="keyPassphrase"
checked={this.state.passPhraseKeySelected === SecureBackupSetupMethod.Key}
onChange={this.onKeyPassphraseChange}
outlined
>
<div className="mx_CreateSecretStorageDialog_optionTitle">
{_t("settings|key_backup|setup_secure_backup|generate_security_key_title")}
</div>
<div>{_t("settings|key_backup|setup_secure_backup|generate_security_key_description")}</div>
</StyledRadioButton>
);
}
private renderOptionPassphrase(): JSX.Element {
return (
<StyledRadioButton
key={SecureBackupSetupMethod.Passphrase}
value={SecureBackupSetupMethod.Passphrase}
name="keyPassphrase"
checked={this.state.passPhraseKeySelected === SecureBackupSetupMethod.Passphrase}
onChange={this.onKeyPassphraseChange}
outlined
>
<div className="mx_CreateSecretStorageDialog_optionTitle">
{_t("settings|key_backup|setup_secure_backup|enter_phrase_title")}
</div>
<div>{_t("settings|key_backup|setup_secure_backup|use_phrase_only_you_know")}</div>
</StyledRadioButton>
);
}
private renderPhaseChooseKeyPassphrase(): JSX.Element {
const optionKey = this.renderOptionKey();
const optionPassphrase = this.renderOptionPassphrase();
return (
<form onSubmit={this.onChooseKeyPassphraseFormSubmit}>
<p className="mx_CreateSecretStorageDialog_centeredBody">
{_t("settings|key_backup|setup_secure_backup|description")}
</p>
<div className="mx_CreateSecretStorageDialog_primaryContainer" role="radiogroup">
{optionKey}
{optionPassphrase}
</div>
<DialogButtons
primaryButton={_t("action|continue")}
onPrimaryButtonClick={this.onChooseKeyPassphraseFormSubmit}
onCancel={this.onCancelClick}
/>
</form>
);
}
private renderPhasePassPhrase(): JSX.Element {
return (
<form onSubmit={this.onPassPhraseNextClick}>
<p>{_t("settings|key_backup|setup_secure_backup|enter_phrase_description")}</p>
<div className="mx_CreateSecretStorageDialog_passPhraseContainer">
<PassphraseField
id="mx_passPhraseInput"
className="mx_CreateSecretStorageDialog_passPhraseField"
onChange={this.onPassPhraseChange}
minScore={PASSWORD_MIN_SCORE}
value={this.state.passPhrase}
onValidate={this.onPassPhraseValidate}
fieldRef={this.passphraseField}
autoFocus={true}
label={_td("settings|key_backup|setup_secure_backup|enter_phrase_title")}
labelEnterPassword={_td("settings|key_backup|setup_secure_backup|enter_phrase_title")}
labelStrongPassword={_td("settings|key_backup|setup_secure_backup|phrase_strong_enough")}
labelAllowedButUnsafe={_td("settings|key_backup|setup_secure_backup|phrase_strong_enough")}
/>
</div>
<DialogButtons
primaryButton={_t("action|continue")}
onPrimaryButtonClick={this.onPassPhraseNextClick}
hasCancel={false}
disabled={!this.state.passPhraseValid}
>
<button type="button" onClick={this.onCancelClick} className="danger">
{_t("action|cancel")}
</button>
</DialogButtons>
</form>
);
}
private renderPhasePassPhraseConfirm(): JSX.Element {
let matchText;
let changeText;
if (this.state.passPhraseConfirm === this.state.passPhrase) {
matchText = _t("settings|key_backup|setup_secure_backup|pass_phrase_match_success");
changeText = _t("settings|key_backup|setup_secure_backup|use_different_passphrase");
} else if (!this.state.passPhrase.startsWith(this.state.passPhraseConfirm)) {
// only tell them they're wrong if they've actually gone wrong.
// Security conscious readers will note that if you left element-web unattended
// on this screen, this would make it easy for a malicious person to guess
// your passphrase one letter at a time, but they could get this faster by
// just opening the browser's developer tools and reading it.
// Note that not having typed anything at all will not hit this clause and
// fall through so empty box === no hint.
matchText = _t("settings|key_backup|setup_secure_backup|pass_phrase_match_failed");
changeText = _t("settings|key_backup|setup_secure_backup|set_phrase_again");
}
let passPhraseMatch: JSX.Element | undefined;
if (matchText) {
passPhraseMatch = (
<div>
<div>{matchText}</div>
<AccessibleButton kind="link" onClick={this.onSetAgainClick}>
{changeText}
</AccessibleButton>
</div>
);
}
return (
<form onSubmit={this.onPassPhraseConfirmNextClick}>
<p>{_t("settings|key_backup|setup_secure_backup|enter_phrase_to_confirm")}</p>
<div className="mx_CreateSecretStorageDialog_passPhraseContainer">
<PassphraseConfirmField
id="mx_passPhraseInput"
onChange={this.onPassPhraseConfirmChange}
value={this.state.passPhraseConfirm}
className="mx_CreateSecretStorageDialog_passPhraseField"
label={_td("settings|key_backup|setup_secure_backup|confirm_security_phrase")}
labelRequired={_td("settings|key_backup|setup_secure_backup|confirm_security_phrase")}
labelInvalid={_td("settings|key_backup|setup_secure_backup|pass_phrase_match_failed")}
autoFocus={true}
password={this.state.passPhrase}
/>
<div className="mx_CreateSecretStorageDialog_passPhraseMatch">{passPhraseMatch}</div>
</div>
<DialogButtons
primaryButton={_t("action|continue")}
onPrimaryButtonClick={this.onPassPhraseConfirmNextClick}
hasCancel={false}
disabled={this.state.passPhrase !== this.state.passPhraseConfirm}
>
<button type="button" onClick={this.onCancelClick} className="danger">
{_t("action|skip")}
</button>
</DialogButtons>
</form>
);
}
private renderPhaseShowKey(): JSX.Element {
let continueButton: JSX.Element;
if (this.state.phase === Phase.ShowKey) {
continueButton = (
<DialogButtons
primaryButton={_t("action|continue")}
disabled={!this.state.downloaded && !this.state.copied && !this.state.setPassphrase}
onPrimaryButtonClick={this.onShowKeyContinueClick}
hasCancel={false}
/>
);
} else {
continueButton = (
<div className="mx_CreateSecretStorageDialog_continueSpinner">
<InlineSpinner />
</div>
);
}
return (
<div>
<p>{_t("settings|key_backup|setup_secure_backup|security_key_safety_reminder")}</p>
<div className="mx_CreateSecretStorageDialog_primaryContainer mx_CreateSecretStorageDialog_recoveryKeyPrimarycontainer">
<div className="mx_CreateSecretStorageDialog_recoveryKeyContainer">
<div className="mx_CreateSecretStorageDialog_recoveryKey">
<code ref={this.recoveryKeyNode}>{this.recoveryKey?.encodedPrivateKey}</code>
</div>
<div className="mx_CreateSecretStorageDialog_recoveryKeyButtons">
<AccessibleButton
kind="primary"
className="mx_Dialog_primary"
onClick={this.onDownloadClick}
disabled={this.state.phase === Phase.Storing}
>
{_t("action|download")}
</AccessibleButton>
<span>
{_t("settings|key_backup|setup_secure_backup|download_or_copy", {
downloadButton: "",
copyButton: "",
})}
</span>
<AccessibleButton
kind="primary"
className="mx_Dialog_primary mx_CreateSecretStorageDialog_recoveryKeyButtons_copyBtn"
onClick={this.onCopyClick}
disabled={this.state.phase === Phase.Storing}
>
{this.state.copied ? _t("common|copied") : _t("action|copy")}
</AccessibleButton>
</div>
</div>
</div>
{continueButton}
</div>
);
}
private renderBusyPhase(): JSX.Element {
return (
<div>
<Spinner />
</div>
);
}
private renderStoredPhase(): JSX.Element {
return (
<>
<p className="mx_Dialog_content">
{_t("settings|key_backup|setup_secure_backup|backup_setup_success_description")}
</p>
<DialogButtons
primaryButton={_t("action|done")}
onPrimaryButtonClick={() => this.props.onFinished(true)}
hasCancel={false}
/>
</>
);
}
private renderPhaseLoadError(): JSX.Element {
return (
<div>
<p>{_t("settings|key_backup|setup_secure_backup|secret_storage_query_failure")}</p>
<div className="mx_Dialog_buttons">
<DialogButtons
primaryButton={_t("action|retry")}
onPrimaryButtonClick={this.onLoadRetryClick}
onCancel={this.onCancel}
/>
</div>
</div>
);
}
private renderPhaseSkipConfirm(): JSX.Element {
return (
<div>
<p>{_t("settings|key_backup|setup_secure_backup|cancel_warning")}</p>
<p>{_t("settings|key_backup|setup_secure_backup|settings_reminder")}</p>
<DialogButtons
primaryButton={_t("action|go_back")}
onPrimaryButtonClick={this.onGoBackClick}
hasCancel={false}
>
<button type="button" className="danger" onClick={this.onCancel}>
{_t("action|cancel")}
</button>
</DialogButtons>
</div>
);
}
private titleForPhase(phase: Phase): string {
switch (phase) {
case Phase.ChooseKeyPassphrase:
return _t("encryption|set_up_toast_title");
case Phase.Passphrase:
return _t("settings|key_backup|setup_secure_backup|title_set_phrase");
case Phase.PassphraseConfirm:
return _t("settings|key_backup|setup_secure_backup|title_confirm_phrase");
case Phase.ConfirmSkip:
return _t("common|are_you_sure");
case Phase.ShowKey:
return _t("settings|key_backup|setup_secure_backup|title_save_key");
case Phase.Storing:
return _t("encryption|bootstrap_title");
case Phase.Stored:
return _t("settings|key_backup|setup_secure_backup|backup_setup_success_title");
default:
return "";
}
}
private get topComponent(): React.ReactNode | null {
if (this.state.phase === Phase.Stored) {
return <CheckmarkIcon className="mx_Icon mx_Icon_circle-40 mx_Icon_accent mx_Icon_bg-accent-light" />;
}
return null;
}
private get classNames(): string {
return classNames("mx_CreateSecretStorageDialog", {
mx_SuccessDialog: this.state.phase === Phase.Stored,
});
}
public render(): React.ReactNode {
let content;
if (this.state.error) {
content = (
<div>
<p>{_t("settings|key_backup|setup_secure_backup|unable_to_setup")}</p>
<div className="mx_Dialog_buttons">
<DialogButtons
primaryButton={_t("action|retry")}
onPrimaryButtonClick={this.bootstrapSecretStorage}
onCancel={this.onCancel}
/>
</div>
</div>
);
} else {
switch (this.state.phase) {
case Phase.Loading:
content = this.renderBusyPhase();
break;
case Phase.LoadError:
content = this.renderPhaseLoadError();
break;
case Phase.ChooseKeyPassphrase:
content = this.renderPhaseChooseKeyPassphrase();
break;
case Phase.Passphrase:
content = this.renderPhasePassPhrase();
break;
case Phase.PassphraseConfirm:
content = this.renderPhasePassPhraseConfirm();
break;
case Phase.ShowKey:
content = this.renderPhaseShowKey();
break;
case Phase.Storing:
content = this.renderBusyPhase();
break;
case Phase.Stored:
content = this.renderStoredPhase();
break;
case Phase.ConfirmSkip:
content = this.renderPhaseSkipConfirm();
break;
}
}
let titleClass: string | string[] | undefined;
switch (this.state.phase) {
case Phase.ChooseKeyPassphrase:
titleClass = "mx_CreateSecretStorageDialog_centeredTitle";
break;
}
return (
<BaseDialog
className={this.classNames}
onFinished={this.props.onFinished}
top={this.topComponent}
title={this.titleForPhase(this.state.phase)}
titleClass={titleClass}
hasCancel={false}
fixedWidth={false}
>
<div>{content}</div>
</BaseDialog>
);
}
}
@@ -0,0 +1,222 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 The Matrix.org Foundation C.I.C.
Copyright 2017 Vector Creations Ltd
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import FileSaver from "file-saver";
import React, { type ChangeEvent } from "react";
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";
import { _t, _td } from "../../../../languageHandler";
import * as MegolmExportEncryption from "../../../../utils/MegolmExportEncryption";
import BaseDialog from "../../../../components/views/dialogs/BaseDialog";
import { type KeysStartingWith } from "../../../../@types/common";
import PassphraseField from "../../../../components/views/auth/PassphraseField";
import PassphraseConfirmField from "../../../../components/views/auth/PassphraseConfirmField";
import type Field from "../../../../components/views/elements/Field";
enum Phase {
Edit = "edit",
Exporting = "exporting",
}
interface IProps {
matrixClient: MatrixClient;
onFinished(doExport?: boolean): void;
}
interface IState {
phase: Phase;
errStr: string | null;
passphrase1: string;
passphrase2: string;
}
type AnyPassphrase = KeysStartingWith<IState, "passphrase">;
export default class ExportE2eKeysDialog extends React.Component<IProps, IState> {
private fieldPassword: Field | null = null;
private fieldPasswordConfirm: Field | null = null;
private unmounted = false;
public constructor(props: IProps) {
super(props);
this.state = {
phase: Phase.Edit,
errStr: null,
passphrase1: "",
passphrase2: "",
};
}
public componentDidMount(): void {
this.unmounted = false;
}
public componentWillUnmount(): void {
this.unmounted = true;
}
private async verifyFieldsBeforeSubmit(): Promise<boolean> {
const fieldsInDisplayOrder = [this.fieldPassword, this.fieldPasswordConfirm];
const invalidFields: Field[] = [];
for (const field of fieldsInDisplayOrder) {
if (!field) continue;
const valid = await field.validate({ allowEmpty: false });
if (!valid) {
invalidFields.push(field);
}
}
if (invalidFields.length === 0) {
return true;
}
// Focus on the first invalid field, then re-validate,
// which will result in the error tooltip being displayed for that field.
invalidFields[0].focus();
invalidFields[0].validate({ allowEmpty: false, focused: true });
return false;
}
private onPassphraseFormSubmit = async (ev: React.FormEvent): Promise<void> => {
ev.preventDefault();
if (!(await this.verifyFieldsBeforeSubmit())) return;
if (this.unmounted) return;
const passphrase = this.state.passphrase1;
this.startExport(passphrase);
};
private startExport(passphrase: string): void {
// extra Promise.resolve() to turn synchronous exceptions into
// asynchronous ones.
Promise.resolve()
.then(() => {
return this.props.matrixClient.getCrypto()!.exportRoomKeysAsJson();
})
.then((k) => {
return MegolmExportEncryption.encryptMegolmKeyFile(k, passphrase);
})
.then((f) => {
const blob = new Blob([f], {
type: "text/plain;charset=us-ascii",
});
FileSaver.saveAs(blob, "element-keys.txt");
this.props.onFinished(true);
})
.catch((e) => {
logger.error("Error exporting e2e keys:", e);
if (this.unmounted) {
return;
}
const msg = e.friendlyText || _t("error|unknown");
this.setState({
errStr: msg,
phase: Phase.Edit,
});
});
this.setState({
errStr: null,
phase: Phase.Exporting,
});
}
private onCancelClick = (ev: React.MouseEvent): boolean => {
ev.preventDefault();
this.props.onFinished(false);
return false;
};
private onPassphraseChange = (ev: React.ChangeEvent<HTMLInputElement>, phrase: AnyPassphrase): void => {
this.setState({
[phrase]: ev.target.value,
} as Pick<IState, AnyPassphrase>);
};
public render(): React.ReactNode {
const disableForm = this.state.phase === Phase.Exporting;
return (
<BaseDialog
className="mx_exportE2eKeysDialog"
onFinished={this.props.onFinished}
title={_t("settings|key_export_import|export_title")}
>
<form onSubmit={this.onPassphraseFormSubmit}>
<div className="mx_Dialog_content">
<p>{_t("settings|key_export_import|export_description_1")}</p>
<p>{_t("settings|key_export_import|export_description_2")}</p>
<div className="error">{this.state.errStr}</div>
<div className="mx_E2eKeysDialog_inputTable">
<div className="mx_E2eKeysDialog_inputRow">
<PassphraseField
minScore={3}
label={_td("settings|key_export_import|enter_passphrase")}
labelEnterPassword={_td("settings|key_export_import|enter_passphrase")}
labelStrongPassword={_td("settings|key_export_import|phrase_strong_enough")}
labelAllowedButUnsafe={_td("settings|key_export_import|phrase_strong_enough")}
value={this.state.passphrase1}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
this.onPassphraseChange(e, "passphrase1")
}
autoFocus={true}
size={64}
type="password"
disabled={disableForm}
autoComplete="new-password"
fieldRef={(field) => {
this.fieldPassword = field;
}}
/>
</div>
<div className="mx_E2eKeysDialog_inputRow">
<PassphraseConfirmField
password={this.state.passphrase1}
label={_td("settings|key_export_import|confirm_passphrase")}
labelRequired={_td("settings|key_export_import|phrase_cannot_be_empty")}
labelInvalid={_td("settings|key_export_import|phrase_must_match")}
value={this.state.passphrase2}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
this.onPassphraseChange(e, "passphrase2")
}
size={64}
type="password"
disabled={disableForm}
autoComplete="new-password"
fieldRef={(field) => {
this.fieldPasswordConfirm = field;
}}
/>
</div>
</div>
</div>
<div className="mx_Dialog_buttons">
<input
className="mx_Dialog_primary"
type="submit"
value={_t("action|export")}
disabled={disableForm}
/>
<button onClick={this.onCancelClick} disabled={disableForm}>
{_t("action|cancel")}
</button>
</div>
</form>
</BaseDialog>
);
}
}
@@ -0,0 +1,191 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 The Matrix.org Foundation C.I.C.
Copyright 2017 Vector Creations Ltd
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React, { createRef } from "react";
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";
import * as MegolmExportEncryption from "../../../../utils/MegolmExportEncryption";
import { _t } from "../../../../languageHandler";
import BaseDialog from "../../../../components/views/dialogs/BaseDialog";
import Field from "../../../../components/views/elements/Field";
function readFileAsArrayBuffer(file: File): Promise<ArrayBuffer> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
if (e.target?.result) {
resolve(e.target.result as ArrayBuffer);
} else {
reject(new Error("Failed to read file due to unknown error"));
}
};
reader.onerror = reject;
reader.readAsArrayBuffer(file);
});
}
enum Phase {
Edit = "edit",
Importing = "importing",
}
interface IProps {
matrixClient: MatrixClient;
onFinished(imported?: boolean): void;
}
interface IState {
enableSubmit: boolean;
phase: Phase;
errStr: string | null;
passphrase: string;
}
export default class ImportE2eKeysDialog extends React.Component<IProps, IState> {
private unmounted = false;
private file = createRef<HTMLInputElement>();
public constructor(props: IProps) {
super(props);
this.state = {
enableSubmit: false,
phase: Phase.Edit,
errStr: null,
passphrase: "",
};
}
public componentDidMount(): void {
this.unmounted = false;
}
public componentWillUnmount(): void {
this.unmounted = true;
}
private onFormChange = (): void => {
const files = this.file.current?.files;
this.setState({
enableSubmit: this.state.passphrase !== "" && !!files?.length,
});
};
private onPassphraseChange = (ev: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({ passphrase: ev.target.value }, this.onFormChange); // update general form state too
};
private onFormSubmit = (ev: React.FormEvent): boolean => {
ev.preventDefault();
// noinspection JSIgnoredPromiseFromCall
const file = this.file.current?.files?.[0];
if (file) {
this.startImport(file, this.state.passphrase);
}
return false;
};
private startImport(file: File, passphrase: string): Promise<void> {
this.setState({
errStr: null,
phase: Phase.Importing,
});
return readFileAsArrayBuffer(file)
.then((arrayBuffer) => {
return MegolmExportEncryption.decryptMegolmKeyFile(arrayBuffer, passphrase);
})
.then((keys) => {
return this.props.matrixClient.getCrypto()!.importRoomKeysAsJson(keys);
})
.then(() => {
// TODO: it would probably be nice to give some feedback about what we've imported here.
this.props.onFinished(true);
})
.catch((e) => {
logger.error("Error importing e2e keys:", e);
if (this.unmounted) {
return;
}
const msg = e.friendlyText || _t("error|unknown");
this.setState({
errStr: msg,
phase: Phase.Edit,
});
});
}
private onCancelClick = (ev: React.MouseEvent): boolean => {
ev.preventDefault();
this.props.onFinished(false);
return false;
};
public render(): React.ReactNode {
const disableForm = this.state.phase !== Phase.Edit;
return (
<BaseDialog
className="mx_importE2eKeysDialog"
onFinished={this.props.onFinished}
title={_t("settings|key_export_import|import_title")}
>
<form onSubmit={this.onFormSubmit}>
<div className="mx_Dialog_content">
<p>{_t("settings|key_export_import|import_description_1")}</p>
<p>{_t("settings|key_export_import|import_description_2")}</p>
<div className="error">{this.state.errStr}</div>
<div className="mx_E2eKeysDialog_inputTable">
<div className="mx_E2eKeysDialog_inputRow">
<div className="mx_E2eKeysDialog_inputLabel">
<label htmlFor="importFile">
{_t("settings|key_export_import|file_to_import")}
</label>
</div>
<div className="mx_E2eKeysDialog_inputCell">
<input
ref={this.file}
id="importFile"
type="file"
autoFocus={true}
onChange={this.onFormChange}
disabled={disableForm}
/>
</div>
</div>
<div className="mx_E2eKeysDialog_inputRow">
<Field
label={_t("settings|key_export_import|enter_passphrase")}
value={this.state.passphrase}
onChange={this.onPassphraseChange}
size={64}
type="password"
disabled={disableForm}
/>
</div>
</div>
</div>
<div className="mx_Dialog_buttons">
<input
className="mx_Dialog_primary"
type="submit"
value={_t("action|import")}
disabled={!this.state.enableSubmit || disableForm}
/>
<button onClick={this.onCancelClick} disabled={disableForm}>
{_t("action|cancel")}
</button>
</div>
</form>
</BaseDialog>
);
}
}
@@ -0,0 +1,83 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2020 The Matrix.org Foundation C.I.C.
Copyright 2018, 2019 New Vector Ltd
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React, { type JSX, useEffect, useState } from "react";
import { ErrorIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import dis from "../../../../dispatcher/dispatcher";
import { _t } from "../../../../languageHandler";
import Modal from "../../../../Modal";
import RestoreKeyBackupDialog from "../../../../components/views/dialogs/security/RestoreKeyBackupDialog";
import { Action } from "../../../../dispatcher/actions";
import DialogButtons from "../../../../components/views/elements/DialogButtons";
import BaseDialog from "../../../../components/views/dialogs/BaseDialog";
import { useMatrixClientContext } from "../../../../contexts/MatrixClientContext.tsx";
/**
* Properties for {@link NewRecoveryMethodDialog}.
*/
interface NewRecoveryMethodDialogProps {
/**
* Callback when the dialog is dismissed.
*/
onFinished(this: void): void;
}
// Export as default instead of a named export so that it can be dynamically imported with React lazy
/**
* Dialog to inform the user that a new recovery method has been detected.
*/
export default function NewRecoveryMethodDialog({ onFinished }: NewRecoveryMethodDialogProps): JSX.Element {
const matrixClient = useMatrixClientContext();
const [isKeyBackupEnabled, setIsKeyBackupEnabled] = useState(false);
useEffect(() => {
const checkBackupEnabled = async (): Promise<void> => {
const crypto = matrixClient.getCrypto();
setIsKeyBackupEnabled(Boolean(crypto && (await crypto.getActiveSessionBackupVersion()) !== null));
};
checkBackupEnabled();
}, [matrixClient]);
function onClick(): void {
if (isKeyBackupEnabled) {
onFinished();
} else {
const { finished } = Modal.createDialog(RestoreKeyBackupDialog, {}, undefined, false, true);
finished.then(onFinished);
}
}
return (
<BaseDialog
className="mx_KeyBackupFailedDialog"
onFinished={onFinished}
title={
<span className="mx_KeyBackupFailedDialog_title">
<ErrorIcon />
{_t("encryption|new_recovery_method_detected|title")}
</span>
}
>
<p>{_t("encryption|new_recovery_method_detected|description_1")}</p>
{isKeyBackupEnabled && <p>{_t("encryption|new_recovery_method_detected|description_2")}</p>}
<strong className="warning">{_t("encryption|new_recovery_method_detected|warning")}</strong>
<DialogButtons
primaryButton={_t("common|setup_secure_messages")}
onPrimaryButtonClick={onClick}
cancelButton={_t("common|go_to_settings")}
onCancel={() => {
onFinished();
dis.fire(Action.ViewUserSettings);
}}
/>
</BaseDialog>
);
}
@@ -0,0 +1,65 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2020 The Matrix.org Foundation C.I.C.
Copyright 2019 New Vector Ltd
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React from "react";
import { ErrorIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import dis from "../../../../dispatcher/dispatcher";
import { _t } from "../../../../languageHandler";
import { Action } from "../../../../dispatcher/actions";
import { UserTab } from "../../../../components/views/dialogs/UserTab";
import BaseDialog from "../../../../components/views/dialogs/BaseDialog";
import DialogButtons from "../../../../components/views/elements/DialogButtons";
import { type OpenToTabPayload } from "../../../../dispatcher/payloads/OpenToTabPayload";
interface IProps {
onFinished(): void;
}
export default class RecoveryMethodRemovedDialog extends React.PureComponent<IProps> {
private onGoToSettingsClick = (): void => {
this.props.onFinished();
dis.fire(Action.ViewUserSettings);
};
private onSetupClick = (): void => {
this.props.onFinished();
// Open the user settings dialog to the encryption tab and start the flow to reset encryption
const payload: OpenToTabPayload = {
action: Action.ViewUserSettings,
initialTabId: UserTab.Encryption,
};
dis.dispatch(payload);
};
public render(): React.ReactNode {
const title = (
<span className="mx_KeyBackupFailedDialog_title">
<ErrorIcon />
{_t("encryption|recovery_method_removed|title")}
</span>
);
return (
<BaseDialog className="mx_KeyBackupFailedDialog" onFinished={this.props.onFinished} title={title}>
<div>
<p>{_t("encryption|recovery_method_removed|description_1")}</p>
<p>{_t("encryption|recovery_method_removed|description_2")}</p>
<strong className="warning">{_t("encryption|recovery_method_removed|warning")}</strong>
<DialogButtons
primaryButton={_t("common|setup_secure_messages")}
onPrimaryButtonClick={this.onSetupClick}
cancelButton={_t("common|go_to_settings")}
onCancel={this.onGoToSettingsClick}
/>
</div>
</BaseDialog>
);
}
}