Set the vault passphrase before the first key (first-run onboarding) #9

Merged
raucao merged 3 commits from feature/onboarding into main 2026-11-30 12:19:36 +00:00
6 changed files with 902 additions and 150 deletions

No files matched your search

+69 -21
View File
@@ -260,9 +260,13 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
(`data/resources/ui/keys.blp`) around the existing `KeysView`. A second
`AppState` would mean a second registry and a second signer on one device key
(see M5), so the registry is created once in `application.rs` and shared. The
window is 420×560: tall enough for the **first-run empty state** and the
add/import alert dialogs, because GTK never resizes a mapped window, so the
default has to fit the tallest thing it shows.
window is 460×560: tall enough for the **first-run empty state** and the
add/import dialog forms, because GTK never resizes a mapped window, so the
default has to fit the tallest thing it shows. The **width is deliberate**: it
is above libadwaita's bottom-sheet threshold (`AdwDialog`'s `auto` mode uses a
bottom sheet when the window is `max-width: 450px or max-height: 360px` — see
`adw-dialog.c`), so every dialog parented to this window is a centered floating
card rather than a sheet docked to the bottom edge.
- **The invariant: the main window is presentable exactly when the responder can
serve prompts.** The approval dialogs are parented to the main window, so a
request must never arrive without it. With no keys there is nothing to sign
@@ -806,20 +810,24 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
(mode **0600**, written atomically to a **unique** `tempfile::NamedTempFile`
and renamed over the target, a corrupt file moved to a timestamped
`keys.json.corrupt.<secs>.<nanos>` so a second corruption does not erase the
first). It holds `version`, an optional plaintext `device` nsec,
and `keys: [{pubkey, name, ncryptsec}]`. A `version` **above 1** is refused
**in place** (left on disk, not quarantined — a newer vault is intact, not
corrupt), so an older Regent never silently downgrades it. There is **no
Secret Service and no
first). It holds `version`, an optional plaintext `device` nsec, an optional
`verifier` (present **only while the vault has no keys** — see the first-run
bullet below), and `keys: [{pubkey, name, ncryptsec}]`. A `version` **above 1**
is refused **in place** (left on disk, not quarantined — a newer vault is
intact, not corrupt), so an older Regent never silently downgrades it. (The
verifier did **not** need a version bump: serde ignores the unknown field, so an
older Regent reads a verifier-only vault as empty — it can then set a fresh
passphrase and drop the verifier, which loses nothing because there were no
keys. Accepted.) There is **no Secret Service and no
`oo7`** dependency: the login keyring was never at-rest protection (unlocked at
login for the whole session, keyed off the login password). The data, config
and cache directories — and the lock file's directory — are created **0700**
through the shared `store::create_private_dir` (L6), not with the process umask.
- **Vault mutations are serialized (M9).** `add_user_key` and `change_passphrase`
hold a `tokio::sync::Mutex` (`writes`) across their whole body, because each
encrypts and then updates state — interleaved, they could write a key under the
old passphrase beside keys re-encrypted under the new one, producing a vault no
passphrase opens. `save()` additionally holds a `std::sync::Mutex`
- **Vault mutations are serialized (M9).** `add_user_key`, `set_passphrase` and
`change_passphrase` hold a `tokio::sync::Mutex` (`writes`) across their whole
body, because each encrypts and then updates state — interleaved, they could
write a key under the old passphrase beside keys re-encrypted under the new one,
producing a vault no passphrase opens. `save()` additionally holds a `std::sync::Mutex`
(`save_lock`, never across an `await`) across read-clone → write → rename, and
the temp file is unique, so concurrent saves cannot collide on a shared
`keys.json.tmp`. (`profiles.json` uses the same unique-temp write.)
@@ -840,10 +848,28 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
other machines, backups), it enables offline scrypt attack on every backed-up
copy, and it pays a synchronous scrypt (~70 ms and 64 MiB at `log_n` 16) on
every request — a 100-event burst would be ~7 s of one core.
- **`add_user_key` verifies the passphrase** against an existing entry before
writing, so a typo cannot quietly create a second passphrase that opens only
the new key. `change_passphrase` needs only the *new* one (we hold the keys)
and re-encrypts every entry. `rename`/`forget` need no passphrase at all.
- **The first-run onboarding sets the passphrase before any key exists**, which is
what the optional `verifier` is for. `set_passphrase` (the "Set a passphrase"
step, and its keyless "Reset passphrase…" — the reset is allowed only while no
key is stored, where it loses nothing) encrypts a **fixed public constant**
(`VAULT_VERIFIER`, a 32-byte `SecretKey` because `EncryptedSecretKey::new`
takes one) under the passphrase and stores the `ncryptsec1…` string, then opens
the session through the ordinary `unlock`. `has_vault()` is
`verifier.is_some() || !keys.is_empty()`; `verify_passphrase` checks the first
**key** if one exists, else the **verifier**, else returns `Ok` (that last is
load-bearing for `generate_user_key` on a scratch store / headless, and
unreachable in the UI). `unlock` with no keys verifies the verifier, so a wrong
passphrase still fails. `add_user_key` **clears the verifier** as it stores the
first key: with a key, the key is the ground truth and the on-disk shape is
byte-for-byte the pre-onboarding one. A malformed verifier is dropped on load
(logged, not fatal) so the reset path stays reachable.
- **`add_user_key` verifies the passphrase** against the verifier or an existing
entry before writing, so a typo cannot quietly create a second passphrase that
opens only the new key. `change_passphrase` needs only the *new* one (we hold
the keys), re-encrypts every entry, and **re-encrypts the verifier too** when
one is present — its plaintext is the public constant, so this needs no old
passphrase, and without it the change would be a silent no-op on a keyless
vault. `rename`/`forget` need no passphrase at all.
**The unlocked vault is the authorisation (L3):** both `change_passphrase` and
`export_user_key_encrypted` refuse a locked vault and require no re-entry of the
current passphrase while it is open. That is deliberate — the control is the
@@ -884,10 +910,16 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
lock row that **toggles with the vault's state**: unlocked it offers "Lock",
locked it offers "Unlock…" through the same `present_unlock` dialog the header
button uses — which is what lets a locked user reach "Change…" without leaving
Preferences. It is inert until a key (and so a passphrase) exists. The
identities window's add/import dialogs carry the passphrase field
(with a confirmation only when that call *sets* the passphrase). Export needs
the vault open first (`with_unlocked`).
Preferences. It is inert until a passphrase exists (a key, or the first-run
onboarding's verifier). **The identities window's first-run empty state is a
"Set up your vault" step** (`present_setup`, passphrase + confirmation) whose
only action sets the passphrase; the page only offers Create / Import once
`has_vault()` is true, and those dialogs then carry a **single** "Vault
passphrase" row (no confirmation — there is nothing to set, only to check, and
retyping it when the first key is added is the point). A quiet "Reset
passphrase…" on that keyless page reopens the same setup dialog (the store
allows an overwrite while no key is stored). Export needs the vault open first
(`with_unlocked`).
- **Export and import hygiene (L2).** The export password is always confirmed
and at least 8 characters (`PassphraseFields::export`; the pure
`validate_passphrase` is unit-tested), so an accidental empty submit cannot
@@ -895,6 +927,22 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
(masked), so a pasted `nsec` is not shown in cleartext. `plain::copy_secret`
copies an exported `ncryptsec` or a `bunker://` string and clears the
clipboard again after 60 s **if it still holds that value**.
- **The passphrase forms are action dialogs, not alert dialogs (HIG).**
`present_setup` / `present_create` / `present_import` are plain `AdwDialog`s
with a header bar, a bottom bar (Cancel + a suggested action) and an
`AdwToastOverlay`, because **an `AdwAlertDialog` always closes when a response
is activated** — the old forms vanished and opened a second "Something went
wrong" modal on a bad passphrase, with no way to keep them open. The action
starts **insensitive** and is re-evaluated on every keystroke
(`PassphraseFields::review`), which also marks the offending row with
libadwaita's `.error` validation class, so a too-short or mismatched passphrase
can never be submitted and needs no error message at all. Only an error that
cannot be known in advance — a wrong vault passphrase — is shown, as a **toast
inside the dialog** (a window toast would sit behind the dialog's scrim);
`AdwToast` renders markup by default, so it is built with `set_use_markup(false)`.
Return activates the action (`AdwDialog:default-widget` + the rows'
`activates-default`); `connect_closed` wipes the fields, and a failed submit
keeps them (L5). Do not "simplify" these back to `AdwAlertDialog`.
- **Never log, print or put the passphrase in argv/env.** The passphrase is
`Zeroizing` where it crosses the vault and the headless path, and is dropped as
soon as the unlock lands. The GTK dialogs now **clear their entry rows** on
+4 -1
View File
@@ -3,7 +3,10 @@ using Adw 1;
Adw.ApplicationWindow keys_window {
title: "Identities";
default-width: 420;
// Wider than libadwaita's 450px bottom-sheet threshold (`max-width: 450px`),
// so dialogs parented to this window present as centered floating cards rather
// than sheets docked to the bottom edge. See `adw-dialog.c`.
default-width: 460;
default-height: 560;
content: Adw.ToolbarView toolbar_view {
+321 -30
View File
@@ -17,6 +17,13 @@
//! instead of the keys would be strictly worse: `keys.json` is readable on disk,
//! so a memory dump holding it decrypts every entry, and it is the reusable
//! secret — reused across exports, other clients, other machines and backups.
//!
//! A passphrase can be set **before any key exists** (the first-run onboarding):
//! that is what the optional **verifier** is for. It is a NIP-49 encryption of a
//! fixed public constant ([`VAULT_VERIFIER`]), so a correct passphrase decrypts
//! and a wrong one fails; it is cleared the moment the first key is stored, at
//! which point the key itself is the ground truth and the on-disk shape is
//! exactly what it has always been.
use std::collections::HashMap;
use std::path::PathBuf;
@@ -37,6 +44,17 @@ const VAULT_LOG_N: u8 = 16;
/// NIP-49 `log_n` for an export the user picks a password for.
const EXPORT_LOG_N: u8 = 16;
/// The plaintext the vault verifier encrypts, so a passphrase can be set and
/// checked **before any identity key exists**.
///
/// It is a fixed, public constant: NIP-49 authenticates the ciphertext, so a
/// correct passphrase decrypts and a wrong one fails — the value itself is never
/// used. It has to be a valid 32-byte secp256k1 secret because
/// [`EncryptedSecretKey::new`] takes a [`SecretKey`] (`b"regent vault verifier"`
/// is 21 bytes, zero-padded to 32; as a big-endian integer it is far below the
/// curve order and nonzero).
const VAULT_VERIFIER: [u8; 32] = *b"regent vault verifier\0\0\0\0\0\0\0\0\0\0\0";
/// Label used for a key that was stored without a name.
pub const UNNAMED: &str = "Identity key";
@@ -69,13 +87,25 @@ struct Vault {
/// The NIP-46 transport key, deliberately plaintext. See the module docs.
#[serde(default, skip_serializing_if = "Option::is_none")]
device: Option<String>,
/// NIP-49 ciphertext of [`VAULT_VERIFIER`], present only while the vault has
/// **no** identity keys. It is what makes a passphrase settable (and
/// checkable) before the first key; it is cleared once a key is stored, so a
/// keyed vault is byte-for-byte the shape it has always been.
///
/// Kept as a bech32 string, not a parsed `EncryptedSecretKey`: a malformed
/// value is dropped on load (`at`) rather than failing the whole file into
/// quarantine.
#[serde(default, skip_serializing_if = "Option::is_none")]
verifier: Option<String>,
#[serde(default)]
keys: Vec<StoredKey>,
}
/// Metadata and the parsed device key. Never an identity secret.
/// Metadata, the parsed device key, and the still-encrypted verifier. Never an
/// identity secret.
struct State {
device: Option<Keys>,
verifier: Option<String>,
keys: Vec<StoredKey>,
}
@@ -168,10 +198,26 @@ impl KeyStore {
.transpose()
.map_err(|error| format!("the stored device key is invalid: {error}"))?;
// A malformed verifier is logged and dropped, not fatal: it guards
// nothing while the vault is keyless, and refusing to load would close
// the "reset passphrase" path that is the way back. (Storing it as a
// parsed `EncryptedSecretKey` would instead fail the whole file into
// quarantine over one decorative value.)
let verifier = vault.verifier.filter(|encoded| {
match EncryptedSecretKey::from_bech32(encoded) {
Ok(_) => true,
Err(error) => {
eprintln!("regent: ignoring an unreadable vault verifier: {error}");
false
}
}
});
Ok(Self {
path,
state: Mutex::new(State {
device,
verifier,
keys: vault.keys,
}),
unlocked: Mutex::new(None),
@@ -201,13 +247,15 @@ impl KeyStore {
keys
}
/// Whether there is a passphrase to open: true once a key is stored.
/// Whether a passphrase has been set: true once a key is stored, **or** once
/// the keyless onboarding set one (the verifier).
pub fn has_vault(&self) -> bool {
!self.state.lock().unwrap().keys.is_empty()
let state = self.state.lock().unwrap();
state.verifier.is_some() || !state.keys.is_empty()
}
/// Whether the vault still needs the passphrase. An empty vault is never
/// "locked": there is nothing to protect yet.
/// Whether the vault still needs the passphrase. A vault with neither a key
/// nor a verifier is never "locked": no passphrase exists yet.
pub fn is_locked(&self) -> bool {
self.has_vault() && self.unlocked.lock().unwrap().is_none()
}
@@ -217,16 +265,57 @@ impl KeyStore {
*self.unlocked_at.lock().unwrap()
}
/// Set the vault passphrase before the first identity key exists.
///
/// Allowed **only while no key is stored** (that is also what makes it the
/// "forgot the passphrase" reset, which loses nothing). It writes the
/// verifier and then opens the session through the ordinary [`Self::unlock`]
/// path, so a session is never left in a state only this method knows about.
pub async fn set_passphrase(&self, passphrase: &str) -> Result<()> {
let _write = self.writes.lock().await;
if !self.state.lock().unwrap().keys.is_empty() {
return Err("the vault already holds identity keys".into());
}
let passphrase = Zeroizing::new(passphrase.to_string());
let for_task = passphrase.clone();
let verifier = tokio::task::spawn_blocking(move || encrypt_verifier(for_task.as_str()))
.await
.map_err(|error| format!("the passphrase task failed: {error}"))??;
self.state.lock().unwrap().verifier = Some(verifier);
self.save()?;
// The passphrase is in hand: leave the session open, exactly as adding a
// key does.
self.unlock(passphrase.as_str()).await
}
/// Open the vault, decrypting every identity key.
///
/// The passphrase is used here and dropped; a wrong one fails on the first
/// entry (NIP-49 authenticates the ciphertext).
/// entry (NIP-49 authenticates the ciphertext). With no keys stored, the
/// verifier is what tells a right passphrase from a wrong one; with neither,
/// the vault has no passphrase yet and this is a no-op.
pub async fn unlock(&self, passphrase: &str) -> Result<()> {
let entries = self.state.lock().unwrap().keys.clone();
let (entries, verifier) = {
let state = self.state.lock().unwrap();
(state.keys.clone(), state.verifier.clone())
};
let passphrase = Zeroizing::new(passphrase.to_string());
let keys = tokio::task::spawn_blocking(move || decrypt_all(&entries, &passphrase))
.await
.map_err(|error| format!("the unlock task failed: {error}"))??;
let keys = tokio::task::spawn_blocking(move || {
if entries.is_empty() {
if let Some(ciphertext) = verifier.as_deref() {
EncryptedSecretKey::from_bech32(ciphertext)
.and_then(|encrypted| encrypted.decrypt(passphrase.as_str()))?;
}
Ok::<_, Error>(HashMap::new())
} else {
decrypt_all(&entries, &passphrase)
}
})
.await
.map_err(|error| format!("the unlock task failed: {error}"))??;
*self.unlocked.lock().unwrap() = Some(Unlocked { keys });
*self.unlocked_at.lock().unwrap() = Some(boottime());
@@ -306,8 +395,20 @@ impl KeyStore {
let ncryptsec = Zeroizing::new(ncryptsec.trim().to_string());
let import_password = Zeroizing::new(import_password.to_string());
let keys = tokio::task::spawn_blocking(move || {
let encrypted = EncryptedSecretKey::from_bech32(ncryptsec.as_str())?;
Ok::<_, Error>(Keys::new(encrypted.decrypt(import_password.as_str())?))
let encrypted = EncryptedSecretKey::from_bech32(ncryptsec.as_str())
.map_err(|error| format!("That is not a valid ncryptsec: {error}"))?;
let secret = encrypted
.decrypt(import_password.as_str())
.map_err(|error| match error.kind() {
// NIP-49 authenticates the ciphertext, so on a well-formed
// `ncryptsec` a crypto failure means the password is wrong —
// and the raw error is an opaque `aead::Error`.
ErrorKind::Crypto => "Wrong ncryptsec password.".to_string(),
// Anything else (e.g. an unsupported/tampered `log_n`) is not
// a password problem.
_ => format!("Could not open the ncryptsec: {error}"),
})?;
Ok::<_, Error>(Keys::new(secret))
})
.await
.map_err(|error| format!("the import task failed: {error}"))??;
@@ -370,11 +471,17 @@ impl KeyStore {
/// Re-encrypt every key under a new passphrase.
///
/// Only possible while unlocked — we hold the decrypted keys, so the *old*
/// passphrase is not needed. Serialized with `add_user_key` behind the
/// `writes` mutex, so a key being added cannot be written under the old
/// passphrase beside keys re-encrypted under the new one (M9).
/// passphrase is not needed. The **verifier** (present only while the vault
/// is keyless) is re-encrypted under the same new passphrase: it is the only
/// thing that guards a keyless vault, so leaving it under the old passphrase
/// would make the new one fail on the next add. Its plaintext is the public
/// [`VAULT_VERIFIER`] constant, so no old passphrase is needed for it.
/// Serialized with `add_user_key` behind the `writes` mutex, so a key being
/// added cannot be written under the old passphrase beside keys re-encrypted
/// under the new one (M9).
pub async fn change_passphrase(&self, new_passphrase: &str) -> Result<()> {
let _write = self.writes.lock().await;
let had_verifier = self.state.lock().unwrap().verifier.is_some();
let keys: Vec<(PublicKey, Keys)> = {
let unlocked = self.unlocked.lock().unwrap();
let unlocked = unlocked
@@ -388,8 +495,9 @@ impl KeyStore {
};
let passphrase = Zeroizing::new(new_passphrase.to_string());
let re_encrypted = tokio::task::spawn_blocking(move || {
keys.into_iter()
let (re_encrypted, verifier) = tokio::task::spawn_blocking(move || {
let re_encrypted = keys
.into_iter()
.map(|(public_key, keys)| {
let encrypted = EncryptedSecretKey::new(
keys.secret_key(),
@@ -399,7 +507,13 @@ impl KeyStore {
)?;
Ok::<_, Error>((public_key, encrypted.to_bech32()?))
})
.collect::<Result<Vec<_>>>()
.collect::<Result<Vec<_>>>()?;
let verifier = if had_verifier {
Some(encrypt_verifier(passphrase.as_str())?)
} else {
None
};
Ok::<_, Error>((re_encrypted, verifier))
})
.await
.map_err(|error| format!("the re-encrypt task failed: {error}"))??;
@@ -415,6 +529,9 @@ impl KeyStore {
entry.ncryptsec = ncryptsec.clone();
}
}
if let Some(verifier) = verifier {
state.verifier = Some(verifier);
}
}
// The cache still holds the same keys, so the session stays unlocked.
self.save()
@@ -455,6 +572,10 @@ impl KeyStore {
name: name.to_string(),
ncryptsec,
});
// The verifier only ever held the passphrase before a key existed.
// With a key stored the key is the ground truth, so a keyed vault
// keeps exactly the shape it has always had.
state.verifier = None;
}
self.save()?;
@@ -462,15 +583,29 @@ impl KeyStore {
self.unlock(passphrase.as_str()).await
}
/// Refuse a passphrase that does not open the existing vault. A vault with
/// no keys yet accepts anything: that call is what sets the passphrase.
/// Refuse a passphrase that does not open the existing vault.
///
/// The check is the first stored **key** if there is one, else the
/// **verifier** (the keyless onboarding's passphrase). With neither — a
/// truly fresh vault — it returns `Ok`: that is the load-bearing fallback
/// that lets `generate_user_key` work directly on a scratch store in tests
/// and headless. In the UI it is unreachable, because create/import only
/// exist on the "empty" page, which requires `has_vault()`.
async fn verify_passphrase(&self, passphrase: &str) -> Result<()> {
let Some(entry) = self.state.lock().unwrap().keys.first().cloned() else {
let ciphertext = {
let state = self.state.lock().unwrap();
state
.keys
.first()
.map(|entry| entry.ncryptsec.clone())
.or_else(|| state.verifier.clone())
};
let Some(ciphertext) = ciphertext else {
return Ok(());
};
let passphrase = Zeroizing::new(passphrase.to_string());
let opens = tokio::task::spawn_blocking(move || {
EncryptedSecretKey::from_bech32(&entry.ncryptsec)
EncryptedSecretKey::from_bech32(&ciphertext)
.and_then(|encrypted| encrypted.decrypt(passphrase.as_str()))
.is_ok()
})
@@ -480,7 +615,7 @@ impl KeyStore {
if opens {
Ok(())
} else {
Err("that passphrase does not open this vault".into())
Err("Wrong vault passphrase.".into())
}
}
@@ -495,18 +630,19 @@ impl KeyStore {
return Ok(());
}
let _guard = self.save_lock.lock().unwrap();
let (device, keys) = {
let (device, verifier, keys) = {
let state = self.state.lock().unwrap();
let device = state
.device
.as_ref()
.map(|keys| keys.secret_key().to_bech32())
.transpose()?;
(device, state.keys.clone())
(device, state.verifier.clone(), state.keys.clone())
};
let vault = Vault {
version: 1,
device,
verifier,
keys,
};
@@ -603,6 +739,18 @@ fn decrypt_all(entries: &[StoredKey], passphrase: &str) -> Result<HashMap<Public
Ok(keys)
}
/// Encrypt the fixed [`VAULT_VERIFIER`] constant under `passphrase`, for storage
/// as the vault's keyless-passphrase check.
///
/// The value is a public constant, so this needs no old passphrase — which is
/// what lets `change_passphrase` move the verifier without holding the old one.
fn encrypt_verifier(passphrase: &str) -> Result<String> {
let secret = SecretKey::from_slice(&VAULT_VERIFIER)
.expect("the vault verifier constant is a valid 32-byte secret key");
let encrypted = EncryptedSecretKey::new(&secret, passphrase, VAULT_LOG_N, KeySecurity::Medium)?;
Ok(encrypted.to_bech32()?)
}
/// A unique name for a quarantined unreadable vault.
///
/// Sub-second precision (or the pid) so a second corruption does not rename over
@@ -750,7 +898,7 @@ mod tests {
.import_user_key("Sneaky", &keys.secret_key().to_bech32().unwrap(), "typo")
.await
.expect_err("a second passphrase must not be accepted");
assert!(error.to_string().contains("does not open"));
assert!(error.to_string().contains("vault passphrase"));
// Nothing was written, and the vault still opens with the real one.
store.lock();
@@ -821,11 +969,13 @@ mod tests {
.await
.expect("import");
assert_eq!(imported, key);
let error = store
.import_user_key_encrypted("Backup", &ncryptsec, "wrong", "hunter2")
.await
.expect_err("a wrong ncryptsec password fails");
assert!(
store
.import_user_key_encrypted("Backup", &ncryptsec, "wrong", "hunter2")
.await
.is_err()
error.to_string().contains("ncryptsec password"),
"the raw crypto error must not leak: {error}"
);
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
@@ -848,6 +998,147 @@ mod tests {
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// Setting a passphrase before any key exists is what the first-run
/// onboarding does: the vault exists (as a verifier), holds no keys, and can
/// be unlocked — and refuses a wrong passphrase — without one.
#[tokio::test]
async fn setting_a_passphrase_makes_a_keyless_vault() {
let (path, store) = scratch();
assert!(!store.has_vault(), "a fresh vault has no passphrase");
store.set_passphrase("hunter2").await.expect("set");
assert!(store.has_vault(), "the verifier is the vault now");
assert!(store.list_user_keys().is_empty(), "still no identity key");
assert!(!store.is_locked(), "setting it opens the session");
// The verifier is NIP-49, exactly like the keys.
let json: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
assert!(json["verifier"]
.as_str()
.unwrap()
.starts_with("ncryptsec1"));
store.lock();
assert!(store.is_locked());
assert!(store.unlock("wrong").await.is_err(), "a wrong passphrase fails");
assert!(store.unlock("hunter2").await.is_ok());
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// The point of the separate step: adding the first key asks for the
/// passphrase again, checked against the verifier.
#[tokio::test]
async fn the_first_key_must_retype_the_vault_passphrase() {
let (path, store) = scratch();
store.set_passphrase("hunter2").await.expect("set");
let keys = Keys::generate();
let secret = keys.secret_key().to_bech32().unwrap();
let error = store
.import_user_key("Sneaky", &secret, "typo")
.await
.expect_err("the verifier must refuse a wrong passphrase");
assert!(error.to_string().contains("vault passphrase"), "got: {error}");
assert!(store.list_user_keys().is_empty(), "nothing was stored");
let added = store
.import_user_key("Work", &secret, "hunter2")
.await
.expect("the right passphrase adds the key");
assert_eq!(added, keys.public_key());
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// A keyed vault is the shape it has always been: the verifier is cleared,
/// and the key is what the passphrase is checked against.
#[tokio::test]
async fn a_key_drops_the_verifier() {
let (path, store) = scratch();
store.set_passphrase("hunter2").await.expect("set");
store.generate_user_key("Work", "hunter2").await.expect("generate");
let json: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
assert!(json.get("verifier").is_none(), "the verifier is cleared: {json}");
store.lock();
assert!(store.unlock("wrong").await.is_err());
assert!(store.unlock("hunter2").await.is_ok());
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// Once a key is stored, setting the passphrase again is refused: it is no
/// longer a harmless reset, it would strand the key.
#[tokio::test]
async fn resetting_is_refused_once_a_key_exists() {
let (path, store) = scratch();
store.generate_user_key("Work", "hunter2").await.expect("generate");
let error = store
.set_passphrase("other")
.await
.expect_err("a keyed vault must refuse a reset");
assert!(error.to_string().contains("already holds"), "got: {error}");
store.lock();
assert!(store.unlock("hunter2").await.is_ok());
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// Changing the passphrase on a keyless vault moves the verifier too, so the
/// change is not a silent no-op: the next add accepts the new one, not the
/// old one.
#[tokio::test]
async fn changing_the_passphrase_moves_the_keyless_verifier() {
let (path, store) = scratch();
store.set_passphrase("old").await.expect("set");
store.change_passphrase("new").await.expect("change");
let json: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
assert!(json.get("verifier").is_some(), "still a keyless vault");
store.lock();
assert!(store.unlock("old").await.is_err(), "the old one stops working");
assert!(store.unlock("new").await.is_ok());
let keys = Keys::generate();
let secret = keys.secret_key().to_bech32().unwrap();
assert!(store.import_user_key("Work", &secret, "old").await.is_err());
assert!(store.import_user_key("Work", &secret, "new").await.is_ok());
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// Removing the last key disbands the vault back to the first-run setup
/// state: with no key and no verifier there is no passphrase.
#[tokio::test]
async fn removing_the_last_key_returns_to_the_setup_state() {
let (path, store) = scratch();
store.set_passphrase("hunter2").await.expect("set");
let key = store.generate_user_key("Work", "hunter2").await.expect("generate");
assert!(store.has_vault());
store.forget_user_key(&key).expect("forget");
assert!(!store.has_vault(), "no key and no verifier: no vault");
assert!(store.list_user_keys().is_empty());
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// A hand-edited, unreadable verifier is dropped rather than quarantining
/// the whole file, so the "reset passphrase" path stays reachable.
#[tokio::test]
async fn an_unreadable_verifier_is_dropped_not_fatal() {
let (path, _store) = scratch();
std::fs::create_dir_all(path.parent().unwrap()).expect("dir");
std::fs::write(&path, br#"{"version":1,"verifier":"ncryptsec1notreally"}"#)
.expect("write a bad verifier");
let reopened = KeyStore::at(path.clone()).expect("the file still opens");
assert!(!reopened.has_vault(), "the bad verifier is ignored");
reopened.set_passphrase("hunter2").await.expect("reset over it");
assert!(reopened.has_vault());
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// A hand-edited entry must not let Regent sign as a different identity than
/// the one it lists and resolves.
#[tokio::test]
+502 -95
View File
@@ -5,12 +5,14 @@
//! nothing to listen for until a key exists — and afterwards it lives in its own
//! window, reached from the identity switcher.
//!
//! Choosing which identity is *current* (the default for new pairings) is the
//! header switcher's job, not this window's. The vault's passphrase, its
//! auto-lock timeout and the device key are not key *management* and live in
//! Preferences (`ui/preferences.rs`).
//! On first run the **passphrase comes first**: the empty state is a "set up
//! your vault" step, and only once it is set does the page offer Create / Import
//! (which then just *check* the passphrase). Choosing which identity is *current*
//! (the default for new pairings) is the header switcher's job, not this
//! window's. The auto-lock timeout and the device key are not key *management*
//! and live in Preferences (`ui/preferences.rs`).
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
@@ -62,6 +64,25 @@ impl KeysView {
pub fn new(state: Rc<AppState>) -> Self {
let stack = gtk::Stack::builder().vexpand(true).build();
// First run, before a passphrase is set: one step, and the only thing on
// screen. Keys are added afterwards (the "empty" page below).
let set_up = gtk::Button::builder()
.label("Set a passphrase")
.css_classes(["pill", "suggested-action"])
.halign(gtk::Align::Center)
.build();
let setup = adw::StatusPage::builder()
.icon_name("security-high-symbolic")
.title("Set up your vault")
.description(
"Your identity keys are stored encrypted under one passphrase, which you \
will need to sign. Choose it now; you will type it again when you add a key.",
)
.child(&set_up)
.build();
stack.add_named(&setup, Some("setup"));
// A passphrase is set, but no key exists yet.
let create = gtk::Button::builder()
.label("Create a key")
.css_classes(["pill", "suggested-action"])
@@ -70,12 +91,25 @@ impl KeysView {
.label("Import a key…")
.css_classes(["pill"])
.build();
let actions = gtk::Box::builder()
let actions_row = gtk::Box::builder()
.spacing(12)
.halign(gtk::Align::Center)
.build();
actions.append(&create);
actions.append(&import);
actions_row.append(&create);
actions_row.append(&import);
// A quiet way back if the passphrase just set was forgotten: no key is
// stored yet, so setting another one loses nothing.
let reset = gtk::Button::builder()
.label("Reset passphrase…")
.css_classes(["flat"])
.build();
let actions = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(12)
.halign(gtk::Align::Center)
.build();
actions.append(&actions_row);
actions.append(&reset);
let empty = adw::StatusPage::builder()
.icon_name("security-high-symbolic")
.title("No key yet")
@@ -137,6 +171,12 @@ impl KeysView {
let (state, handles) = (Rc::clone(&state), handles.clone());
button.connect_clicked(move |_| present_import(handles.clone(), Rc::clone(&state)));
}
// The setup step and its keyless "forgot it" reset are the same dialog:
// both just set the passphrase (the store refuses it once a key exists).
for button in [&set_up, &reset] {
let (state, handles) = (Rc::clone(&state), handles.clone());
button.connect_clicked(move |_| present_setup(handles.clone(), Rc::clone(&state)));
}
// Reload on key changes (`refresh_identities` announces them with
// `notify`). The selection no longer shows here, so a registry change is
@@ -171,7 +211,13 @@ fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows, live: &LiveRows)
let names = names.lock().unwrap().clone();
if names.is_empty() {
handles.stack.set_visible_child_name("empty");
// No key: either the passphrase has not been set yet (the setup step) or
// it has (add the first key).
if state.store().has_vault() {
handles.stack.set_visible_child_name("empty");
} else {
handles.stack.set_visible_child_name("setup");
}
return;
}
handles.stack.set_visible_child_name("loaded");
@@ -352,30 +398,42 @@ fn key_row(state: &Rc<AppState>, handles: &Handles, live: &LiveRows, hex: &str)
row
}
/// A passphrase field for the add/import dialogs, plus a confirmation when this
/// is the call that *sets* the vault passphrase.
/// A passphrase field for the vault dialogs: [`Self::setting`] for the first-run
/// setup (with a confirmation), [`Self::vault`] for the add/import dialogs and
/// [`Self::export`] for a backup password.
///
/// `Clone` shares the same rows (they are GObjects): the live-validation closure
/// and the submit closure need handles to the same widgets.
#[derive(Clone)]
struct PassphraseFields {
passphrase: adw::PasswordEntryRow,
confirm: Option<adw::PasswordEntryRow>,
}
impl PassphraseFields {
fn new(first: bool) -> Self {
let passphrase = adw::PasswordEntryRow::builder()
.title(if first {
"Choose a passphrase"
} else {
"Vault passphrase"
})
.build();
let confirm = first.then(|| {
adw::PasswordEntryRow::builder()
.title("Confirm passphrase")
.build()
});
/// Setting the vault passphrase, before any key exists: confirmed, because
/// there is nothing to check it against yet.
fn setting() -> Self {
Self {
passphrase,
confirm,
passphrase: adw::PasswordEntryRow::builder()
.title("Choose a passphrase")
.build(),
confirm: Some(
adw::PasswordEntryRow::builder()
.title("Confirm passphrase")
.build(),
),
}
}
/// An already-set vault: one field, checked against the verifier (or, once a
/// key exists, against the key).
fn vault() -> Self {
Self {
passphrase: adw::PasswordEntryRow::builder()
.title("Vault passphrase")
.build(),
confirm: None,
}
}
@@ -416,6 +474,65 @@ impl PassphraseFields {
confirm.set_text("");
}
}
/// Run `f` on every keystroke in either field, for live validation.
fn connect_changed(&self, f: impl Fn() + 'static) {
let f = Rc::new(f);
{
let f = Rc::clone(&f);
self.passphrase.connect_changed(move |_| f());
}
if let Some(confirm) = &self.confirm {
let f = Rc::clone(&f);
confirm.connect_changed(move |_| f());
}
}
/// Re-evaluate the pair, mark the offending row with the `.error` style
/// class, and report whether it is ready to submit.
///
/// Same rules as [`validate_passphrase`], in widget form (this one needs to
/// know *which* row is at fault); keep the two edited together, and the
/// submit-time [`Self::value`] guard is the backstop.
///
/// The affirmative action is insensitive until this is `true` (the HIG's
/// rule for an action dialog) — which is what removes the "error modal" for
/// a too-short or mismatched passphrase entirely: it can never be submitted.
/// An **empty** field is never marked: only a wrong entry is an error, not
/// an unfinished one (HIG: avoid negative feedback while editing).
fn review(&self) -> bool {
let passphrase = self.passphrase.text().to_string();
let short = passphrase.chars().count() < 8;
set_field_error(&self.passphrase, short && !passphrase.is_empty());
let mismatch = match &self.confirm {
Some(confirm) => {
let typed = confirm.text().to_string();
let differs = typed != passphrase;
set_field_error(confirm, differs && !typed.is_empty());
differs
}
None => false,
};
!short && !mismatch
}
/// Let Return in a field activate the dialog's action, as the HIG asks.
fn set_activates_default(&self) {
self.passphrase.set_activates_default(true);
if let Some(confirm) = &self.confirm {
confirm.set_activates_default(true);
}
}
}
/// Toggle libadwaita's `.error` style class — its affordance for a field whose
/// input failed validation (the row's title and text take the error colour).
fn set_field_error(row: &impl IsA<gtk::Widget>, error: bool) {
if error {
row.add_css_class("error");
} else {
row.remove_css_class("error");
}
}
/// Validate a passphrase/confirmation pair. Pure so it is testable without
@@ -432,20 +549,253 @@ fn validate_passphrase(passphrase: &str, confirm: Option<&str>) -> Result<String
Ok(passphrase.to_string())
}
/// The vault is opened for these dialogs; an import that sets the passphrase
/// explains the risk.
/// Explains the vault passphrase on the first-run setup dialog. The add/import
/// dialogs no longer set it — they only check it — so this is a note about the
/// one step that creates it.
const NEW_VAULT_NOTE: &str = "Choose a passphrase for the key vault. Every identity key is \
stored encrypted under it, and it is needed to sign. There is no recovery if you forget it.";
/// An **action dialog** (the HIG's type for a form) for the passphrase dialogs.
///
/// `AdwAlertDialog` closes whenever a response is activated, which is why these
/// forms used to disappear and open a second "Something went wrong" modal on an
/// invalid passphrase. Here the action is an ordinary button on a plain
/// `AdwDialog`, so a failed submit leaves the form — and the typed input — on
/// screen.
///
/// Validation follows the HIG: the action starts **insensitive**, the caller
/// re-evaluates it on every keystroke (see [`PassphraseFields::review`]), and an
/// error that cannot be known in advance (a wrong vault passphrase) is shown as
/// a toast **inside** the dialog — a toast added to the window would sit behind
/// the dialog's scrim.
struct FormDialog {
dialog: adw::Dialog,
overlay: adw::ToastOverlay,
action: gtk::Button,
/// The caller's live validity verdict, and whether an async submit is in
/// flight. The action is sensitive only when **both** permit it: live
/// validation keeps firing on every keystroke during a submit, so it must not
/// be able to re-enable the action over an in-flight operation (a second
/// `create` would generate a second key).
valid: Cell<bool>,
busy: Cell<bool>,
}
impl FormDialog {
/// Build the chrome — a header bar, a bottom bar with Cancel and an
/// insensitive suggested action — around a `boxed-list` form and a note.
fn new(title: &str, note: &str, form: &gtk::ListBox, action_label: &str) -> Self {
let header = adw::HeaderBar::new();
header.set_title_widget(Some(&adw::WindowTitle::new(title, "")));
let cancel = gtk::Button::with_label("Cancel");
let action = gtk::Button::builder()
.label(action_label)
// Insensitive until the form is valid: the HIG's rule for an action
// dialog, and what makes a too-short passphrase unsubmittable.
.sensitive(false)
.css_classes(["suggested-action"])
.build();
// Equal-width buttons spanning the footer, like an `AdwAlertDialog`'s
// response area: a natural-width right-aligned pair looked cramped and
// unfinished. The spacing and padding copy that response area
// (`padding: 24px`, `padding-top: 12px`, `border-spacing: 12px`).
let buttons = gtk::Box::builder()
.orientation(gtk::Orientation::Horizontal)
.homogeneous(true)
.spacing(12)
.margin_top(12)
.margin_bottom(24)
.margin_start(24)
.margin_end(24)
.build();
buttons.append(&cancel);
buttons.append(&action);
let content = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(18)
.margin_top(18)
.margin_bottom(18)
.margin_start(12)
.margin_end(12)
.build();
let note = plain::label(note);
note.add_css_class("dim-label");
content.append(&note);
content.append(form);
let overlay = adw::ToastOverlay::new();
overlay.set_child(Some(&content));
let toolbar = adw::ToolbarView::new();
toolbar.add_top_bar(&header);
toolbar.add_bottom_bar(&buttons);
toolbar.set_content(Some(&overlay));
// Pin the width on the child: with `follows_content_size` below, the
// dialog ignores `content-width` (trap 16). 360 fits the 460-wide
// identities window (and leaves a margin when it floats).
toolbar.set_size_request(360, -1);
let dialog = adw::Dialog::builder()
.title(title)
// Track the content: an `AdwDialog` otherwise fixes its size at
// presentation (trap 16), which would clip a row revealed later (the
// import dialog's ncryptsec password).
.follows_content_size(true)
.child(&toolbar)
.build();
// Return activates the action, but only while it is sensitive; the
// entries set `activates-default`, so Enter in a field routes here.
dialog.set_default_widget(Some(&action));
{
let dialog = dialog.clone();
cancel.connect_clicked(move |_| {
dialog.close();
});
}
Self {
dialog,
overlay,
action,
valid: Cell::new(false),
busy: Cell::new(false),
}
}
fn present(&self, parent: Option<&gtk::Window>) {
self.dialog.present(parent);
}
/// Point focus at the first field when the dialog opens.
fn focus(&self, widget: &impl IsA<gtk::Widget>) {
self.dialog.set_focus(Some(widget));
}
fn action(&self) -> &gtk::Button {
&self.action
}
/// The caller's live validity verdict. Stored rather than applied directly:
/// the action's sensitivity is the conjunction with `busy`, so a keystroke
/// during an in-flight submit cannot re-enable it.
fn set_action_enabled(&self, enabled: bool) {
self.valid.set(enabled);
self.apply_sensitivity();
}
/// Mark an async submit in flight (or finished), so a second click or Return
/// cannot start two operations. Clearing it restores the **current** validity,
/// not `true`: the user may have edited the fields meanwhile.
fn set_busy(&self, busy: bool) {
self.busy.set(busy);
self.apply_sensitivity();
}
fn apply_sensitivity(&self) {
self.action
.set_sensitive(self.valid.get() && !self.busy.get());
}
/// Run `f` when the dialog closes, however it closed, so the caller can wipe
/// the typed secrets (L5).
fn connect_closed(&self, f: impl Fn() + 'static) {
self.dialog.connect_closed(move |_| f());
}
/// Show an error as a plain-text toast; the dialog stays open.
fn error(&self, message: &str) {
let toast = adw::Toast::new(message);
// `AdwToast` renders markup by default; our errors must not forge it.
toast.set_use_markup(false);
self.overlay.add_toast(toast);
}
fn close(&self) {
self.dialog.force_close();
}
}
/// Set the vault passphrase, before any key exists. Also the "forgot the
/// passphrase" reset: while nothing is stored there is nothing to lose, so the
/// store lets it overwrite a passphrase the user can no longer remember.
fn present_setup(handles: Handles, state: Rc<AppState>) {
let fields = PassphraseFields::setting();
let list = gtk::ListBox::builder()
.selection_mode(gtk::SelectionMode::None)
.css_classes(["boxed-list"])
.build();
fields.append_to(&list);
fields.set_activates_default();
let form = Rc::new(FormDialog::new(
"Set up your vault",
NEW_VAULT_NOTE,
&list,
"Set passphrase",
));
// Live validation (HIG): the action stays insensitive until the passphrase
// is long enough and confirmed, and the offending field is marked `.error`.
{
let review_form = Rc::clone(&form);
let review_fields = fields.clone();
fields.connect_changed(move || review_form.set_action_enabled(review_fields.review()));
form.set_action_enabled(fields.review());
}
// The typed secrets go when the dialog goes, however it goes (L5).
{
let fields = fields.clone();
form.connect_closed(move || fields.clear());
}
{
let state = Rc::clone(&state);
let form_submit = Rc::clone(&form);
let submit_fields = fields.clone();
form.action().connect_clicked(move |_| {
// The action is sensitive only while valid; guard anyway.
let Ok(passphrase) = submit_fields.value() else {
return;
};
let passphrase = Zeroizing::new(passphrase);
form_submit.set_busy(true);
let after = Rc::clone(&state);
let form_done = Rc::clone(&form_submit);
let store = state.store();
runtime::spawn(
async move { store.set_passphrase(&passphrase).await },
move |result| match result {
// No key was added, so the identity list is unchanged; the
// `notify` is what flips the empty state to the add-a-key one.
Ok(()) => {
after.notify();
form_done.close();
}
Err(error) => {
form_done.set_busy(false);
form_done.error(&error);
}
},
);
});
}
form.present(toplevel(&handles).as_ref());
// The passphrase is this form's first field, so it takes initial focus (HIG:
// focus the component the user is expected to operate first).
form.focus(&fields.passphrase);
}
fn present_create(handles: Handles, state: Rc<AppState>) {
let store = state.store();
let first = !store.has_vault();
// Deliberately empty: a freshly generated key has no profile yet, so there is
// no name to prefill and no invented "Identity 3" to store. Empty means "no
// label", which reads as *Identity key* until a profile is discovered.
let name = adw::EntryRow::builder().title("Name").build();
let fields = PassphraseFields::new(first);
name.set_activates_default(true);
let fields = PassphraseFields::vault();
fields.set_activates_default();
let list = gtk::ListBox::builder()
.selection_mode(gtk::SelectionMode::None)
.css_classes(["boxed-list"])
@@ -453,53 +803,60 @@ fn present_create(handles: Handles, state: Rc<AppState>) {
list.append(&name);
fields.append_to(&list);
let dialog = adw::AlertDialog::builder()
.heading("Create an identity key")
.body(if first {
NEW_VAULT_NOTE
} else {
"The new key is encrypted under your vault passphrase."
})
.extra_child(&list)
.build();
plain::dialog(&dialog);
dialog.add_response("cancel", "Cancel");
dialog.add_response("create", "Create");
dialog.set_default_response(Some("create"));
dialog.set_response_appearance("create", adw::ResponseAppearance::Suggested);
dialog.set_close_response("cancel");
let form = Rc::new(FormDialog::new(
"Create an identity key",
"The new key is encrypted under your vault passphrase.",
&list,
"Create",
));
{
let (handles, state) = (handles.clone(), Rc::clone(&state));
dialog.connect_response(None, move |_, response| {
if response != "create" {
let review_form = Rc::clone(&form);
let review_fields = fields.clone();
fields.connect_changed(move || review_form.set_action_enabled(review_fields.review()));
form.set_action_enabled(fields.review());
}
{
let fields = fields.clone();
form.connect_closed(move || fields.clear());
}
{
let state = Rc::clone(&state);
let form_submit = Rc::clone(&form);
let submit_fields = fields.clone();
let submit_name = name.clone();
form.action().connect_clicked(move |_| {
let Ok(passphrase) = submit_fields.value() else {
return;
}
let passphrase = match fields.value() {
Ok(passphrase) => passphrase,
Err(error) => return report_error(&handles, &error),
};
fields.clear();
let name = submit_name.text().trim().to_string();
let passphrase = Zeroizing::new(passphrase);
let name = name.text().trim().to_string();
form_submit.set_busy(true);
let after = Rc::clone(&state);
let handles = handles.clone();
let form_done = Rc::clone(&form_submit);
let store = Arc::clone(&store);
runtime::spawn(
async move { store.generate_user_key(&name, &passphrase).await },
move |result| match result {
Ok(_) => after.refresh_identities(),
Err(error) => report_error(&handles, &error),
Ok(_) => {
after.refresh_identities();
form_done.close();
}
Err(error) => {
form_done.set_busy(false);
form_done.error(&error);
}
},
);
});
}
dialog.present(toplevel(&handles).as_ref());
form.present(toplevel(&handles).as_ref());
// The Name row is this form's first field.
form.focus(&name);
}
fn present_import(handles: Handles, state: Rc<AppState>) {
let store = state.store();
let first = !store.has_vault();
// Masked: the field accepts an `nsec`/hex private key, which must not be
// shown in cleartext on screen (`AdwPasswordEntryRow` is an `AdwEntryRow`,
@@ -513,7 +870,7 @@ fn present_import(handles: Handles, state: Rc<AppState>) {
// anyway, and a label is only for keys with no discoverable profile.
let name = adw::EntryRow::builder().title("Name").build();
let import_password = adw::PasswordEntryRow::builder()
.title("Password (ncryptsec only)")
.title("ncryptsec password")
.build();
{
let name = name.clone();
@@ -531,61 +888,103 @@ fn present_import(handles: Handles, state: Rc<AppState>) {
*prefilled.borrow_mut() = found;
});
}
let fields = PassphraseFields::new(first);
let fields = PassphraseFields::vault();
fields.set_activates_default();
entry.set_activates_default(true);
name.set_activates_default(true);
import_password.set_activates_default(true);
// The ncryptsec password sits directly under the key field, so the reveal is
// next to what triggered it; it stays hidden (and wiped) unless the pasted
// string is an `ncryptsec` — dead weight for the `nsec`/hex case otherwise.
let set_password_visible: Rc<dyn Fn()> = {
let entry = entry.clone();
let import_password = import_password.clone();
Rc::new(move || {
let encrypted = entry.text().trim().starts_with("ncryptsec1");
import_password.set_visible(encrypted);
if !encrypted {
import_password.set_text("");
}
})
};
set_password_visible();
{
let set_password_visible = Rc::clone(&set_password_visible);
entry.connect_changed(move |_| set_password_visible());
}
let list = gtk::ListBox::builder()
.selection_mode(gtk::SelectionMode::None)
.css_classes(["boxed-list"])
.build();
list.append(&entry);
list.append(&name);
list.append(&import_password);
list.append(&name);
fields.append_to(&list);
let dialog = adw::AlertDialog::builder()
.heading("Import an identity key")
.body(if first {
NEW_VAULT_NOTE
} else {
"The imported key is re-encrypted under your vault passphrase."
})
.extra_child(&list)
.build();
plain::dialog(&dialog);
dialog.add_response("cancel", "Cancel");
dialog.add_response("import", "Import");
dialog.set_default_response(Some("import"));
dialog.set_response_appearance("import", adw::ResponseAppearance::Suggested);
dialog.set_close_response("cancel");
let form = Rc::new(FormDialog::new(
"Import an identity key",
"The imported key is re-encrypted under your vault passphrase.",
&list,
"Import",
));
// Validity: there is something to import, and the vault passphrase is valid.
{
let (handles, state) = (handles.clone(), Rc::clone(&state));
dialog.connect_response(None, move |_, response| {
if response != "import" {
return;
}
let passphrase = match fields.value() {
Ok(passphrase) => passphrase,
Err(error) => return report_error(&handles, &error),
};
let text = entry.text().to_string();
let import_password_text = import_password.text().to_string();
// Wipe what was read from the widgets: a pasted `nsec` and the
// passphrases must not linger.
let review_form = Rc::clone(&form);
let review_fields = fields.clone();
let review_entry = entry.clone();
let review: Rc<dyn Fn()> = Rc::new(move || {
review_form.set_action_enabled(
!review_entry.text().trim().is_empty() && review_fields.review(),
);
});
review();
{
let review = Rc::clone(&review);
let fields = fields.clone();
fields.connect_changed(move || review());
}
{
let review = Rc::clone(&review);
entry.connect_changed(move |_| review());
}
}
// A pasted `nsec` and the passphrases go when the dialog goes (L5).
{
let fields = fields.clone();
let entry = entry.clone();
let import_password = import_password.clone();
form.connect_closed(move || {
fields.clear();
entry.set_text("");
import_password.set_text("");
});
}
{
let state = Rc::clone(&state);
let form_submit = Rc::clone(&form);
let submit_fields = fields.clone();
let entry = entry.clone();
let import_password = import_password.clone();
form.action().connect_clicked(move |_| {
let Ok(passphrase) = submit_fields.value() else {
return;
};
let text = entry.text().to_string();
let import_password_text = import_password.text().to_string();
let text = Zeroizing::new(text);
let import_password = Zeroizing::new(import_password_text);
let passphrase = Zeroizing::new(passphrase);
// Empty means "no label": the discovered profile name is what the app
// shows, and a label is only for keys with no profile.
let label = name.text().trim().to_string();
form_submit.set_busy(true);
let after = Rc::clone(&state);
let handles = handles.clone();
let form_done = Rc::clone(&form_submit);
let store = Arc::clone(&store);
runtime::spawn(
async move {
if text.starts_with("ncryptsec1") {
if text.trim().starts_with("ncryptsec1") {
store
.import_user_key_encrypted(&label, &text, &import_password, &passphrase)
.await
@@ -594,13 +993,21 @@ fn present_import(handles: Handles, state: Rc<AppState>) {
}
},
move |result| match result {
Ok(_) => after.refresh_identities(),
Err(error) => report_error(&handles, &error),
Ok(_) => {
after.refresh_identities();
form_done.close();
}
Err(error) => {
form_done.set_busy(false);
form_done.error(&error);
}
},
);
});
}
dialog.present(toplevel(&handles).as_ref());
form.present(toplevel(&handles).as_ref());
// The key field is this form's first field.
form.focus(&entry);
}
/// Run `then` once the vault is open, asking for the passphrase first if needed.
+4 -2
View File
@@ -53,7 +53,8 @@ const AUTO_APPROVE_MAX: f64 = 600.0;
/// The row is a **toggle** mirroring the header lock button: while locked it
/// offers to open the vault — which is the only route to "Change…" from
/// Preferences — and while unlocked it offers to close it. With no vault (no
/// identity key) there is neither, so the row is inert.
/// passphrase set yet) there is neither, so the row is inert. A vault can now
/// exist without a key (the first-run setup), and the row is live then too.
fn lock_row_state(locked: bool, has_vault: bool) -> (&'static str, &'static str, &'static str, bool) {
match (has_vault, locked) {
(false, _) => (
@@ -446,7 +447,8 @@ impl Preferences {
self.lock_row.set_title(title);
self.lock_row.set_subtitle(subtitle);
self.lock_button.set_label(label);
// Nothing to lock or unlock until a key — and so a passphrase — exists.
// Nothing to lock or unlock until a passphrase exists (a key, or the
// first-run setup's verifier).
self.lock_button.set_sensitive(sensitive);
// Changing the passphrase needs the decrypted keys, so it stays gated on
+2 -1
View File
@@ -713,7 +713,8 @@ fn main_window(
let listener_state = Rc::clone(state);
state.listen(move || {
let locked = listener_state.is_locked();
// Nothing to lock until a key — and so a passphrase — exists.
// Nothing to lock until a passphrase exists (a key, or the
// first-run setup's verifier).
button.set_sensitive(listener_state.store().has_vault());
// The icon and the tooltip show the state, not what clicking does:
// a closed padlock means locked, an open one means unlocked. (The