Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add TOTP generator to Rust core (#2492)

Leendert de Borstb64488da4422
diff --git a/core/README.md b/core/README.md
index ac9510c79..47fc6083a 100644
--- a/core/README.md
+++ b/core/README.md
@@ -3,17 +3,11 @@ This folder contains core modules that are used by multiple applications in the
## rust (Primary)
**Primary cross-platform core library** written in Rust, providing shared business logic across ALL platforms:
+- Web app via Webassembly
- Browser extensions (Chrome, Firefox, Edge, Safari) via WebAssembly
- Mobile apps (iOS via Swift bindings, Android via Kotlin bindings)
-- Server (.NET via P/Invoke)
- Desktop apps (future)
-Currently implements:
-- **merge** - Merges two SQLite vault databases using Last-Write-Wins (LWW) strategy
-- **credential_matcher** - Cross-platform credential filtering for autofill
-- **password_generator** - Password and passphrase (Diceware) generation
-- **identity_generator** - Random identity (alias persona) generation with per-language name dictionaries
-
See [rust/README.md](rust/README.md) for detailed documentation.
## client
diff --git a/core/rust/Cargo.lock b/core/rust/Cargo.lock
index 7ba7f789e..8ec53f38d 100644
--- a/core/rust/Cargo.lock
+++ b/core/rust/Cargo.lock
@@ -68,6 +68,7 @@ dependencies = [
"serde",
"serde-wasm-bindgen",
"serde_json",
+ "sha1",
"sha2",
"srp",
"subtle",
@@ -1248,6 +1249,17 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "sha1"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest",
+]
+
[[package]]
name = "sha2"
version = "0.10.9"
diff --git a/core/rust/Cargo.toml b/core/rust/Cargo.toml
index 71d8cd9f6..36acd12ff 100644
--- a/core/rust/Cargo.toml
+++ b/core/rust/Cargo.toml
@@ -55,6 +55,9 @@ hkdf = "0.12"
# HMAC-SHA256 (per-manifest blob addresses)
hmac = "0.12"
+# SHA-1 (hmac-sha1 TOTP generator)
+sha1 = "0.10"
+
# AES-256-GCM (vault blobs, key wrapping) and RSA-OAEP-SHA256 (manifest key grants)
aes-gcm = "0.10"
rsa = "0.9"
diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rs
index 2569ffaf6..e6ecc492b 100644
--- a/core/rust/src/bindings/uniffi_api.rs
+++ b/core/rust/src/bindings/uniffi_api.rs
@@ -9,16 +9,12 @@ use crate::common::error::{json_call, VaultError};
use crate::sqlite_host::{MemoryDatabase, SqlResult, SqlValue};
use crate::vault_codec::{self, CanonicalizeInput};
-// Vault sync.
-
/// Get the list of table names that take part in a vault sync.
#[uniffi::export]
pub fn get_syncable_table_names() -> Vec<String> {
crate::vault_model::SYNCABLE_TABLE_NAMES.iter().map(|s| s.to_string()).collect()
}
-// Credential matcher.
-
/// Filter credentials for autofill by the current URL/app and page title.
/// Input: `CredentialMatcherInput` JSON. Output: `CredentialMatcherOutput` JSON.
#[uniffi::export]
@@ -50,8 +46,6 @@ pub fn is_related_origin_allowed(caller_origin: String, origins: Vec<String>) ->
crate::credential_matcher::is_related_origin_allowed(&caller_origin, &origins)
}
-// Favicon.
-
/// Pick the favicon target for an item from its URLs, in the order the item lists them.
///
/// Returns the URL to fetch from and the `Logos.Source` key to store the result under, or
@@ -68,7 +62,11 @@ pub fn favicon_source_key(url: String) -> String {
crate::favicon::favicon_source_key(&url)
}
-// Password generator.
+/// The RFC 6238 code for a Base32 secret at `unix_seconds`, or `None` for an unusable secret. Unknown parameters fall back to SHA1, 6 digits, 30 seconds.
+#[uniffi::export]
+pub fn generate_totp_code(secret: String, unix_seconds: i64, algorithm: String, digits: u32, period: u32) -> Option<String> {
+ crate::totp::generate_totp_code(&secret, unix_seconds, &algorithm, digits, period)
+}
/// Generate a password or passphrase from `PasswordSettings` JSON; `Type` selects "basic" or "diceware" and an
/// optional 64-character hex `Seed` makes the output deterministic for UI previews.
@@ -83,8 +81,6 @@ pub fn get_diceware_languages() -> Vec<String> {
crate::password_generator::available_languages()
}
-// Identity generator.
-
/// Generate a random identity from `IdentityRequest` JSON (`language`, `gender`, `ageRange`, `birthdateOptions`);
/// returns `Identity` JSON with camelCase fields.
#[uniffi::export]
@@ -124,8 +120,6 @@ pub fn get_identity_age_ranges() -> Vec<String> {
crate::identity_generator::available_age_ranges()
}
-// Email parser.
-
/// Parse a raw RFC 822 email source into its html/plain bodies and attachment metadata, returned as
/// a JSON string (`{htmlBody, textBody, attachments: [{filename, mimeType, size, detached, partIndex}]}`). Input that
/// starts with the gzip magic bytes (0x1f 0x8b) is gunzipped, so the decrypted
@@ -147,8 +141,6 @@ pub fn extract_email_attachment(source: Vec<u8>, index: u32, detached_body: Opti
crate::email_parser::extract_email_attachment(&source, index as usize, detached_body.as_deref())
}
-// Vault codec (manifest-v1 storage format).
-
/// Canonicalize normalized tables into manifest + metadata + blob map.
/// Input: `CanonicalizeInput` JSON. Output: `CanonicalizedVault` JSON.
#[uniffi::export]
@@ -188,8 +180,6 @@ pub fn vault_codec_unpack_payload(plain_bytes: Vec<u8>) -> Result<String, VaultE
crate::vault_codec::unpack_payload(&plain_bytes)
}
-// Argon2id key derivation and the account key chain.
-
/// Derive a 32-byte key from a password and salt (UTF-8 bytes) with Argon2id under the `EncryptionSettings` JSON (required).
#[uniffi::export]
pub fn argon2_derive_key(password: String, salt: String, encryption_settings: String) -> Result<Vec<u8>, Argon2Error> {
@@ -256,8 +246,6 @@ pub fn open_account_key_chain(stored_key: Vec<u8>, encrypted_account_key: String
})
}
-// SRP (Secure Remote Password).
-
/// A random 32-byte SRP salt as an uppercase hex string.
#[uniffi::export]
pub fn srp_generate_salt() -> String {
@@ -294,8 +282,6 @@ pub fn srp_verify_session(client_public: String, client_proof: String, session_k
crate::crypto::srp::srp_verify_session(&client_public, &client_proof, &session_key, &server_proof)
}
-// RSA-OAEP.
-
/// RSA-OAEP-256 decrypt base64 ciphertext with a JWK private key.
#[uniffi::export]
pub fn rsa_decrypt(base64_ciphertext: String, private_key_jwk: String) -> Result<Vec<u8>, VaultError> {
@@ -308,8 +294,6 @@ pub fn mobile_login_encrypt_account_key(account_key: Vec<u8>, public_key_jwk: St
crate::crypto::encrypt_with_public_key_and_label(&account_key, &public_key_jwk, crate::crypto::aad::MOBILE_LOGIN_ACCOUNT_KEY)
}
-// Vault sync engine and SQLite host.
-
/// One engine operation. The host loops on `next_command` / `resume` until the command is `done`; see the
/// `vault_sync` module docs for the command and response shapes.
#[derive(uniffi::Object)]
diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rs
index 7efb1a67e..e18abfdf7 100644
--- a/core/rust/src/bindings/wasm.rs
+++ b/core/rust/src/bindings/wasm.rs
@@ -23,16 +23,12 @@ fn to_js<T: Serialize>(value: &T) -> Result<JsValue, JsValue> {
value.serialize(&serde_wasm_bindgen::Serializer::new().serialize_maps_as_objects(true).serialize_missing_as_null(true)).map_err(js_err)
}
-// Vault sync.
-
/// Get the list of table names that take part in a vault sync.
#[wasm_bindgen(js_name = getSyncableTableNames)]
pub fn get_syncable_table_names_js() -> Vec<String> {
crate::vault_model::SYNCABLE_TABLE_NAMES.iter().map(|s| s.to_string()).collect()
}
-// Vault codec (manifest-v1 storage format).
-
/// The sha256 (lowercase hex) of an uploaded logo's bytes: the `Source` of a `custom` logo row, and
/// what `vaultCodecLogoIdFor` then derives the row id from.
#[wasm_bindgen(js_name = vaultCodecLogoContentHash)]
@@ -74,8 +70,6 @@ pub fn vault_codec_unpack_payload_js(plain_bytes: &[u8]) -> Result<String, JsVal
vault_codec::unpack_payload(plain_bytes).map_err(js_err)
}
-// Credential matcher.
-
/// Filter credentials for autofill. Input: `CredentialMatcherInput`. Output: `CredentialMatcherOutput`.
#[wasm_bindgen(js_name = filterCredentials)]
pub fn filter_credentials_js(input: JsValue) -> Result<JsValue, JsValue> {
@@ -110,8 +104,6 @@ pub fn is_related_origin_allowed_js(caller_origin: &str, origins: Vec<String>) -
crate::credential_matcher::is_related_origin_allowed(caller_origin, &origins)
}
-// Favicon.
-
/// The favicon target for an item's URLs (in item order): the URL to fetch and the `Logos.Source` key, or null.
#[wasm_bindgen(js_name = selectFaviconTarget)]
pub fn select_favicon_target_js(urls: Vec<String>) -> Result<JsValue, JsValue> {
@@ -121,7 +113,11 @@ pub fn select_favicon_target_js(urls: Vec<String>) -> Result<JsValue, JsValue> {
}
}
-// Password generator.
+/// The RFC 6238 code for a Base32 secret at `unixSeconds`, or undefined for an unusable secret. Unknown parameters fall back to SHA1, 6 digits, 30 seconds.
+#[wasm_bindgen(js_name = generateTotpCode)]
+pub fn generate_totp_code_js(secret: &str, unix_seconds: f64, algorithm: &str, digits: u32, period: u32) -> Option<String> {
+ crate::totp::generate_totp_code(secret, unix_seconds as i64, algorithm, digits, period)
+}
/// Generate a password or passphrase from `PasswordSettings` JSON; `Type` selects "basic" or "diceware".
#[wasm_bindgen(js_name = generatePassword)]
@@ -135,8 +131,6 @@ pub fn get_diceware_languages_js() -> Vec<String> {
available_languages()
}
-// Identity generator.
-
/// Generate a random identity from `IdentityRequest` JSON (`language`, `gender`, `ageRange`, `birthdateOptions`);
/// returns `Identity` JSON.
#[wasm_bindgen(js_name = generateIdentity)]
@@ -176,8 +170,6 @@ pub fn get_identity_age_ranges_js() -> Vec<String> {
crate::identity_generator::available_age_ranges()
}
-// Email parser.
-
/// Parse a raw RFC 822 email source into its html/plain bodies and attachment metadata.
/// Input that starts with the gzip magic bytes (0x1f 0x8b) is gunzipped, so the
/// decrypted `MessageSource` of both legacy and source-only emails can be passed as-is.
@@ -200,8 +192,6 @@ pub fn extract_email_attachment_js(source: &[u8], index: usize, detached_body: O
crate::email_parser::extract_email_attachment(source, index, detached_body.as_deref()).map_err(js_err)
}
-// Argon2id key derivation and the account key chain.
-
/// Derive a 32-byte key from a password and salt (UTF-8 bytes) with Argon2id under the `EncryptionSettings` JSON (required).
#[wasm_bindgen(js_name = argon2DeriveKey)]
pub fn argon2_derive_key_js(password: &str, salt: &str, encryption_settings: &str) -> Result<Vec<u8>, JsValue> {
@@ -262,8 +252,6 @@ pub fn open_account_key_chain_js(stored_key: &str, encrypted_account_key: &str,
to_js(&result)
}
-// SRP (Secure Remote Password).
-
/// A random 32-byte SRP salt as an uppercase hex string.
#[wasm_bindgen(js_name = srpGenerateSalt)]
pub fn srp_generate_salt_js() -> String {
@@ -302,8 +290,6 @@ pub fn srp_verify_session_js(client_public: &str, client_proof: &str, session_ke
crate::crypto::srp::srp_verify_session(client_public, client_proof, session_key, server_proof).map_err(js_err)
}
-// Vault sync engine and SQLite host.
-
/// One engine operation. The host loops on `nextCommand` / `resume` until the command is `done`; see the
/// `vault_sync` module docs for the command and response shapes.
#[wasm_bindgen(js_name = VaultSyncSession)]
diff --git a/core/rust/src/lib.rs b/core/rust/src/lib.rs
index d2b3a39d4..cf359be54 100644
--- a/core/rust/src/lib.rs
+++ b/core/rust/src/lib.rs
@@ -11,6 +11,7 @@
//! - **email_parser**: RFC 822 email parsing into bodies and attachment metadata
//! - **favicon**: Favicon handling and source selection
//! - **password_generator**: Password and passphrase (Diceware) generation
+//! - **totp**: RFC 6238 TOTP code generation
//! - **identity_generator**: Random identity (alias persona) generation
//! - **crypto**: Argon2id derivation, AES-256-GCM, RSA-OAEP, the account key hierarchy and the SRP-6a handshake
//! - **common**: `VaultError`, byte encodings, randomness and the vault timestamp formats
@@ -25,6 +26,7 @@ pub mod credential_matcher;
pub mod email_parser;
pub mod favicon;
pub mod password_generator;
+pub mod totp;
pub mod identity_generator;
pub mod crypto;
pub mod vault_sync;
diff --git a/core/rust/src/totp/mod.rs b/core/rust/src/totp/mod.rs
new file mode 100644
index 000000000..cbeea49ad
--- /dev/null
+++ b/core/rust/src/totp/mod.rs
@@ -0,0 +1,99 @@
+//! RFC 6238 TOTP code generation, shared by every client.
+
+#[cfg(test)]
+mod tests;
+
+use hmac::{Hmac, Mac};
+use sha1::Sha1;
+use sha2::{Sha256, Sha512};
+
+/// The HMAC algorithm RFC 6238 assumes when none is given.
+pub const DEFAULT_ALGORITHM: &str = "SHA1";
+
+/// The code length RFC 6238 assumes when none is given.
+pub const DEFAULT_DIGITS: u32 = 6;
+
+/// The time step in seconds RFC 6238 assumes when none is given.
+pub const DEFAULT_PERIOD: u32 = 30;
+
+/// The longest time step accepted; anything above falls back to [`DEFAULT_PERIOD`].
+const MAX_PERIOD: u32 = 300;
+
+/// A supported HMAC algorithm.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Algorithm {
+ Sha1,
+ Sha256,
+ Sha512,
+}
+
+/// The algorithm for a name such as "SHA256", "sha-256" or "SHA_512"; anything unknown is SHA1.
+fn parse_algorithm(name: &str) -> Algorithm {
+ let normalized: String = name.chars().filter(|c| !c.is_whitespace() && *c != '-' && *c != '_').collect::<String>().to_ascii_uppercase();
+ match normalized.as_str() {
+ "SHA256" => Algorithm::Sha256,
+ "SHA512" => Algorithm::Sha512,
+ _ => Algorithm::Sha1,
+ }
+}
+
+/// The digit count if supported (6 to 8), else [`DEFAULT_DIGITS`].
+fn normalize_digits(digits: u32) -> u32 {
+ if (6..=8).contains(&digits) { digits } else { DEFAULT_DIGITS }
+}
+
+/// The period if usable (1 to 300 seconds), else [`DEFAULT_PERIOD`].
+fn normalize_period(period: u32) -> u32 {
+ if (1..=MAX_PERIOD).contains(&period) { period } else { DEFAULT_PERIOD }
+}
+
+/// Decode an RFC 4648 Base32 secret, ignoring case, spaces, dashes and `=` padding. `None` on any other character.
+fn decode_base32(secret: &str) -> Option<Vec<u8>> {
+ const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
+ let mut bytes = Vec::with_capacity(secret.len() * 5 / 8);
+ let mut buffer: u32 = 0;
+ let mut bits = 0;
+ for ch in secret.chars() {
+ if ch.is_whitespace() || ch == '-' || ch == '=' {
+ continue;
+ }
+ let value = ALPHABET.iter().position(|&a| a == ch.to_ascii_uppercase() as u8)? as u32;
+ buffer = (buffer << 5) | value;
+ bits += 5;
+ if bits >= 8 {
+ bits -= 8;
+ bytes.push((buffer >> bits) as u8);
+ buffer &= (1 << bits) - 1;
+ }
+ }
+ Some(bytes)
+}
+
+/// HMAC of `counter` (8 bytes, big-endian) with `key`.
+fn hmac_counter(algorithm: Algorithm, key: &[u8], counter: u64) -> Vec<u8> {
+ let message = counter.to_be_bytes();
+ // Hmac accepts keys of any length, so new_from_slice cannot fail.
+ match algorithm {
+ Algorithm::Sha1 => Hmac::<Sha1>::new_from_slice(key).map(|mut mac| { mac.update(&message); mac.finalize().into_bytes().to_vec() }),
+ Algorithm::Sha256 => Hmac::<Sha256>::new_from_slice(key).map(|mut mac| { mac.update(&message); mac.finalize().into_bytes().to_vec() }),
+ Algorithm::Sha512 => Hmac::<Sha512>::new_from_slice(key).map(|mut mac| { mac.update(&message); mac.finalize().into_bytes().to_vec() }),
+ }
+ .expect("HMAC takes keys of any length")
+}
+
+/// The TOTP code for a Base32 `secret` at `unix_seconds`, or `None` when the secret is empty or not Base32 or the time is negative.
+pub fn generate_totp_code(secret: &str, unix_seconds: i64, algorithm: &str, digits: u32, period: u32) -> Option<String> {
+ let key = decode_base32(secret)?;
+ if key.is_empty() || unix_seconds < 0 {
+ return None;
+ }
+ let digits = normalize_digits(digits);
+ let counter = unix_seconds as u64 / u64::from(normalize_period(period));
+ let hash = hmac_counter(parse_algorithm(algorithm), &key, counter);
+
+ // Dynamic truncation, RFC 4226 section 5.3.
+ let offset = (hash[hash.len() - 1] & 0x0f) as usize;
+ let binary = u32::from_be_bytes([hash[offset] & 0x7f, hash[offset + 1], hash[offset + 2], hash[offset + 3]]);
+ let code = binary % 10u32.pow(digits);
+ Some(format!("{code:0width$}", width = digits as usize))
+}
diff --git a/core/rust/src/totp/tests.rs b/core/rust/src/totp/tests.rs
new file mode 100644
index 000000000..62d112fcd
--- /dev/null
+++ b/core/rust/src/totp/tests.rs
@@ -0,0 +1,81 @@
+//! Tests for TOTP code generation.
+
+use super::*;
+
+/// RFC 6238 appendix B seeds: the ASCII strings "1234567890..." of 20, 32 and 64 bytes, Base32 encoded with padding.
+const SEED_SHA1: &str = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
+const SEED_SHA256: &str = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA====";
+const SEED_SHA512: &str = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNA=";
+
+/// RFC 6238 appendix B: (time, algorithm, seed, 8-digit code) with a 30 second step.
+const VECTORS: &[(i64, &str, &str, &str)] = &[
+ (59, "SHA1", SEED_SHA1, "94287082"),
+ (59, "SHA256", SEED_SHA256, "46119246"),
+ (59, "SHA512", SEED_SHA512, "90693936"),
+ (1111111109, "SHA1", SEED_SHA1, "07081804"),
+ (1111111109, "SHA256", SEED_SHA256, "68084774"),
+ (1111111109, "SHA512", SEED_SHA512, "25091201"),
+ (1111111111, "SHA1", SEED_SHA1, "14050471"),
+ (1111111111, "SHA256", SEED_SHA256, "67062674"),
+ (1111111111, "SHA512", SEED_SHA512, "99943326"),
+ (1234567890, "SHA1", SEED_SHA1, "89005924"),
+ (1234567890, "SHA256", SEED_SHA256, "91819424"),
+ (1234567890, "SHA512", SEED_SHA512, "93441116"),
+ (2000000000, "SHA1", SEED_SHA1, "69279037"),
+ (2000000000, "SHA256", SEED_SHA256, "90698825"),
+ (2000000000, "SHA512", SEED_SHA512, "38618901"),
+ (20000000000, "SHA1", SEED_SHA1, "65353130"),
+ (20000000000, "SHA256", SEED_SHA256, "77737706"),
+ (20000000000, "SHA512", SEED_SHA512, "47863826"),
+];
+
+#[test]
+fn matches_rfc_6238_vectors() {
+ for &(time, algorithm, seed, expected) in VECTORS {
+ assert_eq!(generate_totp_code(seed, time, algorithm, 8, 30).as_deref(), Some(expected), "T={time} {algorithm}");
+ }
+}
+
+#[test]
+fn six_digit_code_is_the_low_digits() {
+ assert_eq!(generate_totp_code(SEED_SHA1, 59, "SHA1", 6, 30).as_deref(), Some("287082"));
+ assert_eq!(generate_totp_code(SEED_SHA1, 1111111109, "SHA1", 6, 30).as_deref(), Some("081804"));
+}
+
+#[test]
+fn accepts_algorithm_spellings() {
+ for name in ["sha256", "SHA-256", "sha_256", " SHA256 "] {
+ assert_eq!(generate_totp_code(SEED_SHA256, 59, name, 8, 30).as_deref(), Some("46119246"), "{name}");
+ }
+}
+
+#[test]
+fn unknown_parameters_fall_back_to_defaults() {
+ let defaults = generate_totp_code(SEED_SHA1, 59, "SHA1", 6, 30);
+ assert_eq!(generate_totp_code(SEED_SHA1, 59, "MD5", 6, 30), defaults);
+ assert_eq!(generate_totp_code(SEED_SHA1, 59, "", 12, 0), defaults);
+ assert_eq!(generate_totp_code(SEED_SHA1, 59, "SHA1", 5, 301), defaults);
+}
+
+#[test]
+fn period_picks_the_time_step() {
+ // T=59 with a 60 second step is counter 0, the same counter as T=29 with a 30 second step.
+ assert_eq!(generate_totp_code(SEED_SHA1, 59, "SHA1", 8, 60), generate_totp_code(SEED_SHA1, 29, "SHA1", 8, 30));
+}
+
+#[test]
+fn secret_tolerates_case_spaces_dashes_and_padding() {
+ let expected = generate_totp_code("JBSWY3DPEHPK3PXP", 59, "SHA1", 6, 30);
+ assert!(expected.is_some());
+ for secret in ["jbswy3dpehpk3pxp", "JBSW Y3DP EHPK 3PXP", "JBSW-Y3DP-EHPK-3PXP", "JBSWY3DPEHPK3PXP===="] {
+ assert_eq!(generate_totp_code(secret, 59, "SHA1", 6, 30), expected, "{secret}");
+ }
+}
+
+#[test]
+fn rejects_unusable_input() {
+ assert_eq!(generate_totp_code("not base32!", 59, "SHA1", 6, 30), None);
+ assert_eq!(generate_totp_code("", 59, "SHA1", 6, 30), None);
+ assert_eq!(generate_totp_code("====", 59, "SHA1", 6, 30), None);
+ assert_eq!(generate_totp_code(SEED_SHA1, -1, "SHA1", 6, 30), None);
+}