From c6cce197a51327c309acf76c7b31fbfea2f042db Mon Sep 17 00:00:00 2001 From: Marcus Murwall Date: Wed, 18 Nov 2026 11:05:31 +0100 Subject: [PATCH] Add encryption settings: set up and change the recovery key Adds an Encryption dialog (account menu, and a Set up button on the "no key backup" banner) showing device verification, key backup and recovery status. Users can now set up recovery or replace their Security Key without Element. - Changing re-encrypts the existing secrets under a new key; the key backup is untouched, so history stays readable. Refused unless this device holds every secret, and verified afterwards. - Setting up creates the cross-signing identity if needed (password or OAuth browser approval), enables key backup and stores both. - The new key is shown once with Copy and Save to Downloads; nothing is written to the server until the user confirms they saved it. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/lib.rs | 31 ++- src/App.css | 8 + src/components/EncryptionSettings.tsx | 358 ++++++++++++++++++++++++++ src/components/SecurityBanner.tsx | 21 +- src/components/Sidebar.tsx | 4 +- src/components/StatusUI.tsx | 6 +- src/matrix/client.ts | 17 +- src/matrix/recovery.ts | 162 ++++++++++++ src/util/secrets.ts | 10 + 9 files changed, 604 insertions(+), 13 deletions(-) create mode 100644 src/components/EncryptionSettings.tsx create mode 100644 src/matrix/recovery.ts diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d32925a..c3cbd57 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -29,6 +29,35 @@ fn secret_delete(key: String) -> Result<(), String> { } } +/// Save a newly generated recovery key as a text file in the user's Downloads folder (never +/// overwriting an existing file) and return its path. The file is readable by the user only. +#[tauri::command] +fn save_recovery_key(app: tauri::AppHandle, contents: String) -> Result { + use std::io::Write; + use tauri::Manager; + let dir = app.path().download_dir().map_err(|e| e.to_string())?; + for n in 0..100 { + let name = if n == 0 { "murmrchat-recovery-key.txt".to_string() } else { format!("murmrchat-recovery-key-{n}.txt") }; + let path = dir.join(name); + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + match opts.open(&path) { + Ok(mut f) => { + f.write_all(contents.as_bytes()).map_err(|e| e.to_string())?; + return Ok(path.to_string_lossy().into_owned()); + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e.to_string()), + } + } + Err("Could not find a free file name in Downloads".into()) +} + /// Write a diagnostic line from the web UI to stderr (CSP violations, uncaught errors). /// The packaged app has no visible devtools console, so this is how problems surface. #[tauri::command] @@ -172,7 +201,7 @@ pub fn run() { .plugin(tauri_plugin_window_state::Builder::new().build()) .plugin(tauri_plugin_notification::init()) .plugin(tauri_plugin_opener::init()) - .invoke_handler(tauri::generate_handler![secret_get, secret_set, secret_delete, frontend_log, set_unread]) + .invoke_handler(tauri::generate_handler![secret_get, secret_set, secret_delete, save_recovery_key, frontend_log, set_unread]) .build(tauri::generate_context!()) .expect("error while building tauri application") .run(|app, event| { diff --git a/src/App.css b/src/App.css index ad36038..e616576 100644 --- a/src/App.css +++ b/src/App.css @@ -264,6 +264,14 @@ pre code { background: none; padding: 0; } .modal { width: 480px; max-width: calc(100% - 32px); background: var(--bg); border-radius: 8px; padding: 24px; box-shadow: var(--shadow); } .modal h2 { margin: 0 0 8px; font-size: 18px; color: var(--text-strong); } .modal textarea { width: 100%; margin-top: 12px; padding: 10px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); font-family: ui-monospace, Menlo, monospace; resize: vertical; } +.enc-status { display: grid; grid-template-columns: auto 1fr; gap: 6px 16px; margin: 12px 0; font-size: 14px; } +.enc-status dt { color: var(--muted); } +.enc-status dd { margin: 0; font-weight: 600; } +.enc-status dd.ok { color: var(--text-strong); } +.enc-status dd.warn { color: var(--danger); } +.recovery-key { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-size: 16px; line-height: 1.6; word-spacing: 4px; padding: 12px 14px; margin-top: 12px; background: var(--bg-soft); border-radius: 6px; color: var(--text-strong); user-select: all; overflow-wrap: anywhere; } +.enc-note { margin-top: 8px; overflow-wrap: anywhere; } +.enc-check { display: flex; align-items: center; gap: 8px; margin-top: 16px; font-weight: 600; font-size: 13px; } ::-webkit-scrollbar { width: 8px; height: 8px; } ::-webkit-scrollbar-thumb { background: rgba(128, 128, 128, 0.35); border-radius: 4px; } diff --git a/src/components/EncryptionSettings.tsx b/src/components/EncryptionSettings.tsx new file mode 100644 index 0000000..7f8e2ac --- /dev/null +++ b/src/components/EncryptionSettings.tsx @@ -0,0 +1,358 @@ +import { useEffect, useRef, useState } from "react"; +import type { GeneratedSecretStorageKey } from "matrix-js-sdk/lib/crypto-api"; +import { useClient } from "../matrix/hooks"; +import { + applyRecoveryKey, + generateRecoveryKey, + getRecoveryInfo, + whyCantMakeRecoveryKey, + type AuthRequest, + type RecoveryInfo, +} from "../matrix/recovery"; +import { openExternal } from "../util/open"; +import { saveRecoveryKeyFile } from "../util/secrets"; + +export const ENCRYPTION_EVENT = "murmrchat:encryption"; + +/** Open the Encryption settings dialog from anywhere. */ +export function requestEncryptionSettings() { + window.dispatchEvent(new Event(ENCRYPTION_EVENT)); +} + +type Step = + | { kind: "overview" } + | { kind: "confirm-change" } + | { kind: "show-key"; key: GeneratedSecretStorageKey & { encodedPrivateKey: string } } + | { kind: "applying"; key: GeneratedSecretStorageKey & { encodedPrivateKey: string } } + | { kind: "done"; wasChange: boolean }; + +/** + * Encryption settings: this device's status, plus setting up or changing the account's recovery key + * (the Security Key). Replaces the corresponding screens in Element. + */ +export function EncryptionDialog({ onClose, onUnlock, onChanged }: { onClose: () => void; onUnlock: () => void; onChanged: () => void }) { + const client = useClient(); + const [info, setInfo] = useState(null); + const [step, setStep] = useState({ kind: "overview" }); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const refresh = () => + getRecoveryInfo(client) + .then(setInfo) + .catch((e) => setError((e as Error).message)); + useEffect(() => { + void refresh(); + }, [client]); + + // Closing is safe until the new key is being written; nothing has reached the server before that. + const closable = step.kind !== "applying"; + useEffect(() => { + const onKey = (e: KeyboardEvent) => e.key === "Escape" && closable && onClose(); + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [closable, onClose]); + + const generate = async () => { + setBusy(true); + setError(null); + try { + setStep({ kind: "show-key", key: await generateRecoveryKey(client) }); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(false); + } + }; + + const wasChange = !!info?.recoverySetUp; + + return ( +
+
e.stopPropagation()}> + {step.kind === "overview" && ( + { + onClose(); + onUnlock(); + }} + onSetUp={generate} + onChange={() => setStep({ kind: "confirm-change" })} + /> + )} + + {step.kind === "confirm-change" && ( + <> +

Change recovery key?

+

+ You'll get a new Security Key and your current one will stop working. Your message history stays + readable and your other signed-in devices stay verified. +

+
+ + +
+ + )} + + {step.kind === "show-key" && ( + setStep({ kind: "overview" })} + onContinue={() => { + setError(null); + setStep({ kind: "applying", key: step.key }); + }} + /> + )} + + {step.kind === "applying" && ( + { + setStep({ kind: "done", wasChange }); + void refresh(); + onChanged(); + }} + onFailed={(msg) => { + setError(msg); + setStep({ kind: "overview" }); + void refresh(); + }} + /> + )} + + {step.kind === "done" && ( + <> +

{step.wasChange ? "Recovery key changed" : "Recovery is set up"}

+

+ {step.wasChange + ? "Use your new Security Key from now on, here and in other apps. The old one no longer works." + : "Your message keys are now backed up. Use your Security Key to unlock your messages on a new device."} +

+
+ +
+ + )} + + {error &&
{error}
} +
+
+ ); +} + +function Overview({ + info, + busy, + onClose, + onUnlock, + onSetUp, + onChange, +}: { + info: RecoveryInfo | null; + busy: boolean; + onClose: () => void; + onUnlock: () => void; + onSetUp: () => void; + onChange: () => void; +}) { + const blocked = info && whyCantMakeRecoveryKey(info); + const canUnlock = info && info.recoverySetUp && !info.deviceVerified; + return ( + <> +

Encryption

+ {!info ? ( +

Checking…

+ ) : ( +
+
This device
+
{info.deviceVerified ? "Verified" : "Not verified"}
+
Key backup
+
{info.backupVersion ? "On" : "Off"}
+
Recovery key
+
{info.recoverySetUp ? "Set up" : "Not set up"}
+
+ )} + {info && ( +

+ {info.recoverySetUp + ? "Your Security Key unlocks your encrypted messages on new devices. It can't be shown again, but you can replace it with a new one." + : "Set up a Security Key so you can read your encrypted messages on new devices, even if you sign out everywhere."} +

+ )} + {blocked && !canUnlock &&

{blocked}

} +
+ + {canUnlock && ( + + )} + {info && !blocked && ( + + )} +
+ + ); +} + +function ShowKey({ encoded, onCancel, onContinue }: { encoded: string; onCancel: () => void; onContinue: () => void }) { + const [saved, setSaved] = useState(false); + const [note, setNote] = useState(null); + + const copy = async () => { + try { + await navigator.clipboard.writeText(encoded); + setNote("Copied. Paste it into your password manager."); + } catch { + setNote("Couldn't copy. Select the key and copy it manually."); + } + }; + const save = async () => { + try { + const path = await saveRecoveryKeyFile(`MurmrChat recovery key (Matrix Security Key)\n\n${encoded}\n`); + setNote(path ? `Saved to ${path}` : "Saved."); + } catch (e) { + setNote(`Couldn't save: ${(e as Error).message}`); + } + }; + + return ( + <> +

Save your Security Key

+

+ Store it somewhere safe, like a password manager. You'll need it to read your messages on a new device, and it + won't be shown again. +

+
+ {encoded} +
+
+ + +
+ {note &&
{note}
} + +
+ + +
+ + ); +} + +function Applying({ + keyToApply, + onDone, + onFailed, +}: { + keyToApply: GeneratedSecretStorageKey; + onDone: () => void; + onFailed: (msg: string) => void; +}) { + const client = useClient(); + const [progress, setProgress] = useState("Saving…"); + const [auth, setAuth] = useState(null); + const [password, setPassword] = useState(""); + const resolver = useRef<((v: string | null) => void) | null>(null); + const started = useRef(false); + + useEffect(() => { + if (started.current) return; // StrictMode runs effects twice; this must only happen once. + started.current = true; + const prompt = (req: AuthRequest) => + new Promise((resolve) => { + resolver.current = resolve; + setAuth(req); + if (req.kind === "browser") void openExternal(req.url); + }); + applyRecoveryKey(client, keyToApply, prompt, setProgress) + .then(onDone) + .catch((e) => onFailed((e as Error).message)); + }, []); + + const answer = (v: string | null) => { + resolver.current?.(v); + resolver.current = null; + setAuth(null); + setPassword(""); + }; + + if (auth?.kind === "browser") { + return ( + <> +

Confirm in your browser

+

+ Your server wants you to approve this change. We opened its page in your browser; approve it there, then come + back and continue. +

+
+ + + +
+ + ); + } + if (auth?.kind === "password") { + return ( +
{ + e.preventDefault(); + answer(password); + }} + > +

Confirm your password

+

Your server needs your account password to set up encryption.

+
+ setPassword(e.target.value)} placeholder="Password" /> +
+
+ + +
+
+ ); + } + return ( + <> +

Saving your Security Key

+

{progress}

+ + ); +} diff --git a/src/components/SecurityBanner.tsx b/src/components/SecurityBanner.tsx index 7803efa..a34c60e 100644 --- a/src/components/SecurityBanner.tsx +++ b/src/components/SecurityBanner.tsx @@ -2,6 +2,7 @@ import { useEffect, useState } from "react"; import { CryptoEvent } from "matrix-js-sdk/lib/crypto-api"; import { getEncryptionStatus, unlockWithRecovery, type EncryptionStatus } from "../matrix/client"; import { useClient } from "../matrix/hooks"; +import { ENCRYPTION_EVENT, EncryptionDialog, requestEncryptionSettings } from "./EncryptionSettings"; export const UNLOCK_EVENT = "murmrchat:unlock"; @@ -18,6 +19,7 @@ export function SecurityBanner() { const client = useClient(); const [status, setStatus] = useState("unknown"); const [open, setOpen] = useState(false); + const [settingsOpen, setSettingsOpen] = useState(false); const [dismissed, setDismissed] = useState(false); useEffect(() => { @@ -28,7 +30,10 @@ export function SecurityBanner() { // Any "Unlock" button elsewhere in the app opens the dialog via this event. const openDialog = () => setOpen(true); window.addEventListener(UNLOCK_EVENT, openDialog); + const openSettings = () => setSettingsOpen(true); + window.addEventListener(ENCRYPTION_EVENT, openSettings); return () => { + window.removeEventListener(ENCRYPTION_EVENT, openSettings); client.off(CryptoEvent.DevicesUpdated, refresh); client.off(CryptoEvent.UserTrustStatusChanged, refresh); window.removeEventListener(UNLOCK_EVENT, openDialog); @@ -42,7 +47,12 @@ export function SecurityBanner() { {showBanner && (
{status === "no-recovery-setup" ? ( - 🔒 Your account has no key backup set up, so older encrypted messages can't be restored here. + <> + 🔒 Your account has no key backup set up, so older encrypted messages can't be restored here. + + ) : ( <> 🔒 Encrypted messages are locked on this device. Enter your Security Key to read them. @@ -56,6 +66,13 @@ export function SecurityBanner() {
)} + {settingsOpen && ( + setSettingsOpen(false)} + onUnlock={() => setOpen(true)} + onChanged={() => getEncryptionStatus(client).then(setStatus)} + /> + )} {open && ( setOpen(false)} @@ -96,7 +113,7 @@ function UnlockDialog({ onClose, onDone }: { onClose: () => void; onDone: () =>

Unlock encrypted messages

Enter the Security Key (looks like EsTc 1234 abcd …) or Security Phrase you saved - when you set up encryption in Element. It never leaves this device. + when you set up recovery (here or in another Matrix app). It never leaves this device.

{ diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx index d50d1df..efcc9fc 100644 --- a/src/components/Sidebar.tsx +++ b/src/components/Sidebar.tsx @@ -16,7 +16,7 @@ import { dmPartner, dmRoomIds, HOME_TEAM, invitedRooms, markRoomRead, sidebarRoo import { Avatar } from "./Avatar"; import { followedThreads, threadUnread } from "./GlobalThreads"; import { BellOffIcon, HashIcon, LockIcon, ThreadIcon } from "./icons"; -import { requestUnlock } from "./SecurityBanner"; +import { requestEncryptionSettings } from "./EncryptionSettings"; import { AvatarWithStatus, MyStatusMenu, StatusEmoji } from "./StatusUI"; import { confirmDialog } from "../util/dialogs"; @@ -194,7 +194,7 @@ export function Sidebar({