/* Copyright 2018 New Vector Ltd Copyright 2019, 2020 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react'; import {MatrixClientPeg} from '../../../MatrixClientPeg'; import { _t } from '../../../languageHandler'; import Modal from '../../../Modal'; import { isSecureBackupRequired } from '../../../utils/WellKnownUtils'; import Spinner from '../elements/Spinner'; import AccessibleButton from '../elements/AccessibleButton'; import QuestionDialog from '../dialogs/QuestionDialog'; import RestoreKeyBackupDialog from '../dialogs/security/RestoreKeyBackupDialog'; import { accessSecretStorage } from '../../../SecurityManager'; import {replaceableComponent} from "../../../utils/replaceableComponent"; @replaceableComponent("views.settings.SecureBackupPanel") export default class SecureBackupPanel extends React.PureComponent { constructor(props) { super(props); this._unmounted = false; this.state = { loading: true, error: null, backupKeyStored: null, backupKeyCached: null, backupKeyWellFormed: null, secretStorageKeyInAccount: null, secretStorageReady: null, backupInfo: null, backupSigStatus: null, sessionsRemaining: 0, }; } componentDidMount() { this._checkKeyBackupStatus(); MatrixClientPeg.get().on('crypto.keyBackupStatus', this._onKeyBackupStatus); MatrixClientPeg.get().on( 'crypto.keyBackupSessionsRemaining', this._onKeyBackupSessionsRemaining, ); } componentWillUnmount() { this._unmounted = true; if (MatrixClientPeg.get()) { MatrixClientPeg.get().removeListener('crypto.keyBackupStatus', this._onKeyBackupStatus); MatrixClientPeg.get().removeListener( 'crypto.keyBackupSessionsRemaining', this._onKeyBackupSessionsRemaining, ); } } _onKeyBackupSessionsRemaining = (sessionsRemaining) => { this.setState({ sessionsRemaining, }); } _onKeyBackupStatus = () => { // This just loads the current backup status rather than forcing // a re-check otherwise we risk causing infinite loops this._loadBackupStatus(); } async _checkKeyBackupStatus() { this._getUpdatedDiagnostics(); try { const {backupInfo, trustInfo} = await MatrixClientPeg.get().checkKeyBackup(); this.setState({ loading: false, error: null, backupInfo, backupSigStatus: trustInfo, }); } catch (e) { console.log("Unable to fetch check backup status", e); if (this._unmounted) return; this.setState({ loading: false, error: e, backupInfo: null, backupSigStatus: null, }); } } async _loadBackupStatus() { this.setState({ loading: true }); this._getUpdatedDiagnostics(); try { const backupInfo = await MatrixClientPeg.get().getKeyBackupVersion(); const backupSigStatus = await MatrixClientPeg.get().isKeyBackupTrusted(backupInfo); if (this._unmounted) return; this.setState({ loading: false, error: null, backupInfo, backupSigStatus, }); } catch (e) { console.log("Unable to fetch key backup status", e); if (this._unmounted) return; this.setState({ loading: false, error: e, backupInfo: null, backupSigStatus: null, }); } } async _getUpdatedDiagnostics() { const cli = MatrixClientPeg.get(); const secretStorage = cli.crypto._secretStorage; const backupKeyStored = !!(await cli.isKeyBackupKeyStored()); const backupKeyFromCache = await cli.crypto.getSessionBackupPrivateKey(); const backupKeyCached = !!(backupKeyFromCache); const backupKeyWellFormed = backupKeyFromCache instanceof Uint8Array; const secretStorageKeyInAccount = await secretStorage.hasKey(); const secretStorageReady = await cli.isSecretStorageReady(); if (this._unmounted) return; this.setState({ backupKeyStored, backupKeyCached, backupKeyWellFormed, secretStorageKeyInAccount, secretStorageReady, }); } _startNewBackup = () => { Modal.createTrackedDialogAsync('Key Backup', 'Key Backup', import('../../../async-components/views/dialogs/security/CreateKeyBackupDialog'), { onFinished: () => { this._loadBackupStatus(); }, }, null, /* priority = */ false, /* static = */ true, ); } _deleteBackup = () => { Modal.createTrackedDialog('Delete Backup', '', QuestionDialog, { title: _t('Delete Backup'), description: _t( "Are you sure? You will lose your encrypted messages if your " + "keys are not backed up properly.", ), button: _t('Delete Backup'), danger: true, onFinished: (proceed) => { if (!proceed) return; this.setState({loading: true}); MatrixClientPeg.get().deleteKeyBackupVersion(this.state.backupInfo.version).then(() => { this._loadBackupStatus(); }); }, }); } _restoreBackup = async () => { Modal.createTrackedDialog( 'Restore Backup', '', RestoreKeyBackupDialog, null, null, /* priority = */ false, /* static = */ true, ); } _resetSecretStorage = async () => { this.setState({ error: null }); try { await accessSecretStorage(() => { }, /* forceReset = */ true); } catch (e) { console.error("Error resetting secret storage", e); if (this._unmounted) return; this.setState({ error: e }); } if (this._unmounted) return; this._loadBackupStatus(); } render() { const { loading, error, backupKeyStored, backupKeyCached, backupKeyWellFormed, secretStorageKeyInAccount, secretStorageReady, backupInfo, backupSigStatus, sessionsRemaining, } = this.state; let statusDescription; let extraDetailsTableRows; let extraDetails; const actions = []; if (error) { statusDescription = (
{_t("Unable to load key backup status")}
); } else if (loading) { statusDescription = ; } else if (backupInfo) { let restoreButtonCaption = _t("Restore from Backup"); if (MatrixClientPeg.get().getKeyBackupEnabled()) { statusDescription =

✅ {_t("This session is backing up your keys. ")}

; } else { statusDescription = <>

{_t( "This session is not backing up your keys, " + "but you do have an existing backup you can restore from " + "and add to going forward.", {}, {b: sub => {sub}}, )}

{_t( "Connect this session to key backup before signing out to avoid " + "losing any keys that may only be on this session.", )}

; restoreButtonCaption = _t("Connect this session to Key Backup"); } let uploadStatus; if (!MatrixClientPeg.get().getKeyBackupEnabled()) { // No upload status to show when backup disabled. uploadStatus = ""; } else if (sessionsRemaining > 0) { uploadStatus =
{_t("Backing up %(sessionsRemaining)s keys...", { sessionsRemaining })}
; } else { uploadStatus =
{_t("All keys backed up")}
; } let backupSigStatuses = backupSigStatus.sigs.map((sig, i) => { const deviceName = sig.device ? (sig.device.getDisplayName() || sig.device.deviceId) : null; const validity = sub => {sub} ; const verify = sub => {sub} ; const device = sub => {deviceName}; const fromThisDevice = ( sig.device && sig.device.getFingerprint() === MatrixClientPeg.get().getDeviceEd25519Key() ); const fromThisUser = ( sig.crossSigningId && sig.deviceId === MatrixClientPeg.get().getCrossSigningId() ); let sigStatus; if (sig.valid && fromThisUser) { sigStatus = _t( "Backup has a valid signature from this user", {}, { validity }, ); } else if (!sig.valid && fromThisUser) { sigStatus = _t( "Backup has a invalid signature from this user", {}, { validity }, ); } else if (sig.crossSigningId) { sigStatus = _t( "Backup has a signature from unknown user with ID %(deviceId)s", { deviceId: sig.deviceId }, { verify }, ); } else if (!sig.device) { sigStatus = _t( "Backup has a signature from unknown session with ID %(deviceId)s", { deviceId: sig.deviceId }, { verify }, ); } else if (sig.valid && fromThisDevice) { sigStatus = _t( "Backup has a valid signature from this session", {}, { validity }, ); } else if (!sig.valid && fromThisDevice) { // it can happen... sigStatus = _t( "Backup has an invalid signature from this session", {}, { validity }, ); } else if (sig.valid && sig.deviceTrust.isVerified()) { sigStatus = _t( "Backup has a valid signature from " + "verified session ", {}, { validity, verify, device }, ); } else if (sig.valid && !sig.deviceTrust.isVerified()) { sigStatus = _t( "Backup has a valid signature from " + "unverified session ", {}, { validity, verify, device }, ); } else if (!sig.valid && sig.deviceTrust.isVerified()) { sigStatus = _t( "Backup has an invalid signature from " + "verified session ", {}, { validity, verify, device }, ); } else if (!sig.valid && !sig.deviceTrust.isVerified()) { sigStatus = _t( "Backup has an invalid signature from " + "unverified session ", {}, { validity, verify, device }, ); } return
{sigStatus}
; }); if (backupSigStatus.sigs.length === 0) { backupSigStatuses = _t("Backup is not signed by any of your sessions"); } let trustedLocally; if (backupSigStatus.trusted_locally) { trustedLocally = _t("This backup is trusted because it has been restored on this session"); } extraDetailsTableRows = <> {_t("Backup version:")} {backupInfo.version} {_t("Algorithm:")} {backupInfo.algorithm} ; extraDetails = <> {uploadStatus}
{backupSigStatuses}
{trustedLocally}
; actions.push( {restoreButtonCaption} , ); if (!isSecureBackupRequired()) { actions.push( {_t("Delete Backup")} , ); } } else { statusDescription = <>

{_t( "Your keys are not being backed up from this session.", {}, {b: sub => {sub}}, )}

{_t("Back up your keys before signing out to avoid losing them.")}

; actions.push( {_t("Set up")} , ); } if (secretStorageKeyInAccount) { actions.push( {_t("Reset")} , ); } let backupKeyWellFormedText = ""; if (backupKeyCached) { backupKeyWellFormedText = ", "; if (backupKeyWellFormed) { backupKeyWellFormedText += _t("well formed"); } else { backupKeyWellFormedText += _t("unexpected type"); } } let actionRow; if (actions.length) { actionRow =
{actions}
; } return (

{_t( "Back up your encryption keys with your account data in case you " + "lose access to your sessions. Your keys will be secured with a " + "unique Security Key.", )}

{statusDescription}
{_t("Advanced")} {extraDetailsTableRows}
{_t("Backup key stored:")} { backupKeyStored === true ? _t("in secret storage") : _t("not stored") }
{_t("Backup key cached:")} {backupKeyCached ? _t("cached locally") : _t("not found locally")} {backupKeyWellFormedText}
{_t("Secret storage public key:")} {secretStorageKeyInAccount ? _t("in account data") : _t("not found")}
{_t("Secret storage:")} {secretStorageReady ? _t("ready") : _t("not ready")}
{extraDetails}
{actionRow}
); } }