Skip to content

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

Update Rust bindings and refactor to use shared logic (#2159)

Leendert de Borst535afd5f1422
diff --git a/core/rust/Cargo.lock b/core/rust/Cargo.lock
index 2b73f0330..9b76f6c31 100644
--- a/core/rust/Cargo.lock
+++ b/core/rust/Cargo.lock
@@ -1348,7 +1348,6 @@ dependencies = [
"cargo_metadata",
"clap",
"uniffi_bindgen",
- "uniffi_build",
"uniffi_core",
"uniffi_macros",
]
@@ -1376,17 +1375,6 @@ dependencies = [
"uniffi_udl",
]
-[[package]]
-name = "uniffi_build"
-version = "0.28.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4c7cf32576e08104b7dc2a6a5d815f37616e66c6866c2a639fe16e6d2286b75b"
-dependencies = [
- "anyhow",
- "camino",
- "uniffi_bindgen",
-]
-
[[package]]
name = "uniffi_checksum_derive"
version = "0.28.3"
diff --git a/core/rust/Cargo.toml b/core/rust/Cargo.toml
index 889a1c686..b175d73c3 100644
--- a/core/rust/Cargo.toml
+++ b/core/rust/Cargo.toml
@@ -85,10 +85,6 @@ rusqlite = { version = "0.40", features = ["bundled", "serialize"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom02 = { package = "getrandom", version = "0.2", features = ["js"] }
-# Build dependencies for UniFFI
-[build-dependencies]
-uniffi = { version = "0.28", features = ["build"] }
-
# Binary for generating Swift/Kotlin bindings
# This binary requires uniffi-cli feature which includes the heavy bindgen dependencies
[[bin]]
@@ -102,7 +98,7 @@ opt-level = 0
debug = false
incremental = true
-# Release profile - optimized for size (web app WASM, fetched on page load, and .NET)
+# Release profile - optimized for size (web app WASM, fetched on page load)
[profile.release]
opt-level = "z"
lto = "fat"
@@ -119,3 +115,8 @@ opt-level = 3
[profile.mobile]
inherits = "release"
opt-level = 3
+
+# .NET profile - optimized for speed as the native library runs server-side where size is irrelevant
+[profile.dotnet]
+inherits = "release"
+opt-level = 3
diff --git a/core/rust/README.md b/core/rust/README.md
index 1e081d0cf..2b269ac64 100644
--- a/core/rust/README.md
+++ b/core/rust/README.md
@@ -3,8 +3,9 @@
Cross-platform core library providing shared business logic for all AliasVault clients:
- **Browser Extensions** (Chrome, Firefox, Edge, Safari via WASM)
+- **Web App and Blazor Client** (via the same WASM build)
- **Mobile Apps** (iOS via Swift bindings, Android via Kotlin bindings)
-- **Server** (.NET via P/Invoke - prepared, not yet consumed by current API version)
+- **.NET** (C FFI exports for P/Invoke, built with `--dotnet`; nothing consumes them yet)
## Core Modules
@@ -19,12 +20,29 @@ content-addressed blobs, and materialize them back.
### vault_merge
Last-Write-Wins (LWW) merge of a local vault onto the server's, one manifest at a time, rows out.
+### vault_sharing
+Which manifests a push writes and which the account can still open, for multi-manifest (shared) vaults.
+
### vault_pruner
Permanently deletes items in trash older than retention period (default: 30 days).
+### vault_sync
+The sync engine every client drives: a sans-IO command loop that asks the host for HTTP, state and
+SQLite access and runs the status check, pull, merge, push and the storage-format migration.
+
+### sqlite_host
+An in-memory SQLite database (`SqliteMemoryDatabase`) that hosts every client's vault, so no platform
+needs its own SQLite build or writes plaintext to disk.
+
### credential_matcher
Priority-based credential filtering for autofill with anti-phishing protection.
+### email_parser
+RFC 822 email parsing into html/plain bodies and attachment metadata, with on-demand attachment bytes.
+
+### favicon
+Which of an item's URLs a favicon is fetched from, and the `Logos.Source` key it is stored under.
+
### password_generator
Password and passphrase (Diceware) generation with embedded per-language wordlists.
@@ -33,17 +51,34 @@ Random identity (alias persona) generation: names from embedded per-language dic
(decade-based for de/it/ro), birth date, email prefix and username. See
`src/identity_generator/dictionaries/README.md` for the dictionary format.
+### crypto
+Argon2id key derivation, AES-256-GCM, RSA-OAEP key grants, the account key hierarchy and the SRP-6a handshake.
+
+### timestamp and error
+The vault datetime formats plus the `UpdatedAt` comparison the merge relies on, and the `VaultError`
+type with the JSON-in/JSON-out call helper the bindings share.
+
## Building
```bash
-./build.sh --browser # WASM for browser extension
-./build.sh --ios # iOS device + simulator with Swift bindings
-./build.sh --android # Android ABIs with Kotlin bindings
-./build.sh --dotnet # Native library for .NET
-./build.sh --mobile # iOS + Android
-./build.sh --all # All targets
+./build.sh --web # WASM for the web app and Blazor client
+./build.sh --browser-extension # WASM for the browser extension
+./build.sh --ios # iOS device + simulator with Swift bindings
+./build.sh --android # Android ABIs with Kotlin bindings
+./build.sh --dotnet # Native library for .NET
+./build.sh --mobile # iOS + Android
+./build.sh --all # All targets (WASM as --web)
```
+Only the web app (fetched on page load) builds with the size-optimized `release` profile. The browser extension
+(`extension` profile), iOS and Android (`mobile` profile) and .NET (`dotnet` profile) build with `opt-level = 3`, which
+trades a few megabytes for faster sync, since those ship as a one time download or run server-side. Both WASM builds write to `core/client/wasm`, so locally the
+apps run whichever was built last. Every build bundles SQLite behind
+`SqliteMemoryDatabase` (the .NET C exports included), which hosts every client's vault database in
+memory (the sync engine's staging database included), so all clients run one SQLite build and the phones never
+write plaintext to disk. On wasm32 that SQLite is compiled by clang (sqlite-wasm-rs); macOS needs Homebrew LLVM
+(`brew install llvm`), which `build.sh` finds on its own.
+
## Testing
```bash
diff --git a/core/rust/build.sh b/core/rust/build.sh
index 594515cce..b5fdc8911 100755
--- a/core/rust/build.sh
+++ b/core/rust/build.sh
@@ -65,7 +65,7 @@ compute_source_checksum() {
}
# Cargo profile the mobile builds produce: the speed-optimized `mobile` profile (see Cargo.toml), while
-# the web app WASM and .NET keep `release`.
+# only the web app WASM keeps the size-optimized `release`.
MOBILE_CARGO_PROFILE="mobile"
echo -e "${YELLOW}Checking prerequisites...${NC}"
@@ -133,7 +133,7 @@ while [[ $# -gt 0 ]]; do
echo "Target options:"
echo " --web Build WASM for the web app and Blazor client (size-optimized)"
echo " --browser-extension Build WASM for the browser extension (speed-optimized)"
- echo " --dotnet Build native library for .NET server-side use (macOS/Linux/Windows)"
+ echo " --dotnet Build native library for .NET server-side use (macOS/Linux/Windows, speed-optimized)"
echo " --ios Build for iOS (device + simulator arm64) with Swift bindings"
echo " --android Build for Android (arm64-v8a, armeabi-v7a, x86_64) with Kotlin bindings"
echo " --all Build all targets (WASM as --web)"
@@ -320,8 +320,8 @@ build_dotnet() {
# Build with cargo
echo -e " Running cargo build..."
- cargo build --release --features ffi
- local cargo_target="target/release"
+ cargo build --profile dotnet --features ffi
+ local cargo_target="target/dotnet"
# Copy the library
if [ -f "$cargo_target/$lib_name" ]; then
diff --git a/core/rust/src/credential_matcher/mod.rs b/core/rust/src/credential_matcher/mod.rs
index c13182721..8803cc957 100644
--- a/core/rust/src/credential_matcher/mod.rs
+++ b/core/rust/src/credential_matcher/mod.rs
@@ -19,10 +19,8 @@ pub use domain::{extract_domain, extract_domain_with_port, extract_root_domain,
use domain::{domains_match, is_app_package_name};
use stop_words::STOP_WORD_SET;
-/// Default per-priority cap on returned matches when the caller does not
-/// supply `max_results`. Chosen as a balance between dropdown usability
-/// (scrollable but not overwhelming) and inline-strip needs.
-pub const DEFAULT_MAX_RESULTS: usize = 10;
+/// Default per-priority cap on returned matches when the caller does not supply `max_results`.
+const DEFAULT_MAX_RESULTS: usize = 10;
/// Matching mode for credential filtering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
@@ -64,8 +62,7 @@ pub struct CredentialMatcherInput {
/// All domain matches will be treated equally regardless of port.
#[serde(default)]
pub ignore_port: bool,
- /// Per-priority cap on returned matches. Defaults to [`DEFAULT_MAX_RESULTS`]
- /// (10) when omitted by the caller.
+ /// Per-priority cap on returned matches, 10 when omitted by the caller.
#[serde(default)]
pub max_results: Option<usize>,
}
@@ -73,8 +70,7 @@ pub struct CredentialMatcherInput {
/// Output from credential filtering.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CredentialMatcherOutput {
- /// IDs of matched credentials, in priority order. Capped at
- /// `input.max_results` (defaults to [`DEFAULT_MAX_RESULTS`]).
+ /// IDs of matched credentials, in priority order, capped at `input.max_results` (10 by default).
pub matched_ids: Vec<String>,
/// Which priority level matched (1-4, or 0 if no match)
pub matched_priority: u8,
@@ -89,8 +85,7 @@ impl CredentialMatcherOutput {
/// Filter credentials based on current URL and page context with anti-phishing protection.
///
-/// Returns the credentials of the best matching priority stage, capped per `input.max_results`
-/// (defaulting to [`DEFAULT_MAX_RESULTS`]).
+/// Returns the credentials of the best matching priority stage, capped per `input.max_results` (10 by default).
pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOutput {
let CredentialMatcherInput { credentials, current_url, page_title, matching_mode, ignore_port, max_results } = input;
let max_results = max_results.unwrap_or(DEFAULT_MAX_RESULTS);
diff --git a/core/rust/src/crypto/argon2.rs b/core/rust/src/crypto/argon2.rs
index f171a7b8d..00e068284 100644
--- a/core/rust/src/crypto/argon2.rs
+++ b/core/rust/src/crypto/argon2.rs
@@ -4,16 +4,16 @@ use serde::Deserialize;
use thiserror::Error;
/// Length of every derived key in bytes; the vault format assumes a 256-bit key throughout.
-pub const ARGON2_OUTPUT_LENGTH: usize = 32;
+const ARGON2_OUTPUT_LENGTH: usize = 32;
/// Default memory cost in KiB, used when the settings do not state one.
-pub const ARGON2_DEFAULT_MEMORY_KIB: u32 = 19456;
+const ARGON2_DEFAULT_MEMORY_KIB: u32 = 19456;
/// Default number of passes, used when the settings do not state one.
-pub const ARGON2_DEFAULT_ITERATIONS: u32 = 2;
+const ARGON2_DEFAULT_ITERATIONS: u32 = 2;
/// Default number of lanes, used when the settings do not state one.
-pub const ARGON2_DEFAULT_PARALLELISM: u32 = 1;
+const ARGON2_DEFAULT_PARALLELISM: u32 = 1;
/// Argon2-related errors.
#[derive(Error, Debug, Clone)]
@@ -53,16 +53,8 @@ impl Default for Argon2Params {
}
impl Argon2Params {
- /// Reads the `EncryptionSettings` JSON the server handed the client with its login challenge.
- ///
- /// A missing field falls back to the AliasVault default for that field. An empty string means
- /// the caller has no settings at all and wants the defaults.
- ///
- /// # Arguments
- /// * `settings_json` - Settings as `{"DegreeOfParallelism":1,"MemorySize":19456,"Iterations":2}`.
- ///
- /// # Returns
- /// The parsed cost parameters.
+ /// The cost parameters from the server's `EncryptionSettings` JSON
+ /// (`{"DegreeOfParallelism":1,"MemorySize":19456,"Iterations":2}`); a missing field, or an empty string, means the default.
pub fn from_settings_json(settings_json: &str) -> Result<Self, Argon2Error> {
let defaults = Self::default();
if settings_json.trim().is_empty() {
@@ -92,15 +84,7 @@ struct EncryptionSettingsJson {
degree_of_parallelism: Option<u32>,
}
-/// Derives a 32-byte key from a password using Argon2id with explicit cost parameters.
-///
-/// # Arguments
-/// * `password` - The password bytes.
-/// * `salt` - The salt bytes, at least 8 bytes long.
-/// * `params` - The cost parameters.
-///
-/// # Returns
-/// The derived key, [`ARGON2_OUTPUT_LENGTH`] bytes long.
+/// Derive a 32-byte key from a password with Argon2id under explicit cost parameters; the salt is at least 8 bytes.
pub fn argon2_derive_key(password: &[u8], salt: &[u8], params: Argon2Params) -> Result<Vec<u8>, Argon2Error> {
use argon2::{Algorithm, Argon2, Params, Version};
@@ -117,31 +101,14 @@ pub fn argon2_derive_key(password: &[u8], salt: &[u8], params: Argon2Params) ->
Ok(output)
}
-/// Derives a 32-byte key from a password using the cost parameters stated as settings JSON.
-///
-/// # Arguments
-/// * `password` - The password; hashed as its UTF-8 bytes.
-/// * `salt` - The salt; hashed as its UTF-8 bytes, at least 8 bytes long.
-/// * `settings_json` - The `EncryptionSettings` JSON, or an empty string for the defaults.
-///
-/// # Returns
-/// The derived key, [`ARGON2_OUTPUT_LENGTH`] bytes long.
+/// Derive a 32-byte key from a password and salt (hashed as their UTF-8 bytes) under the cost parameters in
+/// `settings_json`, or the defaults for an empty string.
pub fn argon2_derive_key_from_settings(password: &str, salt: &str, settings_json: &str) -> Result<Vec<u8>, Argon2Error> {
argon2_derive_key_bytes_from_settings(password.as_bytes(), salt.as_bytes(), settings_json)
}
-/// Derives a 32-byte key from raw password and salt bytes using the cost parameters stated as settings JSON.
-///
-/// The mobile PIN unlock draws its salt from the Keychain/Keystore as random bytes, which are not
-/// valid UTF-8, so it needs this byte entry point rather than the string one.
-///
-/// # Arguments
-/// * `password` - The password bytes.
-/// * `salt` - The salt bytes, at least 8 bytes long.
-/// * `settings_json` - The `EncryptionSettings` JSON, or an empty string for the defaults.
-///
-/// # Returns
-/// The derived key, [`ARGON2_OUTPUT_LENGTH`] bytes long.
+/// [`argon2_derive_key_from_settings`] over raw bytes: the mobile PIN unlock's Keychain/Keystore salt is random
+/// bytes, not UTF-8.
pub fn argon2_derive_key_bytes_from_settings(password: &[u8], salt: &[u8], settings_json: &str) -> Result<Vec<u8>, Argon2Error> {
let params = Argon2Params::from_settings_json(settings_json)?;
argon2_derive_key(password, salt, params)
diff --git a/core/rust/src/crypto/rsa_oaep.rs b/core/rust/src/crypto/rsa_oaep.rs
index 297cb143a..a1ee0672b 100644
--- a/core/rust/src/crypto/rsa_oaep.rs
+++ b/core/rust/src/crypto/rsa_oaep.rs
@@ -1,7 +1,5 @@
//! RSA-OAEP (SHA-256) with keys carried as JWK JSON strings compatible with the WebCrypto API.
-use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64_URL;
-use base64::Engine;
use rsa::traits::{PrivateKeyParts, PublicKeyParts};
use rsa::{BigUint, Oaep, RsaPrivateKey, RsaPublicKey};
use serde::{Deserialize, Serialize};
@@ -9,7 +7,7 @@ use sha2::Sha256;
use std::fmt;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
-use crate::encoding::{base64_decode, base64_encode};
+use crate::encoding::{base64_decode, base64_encode, base64url_decode, base64url_encode};
use crate::error::{VaultError, VaultResult};
const MODULUS_BITS: usize = 2048;
@@ -101,12 +99,12 @@ fn parse_jwk(jwk: &str) -> VaultResult<RsaJwk> {
}
fn field(value: &str) -> VaultResult<BigUint> {
- let bytes = Zeroizing::new(BASE64_URL.decode(value).map_err(|_| VaultError::General("Invalid base64url in JWK".to_string()))?);
+ let bytes = Zeroizing::new(base64url_decode(value).map_err(|_| VaultError::General("Invalid base64url in JWK".to_string()))?);
Ok(BigUint::from_bytes_be(&bytes))
}
fn encode(value: &BigUint) -> String {
- BASE64_URL.encode(Zeroizing::new(value.to_bytes_be()))
+ base64url_encode(&Zeroizing::new(value.to_bytes_be()))
}
fn public_to_jwk(public: &RsaPublicKey) -> VaultResult<String> {
diff --git a/core/rust/src/crypto/srp.rs b/core/rust/src/crypto/srp.rs
index f05403df8..38d4fd60a 100644
--- a/core/rust/src/crypto/srp.rs
+++ b/core/rust/src/crypto/srp.rs
@@ -91,27 +91,13 @@ fn to_padded_bytes(value: &BigUint) -> Vec<u8> {
// Client Operations
// ═══════════════════════════════════════════════════════════════════════════════
-/// Generate a cryptographic salt for SRP.
-///
-/// Returns a 32-byte random salt as an uppercase hex string.
+/// A random 32-byte SRP salt as an uppercase hex string.
pub fn srp_generate_salt() -> String {
bytes_to_hex(&generate_random_bytes(32))
}
-/// Derive the SRP private key (x) from credentials.
-///
-/// Formula: x = H(salt | H(identity | ":" | password_hash))
-///
-/// The final hash is returned as the full 32-byte digest (not via BigUint, which
-/// would strip leading zero bytes from the fixed-length hex output).
-///
-/// # Arguments
-/// * `salt` - Salt as hex string
-/// * `identity` - User identity (lowercased internally)
-/// * `password_hash` - Pre-hashed password as hex string
-///
-/// # Returns
-/// Private key as uppercase hex string (64 characters)
+/// The SRP private key `x = H(salt | H(identity | ":" | password_hash))` as uppercase hex, from hex inputs.
+/// The full 32-byte digest is returned (not via BigUint, which would strip leading zero bytes).
pub fn srp_derive_private_key(
salt: &str,
identity: &str,
@@ -130,15 +116,7 @@ pub fn srp_derive_private_key(
Ok(bytes_to_hex(&x_hasher.finalize()))
}
-/// Derive the SRP verifier (v) from a private key.
-///
-/// Formula: v = g^x mod N
-///
-/// # Arguments
-/// * `private_key` - Private key as hex string
-///
-/// # Returns
-/// Verifier as uppercase hex string (256 bytes)
+/// The SRP verifier `v = g^x mod N` as uppercase hex (256 bytes), from the hex private key.
pub fn srp_derive_verifier(private_key: &str) -> Result<String, SrpError> {
let x = BigUint::from_bytes_be(&hex_to_bytes(private_key)?);
@@ -148,9 +126,7 @@ pub fn srp_derive_verifier(private_key: &str) -> Result<String, SrpError> {
Ok(bytes_to_hex(&to_padded_bytes(&v)))
}
-/// Generate a client ephemeral key pair.
-///
-/// Computes A = g^a mod N where a is a random 64-byte secret.
+/// A client ephemeral pair: `A = g^a mod N` for a random 64-byte secret `a`.
pub fn srp_generate_ephemeral() -> SrpEphemeral {
let client = SrpClient::<Sha256>::new(&G_2048);
@@ -163,19 +139,7 @@ pub fn srp_generate_ephemeral() -> SrpEphemeral {
}
}
-/// Derive the client session from server response.
-///
-/// Computes the shared session key K and client proof M1.
-///
-/// # Arguments
-/// * `client_secret` - Client secret ephemeral (a) as hex string
-/// * `server_public` - Server public ephemeral (B) as hex string
-/// * `salt` - Salt as hex string
-/// * `identity` - User identity (lowercased internally)
-/// * `private_key` - Private key (x) as hex string
-///
-/// # Returns
-/// Session with proof (M1) and key (K), or error if B is invalid
+/// The client session (key `K` and proof `M1`) from the server's public ephemeral `B`; hex in, hex out.
pub fn srp_derive_session(
client_secret: &str,
server_public: &str,
@@ -217,18 +181,7 @@ pub fn srp_derive_session(
})
}
-/// Verify the server's session proof (M2) on the client side.
-///
-/// This confirms that the server successfully derived the same session key.
-///
-/// # Arguments
-/// * `client_public` - Client public ephemeral (A) as hex string
-/// * `client_proof` - Client proof (M1) as hex string
-/// * `session_key` - Session key (K) as hex string
-/// * `server_proof` - Server proof (M2) as hex string to verify
-///
-/// # Returns
-/// True if verification succeeds, false otherwise
+/// Whether the server's proof `M2` matches, which confirms it derived the same session key.
pub fn srp_verify_session(
client_public: &str,
client_proof: &str,
@@ -249,12 +202,7 @@ pub fn srp_verify_session(
// Server Operations
// ═══════════════════════════════════════════════════════════════════════════════
-/// Generate a server ephemeral key pair.
-///
-/// Computes B = k*v + g^b mod N where b is a random 64-byte secret.
-///
-/// # Arguments
-/// * `verifier` - Password verifier (v) as hex string
+/// A server ephemeral pair: `B = k*v + g^b mod N` for a random 64-byte secret `b`, from the hex verifier.
pub fn srp_generate_ephemeral_server(verifier: &str) -> Result<SrpEphemeral, SrpError> {
let v_bytes = hex_to_bytes(verifier)?;
@@ -269,20 +217,7 @@ pub fn srp_generate_ephemeral_server(verifier: &str) -> Result<SrpEphemeral, Srp
})
}
-/// Derive and verify the server session from client response.
-///
-/// Verifies client proof M1 and computes server proof M2.
-///
-/// # Arguments
-/// * `server_secret` - Server secret ephemeral (b) as hex string
-/// * `client_public` - Client public ephemeral (A) as hex string
-/// * `salt` - Salt as hex string
-/// * `identity` - User identity (lowercased internally)
-/// * `verifier` - Password verifier (v) as hex string
-/// * `client_proof` - Client proof (M1) as hex string
-///
-/// # Returns
-/// Session with proof (M2) and key (K) if verification succeeds, None if M1 is invalid
+/// The server session (key `K` and proof `M2`) once the client's proof `M1` verifies; `None` when it does not.
pub fn srp_derive_session_server(
server_secret: &str,
client_public: &str,
diff --git a/core/rust/src/email_parser/mod.rs b/core/rust/src/email_parser/mod.rs
index 3551e59b6..6b1e51377 100644
--- a/core/rust/src/email_parser/mod.rs
+++ b/core/rust/src/email_parser/mod.rs
@@ -45,10 +45,7 @@ pub struct ParsedEmail {
/// gunzipping gzip-compressed input.
pub fn parse_email_source(source: &[u8]) -> VaultResult<ParsedEmail> {
let raw = decode_email_source(source)?;
-
- let message = MessageParser::default()
- .parse(raw.as_slice())
- .ok_or_else(|| VaultError::General("Failed to parse email source as a MIME message".to_string()))?;
+ let message = parse_message(&raw)?;
let has_html_part = message.html_body.iter().any(|id| message.part(*id).is_some_and(|part| part.is_text_html()));
let has_text_part = message.text_body.iter().any(|id| message.part(*id).is_some_and(|part| part.is_text() && !part.is_text_html()));
@@ -125,8 +122,7 @@ pub fn extract_email_attachment(source: &[u8], index: usize, detached_body: Opti
/// Parse a raw RFC 822 email source and return the result as a JSON string (for uniffi/ffi callers).
pub fn parse_email_source_json(source: &[u8]) -> VaultResult<String> {
- let parsed = parse_email_source(source)?;
- serde_json::to_string(&parsed).map_err(VaultError::from)
+ Ok(serde_json::to_string(&parse_email_source(source)?)?)
}
/// Parse raw RFC 822 bytes into a message, turning the parser's `None` into a proper error.
diff --git a/core/rust/src/encoding.rs b/core/rust/src/encoding.rs
index 2bdeff5fc..4a63ada6f 100644
--- a/core/rust/src/encoding.rs
+++ b/core/rust/src/encoding.rs
@@ -1,6 +1,6 @@
-//! Crate-wide byte encodings: hex, base64 and the UUID text form.
+//! Crate-wide byte encodings: hex, base64 (standard and URL-safe) and the UUID text form.
-use base64::engine::general_purpose::STANDARD as BASE64;
+use base64::engine::general_purpose::{STANDARD as BASE64, URL_SAFE_NO_PAD as BASE64_URL};
use base64::Engine;
use crate::error::{VaultError, VaultResult};
@@ -52,12 +52,29 @@ pub(crate) fn base64_decode(value: &str) -> VaultResult<Vec<u8>> {
BASE64.decode(value).map_err(|_| VaultError::General("Invalid base64".to_string()))
}
+/// URL-safe base64 without padding (the JWK spelling) of a byte slice.
+pub(crate) fn base64url_encode(bytes: &[u8]) -> String {
+ BASE64_URL.encode(bytes)
+}
+
+/// Decode a URL-safe unpadded base64 string.
+pub(crate) fn base64url_decode(value: &str) -> VaultResult<Vec<u8>> {
+ BASE64_URL.decode(value).map_err(|_| VaultError::General("Invalid base64url".to_string()))
+}
+
/// The lowercase `8-4-4-4-12` text form of 16 bytes.
pub(crate) fn format_uuid(bytes: &[u8; 16]) -> String {
let hex = hex_encode_lower(bytes);
format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])
}
+/// The lowercase UUID text of 16 bytes with the RFC 9562 `version` nibble and variant bits set.
+pub(crate) fn uuid_from_bytes(mut bytes: [u8; 16], version: u8) -> String {
+ bytes[6] = (bytes[6] & 0x0f) | (version << 4);
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
+ format_uuid(&bytes)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -75,9 +92,21 @@ mod tests {
assert_eq!(hex_decode("0é9"), None);
}
+ #[test]
+ fn base64url_round_trips_without_padding() {
+ let bytes = vec![0xfbu8, 0xff, 0xfe];
+ let text = base64url_encode(&bytes);
+ assert_eq!(text, "-__-");
+ assert_eq!(base64url_decode(&text).unwrap(), bytes);
+ assert!(base64url_decode("+//+").is_err());
+ }
+
#[test]
fn uuid_text_form_is_lowercase_and_grouped() {
let bytes = [0xABu8; 16];
assert_eq!(format_uuid(&bytes), "abababab-abab-abab-abab-abababababab");
+ let stamped = uuid_from_bytes([0xFFu8; 16], 4);
+ assert_eq!(&stamped[14..15], "4");
+ assert!(matches!(&stamped[19..20], "8" | "9" | "a" | "b"));
}
}
diff --git a/core/rust/src/ffi.rs b/core/rust/src/ffi.rs
index ebc6ee650..86c6ee4c9 100644
--- a/core/rust/src/ffi.rs
+++ b/core/rust/src/ffi.rs
@@ -12,7 +12,7 @@ use crate::error::{json_call, VaultResult};
use crate::sqlite_host::MemoryDatabase;
use crate::vault_codec::{self, CanonicalizeInput, DataBucket, ExtractBucketsInput, Manifest, MaterializeInput};
use crate::vault_pruner::{prune_vault, PruneInput};
-use crate::vault_sync::types::SqlStatement;
+use crate::sqlite_host::SqlStatement;
/// Prune expired items from trash.
///
diff --git a/core/rust/src/identity_generator/dictionaries/mod.rs b/core/rust/src/identity_generator/dictionaries/mod.rs
index fc3773772..d394939be 100644
--- a/core/rust/src/identity_generator/dictionaries/mod.rs
+++ b/core/rust/src/identity_generator/dictionaries/mod.rs
@@ -14,7 +14,7 @@
//! that were popular around the generated birth year. Used by de, it and ro.
/// First names that were popular for births within `[start_year, end_year]`.
-pub struct DecadeNames {
+pub(crate) struct DecadeNames {
/// First birth year covered by this list (inclusive).
pub start_year: i32,
/// Last birth year covered by this list (inclusive).
@@ -30,7 +30,7 @@ impl DecadeNames {
}
/// All embedded name lists for one language.
-pub struct LanguageDictionary {
+pub(crate) struct LanguageDictionary {
/// Two-letter ISO 639-1 language code.
pub code: &'static str,
firstnames_male: &'static str,
@@ -106,7 +106,7 @@ macro_rules! decade_language {
/// The registry of bundled language dictionaries. The order here is the order returned
/// by the language list APIs. English is the fallback for unknown codes.
-pub static DICTIONARIES: &[LanguageDictionary] = &[
+pub(crate) static DICTIONARIES: &[LanguageDictionary] = &[
flat_language!("da"),
decade_language!(
"de",
@@ -150,7 +150,7 @@ pub static DICTIONARIES: &[LanguageDictionary] = &[
/// Resolve a language code (case-insensitive) to its dictionary, falling back to
/// English for any unknown or empty code.
-pub fn resolve(code: &str) -> &'static LanguageDictionary {
+pub(crate) fn resolve(code: &str) -> &'static LanguageDictionary {
DICTIONARIES
.iter()
.find(|d| d.code.eq_ignore_ascii_case(code))
@@ -163,7 +163,7 @@ pub fn resolve(code: &str) -> &'static LanguageDictionary {
}
/// List the codes of all bundled languages, in registry order.
-pub fn available_codes() -> Vec<&'static str> {
+pub(crate) fn available_codes() -> Vec<&'static str> {
DICTIONARIES.iter().map(|d| d.code).collect()
}
diff --git a/core/rust/src/identity_generator/mod.rs b/core/rust/src/identity_generator/mod.rs
index bfdfa547a..a289ae1a0 100644
--- a/core/rust/src/identity_generator/mod.rs
+++ b/core/rust/src/identity_generator/mod.rs
@@ -10,7 +10,7 @@
//! for languages with decade-based dictionaries (de, it, ro) the first name is matched
//! to names that were popular around the generated birth year.
-pub mod dictionaries;
+pub(crate) mod dictionaries;
mod username_email;
#[cfg(test)]
@@ -20,7 +20,7 @@ use chrono::{Datelike, Days, NaiveDate, Utc};
use rand::RngCore;
use serde::{Deserialize, Serialize};
-use crate::error::VaultError;
+use crate::error::{json_call, VaultError};
use crate::rng::{make_rng, unbiased_index};
/// Gender value used in generated identities.
@@ -107,13 +107,11 @@ pub struct NameInput {
/// Returns the generated [`Identity`] as a JSON string, or a [`VaultError`] if the
/// request JSON is invalid.
pub fn generate_identity(request_json: &str) -> Result<String, VaultError> {
- let request: IdentityRequest = serde_json::from_str(request_json)?;
- let identity = generate_from_request(&request);
- Ok(serde_json::to_string(&identity)?)
+ json_call(request_json, |request: IdentityRequest| Ok(generate_from_request(&request)))
}
/// Generate a random identity from an already-parsed request.
-pub fn generate_from_request(request: &IdentityRequest) -> Identity {
+fn generate_from_request(request: &IdentityRequest) -> Identity {
let mut rng = make_rng(request.seed.as_deref());
let dictionary = dictionaries::resolve(&request.language);
@@ -200,7 +198,7 @@ pub fn available_age_ranges() -> Vec<String> {
/// Convert an age range string (e.g. "21-25") to birth year options relative to the
/// current year. Returns `None` for "random", empty or malformed input, which means
/// the default age behavior (21-65) applies.
-pub fn age_range_to_birthdate_options(age_range: &str) -> Option<BirthdateOptions> {
+fn age_range_to_birthdate_options(age_range: &str) -> Option<BirthdateOptions> {
age_range_to_birthdate_options_at(age_range, Utc::now().year())
}
diff --git a/core/rust/src/lib.rs b/core/rust/src/lib.rs
index 67163e838..d56243523 100644
--- a/core/rust/src/lib.rs
+++ b/core/rust/src/lib.rs
@@ -16,10 +16,6 @@
//! - **crypto**: Argon2id derivation, AES-256-GCM, RSA-OAEP, the account key hierarchy and the SRP-6a handshake
//! - **timestamp**: the vault datetime formats and the `UpdatedAt` comparison the merge relies on
//! - **error**: the `VaultError` type and the JSON-in/JSON-out call helper the bindings share
-//!
-//! This library accepts data as JSON and returns results as JSON.
-//! Each platform (browser, iOS, Android, .NET) handles its own I/O
-//! and calls this library for the core logic.
pub mod error;
mod encoding;
@@ -40,44 +36,12 @@ pub mod vault_sync;
pub mod sqlite_host;
pub use error::VaultError;
-pub use vault_merge::{merge_canonical, CanonicalManifestMerge, CanonicalMergeInput, CanonicalMergeOutput, MergeStats, SqlStatement};
-pub use vault_model::{SYNCABLE_TABLES, SYNCABLE_TABLE_NAMES};
-pub use vault_codec::{
- compute_ciphertext_hash, compute_content_fingerprint, canonicalize_from_sqlite,
- extract_buckets, generate_manifest_salt, unpack_payload, materialize_as_sqlite, pack_payload,
- validate_manifest, validate_data_bucket, BlobEntry,
- CanonicalizeInput, CanonicalizedManifest, CanonicalizedVault, CodecRecord, CodecTableData, DataBucket, Manifest,
- MaterializeInput, MaterializedTables, ManifestSpec, ValidationResult,
-};
-pub use vault_sharing::{
- partition_manifest_access, resolve_manifest_write_set, ManifestAccessPartition, ManifestAccessRequest,
- ManifestWriteRecord, ManifestWriteSet, ManifestWriteSetRequest, SharedManifestRecord, SkippedManifest,
- WriteSkipReason,
-};
-pub use vault_pruner::{
- prune_vault, PruneInput, PruneOutput, PruneStats,
-};
-pub use credential_matcher::{
- filter_credentials, extract_domain, extract_root_domain,
- AutofillMatchingMode, CredentialMatcherInput, CredentialMatcherOutput,
-};
-pub use email_parser::{ParsedEmail, ParsedEmailAttachment};
-pub use favicon::{favicon_source_key, select_favicon_target, FaviconTarget};
-pub use password_generator::{generate_password, PasswordSettings};
-pub use identity_generator::{generate_identity, Identity, IdentityRequest};
-pub use crypto::{
- argon2_derive_key, argon2_derive_key_bytes_from_settings, argon2_derive_key_from_settings, Argon2Error, Argon2Params,
- srp_generate_salt, srp_derive_private_key, srp_derive_verifier,
- srp_generate_ephemeral, srp_derive_session, srp_verify_session,
- srp_generate_ephemeral_server, srp_derive_session_server,
- SrpEphemeral, SrpSession, SrpError,
-};
// WASM bindings
#[cfg(feature = "wasm")]
pub mod wasm;
-// C FFI exports for .NET P/Invoke
+// C FFI exports (.NET P/Invoke), built with --dotnet but not consumed by any app yet
#[cfg(feature = "ffi")]
pub mod ffi;
@@ -88,9 +52,3 @@ pub mod uniffi_api;
// UniFFI scaffolding - generates the FFI glue code
#[cfg(feature = "uniffi")]
uniffi::setup_scaffolding!();
-
-/// Returns the version of the aliasvault-core library.
-/// This is set at compile time from Cargo.toml.
-pub fn get_core_version() -> &'static str {
- env!("CARGO_PKG_VERSION")
-}
diff --git a/core/rust/src/password_generator/mod.rs b/core/rust/src/password_generator/mod.rs
index 6fa031aee..7a3bfbc86 100644
--- a/core/rust/src/password_generator/mod.rs
+++ b/core/rust/src/password_generator/mod.rs
@@ -25,7 +25,7 @@ use crate::rng::{make_rng, unbiased_index};
/// Which generator to use.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
-pub enum GeneratorType {
+pub(crate) enum GeneratorType {
/// Character-set password generator.
#[default]
Basic,
@@ -89,7 +89,7 @@ pub enum Salt {
/// older blobs (which lack the Diceware fields) deserialize cleanly.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
-pub struct PasswordSettings {
+pub(crate) struct PasswordSettings {
/// Which generator to use.
#[serde(rename = "Type", default)]
pub generator_type: GeneratorType,
@@ -179,7 +179,7 @@ pub fn generate_password(settings_json: &str) -> Result<String, VaultError> {
}
/// Generate a password or passphrase from already-parsed settings.
-pub fn generate_from_settings(settings: &PasswordSettings) -> String {
+fn generate_from_settings(settings: &PasswordSettings) -> String {
let mut rng = make_rng(settings.seed.as_deref());
// Limit the maximum values for the password and passphrase length.
diff --git a/core/rust/src/sqlite_host.rs b/core/rust/src/sqlite_host.rs
index 2685474ad..df70691ff 100644
--- a/core/rust/src/sqlite_host.rs
+++ b/core/rust/src/sqlite_host.rs
@@ -4,14 +4,22 @@
use std::sync::Mutex;
-use base64::engine::general_purpose::STANDARD as BASE64;
-use base64::Engine;
use rusqlite::types::{ToSql, ToSqlOutput, Value as RsValue, ValueRef};
use rusqlite::{params_from_iter, Connection, MAIN_DB};
+use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
+use crate::encoding::base64_decode;
use crate::error::{VaultError, VaultResult};
-use crate::vault_sync::types::SqlStatement;
+use crate::vault_codec::row::{inline_b64, inline_bytes};
+
+/// One parameterized SQL statement, as the bindings and the sync engine hand it to a host.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SqlStatement {
+ pub sql: String,
+ #[serde(default)]
+ pub params: Vec<Value>,
+}
/// A SQLite value as the bindings see it, typed and without JSON encoding.
#[derive(Debug, Clone, PartialEq)]
@@ -75,9 +83,9 @@ impl MemoryDatabase {
/// Run one query with typed parameters and return its rows positionally.
pub fn query_values(&self, sql: &str, params: &[SqlValue]) -> VaultResult<SqlResult> {
let conn = self.lock();
- let mut statement = conn.prepare_cached(sql).map_err(|e| VaultError::General(format!("{} ({})", e, sql)))?;
+ let mut statement = conn.prepare_cached(sql).map_err(sql_error_at(sql))?;
let columns: Vec<String> = statement.column_names().iter().map(|c| c.to_string()).collect();
- let mut rows = statement.query(params_from_iter(params.iter())).map_err(|e| VaultError::General(format!("{} ({})", e, sql)))?;
+ let mut rows = statement.query(params_from_iter(params.iter())).map_err(sql_error_at(sql))?;
let mut out = Vec::new();
while let Some(row) = rows.next().map_err(sql_error)? {
let mut values = Vec::with_capacity(columns.len());
@@ -92,8 +100,8 @@ impl MemoryDatabase {
/// Run one statement with typed parameters and return the rows it changed.
pub fn execute(&self, sql: &str, params: &[SqlValue]) -> VaultResult<u64> {
let conn = self.lock();
- let mut statement = conn.prepare_cached(sql).map_err(|e| VaultError::General(format!("{} ({})", e, sql)))?;
- let mut rows = statement.query(params_from_iter(params.iter())).map_err(|e| VaultError::General(format!("{} ({})", e, sql)))?;
+ let mut statement = conn.prepare_cached(sql).map_err(sql_error_at(sql))?;
+ let mut rows = statement.query(params_from_iter(params.iter())).map_err(sql_error_at(sql))?;
while rows.next().map_err(sql_error)?.is_some() {}
Ok(conn.changes())
}
@@ -120,6 +128,11 @@ fn sql_error(error: rusqlite::Error) -> VaultError {
VaultError::General(error.to_string())
}
+/// The error mapper for a failure inside `sql`, naming the statement.
+fn sql_error_at(sql: &str) -> impl Fn(rusqlite::Error) -> VaultError + '_ {
+ move |error| VaultError::General(format!("{} ({})", error, sql))
+}
+
impl ToSql for SqlValue {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(match self {
@@ -145,34 +158,36 @@ impl From<ValueRef<'_>> for SqlValue {
}
/// A JSON parameter as a SQLite value.
-pub fn to_sql(value: &Value) -> RsValue {
+fn to_sql(value: &Value) -> RsValue {
match value {
Value::Null => RsValue::Null,
Value::Bool(b) => RsValue::Integer(*b as i64),
Value::Number(n) => n.as_i64().map(RsValue::Integer).unwrap_or_else(|| RsValue::Real(n.as_f64().unwrap_or(0.0))),
Value::String(s) => RsValue::Text(s.clone()),
- Value::Object(o) if o.contains_key("__b64") => RsValue::Blob(BASE64.decode(o["__b64"].as_str().unwrap_or("")).unwrap_or_default()),
- other => RsValue::Text(other.to_string()),
+ other => match inline_b64(other) {
+ Some(b64) => RsValue::Blob(base64_decode(b64).unwrap_or_default()),
+ None => RsValue::Text(other.to_string()),
+ },
}
}
/// A SQLite value as JSON.
-pub fn from_sql(value: ValueRef<'_>) -> Value {
+fn from_sql(value: ValueRef<'_>) -> Value {
match value {
ValueRef::Null => Value::Null,
ValueRef::Integer(i) => json!(i),
ValueRef::Real(f) => json!(f),
ValueRef::Text(t) => Value::String(String::from_utf8_lossy(t).to_string()),
- ValueRef::Blob(b) => json!({ "__b64": BASE64.encode(b) }),
+ ValueRef::Blob(b) => inline_bytes(b),
}
}
/// Run one query on a connection and return its rows as JSON objects keyed by column name.
pub fn query(conn: &Connection, sql: &str, params: &[Value]) -> VaultResult<Vec<Map<String, Value>>> {
- let mut statement = conn.prepare(sql).map_err(|e| VaultError::General(format!("{} ({})", e, sql)))?;
+ let mut statement = conn.prepare(sql).map_err(sql_error_at(sql))?;
let columns: Vec<String> = statement.column_names().iter().map(|c| c.to_string()).collect();
let values: Vec<RsValue> = params.iter().map(to_sql).collect();
- let mut rows = statement.query(params_from_iter(values.iter())).map_err(|e| VaultError::General(format!("{} ({})", e, sql)))?;
+ let mut rows = statement.query(params_from_iter(values.iter())).map_err(sql_error_at(sql))?;
let mut out = Vec::new();
while let Some(row) = rows.next().map_err(sql_error)? {
let mut object = Map::new();
@@ -191,7 +206,7 @@ pub fn exec(conn: &Connection, statements: &[SqlStatement]) -> VaultResult<()> {
let values: Vec<RsValue> = statement.params.iter().map(to_sql).collect();
if let Err(error) = conn.execute(&statement.sql, params_from_iter(values.iter())) {
let _ = conn.execute_batch("ROLLBACK TO exec_batch; RELEASE exec_batch");
- return Err(VaultError::General(format!("{} ({})", error, statement.sql)));
+ return Err(sql_error_at(&statement.sql)(error));
}
}
conn.execute_batch("RELEASE exec_batch").map_err(sql_error)
diff --git a/core/rust/src/timestamp.rs b/core/rust/src/timestamp.rs
index 1d876786c..861b07db4 100644
--- a/core/rust/src/timestamp.rs
+++ b/core/rust/src/timestamp.rs
@@ -52,4 +52,12 @@ mod tests {
assert_eq!(at("not a timestamp"), None);
assert_eq!(updated_at(&HashMap::new()), None);
}
+
+ #[test]
+ fn now_uses_the_vault_and_iso_formats() {
+ let stamp = now_vault_datetime();
+ assert_eq!(stamp.len(), 23);
+ assert_eq!(&stamp[10..11], " ");
+ assert!(now_iso_utc().ends_with('Z'));
+ }
}
diff --git a/core/rust/src/uniffi_api.rs b/core/rust/src/uniffi_api.rs
index 38440d553..af717c7e5 100644
--- a/core/rust/src/uniffi_api.rs
+++ b/core/rust/src/uniffi_api.rs
@@ -3,15 +3,12 @@
//! This module exposes the core vault operations via UniFFI for mobile platforms.
//! All functions use JSON strings for input/output to simplify cross-language marshalling.
+use crate::crypto::argon2::Argon2Error;
+use crate::crypto::srp::{SrpEphemeral, SrpError, SrpSession};
use crate::error::{json_call, VaultError};
+use crate::sqlite_host::{MemoryDatabase, SqlResult, SqlValue};
use crate::vault_codec::{self, CanonicalizeInput, DataBucket, ExtractBucketsInput, Manifest, MaterializeInput};
-/// Get the version of the aliasvault-core library.
-#[uniffi::export]
-pub fn get_core_version() -> String {
- crate::get_core_version().to_string()
-}
-
/// Get the list of table names that take part in a vault sync.
#[uniffi::export]
pub fn get_syncable_table_names() -> Vec<String> {
@@ -25,26 +22,8 @@ pub fn merge_canonical_json(input_json: String) -> Result<String, VaultError> {
json_call(&input_json, crate::vault_merge::merge_canonical)
}
-/// Prune expired items from trash (items with DeletedAt older than retention_days).
-///
-/// # Arguments
-/// * `input_json` - JSON string with format:
-/// ```json
-/// {
-/// "tables": [{"name": "Items", "records": [...]}],
-/// "retention_days": 30
-/// }
-/// ```
-///
-/// # Returns
-/// JSON string with format:
-/// ```json
-/// {
-/// "success": true,
-/// "statements": [{"sql": "UPDATE ...", "params": [...]}],
-/// "stats": {"items_pruned": 0, ...}
-/// }
-/// ```
+/// Prune expired items from trash (items with DeletedAt older than retention_days, default 30).
+/// Input: `PruneInput` JSON. Output: `PruneOutput` JSON.
#[uniffi::export]
pub fn prune_vault_json(input_json: String) -> Result<String, VaultError> {
json_call(&input_json, crate::vault_pruner::prune_vault)
@@ -58,27 +37,8 @@ pub fn get_prune_table_queries() -> Vec<crate::vault_pruner::PruneTableQuery> {
crate::vault_pruner::get_prune_table_queries()
}
-/// Filter credentials for autofill based on current URL/app and page title.
-///
-/// # Arguments
-/// * `input_json` - JSON string with format:
-/// ```json
-/// {
-/// "credentials": [{"Id": "...", "ItemName": "...", "ItemUrls": ["url1", "url2"]}],
-/// "current_url": "https://github.com",
-/// "page_title": "GitHub",
-/// "matching_mode": "default"
-/// }
-/// ```
-///
-/// # Returns
-/// JSON string with format:
-/// ```json
-/// {
-/// "matched_ids": ["id1", "id2"],
-/// "matched_priority": 2
-/// }
-/// ```
+/// Filter credentials for autofill by the current URL/app and page title.
+/// Input: `CredentialMatcherInput` JSON. Output: `CredentialMatcherOutput` JSON.
#[uniffi::export]
pub fn filter_credentials_json(input_json: String) -> Result<String, VaultError> {
crate::credential_matcher::filter_credentials_json(&input_json)
@@ -123,17 +83,8 @@ pub fn favicon_source_key(url: String) -> String {
// Password Generator Functions
// ═══════════════════════════════════════════════════════════════════════════════
-/// Generate a password or passphrase from a JSON-serialized `PasswordSettings` object.
-///
-/// The `Type` field selects the generator ("basic" or "diceware"). An optional `Seed`
-/// field (64-character hex string) makes generation deterministic for UI previews.
-///
-/// # Arguments
-/// * `settings_json` - JSON string containing the password settings.
-///
-/// # Returns
-/// The generated password/passphrase string, or a [`VaultError`] if the settings JSON
-/// is invalid.
+/// 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.
#[uniffi::export]
pub fn generate_password(settings_json: String) -> Result<String, VaultError> {
crate::password_generator::generate_password(&settings_json)
@@ -149,17 +100,8 @@ pub fn get_diceware_languages() -> Vec<String> {
// Identity Generator Functions
// ═══════════════════════════════════════════════════════════════════════════════
-/// Generate a random identity from a JSON-serialized request.
-///
-/// The request accepts `language`, `gender` ("male"/"female"/"random"), `ageRange`
-/// (e.g. "21-25" or "random") and/or explicit `birthdateOptions`.
-///
-/// # Arguments
-/// * `request_json` - JSON string, e.g. `{"language":"en","gender":"random","ageRange":"21-25"}`
-///
-/// # Returns
-/// The generated identity as a JSON string with camelCase fields:
-/// `{"firstName":"...","lastName":"...","gender":"Male","birthDate":"1990-05-15","emailPrefix":"...","nickName":"..."}`
+/// Generate a random identity from `IdentityRequest` JSON (`language`, `gender`, `ageRange`, `birthdateOptions`);
+/// returns `Identity` JSON with camelCase fields.
#[uniffi::export]
pub fn generate_identity(request_json: String) -> Result<String, VaultError> {
crate::identity_generator::generate_identity(&request_json)
@@ -268,7 +210,7 @@ pub fn vault_codec_bucket_layout() -> Result<String, VaultError> {
/// The name of the client-local SQLite table that carries the codec overflow inside the vault DB.
#[uniffi::export]
pub fn vault_codec_overflow_table() -> String {
- crate::vault_codec::OVERFLOW_TABLE.to_string()
+ crate::vault_model::OVERFLOW_TABLE.to_string()
}
/// Generate a fresh 32-byte per-manifest blob-hashing salt (lowercase hex).
@@ -277,7 +219,7 @@ pub fn vault_codec_generate_manifest_salt() -> String {
crate::vault_codec::generate_manifest_salt()
}
-/// The `Logos.Id` to use for `source` inside the manifest with id `manifest_id`.
+/// The `Logos.Id` to use for `source` inside the manifest with id `manifest_id`.
/// Every platform derives logo ids via this method to prevent duplicates.
#[uniffi::export]
pub fn vault_codec_logo_id_for_source(manifest_id: String, source: String) -> String {
@@ -346,32 +288,14 @@ pub fn vault_codec_extract_encryption_key_for_public_key(manifest_json: String,
// Argon2id Key Derivation Functions
// ═══════════════════════════════════════════════════════════════════════════════
-pub use crate::crypto::argon2::Argon2Error;
-
-/// Derive a key from a password using Argon2id.
-///
-/// # Arguments
-/// * `password` - The password, hashed as its UTF-8 bytes
-/// * `salt` - The salt, hashed as its UTF-8 bytes, at least 8 bytes long
-/// * `encryption_settings` - The `EncryptionSettings` JSON, or an empty string for the defaults
-///
-/// # Returns
-/// The derived key as 32 bytes
+/// Derive a 32-byte key from a password and salt (UTF-8 bytes) with Argon2id under the `EncryptionSettings`
+/// JSON, or the defaults for an empty string.
#[uniffi::export]
pub fn argon2_derive_key(password: String, salt: String, encryption_settings: String) -> Result<Vec<u8>, Argon2Error> {
crate::crypto::argon2::argon2_derive_key_from_settings(&password, &salt, &encryption_settings)
}
-/// Derive a key from a password using Argon2id, taking the password and salt as raw bytes (the mobile
-/// PIN unlock's Keychain/Keystore salt is random bytes, not UTF-8).
-///
-/// # Arguments
-/// * `password` - The password bytes
-/// * `salt` - The salt bytes, at least 8 bytes long
-/// * `encryption_settings` - The `EncryptionSettings` JSON, or an empty string for the defaults
-///
-/// # Returns
-/// The derived key as 32 bytes
+/// `argon2_derive_key` over raw bytes: the mobile PIN unlock's Keychain/Keystore salt is random bytes, not UTF-8.
#[uniffi::export]
pub fn argon2_derive_key_bytes(password: Vec<u8>, salt: Vec<u8>, encryption_settings: String) -> Result<Vec<u8>, Argon2Error> {
crate::crypto::argon2::argon2_derive_key_bytes_from_settings(&password, &salt, &encryption_settings)
@@ -381,173 +305,46 @@ pub fn argon2_derive_key_bytes(password: Vec<u8>, salt: Vec<u8>, encryption_sett
// SRP (Secure Remote Password) Functions
// ═══════════════════════════════════════════════════════════════════════════════
-pub use crate::crypto::srp::{SrpEphemeral, SrpSession, SrpError};
-
-/// Generate a cryptographic salt for SRP.
-/// Returns a 32-byte random salt as an uppercase hex string.
+/// A random 32-byte SRP salt as an uppercase hex string.
#[uniffi::export]
pub fn srp_generate_salt() -> String {
crate::crypto::srp::srp_generate_salt()
}
-/// Derive the SRP private key (x) from credentials.
-///
-/// # Arguments
-/// * `salt` - Salt as uppercase hex string
-/// * `identity` - User identity (username or SRP identity GUID)
-/// * `password_hash` - Pre-hashed password as uppercase hex string (from Argon2id)
-///
-/// # Returns
-/// Private key as uppercase hex string
-#[uniffi::export]
-pub fn srp_derive_private_key(
- salt: String,
- identity: String,
- password_hash: String,
-) -> Result<String, SrpError> {
+/// The SRP private key (x) as uppercase hex from the hex salt, the identity and the hex password hash.
+#[uniffi::export]
+pub fn srp_derive_private_key(salt: String, identity: String, password_hash: String) -> Result<String, SrpError> {
crate::crypto::srp::srp_derive_private_key(&salt, &identity, &password_hash)
}
-/// Derive the SRP verifier (v) from a private key.
-///
-/// # Arguments
-/// * `private_key` - Private key as uppercase hex string
-///
-/// # Returns
-/// Verifier as uppercase hex string (for registration)
+/// The SRP verifier (v) as uppercase hex from the hex private key, for registration.
#[uniffi::export]
pub fn srp_derive_verifier(private_key: String) -> Result<String, SrpError> {
crate::crypto::srp::srp_derive_verifier(&private_key)
}
-/// Generate a client ephemeral key pair.
-/// Returns a pair of public (A) and secret (a) values as uppercase hex strings.
+/// A client ephemeral pair: public (A) and secret (a) as uppercase hex.
#[uniffi::export]
pub fn srp_generate_ephemeral() -> SrpEphemeral {
crate::crypto::srp::srp_generate_ephemeral()
}
-/// Derive the client session from server response.
-///
-/// # Arguments
-/// * `client_secret` - Client secret ephemeral (a) as hex string
-/// * `server_public` - Server public ephemeral (B) as hex string
-/// * `salt` - Salt as hex string
-/// * `identity` - User identity (username or SRP identity GUID)
-/// * `private_key` - Private key (x) as hex string
-///
-/// # Returns
-/// Session containing proof and key as uppercase hex strings
-#[uniffi::export]
-pub fn srp_derive_session(
- client_secret: String,
- server_public: String,
- salt: String,
- identity: String,
- private_key: String,
-) -> Result<SrpSession, SrpError> {
+/// The client session (proof M1 and key K, uppercase hex) from the server's public ephemeral; hex inputs.
+#[uniffi::export]
+pub fn srp_derive_session(client_secret: String, server_public: String, salt: String, identity: String, private_key: String) -> Result<SrpSession, SrpError> {
crate::crypto::srp::srp_derive_session(&client_secret, &server_public, &salt, &identity, &private_key)
}
-/// Generate a server ephemeral key pair.
-///
-/// # Arguments
-/// * `verifier` - Password verifier (v) as hex string
-///
-/// # Returns
-/// Ephemeral containing public (B) and secret (b) as uppercase hex strings
+/// A server ephemeral pair: public (B) and secret (b) as uppercase hex, from the hex verifier.
#[uniffi::export]
pub fn srp_generate_ephemeral_server(verifier: String) -> Result<SrpEphemeral, SrpError> {
crate::crypto::srp::srp_generate_ephemeral_server(&verifier)
}
-/// Derive and verify the server session from client response.
-///
-/// # Arguments
-/// * `server_secret` - Server secret ephemeral (b) as hex string
-/// * `client_public` - Client public ephemeral (A) as hex string
-/// * `salt` - Salt as hex string (not used in calculation, for API compatibility)
-/// * `identity` - User identity (not used in calculation, for API compatibility)
-/// * `verifier` - Password verifier (v) as hex string
-/// * `client_proof` - Client proof (M1) as hex string
-///
-/// # Returns
-/// Session with server proof and key if client proof is valid, None otherwise
-#[uniffi::export]
-pub fn srp_derive_session_server(
- server_secret: String,
- client_public: String,
- salt: String,
- identity: String,
- verifier: String,
- client_proof: String,
-) -> Result<Option<SrpSession>, SrpError> {
- crate::crypto::srp::srp_derive_session_server(
- &server_secret,
- &client_public,
- &salt,
- &identity,
- &verifier,
- &client_proof,
- )
-}
-
-/// Verify the server's session proof (M2) on the client side: true when the server derived the same session key.
-///
-/// # Arguments
-/// * `client_public` - Client public ephemeral (A) as hex string
-/// * `client_proof` - Client proof (M1) as hex string
-/// * `session_key` - Session key (K) as hex string
-/// * `server_proof` - Server proof (M2) as hex string to verify
+/// The server session (proof M2 and key K) once the client's proof verifies, `None` when it does not; hex inputs.
#[uniffi::export]
-pub fn srp_verify_session(client_public: String, client_proof: String, session_key: String, server_proof: String) -> Result<bool, SrpError> {
- crate::crypto::srp::srp_verify_session(&client_public, &client_proof, &session_key, &server_proof)
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_get_syncable_table_names() {
- let names = get_syncable_table_names();
- assert!(names.contains(&"Items".to_string()));
- assert!(names.contains(&"FieldValues".to_string()));
- assert!(names.contains(&"Settings".to_string()));
- assert!(names.contains(&"ItemStats".to_string()));
- assert!(names.contains(&"EncryptionKeys".to_string()));
- assert!(!names.contains(&crate::vault_codec::OVERFLOW_TABLE.to_string()), "the overflow carrier is not synced as a table of its own; it rides inside the manifest");
- assert_eq!(names.len(), 14);
- }
-
- #[test]
- fn test_prune_vault_json() {
- let input = r#"{
- "tables": [{"name": "Items", "records": []}],
- "retention_days": 30,
- "current_time": "2024-01-15T10:30:00.000Z"
- }"#;
-
- let result = prune_vault_json(input.to_string());
- assert!(result.is_ok());
-
- let output: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
- assert_eq!(output["success"], true);
- }
-
- #[test]
- fn test_extract_domain() {
- // extract_domain strips www. prefix from domains
- assert_eq!(extract_domain("https://www.example.com/path".to_string()), "example.com");
- assert_eq!(extract_domain("http://github.com".to_string()), "github.com");
- assert_eq!(extract_domain("https://subdomain.example.com".to_string()), "subdomain.example.com");
- }
-
- #[test]
- fn test_extract_root_domain() {
- assert_eq!(extract_root_domain("www.example.com".to_string()), "example.com");
- assert_eq!(extract_root_domain("github.com".to_string()), "github.com");
- }
+pub fn srp_derive_session_server(server_secret: String, client_public: String, salt: String, identity: String, verifier: String, client_proof: String) -> Result<Option<SrpSession>, SrpError> {
+ crate::crypto::srp::srp_derive_session_server(&server_secret, &client_public, &salt, &identity, &verifier, &client_proof)
}
// ═══════════════════════════════════════════════════════════════════════════════
@@ -598,12 +395,6 @@ pub fn rsa_decrypt(base64_ciphertext: String, private_key_jwk: String) -> Result
crate::crypto::decrypt_with_private_key(&base64_ciphertext, &private_key_jwk)
}
-/// Create a new account key hierarchy under a base64 KEK. Output: `AccountKeyHierarchy` JSON.
-#[uniffi::export]
-pub fn create_account_key_hierarchy_json(kek_base64: String) -> Result<String, VaultError> {
- Ok(serde_json::to_string(&crate::crypto::create_account_key_hierarchy(&kek_base64)?)?)
-}
-
// ═══════════════════════════════════════════════════════════════════════════════
// Vault sync engine
// ═══════════════════════════════════════════════════════════════════════════════
@@ -637,7 +428,7 @@ impl VaultSyncSession {
/// An in-memory SQLite database that can be used by host applications to be have uniform access to the database.
#[derive(uniffi::Object)]
pub struct SqliteMemoryDatabase {
- inner: crate::sqlite_host::MemoryDatabase,
+ inner: MemoryDatabase,
}
#[uniffi::export]
@@ -645,13 +436,13 @@ impl SqliteMemoryDatabase {
/// Open a database from its SQLite file bytes.
#[uniffi::constructor]
pub fn from_bytes(bytes: Vec<u8>) -> Result<std::sync::Arc<Self>, VaultError> {
- Ok(std::sync::Arc::new(Self { inner: crate::sqlite_host::MemoryDatabase::from_bytes(&bytes)? }))
+ Ok(std::sync::Arc::new(Self { inner: MemoryDatabase::from_bytes(&bytes)? }))
}
/// Open an empty database and run a schema script on it.
#[uniffi::constructor]
pub fn with_schema(schema_sql: String) -> Result<std::sync::Arc<Self>, VaultError> {
- Ok(std::sync::Arc::new(Self { inner: crate::sqlite_host::MemoryDatabase::with_schema(&schema_sql)? }))
+ Ok(std::sync::Arc::new(Self { inner: MemoryDatabase::with_schema(&schema_sql)? }))
}
/// Run a SQL script without parameters.
@@ -667,17 +458,17 @@ impl SqliteMemoryDatabase {
/// Run statements (a JSON array of `{"sql", "params"}`) in one transaction.
pub fn exec(&self, statements_json: String) -> Result<(), VaultError> {
- let statements: Vec<crate::vault_sync::types::SqlStatement> = serde_json::from_str(&statements_json)?;
+ let statements: Vec<crate::sqlite_host::SqlStatement> = serde_json::from_str(&statements_json)?;
self.inner.exec(&statements)
}
/// Run one query with typed parameters; rows come back positionally under `columns`.
- pub fn query_values(&self, sql: String, params: Vec<crate::sqlite_host::SqlValue>) -> Result<crate::sqlite_host::SqlResult, VaultError> {
+ pub fn query_values(&self, sql: String, params: Vec<SqlValue>) -> Result<SqlResult, VaultError> {
self.inner.query_values(&sql, &params)
}
/// Run one statement with typed parameters and return the number of rows it changed.
- pub fn execute(&self, sql: String, params: Vec<crate::sqlite_host::SqlValue>) -> Result<u64, VaultError> {
+ pub fn execute(&self, sql: String, params: Vec<SqlValue>) -> Result<u64, VaultError> {
self.inner.execute(&sql, &params)
}
@@ -686,3 +477,49 @@ impl SqliteMemoryDatabase {
self.inner.export()
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_get_syncable_table_names() {
+ let names = get_syncable_table_names();
+ assert!(names.contains(&"Items".to_string()));
+ assert!(names.contains(&"FieldValues".to_string()));
+ assert!(names.contains(&"Settings".to_string()));
+ assert!(names.contains(&"ItemStats".to_string()));
+ assert!(names.contains(&"EncryptionKeys".to_string()));
+ assert!(!names.contains(&crate::vault_model::OVERFLOW_TABLE.to_string()), "the overflow carrier is not synced as a table of its own; it rides inside the manifest");
+ assert_eq!(names.len(), 14);
+ }
+
+ #[test]
+ fn test_prune_vault_json() {
+ let input = r#"{
+ "tables": [{"name": "Items", "records": []}],
+ "retention_days": 30,
+ "current_time": "2024-01-15T10:30:00.000Z"
+ }"#;
+
+ let result = prune_vault_json(input.to_string());
+ assert!(result.is_ok());
+
+ let output: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
+ assert_eq!(output["success"], true);
+ }
+
+ #[test]
+ fn test_extract_domain() {
+ // extract_domain strips www. prefix from domains
+ assert_eq!(extract_domain("https://www.example.com/path".to_string()), "example.com");
+ assert_eq!(extract_domain("http://github.com".to_string()), "github.com");
+ assert_eq!(extract_domain("https://subdomain.example.com".to_string()), "subdomain.example.com");
+ }
+
+ #[test]
+ fn test_extract_root_domain() {
+ assert_eq!(extract_root_domain("www.example.com".to_string()), "example.com");
+ assert_eq!(extract_root_domain("github.com".to_string()), "github.com");
+ }
+}