Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Remove Rust FFI bindings as dotnet does not call it and it has no further planned usages (#2159)
Leendert de Borstf061faaa214a
diff --git a/.gitignore b/.gitignoreindex 63a17b76a..039c30311 100644--- a/.gitignore+++ b/.gitignore@@ -451,8 +451,7 @@ core/rust/target/# Browser WASM for web app and extension (built by: cd core/rust && ./build.sh --web or --browser-extension)core/client/wasm-# Server .NET bindings (built by: cd core/rust && ./build.sh --server)-apps/server/Utilities/AliasVault.RustCore/+# Blazor client browser WASM (built by: cd core/rust && ./build.sh --web)apps/server/AliasVault.Client/wwwroot/wasm# Client JS bundle (built by: npm run build:js in apps/server/AliasVault.Client)diff --git a/core/build-and-distribute.sh b/core/build-and-distribute.shindex 5d4a48664..4b8167663 100755--- a/core/build-and-distribute.sh+++ b/core/build-and-distribute.sh@@ -6,7 +6,6 @@ set -u # Treat unset variables as errors# Build mode selectionBUILD_ALL=falseBROWSER_TARGET="" # "web" or "browser-extension": both write core/client/wasm, so one per run-BUILD_DOTNET=falseBUILD_IOS=falseBUILD_ANDROID=falseBUILD_COMMON=true # Always build TypeScript utils, models, and vault@@ -26,10 +25,6 @@ while [[ $# -gt 0 ]]; doecho "Error: --browser was split into --web (size-optimized) and --browser-extension (speed-optimized)"exit 1;;- --dotnet)- BUILD_DOTNET=true- shift- ;;--ios)BUILD_IOS=trueshift@@ -40,7 +35,6 @@ while [[ $# -gt 0 ]]; do;;--all)BROWSER_TARGET="${BROWSER_TARGET:-web}"- BUILD_DOTNET=trueBUILD_ANDROID=true# Note: iOS excluded from --all as it requires macOS/Xcode (use --ios explicitly)shift@@ -51,10 +45,9 @@ while [[ $# -gt 0 ]]; doecho "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"echo " --ios Build for iOS with Swift bindings"echo " --android Build for Android with Kotlin bindings"- echo " --all Build cross-platform targets (web, dotnet, android)"+ echo " --all Build cross-platform targets (web, android)"echo ""echo "Notes:"echo " - iOS requires macOS/Xcode, use --ios explicitly (not included in --all)"@@ -71,10 +64,9 @@ while [[ $# -gt 0 ]]; dodone# If no targets specified, build cross-platform targets (iOS excluded - requires macOS)-if [ -z "$BROWSER_TARGET" ] && ! $BUILD_DOTNET && ! $BUILD_IOS && ! $BUILD_ANDROID; then+if [ -z "$BROWSER_TARGET" ] && ! $BUILD_IOS && ! $BUILD_ANDROID; thenecho "No target specified, building cross-platform targets..."BROWSER_TARGET="web"- BUILD_DOTNET=trueBUILD_ANDROID=truefi@@ -104,7 +96,7 @@ if $BUILD_COMMON; thenfi# Rust core build (required when any platform target is specified)-if [ -n "$BROWSER_TARGET" ] || $BUILD_DOTNET || $BUILD_IOS || $BUILD_ANDROID; then+if [ -n "$BROWSER_TARGET" ] || $BUILD_IOS || $BUILD_ANDROID; thencd ./rustif ! command -v rustc &> /dev/null; then@@ -113,7 +105,6 @@ if [ -n "$BROWSER_TARGET" ] || $BUILD_DOTNET || $BUILD_IOS || $BUILD_ANDROID; thecho ""echo " Requested targets require Rust:"[ -n "$BROWSER_TARGET" ] && echo " - Browser/WASM ($BROWSER_TARGET)"- $BUILD_DOTNET && echo " - .NET"$BUILD_IOS && echo " - iOS"$BUILD_ANDROID && echo " - Android"exit 1@@ -136,11 +127,6 @@ if [ -n "$BROWSER_TARGET" ] || $BUILD_DOTNET || $BUILD_IOS || $BUILD_ANDROID; th./build.sh --"$BROWSER_TARGET"fi- if $BUILD_DOTNET; then- echo " → Building for .NET..."- ./build.sh --dotnet- fi-echo "✅ Rust core built"cd ..diff --git a/core/rust/Cargo.toml b/core/rust/Cargo.tomlindex b175d73c3..920db0889 100644--- a/core/rust/Cargo.toml+++ b/core/rust/Cargo.toml@@ -26,8 +26,6 @@ uniffi = ["dep:uniffi"]uniffi-cli = ["uniffi/cli"]# Feature for WASM builds (browser extension)wasm = ["dep:wasm-bindgen", "dep:serde-wasm-bindgen", "dep:console_error_panic_hook", "dep:js-sys"]-# Feature for C FFI exports (.NET P/Invoke)-ffi = [][dependencies]# Serialization - core dependency for JSON handling@@ -115,8 +113,3 @@ 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 = 3diff --git a/core/rust/README.md b/core/rust/README.mdindex 2b269ac64..440c362a6 100644--- a/core/rust/README.md+++ b/core/rust/README.md@@ -5,7 +5,6 @@ Cross-platform core library providing shared business logic for all AliasVault c- **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)-- **.NET** (C FFI exports for P/Invoke, built with `--dotnet`; nothing consumes them yet)## Core Modules@@ -65,16 +64,15 @@ type with the JSON-in/JSON-out call helper the bindings share../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+(`extension` profile), iOS and Android (`mobile` profile) build with `opt-level = 3`, which+trades a few megabytes for faster sync, since those ship as a one time download. Both WASM builds write to `core/client/wasm`, so locally theapps run whichever was built last. Every build bundles SQLite behind-`SqliteMemoryDatabase` (the .NET C exports included), which hosts every client's vault database in+`SqliteMemoryDatabase`, which hosts every client's vault database inmemory (the sync engine's staging database included), so all clients run one SQLite build and the phones neverwrite 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.diff --git a/core/rust/build.sh b/core/rust/build.shindex 010c40ea0..ba162f251 100755--- a/core/rust/build.sh+++ b/core/rust/build.sh@@ -17,7 +17,6 @@ cd "$SCRIPT_DIR"# Output directoriesDIST_DIR="$SCRIPT_DIR/dist"WASM_DIR="$DIST_DIR/wasm"-DOTNET_DIR="$DIST_DIR/dotnet"IOS_DIR="$DIST_DIR/ios"ANDROID_DIR="$DIST_DIR/android"@@ -79,7 +78,6 @@ echo -e " Rust version: ${GREEN}$RUST_VERSION${NC}"# Build mode selectionBUILD_ALL=falseBROWSER_TARGET="" # "web" or "browser-extension": both write core/client/wasm, so one per run-BUILD_DOTNET=falseBUILD_IOS=falseBUILD_ANDROID=falseINCREMENTAL=false@@ -100,10 +98,6 @@ while [[ $# -gt 0 ]]; doecho -e "${RED}Error: --browser was split into --web (size-optimized) and --browser-extension (speed-optimized)${NC}"exit 1;;- --dotnet)- BUILD_DOTNET=true- shift- ;;--ios)BUILD_IOS=trueshift@@ -114,7 +108,6 @@ while [[ $# -gt 0 ]]; do;;--all)BROWSER_TARGET="${BROWSER_TARGET:-web}"- BUILD_DOTNET=trueBUILD_IOS=trueBUILD_ANDROID=trueshift@@ -133,7 +126,6 @@ while [[ $# -gt 0 ]]; doecho "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, 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)"@@ -155,13 +147,12 @@ while [[ $# -gt 0 ]]; dodone# If no targets specified, show help-if [ -z "$BROWSER_TARGET" ] && ! $BUILD_DOTNET && ! $BUILD_IOS && ! $BUILD_ANDROID; then+if [ -z "$BROWSER_TARGET" ] && ! $BUILD_IOS && ! $BUILD_ANDROID; thenecho "No target specified. Use --help for usage."echo ""echo "Quick start:"echo " ./build.sh --web # Build for web app"echo " ./build.sh --browser-extension # Build for browser extension"- echo " ./build.sh --dotnet # Build for .NET"echo " ./build.sh --ios # Build for iOS"echo " ./build.sh --android # Build for Android"exit 0@@ -267,80 +258,6 @@ README_EOFfi}-# ============================================-# .NET Build (Native Library with FFI)-# ============================================-build_dotnet() {- echo ""- echo -e "${BLUE}Building native library for .NET...${NC}"-- local start_time=$(date +%s)-- # Detect current platform- local os_name- local arch_name- local lib_name- local target_dir-- case "$(uname -s)" in- Darwin)- os_name="macos"- lib_name="libaliasvault_core.dylib"- ;;- Linux)- os_name="linux"- lib_name="libaliasvault_core.so"- ;;- MINGW*|MSYS*|CYGWIN*)- os_name="windows"- lib_name="aliasvault_core.dll"- ;;- *)- echo -e "${RED}Unsupported OS: $(uname -s)${NC}"- exit 1- ;;- esac-- case "$(uname -m)" in- x86_64|amd64)- arch_name="x64"- ;;- arm64|aarch64)- arch_name="arm64"- ;;- *)- arch_name="$(uname -m)"- ;;- esac-- target_dir="$DOTNET_DIR/${os_name}-${arch_name}"- mkdir -p "$target_dir"-- echo -e " Platform: ${YELLOW}${os_name}-${arch_name}${NC}"-- # Build with cargo- echo -e " Running cargo build..."- cargo build --profile dotnet --features ffi- local cargo_target="target/dotnet"-- # Copy the library- if [ -f "$cargo_target/$lib_name" ]; then- cp "$cargo_target/$lib_name" "$target_dir/"- local lib_size- lib_size=$(ls -lh "$target_dir/$lib_name" | awk '{print $5}')- echo -e "${GREEN}Native library built! ${NC}"- echo -e " Output: ${YELLOW}$target_dir/$lib_name${NC}"- echo -e " Size: ${YELLOW}$lib_size${NC}"- else- echo -e "${RED}Build failed: $lib_name not found${NC}"- exit 1- fi-- local end_time=$(date +%s)- local duration=$((end_time - start_time))- echo -e "${GREEN}.NET build complete! (${duration}s)${NC}"-}-# ============================================# iOS Build (ARM64 only - device + simulator)# ============================================@@ -729,13 +646,6 @@ if [ -n "$BROWSER_TARGET" ]; thendistribute_browserfi-if $BUILD_DOTNET; then- build_dotnet- # Note: dotnet native libs are built to dist/dotnet/ but not distributed- # Blazor WASM uses the WASM module via JS interop instead- echo -e "${YELLOW}Note: Native library built to dist/dotnet/ (for server-side .NET use)${NC}"-fi-if $BUILD_IOS; thenIOS_BUILD_SKIPPED=falsebuild_iosdiff --git a/core/rust/src/ffi.rs b/core/rust/src/ffi.rsdeleted file mode 100644index 86c6ee4c9..000000000--- a/core/rust/src/ffi.rs+++ /dev/null@@ -1,834 +0,0 @@-//! C FFI exports for .NET P/Invoke.-//!-//! These functions provide a C-compatible interface for calling Rust functions from C#.--use std::ffi::{c_char, CStr, CString};-use std::ptr;--use serde_json::Value;--use crate::credential_matcher::{filter_credentials, CredentialMatcherInput};-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::sqlite_host::SqlStatement;--/// Prune expired items from trash.-///-/// Items with DeletedAt older than retention_days are marked as permanently deleted.-///-/// # Safety-///-/// - `input_json` must be a valid null-terminated C string-/// - The returned pointer must be freed by calling `free_string`-///-/// # Returns-///-/// A null-terminated C string containing the JSON result (PruneOutput).-/// Returns null on error.-#[no_mangle]-pub unsafe extern "C" fn prune_vault_ffi(input_json: *const c_char) -> *mut c_char {- if input_json.is_null() {- return ptr::null_mut();- }-- let c_str = match CStr::from_ptr(input_json).to_str() {- Ok(s) => s,- Err(_) => return ptr::null_mut(),- };-- let input: PruneInput = match serde_json::from_str(c_str) {- Ok(i) => i,- Err(e) => {- return create_error_response(&format!("Failed to parse input: {}", e));- }- };-- let output = match prune_vault(input) {- Ok(o) => o,- Err(e) => {- return create_error_response(&format!("Prune failed: {}", e));- }- };-- match serde_json::to_string(&output) {- Ok(json) => string_to_c_char(json),- Err(e) => create_error_response(&format!("Failed to serialize output: {}", e)),- }-}--/// Filter credentials for autofill.-///-/// # Safety-///-/// - `input_json` must be a valid null-terminated C string-/// - The returned pointer must be freed by calling `free_string`-///-/// # Returns-///-/// A null-terminated C string containing the JSON result (CredentialMatcherOutput).-/// Returns null on error.-#[no_mangle]-pub unsafe extern "C" fn filter_credentials_ffi(input_json: *const c_char) -> *mut c_char {- if input_json.is_null() {- return ptr::null_mut();- }-- let c_str = match CStr::from_ptr(input_json).to_str() {- Ok(s) => s,- Err(_) => return ptr::null_mut(),- };-- let input: CredentialMatcherInput = match serde_json::from_str(c_str) {- Ok(i) => i,- Err(e) => {- return create_error_response(&format!("Failed to parse input: {}", e));- }- };-- let output = filter_credentials(input);-- match serde_json::to_string(&output) {- Ok(json) => string_to_c_char(json),- Err(e) => create_error_response(&format!("Failed to serialize output: {}", e)),- }-}--/// Get the list of syncable table names as a JSON array.-///-/// # Safety-///-/// - The returned pointer must be freed by calling `free_string`-///-/// # Returns-///-/// 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_model::SYNCABLE_TABLE_NAMES;- match serde_json::to_string(&names) {- Ok(json) => string_to_c_char(json),- Err(_) => ptr::null_mut(),- }-}--/// Get the per-table SELECT queries used to build prune input, as a JSON array-/// of `{ "name": ..., "query": ... }` objects. Blob columns are reduced to a-/// 1-byte presence marker to avoid serializing large binary data to JSON.-#[no_mangle]-pub extern "C" fn get_prune_table_queries_ffi() -> *mut c_char {- match serde_json::to_string(&crate::vault_pruner::get_prune_table_queries()) {- Ok(json) => string_to_c_char(json),- Err(_) => ptr::null_mut(),- }-}--/// Free a string that was allocated by Rust.-///-/// # Safety-///-/// - `s` must be a pointer that was returned by one of the FFI functions-/// - This function must only be called once per pointer-/// - After calling this function, the pointer is invalid-#[no_mangle]-pub unsafe extern "C" fn free_string(s: *mut c_char) {- if !s.is_null() {- drop(CString::from_raw(s));- }-}--/// Convert a Rust string to a C string pointer.-fn string_to_c_char(s: String) -> *mut c_char {- match CString::new(s) {- Ok(c_string) => c_string.into_raw(),- Err(_) => ptr::null_mut(),- }-}--/// Create an error response JSON string.-fn create_error_response(message: &str) -> *mut c_char {- string_to_c_char(serde_json::json!({ "success": false, "error": message }).to_string())-}--// ═══════════════════════════════════════════════════════════════════════════════-// Vault Codec FFI Functions (manifest-v1 storage format)-// ═══════════════════════════════════════════════════════════════════════════════--/// Read a JSON c-string argument, returning an error response on null / invalid UTF-8.-macro_rules! ffi_read_str {- ($ptr:expr, $name:literal) => {{- if $ptr.is_null() {- return create_error_response(concat!("Null pointer argument: ", $name));- }- match CStr::from_ptr($ptr).to_str() {- Ok(s) => s,- Err(_) => return create_error_response(concat!("Invalid UTF-8 in ", $name)),- }- }};-}--/// Wrap a `fn(&str) -> VaultResult<String>` codec entry point as a C FFI function.-unsafe fn codec_json_ffi(- input_json: *const c_char,- arg_name: &'static str,- f: impl Fn(&str) -> crate::error::VaultResult<String>,-) -> *mut c_char {- if input_json.is_null() {- return create_error_response(&format!("Null pointer argument: {}", arg_name));- }- let c_str = match CStr::from_ptr(input_json).to_str() {- Ok(s) => s,- Err(_) => return create_error_response(&format!("Invalid UTF-8 in {}", arg_name)),- };- match f(c_str) {- Ok(json) => string_to_c_char(json),- Err(e) => create_error_response(&format!("vault_codec error: {}", e)),- }-}--/// Canonicalize normalized tables. Input: `CanonicalizeInput` JSON. Output: `CanonicalizedVault` JSON.-///-/// # Safety-/// `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", |s| json_call(s, |input: CanonicalizeInput| vault_codec::canonicalize_from_sqlite(input)))-}--/// Materialize manifest + metadata. Input: `MaterializeInput` JSON. Output: `MaterializedTables` JSON.-///-/// # Safety-/// `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", |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.-/// Output: `DataBucket[]` JSON.-///-/// # Safety-/// `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", |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.-///-/// # Safety-/// `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", |s| json_call(s, |manifest: Manifest| Ok(vault_codec::validate_manifest(&manifest))))-}--/// Validate a data bucket. Input: `DataBucket` JSON. Output: `ValidationResult` JSON.-///-/// # Safety-/// `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", |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-/// `EncryptionKeys` table.-///-/// # Safety-/// `input_json` and `public_key` must be valid null-terminated C strings; free the result with `free_string`.-#[no_mangle]-pub 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 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)),- }-}--/// The bucket layout: `[{ category, tables: [<name>] }]` JSON.-///-/// # Safety-/// Free the result with `free_string`.-#[no_mangle]-pub extern "C" fn vault_codec_bucket_layout_ffi() -> *mut c_char {- 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)),- }-}--/// Generate a fresh per-manifest blob-hashing salt (lowercase hex).-///-/// # Safety-/// Free the result with `free_string`.-#[no_mangle]-pub extern "C" fn vault_codec_generate_manifest_salt_ffi() -> *mut c_char {- string_to_c_char(crate::vault_codec::generate_manifest_salt())-}--/// SHA-256 (lowercase hex) of a base64 ciphertext string.-///-/// # Safety-/// `base64_ciphertext` must be a valid null-terminated C string; free the result with `free_string`.-#[no_mangle]-pub unsafe extern "C" fn vault_codec_compute_ciphertext_hash_ffi(base64_ciphertext: *const c_char) -> *mut c_char {- let s = ffi_read_str!(base64_ciphertext, "base64_ciphertext");- string_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.-///-/// # 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_pack_payload_ffi(payload_json: *const c_char) -> *mut c_char {- let s = ffi_read_str!(payload_json, "payload_json");- match crate::vault_codec::pack_payload(s) {- Ok(bytes) => string_to_c_char(crate::encoding::base64_encode(&bytes)),- Err(e) => create_error_response(&format!("pack_payload error: {}", e)),- }-}--/// Unpack a payload supplied as base64 of the decrypted bytes. Output: payload JSON string.-///-/// # Safety-/// `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 {- let s = ffi_read_str!(base64_plain_bytes, "base64_plain_bytes");- let bytes = match crate::encoding::base64_decode(s) {- Ok(b) => b,- Err(e) => return create_error_response(&format!("invalid base64: {}", e)),- };- match crate::vault_codec::unpack_payload(&bytes) {- Ok(json) => string_to_c_char(json),- Err(e) => create_error_response(&format!("unpack_payload error: {}", e)),- }-}--// ═══════════════════════════════════════════════════════════════════════════════-// SRP (Secure Remote Password) FFI Functions-// ═══════════════════════════════════════════════════════════════════════════════--/// Generate a cryptographic salt for SRP.-///-/// # Safety-///-/// - The returned pointer must be freed by calling `free_string`-///-/// # Returns-///-/// A null-terminated C string containing the salt as uppercase hex.-#[no_mangle]-pub extern "C" fn srp_generate_salt_ffi() -> *mut c_char {- string_to_c_char(crate::crypto::srp::srp_generate_salt())-}--/// Derive the SRP private key from credentials.-///-/// # Safety-///-/// - All input pointers must be valid null-terminated C strings-/// - The returned pointer must be freed by calling `free_string`-///-/// # Returns-///-/// A null-terminated C string containing the private key as uppercase hex,-/// or an error JSON if the inputs are invalid.-#[no_mangle]-pub unsafe extern "C" fn srp_derive_private_key_ffi(- salt: *const c_char,- identity: *const c_char,- password_hash: *const c_char,-) -> *mut c_char {- if salt.is_null() || identity.is_null() || password_hash.is_null() {- return create_error_response("Null pointer argument");- }-- let salt_str = match CStr::from_ptr(salt).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in salt"),- };-- let identity_str = match CStr::from_ptr(identity).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in identity"),- };-- let password_hash_str = match CStr::from_ptr(password_hash).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in password_hash"),- };-- match crate::crypto::srp::srp_derive_private_key(salt_str, identity_str, password_hash_str) {- Ok(key) => string_to_c_char(key),- Err(e) => create_error_response(&format!("SRP error: {}", e)),- }-}--/// Derive the SRP verifier from a private key.-///-/// # Safety-///-/// - `private_key` must be a valid null-terminated C string-/// - The returned pointer must be freed by calling `free_string`-///-/// # Returns-///-/// A null-terminated C string containing the verifier as uppercase hex,-/// or an error JSON if the input is invalid.-#[no_mangle]-pub unsafe extern "C" fn srp_derive_verifier_ffi(private_key: *const c_char) -> *mut c_char {- if private_key.is_null() {- return create_error_response("Null pointer argument");- }-- let private_key_str = match CStr::from_ptr(private_key).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in private_key"),- };-- match crate::crypto::srp::srp_derive_verifier(private_key_str) {- Ok(verifier) => string_to_c_char(verifier),- Err(e) => create_error_response(&format!("SRP error: {}", e)),- }-}--/// Generate a client ephemeral key pair.-///-/// # Safety-///-/// - The returned pointer must be freed by calling `free_string`-///-/// # Returns-///-/// A null-terminated C string containing JSON: {"public": "...", "secret": "..."}-#[no_mangle]-pub extern "C" fn srp_generate_ephemeral_ffi() -> *mut c_char {- let ephemeral = crate::crypto::srp::srp_generate_ephemeral();- match serde_json::to_string(&ephemeral) {- Ok(json) => string_to_c_char(json),- Err(e) => create_error_response(&format!("Failed to serialize ephemeral: {}", e)),- }-}--/// Derive the client session from server response.-///-/// # Safety-///-/// - All input pointers must be valid null-terminated C strings-/// - The returned pointer must be freed by calling `free_string`-///-/// # Returns-///-/// A null-terminated C string containing JSON: {"proof": "...", "key": "..."}-/// or an error JSON if inputs are invalid.-#[no_mangle]-pub unsafe extern "C" fn srp_derive_session_ffi(- client_secret: *const c_char,- server_public: *const c_char,- salt: *const c_char,- identity: *const c_char,- private_key: *const c_char,-) -> *mut c_char {- if client_secret.is_null() || server_public.is_null() || salt.is_null()- || identity.is_null() || private_key.is_null()- {- return create_error_response("Null pointer argument");- }-- let client_secret_str = match CStr::from_ptr(client_secret).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in client_secret"),- };-- let server_public_str = match CStr::from_ptr(server_public).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in server_public"),- };-- let salt_str = match CStr::from_ptr(salt).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in salt"),- };-- let identity_str = match CStr::from_ptr(identity).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in identity"),- };-- let private_key_str = match CStr::from_ptr(private_key).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in private_key"),- };-- match crate::crypto::srp::srp_derive_session(- client_secret_str,- server_public_str,- salt_str,- identity_str,- private_key_str,- ) {- Ok(session) => match serde_json::to_string(&session) {- Ok(json) => string_to_c_char(json),- Err(e) => create_error_response(&format!("Failed to serialize session: {}", e)),- },- Err(e) => create_error_response(&format!("SRP error: {}", e)),- }-}--/// Generate a server ephemeral key pair.-///-/// # Safety-///-/// - `verifier` must be a valid null-terminated C string-/// - The returned pointer must be freed by calling `free_string`-///-/// # Returns-///-/// A null-terminated C string containing JSON: {"public": "...", "secret": "..."}-/// or an error JSON if the input is invalid.-#[no_mangle]-pub unsafe extern "C" fn srp_generate_ephemeral_server_ffi(verifier: *const c_char) -> *mut c_char {- if verifier.is_null() {- return create_error_response("Null pointer argument");- }-- let verifier_str = match CStr::from_ptr(verifier).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in verifier"),- };-- match crate::crypto::srp::srp_generate_ephemeral_server(verifier_str) {- Ok(ephemeral) => match serde_json::to_string(&ephemeral) {- Ok(json) => string_to_c_char(json),- Err(e) => create_error_response(&format!("Failed to serialize ephemeral: {}", e)),- },- Err(e) => create_error_response(&format!("SRP error: {}", e)),- }-}--/// Derive and verify the server session from client response.-///-/// # Safety-///-/// - All input pointers must be valid null-terminated C strings-/// - The returned pointer must be freed by calling `free_string`-///-/// # Returns-///-/// A null-terminated C string containing JSON:-/// - {"proof": "...", "key": "..."} if client proof is valid-/// - "null" if client proof is invalid (authentication failed)-/// - Error JSON if inputs are invalid-#[no_mangle]-pub unsafe extern "C" fn srp_derive_session_server_ffi(- server_secret: *const c_char,- client_public: *const c_char,- salt: *const c_char,- identity: *const c_char,- verifier: *const c_char,- client_proof: *const c_char,-) -> *mut c_char {- if server_secret.is_null() || client_public.is_null() || salt.is_null()- || identity.is_null() || verifier.is_null() || client_proof.is_null()- {- return create_error_response("Null pointer argument");- }-- let server_secret_str = match CStr::from_ptr(server_secret).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in server_secret"),- };-- let client_public_str = match CStr::from_ptr(client_public).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in client_public"),- };-- let salt_str = match CStr::from_ptr(salt).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in salt"),- };-- let identity_str = match CStr::from_ptr(identity).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in identity"),- };-- let verifier_str = match CStr::from_ptr(verifier).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in verifier"),- };-- let client_proof_str = match CStr::from_ptr(client_proof).to_str() {- Ok(s) => s,- Err(_) => return create_error_response("Invalid UTF-8 in client_proof"),- };-- match crate::crypto::srp::srp_derive_session_server(- server_secret_str,- client_public_str,- salt_str,- identity_str,- verifier_str,- client_proof_str,- ) {- Ok(Some(session)) => match serde_json::to_string(&session) {- Ok(json) => string_to_c_char(json),- Err(e) => create_error_response(&format!("Failed to serialize session: {}", e)),- },- Ok(None) => string_to_c_char("null".to_string()),- Err(e) => create_error_response(&format!("SRP error: {}", e)),- }-}--// ═══════════════════════════════════════════════════════════════════════════════-// SQLite host FFI Functions (in-memory database)-// ═══════════════════════════════════════════════════════════════════════════════--const SUCCESS_RESPONSE: &str = r#"{"success":true}"#;--/// Box a database into a handle, or report the error through `error_out`.-unsafe fn database_handle(result: VaultResult<MemoryDatabase>, error_out: *mut *mut c_char) -> *mut MemoryDatabase {- match result {- Ok(database) => Box::into_raw(Box::new(database)),- Err(e) => set_error(error_out, &format!("sqlite error: {}", e)),- }-}--/// Write an error response into `error_out` when it is given, and return null.-unsafe fn set_error<T>(error_out: *mut *mut c_char, message: &str) -> *mut T {- if !error_out.is_null() {- *error_out = create_error_response(message);- }- ptr::null_mut()-}--/// A SQLite host result as a C string: the JSON on success, an error response otherwise.-fn sqlite_response(result: VaultResult<String>) -> *mut c_char {- match result {- Ok(json) => string_to_c_char(json),- Err(e) => create_error_response(&format!("sqlite error: {}", e)),- }-}--/// Open a database from SQLite file bytes. Returns null on failure, with the error JSON in `error_out` when given.-///-/// # Safety-/// `bytes` must point to `len` readable bytes and `error_out` must be null or writable; free the handle with-/// `sqlite_database_free_ffi` and an error with `free_string`.-#[no_mangle]-pub unsafe extern "C" fn sqlite_database_from_bytes_ffi(bytes: *const u8, len: usize, error_out: *mut *mut c_char) -> *mut MemoryDatabase {- if bytes.is_null() {- return set_error(error_out, "Null pointer argument: bytes");- }- database_handle(MemoryDatabase::from_bytes(std::slice::from_raw_parts(bytes, len)), error_out)-}--/// Open an empty database and run a schema script on it. Returns null on failure, with the error JSON in `error_out` when given.-///-/// # Safety-/// `schema_sql` must be a valid null-terminated C string and `error_out` null or writable; free the handle with-/// `sqlite_database_free_ffi` and an error with `free_string`.-#[no_mangle]-pub unsafe extern "C" fn sqlite_database_with_schema_ffi(schema_sql: *const c_char, error_out: *mut *mut c_char) -> *mut MemoryDatabase {- if schema_sql.is_null() {- return set_error(error_out, "Null pointer argument: schema_sql");- }- match CStr::from_ptr(schema_sql).to_str() {- Ok(sql) => database_handle(MemoryDatabase::with_schema(sql), error_out),- Err(_) => set_error(error_out, "Invalid UTF-8 in schema_sql"),- }-}--/// Run a SQL script without parameters. Output: `{"success":true}` JSON.-///-/// # Safety-/// `database` must be a live handle and `sql` a valid null-terminated C string; free the result with `free_string`.-#[no_mangle]-pub unsafe extern "C" fn sqlite_database_execute_batch_ffi(database: *const MemoryDatabase, sql: *const c_char) -> *mut c_char {- let Some(database) = database.as_ref() else { return create_error_response("Null pointer argument: database") };- let sql = ffi_read_str!(sql, "sql");- sqlite_response(database.execute_batch(sql).map(|_| SUCCESS_RESPONSE.to_string()))-}--/// Run one query. Input: a JSON array of parameters, BLOBs as `{"__b64": ...}`. Output: JSON array of row objects.-///-/// # Safety-/// `database` must be a live handle, `sql` and `params_json` valid null-terminated C strings; free the result with `free_string`.-#[no_mangle]-pub unsafe extern "C" fn sqlite_database_query_ffi(database: *const MemoryDatabase, sql: *const c_char, params_json: *const c_char) -> *mut c_char {- let Some(database) = database.as_ref() else { return create_error_response("Null pointer argument: database") };- let sql = ffi_read_str!(sql, "sql");- let params_json = ffi_read_str!(params_json, "params_json");- sqlite_response(json_call(params_json, |params: Vec<Value>| database.query(sql, ¶ms)))-}--/// Run statements in one transaction. Input: a JSON array of `{"sql", "params"}`. Output: `{"success":true}` JSON.-///-/// # Safety-/// `database` must be a live handle and `statements_json` a valid null-terminated C string; free the result with `free_string`.-#[no_mangle]-pub unsafe extern "C" fn sqlite_database_exec_ffi(database: *const MemoryDatabase, statements_json: *const c_char) -> *mut c_char {- let Some(database) = database.as_ref() else { return create_error_response("Null pointer argument: database") };- let statements_json = ffi_read_str!(statements_json, "statements_json");- sqlite_response(json_call(statements_json, |statements: Vec<SqlStatement>| database.exec(&statements)).map(|_| SUCCESS_RESPONSE.to_string()))-}--/// The database as SQLite file bytes, their length written to `len_out`. Returns null on failure, with the error JSON in `error_out`.-///-/// # Safety-/// `database` must be a live handle, `len_out` writable and `error_out` null or writable; free the bytes with `free_bytes`.-#[no_mangle]-pub unsafe extern "C" fn sqlite_database_export_ffi(database: *const MemoryDatabase, len_out: *mut usize, error_out: *mut *mut c_char) -> *mut u8 {- let Some(database) = database.as_ref() else { return set_error(error_out, "Null pointer argument: database") };- if len_out.is_null() {- return set_error(error_out, "Null pointer argument: len_out");- }- match database.export() {- Ok(bytes) => {- let bytes = bytes.into_boxed_slice();- *len_out = bytes.len();- Box::into_raw(bytes) as *mut u8- }- Err(e) => set_error(error_out, &format!("sqlite error: {}", e)),- }-}--/// Free bytes returned by `sqlite_database_export_ffi`.-///-/// # Safety-/// `bytes` and `len` must come from one `sqlite_database_export_ffi` call and be freed only once.-#[no_mangle]-pub unsafe extern "C" fn free_bytes(bytes: *mut u8, len: usize) {- if !bytes.is_null() {- drop(Box::from_raw(ptr::slice_from_raw_parts_mut(bytes, len)));- }-}--/// Close a database and free its memory.-///-/// # Safety-/// `database` must be null or a handle from this module, freed only once and not used afterwards.-#[no_mangle]-pub unsafe extern "C" fn sqlite_database_free_ffi(database: *mut MemoryDatabase) {- if !database.is_null() {- drop(Box::from_raw(database));- }-}--#[cfg(test)]-mod tests {- use super::*;- use std::ffi::CString;-- #[test]- fn test_sqlite_database_round_trip() {- unsafe {- let schema = CString::new("CREATE TABLE Items (Id TEXT PRIMARY KEY, Logo BLOB);").unwrap();- let database = sqlite_database_with_schema_ffi(schema.as_ptr(), ptr::null_mut());- assert!(!database.is_null());-- let statements = CString::new(r#"[{"sql":"INSERT INTO Items VALUES (?, ?)","params":["a",{"__b64":"AQI="}]}]"#).unwrap();- let result = sqlite_database_exec_ffi(database, statements.as_ptr());- assert_eq!(CStr::from_ptr(result).to_str().unwrap(), SUCCESS_RESPONSE);- free_string(result);-- let mut len = 0;- let bytes = sqlite_database_export_ffi(database, &mut len, ptr::null_mut());- assert!(!bytes.is_null() && len > 0);- sqlite_database_free_ffi(database);-- let reopened = sqlite_database_from_bytes_ffi(bytes, len, ptr::null_mut());- free_bytes(bytes, len);- assert!(!reopened.is_null());-- let sql = CString::new("SELECT Id, Logo FROM Items WHERE Id = ?").unwrap();- let params = CString::new(r#"["a"]"#).unwrap();- let result = sqlite_database_query_ffi(reopened, sql.as_ptr(), params.as_ptr());- let rows: Value = serde_json::from_str(CStr::from_ptr(result).to_str().unwrap()).unwrap();- assert_eq!(rows, serde_json::json!([{ "Id": "a", "Logo": { "__b64": "AQI=" } }]));- free_string(result);- sqlite_database_free_ffi(reopened);- }- }-- #[test]- fn test_sqlite_database_errors_are_valid_json() {- unsafe {- let mut error = ptr::null_mut();- assert!(sqlite_database_from_bytes_ffi([0u8; 0].as_ptr(), 0, &mut error).is_null());- let response: Value = serde_json::from_str(CStr::from_ptr(error).to_str().unwrap()).unwrap();- assert_eq!(response["success"], false);- free_string(error);-- // The error echoes the SQL, so its quotes and newline must survive as JSON.- let schema = CString::new("CREATE TABLE Items (Id TEXT);").unwrap();- let database = sqlite_database_with_schema_ffi(schema.as_ptr(), ptr::null_mut());- let sql = CString::new("SELECT \"Id\"\nFROM Missing").unwrap();- let params = CString::new("[]").unwrap();- let result = sqlite_database_query_ffi(database, sql.as_ptr(), params.as_ptr());- let response: Value = serde_json::from_str(CStr::from_ptr(result).to_str().unwrap()).unwrap();- assert_eq!(response["success"], false);- assert!(response["error"].as_str().unwrap().contains("Missing"));- free_string(result);- sqlite_database_free_ffi(database);- }- }-- #[test]- fn test_get_syncable_table_names() {- let result = get_syncable_table_names_ffi();- assert!(!result.is_null());-- unsafe {- let c_str = CStr::from_ptr(result);- let json = c_str.to_str().unwrap();- let names: Vec<String> = serde_json::from_str(json).unwrap();- assert!(names.contains(&"Items".to_string()));- assert!(names.contains(&"FieldValues".to_string()));- free_string(result);- }- }-- #[test]- fn test_null_input() {- unsafe {- let result = prune_vault_ffi(ptr::null());- assert!(result.is_null());-- let result = filter_credentials_ffi(ptr::null());- assert!(result.is_null());- }- }-- #[test]- fn test_invalid_json_input() {- let invalid_json = CString::new("not valid json").unwrap();- unsafe {- let result = prune_vault_ffi(invalid_json.as_ptr());- assert!(!result.is_null());-- let c_str = CStr::from_ptr(result);- let json = c_str.to_str().unwrap();- assert!(json.contains("error"));- free_string(result);- }- }-}diff --git a/core/rust/src/lib.rs b/core/rust/src/lib.rsindex d56243523..a9cdf406a 100644--- a/core/rust/src/lib.rs+++ b/core/rust/src/lib.rs@@ -41,10 +41,6 @@ pub use error::VaultError;#[cfg(feature = "wasm")]pub mod wasm;-// C FFI exports (.NET P/Invoke), built with --dotnet but not consumed by any app yet-#[cfg(feature = "ffi")]-pub mod ffi;-// UniFFI bindings for Swift/Kotlin#[cfg(feature = "uniffi")]pub mod uniffi_api;diff --git a/core/rust/src/vault_codec/manifest.rs b/core/rust/src/vault_codec/manifest.rsindex 73220ae6a..352f30c43 100644--- a/core/rust/src/vault_codec/manifest.rs+++ b/core/rust/src/vault_codec/manifest.rs@@ -235,18 +235,6 @@ pub struct CanonicalizeInput {pub adopt_unstamped_into: Option<String>,}-/// Input for [`crate::vault_codec::extract_buckets`].-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct ExtractBucketsInput {- pub category: String,- /// Every manifest this vault can write. Each gets a bucket back; rows naming anything else are dropped.- pub manifest_ids: Vec<String>,- /// The category's tables as read from the local vault, plus the- /// [`OVERFLOW_TABLE`](crate::vault_model::OVERFLOW_TABLE) row so a newer writer's columns/tables re-merge.- pub tables: HashMap<String, Vec<CodecRecord>>,-}-/// Input for [`crate::vault_codec::materialize_as_sqlite`].#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]diff --git a/core/rust/src/vault_codec/mod.rs b/core/rust/src/vault_codec/mod.rsindex f532ec594..4a99aa94e 100644--- a/core/rust/src/vault_codec/mod.rs+++ b/core/rust/src/vault_codec/mod.rs@@ -30,7 +30,7 @@ pub 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,+ Manifest, MaterializeInput, MaterializedTables, CodecRecord, CodecTableData, ManifestSpec,};pub use materialize::materialize_as_sqlite;pub use scoped_assets::logo_id_for;