Skip to content

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

Move sqlite vacuum call to Rust core, remove unused methods

Leendert de Borst18f6f7dad560
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
index 425244951..20ed14e86 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
@@ -417,21 +417,6 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
}
- /**
- * Get the encrypted database.
- * @param promise The promise to resolve
- */
- @ReactMethod
- override fun getEncryptedDatabase(promise: Promise) {
- try {
- val encryptedDb = vaultStore.getEncryptedDatabase()
- promise.resolve(encryptedDb)
- } catch (e: Exception) {
- Log.e(TAG, "Error getting encrypted database", e)
- promise.reject("ERR_GET_DB", "Failed to get encrypted database: ${e.message}", e)
- }
- }
-
/**
* Execute a query on the vault.
* @param query The query
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
index 3c282cd53..cc7999649 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
@@ -95,7 +95,7 @@ class VaultDatabase(
close()
JnaInitializer.ensureInitialized()
- val opened = try {
+ db = try {
SqliteMemoryDatabase.fromBytes(bytes).also {
it.queryValues("SELECT count(*) FROM sqlite_master", emptyList())
}
@@ -103,14 +103,6 @@ class VaultDatabase(
Log.e(TAG, "Failed to open the vault database (data may be corrupt)", e)
throw AppError.DatabaseOpenFailed(cause = e)
}
- try {
- opened.executeBatch("PRAGMA foreign_keys = ON")
- } catch (e: Exception) {
- opened.destroy()
- Log.e(TAG, "Failed to set database pragmas", e)
- throw AppError.DatabasePragmaFailed(cause = e)
- }
- db = opened
}
/**
@@ -174,8 +166,7 @@ class VaultDatabase(
*/
fun commitTransaction(scope: String = VaultMutationScope.MAIN) {
connection().executeBatch("COMMIT")
- persistDatabaseToEncryptedStorage()
- markMutated(scope)
+ persistAndMarkDirty(scope)
}
/**
@@ -197,9 +188,8 @@ class VaultDatabase(
/**
* Persist the in-memory database to encrypted local storage.
- * This method can be called independently to persist the database without committing a transaction.
*/
- fun persistDatabaseToEncryptedStorage() {
+ private fun persistDatabaseToEncryptedStorage() {
val connection = connection()
// End any open transactions.
try { connection.executeBatch("END") } catch (_: Exception) {}
@@ -221,13 +211,9 @@ class VaultDatabase(
}
/**
- * The database as SQLite file bytes, compacted first when no transaction is open.
+ * The database as SQLite file bytes.
*/
- fun export(): ByteArray {
- val connection = connection()
- try { connection.executeBatch("VACUUM") } catch (_: Exception) {}
- return connection.export()
- }
+ fun export(): ByteArray = connection().export()
/**
* Close the database connection.
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
index 2e42fab94..db6e24ec9 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
@@ -377,40 +377,28 @@ class VaultStore(
* Execute a read-only SQL query (SELECT) on the vault.
*/
fun executeQuery(queryString: String, params: Array<Any?>): List<Map<String, Any?>> {
- // Process params - convert base64-prefixed strings to ByteArray for blob binding
- val convertedParams = params.map { param ->
- when {
- param == null -> null
- param is String && param.startsWith(BASE64_BLOB_PREFIX) -> {
- val base64 = param.removePrefix(BASE64_BLOB_PREFIX)
- android.util.Base64.decode(base64, android.util.Base64.NO_WRAP)
- }
- param is ByteArray -> param
- else -> param.toString()
- }
- }
-
- return database.query(queryString, convertedParams)
+ return database.query(queryString, bridgeParams(params))
}
/**
* Execute an SQL update on the vault that mutates it.
*/
fun executeUpdate(queryString: String, params: Array<Any?>): Int {
- // Process params - convert base64-prefixed strings to ByteArray for blob binding
- val processedParams = params.map { param ->
- when {
- param == null -> null
- param is String && param.startsWith(BASE64_BLOB_PREFIX) -> {
- val base64 = param.removePrefix(BASE64_BLOB_PREFIX)
- android.util.Base64.decode(base64, android.util.Base64.NO_WRAP)
- }
- param is ByteArray -> param
- else -> param.toString()
+ return database.execute(queryString, bridgeParams(params))
+ }
+
+ /**
+ * Bridge parameters as SQL values: base64-prefixed strings bind as a BLOB, everything else as text.
+ */
+ private fun bridgeParams(params: Array<Any?>): List<Any?> = params.map { param ->
+ when {
+ param == null -> null
+ param is String && param.startsWith(BASE64_BLOB_PREFIX) -> {
+ android.util.Base64.decode(param.removePrefix(BASE64_BLOB_PREFIX), android.util.Base64.NO_WRAP)
}
+ param is ByteArray -> param
+ else -> param.toString()
}
-
- return database.execute(queryString, processedParams)
}
/**
diff --git a/apps/mobile-app/android/app/src/main/res/values/strings.xml b/apps/mobile-app/android/app/src/main/res/values/strings.xml
index 8d431ab66..fed75ea51 100644
--- a/apps/mobile-app/android/app/src/main/res/values/strings.xml
+++ b/apps/mobile-app/android/app/src/main/res/values/strings.xml
@@ -67,7 +67,7 @@
<string name="network_error_title">Network Error</string>
<string name="network_error_message">A network error occurred. Please check your connection and try again.</string>
<string name="server_version_not_supported_title">Server Update Required</string>
- <string name="server_version_not_supported_message">The AliasVault server needs to be updated to work with this version of AliasVault. Please contact support if you need help.</string>
+ <string name="server_version_not_supported_message">The AliasVault server needs to be updated to work with this version of AliasVault. Please try again later. If you use a self-hosted server, please contact your server administrator.</string>
<string name="error_unlock_method_required">Please enable biometric or PIN authentication in the main AliasVault app in order to continue</string>
<string name="error_unlock_vault_first">Please unlock vault in AliasVault app first</string>
<string name="error_vault_decrypt_failed">Failed to decrypt vault</string>
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index 0fcde0408..fbcfddfe0 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -147,10 +147,6 @@
resolve(nil);
}
-- (void)getEncryptedDatabase:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
- [vaultManager getEncryptedDatabase:resolve rejecter:reject];
-}
-
- (void)deriveKeyFromPassword:(NSString *)password salt:(NSString *)salt encryptionType:(NSString *)encryptionType encryptionSettings:(NSString *)encryptionSettings resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
[vaultManager deriveKeyFromPassword:password salt:salt encryptionType:encryptionType encryptionSettings:encryptionSettings resolver:resolve rejecter:reject];
}
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 52e00e7b4..5c01db922 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -257,16 +257,6 @@ public class VaultManager: NSObject {
}
}
- @objc
- func getEncryptedDatabase(_ resolve: @escaping RCTPromiseResolveBlock,
- rejecter reject: @escaping RCTPromiseRejectBlock) {
- if let encryptedDb = vaultStore.getEncryptedDatabase() {
- resolve(encryptedDb)
- } else {
- reject("DB_ERROR", "Failed to get encrypted database", nil)
- }
- }
-
@objc
func hasEncryptedDatabase(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
index 6549caf28..83d7d605b 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
@@ -76,20 +76,12 @@ extension VaultStore {
// Step 2: Open the bytes in the Rust core's memory directly without persisting to the filesystem.
self.dbConnection = nil
- let opened: SqliteMemoryDatabase
do {
- opened = try SqliteMemoryDatabase.fromBytes(bytes: decryptedDbData)
+ let opened = try SqliteMemoryDatabase.fromBytes(bytes: decryptedDbData)
_ = try opened.queryValues(sql: "SELECT count(*) FROM sqlite_master", params: [])
+ self.dbConnection = opened
} catch {
throw AppError.databaseOpenFailed
}
-
- // Step 3: Set pragmas
- do {
- try opened.executeBatch(sql: "PRAGMA foreign_keys = ON")
- } catch {
- throw AppError.databasePragmaFailed
- }
- self.dbConnection = opened
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
index a44bfd462..7d5026a21 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
@@ -45,7 +45,7 @@ extension VaultStore {
}
/// Persist the in-memory database to encrypted local storage.
- public func persistDatabaseToEncryptedStorage() throws {
+ private func persistDatabaseToEncryptedStorage() throws {
let database = try requireDatabase()
// End any open transactions.
_ = try? database.executeBatch(sql: "END")
@@ -53,23 +53,16 @@ extension VaultStore {
try storeEncryptedDatabase(encrypted.base64EncodedString())
}
- /// The database as SQLite file bytes, compacted first when no transaction is open.
+ /// The database as SQLite file bytes.
public func exportDatabase() throws -> Data {
- let database = try requireDatabase()
- _ = try? database.executeBatch(sql: "VACUUM")
- return try database.export()
+ return try requireDatabase().export()
}
/// Commit a transaction on the database. This is required for all database operations that modify the database.
/// - Parameter scope: What the mutation touched, so the next sync can push only that scope
public func commitTransaction(scope: String = VaultMutationScope.main) throws {
try requireDatabase().executeBatch(sql: "COMMIT")
- try persistDatabaseToEncryptedStorage()
-
- // Atomically mark vault as dirty and increment mutation sequence
- // This ensures sync can properly detect local changes
- markDirty(scope: scope)
- _ = incrementMutationSequence()
+ try persistAndMarkDirty(scope: scope)
}
/// Rollback a transaction on the database on error.
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index f3e112d8b..586fc6a1b 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -73,7 +73,6 @@ export interface Spec extends TurboModule {
getPersonalManifestId(): Promise<string | null>;
decryptInvitationName(encryptedName: string): Promise<string | null>;
hasEncryptedDatabase(): Promise<boolean>;
- getEncryptedDatabase(): Promise<string | null>;
// Auto-lock settings
setAutoLockTimeout(timeout: number): Promise<void>;
diff --git a/core/client/src/database/SqliteClient.ts b/core/client/src/database/SqliteClient.ts
index 6e8f8398f..863dd766f 100644
--- a/core/client/src/database/SqliteClient.ts
+++ b/core/client/src/database/SqliteClient.ts
@@ -28,12 +28,6 @@ import type { ISqliteDatabase } from '../platform/SqliteEngine';
import type { VaultMutationScope } from '../sync/VaultMutationScope';
import type { VaultVersion } from '@aliasvault/vault';
-/** Minimum number of free pages before a VACUUM is worth the full database rewrite on export. */
-const VACUUM_MIN_FREE_PAGES = 64;
-
-/** A VACUUM runs when the freelist holds at least this fraction (1/n) of the database's pages. */
-const VACUUM_FREE_PAGE_RATIO = 10;
-
/**
* Core SQLite database client.
* Provides low-level database operations and exposes repositories for domain-specific operations.
@@ -299,7 +293,7 @@ export class SqliteClient implements ISyncDatabaseClient {
}
/**
- * Export the SQLite database as raw bytes.
+ * Export the SQLite database as raw bytes (the Rust core compacts it first when fragmented).
* @returns The database bytes
*/
public exportToBytes(): Uint8Array {
@@ -308,7 +302,6 @@ export class SqliteClient implements ISyncDatabaseClient {
}
try {
- this.vacuumIfFragmented();
return this.db.export();
} catch (error) {
logDefect('[Sqlite] Exporting the database failed', error);
@@ -316,18 +309,6 @@ export class SqliteClient implements ISyncDatabaseClient {
}
}
- /**
- * Rebuild the database to reclaim free pages, but only when enough of them have accumulated to be worth it.
- */
- private vacuumIfFragmented(): void {
- const freePages = this.executeQuery<{ freelist_count: number }>('PRAGMA freelist_count')[0]?.freelist_count ?? 0;
- const totalPages = this.executeQuery<{ page_count: number }>('PRAGMA page_count')[0]?.page_count ?? 0;
-
- if (freePages >= VACUUM_MIN_FREE_PAGES && freePages * VACUUM_FREE_PAGE_RATIO >= totalPages) {
- this.executeRaw('VACUUM');
- }
- }
-
/**
* Execute a SELECT query.
* @param query - SQL query string
diff --git a/core/rust/src/sqlite_host/mod.rs b/core/rust/src/sqlite_host/mod.rs
index 87591bd90..137f0ad79 100644
--- a/core/rust/src/sqlite_host/mod.rs
+++ b/core/rust/src/sqlite_host/mod.rs
@@ -1,6 +1,7 @@
//! An in-memory SQLite database that host applications use for uniform access to the database.
//!
-//! The database lives in SQLite's own memory and is never persisted to the filesystem.
+//! The database lives in SQLite's own memory and is never persisted to the filesystem; temporary tables and the
+//! scratch copy a VACUUM builds stay in memory too (`temp_store = MEMORY`), so no plaintext page spills to disk.
use std::sync::Mutex;
@@ -13,6 +14,12 @@ use crate::common::encoding::base64_decode;
use crate::common::error::{VaultError, VaultResult};
use crate::vault_codec::row::{inline_b64, inline_bytes};
+/// Minimum number of free pages before a VACUUM is worth the full database rewrite on export.
+const VACUUM_MIN_FREE_PAGES: i64 = 64;
+
+/// A VACUUM runs when the freelist holds at least this fraction (1/n) of the database's pages.
+const VACUUM_FREE_PAGE_RATIO: i64 = 10;
+
/// One parameterized SQL statement, as the bindings and the sync engine hand it to a host.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SqlStatement {
@@ -48,19 +55,19 @@ pub struct MemoryDatabase {
impl MemoryDatabase {
/// Open a database from its file bytes.
pub fn from_bytes(bytes: &[u8]) -> VaultResult<Self> {
- let mut conn = Connection::open_in_memory().map_err(sql_error)?;
+ let mut conn = open_connection()?;
deserialize_into(&mut conn, bytes)?;
Ok(Self { conn: Mutex::new(conn) })
}
/// Open an empty database.
pub fn empty() -> VaultResult<Self> {
- Ok(Self { conn: Mutex::new(Connection::open_in_memory().map_err(sql_error)?) })
+ Ok(Self { conn: Mutex::new(open_connection()?) })
}
/// Open an empty database and run a schema script on it.
pub fn with_schema(schema_sql: &str) -> VaultResult<Self> {
- let conn = Connection::open_in_memory().map_err(sql_error)?;
+ let conn = open_connection()?;
conn.execute_batch(schema_sql).map_err(sql_error)?;
Ok(Self { conn: Mutex::new(conn) })
}
@@ -106,9 +113,11 @@ impl MemoryDatabase {
Ok(conn.changes())
}
- /// The database as SQLite file bytes.
+ /// The database as SQLite file bytes, compacted first when it is fragmented and no transaction is open.
pub fn export(&self) -> VaultResult<Vec<u8>> {
- Ok(self.lock().serialize(MAIN_DB).map_err(sql_error)?.to_vec())
+ let conn = self.lock();
+ vacuum_if_fragmented(&conn)?;
+ Ok(conn.serialize(MAIN_DB).map_err(sql_error)?.to_vec())
}
fn lock(&self) -> std::sync::MutexGuard<'_, Connection> {
@@ -116,6 +125,26 @@ impl MemoryDatabase {
}
}
+/// An in-memory connection.
+fn open_connection() -> VaultResult<Connection> {
+ let conn = Connection::open_in_memory().map_err(sql_error)?;
+ conn.pragma_update(None, "temp_store", "MEMORY").map_err(sql_error)?;
+ Ok(conn)
+}
+
+/// Rebuild the database to reclaim free pages if there are enough free pages to make it worth it.
+fn vacuum_if_fragmented(conn: &Connection) -> VaultResult<()> {
+ if !conn.is_autocommit() {
+ return Ok(());
+ }
+ let free_pages: i64 = conn.pragma_query_value(None, "freelist_count", |row| row.get(0)).map_err(sql_error)?;
+ let total_pages: i64 = conn.pragma_query_value(None, "page_count", |row| row.get(0)).map_err(sql_error)?;
+ if free_pages >= VACUUM_MIN_FREE_PAGES && free_pages * VACUUM_FREE_PAGE_RATIO >= total_pages {
+ conn.execute_batch("VACUUM").map_err(sql_error)?;
+ }
+ Ok(())
+}
+
/// Load SQLite file bytes into a connection's main database, held in SQLite-owned memory.
pub fn deserialize_into(conn: &mut Connection, bytes: &[u8]) -> VaultResult<()> {
if bytes.is_empty() {
@@ -244,6 +273,49 @@ mod tests {
}
}
+ #[test]
+ fn temporary_storage_stays_in_memory() {
+ let db = MemoryDatabase::empty().unwrap();
+ assert_eq!(db.query("PRAGMA temp_store", &[]).unwrap()[0]["temp_store"], json!(2));
+ let reopened = MemoryDatabase::from_bytes(&db.export().unwrap()).unwrap();
+ assert_eq!(reopened.query("PRAGMA temp_store", &[]).unwrap()[0]["temp_store"], json!(2));
+ }
+
+ #[test]
+ fn foreign_keys_are_on_by_default() {
+ let db = MemoryDatabase::empty().unwrap();
+ assert_eq!(db.query("PRAGMA foreign_keys", &[]).unwrap()[0]["foreign_keys"], json!(1), "the hosts rely on the bundled SQLite default");
+ }
+
+ #[test]
+ fn export_compacts_only_a_fragmented_database_outside_a_transaction() {
+ let page_count = |db: &MemoryDatabase| db.query("PRAGMA page_count", &[]).unwrap()[0]["page_count"].as_i64().unwrap();
+ let free_pages = |db: &MemoryDatabase| db.query("PRAGMA freelist_count", &[]).unwrap()[0]["freelist_count"].as_i64().unwrap();
+ let db = MemoryDatabase::with_schema("CREATE TABLE T (Id INTEGER, Data BLOB);").unwrap();
+ for id in 0..200 {
+ db.execute("INSERT INTO T (Id, Data) VALUES (?, ?)", &[SqlValue::Integer(id), SqlValue::Blob(vec![7u8; 4096])]).unwrap();
+ }
+
+ db.execute("DELETE FROM T WHERE Id < 5", &[]).unwrap();
+ let slightly_fragmented = free_pages(&db);
+ assert!(slightly_fragmented > 0 && slightly_fragmented < VACUUM_MIN_FREE_PAGES);
+ db.export().unwrap();
+ assert_eq!(free_pages(&db), slightly_fragmented, "a few free pages are not worth a rewrite");
+
+ db.execute_batch("BEGIN; DELETE FROM T WHERE Id < 150;").unwrap();
+ db.export().unwrap();
+ assert!(free_pages(&db) >= VACUUM_MIN_FREE_PAGES, "no VACUUM inside an open transaction");
+ db.execute_batch("COMMIT").unwrap();
+
+ let before = page_count(&db);
+ let exported = db.export().unwrap();
+ assert_eq!(free_pages(&db), 0);
+ assert!(page_count(&db) < before);
+ let reopened = MemoryDatabase::from_bytes(&exported).unwrap();
+ assert_eq!(reopened.query("SELECT COUNT(*) AS N FROM T", &[]).unwrap()[0]["N"], json!(50));
+ assert_eq!(free_pages(&reopened), 0);
+ }
+
#[test]
fn invalid_base64_blob_parameter_fails_instead_of_binding_empty_bytes() {
let db = MemoryDatabase::with_schema("CREATE TABLE T (Data BLOB);").unwrap();