Convert RestoreKeyBackupDialog to TS

Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
pull/21833/head
Šimon Brandner 2021-09-04 18:40:54 +02:00
parent 8791b10ca9
commit 3c9ded5a9a
No known key found for this signature in database
GPG Key ID: 55C211A1226CB17D
1 changed files with 103 additions and 72 deletions

View File

@ -16,30 +16,64 @@ limitations under the License.
*/ */
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types';
import * as sdk from '../../../../index';
import { MatrixClientPeg } from '../../../../MatrixClientPeg'; import { MatrixClientPeg } from '../../../../MatrixClientPeg';
import { MatrixClient } from 'matrix-js-sdk/src/client'; import { MatrixClient } from 'matrix-js-sdk/src/client';
import { _t } from '../../../../languageHandler'; import { _t } from '../../../../languageHandler';
import { accessSecretStorage } from '../../../../SecurityManager'; import { accessSecretStorage } from '../../../../SecurityManager';
import { IKeyBackupInfo, IKeyBackupRestoreResult } from "matrix-js-sdk/src/crypto/keybackup";
import { ISecretStorageKeyInfo } from "matrix-js-sdk/src/crypto/api";
import * as sdk from '../../../../index';
const RESTORE_TYPE_PASSPHRASE = 0; enum RestoreType {
const RESTORE_TYPE_RECOVERYKEY = 1; Passphrase = "passphrase",
const RESTORE_TYPE_SECRET_STORAGE = 2; RecoveryKey = "recovery_key",
SecretStorage = "secret_storage"
}
enum ProgressState {
PreFetch = "prefetch",
Fetch = "fetch",
LoadKeys = "load_keys",
}
interface IProps {
// if false, will close the dialog as soon as the restore completes succesfully
// default: true
showSummary?: boolean;
// If specified, gather the key from the user but then call the function with the backup
// key rather than actually (necessarily) restoring the backup.
keyCallback?: (key: Uint8Array) => void;
onFinished: (success: boolean) => void;
}
interface IState {
backupInfo: IKeyBackupInfo;
backupKeyStored: Record<string, ISecretStorageKeyInfo>;
loading: boolean;
loadError: string;
restoreError: {
errcode: string;
};
recoveryKey: string;
recoverInfo: IKeyBackupRestoreResult;
recoveryKeyValid: boolean;
forceRecoveryKey: boolean;
passPhrase: "";
restoreType: RestoreType;
progress: {
stage: ProgressState;
total?: number;
successes?: number;
failures?: number;
};
}
/* /*
* Dialog for restoring e2e keys from a backup and the user's recovery key * Dialog for restoring e2e keys from a backup and the user's recovery key
*/ */
export default class RestoreKeyBackupDialog extends React.PureComponent { export default class RestoreKeyBackupDialog extends React.PureComponent<IProps, IState> {
static propTypes = {
// if false, will close the dialog as soon as the restore completes succesfully
// default: true
showSummary: PropTypes.bool,
// If specified, gather the key from the user but then call the function with the backup
// key rather than actually (necessarily) restoring the backup.
keyCallback: PropTypes.func,
};
static defaultProps = { static defaultProps = {
showSummary: true, showSummary: true,
}; };
@ -58,58 +92,58 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
forceRecoveryKey: false, forceRecoveryKey: false,
passPhrase: '', passPhrase: '',
restoreType: null, restoreType: null,
progress: { stage: "prefetch" }, progress: { stage: ProgressState.PreFetch },
}; };
} }
componentDidMount() { public componentDidMount(): void {
this._loadBackupStatus(); this.loadBackupStatus();
} }
_onCancel = () => { private onCancel = (): void => {
this.props.onFinished(false); this.props.onFinished(false);
} };
_onDone = () => { private onDone = (): void => {
this.props.onFinished(true); this.props.onFinished(true);
} };
_onUseRecoveryKeyClick = () => { private onUseRecoveryKeyClick = (): void => {
this.setState({ this.setState({
forceRecoveryKey: true, forceRecoveryKey: true,
}); });
} };
_progressCallback = (data) => { private progressCallback = (data): void => {
this.setState({ this.setState({
progress: data, progress: data,
}); });
} };
_onResetRecoveryClick = () => { private onResetRecoveryClick = (): void => {
this.props.onFinished(false); this.props.onFinished(false);
accessSecretStorage(() => {}, /* forceReset = */ true); accessSecretStorage(async () => {}, /* forceReset = */ true);
} };
_onRecoveryKeyChange = (e) => { private onRecoveryKeyChange = (e): void => {
this.setState({ this.setState({
recoveryKey: e.target.value, recoveryKey: e.target.value,
recoveryKeyValid: MatrixClientPeg.get().isValidRecoveryKey(e.target.value), recoveryKeyValid: MatrixClientPeg.get().isValidRecoveryKey(e.target.value),
}); });
} };
_onPassPhraseNext = async () => { private onPassPhraseNext = async (): Promise<void> => {
this.setState({ this.setState({
loading: true, loading: true,
restoreError: null, restoreError: null,
restoreType: RESTORE_TYPE_PASSPHRASE, restoreType: RestoreType.Passphrase,
}); });
try { try {
// We do still restore the key backup: we must ensure that the key backup key // We do still restore the key backup: we must ensure that the key backup key
// is the right one and restoring it is currently the only way we can do this. // is the right one and restoring it is currently the only way we can do this.
const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithPassword( const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithPassword(
this.state.passPhrase, undefined, undefined, this.state.backupInfo, this.state.passPhrase, undefined, undefined, this.state.backupInfo,
{ progressCallback: this._progressCallback }, { progressCallback: this.progressCallback },
); );
if (this.props.keyCallback) { if (this.props.keyCallback) {
const key = await MatrixClientPeg.get().keyBackupKeyFromPassword( const key = await MatrixClientPeg.get().keyBackupKeyFromPassword(
@ -133,20 +167,20 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
restoreError: e, restoreError: e,
}); });
} }
} };
_onRecoveryKeyNext = async () => { private onRecoveryKeyNext = async (): Promise<void> => {
if (!this.state.recoveryKeyValid) return; if (!this.state.recoveryKeyValid) return;
this.setState({ this.setState({
loading: true, loading: true,
restoreError: null, restoreError: null,
restoreType: RESTORE_TYPE_RECOVERYKEY, restoreType: RestoreType.RecoveryKey,
}); });
try { try {
const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithRecoveryKey( const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithRecoveryKey(
this.state.recoveryKey, undefined, undefined, this.state.backupInfo, this.state.recoveryKey, undefined, undefined, this.state.backupInfo,
{ progressCallback: this._progressCallback }, { progressCallback: this.progressCallback },
); );
if (this.props.keyCallback) { if (this.props.keyCallback) {
const key = MatrixClientPeg.get().keyBackupKeyFromRecoveryKey(this.state.recoveryKey); const key = MatrixClientPeg.get().keyBackupKeyFromRecoveryKey(this.state.recoveryKey);
@ -167,31 +201,30 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
restoreError: e, restoreError: e,
}); });
} }
} };
_onPassPhraseChange = (e) => { private onPassPhraseChange = (e): void => {
this.setState({ this.setState({
passPhrase: e.target.value, passPhrase: e.target.value,
}); });
} };
async _restoreWithSecretStorage() { private async restoreWithSecretStorage(): Promise<void> {
this.setState({ this.setState({
loading: true, loading: true,
restoreError: null, restoreError: null,
restoreType: RESTORE_TYPE_SECRET_STORAGE, restoreType: RestoreType.SecretStorage,
}); });
try { try {
// `accessSecretStorage` may prompt for storage access as needed. // `accessSecretStorage` may prompt for storage access as needed.
const recoverInfo = await accessSecretStorage(async () => { await accessSecretStorage(async () => {
return MatrixClientPeg.get().restoreKeyBackupWithSecretStorage( await MatrixClientPeg.get().restoreKeyBackupWithSecretStorage(
this.state.backupInfo, undefined, undefined, this.state.backupInfo, undefined, undefined,
{ progressCallback: this._progressCallback }, { progressCallback: this.progressCallback },
); );
}); });
this.setState({ this.setState({
loading: false, loading: false,
recoverInfo,
}); });
} catch (e) { } catch (e) {
console.log("Error restoring backup", e); console.log("Error restoring backup", e);
@ -202,14 +235,14 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
} }
} }
async _restoreWithCachedKey(backupInfo) { private async restoreWithCachedKey(backupInfo): Promise<boolean> {
if (!backupInfo) return false; if (!backupInfo) return false;
try { try {
const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithCache( const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithCache(
undefined, /* targetRoomId */ undefined, /* targetRoomId */
undefined, /* targetSessionId */ undefined, /* targetSessionId */
backupInfo, backupInfo,
{ progressCallback: this._progressCallback }, { progressCallback: this.progressCallback },
); );
this.setState({ this.setState({
recoverInfo, recoverInfo,
@ -221,7 +254,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
} }
} }
async _loadBackupStatus() { private async loadBackupStatus(): Promise<void> {
this.setState({ this.setState({
loading: true, loading: true,
loadError: null, loadError: null,
@ -236,7 +269,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
backupKeyStored, backupKeyStored,
}); });
const gotCache = await this._restoreWithCachedKey(backupInfo); const gotCache = await this.restoreWithCachedKey(backupInfo);
if (gotCache) { if (gotCache) {
console.log("RestoreKeyBackupDialog: found cached backup key"); console.log("RestoreKeyBackupDialog: found cached backup key");
this.setState({ this.setState({
@ -247,7 +280,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
// If the backup key is stored, we can proceed directly to restore. // If the backup key is stored, we can proceed directly to restore.
if (backupKeyStored) { if (backupKeyStored) {
return this._restoreWithSecretStorage(); return this.restoreWithSecretStorage();
} }
this.setState({ this.setState({
@ -263,7 +296,10 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
} }
} }
render() { public render(): JSX.Element {
// FIXME: Making these into imports will break tests
const DialogButtons = sdk.getComponent('views.elements.DialogButtons');
const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog'); const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog');
const Spinner = sdk.getComponent("elements.Spinner"); const Spinner = sdk.getComponent("elements.Spinner");
@ -279,12 +315,12 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
if (this.state.loading) { if (this.state.loading) {
title = _t("Restoring keys from backup"); title = _t("Restoring keys from backup");
let details; let details;
if (this.state.progress.stage === "fetch") { if (this.state.progress.stage === ProgressState.Fetch) {
details = _t("Fetching keys from server..."); details = _t("Fetching keys from server...");
} else if (this.state.progress.stage === "load_keys") { } else if (this.state.progress.stage === ProgressState.LoadKeys) {
const { total, successes, failures } = this.state.progress; const { total, successes, failures } = this.state.progress;
details = _t("%(completed)s of %(total)s keys restored", { total, completed: successes + failures }); details = _t("%(completed)s of %(total)s keys restored", { total, completed: successes + failures });
} else if (this.state.progress.stage === "prefetch") { } else if (this.state.progress.stage === ProgressState.PreFetch) {
details = _t("Fetching keys from server..."); details = _t("Fetching keys from server...");
} }
content = <div> content = <div>
@ -296,7 +332,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
content = _t("Unable to load backup status"); content = _t("Unable to load backup status");
} else if (this.state.restoreError) { } else if (this.state.restoreError) {
if (this.state.restoreError.errcode === MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY) { if (this.state.restoreError.errcode === MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY) {
if (this.state.restoreType === RESTORE_TYPE_RECOVERYKEY) { if (this.state.restoreType === RestoreType.RecoveryKey) {
title = _t("Security Key mismatch"); title = _t("Security Key mismatch");
content = <div> content = <div>
<p>{ _t( <p>{ _t(
@ -321,7 +357,6 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
title = _t("Error"); title = _t("Error");
content = _t("No backup found!"); content = _t("No backup found!");
} else if (this.state.recoverInfo) { } else if (this.state.recoverInfo) {
const DialogButtons = sdk.getComponent('views.elements.DialogButtons');
title = _t("Keys restored"); title = _t("Keys restored");
let failedToDecrypt; let failedToDecrypt;
if (this.state.recoverInfo.total > this.state.recoverInfo.imported) { if (this.state.recoverInfo.total > this.state.recoverInfo.imported) {
@ -334,14 +369,12 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
<p>{ _t("Successfully restored %(sessionCount)s keys", { sessionCount: this.state.recoverInfo.imported }) }</p> <p>{ _t("Successfully restored %(sessionCount)s keys", { sessionCount: this.state.recoverInfo.imported }) }</p>
{ failedToDecrypt } { failedToDecrypt }
<DialogButtons primaryButton={_t('OK')} <DialogButtons primaryButton={_t('OK')}
onPrimaryButtonClick={this._onDone} onPrimaryButtonClick={this.onDone}
hasCancel={false} hasCancel={false}
focus={true} focus={true}
/> />
</div>; </div>;
} else if (backupHasPassphrase && !this.state.forceRecoveryKey) { } else if (backupHasPassphrase && !this.state.forceRecoveryKey) {
const DialogButtons = sdk.getComponent('views.elements.DialogButtons');
const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
title = _t("Enter Security Phrase"); title = _t("Enter Security Phrase");
content = <div> content = <div>
<p>{ _t( <p>{ _t(
@ -357,16 +390,16 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
<form className="mx_RestoreKeyBackupDialog_primaryContainer"> <form className="mx_RestoreKeyBackupDialog_primaryContainer">
<input type="password" <input type="password"
className="mx_RestoreKeyBackupDialog_passPhraseInput" className="mx_RestoreKeyBackupDialog_passPhraseInput"
onChange={this._onPassPhraseChange} onChange={this.onPassPhraseChange}
value={this.state.passPhrase} value={this.state.passPhrase}
autoFocus={true} autoFocus={true}
/> />
<DialogButtons <DialogButtons
primaryButton={_t('Next')} primaryButton={_t('Next')}
onPrimaryButtonClick={this._onPassPhraseNext} onPrimaryButtonClick={this.onPassPhraseNext}
primaryIsSubmit={true} primaryIsSubmit={true}
hasCancel={true} hasCancel={true}
onCancel={this._onCancel} onCancel={this.onCancel}
focus={false} focus={false}
/> />
</form> </form>
@ -379,14 +412,14 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
button1: s => <AccessibleButton button1: s => <AccessibleButton
className="mx_linkButton" className="mx_linkButton"
element="span" element="span"
onClick={this._onUseRecoveryKeyClick} onClick={this.onUseRecoveryKeyClick}
> >
{ s } { s }
</AccessibleButton>, </AccessibleButton>,
button2: s => <AccessibleButton button2: s => <AccessibleButton
className="mx_linkButton" className="mx_linkButton"
element="span" element="span"
onClick={this._onResetRecoveryClick} onClick={this.onResetRecoveryClick}
> >
{ s } { s }
</AccessibleButton>, </AccessibleButton>,
@ -394,8 +427,6 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
</div>; </div>;
} else { } else {
title = _t("Enter Security Key"); title = _t("Enter Security Key");
const DialogButtons = sdk.getComponent('views.elements.DialogButtons');
const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
let keyStatus; let keyStatus;
if (this.state.recoveryKey.length === 0) { if (this.state.recoveryKey.length === 0) {
@ -423,15 +454,15 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
<div className="mx_RestoreKeyBackupDialog_primaryContainer"> <div className="mx_RestoreKeyBackupDialog_primaryContainer">
<input className="mx_RestoreKeyBackupDialog_recoveryKeyInput" <input className="mx_RestoreKeyBackupDialog_recoveryKeyInput"
onChange={this._onRecoveryKeyChange} onChange={this.onRecoveryKeyChange}
value={this.state.recoveryKey} value={this.state.recoveryKey}
autoFocus={true} autoFocus={true}
/> />
{ keyStatus } { keyStatus }
<DialogButtons primaryButton={_t('Next')} <DialogButtons primaryButton={_t('Next')}
onPrimaryButtonClick={this._onRecoveryKeyNext} onPrimaryButtonClick={this.onRecoveryKeyNext}
hasCancel={true} hasCancel={true}
onCancel={this._onCancel} onCancel={this.onCancel}
focus={false} focus={false}
primaryDisabled={!this.state.recoveryKeyValid} primaryDisabled={!this.state.recoveryKeyValid}
/> />
@ -443,7 +474,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
{ {
button: s => <AccessibleButton className="mx_linkButton" button: s => <AccessibleButton className="mx_linkButton"
element="span" element="span"
onClick={this._onResetRecoveryClick} onClick={this.onResetRecoveryClick}
> >
{ s } { s }
</AccessibleButton>, </AccessibleButton>,