Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add fingerprinting to Rust core (#2159)
Leendert de Borst54276b98f178
diff --git a/apps/browser-extension/src/utils/RustCore.ts b/apps/browser-extension/src/utils/RustCore.tsindex 9bb376120..5ca2108d9 100644--- a/apps/browser-extension/src/utils/RustCore.ts+++ b/apps/browser-extension/src/utils/RustCore.ts@@ -356,6 +356,16 @@ export async function vaultCodecComputeCiphertextHash(base64Ciphertext: string):return core.vaultCodecComputeCiphertextHash(base64Ciphertext);}+/**+ * Content fingerprint of a manifest / data-bucket payload JSON for change detection: SHA-256 (lowercase hex)+ * of the Rust codec's canonical JSON, excluding the volatile `canonicalizedAt` timestamp. Calculated in Rust so+ * every platform uses the same fingerprinting algorithm.+ */+export async function vaultCodecComputeContentFingerprint(payloadJson: string): Promise<string> {+ await initRustCore();+ return core.vaultCodecComputeContentFingerprint(payloadJson);+}+/*** Read all non-empty values for a field key from an item, returning them as* a string array (single-value fields are wrapped to a 1-element array).diff --git a/apps/browser-extension/src/utils/WebApiService.ts b/apps/browser-extension/src/utils/WebApiService.tsindex fcf99a639..fb148666d 100644--- a/apps/browser-extension/src/utils/WebApiService.ts+++ b/apps/browser-extension/src/utils/WebApiService.ts@@ -32,17 +32,6 @@ type TokenResponse = {refreshToken: string;}-/**- * How long a fetched /v2/Status response is reused before hitting the network again.- */-const STATUS_CACHE_TTL_MS = 1000;--/**- * Process-wide (background service worker) cache of the last successful /v2/Status response, shared across all- * WebApiService instances.- */-let cachedStatus: { data: StatusResponseV2; timestamp: number } | null = null;-/*** Service class for interacting with the web API.*/@@ -320,20 +309,12 @@ export class WebApiService {* Auth errors (ApiAuthError) are re-thrown to be handled appropriately (e.g., trigger logout).*/public async getStatus(): Promise<StatusResponseV2> {- /*- * Serve a very recent status from the shared cache to prevent multiple round-trips to the server.- */- if (cachedStatus && Date.now() - cachedStatus.timestamp < STATUS_CACHE_TTL_MS) {- return cachedStatus.data;- }-try {const status = await this.get<StatusResponseV2>('Status');// Persist the server version so it can be shown on the settings page, also while offline.if (status.serverVersion && status.serverVersion !== '0.0.0') {await storage.setItem('local:serverVersion', status.serverVersion);}- cachedStatus = { data: status, timestamp: Date.now() };return status;} catch (error) {/**diff --git a/core/rust/src/ffi.rs b/core/rust/src/ffi.rsindex 9f4e126e3..db32591a6 100644--- a/core/rust/src/ffi.rs+++ b/core/rust/src/ffi.rs@@ -318,6 +318,17 @@ pub unsafe extern "C" fn vault_codec_compute_ciphertext_hash_ffi(base64_ciphertestring_to_c_char(crate::vault_codec::compute_ciphertext_hash(s))}+/// Content fingerprint of a manifest / data-bucket payload JSON for change detection: SHA-256 (lowercase+/// hex) of the canonical JSON, excluding the volatile `canonicalizedAt` timestamp.+///+/// # Safety+/// `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_compute_content_fingerprint_ffi(payload_json: *const c_char) -> *mut c_char {+ let s = ffi_read_str!(payload_json, "payload_json");+ string_to_c_char(crate::vault_codec::compute_content_fingerprint(s))+}+/// Pack a payload JSON string. Output: base64 of gzip(envelope{contentHash, payload}). The caller/// base64-decodes, then encrypts.///diff --git a/core/rust/src/lib.rs b/core/rust/src/lib.rsindex f45cc07aa..d4f73efe4 100644--- a/core/rust/src/lib.rs+++ b/core/rust/src/lib.rs@@ -24,7 +24,7 @@ pub use vault_merge::{SYNCABLE_TABLE_NAMES,};pub use vault_codec::{- compute_ciphertext_hash, canonicalize_from_sqlite,+ compute_ciphertext_hash, compute_content_fingerprint, canonicalize_from_sqlite,extract_bucket, generate_user_salt, unpack_payload, materialize_as_sqlite, pack_payload,validate_manifest, validate_data_bucket, BlobEntry,CanonicalizeInput, CanonicalizedVault, CodecRecord, CodecTableData, DataBucket, Manifest,diff --git a/core/rust/src/uniffi_api.rs b/core/rust/src/uniffi_api.rsindex 9492af96a..5bbd22790 100644--- a/core/rust/src/uniffi_api.rs+++ b/core/rust/src/uniffi_api.rs@@ -210,6 +210,13 @@ pub fn vault_codec_compute_ciphertext_hash(base64_ciphertext: String) -> Stringcrate::vault_codec::compute_ciphertext_hash(&base64_ciphertext)}+/// Content fingerprint of a manifest / data-bucket payload JSON for change detection: SHA-256 (lowercase+/// hex) of the canonical JSON, excluding the volatile `canonicalizedAt` timestamp.+#[uniffi::export]+pub fn vault_codec_compute_content_fingerprint(payload_json: String) -> String {+ crate::vault_codec::compute_content_fingerprint(&payload_json)+}+/// Extract the encryption-key row whose `PublicKey` matches `public_key` from the decrypted `EncryptionKeys`/// data bucket. Input: `DataBucket` JSON + the target public key. Output: the matching row JSON object, or/// `null` when no live row carries that key. Chosen over the primary key so a shared-folder VEK wrapped fordiff --git a/core/rust/src/vault_codec/mod.rs b/core/rust/src/vault_codec/mod.rsindex 656cfb358..1dad22103 100644--- a/core/rust/src/vault_codec/mod.rs+++ b/core/rust/src/vault_codec/mod.rs@@ -154,6 +154,23 @@ pub fn compute_ciphertext_hash(base64_ciphertext: &str) -> String {}}+/// Content fingerprint of a manifest / data-bucket payload for client-side change detection: SHA-256+/// (lowercase hex) of the canonical JSON with the volatile top-level `canonicalizedAt` timestamp removed+/// (it is regenerated on every canonicalize and must not read as a content change).+pub fn compute_content_fingerprint(payload_json: &str) -> String {+ match serde_json::from_str::<serde_json::Value>(payload_json) {+ Ok(mut value) => {+ if let Some(obj) = value.as_object_mut() {+ obj.remove("canonicalizedAt");+ }+ hash::content_hash(&value)+ }+ // An unparsable payload hashes to a stable but obviously-wrong value; callers compare equality, so+ // a malformed input simply reads as "changed" (safe: it only forces an upload).+ Err(_) => hash::sha256_hex(payload_json.as_bytes()),+ }+}+// ─────────────────────────────────────────────────────────────────────────────// JSON-string siblings (FFI / UniFFI interface)// ─────────────────────────────────────────────────────────────────────────────diff --git a/core/rust/src/vault_codec/tests.rs b/core/rust/src/vault_codec/tests.rsindex e2bd43b63..7d18ffbee 100644--- a/core/rust/src/vault_codec/tests.rs+++ b/core/rust/src/vault_codec/tests.rs@@ -548,3 +548,46 @@ fn json_siblings_roundtrip() {let materialized: MaterializedTables = serde_json::from_str(&materialized_json).unwrap();assert!(materialized.tables.iter().any(|t| t.name == "Items"));}++#[test]+fn content_fingerprint_ignores_key_order_and_whitespace() {+ let a = compute_content_fingerprint(r#"{"schemaVersion":1,"tables":{"Items":[{"Id":"x","Name":"n"}]}}"#);+ let b = compute_content_fingerprint(r#"{ "tables": { "Items": [ { "Name": "n", "Id": "x" } ] }, "schemaVersion": 1 }"#);+ assert_eq!(a, b);+ assert_eq!(a.len(), 64);+}++#[test]+fn content_fingerprint_excludes_canonicalized_at() {+ let a = compute_content_fingerprint(r#"{"canonicalizedAt":"2026-01-01T00:00:00.000Z","tables":{}}"#);+ let b = compute_content_fingerprint(r#"{"canonicalizedAt":"2026-07-25T12:34:56.789Z","tables":{}}"#);+ let c = compute_content_fingerprint(r#"{"tables":{}}"#);+ assert_eq!(a, b);+ assert_eq!(a, c);+}++#[test]+fn content_fingerprint_detects_content_change() {+ let a = compute_content_fingerprint(r#"{"tables":{"Items":[{"Id":"x"}]}}"#);+ let b = compute_content_fingerprint(r#"{"tables":{"Items":[{"Id":"y"}]}}"#);+ assert_ne!(a, b);+}++#[test]+fn content_fingerprint_matches_serialized_manifest_roundtrip() {+ // A manifest serialized by this codec and the same JSON re-parsed/re-serialized by another producer+ // (different key order) must fingerprint identically.+ let manifest = Manifest {+ schema_version: 1,+ migration_id: "20250101000000_Test".into(),+ version: "2.0.0".into(),+ user_salt: "00ff".into(),+ canonicalized_at: "2026-01-01T00:00:00.000Z".into(),+ shared_folder_id: None,+ tables: std::collections::HashMap::from([(String::from("Items"), vec![])]),+ extra: std::collections::HashMap::new(),+ };+ let serialized = serde_json::to_string(&manifest).unwrap();+ let reordered = r#"{"tables":{"Items":[]},"userSalt":"00ff","version":"2.0.0","migrationId":"20250101000000_Test","schemaVersion":1,"canonicalizedAt":"1999-12-31T23:59:59.000Z"}"#;+ assert_eq!(compute_content_fingerprint(&serialized), compute_content_fingerprint(reordered));+}diff --git a/core/rust/src/wasm.rs b/core/rust/src/wasm.rsindex 691713fc7..80d8e091f 100644--- a/core/rust/src/wasm.rs+++ b/core/rust/src/wasm.rs@@ -214,6 +214,13 @@ pub fn vault_codec_compute_ciphertext_hash_js(base64_ciphertext: &str) -> Stringvault_codec::compute_ciphertext_hash(base64_ciphertext)}+/// Content fingerprint of a manifest / data-bucket payload JSON for change detection: SHA-256 (lowercase+/// hex) of the canonical JSON, excluding the volatile `canonicalizedAt` timestamp.+#[wasm_bindgen(js_name = vaultCodecComputeContentFingerprint)]+pub fn vault_codec_compute_content_fingerprint_js(payload_json: &str) -> String {+ vault_codec::compute_content_fingerprint(payload_json)+}+/// Extract the encryption-key row whose `PublicKey` matches `public_key` from the decrypted `EncryptionKeys`/// data bucket. Input: `DataBucket` + the target public key. Output: the matching row object, or null when/// no live row carries that key.