Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Use central encoding and hex methods (#2159)
Leendert de Borst9b19b4441ecb
diff --git a/core/rust/src/ffi.rs b/core/rust/src/ffi.rsindex 3b244868d..0403408d0 100644--- a/core/rust/src/ffi.rs+++ b/core/rust/src/ffi.rs@@ -7,6 +7,8 @@ use std::ffi::{c_char, CStr, CString};use std::ptr;use crate::credential_matcher::{filter_credentials, CredentialMatcherInput};+use crate::error::json_call;+use crate::vault_codec::{self, CanonicalizeInput, DataBucket, ExtractBucketsInput, Manifest, MaterializeInput};use crate::vault_pruner::{prune_vault, PruneInput};/// Prune expired items from trash.@@ -101,7 +103,7 @@ pub unsafe extern "C" fn filter_credentials_ffi(input_json: *const c_char) -> *m/// A null-terminated C string containing a JSON array of table names.#[no_mangle]pub extern "C" fn get_syncable_table_names_ffi() -> *mut c_char {- let names = crate::vault_merge::syncable_table_names();+ let names = crate::vault_model::SYNCABLE_TABLE_NAMES;match serde_json::to_string(&names) {Ok(json) => string_to_c_char(json),Err(_) => ptr::null_mut(),@@ -189,7 +191,7 @@ unsafe fn codec_json_ffi(/// `input_json` must be a valid null-terminated C string; free the result with `free_string`.#[no_mangle]pub unsafe extern "C" fn vault_codec_canonicalize_from_sqlite_ffi(input_json: *const c_char) -> *mut c_char {- codec_json_ffi(input_json, "input_json", crate::vault_codec::canonicalize_from_sqlite_json)+ codec_json_ffi(input_json, "input_json", |s| json_call(s, |input: CanonicalizeInput| vault_codec::canonicalize_from_sqlite(input)))}/// Materialize manifest + metadata. Input: `MaterializeInput` JSON. Output: `MaterializedTables` JSON.@@ -198,7 +200,7 @@ pub unsafe extern "C" fn vault_codec_canonicalize_from_sqlite_ffi(input_json: *c/// `input_json` must be a valid null-terminated C string; free the result with `free_string`.#[no_mangle]pub unsafe extern "C" fn vault_codec_materialize_as_sqlite_ffi(input_json: *const c_char) -> *mut c_char {- codec_json_ffi(input_json, "input_json", crate::vault_codec::materialize_as_sqlite_json)+ codec_json_ffi(input_json, "input_json", |s| json_call(s, |input: MaterializeInput| vault_codec::materialize_as_sqlite(input)))}/// Build a bucket category's data buckets, one per manifest. Input: `{ category, manifestIds, tables }` JSON.@@ -208,7 +210,7 @@ pub unsafe extern "C" fn vault_codec_materialize_as_sqlite_ffi(input_json: *cons/// `input_json` must be a valid null-terminated C string; free the result with `free_string`.#[no_mangle]pub unsafe extern "C" fn vault_codec_extract_buckets_ffi(input_json: *const c_char) -> *mut c_char {- codec_json_ffi(input_json, "input_json", crate::vault_codec::extract_buckets_json)+ codec_json_ffi(input_json, "input_json", |s| json_call(s, |input: ExtractBucketsInput| vault_codec::extract_buckets(input.category, input.manifest_ids, input.tables)))}/// Validate a manifest. Input: `Manifest` JSON. Output: `ValidationResult` JSON.@@ -217,7 +219,7 @@ pub unsafe extern "C" fn vault_codec_extract_buckets_ffi(input_json: *const c_ch/// `input_json` must be a valid null-terminated C string; free the result with `free_string`.#[no_mangle]pub unsafe extern "C" fn vault_codec_validate_manifest_ffi(input_json: *const c_char) -> *mut c_char {- codec_json_ffi(input_json, "input_json", crate::vault_codec::validate_manifest_json)+ codec_json_ffi(input_json, "input_json", |s| json_call(s, |manifest: Manifest| Ok(vault_codec::validate_manifest(&manifest))))}/// Validate a data bucket. Input: `DataBucket` JSON. Output: `ValidationResult` JSON.@@ -226,7 +228,7 @@ pub unsafe extern "C" fn vault_codec_validate_manifest_ffi(input_json: *const c_/// `input_json` must be a valid null-terminated C string; free the result with `free_string`.#[no_mangle]pub unsafe extern "C" fn vault_codec_validate_data_bucket_ffi(input_json: *const c_char) -> *mut c_char {- codec_json_ffi(input_json, "input_json", crate::vault_codec::validate_data_bucket_json)+ codec_json_ffi(input_json, "input_json", |s| json_call(s, |bucket: DataBucket| Ok(vault_codec::validate_data_bucket(&bucket))))}/// Extract the encryption-key row whose `PublicKey` matches `public_key` from a decrypted manifest's@@ -238,7 +240,7 @@ pub unsafe extern "C" fn vault_codec_validate_data_bucket_ffi(input_json: *constpub unsafe extern "C" fn vault_codec_extract_encryption_key_for_public_key_ffi(input_json: *const c_char, public_key: *const c_char) -> *mut c_char {let manifest = ffi_read_str!(input_json, "input_json");let key = ffi_read_str!(public_key, "public_key");- match crate::vault_codec::extract_encryption_key_for_public_key_json(manifest, key) {+ match json_call(manifest, |manifest: Manifest| Ok(vault_codec::extract_encryption_key_for_public_key(&manifest, key))) {Ok(json) => string_to_c_char(json),Err(e) => create_error_response(&format!("vault_codec error: {}", e)),}@@ -250,7 +252,7 @@ pub unsafe extern "C" fn vault_codec_extract_encryption_key_for_public_key_ffi(i/// Free the result with `free_string`.#[no_mangle]pub extern "C" fn vault_codec_bucket_layout_ffi() -> *mut c_char {- match crate::vault_codec::bucket_layout_json() {+ match serde_json::to_string(&vault_codec::bucket_layout()) {Ok(json) => string_to_c_char(json),Err(e) => create_error_response(&format!("vault_codec error: {}", e)),}@@ -293,11 +295,9 @@ pub unsafe extern "C" fn vault_codec_compute_content_fingerprint_ffi(payload_jso/// `payload_json` must be a valid null-terminated C string; free the result with `free_string`.#[no_mangle]pub unsafe extern "C" fn vault_codec_pack_payload_ffi(payload_json: *const c_char) -> *mut c_char {- use base64::engine::general_purpose::STANDARD as BASE64;- use base64::Engine;let s = ffi_read_str!(payload_json, "payload_json");match crate::vault_codec::pack_payload(s) {- Ok(bytes) => string_to_c_char(BASE64.encode(bytes)),+ Ok(bytes) => string_to_c_char(crate::encoding::base64_encode(&bytes)),Err(e) => create_error_response(&format!("pack_payload error: {}", e)),}}@@ -308,10 +308,8 @@ pub unsafe extern "C" fn vault_codec_pack_payload_ffi(payload_json: *const c_cha/// `base64_plain_bytes` must be a valid null-terminated C string; free the result with `free_string`.#[no_mangle]pub unsafe extern "C" fn vault_codec_unpack_payload_ffi(base64_plain_bytes: *const c_char) -> *mut c_char {- use base64::engine::general_purpose::STANDARD as BASE64;- use base64::Engine;let s = ffi_read_str!(base64_plain_bytes, "base64_plain_bytes");- let bytes = match BASE64.decode(s) {+ let bytes = match crate::encoding::base64_decode(s) {Ok(b) => b,Err(e) => return create_error_response(&format!("invalid base64: {}", e)),};diff --git a/core/rust/src/hex.rs b/core/rust/src/hex.rsdeleted file mode 100644index 4395db775..000000000--- a/core/rust/src/hex.rs+++ /dev/null@@ -1,12 +0,0 @@-//! Crate-internal hex encoding helpers.--/// Convert bytes to uppercase hex string.-pub(crate) fn bytes_to_hex(bytes: &[u8]) -> String {- const HEX: &[u8; 16] = b"0123456789ABCDEF";- let mut out = String::with_capacity(bytes.len() * 2);- for &b in bytes {- out.push(HEX[(b >> 4) as usize] as char);- out.push(HEX[(b & 0x0F) as usize] as char);- }- out-}diff --git a/core/rust/src/lib.rs b/core/rust/src/lib.rsindex 0d15da32c..84502934f 100644--- a/core/rust/src/lib.rs+++ b/core/rust/src/lib.rs@@ -1,22 +1,27 @@//! AliasVault Core Library//!//! Cross-platform core functionality for AliasVault, including:+//! - **vault_model**: the client vault datamodel registry, generated from `core/models`+//! - **vault_codec**: the manifest-v1 storage format, mapped to and from the local SQLite vault//! - **vault_merge**: Vault merge using Last-Write-Wins (LWW) strategy//! - **vault_sharing**: Sharing write logic for multi-manifest vaults//! - **vault_pruner**: Prunes expired items from trash (30-day retention)+//! - **vault_sync**: the vault sync engine that every client uses for syncing with the server//! - **credential_matcher**: Cross-platform credential filtering for autofill+//! - **email_parser**: RFC 822 email parsing into bodies and attachment metadata//! - **favicon**: Favicon handling and source selection//! - **password_generator**: Password and passphrase (Diceware) 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-//! - **vault_sync**: the sans-IO vault sync engine every client drives+//! - **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 hex;+mod encoding;pub mod timestamp;mod rng;pub mod vault_model;@@ -33,10 +38,8 @@ pub mod crypto;pub mod vault_sync;pub use error::VaultError;-pub use vault_merge::{- merge_canonical, merge_canonical_json, CanonicalManifestMerge, CanonicalMergeInput,- CanonicalMergeOutput, MergeStats, SqlStatement, SYNCABLE_TABLE_NAMES,-};+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,@@ -61,9 +64,9 @@ 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_from_settings, Argon2Error, Argon2Params,+ 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_generate_ephemeral, srp_derive_session, srp_verify_session,srp_generate_ephemeral_server, srp_derive_session_server,SrpEphemeral, SrpSession, SrpError,};@@ -72,9 +75,6 @@ pub use crypto::{#[cfg(feature = "wasm")]pub mod wasm;-#[cfg(feature = "wasm")]-pub use wasm::*;-// C FFI exports for .NET P/Invoke#[cfg(feature = "ffi")]pub mod ffi;@@ -83,9 +83,6 @@ pub mod ffi;#[cfg(feature = "uniffi")]pub mod uniffi_api;-#[cfg(feature = "uniffi")]-pub use uniffi_api::*;-// UniFFI scaffolding - generates the FFI glue code#[cfg(feature = "uniffi")]uniffi::setup_scaffolding!();diff --git a/core/rust/src/password_generator/defaults.rs b/core/rust/src/password_generator/defaults.rsindex 825afda7d..88f415bf9 100644--- a/core/rust/src/password_generator/defaults.rs+++ b/core/rust/src/password_generator/defaults.rs@@ -1,6 +1,6 @@//! Client-facing defaults for the password/passphrase generator.//!-//! @generated — do NOT edit this file directly. It is generated from+//! @generated: do NOT edit this file directly. It is generated from//! core/models/src/defaults/PasswordGeneratorDefaults.ts by core/models/scripts/generate-password-defaults.cjs.//! Edit the TypeScript source and run 'core/models/build.sh' to regenerate.diff --git a/core/rust/src/password_generator/tests.rs b/core/rust/src/password_generator/tests.rsindex 1ef724ae8..011d1558c 100644--- a/core/rust/src/password_generator/tests.rs+++ b/core/rust/src/password_generator/tests.rs@@ -168,7 +168,7 @@ fn same_seed_yields_same_output() {#[test]fn same_seed_different_separator_keeps_words() {- // With the same seed, only the separator should change — the words stay identical.+ // With the same seed, only the separator should change; the words stay identical.let dash = generate_password(&format!(r#"{{"Type":"diceware","WordCount":4,"Separator":"Dash","Seed":"{TEST_SEED}"}}"#))@@ -186,7 +186,7 @@ fn same_seed_different_separator_keeps_words() {#[test]fn invalid_seed_falls_back_to_random() {- // A malformed seed must not error — it falls back to a random seed.+ // A malformed seed must not error; it falls back to a random seed.let pw = generate_password(r#"{"Type":"diceware","Seed":"not-hex"}"#).unwrap();assert!(!pw.is_empty());}diff --git a/core/rust/src/password_generator/wordlists/mod.rs b/core/rust/src/password_generator/wordlists/mod.rsindex 48447a95a..55ed72e72 100644--- a/core/rust/src/password_generator/wordlists/mod.rs+++ b/core/rust/src/password_generator/wordlists/mod.rs@@ -5,7 +5,7 @@//!//! Languages are keyed by a free-text code (case-insensitive). Adding a new language is a//! Rust-only change: drop the `<code>.diceware` file in this directory and add one entry to-//! the `WORDLISTS` registry below — no changes are needed in the TypeScript model or the+//! the `WORDLISTS` registry below; no changes are needed in the TypeScript model or the//! apps. Unknown codes fall back to English./// The registry of bundled wordlists, as `(code, raw text)`. The code is the normalized two-letterdiff --git a/core/rust/src/rng.rs b/core/rust/src/rng.rsindex 154e02cd6..e998b0532 100644--- a/core/rust/src/rng.rs+++ b/core/rust/src/rng.rs@@ -1,8 +1,13 @@-//! Shared RNG helpers used by the generator modules (password, identity).+//! Randomness: the one OS entropy entry point and the seedable RNG the generator modules use.use rand::rngs::StdRng;use rand::{RngCore, SeedableRng};+/// Fill a buffer from the operating system's CSPRNG.+pub(crate) fn fill_random(dest: &mut [u8]) {+ getrandom::fill(dest).expect("the OS CSPRNG is unavailable");+}+/// Build the RNG used for generation.////// If `seed` is a valid 64-character hex string (32 bytes), the RNG is deterministically@@ -13,20 +18,13 @@ pub(crate) fn make_rng(seed: Option<&str>) -> StdRng {}let mut bytes = [0u8; 32];- rand::rng().fill_bytes(&mut bytes);+ fill_random(&mut bytes);StdRng::from_seed(bytes)}/// Parse a 64-character hex string into a 32-byte seed, or `None` if it is malformed.fn parse_seed_hex(hex: &str) -> Option<[u8; 32]> {- if hex.len() != 64 {- return None;- }- let mut bytes = [0u8; 32];- for (i, byte) in bytes.iter_mut().enumerate() {- *byte = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).ok()?;- }- Some(bytes)+ crate::encoding::hex_decode(hex)?.try_into().ok()}/// Get an unbiased random index in `0..max` using rejection sampling over the given CSPRNG.@@ -86,4 +84,11 @@ mod tests {assert!(unbiased_index(&mut rng, usize::MAX) < usize::MAX);}}++ #[test]+ fn seed_must_be_exactly_32_bytes_of_hex() {+ assert!(parse_seed_hex(&"ab".repeat(32)).is_some());+ assert!(parse_seed_hex(&"ab".repeat(31)).is_none());+ assert!(parse_seed_hex(&"zz".repeat(32)).is_none());+ }}diff --git a/core/rust/src/timestamp.rs b/core/rust/src/timestamp.rsindex 66427f6b9..1d876786c 100644--- a/core/rust/src/timestamp.rs+++ b/core/rust/src/timestamp.rs@@ -1,6 +1,8 @@//! The timestamp formats the vault data model uses.-use chrono::{DateTime, Utc};+use std::collections::HashMap;++use chrono::{DateTime, NaiveDateTime, Utc};/// ISO-8601 UTC with milliseconds (`2026-01-01T00:00:00.000Z`): canonicalized payloads and prune input.pub const ISO_UTC_MILLIS: &str = "%Y-%m-%dT%H:%M:%S%.3fZ";@@ -22,3 +24,32 @@ pub fn now_iso_utc() -> String {pub fn now_vault_datetime() -> String {Utc::now().format(VAULT_DATETIME).to_string()}++/// Parse either spelling a vault carries: RFC3339 (`2025-12-11T06:50:10.674Z`, what the codec+/// writes) or the SQLite row form (`2025-12-11 06:50:10.674`, read as UTC).+pub fn parse_vault_datetime(text: &str) -> Option<DateTime<Utc>> {+ DateTime::parse_from_rfc3339(text)+ .map(|dt| dt.with_timezone(&Utc))+ .ok()+ .or_else(|| NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M:%S%.f").ok().map(|naive| naive.and_utc()))+}++/// A row's `UpdatedAt`, or `None` when absent or unparsable.+pub fn updated_at(row: &HashMap<String, serde_json::Value>) -> Option<DateTime<Utc>> {+ row.get("UpdatedAt").and_then(|v| v.as_str()).and_then(parse_vault_datetime)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn updated_at_parses_both_spellings_a_vault_carries() {+ let at = |value: &str| -> Option<DateTime<Utc>> { updated_at(&HashMap::from([("UpdatedAt".to_string(), serde_json::json!(value))])) };++ assert_eq!(at("2025-12-11T06:50:10.674Z"), at("2025-12-11 06:50:10.674"));+ assert!(at("2025-12-11T06:50:11Z") > at("2025-12-11 06:50:10.674"));+ assert_eq!(at("not a timestamp"), None);+ assert_eq!(updated_at(&HashMap::new()), None);+ }+}diff --git a/core/rust/src/uniffi_api.rs b/core/rust/src/uniffi_api.rsindex 61dba0a99..d5c7bdeb5 100644--- a/core/rust/src/uniffi_api.rs+++ b/core/rust/src/uniffi_api.rs@@ -3,7 +3,8 @@//! 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::error::VaultError;+use crate::error::{json_call, VaultError};+use crate::vault_codec::{self, CanonicalizeInput, DataBucket, ExtractBucketsInput, Manifest, MaterializeInput};/// Get the version of the aliasvault-core library.#[uniffi::export]@@ -14,14 +15,14 @@ pub fn get_core_version() -> String {/// 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_merge::syncable_table_names().iter().map(|s| s.to_string()).collect()+ crate::vault_model::SYNCABLE_TABLE_NAMES.iter().map(|s| s.to_string()).collect()}/// Merge the local canonical vault onto the server canonical vault (manifest-v1 format), one/// manifest at a time, rows out. Input: `CanonicalMergeInput` JSON. Output: `CanonicalMergeOutput` JSON.#[uniffi::export]pub fn merge_canonical_json(input_json: String) -> Result<String, VaultError> {- crate::vault_merge::merge_canonical_json(&input_json)+ json_call(&input_json, crate::vault_merge::merge_canonical)}/// Prune expired items from trash (items with DeletedAt older than retention_days).@@ -46,7 +47,7 @@ pub fn merge_canonical_json(input_json: String) -> Result<String, VaultError> {/// ```#[uniffi::export]pub fn prune_vault_json(input_json: String) -> Result<String, VaultError> {- crate::vault_pruner::prune_vault_json(&input_json)+ json_call(&input_json, crate::vault_pruner::prune_vault)}/// Get the per-table SELECT queries used to build prune input.@@ -81,7 +82,6 @@ pub fn get_prune_table_queries() -> Vec<crate::vault_pruner::PruneTableQuery> {#[uniffi::export]pub fn filter_credentials_json(input_json: String) -> Result<String, VaultError> {crate::credential_matcher::filter_credentials_json(&input_json)- .map_err(|e| VaultError::General(e))}/// Extract domain from a URL.@@ -225,44 +225,44 @@ pub fn get_identity_age_ranges() -> Vec<String> {/// Resolve which manifests the next push writes, personal manifest first.#[uniffi::export]pub fn vault_sharing_resolve_manifest_write_set(input_json: String) -> Result<String, VaultError> {- crate::vault_sharing::resolve_manifest_write_set_json(&input_json)+ json_call(&input_json, |request| Ok(crate::vault_sharing::resolve_manifest_write_set(request)))}/// Split what the vault holds into what cannot be written and what access was lost.#[uniffi::export]pub fn vault_sharing_partition_manifest_access(input_json: String) -> Result<String, VaultError> {- crate::vault_sharing::partition_manifest_access_json(&input_json)+ json_call(&input_json, |request| Ok(crate::vault_sharing::partition_manifest_access(request)))}// ═══════════════════════════════════════════════════════════════════════════════-// Vault Codec Functions (manifest-v1 storage format) — JSON-string in/out.+// Vault Codec Functions (manifest-v1 storage format), JSON-string in/out.// ═══════════════════════════════════════════════════════════════════════════════/// Canonicalize normalized tables into manifest + metadata + blob map./// Input: `CanonicalizeInput` JSON. Output: `CanonicalizedVault` JSON.#[uniffi::export]pub fn vault_codec_canonicalize_from_sqlite(input_json: String) -> Result<String, VaultError> {- crate::vault_codec::canonicalize_from_sqlite_json(&input_json)+ json_call(&input_json, |input: CanonicalizeInput| vault_codec::canonicalize_from_sqlite(input))}/// Materialize manifest + metadata into the table set the platform inserts./// Input: `MaterializeInput` JSON. Output: `MaterializedTables` JSON.#[uniffi::export]pub fn vault_codec_materialize_as_sqlite(input_json: String) -> Result<String, VaultError> {- crate::vault_codec::materialize_as_sqlite_json(&input_json)+ json_call(&input_json, |input: MaterializeInput| vault_codec::materialize_as_sqlite(input))}/// Build a bucket category's data buckets, one per manifest this vault writes./// Input: `{ category, manifestIds, tables }` JSON. Output: `DataBucket[]` JSON.#[uniffi::export]pub fn vault_codec_extract_buckets(input_json: String) -> Result<String, VaultError> {- crate::vault_codec::extract_buckets_json(&input_json)+ json_call(&input_json, |input: ExtractBucketsInput| vault_codec::extract_buckets(input.category, input.manifest_ids, input.tables))}/// The bucket layout: `[{ category, tables: [<name>] }]` JSON. Source of truth for bucket-only sync.#[uniffi::export]pub fn vault_codec_bucket_layout() -> Result<String, VaultError> {- crate::vault_codec::bucket_layout_json()+ Ok(serde_json::to_string(&vault_codec::bucket_layout())?)}/// The name of the client-local SQLite table that carries the codec overflow inside the vault DB.@@ -313,13 +313,13 @@ pub fn vault_codec_unpack_payload(plain_bytes: Vec<u8>) -> Result<String, VaultE/// Structurally validate a manifest. Input: `Manifest` JSON. Output: `ValidationResult` JSON.#[uniffi::export]pub fn vault_codec_validate_manifest(manifest_json: String) -> Result<String, VaultError> {- crate::vault_codec::validate_manifest_json(&manifest_json)+ json_call(&manifest_json, |manifest: Manifest| Ok(vault_codec::validate_manifest(&manifest)))}/// Validate a data bucket. Input: `DataBucket` JSON. Output: `ValidationResult` JSON.#[uniffi::export]pub fn vault_codec_validate_data_bucket(data_bucket_json: String) -> Result<String, VaultError> {- crate::vault_codec::validate_data_bucket_json(&data_bucket_json)+ json_call(&data_bucket_json, |bucket: DataBucket| Ok(vault_codec::validate_data_bucket(&bucket)))}/// SHA-256 (lowercase hex) of a base64 ciphertext string.@@ -339,7 +339,7 @@ pub fn vault_codec_compute_content_fingerprint(payload_json: String) -> String {/// `EncryptionKeys` table.#[uniffi::export]pub fn vault_codec_extract_encryption_key_for_public_key(manifest_json: String, public_key: String) -> Result<String, VaultError> {- crate::vault_codec::extract_encryption_key_for_public_key_json(&manifest_json, &public_key)+ json_call(&manifest_json, |manifest: Manifest| Ok(vault_codec::extract_encryption_key_for_public_key(&manifest, &public_key)))}// ═══════════════════════════════════════════════════════════════════════════════@@ -362,10 +362,8 @@ pub fn argon2_derive_key(password: String, salt: String, encryption_settings: Stcrate::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.-///-/// Note: the mobile PIN unlock draws its salt from the Keychain/Keystore as random bytes, which are-/// not valid UTF-8 and require this direct byte-salt entry point.+/// 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@@ -376,8 +374,7 @@ pub fn argon2_derive_key(password: String, salt: String, encryption_settings: St/// The derived key as 32 bytes#[uniffi::export]pub fn argon2_derive_key_bytes(password: Vec<u8>, salt: Vec<u8>, encryption_settings: String) -> Result<Vec<u8>, Argon2Error> {- let params = crate::crypto::argon2::Argon2Params::from_settings_json(&encryption_settings)?;- crate::crypto::argon2::argon2_derive_key(&password, &salt, params)+ crate::crypto::argon2::argon2_derive_key_bytes_from_settings(&password, &salt, &encryption_settings)}// ═══════════════════════════════════════════════════════════════════════════════@@ -495,6 +492,18 @@ pub fn srp_derive_session_server()}+/// 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+#[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::*;@@ -554,7 +563,7 @@ pub fn aes_gcm_encrypt(plaintext: Vec<u8>, key_base64: String) -> Result<String,/// AES-256-GCM decrypt base64 `IV | ciphertext | tag` with a base64 key.#[uniffi::export]pub fn aes_gcm_decrypt(base64_ciphertext: String, key_base64: String) -> Result<Vec<u8>, VaultError> {- let bytes = crate::crypto::aes_gcm::decode_base64(&base64_ciphertext)?;+ let bytes = crate::encoding::base64_decode(&base64_ciphertext)?;crate::crypto::symmetric_decrypt_bytes(&bytes, &key_base64)}diff --git a/core/rust/src/vault_codec/canonicalize.rs b/core/rust/src/vault_codec/canonicalize.rsindex aba230c18..985808132 100644--- a/core/rust/src/vault_codec/canonicalize.rs+++ b/core/rust/src/vault_codec/canonicalize.rs@@ -12,8 +12,6 @@use std::collections::HashMap;-use base64::engine::general_purpose::STANDARD as BASE64;-use base64::Engine;use serde_json::{json, Value};use super::normalize::{normalize_id_spelling, normalize_row_shapes};@@ -286,7 +284,7 @@ fn extract_blob_cell(None => return serde_json::Value::Null,};- let bytes = match BASE64.decode(b64) {+ let bytes = match crate::encoding::base64_decode(b64) {Ok(b) if !b.is_empty() => b,_ => return serde_json::Value::Null,};@@ -336,8 +334,9 @@ fn primary_key_of(identity: &str) -> &str {identity.rsplit('\u{1f}').next().unwrap_or(identity)}-/// Build `category`'s data buckets from its already-normalized tables (name > rows): the bucket-only push-/// path, taken when a bucket changed but the manifest did not.+/// Build `category`'s data buckets, one per manifest in `manifest_ids`, from the category's tables as the+/// platform reads them out of its local vault (name > rows): the bucket-only push path, taken when a bucket+/// changed but the manifest did not. Rows route by the manifest each one names, exactly as the full push routes them.////// Include the [`OVERFLOW_TABLE`] row in `tables` (read it alongside the category's tables) so a newer/// writer's columns/tables re-merge and survive; it is consumed and never emitted into a bucket.diff --git a/core/rust/src/vault_codec/hash.rs b/core/rust/src/vault_codec/hash.rsindex cf5dcacf8..67a8a6122 100644--- a/core/rust/src/vault_codec/hash.rs+++ b/core/rust/src/vault_codec/hash.rs@@ -8,8 +8,8 @@//! one platform and re-hashed by another would fail integrity even when byte-identical. This module is//! the single canonical-serialization contract every binding reproduces.//!-//! [`canonical_json`] is intentionally byte-compatible with the original `VaultIntegrity.ts`-//! `canonicalize()`:+//! [`canonical_json`] is intentionally byte-compatible with the TypeScript `canonicalize()` the+//! clients used before the codec moved into Rust://! - object keys sorted ascending, recursively;//! - arrays kept in order;//! - primitives serialized exactly as `JSON.stringify` would (serde_json matches JS for the@@ -17,58 +17,25 @@use sha2::{Digest, Sha256};-/// Lowercase hex of a byte slice. Matches the browser extension's lowercase hashing.-pub fn bytes_to_hex(bytes: &[u8]) -> String {- let mut s = String::with_capacity(bytes.len() * 2);- for b in bytes {- s.push_str(&format!("{:02x}", b));- }- s-}+use crate::encoding::{format_uuid, hex_decode, hex_encode_lower};-/// Generate a GUID derived from a string.+/// A UUIDv8 derived from a string: the first 16 bytes of its sha256, version and variant bits set.pub fn derived_uuid(material: &str) -> String {- let digest = sha256_hex(material.as_bytes());+ let digest = Sha256::digest(material.as_bytes());let mut bytes = [0u8; 16];- for (i, byte) in bytes.iter_mut().enumerate() {- *byte = u8::from_str_radix(&digest[i * 2..i * 2 + 2], 16).unwrap_or(0);- }+ bytes.copy_from_slice(&digest[..16]);bytes[6] = (bytes[6] & 0x0f) | 0x80;bytes[8] = (bytes[8] & 0x3f) | 0x80;-- let hex = bytes_to_hex(&bytes);- format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])-}--/// Decode a lowercase/uppercase hex string into bytes. Returns `None` on malformed input.-pub fn hex_to_bytes(hex: &str) -> Option<Vec<u8>> {- if hex.len() % 2 != 0 {- return None;- }- let mut out = Vec::with_capacity(hex.len() / 2);- let bytes = hex.as_bytes();- let mut i = 0;- while i < bytes.len() {- let hi = (bytes[i] as char).to_digit(16)?;- let lo = (bytes[i + 1] as char).to_digit(16)?;- out.push(((hi << 4) | lo) as u8);- i += 2;- }- Some(out)+ format_uuid(&bytes)}/// SHA-256 of arbitrary bytes, returned as lowercase hex.pub fn sha256_hex(bytes: &[u8]) -> String {- let mut hasher = Sha256::new();- hasher.update(bytes);- bytes_to_hex(&hasher.finalize())+ hex_encode_lower(&Sha256::digest(bytes))}-/// Canonicalize a JSON value into a stable string for hashing.-///-/// Serializes JSON with object keys sorted recursively, arrays kept in order,-// and primitives serialized using `serde_json::to_string` for string-escaping-// and integer values present in vault data.+/// Canonicalize a JSON value into a stable string for hashing: object keys sorted recursively, arrays+/// kept in order, primitives as `serde_json::to_string` renders them.pub fn canonical_json(value: &serde_json::Value) -> String {match value {serde_json::Value::Object(map) => {@@ -110,11 +77,11 @@ pub fn content_hash(value: &serde_json::Value) -> String {/// Per-manifest salted blob hash `sha256(salt_bytes ‖ plaintext_bytes)`, lowercase hex.pub fn salted_blob_hash(bytes: &[u8], manifest_salt: &str) -> String {- let salt_bytes = hex_to_bytes(manifest_salt).unwrap_or_default();+ let salt_bytes = hex_decode(manifest_salt).unwrap_or_default();let mut hasher = Sha256::new();hasher.update(&salt_bytes);hasher.update(bytes);- bytes_to_hex(&hasher.finalize())+ hex_encode_lower(&hasher.finalize())}#[cfg(test)]@@ -142,11 +109,12 @@ mod tests {}#[test]- fn hex_roundtrip() {- let bytes = vec![0x00u8, 0x1f, 0xab, 0xff];- let hex = bytes_to_hex(&bytes);- assert_eq!(hex, "001fabff");- assert_eq!(hex_to_bytes(&hex).unwrap(), bytes);+ fn derived_uuid_is_stable_and_well_formed() {+ let id = derived_uuid("aliasvault:test");+ assert_eq!(id, derived_uuid("aliasvault:test"));+ assert_eq!(id.len(), 36);+ assert_eq!(&id[14..15], "8");+ assert!(matches!(&id[19..20], "8" | "9" | "a" | "b"));}#[test]diff --git a/core/rust/src/vault_codec/mod.rs b/core/rust/src/vault_codec/mod.rsindex b3e8f416c..d13019f5f 100644--- a/core/rust/src/vault_codec/mod.rs+++ b/core/rust/src/vault_codec/mod.rs@@ -13,55 +13,29 @@ pub(crate) mod normalize;mod hash;mod manifest;mod materialize;+pub(crate) mod row;mod scoped_assets;mod sharing;mod types;mod validate;-use std::collections::HashMap;--use base64::engine::general_purpose::STANDARD as BASE64;-use base64::Engine;use serde_json::json;+use crate::encoding::{base64_decode, hex_encode_lower};use crate::error::{VaultError, VaultResult};+use crate::vault_model::names::LOGO_KIND_FAVICON;+use types::SCHEMA_VERSION;+pub use canonicalize::{canonicalize_from_sqlite, extract_buckets};pub use manifest::{BlobEntry, BucketLayoutEntry, CanonicalizeInput, CanonicalizedManifest, CanonicalizedVault, CodecOverflow, DataBucket,ExtractBucketsInput, Manifest, MaterializeInput, MaterializedTables, CodecRecord, CodecTableData, ManifestSpec,};-pub use scoped_assets::{KIND_BUILTIN as LOGO_KIND_BUILTIN, KIND_CUSTOM as LOGO_KIND_CUSTOM, KIND_FAVICON as LOGO_KIND_FAVICON};-pub use sharing::{active_encryption_key, extract_encryption_key_for_public_key};-pub use types::{- bucket_categories, bucket_category_for, identity_part, is_bucketed_table, is_personal_table, tables_for_category, BLOB_COLUMNS, BUCKET_TABLES,- ENCRYPTION_KEYS_TABLE, MANIFESTS_TABLE, MANIFEST_ID_COL, MULTI_VALUE_FIELD_KEYS, OVERFLOW_TABLE, PERSONAL_TABLES, SCHEMA_VERSION,- SKIP_TABLES,-};-pub use validate::ValidationResult;--// ─────────────────────────────────────────────────────────────────────────────-// canonicalize_from_sqlite / materialize_as_sqlite-// ─────────────────────────────────────────────────────────────────────────────--/// Canonicalize normalized tables into manifest + data buckets + blob map.-pub fn canonicalize_from_sqlite(input: CanonicalizeInput) -> VaultResult<CanonicalizedVault> {- canonicalize::canonicalize_from_sqlite(input)-}--/// Materialize the vault's manifests + data buckets into the table set the platform inserts into a fresh schema DB.-pub fn materialize_as_sqlite(input: MaterializeInput) -> VaultResult<MaterializedTables> {- materialize::materialize_as_sqlite(input)-}--/// Build `category`'s data buckets, one per manifest in `manifest_ids`, from the category's tables as the-/// platform reads them out of its local vault (bucket-only push path). Rows route by the manifest each one-/// names, exactly as the full push routes them.-///-/// Include the [`OVERFLOW_TABLE`] row in `tables` (read it alongside the category's tables) so a newer-/// writer's columns/tables re-merge and survive; it is consumed and never emitted into a bucket.-pub fn extract_buckets(category: String, manifest_ids: Vec<String>, tables: HashMap<String, Vec<CodecRecord>>) -> VaultResult<Vec<DataBucket>> {- canonicalize::extract_buckets(category, manifest_ids, tables)-}+pub use materialize::materialize_as_sqlite;+pub use scoped_assets::logo_id_for;+pub use sharing::extract_encryption_key_for_public_key;+pub use types::{bucket_categories, identity_part, is_bucketed_table, tables_for_category, MANIFEST_ID_COL, OVERFLOW_TABLE};+pub use validate::{validate_data_bucket, validate_manifest, ValidationResult};/// The bucket layout: every category and the tables it owns, in declaration order.pub fn bucket_layout() -> Vec<BucketLayoutEntry> {@@ -74,36 +48,25 @@ pub fn bucket_layout() -> Vec<BucketLayoutEntry> {.collect()}-/// The `Logos.Id` a client must use for the logo `(kind, source)` inside the manifest with id-/// `manifest_id`.-pub fn logo_id_for(manifest_id: &str, kind: &str, source: &str) -> String {- scoped_assets::logo_id_for(manifest_id, kind, source)-}-/// The `Logos.Id` for the automatically fetched favicon of `source`. Shorthand for [`logo_id_for`]/// with [`LOGO_KIND_FAVICON`].pub fn logo_id_for_source(manifest_id: &str, source: &str) -> String {- scoped_assets::logo_id_for(manifest_id, LOGO_KIND_FAVICON, source)+ logo_id_for(manifest_id, LOGO_KIND_FAVICON, source)}/// The sha256 (lowercase hex) of an uploaded logo's bytes: the `Source` of a-/// [`LOGO_KIND_CUSTOM`] row. Exposed so we ensure every platform hashes identically.+/// [`LOGO_KIND_CUSTOM`](crate::vault_model::names::LOGO_KIND_CUSTOM) row. Exposed so every platform hashes identically.pub fn logo_content_hash(bytes: &[u8]) -> String {hash::sha256_hex(bytes)}/// Generate a fresh 32-byte per-manifest blob-hashing salt as a lowercase hex string.pub fn generate_manifest_salt() -> String {- use rand::RngCore;let mut bytes = [0u8; 32];- rand::rng().fill_bytes(&mut bytes);- hash::bytes_to_hex(&bytes)+ crate::rng::fill_random(&mut bytes);+ hex_encode_lower(&bytes)}-// ─────────────────────────────────────────────────────────────────────────────-// packing: envelope + canonical hash + gzip.-// ─────────────────────────────────────────────────────────────────────────────-/// Wrap a payload JSON string in an integrity envelope (`{ schemaVersion, contentHash, payload }`)/// and gzip it.pub fn pack_payload(payload_json: &str) -> VaultResult<Vec<u8>> {@@ -140,7 +103,7 @@ pub fn unpack_payload(plain_bytes: &[u8]) -> VaultResult<String> {let expected = hash::content_hash(payload);if expected != content_hash {return Err(VaultError::General(format!(- "contentHash mismatch (expected {}, got {}). Vault may be corrupt — do not load.",+ "contentHash mismatch (expected {}, got {}). Vault may be corrupt, do not load.",content_hash, expected)));}@@ -148,33 +111,12 @@ pub fn unpack_payload(plain_bytes: &[u8]) -> VaultResult<String> {Ok(serde_json::to_string(payload)?)}-// ─────────────────────────────────────────────────────────────────────────────-// integrity checks-// ─────────────────────────────────────────────────────────────────────────────--/// Structurally validate a manifest before upload.-pub fn validate_manifest(m: &Manifest) -> ValidationResult {- validate::validate_manifest(m)-}--/// Validate a data bucket before upload.-pub fn validate_data_bucket(b: &DataBucket) -> ValidationResult {- validate::validate_data_bucket(b)-}--/// Extract the encryption-key row whose `PublicKey` matches `public_key` from a decrypted manifest's-/// `EncryptionKeys` table (scoped to the manifest itself; see [`extract_encryption_key_for_public_key`]).-pub fn extract_encryption_key_for_public_key_json(manifest_json: &str, public_key: &str) -> VaultResult<String> {- let m: Manifest = serde_json::from_str(manifest_json)?;- Ok(serde_json::to_string(&extract_encryption_key_for_public_key(&m, public_key))?)-}--/// SHA-256 (lowercase hex) of a base64 ciphertext string — storage-layer integrity.+/// SHA-256 (lowercase hex) of a base64 ciphertext string: storage-layer integrity.pub fn compute_ciphertext_hash(base64_ciphertext: &str) -> String {- match BASE64.decode(base64_ciphertext) {+ match base64_decode(base64_ciphertext) {Ok(raw) => hash::sha256_hex(&raw),- // Mirror nothing weird: an undecodable input hashes to a stable but obviously-wrong value;- // callers compare equality so a malformed input simply fails the check.+ // An undecodable input still yields a stable hash; callers compare equality, so a malformed+ // input simply fails the check.Err(_) => hash::sha256_hex(base64_ciphertext.as_bytes()),}}@@ -196,46 +138,6 @@ pub fn compute_content_fingerprint(payload_json: &str) -> String {}}-// ─────────────────────────────────────────────────────────────────────────────-// JSON-string siblings (FFI / UniFFI interface)-// ─────────────────────────────────────────────────────────────────────────────--/// JSON-string sibling of [`canonicalize_from_sqlite`].-pub fn canonicalize_from_sqlite_json(input_json: &str) -> VaultResult<String> {- let input: CanonicalizeInput = serde_json::from_str(input_json)?;- Ok(serde_json::to_string(&canonicalize_from_sqlite(input)?)?)-}--/// JSON-string sibling of [`materialize_as_sqlite`].-pub fn materialize_as_sqlite_json(input_json: &str) -> VaultResult<String> {- let input: MaterializeInput = serde_json::from_str(input_json)?;- Ok(serde_json::to_string(&materialize_as_sqlite(input)?)?)-}--/// JSON-string sibling of [`extract_buckets`].-/// Input: `{ "category": <str>, "manifestIds": [<str>], "tables": { <name>: [rows] } }`.-pub fn extract_buckets_json(input_json: &str) -> VaultResult<String> {- let input: ExtractBucketsInput = serde_json::from_str(input_json)?;- Ok(serde_json::to_string(&extract_buckets(input.category, input.manifest_ids, input.tables)?)?)-}--/// JSON-string sibling of [`bucket_layout`]. Output: `[{ "category": <str>, "tables": [<str>] }]`.-pub fn bucket_layout_json() -> VaultResult<String> {- Ok(serde_json::to_string(&bucket_layout())?)-}--/// JSON-string sibling of [`validate_manifest`].-pub fn validate_manifest_json(manifest_json: &str) -> VaultResult<String> {- let m: Manifest = serde_json::from_str(manifest_json)?;- Ok(serde_json::to_string(&validate_manifest(&m))?)-}--/// JSON-string sibling of [`validate_data_bucket`].-pub fn validate_data_bucket_json(data_bucket_json: &str) -> VaultResult<String> {- let b: DataBucket = serde_json::from_str(data_bucket_json)?;- Ok(serde_json::to_string(&validate_data_bucket(&b))?)-}-#[cfg(test)]mod tests;diff --git a/core/rust/src/vault_sync/db.rs b/core/rust/src/vault_sync/db.rsindex eefcfd26f..8d0181942 100644--- a/core/rust/src/vault_sync/db.rs+++ b/core/rust/src/vault_sync/db.rs@@ -2,14 +2,13 @@use std::collections::HashMap;-use base64::engine::general_purpose::STANDARD as BASE64;-use base64::Engine;use serde_json::{json, Map, Value};use super::errors::{SyncError, SyncResult};use super::session::Host;use super::types::{Ack, Command, Db, DbBytes, DbRows, LogLevel, SqlStatement};-use super::version;+use super::legacy;+use crate::encoding::{base64_decode, base64_encode};use crate::vault_codec::{CodecRecord, CodecTableData, MaterializedTables};pub(crate) type Row = Map<String, Value>;@@ -39,37 +38,18 @@ pub(crate) async fn exec_one(host: &Host, db: Db, sql: &str, params: Vec<Value>)/// Open the staging database: fresh with the current schema, or from SQLite bytes.pub(crate) async fn open_staging(host: &Host, bytes: Option<&[u8]>) -> SyncResult<()> {- host.call::<Ack>(Command::DbOpen { db: Db::Staging, bytes: bytes.map(|b| BASE64.encode(b)) }).await?;+ host.call::<Ack>(Command::DbOpen { db: Db::Staging, bytes: bytes.map(base64_encode) }).await?;Ok(())}/// Serialize a database to SQLite bytes.pub(crate) async fn export(host: &Host, db: Db) -> SyncResult<Vec<u8>> {let response: DbBytes = host.call(Command::DbExport { db }).await?;- BASE64.decode(response.bytes).map_err(|_| SyncError::Other("host returned invalid database bytes".to_string()))+ base64_decode(&response.bytes).map_err(|_| SyncError::Other("host returned invalid database bytes".to_string()))}pub(crate) fn b64_param(bytes: &[u8]) -> Value {- json!({ "__b64": BASE64.encode(bytes) })-}--/// The lookup key of a manifest id: ids compare case-insensitively.-pub(crate) fn id_key(id: &str) -> String {- id.to_lowercase()-}--pub(crate) fn ids_equal(a: &str, b: &str) -> bool {- a.eq_ignore_ascii_case(b)-}--/// SQLite booleans arrive as 0/1 numbers or as JSON booleans.-pub(crate) fn truthy(value: Option<&Value>) -> bool {- match value {- Some(Value::Bool(b)) => *b,- Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0 || n.as_f64().unwrap_or(0.0) != 0.0,- Some(Value::String(s)) => s == "1" || s.eq_ignore_ascii_case("true"),- _ => false,- }+ json!({ "__b64": base64_encode(bytes) })}/// A cell as text: strings as they are, null as empty, anything else in its JSON form.@@ -141,27 +121,26 @@ pub(crate) async fn latest_migration_id(host: &Host, db: Db) -> SyncResult<StrinOk(rows.first().and_then(|row| row.get("MigrationId")).and_then(Value::as_str).unwrap_or("").to_string())}-/// Whether the local vault still has to walk the frozen sqlite-blob upgrade chain (a pre-2.0.0 vault).-pub(crate) async fn requires_legacy_sqlite_blob_migration(host: &Host, db: Db) -> SyncResult<bool> {- let migration_id = latest_migration_id(host, db).await?;- if migration_id.is_empty() {- return Err(SyncError::Other("No migrations found in the database.".to_string()));- }- let database_version = version::extract_version_from_migration_id(&migration_id).ok_or_else(|| SyncError::Other("Could not extract version from migration ID".to_string()))?;- let revision = version::legacy_revision_for(&database_version).map_err(SyncError::VaultVersionIncompatible)?;- Ok(revision < version::latest_legacy_revision())+/// Where the local vault's schema stands against the current one.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum SchemaState {+ /// LEGACY: still on the frozen sqlite-blob upgrade chain (a pre-2.0.0 vault), which the host walks first.+ LegacyChain,+ /// Predates the current full schema; the manifest migration rebuilds it locally.+ Stale,+ Current,}-/// Whether the local schema predates the current full schema (whose stamp the staging database carries).-pub(crate) async fn requires_schema_migration(host: &Host, schema_migration_id: &str) -> SyncResult<bool> {- if requires_legacy_sqlite_blob_migration(host, Db::Local).await? {- return Ok(false);- }+/// Classify the local vault's schema against the current one (whose stamp the staging database carries).+pub(crate) async fn schema_state(host: &Host, current_migration_id: &str) -> SyncResult<SchemaState> {let local = latest_migration_id(host, Db::Local).await?;- if local.is_empty() || schema_migration_id.is_empty() {- return Ok(false);+ if local.is_empty() {+ return Err(SyncError::Other("No migrations found in the database.".to_string()));+ }+ if legacy::stamp_predates_manifest_schema(&local)? {+ return Ok(SchemaState::LegacyChain);}- Ok(local.as_str() < schema_migration_id)+ Ok(if !current_migration_id.is_empty() && local.as_str() < current_migration_id { SchemaState::Stale } else { SchemaState::Current })}pub(crate) async fn has_column(host: &Host, db: Db, table: &str, column: &str) -> SyncResult<bool> {@@ -256,12 +235,10 @@ pub(crate) fn now_iso() -> String {/// A random lowercase UUID v4.pub(crate) fn new_id() -> String {let mut bytes = [0u8; 16];- crate::crypto::fill_random(&mut bytes);+ crate::rng::fill_random(&mut bytes);bytes[6] = (bytes[6] & 0x0f) | 0x40;bytes[8] = (bytes[8] & 0x3f) | 0x80;- let hex: Vec<String> = bytes.iter().map(|b| format!("{:02x}", b)).collect();- let hex = hex.join("");- format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])+ crate::encoding::format_uuid(&bytes)}pub(crate) const GET_ACTIVE_KEY_FOR_MANIFEST: &str = "SELECT x.Id, x.PublicKey, x.PrivateKey, x.IsPrimary FROM EncryptionKeys x WHERE x.ManifestId = ? AND x.IsPrimary = 1 AND x.IsDeleted = 0 LIMIT 1";