import * as React from 'react'; import EncryptionService from '@joplin/lib/services/e2ee/EncryptionService'; import { themeStyle } from '@joplin/lib/theme'; import { _ } from '@joplin/lib/locale'; import time from '@joplin/lib/time'; import shim, { MessageBoxType } from '@joplin/lib/shim'; import dialogs from '../dialogs'; import { decryptedStatText, determineKeyPassword, dontReencryptData, enableEncryptionConfirmationMessages, onSavePasswordClick, onToggleEnabledClick, reencryptData, upgradeMasterKey, useHasUnknownEncryptionMethodKeysMessage, useInputPasswords, useNeedMasterPassword, usePasswordChecker, useStats, useToggleShowDisabledMasterKeys } from '@joplin/lib/components/EncryptionConfigScreen/utils'; import { MasterKeyEntity } from '@joplin/lib/services/e2ee/types'; import { getEncryptionEnabled, localSyncInfoSelector, masterKeyEnabled } from '@joplin/lib/services/synchronizer/syncInfoUtils'; import { getDefaultMasterKey, getMasterPasswordStatusMessage, isKnownEncryptionMethod, masterPasswordIsValid, toggleAndSetupEncryption } from '@joplin/lib/services/e2ee/utils'; import Button, { ButtonLevel } from '../Button/Button'; import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'; import { connect } from 'react-redux'; import { AppState, AppStateDialogName } from '../../app.reducer'; import Setting from '@joplin/lib/models/Setting'; import CommandService from '@joplin/lib/services/CommandService'; import { PublicPrivateKeyPair } from '@joplin/lib/services/e2ee/ppk/ppk'; import ToggleAdvancedSettingsButton from '../ConfigScreen/controls/ToggleAdvancedSettingsButton'; import MacOSMissingPasswordHelpLink from '../ConfigScreen/controls/MissingPasswordHelpLink'; import { Dispatch } from 'redux'; import { shouldCancelPendingEnableAfterMasterPasswordDialog, shouldOpenMasterPasswordDialogForEnable, shouldResumeEnableAfterMasterPasswordDialog } from './enableFlow'; import Dialog from '@joplin/lib/components/Dialog'; import DialogButtonRow from '../DialogButtonRow'; import DialogTitle from '../DialogTitle'; import PasswordInput from '../PasswordInput/PasswordInput'; interface Props { themeId: number; dispatch: Dispatch; masterKeys: MasterKeyEntity[]; passwords: Record; notLoadedMasterKeys: string[]; encryptionEnabled: boolean; shouldReencrypt: boolean; activeMasterKeyId: string; masterPassword: string; ppk: PublicPrivateKeyPair; masterPasswordDialogOpen: boolean; } interface EncryptionDialogOptions{ className: string; title: string; content: React.ReactNode; onClose: ()=> void; onDialogButtonRowClick: (event: { buttonName: string })=> void; okButtonDisabled?: boolean; } export const EncryptionConfigScreen = (props: Props) => { const { inputPasswords, onInputPasswordChange } = useInputPasswords(props.passwords); const [pendingEnableEncryption, setPendingEnableEncryption] = useState(false); const [enableEncryptionPromptVisible, setEnableEncryptionPromptVisible] = useState(false); const [enableEncryptionPassword, setEnableEncryptionPassword] = useState(''); const [enableEncryptionError, setEnableEncryptionError] = useState(''); const [disableEncryptionPromptVisible, setDisableEncryptionPromptVisible] = useState(false); const disablePromptPromiseRef = useRef<(value: boolean)=> void>(null); const promptPromiseRef = useRef<(password: string | null)=> void>(null); // Cleanup on unmount to resolve pending promises if the user navigates away useEffect(() => { return () => { if (disablePromptPromiseRef.current) disablePromptPromiseRef.current(false); if (promptPromiseRef.current) promptPromiseRef.current(null); }; }, []); const wasMasterPasswordDialogOpen = useRef(props.masterPasswordDialogOpen); const theme = useMemo(() => { return themeStyle(props.themeId); }, [props.themeId]); const stats = useStats(); const { passwordChecks, masterPasswordKeys, masterPasswordStatus } = usePasswordChecker(props.masterKeys, props.activeMasterKeyId, props.masterPassword, props.passwords); const { showDisabledMasterKeys, toggleShowDisabledMasterKeys } = useToggleShowDisabledMasterKeys(); const needMasterPassword = useNeedMasterPassword(passwordChecks, props.masterKeys); const unknownEncryptionMethodMessage = useHasUnknownEncryptionMethodKeysMessage(props.masterKeys); useEffect(() => { const wasOpen = wasMasterPasswordDialogOpen.current; wasMasterPasswordDialogOpen.current = props.masterPasswordDialogOpen; if (shouldCancelPendingEnableAfterMasterPasswordDialog({ pendingEnableEncryption, wasMasterPasswordDialogOpen: wasOpen, masterPasswordDialogOpen: props.masterPasswordDialogOpen, masterPassword: props.masterPassword, })) { setPendingEnableEncryption(false); return; } if (!shouldResumeEnableAfterMasterPasswordDialog({ pendingEnableEncryption, wasMasterPasswordDialogOpen: wasOpen, masterPasswordDialogOpen: props.masterPasswordDialogOpen, masterPassword: props.masterPassword, })) return; const masterKey = getDefaultMasterKey(); void (async () => { try { await toggleAndSetupEncryption(EncryptionService.instance(), true, masterKey, props.masterPassword); } catch (error) { const message = error instanceof Error ? error.message : String(error); await dialogs.alert(message); } finally { setPendingEnableEncryption(false); } })(); }, [pendingEnableEncryption, props.masterPasswordDialogOpen, props.masterPassword]); const onUpgradeMasterKey = useCallback(async (mk: MasterKeyEntity) => { const password = determineKeyPassword(mk.id, masterPasswordKeys, props.masterPassword, props.passwords); const result = await upgradeMasterKey(mk, password); await shim.showMessageBox(result, { type: MessageBoxType.Info }); }, [props.passwords, masterPasswordKeys, props.masterPassword]); const renderNeedUpgradeSection = () => { if (!shim.isElectron()) return null; const needUpgradeMasterKeys = EncryptionService.instance().masterKeysThatNeedUpgrading(props.masterKeys); if (!needUpgradeMasterKeys.length) return null; const theme = themeStyle(props.themeId); const rows = []; for (const mk of needUpgradeMasterKeys) { rows.push( {mk.id} , ); } return (

{_('Keys that need upgrading')}

{_('The following keys use an out-dated encryption algorithm and it is recommended to upgrade them. The upgraded key will still be able to decrypt and encrypt your data as usual.')}

{rows}
{_('ID')} {_('Upgrade')}
); }; const renderMasterKey = (mk: MasterKeyEntity) => { const theme = themeStyle(props.themeId); const passwordStyle = { color: theme.color, backgroundColor: theme.backgroundColor, border: '1px solid', borderColor: theme.dividerColor, }; const missingPasswordCellStyle = { ...theme.textStyle, border: '3px solid', borderColor: theme.colorError, }; const password = inputPasswords[mk.id] ? inputPasswords[mk.id] : ''; const isActive = props.activeMasterKeyId === mk.id; const activeIcon = isActive ? '✔' : ''; const knownKeyType = isKnownEncryptionMethod(mk.encryption_method); const passwordOk = passwordChecks[mk.id] === true ? '✔' : '❌'; const renderPasswordInput = (masterKeyId: string) => { if (masterPasswordKeys[masterKeyId] || !passwordChecks['master']) { return ( ({_('Master password')}) ); } else { return ( onInputPasswordChange(mk, event.target.value)} /> {' '} ); } }; return ( {activeIcon} {mk.id}
{_('Source: ')}{mk.source_application} {_('Created: ')}{time.formatMsToLocal(mk.created_time)}
{_('Updated: ')}{time.formatMsToLocal(mk.updated_time)} {renderPasswordInput(mk.id)} {knownKeyType ? passwordOk : ❓} ); }; const renderMasterKeySection = (masterKeys: MasterKeyEntity[], isEnabledMasterKeys: boolean) => { const theme = themeStyle(props.themeId); const mkComps = []; const showTable = isEnabledMasterKeys || showDisabledMasterKeys; for (let i = 0; i < masterKeys.length; i++) { const mk = masterKeys[i]; mkComps.push(renderMasterKey(mk)); } const headerComp = isEnabledMasterKeys ?

{_('Encryption keys')}

: toggleShowDisabledMasterKeys() } style={{ ...theme.urlStyle, display: 'inline-block', marginBottom: 10 }} href="#">{showTable ? _('Hide disabled keys') : _('Show disabled keys')}; const infoComp: React.ReactNode = null; // isEnabledMasterKeys ?

{'Note: Only one key is going to be used for encryption (the one marked as "active"). Any of the keys might be used for decryption, depending on how the notes or notebooks were originally encrypted.'}

: null; const tableComp = !showTable ? null : ( {mkComps}
{_('Active')} {_('ID')} {_('Date')} {_('Password')} {_('Valid')} {_('Actions')}
); if (mkComps.length) { return (
{headerComp} {tableComp} {infoComp}
); } return null; }; const onToggleButtonClick = useCallback(async () => { const isEnabled = getEncryptionEnabled(); const newEnabled = !isEnabled; const masterKey = getDefaultMasterKey(); const hasMasterPassword = !!props.masterPassword; let newPassword: string | null = ''; if (isEnabled) { setDisableEncryptionPromptVisible(true); const answer = await new Promise((resolve) => { disablePromptPromiseRef.current = resolve; }); if (!answer) return; } else { if (shouldOpenMasterPasswordDialogForEnable({ hasMasterPassword, masterPasswordDialogOpen: props.masterPasswordDialogOpen, })) { setPendingEnableEncryption(true); props.dispatch({ type: 'DIALOG_OPEN', name: AppStateDialogName.MasterPassword, }); return; } // Wait for the custom React Dialog to resolve setEnableEncryptionPassword(''); setEnableEncryptionError(''); setEnableEncryptionPromptVisible(true); newPassword = await new Promise((resolve) => { promptPromiseRef.current = resolve; }); if (newPassword === null) return; // User cancelled } try { await toggleAndSetupEncryption(EncryptionService.instance(), newEnabled, masterKey, newPassword); } catch (error) { await dialogs.alert(error.message); } }, [props.dispatch, props.masterPassword, props.masterPasswordDialogOpen]); const renderEncryptionDialog = (options: EncryptionDialogOptions) => { return (
{options.content}
); }; const renderEnableEncryptionDialog = () => { if (!enableEncryptionPromptVisible) return null; const masterKey = getDefaultMasterKey(); const hasMasterPassword = !!props.masterPassword; const msg = enableEncryptionConfirmationMessages(masterKey, hasMasterPassword); const messageComps = msg.map((m, index) =>

{m}

); const onClose = () => { setEnableEncryptionPromptVisible(false); if (promptPromiseRef.current) promptPromiseRef.current(null); }; const onDialogButtonRowClick = async (event: { buttonName: string }) => { if (event.buttonName === 'cancel') { onClose(); return; } if (event.buttonName === 'ok') { if (hasMasterPassword) { if (!(await masterPasswordIsValid(enableEncryptionPassword))) { setEnableEncryptionError(_('Invalid password. Please try again. If you have forgotten your password you will need to reset it.')); return; } } setEnableEncryptionError(''); setEnableEncryptionPromptVisible(false); if (promptPromiseRef.current) promptPromiseRef.current(enableEncryptionPassword); } }; const onPasswordInputChange = (event: React.ChangeEvent) => { setEnableEncryptionError(''); setEnableEncryptionPassword(event.target.value); }; return renderEncryptionDialog({ className: 'enable-encryption-dialog', title: _('Enable encryption'), content: ( <>
{messageComps}
{enableEncryptionError && (
{enableEncryptionError}
)} ), onClose, onDialogButtonRowClick, okButtonDisabled: !enableEncryptionPassword, }); }; const renderDisableEncryptionDialog = () => { if (!disableEncryptionPromptVisible) return null; const onClose = () => { setDisableEncryptionPromptVisible(false); if (disablePromptPromiseRef.current) disablePromptPromiseRef.current(false); }; const onDialogButtonRowClick = (event: { buttonName: string }) => { if (event.buttonName === 'cancel') { onClose(); return; } if (event.buttonName === 'ok') { setDisableEncryptionPromptVisible(false); if (disablePromptPromiseRef.current) disablePromptPromiseRef.current(true); } }; return renderEncryptionDialog({ className: 'disable-encryption-dialog', title: _('Disable encryption'), content: (

{_('Disabling encryption means *all* your notes and attachments are going to be re-synchronised and sent unencrypted to the sync target. Do you wish to continue?')}

), onClose, onDialogButtonRowClick, }); }; const renderEncryptionSection = () => { const decryptedItemsInfo =

{decryptedStatText(stats)}

; const toggleButton = ( { !props.shouldReencrypt ? null : } ); }; // If the user should re-encrypt, ensure that the section is visible initially. const [showAdvanced, setShowAdvanced] = useState(props.shouldReencrypt); const toggleAdvanced = useCallback(() => { setShowAdvanced(!showAdvanced); }, [showAdvanced]); const advancedSettingsId = useId(); const renderAdvancedSection = () => { const reEncryptSection = renderReencryptData(); if (!reEncryptSection) return null; return (
{ showAdvanced ? reEncryptSection : null }
); }; return (
{renderDebugSection()} {renderEncryptionSection()} {renderMasterPasswordSection()} {renderMasterKeySection(props.masterKeys.filter(mk => masterKeyEnabled(mk)), true)} {renderMasterKeySection(props.masterKeys.filter(mk => !masterKeyEnabled(mk)), false)} {renderNonExistingMasterKeysSection()} {renderAdvancedSection()} {renderEnableEncryptionDialog()} {renderDisableEncryptionDialog()}
); }; const mapStateToProps = (state: AppState) => { const syncInfo = localSyncInfoSelector(state); return { themeId: state.settings.theme, masterKeys: syncInfo.masterKeys, passwords: state.settings['encryption.passwordCache'], encryptionEnabled: syncInfo.e2ee, activeMasterKeyId: syncInfo.activeMasterKeyId, shouldReencrypt: state.settings['encryption.shouldReencrypt'] >= Setting.SHOULD_REENCRYPT_YES, notLoadedMasterKeys: state.notLoadedMasterKeys, masterPassword: state.settings['encryption.masterPassword'], ppk: syncInfo.ppk, masterPasswordDialogOpen: !!state.dialogs.find(dialog => dialog.name === AppStateDialogName.MasterPassword), }; }; export default connect(mapStateToProps)(EncryptionConfigScreen);