Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor rust build features and opt-level targets (#2159)
Leendert de Borst7408769f3365
diff --git a/.github/actions/build-browser-extension/action.yml b/.github/actions/build-browser-extension/action.ymlindex 69d1ee71f..b5712c098 100644--- a/.github/actions/build-browser-extension/action.yml+++ b/.github/actions/build-browser-extension/action.yml@@ -33,18 +33,22 @@ runs:shell: bashrun: cargo install wasm-pack --locked+ - name: Install clang (compiles SQLite for wasm32)+ shell: bash+ run: sudo apt-get update && sudo apt-get install -y clang+- name: Build core librariesshell: bashrun: |cd ./corechmod +x build-and-distribute.sh- ./build-and-distribute.sh+ ./build-and-distribute.sh --browser-extension- name: Verify core library distributionshell: bashrun: |# Verify critical rust WASM files exist- if [ ! -f "apps/browser-extension/src/utils/dist/core/rust/aliasvault_core_bg.wasm" ]; then+ if [ ! -f "core/client/wasm/aliasvault_core_bg.wasm" ]; thenecho "Error: Rust WASM files not found in browser extension"exit 1fidiff --git a/.github/actions/build-core-libraries/action.yml b/.github/actions/build-core-libraries/action.ymlindex 53bcb4f2d..c216a6805 100644--- a/.github/actions/build-core-libraries/action.yml+++ b/.github/actions/build-core-libraries/action.yml@@ -23,6 +23,10 @@ runs:shell: bashrun: cargo install wasm-pack --locked+ - name: Install clang (compiles SQLite for wasm32)+ shell: bash+ run: sudo apt-get update && sudo apt-get install -y clang+- name: Build and distribute core librariesshell: bashworking-directory: ${{ inputs.working-directory }}@@ -83,8 +87,8 @@ runs:done# Verify critical rust WASM files exist- if [ ! -f "apps/browser-extension/src/utils/dist/core/rust/aliasvault_core_bg.wasm" ]; then- echo "Error: Rust WASM files not found in browser extension"+ if [ ! -f "core/client/wasm/aliasvault_core_bg.wasm" ]; then+ echo "Error: Rust WASM files not found in core/client/wasm"exit 1fidiff --git a/.gitignore b/.gitignoreindex 4b6132fd5..63a17b76a 100644--- a/.gitignore+++ b/.gitignore@@ -448,7 +448,7 @@ apps/browser-extension/build-assets/safari-xcode/buildcore/rust/dist/core/rust/target/-# Browser extension WASM (built by: cd core/rust && ./build.sh --browser)+# 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)diff --git a/apps/browser-extension/package.json b/apps/browser-extension/package.jsonindex 19b991e90..2c1d8cd79 100644--- a/apps/browser-extension/package.json+++ b/apps/browser-extension/package.json@@ -5,7 +5,7 @@"version": "0.31.0","type": "module","scripts": {- "build:rust": "cd ../../core/rust && bash ./build.sh --browser",+ "build:rust": "cd ../../core/rust && bash ./build.sh --browser-extension","dev:chrome": "wxt -b chrome","dev:firefox": "wxt -b firefox","dev:edge": "wxt -b edge",diff --git a/apps/mobile-app/android/app/build.gradle b/apps/mobile-app/android/app/build.gradleindex 2b4ca2f44..8d040abfd 100644--- a/apps/mobile-app/android/app/build.gradle+++ b/apps/mobile-app/android/app/build.gradle@@ -360,11 +360,7 @@ task buildRustCore(type: Exec) {// Set up environment for cargoenvironment "PATH", "${System.getProperty('user.home')}/.cargo/bin:/usr/local/bin:/opt/homebrew/bin:${System.getenv('PATH')}"- // Determine build mode based on variant- def isRelease = gradle.startParameter.taskNames.any { it.toLowerCase().contains('release') }- def buildArgs = isRelease ? ['./build-rust-core.sh', '--release'] : ['./build-rust-core.sh', '--debug']-- commandLine buildArgs+ commandLine './build-rust-core.sh'// Only log if there are actual changesignoreExitValue = falsediff --git a/apps/mobile-app/android/scripts/build-rust-core.sh b/apps/mobile-app/android/scripts/build-rust-core.shindex 8b0567c90..e62a382df 100755--- a/apps/mobile-app/android/scripts/build-rust-core.sh+++ b/apps/mobile-app/android/scripts/build-rust-core.sh@@ -4,7 +4,7 @@# This is called by Gradle build phases## Usage:-# ./build-rust-core.sh [--force] [--release|--debug]+# ./build-rust-core.sh [--force]## The main build script lives at: /core/rust/build.sh@@ -19,7 +19,6 @@ RUST_CORE_DIR="$(cd "$SCRIPT_DIR/../../../../core/rust" && pwd)"JNILIBS_DIR="$SCRIPT_DIR/../app/src/main/jniLibs"# Parse arguments to pass through-EXTRA_ARGS=""FORCE_FLAG=""while [[ $# -gt 0 ]]; do@@ -28,14 +27,6 @@ while [[ $# -gt 0 ]]; doFORCE_FLAG="--force"shift;;- --release)- EXTRA_ARGS=""- shift- ;;- --debug)- EXTRA_ARGS="--fast"- shift- ;;*)shift;;@@ -44,4 +35,4 @@ done# Call the main build script with incremental modecd "$RUST_CORE_DIR"-exec ./build.sh --android --incremental $FORCE_FLAG $EXTRA_ARGS+exec ./build.sh --android --incremental $FORCE_FLAGdiff --git a/apps/mobile-app/ios/Scripts/build-rust-core.sh b/apps/mobile-app/ios/Scripts/build-rust-core.shdeleted file mode 100755index f3ae2f16d..000000000--- a/apps/mobile-app/ios/Scripts/build-rust-core.sh+++ /dev/null@@ -1,51 +0,0 @@-#!/bin/bash--# Thin wrapper that calls the main Rust core build script-# This is called by Xcode build phases-#-# Usage:-# ./build-rust-core.sh [--force] [--release|--debug]-#-# The main build script lives at: /core/rust/build.sh--set -e--# Ensure cargo is in PATH (for Xcode build phases)-export PATH="$HOME/.cargo/bin:/usr/local/bin:/opt/homebrew/bin:$PATH"--# Script location-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-RUST_CORE_DIR="$(cd "$SCRIPT_DIR/../../../../core/rust" && pwd)"--# Parse arguments to pass through-EXTRA_ARGS=""-FORCE_FLAG=""--# Check Xcode environment for configuration-if [ "${CONFIGURATION:-}" = "Debug" ]; then- EXTRA_ARGS="--fast"-fi--while [[ $# -gt 0 ]]; do- case $1 in- --force)- FORCE_FLAG="--force"- shift- ;;- --release)- EXTRA_ARGS=""- shift- ;;- --debug)- EXTRA_ARGS="--fast"- shift- ;;- *)- shift- ;;- esac-done--# Call the main build script with incremental mode-cd "$RUST_CORE_DIR"-exec ./build.sh --ios --incremental $FORCE_FLAG $EXTRA_ARGSdiff --git a/apps/server/AliasVault.Client/Dockerfile b/apps/server/AliasVault.Client/Dockerfileindex fb8810607..5de85640b 100644--- a/apps/server/AliasVault.Client/Dockerfile+++ b/apps/server/AliasVault.Client/Dockerfile@@ -6,11 +6,11 @@ WORKDIR /app# ============================================# Use BUILDPLATFORM to run on native arch (amd64) instead of emulating arm64.# WASM output is platform-independent, so we only need to build once.-FROM --platform=$BUILDPLATFORM rust:1-slim-bookworm AS core-builder+FROM --platform=$BUILDPLATFORM rust:1-slim-trixie AS core-builder# Install Node.js and wasm-pack (Rust already included in base image)RUN apt-get update && \- apt-get install -y --no-install-recommends curl ca-certificates && \+ apt-get install -y --no-install-recommends curl ca-certificates clang llvm && \curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \apt-get install -y --no-install-recommends nodejs && \rustup target add wasm32-unknown-unknown && \@@ -26,7 +26,7 @@ COPY core/ ./core/# Build core libraries (only browser target needed for Blazor WASM client)RUN cd ./core && \chmod +x build-and-distribute.sh && \- ./build-and-distribute.sh --browser+ ./build-and-distribute.sh --web# ============================================# Stage: Build .NET applicationdiff --git a/core/build-and-distribute.sh b/core/build-and-distribute.shindex 9be0eee49..5d4a48664 100755--- a/core/build-and-distribute.sh+++ b/core/build-and-distribute.sh@@ -5,7 +5,7 @@ set -u # Treat unset variables as errors# Build mode selectionBUILD_ALL=false-BUILD_BROWSER=false+BROWSER_TARGET="" # "web" or "browser-extension": both write core/client/wasm, so one per runBUILD_DOTNET=falseBUILD_IOS=falseBUILD_ANDROID=false@@ -14,10 +14,18 @@ BUILD_COMMON=true # Always build TypeScript utils, models, and vault# Parse argumentswhile [[ $# -gt 0 ]]; docase $1 in- --browser)- BUILD_BROWSER=true+ --web|--browser-extension)+ if [ -n "$BROWSER_TARGET" ] && [ "$BROWSER_TARGET" != "${1#--}" ]; then+ echo "Error: --web and --browser-extension share one output directory, build one at a time"+ exit 1+ fi+ BROWSER_TARGET="${1#--}"shift;;+ --browser)+ echo "Error: --browser was split into --web (size-optimized) and --browser-extension (speed-optimized)"+ exit 1+ ;;--dotnet)BUILD_DOTNET=trueshift@@ -31,7 +39,7 @@ while [[ $# -gt 0 ]]; doshift;;--all)- BUILD_BROWSER=true+ BROWSER_TARGET="${BROWSER_TARGET:-web}"BUILD_DOTNET=trueBUILD_ANDROID=true# Note: iOS excluded from --all as it requires macOS/Xcode (use --ios explicitly)@@ -41,11 +49,12 @@ while [[ $# -gt 0 ]]; doecho "Usage: $0 [options]"echo ""echo "Target options:"- echo " --browser Build WASM for browser extension and Blazor WASM client"- 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 (browser, dotnet, android)"+ 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 ""echo "Notes:"echo " - iOS requires macOS/Xcode, use --ios explicitly (not included in --all)"@@ -62,9 +71,9 @@ while [[ $# -gt 0 ]]; dodone# If no targets specified, build cross-platform targets (iOS excluded - requires macOS)-if ! $BUILD_BROWSER && ! $BUILD_DOTNET && ! $BUILD_IOS && ! $BUILD_ANDROID; then+if [ -z "$BROWSER_TARGET" ] && ! $BUILD_DOTNET && ! $BUILD_IOS && ! $BUILD_ANDROID; thenecho "No target specified, building cross-platform targets..."- BUILD_BROWSER=true+ BROWSER_TARGET="web"BUILD_DOTNET=trueBUILD_ANDROID=truefi@@ -95,7 +104,7 @@ if $BUILD_COMMON; thenfi# Rust core build (required when any platform target is specified)-if $BUILD_BROWSER || $BUILD_DOTNET || $BUILD_IOS || $BUILD_ANDROID; then+if [ -n "$BROWSER_TARGET" ] || $BUILD_DOTNET || $BUILD_IOS || $BUILD_ANDROID; thencd ./rustif ! command -v rustc &> /dev/null; then@@ -103,7 +112,7 @@ if $BUILD_BROWSER || $BUILD_DOTNET || $BUILD_IOS || $BUILD_ANDROID; thenecho " Install Rust from https://rustup.rs"echo ""echo " Requested targets require Rust:"- $BUILD_BROWSER && echo " - Browser/WASM"+ [ -n "$BROWSER_TARGET" ] && echo " - Browser/WASM ($BROWSER_TARGET)"$BUILD_DOTNET && echo " - .NET"$BUILD_IOS && echo " - iOS"$BUILD_ANDROID && echo " - Android"@@ -122,9 +131,9 @@ if $BUILD_BROWSER || $BUILD_DOTNET || $BUILD_IOS || $BUILD_ANDROID; then./build.sh --iosfi- if $BUILD_BROWSER; then- echo " → Building for Browser/WASM..."- ./build.sh --browser+ if [ -n "$BROWSER_TARGET" ]; then+ echo " → Building for Browser/WASM ($BROWSER_TARGET)..."+ ./build.sh --"$BROWSER_TARGET"fiif $BUILD_DOTNET; thendiff --git a/core/rust/Cargo.toml b/core/rust/Cargo.tomlindex 79aece945..889a1c686 100644--- a/core/rust/Cargo.toml+++ b/core/rust/Cargo.toml@@ -10,6 +10,10 @@ authors = ["AliasVault"][package.metadata.wasm-pack.profile.release]wasm-opt = false+# Applies to every profile passed via `wasm-pack --profile`, i.e. the browser extension build+[package.metadata.wasm-pack.profile.custom]+wasm-opt = false+[lib]crate-type = ["lib", "cdylib", "staticlib"]name = "aliasvault_core"@@ -24,8 +28,6 @@ uniffi-cli = ["uniffi/cli"]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 = []-# Feature for the in-memory SQLite host-sqlite = ["dep:rusqlite"][dependencies]# Serialization - core dependency for JSON handling@@ -77,16 +79,12 @@ console_error_panic_hook = { version = "0.1", optional = true }mail-parser = { version = "0.11.6", features = ["full_encoding"] }# SQLite client which can be used by all host apps for uniform access-rusqlite = { version = "0.40", features = ["bundled", "serialize"], optional = true }+rusqlite = { version = "0.40", features = ["bundled", "serialize"] }# rsa 0.9 pulls rand 0.8 / getrandom 0.2, which only builds for wasm32-unknown-unknown with its "js" feature.[target.'cfg(target_arch = "wasm32")'.dependencies]getrandom02 = { package = "getrandom", version = "0.2", features = ["js"] }-[dev-dependencies]-# The sync engine tests drive the engine against a real SQLite host.-rusqlite = { version = "0.40", features = ["bundled", "serialize"] }-# Build dependencies for UniFFI[build-dependencies]uniffi = { version = "0.28", features = ["build"] }@@ -104,7 +102,7 @@ opt-level = 0debug = falseincremental = true-# Release profile - optimized for size (browser WASM and .NET)+# Release profile - optimized for size (web app WASM, fetched on page load, and .NET)[profile.release]opt-level = "z"lto = "fat"@@ -112,6 +110,11 @@ codegen-units = 1panic = "abort"strip = "symbols"+# Browser extension profile - optimized for speed as the WASM ships inside the one time extension download+[profile.extension]+inherits = "release"+opt-level = 3+# Mobile profile - optimized for speed as increased bundle size is less relevant as its a one time download[profile.mobile]inherits = "release"diff --git a/core/rust/build.sh b/core/rust/build.shindex da66c9af3..ccf6a05bc 100755--- a/core/rust/build.sh+++ b/core/rust/build.sh@@ -64,16 +64,9 @@ compute_source_checksum() {fi}-# Cargo profile this invocation produces. The incremental checksum embeds it so a-# debug (--fast) build never satisfies a later release build: sources are identical,-# but the distributed artifacts are not, and they share one output path.-current_cargo_profile() {- if $FAST_MODE; then- echo "debug"- else- echo "release"- fi-}+# Cargo profile the mobile builds produce: the speed-optimized `mobile` profile (see Cargo.toml), while+# the web app WASM and .NET keep `release`.+MOBILE_CARGO_PROFILE="mobile"echo -e "${YELLOW}Checking prerequisites...${NC}"check_tool "rustc" "Visit https://rustup.rs"@@ -85,21 +78,28 @@ echo -e " Rust version: ${GREEN}$RUST_VERSION${NC}"# Build mode selectionBUILD_ALL=false-BUILD_BROWSER=false+BROWSER_TARGET="" # "web" or "browser-extension": both write core/client/wasm, so one per runBUILD_DOTNET=falseBUILD_IOS=falseBUILD_ANDROID=false-FAST_MODE=falseINCREMENTAL=falseFORCE_BUILD=false# Parse argumentswhile [[ $# -gt 0 ]]; docase $1 in- --browser)- BUILD_BROWSER=true+ --web|--browser-extension)+ if [ -n "$BROWSER_TARGET" ] && [ "$BROWSER_TARGET" != "${1#--}" ]; then+ echo -e "${RED}Error: --web and --browser-extension share one output directory, build one at a time${NC}"+ exit 1+ fi+ BROWSER_TARGET="${1#--}"shift;;+ --browser)+ echo -e "${RED}Error: --browser was split into --web (size-optimized) and --browser-extension (speed-optimized)${NC}"+ exit 1+ ;;--dotnet)BUILD_DOTNET=trueshift@@ -113,17 +113,12 @@ while [[ $# -gt 0 ]]; doshift;;--all)- BUILD_BROWSER=true+ BROWSER_TARGET="${BROWSER_TARGET:-web}"BUILD_DOTNET=trueBUILD_IOS=trueBUILD_ANDROID=trueshift;;- --fast|--dev)- FAST_MODE=true- echo -e "${YELLOW}Fast/dev mode enabled${NC}"- shift- ;;--incremental)INCREMENTAL=trueshift@@ -136,19 +131,19 @@ while [[ $# -gt 0 ]]; doecho "Usage: $0 [options]"echo ""echo "Target options:"- echo " --browser Build WASM for browser extension and Blazor WASM client"- echo " --dotnet Build native library for .NET server-side use (macOS/Linux/Windows)"- 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"+ echo " --web Build WASM for the web app and Blazor client (size-optimized)"+ echo " --browser-extension Build WASM for the browser extension (speed-optimized)"+ echo " --dotnet Build native library for .NET server-side use (macOS/Linux/Windows)"+ echo " --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)"echo ""echo "Speed options:"- echo " --fast, --dev Faster builds (for development)"- echo " --incremental Skip build if sources unchanged (for Xcode build phases)"- echo " --force Force rebuild even with --incremental"+ echo " --incremental Skip build if sources unchanged (for Xcode build phases)"+ echo " --force Force rebuild even with --incremental"echo ""echo "Other options:"- echo " --help Show this help message"+ echo " --help Show this help message"echo ""exit 0;;@@ -160,11 +155,12 @@ while [[ $# -gt 0 ]]; dodone# If no targets specified, show help-if ! $BUILD_BROWSER && ! $BUILD_DOTNET && ! $BUILD_IOS && ! $BUILD_ANDROID; then+if [ -z "$BROWSER_TARGET" ] && ! $BUILD_DOTNET && ! $BUILD_IOS && ! $BUILD_ANDROID; thenecho "No target specified. Use --help for usage."echo ""echo "Quick start:"- echo " ./build.sh --browser # Build for browser extension"+ 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"@@ -172,9 +168,14 @@ if ! $BUILD_BROWSER && ! $BUILD_DOTNET && ! $BUILD_IOS && ! $BUILD_ANDROID; thenfi# ============================================-# Browser Extension Build (WASM)+# Browser Build (WASM): web app (size-optimized `release`) or browser extension (speed-optimized `extension`)# ============================================build_browser() {+ local profile_args=(--release)+ if [ "$BROWSER_TARGET" = "browser-extension" ]; then+ profile_args=(--profile extension)+ fi+echo ""echo -e "${BLUE}Building WASM for browser extension...${NC}"@@ -192,13 +193,18 @@ build_browser() {rustup target add wasm32-unknown-unknownfi+ break+ fi+ done+ if [ -z "${CC_wasm32_unknown_unknown:-}" ]; then+ echo -e "${RED}Error: an LLVM clang with the WebAssembly backend is required (brew install llvm)${NC}"+ exit 1+ fi+ fi+# Build with wasm-packecho -e " Running wasm-pack build..."- if $FAST_MODE; then- wasm-pack build --dev --target web --out-dir "$WASM_DIR" --features wasm,sqlite- else- wasm-pack build --release --target web --out-dir "$WASM_DIR" --features wasm,sqlite- fi+ wasm-pack build "${profile_args[@]}" --target web --out-dir "$WASM_DIR" --features wasmlocal end_time=$(date +%s)local duration=$((end_time - start_time))@@ -234,7 +240,8 @@ Auto-generated from `/core/rust`. Do not edit manually.```bashcd /core/rust-./build.sh --browser+./build.sh --web # web app (size-optimized)+./build.sh --browser-extension # browser extension (speed-optimized)```README_EOF@@ -307,13 +314,8 @@ build_dotnet() {# Build with cargoecho -e " Running cargo build..."- if $FAST_MODE; then- cargo build --features ffi- local cargo_target="target/debug"- else- cargo build --release --features ffi- local cargo_target="target/release"- fi+ cargo build --release --features ffi+ local cargo_target="target/release"# Copy the libraryif [ -f "$cargo_target/$lib_name" ]; then@@ -352,7 +354,7 @@ build_ios() {# Incremental build checklocal checksum_file="$IOS_APP_DIST/.rust-core-checksum"local current_checksum=""- current_checksum="$(compute_source_checksum "$SCRIPT_DIR/src")-$(current_cargo_profile)"+ current_checksum="$(compute_source_checksum "$SCRIPT_DIR/src")"if $INCREMENTAL && [ "$FORCE_BUILD" = false ] && [ -f "$checksum_file" ] && [ -f "$IOS_APP_DIST/lib/device/libaliasvault_core.a" ]; thenlocal stored_checksum=$(cat "$checksum_file" 2>/dev/null || echo "")@@ -378,14 +380,8 @@ build_ios() {mkdir -p "$IOS_DIR/simulator"mkdir -p "$IOS_DIR/swift"- local cargo_profile- if $FAST_MODE; then- cargo_profile="debug"- cargo_flags=""- else- cargo_profile="release"- cargo_flags="--release"- fi+ local cargo_profile="$MOBILE_CARGO_PROFILE"+ local cargo_flags="--profile $cargo_profile"# Build for iOS device (arm64)# Note: Use only 'uniffi' feature for library builds (not uniffi-cli which includes heavy bindgen deps)@@ -402,11 +398,9 @@ build_ios() {# Strip debug symbols from static libraries to reduce size# Note: -S strips debug symbols but keeps the symbol table needed for linking- if ! $FAST_MODE; then- echo -e " Stripping debug symbols from libraries..."- strip -S "$IOS_DIR/device/libaliasvault_core.a" 2>/dev/null || true- strip -S "$IOS_DIR/simulator/libaliasvault_core.a" 2>/dev/null || true- fi+ echo -e " Stripping debug symbols from libraries..."+ strip -S "$IOS_DIR/device/libaliasvault_core.a" 2>/dev/null || true+ strip -S "$IOS_DIR/simulator/libaliasvault_core.a" 2>/dev/null || true# Generate Swift bindings using UniFFI# Note: Use uniffi-cli feature here since we need the bindgen CLI tool@@ -479,7 +473,7 @@ EOF# Save checksum for incremental buildslocal current_checksum=""- current_checksum="$(compute_source_checksum "$SCRIPT_DIR/src")-$(current_cargo_profile)"+ current_checksum="$(compute_source_checksum "$SCRIPT_DIR/src")"echo "$current_checksum" > "$IOS_APP_DIST/.rust-core-checksum"# Create README@@ -527,7 +521,7 @@ build_android() {# Incremental build checklocal checksum_file="$ANDROID_APP_DIST/.rust-core-checksum"local current_checksum=""- current_checksum="$(compute_source_checksum "$SCRIPT_DIR/src")-$(current_cargo_profile)"+ current_checksum="$(compute_source_checksum "$SCRIPT_DIR/src")"if $INCREMENTAL && [ "$FORCE_BUILD" = false ] && [ -f "$checksum_file" ] && [ -f "$ANDROID_APP_DIST/arm64-v8a/libaliasvault_core.so" ]; thenlocal stored_checksum=$(cat "$checksum_file" 2>/dev/null || echo "")@@ -575,14 +569,8 @@ build_android() {mkdir -p "$ANDROID_DIR/x86_64"mkdir -p "$ANDROID_DIR/kotlin"- local cargo_profile- if $FAST_MODE; then- cargo_profile="debug"- cargo_flags=""- else- cargo_profile="release"- cargo_flags="--release"- fi+ local cargo_profile="$MOBILE_CARGO_PROFILE"+ local cargo_flags="--profile $cargo_profile"# Set up Android toolchainlocal host_tag@@ -602,21 +590,21 @@ build_android() {CC="$toolchain/bin/aarch64-linux-android${api_level}-clang" \CXX="$toolchain/bin/aarch64-linux-android${api_level}-clang++" \CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER="$toolchain/bin/aarch64-linux-android${api_level}-clang" \- cargo build $cargo_flags --target aarch64-linux-android --features uniffi,sqlite+ cargo build $cargo_flags --target aarch64-linux-android --features uniffiecho -e " Building for armeabi-v7a..."AR="$toolchain/bin/llvm-ar" \CC="$toolchain/bin/armv7a-linux-androideabi${api_level}-clang" \CXX="$toolchain/bin/armv7a-linux-androideabi${api_level}-clang++" \CARGO_TARGET_ARMV7_LINUX_ANDROIDEABI_LINKER="$toolchain/bin/armv7a-linux-androideabi${api_level}-clang" \- cargo build $cargo_flags --target armv7-linux-androideabi --features uniffi,sqlite+ cargo build $cargo_flags --target armv7-linux-androideabi --features uniffiecho -e " Building for x86_64..."AR="$toolchain/bin/llvm-ar" \CC="$toolchain/bin/x86_64-linux-android${api_level}-clang" \CXX="$toolchain/bin/x86_64-linux-android${api_level}-clang++" \CARGO_TARGET_X86_64_LINUX_ANDROID_LINKER="$toolchain/bin/x86_64-linux-android${api_level}-clang" \- cargo build $cargo_flags --target x86_64-linux-android --features uniffi,sqlite+ cargo build $cargo_flags --target x86_64-linux-android --features uniffi# Copy librariescp "target/aarch64-linux-android/$cargo_profile/libaliasvault_core.so" "$ANDROID_DIR/arm64-v8a/"@@ -625,14 +613,12 @@ build_android() {# Strip debug symbols from shared libraries using NDK strip# This removes debug info while keeping symbols needed for JNI- if ! $FAST_MODE; then- echo -e " Stripping debug symbols from libraries..."- local llvm_strip="$toolchain/bin/llvm-strip"- if [ -x "$llvm_strip" ]; then- "$llvm_strip" --strip-debug "$ANDROID_DIR/arm64-v8a/libaliasvault_core.so" 2>/dev/null || true- "$llvm_strip" --strip-debug "$ANDROID_DIR/armeabi-v7a/libaliasvault_core.so" 2>/dev/null || true- "$llvm_strip" --strip-debug "$ANDROID_DIR/x86_64/libaliasvault_core.so" 2>/dev/null || true- fi+ echo -e " Stripping debug symbols from libraries..."+ local llvm_strip="$toolchain/bin/llvm-strip"+ if [ -x "$llvm_strip" ]; then+ "$llvm_strip" --strip-debug "$ANDROID_DIR/arm64-v8a/libaliasvault_core.so" 2>/dev/null || true+ "$llvm_strip" --strip-debug "$ANDROID_DIR/armeabi-v7a/libaliasvault_core.so" 2>/dev/null || true+ "$llvm_strip" --strip-debug "$ANDROID_DIR/x86_64/libaliasvault_core.so" 2>/dev/null || truefi# Generate Kotlin bindings using UniFFI@@ -659,7 +645,7 @@ build_android() {esacecho -e " Building native library for bindgen..."- cargo build --features uniffi,sqlite --lib+ cargo build --features uniffi --lib# Generate bindings from native librarycargo run --features uniffi-cli --bin uniffi-bindgen -- generate \@@ -719,7 +705,7 @@ distribute_android() {# Save checksum for incremental buildslocal current_checksum=""- current_checksum="$(compute_source_checksum "$SCRIPT_DIR/src")-$(current_cargo_profile)"+ current_checksum="$(compute_source_checksum "$SCRIPT_DIR/src")"echo "$current_checksum" > "$ANDROID_APP_DIST/.rust-core-checksum"echo -e "${GREEN}Distributed to: $ANDROID_APP_DIST${NC}"@@ -730,7 +716,7 @@ distribute_android() {# ============================================TOTAL_START=$(date +%s)-if $BUILD_BROWSER; then+if [ -n "$BROWSER_TARGET" ]; thenbuild_browserdistribute_browserfidiff --git a/core/rust/src/ffi.rs b/core/rust/src/ffi.rsindex 0403408d0..ebc6ee650 100644--- a/core/rust/src/ffi.rs+++ b/core/rust/src/ffi.rs@@ -1,15 +1,18 @@//! C FFI exports for .NET P/Invoke.//!//! These functions provide a C-compatible interface for calling Rust functions from C#.-//! All functions use JSON strings for input/output to simplify marshalling.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;+use crate::error::{json_call, VaultResult};+use crate::sqlite_host::MemoryDatabase;use crate::vault_codec::{self, CanonicalizeInput, DataBucket, ExtractBucketsInput, Manifest, MaterializeInput};use crate::vault_pruner::{prune_vault, PruneInput};+use crate::vault_sync::types::SqlStatement;/// Prune expired items from trash.///@@ -145,8 +148,7 @@ fn string_to_c_char(s: String) -> *mut c_char {/// Create an error response JSON string.fn create_error_response(message: &str) -> *mut c_char {- let error_json = format!(r#"{{"success":false,"error":"{}"}}"#, message.replace('"', r#"\""#));- string_to_c_char(error_json)+ string_to_c_char(serde_json::json!({ "success": false, "error": message }).to_string())}// ═══════════════════════════════════════════════════════════════════════════════@@ -596,11 +598,200 @@ pub unsafe extern "C" fn srp_derive_session_server_ffi(}}+// ═══════════════════════════════════════════════════════════════════════════════+// 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();diff --git a/core/rust/src/lib.rs b/core/rust/src/lib.rsindex acad78f12..67163e838 100644--- a/core/rust/src/lib.rs+++ b/core/rust/src/lib.rs@@ -7,7 +7,7 @@//! - **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-//! - **sqlite_host**: an in-memory SQLite database for hosts that cannot open one from bytes (`sqlite` feature)+//! - **sqlite_host**: an in-memory SQLite database for hosts that cannot open one from bytes//! - **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@@ -37,7 +37,6 @@ pub mod password_generator;pub mod identity_generator;pub mod crypto;pub mod vault_sync;-#[cfg(any(feature = "sqlite", test))]pub mod sqlite_host;pub use error::VaultError;diff --git a/core/rust/src/uniffi_api.rs b/core/rust/src/uniffi_api.rsindex e4b0cb22e..38440d553 100644--- a/core/rust/src/uniffi_api.rs+++ b/core/rust/src/uniffi_api.rs@@ -635,13 +635,11 @@ impl VaultSyncSession {}/// An in-memory SQLite database that can be used by host applications to be have uniform access to the database.-#[cfg(feature = "sqlite")]#[derive(uniffi::Object)]pub struct SqliteMemoryDatabase {inner: crate::sqlite_host::MemoryDatabase,}-#[cfg(feature = "sqlite")]#[uniffi::export]impl SqliteMemoryDatabase {/// Open a database from its SQLite file bytes.diff --git a/core/rust/src/wasm.rs b/core/rust/src/wasm.rsindex 1450862c8..ec666acc3 100644--- a/core/rust/src/wasm.rs+++ b/core/rust/src/wasm.rs@@ -685,7 +685,6 @@ impl VaultSyncSessionJs {// SQLite host WASM Bindings// ============================================================================-#[cfg(feature = "sqlite")]mod sqlite_js {use js_sys::{Array, Object, Reflect, Uint8Array};use wasm_bindgen::prelude::*;diff --git a/dockerfiles/all-in-one/Dockerfile b/dockerfiles/all-in-one/Dockerfileindex 24256d7b7..8eae41e88 100644--- a/dockerfiles/all-in-one/Dockerfile+++ b/dockerfiles/all-in-one/Dockerfile@@ -5,11 +5,11 @@# ============================================# Use BUILDPLATFORM to run on native arch (amd64) instead of emulating arm64.# WASM output is platform-independent, so we only need to build once.-FROM --platform=$BUILDPLATFORM rust:1-slim-bookworm AS core-builder+FROM --platform=$BUILDPLATFORM rust:1-slim-trixie AS core-builder# Install Node.js and wasm-pack (Rust already included in base image)RUN apt-get update && \- apt-get install -y --no-install-recommends curl ca-certificates && \+ apt-get install -y --no-install-recommends curl ca-certificates clang llvm && \curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \apt-get install -y --no-install-recommends nodejs && \rustup target add wasm32-unknown-unknown && \@@ -25,7 +25,7 @@ COPY core/ ./core/# Build core libraries (only browser target needed for server apps)RUN cd ./core && \chmod +x build-and-distribute.sh && \- ./build-and-distribute.sh --browser+ ./build-and-distribute.sh --web# ============================================# Stage 2: Build .NET applications