Skip to content

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

Add mobile app Rust core build scaffolding (#1404)

Leendert de Borst37d72f823d92
diff --git a/.gitignore b/.gitignore
index da99ab99b..cbaeb0927 100644
--- a/.gitignore
+++ b/.gitignore
@@ -444,10 +444,10 @@ core/rust/target/
apps/browser-extension/src/utils/dist/core/rust
# iOS Swift bindings (built by: cd core/rust && ./build.sh --ios)
-apps/mobile-app/ios/AliasVaultCore/
+apps/mobile-app/ios/VaultStoreKit/RustCore/
# Android Kotlin bindings (built by: cd core/rust && ./build.sh --android)
-apps/mobile-app/android/app/src/main/java/com/aliasvault/core/
+apps/mobile-app/android/app/src/main/java/net/aliasvault/app/rustcore/uniffi/
apps/mobile-app/android/app/src/main/jniLibs/
# Server .NET bindings (built by: cd core/rust && ./build.sh --server)
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 c1cd8b870..d2c753983 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
@@ -23,7 +23,6 @@ import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import net.aliasvault.app.qrscanner.QRScannerActivity
import net.aliasvault.app.vaultstore.VaultStore
-import net.aliasvault.app.vaultstore.VaultSyncError
import net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider
import net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
import net.aliasvault.app.webapi.WebApiService
@@ -1548,5 +1547,4 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
promise.reject("ERR_PERSIST_VAULT", "Failed to persist vault: ${e.message}", e)
}
}
-
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/rustcore/VaultMergeService.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/rustcore/VaultMergeService.kt
new file mode 100644
index 000000000..9001234f3
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/rustcore/VaultMergeService.kt
@@ -0,0 +1,254 @@
+package net.aliasvault.app.rustcore
+
+import android.database.sqlite.SQLiteDatabase
+import android.util.Base64
+import android.util.Log
+import net.aliasvault.app.vaultstore.VaultCrypto
+import org.json.JSONArray
+import org.json.JSONObject
+import java.io.File
+
+/**
+ * Service for vault merge operations using the Rust core library.
+ * Wraps UniFFI-generated bindings for LWW merge operations on SQLite vault databases.
+ */
+object VaultMergeService {
+ private const val TAG = "VaultMergeService"
+
+ init {
+ System.loadLibrary("aliasvault_core")
+ Log.d(TAG, "Rust core library loaded")
+ }
+
+ sealed class VaultMergeException(message: String) : Exception(message) {
+ class JsonError(message: String) : VaultMergeException("JSON error: $message")
+ class RustError(message: String) : VaultMergeException("Rust error: $message")
+ class DatabaseError(message: String) : VaultMergeException("Database error: $message")
+ class InvalidInput(message: String) : VaultMergeException("Invalid input: $message")
+ }
+
+ /**
+ * Get the list of syncable table names from Rust.
+ */
+ fun getTableNames(): List<String> {
+ return uniffi.aliasvault_core.getSyncableTableNames()
+ }
+
+ /**
+ * Merge local and server vaults using LWW strategy.
+ */
+ @Throws(VaultMergeException::class)
+ fun mergeVaults(
+ localVaultBase64: String,
+ serverVaultBase64: String,
+ encryptionKey: ByteArray,
+ tempDir: File,
+ ): String {
+ // Decrypt both vaults
+ val localDecrypted = try {
+ VaultCrypto.decrypt(Base64.decode(localVaultBase64, Base64.DEFAULT), encryptionKey)
+ } catch (e: Exception) {
+ throw VaultMergeException.InvalidInput("Failed to decrypt local vault: ${e.message}")
+ }
+
+ val serverDecrypted = try {
+ VaultCrypto.decrypt(Base64.decode(serverVaultBase64, Base64.DEFAULT), encryptionKey)
+ } catch (e: Exception) {
+ throw VaultMergeException.InvalidInput("Failed to decrypt server vault: ${e.message}")
+ }
+
+ // Create temporary database files
+ val localDbFile = File(tempDir, "local_merge_temp.db")
+ val serverDbFile = File(tempDir, "server_merge_temp.db")
+
+ try {
+ localDbFile.writeBytes(localDecrypted)
+ serverDbFile.writeBytes(serverDecrypted)
+
+ val localDb = SQLiteDatabase.openDatabase(localDbFile.absolutePath, null, SQLiteDatabase.OPEN_READWRITE)
+ val serverDb = SQLiteDatabase.openDatabase(serverDbFile.absolutePath, null, SQLiteDatabase.OPEN_READONLY)
+
+ try {
+ // Read all syncable tables
+ val tableNames = getTableNames()
+ val localTables = JSONArray()
+ val serverTables = JSONArray()
+
+ for (tableName in tableNames) {
+ localTables.put(
+ JSONObject().apply {
+ put("name", tableName)
+ put("records", readTable(localDb, tableName))
+ },
+ )
+ serverTables.put(
+ JSONObject().apply {
+ put("name", tableName)
+ put("records", readTable(serverDb, tableName))
+ },
+ )
+ }
+
+ // Call Rust merge
+ val mergeInput = JSONObject().apply {
+ put("local_tables", localTables)
+ put("server_tables", serverTables)
+ }
+
+ val outputJson = uniffi.aliasvault_core.mergeVaultsJson(mergeInput.toString())
+ val statements = parseStatements(outputJson)
+
+ // Apply SQL statements
+ localDb.beginTransaction()
+ try {
+ for ((sql, params) in statements) {
+ localDb.execSQL(sql, params.toTypedArray())
+ }
+ localDb.setTransactionSuccessful()
+ } finally {
+ localDb.endTransaction()
+ }
+
+ localDb.close()
+ serverDb.close()
+
+ // Encrypt and return
+ val mergedData = localDbFile.readBytes()
+ val encrypted = VaultCrypto.encrypt(mergedData, encryptionKey)
+ return Base64.encodeToString(encrypted, Base64.DEFAULT)
+ } finally {
+ if (localDb.isOpen) localDb.close()
+ if (serverDb.isOpen) serverDb.close()
+ }
+ } finally {
+ localDbFile.delete()
+ serverDbFile.delete()
+ }
+ }
+
+ /**
+ * Prune expired items from trash.
+ */
+ @Throws(VaultMergeException::class)
+ fun pruneVault(
+ vaultBase64: String,
+ retentionDays: Int = 30,
+ encryptionKey: ByteArray,
+ tempDir: File,
+ ): Pair<String, Int> {
+ val decrypted = try {
+ VaultCrypto.decrypt(Base64.decode(vaultBase64, Base64.DEFAULT), encryptionKey)
+ } catch (e: Exception) {
+ throw VaultMergeException.InvalidInput("Failed to decrypt vault: ${e.message}")
+ }
+
+ val dbFile = File(tempDir, "prune_temp.db")
+
+ try {
+ dbFile.writeBytes(decrypted)
+ val db = SQLiteDatabase.openDatabase(dbFile.absolutePath, null, SQLiteDatabase.OPEN_READWRITE)
+
+ try {
+ // Read tables needed for pruning
+ val pruneTableNames = listOf("Items", "FieldValues", "Attachments", "TotpCodes", "Passkeys")
+ val tables = JSONArray()
+
+ for (tableName in pruneTableNames) {
+ tables.put(
+ JSONObject().apply {
+ put("name", tableName)
+ put("records", readTable(db, tableName))
+ },
+ )
+ }
+
+ // Call Rust prune
+ val pruneInput = JSONObject().apply {
+ put("tables", tables)
+ put("retention_days", retentionDays)
+ }
+
+ val outputJson = uniffi.aliasvault_core.pruneVaultJson(pruneInput.toString())
+ val statements = parseStatements(outputJson)
+
+ // Apply SQL statements
+ db.beginTransaction()
+ try {
+ for ((sql, params) in statements) {
+ db.execSQL(sql, params.toTypedArray())
+ }
+ db.setTransactionSuccessful()
+ } finally {
+ db.endTransaction()
+ }
+
+ db.close()
+
+ // Encrypt and return
+ val prunedData = dbFile.readBytes()
+ val encrypted = VaultCrypto.encrypt(prunedData, encryptionKey)
+ return Pair(Base64.encodeToString(encrypted, Base64.DEFAULT), statements.size)
+ } finally {
+ if (db.isOpen) db.close()
+ }
+ } finally {
+ dbFile.delete()
+ }
+ }
+
+ private fun readTable(db: SQLiteDatabase, tableName: String): JSONArray {
+ val records = JSONArray()
+
+ // Check if table exists
+ val checkCursor = db.rawQuery(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
+ arrayOf(tableName),
+ )
+ val tableExists = checkCursor.moveToFirst()
+ checkCursor.close()
+ if (!tableExists) return records
+
+ // Read all records
+ val cursor = db.rawQuery("SELECT * FROM $tableName", null)
+ try {
+ while (cursor.moveToNext()) {
+ val record = JSONObject()
+ for (i in 0 until cursor.columnCount) {
+ val columnName = cursor.getColumnName(i)
+ val value = when (cursor.getType(i)) {
+ android.database.Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(i)
+ android.database.Cursor.FIELD_TYPE_FLOAT -> cursor.getDouble(i)
+ android.database.Cursor.FIELD_TYPE_STRING -> cursor.getString(i)
+ android.database.Cursor.FIELD_TYPE_BLOB -> Base64.encodeToString(cursor.getBlob(i), Base64.DEFAULT)
+ else -> JSONObject.NULL
+ }
+ record.put(columnName, value)
+ }
+ records.put(record)
+ }
+ } finally {
+ cursor.close()
+ }
+
+ return records
+ }
+
+ private fun parseStatements(json: String): List<Pair<String, List<String?>>> {
+ val output = JSONObject(json)
+ val statementsArray = output.optJSONArray("statements") ?: JSONArray()
+ val statements = mutableListOf<Pair<String, List<String?>>>()
+
+ for (i in 0 until statementsArray.length()) {
+ val stmt = statementsArray.getJSONObject(i)
+ val sql = stmt.getString("sql")
+ val paramsArray = stmt.optJSONArray("params") ?: JSONArray()
+ val params = (0 until paramsArray.length()).map { j ->
+ val param = paramsArray.opt(j)
+ if (param == JSONObject.NULL || param == null) null else param.toString()
+ }
+ statements.add(Pair(sql, params))
+ }
+
+ return statements
+ }
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMutate.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMutate.kt
index b7ca69b0d..750885d5c 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMutate.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMutate.kt
@@ -3,7 +3,6 @@ package net.aliasvault.app.vaultstore
import android.util.Log
import net.aliasvault.app.exceptions.SerializationException
import net.aliasvault.app.exceptions.VaultOperationException
-import net.aliasvault.app.vaultstore.models.FieldKey
import org.json.JSONArray
import org.json.JSONObject
@@ -23,8 +22,12 @@ class VaultMutate(
/**
* Execute a vault mutation operation.
+ * This captures mutation sequence for race detection and clears dirty after successful upload.
*/
suspend fun mutateVault(webApiService: net.aliasvault.app.webapi.WebApiService): Boolean {
+ // Capture mutation sequence for race detection
+ val mutationSeqAtStart = metadata.getMutationSequence()
+
try {
val vault = prepareVault()
@@ -65,7 +68,8 @@ class VaultMutate(
when (vaultResponse.status) {
0 -> {
- metadata.setVaultRevisionNumber(vaultResponse.newRevisionNumber)
+ // Success - update revision and clear dirty (if no mutations during upload)
+ metadata.markVaultClean(mutationSeqAtStart, vaultResponse.newRevisionNumber)
metadata.setOfflineMode(false)
return true
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultQuery.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultQuery.kt
index e9fb70f16..9925eadd2 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultQuery.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultQuery.kt
@@ -222,7 +222,7 @@ class VaultQuery(
hasAttachment = hasAttachment,
hasTotp = hasTotp,
createdAt = createdAt,
- updatedAt = updatedAt
+ updatedAt = updatedAt,
)
items.add(item)
itemIds.add(idString)
@@ -286,7 +286,7 @@ class VaultQuery(
customFieldType = customFieldType,
customIsHidden = customIsHidden,
customEnableHistory = customEnableHistory,
- isCustomField = isCustomField
+ isCustomField = isCustomField,
)
val field = ItemField(
@@ -297,7 +297,7 @@ class VaultQuery(
isHidden = metadata.isHidden,
displayOrder = displayOrder,
isCustomField = isCustomField,
- enableHistory = metadata.enableHistory
+ enableHistory = metadata.enableHistory,
)
fieldsByItemId.getOrPut(itemIdString) { mutableListOf() }.add(field)
@@ -321,7 +321,7 @@ class VaultQuery(
val label: String,
val fieldType: String,
val isHidden: Boolean,
- val enableHistory: Boolean
+ val enableHistory: Boolean,
)
/**
@@ -334,14 +334,14 @@ class VaultQuery(
customFieldType: String?,
customIsHidden: Boolean,
customEnableHistory: Boolean,
- isCustomField: Boolean
+ isCustomField: Boolean,
): FieldMetadata {
if (isCustomField) {
return FieldMetadata(
label = customLabel ?: fieldKey,
fieldType = customFieldType ?: FieldType.TEXT,
isHidden = customIsHidden,
- enableHistory = customEnableHistory
+ enableHistory = customEnableHistory,
)
}
@@ -391,7 +391,7 @@ class VaultQuery(
logo = item.logo,
createdAt = item.createdAt,
updatedAt = item.updatedAt,
- isDeleted = false
+ isDeleted = false,
)
// Create an Alias if the item has alias fields
@@ -407,7 +407,7 @@ class VaultQuery(
email = item.email,
createdAt = item.createdAt,
updatedAt = item.updatedAt,
- isDeleted = false
+ isDeleted = false,
)
}
@@ -420,7 +420,7 @@ class VaultQuery(
value = passwordValue,
createdAt = item.createdAt,
updatedAt = item.updatedAt,
- isDeleted = false
+ isDeleted = false,
)
}
@@ -433,7 +433,7 @@ class VaultQuery(
password = password,
createdAt = item.createdAt,
updatedAt = item.updatedAt,
- isDeleted = false
+ isDeleted = false,
)
}
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 eba8f1c07..dbb81b8bd 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
@@ -280,9 +280,16 @@ class VaultStore(
/**
* Commit a SQL transaction on the vault.
+ * This also atomically marks the vault as dirty and increments the mutation sequence
+ * for proper sync tracking.
*/
fun commitTransaction() {
databaseComponent.commitTransaction()
+
+ // Atomically mark vault as dirty and increment mutation sequence
+ // This ensures sync can properly detect local changes
+ metadata.setIsDirty(true)
+ metadata.incrementMutationSequence()
}
/**
@@ -522,7 +529,7 @@ class VaultStore(
encryptedVault = encryptedVault,
markDirty = true,
serverRevision = null,
- expectedMutationSeq = null
+ expectedMutationSeq = null,
)
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Item.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Item.kt
index 8ba6c7f58..745487fcf 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Item.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Item.kt
@@ -18,7 +18,7 @@ data class Item(
val hasAttachment: Boolean,
val hasTotp: Boolean,
val createdAt: Date,
- val updatedAt: Date
+ val updatedAt: Date,
) {
/**
* Get the value of a field by its key.
@@ -86,5 +86,5 @@ data class ItemField(
val isHidden: Boolean,
val displayOrder: Int,
val isCustomField: Boolean,
- val enableHistory: Boolean
+ val enableHistory: Boolean,
)
diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.ts
index deedf62bd..3fcb3d28b 100644
--- a/apps/mobile-app/hooks/useVaultMutate.ts
+++ b/apps/mobile-app/hooks/useVaultMutate.ts
@@ -91,11 +91,13 @@ export function useVaultMutate() : {
/**
* Execute the provided operation (e.g. create/update/delete credential)
*
- * Implements the mutation pattern from OFFLINE_MODE.md:
- * 1. Apply mutation to local database
- * 2. Export and encrypt
- * 3. Store locally with dirty flag (ATOMIC!)
- * 4. Sync in background (or immediately if blocking)
+ * Implements the mutation pattern from OFFLINE_MODE.md (matching browser extension):
+ * 1. Apply mutation to local database (via beginTransaction/commitTransaction)
+ * 2. commitTransaction atomically: exports, encrypts, stores vault AND marks dirty + increments mutation sequence
+ * 3. Call syncVault() which handles everything: check isDirty, merge if needed, upload
+ *
+ * Note: The dirty flag and mutation sequence are now set atomically in native commitTransaction(),
+ * so we don't need to call markVaultDirty() separately.
*/
const executeMutateOperation = useCallback(async (
operation: () => Promise<void>,
@@ -104,67 +106,35 @@ export function useVaultMutate() : {
setSyncStatus(t('vault.savingChangesToVault'));
// Execute the provided operation (e.g. create/update/delete credential)
- // The operation should wrap its changes in beginTransaction/commitTransaction
+ // The operation wraps its changes in beginTransaction/commitTransaction
+ // commitTransaction atomically persists vault AND marks dirty + increments mutation sequence
await operation();
- // Persist the updated vault to storage and mark as dirty
- await NativeVaultManager.markVaultDirty();
-
- setSyncStatus(t('vault.uploadingVaultToServer'));
-
- // Upload to server
- try {
- const uploadResult = await NativeVaultManager.uploadVault();
-
- if (uploadResult.success) {
- // Mark vault clean only if no mutations happened during upload
- await NativeVaultManager.markVaultClean(
- uploadResult.mutationSeqAtStart,
- uploadResult.newRevisionNumber
- );
-
- // Register credential identities after successful mutation
+ // Sync vault - this handles everything:
+ // - Checks if server has newer vault
+ // - Merges if isDirty and server has updates
+ // - Uploads local changes
+ // - Handles race detection and retries
+ setSyncStatus(t('vault.syncingVault'));
+ await syncVault({
+ onStatus: (message) => setSyncStatus(message),
+ onSuccess: async () => {
+ // Register credential identities after successful sync
try {
await NativeVaultManager.registerCredentialIdentities();
} catch (error) {
console.warn('VaultMutate: Failed to register credential identities:', error);
}
-
options.onSuccess?.();
- } else if (uploadResult.status === 2) {
- // Vault outdated - need to sync first
- // The sync will handle merging our local changes
- console.log('[VaultMutate] Vault outdated, triggering sync');
- await syncVault({
- onSuccess: () => options.onSuccess?.(),
- onError: (error) => options.onError?.(new Error(error)),
- });
- } else {
- // Other error - keep isDirty true for next sync
- console.warn('[VaultMutate] Failed to upload vault:', uploadResult.error);
-
- // Check if it's a network error
- if (uploadResult.error?.includes('Network') || uploadResult.error?.includes('network')) {
- await NativeVaultManager.setOfflineMode(true);
- // Still call success - the local change is saved
- options.onSuccess?.();
- } else {
- options.onError?.(new Error(uploadResult.error ?? t('common.errors.unknownError')));
- }
- }
- } catch (error) {
- console.error('VaultMutate: Error during vault upload:', error);
-
- // Check if it's a network error
- if (error instanceof Error && (error.message.includes('network') || error.message.includes('timeout'))) {
- await NativeVaultManager.setOfflineMode(true);
- // Still call success - the local change is saved and isDirty is set
+ },
+ onError: (error) => {
+ options.onError?.(new Error(error));
+ },
+ onOffline: () => {
+ // Local change is saved and isDirty is set - will sync when back online
options.onSuccess?.();
- return;
}
-
- options.onError?.(new Error(t('common.errors.unknownError')));
- }
+ });
}, [t, syncVault]);
/**
@@ -275,7 +245,12 @@ export function useVaultMutate() : {
}, [dbContext, authContext, webApi, prepareVaultForPasswordChange, t]);
/**
- * Hook to execute a vault mutation which uploads a new encrypted vault to the server
+ * Hook to execute a vault mutation which uploads a new encrypted vault to the server.
+ *
+ * Follows the pattern from OFFLINE_MODE.md - no pre-sync needed because:
+ * 1. LWW merge resolves conflicts - even if mutating a stale vault, merge picks latest
+ * 2. Popup open triggers sync - vault is reasonably fresh when user starts interacting
+ * 3. Simpler mental model - Mutation = save locally + sync, that's it
*/
const executeVaultMutation = useCallback(async (
operation: () => Promise<void>,
@@ -283,68 +258,12 @@ export function useVaultMutate() : {
) => {
try {
setIsLoading(true);
- setSyncStatus(t('vault.checkingForVaultUpdates'));
-
- // Skip sync check if requested (e.g., during upgrade operations)
- if (options.skipSyncCheck) {
- setSyncStatus(t('vault.executingOperation'));
- await executeMutateOperation(operation, options);
- return;
- }
- // If we're in offline mode, try to sync once to see if we can get back online
- if (authContext.isOffline) {
- await syncVault({
- /**
- * Handle the status update.
- */
- onStatus: (message) => setSyncStatus(message),
- /**
- * Handle successful vault sync and continue with vault mutation.
- */
- onSuccess: async (hasNewVault) => {
- if (hasNewVault) {
- // Vault was changed, but has now been reloaded so we can continue with the operation.
- }
- await executeMutateOperation(operation, options);
- },
- /**
- * Handle offline state and prompt user for action.
- */
- onError: () => {
- // Still offline, proceed with local operation
- executeMutateOperation(operation, options);
- }
- });
- } else {
- await syncVault({
- /**
- * Handle the status update.
- */
- onStatus: (message) => setSyncStatus(message),
- /**
- * Handle successful vault sync and continue with vault mutation.
- */
- onSuccess: async (hasNewVault) => {
- if (hasNewVault) {
- // Vault was changed, but has now been reloaded so we can continue with the operation.
- }
- await executeMutateOperation(operation, options);
- },
- /**
- * Handle error during vault sync.
- */
- onError: (error) => {
- Toast.show({
- type: 'error',
- text1: t('vault.errors.failedToSyncVault'),
- text2: error,
- position: 'bottom'
- });
- options.onError?.(new Error(error));
- }
- });
- }
+ // Execute the mutation operation, which:
+ // 1. Runs the operation (beginTransaction + SQL + commitTransaction)
+ // 2. commitTransaction atomically stores vault + marks dirty + increments mutation sequence
+ // 3. Calls syncVault() which handles merge/upload
+ await executeMutateOperation(operation, options);
} catch (error) {
console.error('Error during vault mutation:', error);
Toast.show({
@@ -357,11 +276,14 @@ export function useVaultMutate() : {
setIsLoading(false);
setSyncStatus('');
}
- }, [syncVault, executeMutateOperation, authContext.isOffline, t]);
+ }, [executeMutateOperation, t]);
/**
* Hook to execute a password change which uploads a new encrypted vault to the server
- * with updated SRP verifier and salt. It shares common logic with the regular vault mutation upload.
+ * with updated SRP verifier and salt.
+ *
+ * Unlike regular mutations, password change REQUIRES a pre-sync to ensure we're
+ * re-encrypting the latest vault. Cannot proceed offline.
*/
const executeVaultPasswordChange = useCallback(async (
currentPasswordHashBase64: string,
@@ -372,61 +294,42 @@ export function useVaultMutate() : {
setIsLoading(true);
setSyncStatus(t('vault.checkingForVaultUpdates'));
- // If we're in offline mode, try to sync once to see if we can get back online
- if (authContext.isOffline) {
- await syncVault({
- /**
- * Handle the status update.
- */
- onStatus: (message) => setSyncStatus(message),
- /**
- * Handle successful vault sync and continue with vault mutation.
- */
- onSuccess: async (hasNewVault) => {
- if (hasNewVault) {
- // Vault was changed, but has now been reloaded so we can continue with the operation.
- }
- await executePasswordChangeOperation(currentPasswordHashBase64, newPasswordPlainText, options);
- },
- /**
- * Handle offline state and prompt user for action.
- */
- onError: () => {
- // Still offline, proceed with local operation
- executePasswordChangeOperation(currentPasswordHashBase64, newPasswordPlainText, options);
- }
- });
- } else {
- await syncVault({
- /**
- * Handle the status update.
- */
+ // Password change requires online - must sync first to get latest vault before re-encryption
+ const syncSuccess = await new Promise<boolean>((resolve) => {
+ syncVault({
onStatus: (message) => setSyncStatus(message),
- /**
- * Handle successful vault sync and continue with vault mutation.
- */
- onSuccess: async (hasNewVault) => {
- if (hasNewVault) {
- // Vault was changed, but has now been reloaded so we can continue with the operation.
- }
- await executePasswordChangeOperation(currentPasswordHashBase64, newPasswordPlainText, options);
- },
- /**
- * Handle error during vault sync.
- */
+ onSuccess: () => resolve(true),
onError: (error) => {
Toast.show({
type: 'error',
text1: t('common.error'),
- text2: t('common.errors.unknownError'),
+ text2: error,
position: 'bottom'
});
options.onError?.(new Error(error));
+ resolve(false);
+ },
+ onOffline: () => {
+ Toast.show({
+ type: 'error',
+ text1: t('common.error'),
+ text2: t('vault.errors.passwordChangeRequiresOnline'),
+ position: 'bottom'
+ });
+ options.onError?.(new Error(t('vault.errors.passwordChangeRequiresOnline')));
+ resolve(false);
}
});
+ });
+
+ if (!syncSuccess) {
+ return;
}
+
+ // Now execute the password change operation
+ await executePasswordChangeOperation(currentPasswordHashBase64, newPasswordPlainText, options);
} catch (error) {
- console.error('Error during vault mutation:', error);
+ console.error('Error during password change:', error);
Toast.show({
type: 'error',
text1: t('common.error'),
@@ -438,7 +341,7 @@ export function useVaultMutate() : {
setIsLoading(false);
setSyncStatus('');
}
- }, [syncVault, executePasswordChangeOperation, authContext.isOffline, t]);
+ }, [syncVault, executePasswordChangeOperation, t]);
return {
executeVaultMutation,
diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.json
index 99d06d147..afe88db5b 100644
--- a/apps/mobile-app/i18n/locales/en.json
+++ b/apps/mobile-app/i18n/locales/en.json
@@ -92,7 +92,8 @@
"versionNotSupported": "This version of the AliasVault mobile app is not supported by the server anymore. Please update your app to the latest version.",
"serverVersionNotSupported": "The AliasVault server needs to be updated to a newer version in order to use this mobile app. Please contact support if you need help.",
"appOutdated": "This app is outdated and cannot be used to access this (newer) vault version. Please update the AliasVault app to continue.",
- "passwordChanged": "Your password has changed since the last time you logged in. Please login again for security reasons."
+ "passwordChanged": "Your password has changed since the last time you logged in. Please login again for security reasons.",
+ "passwordChangeRequiresOnline": "Password change requires an internet connection. Please try again when online."
}
},
"credentials": {
diff --git a/apps/mobile-app/ios/.gitignore b/apps/mobile-app/ios/.gitignore
index 8beb34430..69b9fc167 100644
--- a/apps/mobile-app/ios/.gitignore
+++ b/apps/mobile-app/ios/.gitignore
@@ -28,3 +28,10 @@ project.xcworkspace
# CocoaPods
/Pods/
+
+# Generated Rust Core (built from /core/rust via Scripts/build-rust-core.sh)
+/Frameworks/
+/VaultStoreKit/RustCore/Generated/
+/VaultStoreKit/RustCore/lib/
+/VaultStoreKit/RustCore/include/
+/VaultStoreKit/RustCore/.rust-core-checksum
diff --git a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
index 35b0ea342..3fc35dc56 100644
--- a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
+++ b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
@@ -212,7 +212,7 @@
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
- CEE9098F2DA548C7008D568F /* Exceptions for "Autofill" folder in "Autofill" target */ = {
+ CEE9098F2DA548C7008D568F /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
@@ -222,84 +222,13 @@
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
- CE59C7602E4F47FD0024A246 /* VaultUITests */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultUITests;
- sourceTree = "<group>";
- };
- CE77825E2EA1822400A75E6F /* VaultUtils */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultUtils;
- sourceTree = "<group>";
- };
- CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultStoreKit;
- sourceTree = "<group>";
- };
- CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultStoreKitTests;
- sourceTree = "<group>";
- };
- CEE4816B2DBE8AC800F4A367 /* VaultUI */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultUI;
- sourceTree = "<group>";
- };
- CEE482AB2DBE8EFE00F4A367 /* VaultModels */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultModels;
- sourceTree = "<group>";
- };
- CEE909812DA548C7008D568F /* Autofill */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- CEE9098F2DA548C7008D568F /* Exceptions for "Autofill" folder in "Autofill" target */,
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = Autofill;
- sourceTree = "<group>";
- };
+ CE59C7602E4F47FD0024A246 /* VaultUITests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUITests; sourceTree = "<group>"; };
+ CE77825E2EA1822400A75E6F /* VaultUtils */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUtils; sourceTree = "<group>"; };
+ CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKit; sourceTree = "<group>"; };
+ CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKitTests; sourceTree = "<group>"; };
+ CEE4816B2DBE8AC800F4A367 /* VaultUI */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUI; sourceTree = "<group>"; };
+ CEE482AB2DBE8EFE00F4A367 /* VaultModels */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultModels; sourceTree = "<group>"; };
+ CEE909812DA548C7008D568F /* Autofill */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (CEE9098F2DA548C7008D568F /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Autofill; sourceTree = "<group>"; };
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -633,6 +562,7 @@
isa = PBXNativeTarget;
buildConfigurationList = CEE4809E2DBE86DD00F4A367 /* Build configuration list for PBXNativeTarget "VaultStoreKit" */;
buildPhases = (
+ CE4F28A02F07E5B80032CD40 /* ShellScript */,
CBF1BF747E3EB6DC3F2F5AB8 /* [CP] Check Pods Manifest.lock */,
CEE480822DBE86DC00F4A367 /* Headers */,
CEE480832DBE86DC00F4A367 /* Sources */,
@@ -1126,6 +1056,27 @@
shellPath = /bin/sh;
shellScript = "# Type a script or drag a script file from your workspace to insert its path.\n\"${PODS_ROOT}/SwiftLint/swiftlint\" --config \"${SRCROOT}/.swiftlint.yml\"\n";
};
+ CE4F28A02F07E5B80032CD40 /* ShellScript */ = {
+ isa = PBXShellScriptBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputFileListPaths = (
+ );
+ inputPaths = (
+ "$(SRCROOT)/../../../core/rust/src/",
+ "$(SRCROOT)/../../../core/rust/Cargo.toml",
+ );
+ outputFileListPaths = (
+ );
+ outputPaths = (
+ "$(SRCROOT)/VaultStoreKit/RustCore/lib/device/libaliasvault_core.a",
+ "$(SRCROOT)/VaultStoreKit/RustCore/Generated/aliasvault_core.swift",
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "\"${SRCROOT}/Scripts/build-rust-core.sh\"\n";
+ };
F09C43BBB1E788B0094C9F0D /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
@@ -1324,6 +1275,10 @@
PRODUCT_BUNDLE_IDENTIFIER = net.aliasvault.app;
PRODUCT_NAME = AliasVault;
PROVISIONING_PROFILE_SPECIFIER = "";
+ SWIFT_INCLUDE_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/VaultStoreKit/RustCore/include",
+ );
SWIFT_OBJC_BRIDGING_HEADER = "AliasVault/AliasVault-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
@@ -1359,6 +1314,10 @@
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_RELEASE";
PRODUCT_BUNDLE_IDENTIFIER = net.aliasvault.app;
PRODUCT_NAME = AliasVault;
+ SWIFT_INCLUDE_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/VaultStoreKit/RustCore/include",
+ );
SWIFT_OBJC_BRIDGING_HEADER = "AliasVault/AliasVault-Bridging-Header.h";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
@@ -1420,10 +1379,7 @@
LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
- OTHER_LDFLAGS = (
- "$(inherited)",
- " ",
- );
+ OTHER_LDFLAGS = "$(inherited) ";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";
@@ -1477,10 +1433,7 @@
);
LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";
MTL_ENABLE_DEBUG_INFO = NO;
- OTHER_LDFLAGS = (
- "$(inherited)",
- " ",
- );
+ OTHER_LDFLAGS = "$(inherited) ";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos;
USE_HERMES = true;
@@ -1688,7 +1641,7 @@
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
- ENABLE_USER_SCRIPT_SANDBOXING = YES;
+ ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu17;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
@@ -1699,18 +1652,36 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
+ HEADER_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/VaultStoreKit/RustCore/include",
+ );
+ LIBRARY_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/VaultStoreKit/RustCore/lib/$(RUST_LIB_PLATFORM)",
+ );
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MARKETING_VERSION = 1.0;
MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++";
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20";
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
+ OTHER_LDFLAGS = (
+ "$(inherited)",
+ "-laliasvault_core",
+ );
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_DEBUG";
PRODUCT_BUNDLE_IDENTIFIER = net.aliasvault.app.VaultStoreKit;
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
+ "RUST_LIB_PLATFORM[sdk=iphoneos*]" = device;
+ "RUST_LIB_PLATFORM[sdk=iphonesimulator*]" = simulator;
SKIP_INSTALL = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_INCLUDE_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/VaultStoreKit/RustCore/include",
+ );
SWIFT_INSTALL_MODULE = YES;
SWIFT_INSTALL_OBJC_HEADER = NO;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
@@ -1741,7 +1712,7 @@
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
- ENABLE_USER_SCRIPT_SANDBOXING = YES;
+ ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu17;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
@@ -1752,17 +1723,35 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
+ HEADER_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/VaultStoreKit/RustCore/include",
+ );
+ LIBRARY_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/VaultStoreKit/RustCore/lib/$(RUST_LIB_PLATFORM)",
+ );
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MARKETING_VERSION = 1.0;
MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++";
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20";
MTL_FAST_MATH = YES;
+ OTHER_LDFLAGS = (
+ "$(inherited)",
+ "-laliasvault_core",
+ );
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_RELEASE";
PRODUCT_BUNDLE_IDENTIFIER = net.aliasvault.app.VaultStoreKit;
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
+ "RUST_LIB_PLATFORM[sdk=iphoneos*]" = device;
+ "RUST_LIB_PLATFORM[sdk=iphonesimulator*]" = simulator;
SKIP_INSTALL = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_INCLUDE_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/VaultStoreKit/RustCore/include",
+ );
SWIFT_INSTALL_MODULE = YES;
SWIFT_INSTALL_OBJC_HEADER = NO;
SWIFT_VERSION = 5.0;
@@ -2081,6 +2070,10 @@
SKIP_INSTALL = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_INCLUDE_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/VaultStoreKit/RustCore/include",
+ );
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
@@ -2125,6 +2118,10 @@
SKIP_INSTALL = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_INCLUDE_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/VaultStoreKit/RustCore/include",
+ );
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
diff --git a/apps/mobile-app/ios/Scripts/build-rust-core.sh b/apps/mobile-app/ios/Scripts/build-rust-core.sh
new file mode 100755
index 000000000..5c7aa0d1f
--- /dev/null
+++ b/apps/mobile-app/ios/Scripts/build-rust-core.sh
@@ -0,0 +1,206 @@
+#!/bin/bash
+
+# Build Rust Core for iOS and output static libraries
+# This script is designed to be called from Xcode build phases
+#
+# Usage:
+# ./build-rust-core.sh [--force] [--release]
+#
+# Options:
+# --force Force rebuild even if sources haven't changed
+# --release Build release configuration (default for non-Debug builds)
+
+set -e
+
+# Ensure cargo is in PATH (for Xcode build phases)
+export PATH="$HOME/.cargo/bin:/usr/local/bin:/opt/homebrew/bin:$PATH"
+
+# Colors for output (only if terminal supports it)
+if [ -t 1 ]; then
+ RED='\033[0;31m'
+ GREEN='\033[0;32m'
+ YELLOW='\033[1;33m'
+ BLUE='\033[0;34m'
+ NC='\033[0m'
+else
+ RED=''
+ GREEN=''
+ YELLOW=''
+ BLUE=''
+ NC=''
+fi
+
+# Script location and paths
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+IOS_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
+RUST_CORE_DIR="$(cd "$IOS_DIR/../../../core/rust" && pwd)"
+
+# Output directories - separate device and simulator libraries
+RUST_CORE_OUTPUT="$IOS_DIR/VaultStoreKit/RustCore"
+DEVICE_LIB_OUTPUT="$RUST_CORE_OUTPUT/lib/device"
+SIMULATOR_LIB_OUTPUT="$RUST_CORE_OUTPUT/lib/simulator"
+HEADERS_OUTPUT="$RUST_CORE_OUTPUT/include"
+SWIFT_BINDINGS_OUTPUT="$RUST_CORE_OUTPUT/Generated"
+
+# Parse arguments
+FORCE_BUILD=false
+BUILD_RELEASE=true
+
+# Check Xcode environment for configuration
+if [ "${CONFIGURATION:-}" = "Debug" ]; then
+ BUILD_RELEASE=false
+fi
+
+while [[ $# -gt 0 ]]; do
+ case $1 in
+ --force)
+ FORCE_BUILD=true
+ shift
+ ;;
+ --release)
+ BUILD_RELEASE=true
+ shift
+ ;;
+ --debug)
+ BUILD_RELEASE=false
+ shift
+ ;;
+ *)
+ echo -e "${RED}Unknown option: $1${NC}"
+ exit 1
+ ;;
+ esac
+done
+
+echo -e "${BLUE}========================================${NC}"
+echo -e "${BLUE} Building Rust Core for iOS${NC}"
+echo -e "${BLUE}========================================${NC}"
+
+# Check for Rust toolchain
+if ! command -v rustc &> /dev/null; then
+ echo -e "${RED}Error: Rust is not installed${NC}"
+ echo "Install Rust from https://rustup.rs"
+ exit 1
+fi
+
+if ! command -v cargo &> /dev/null; then
+ echo -e "${RED}Error: Cargo is not installed${NC}"
+ exit 1
+fi
+
+# Check if rebuild is needed
+CHECKSUM_FILE="$RUST_CORE_OUTPUT/.rust-core-checksum"
+CURRENT_CHECKSUM=""
+
+if [ -d "$RUST_CORE_DIR/src" ]; then
+ # Calculate checksum of Rust source files and Cargo.toml
+ CURRENT_CHECKSUM=$(find "$RUST_CORE_DIR/src" -name "*.rs" -type f -exec md5 -q {} \; 2>/dev/null | md5 -q || echo "unknown")
+fi
+
+if [ "$FORCE_BUILD" = false ] && [ -f "$CHECKSUM_FILE" ] && [ -f "$DEVICE_LIB_OUTPUT/libaliasvault_core.a" ]; then
+ STORED_CHECKSUM=$(cat "$CHECKSUM_FILE" 2>/dev/null || echo "")
+ if [ "$CURRENT_CHECKSUM" = "$STORED_CHECKSUM" ]; then
+ echo -e "${GREEN}Rust Core is up to date, skipping build${NC}"
+ exit 0
+ fi
+fi
+
+echo -e "${YELLOW}Rust source changed, rebuilding...${NC}"
+
+# Determine build profile
+if [ "$BUILD_RELEASE" = true ]; then
+ CARGO_FLAGS="--release"
+ CARGO_PROFILE="release"
+ echo -e " Build mode: ${GREEN}Release${NC}"
+else
+ CARGO_FLAGS=""
+ CARGO_PROFILE="debug"
+ echo -e " Build mode: ${YELLOW}Debug${NC}"
+fi
+
+cd "$RUST_CORE_DIR"
+
+# Ensure iOS targets are installed
+echo -e "${YELLOW}Checking iOS build targets...${NC}"
+for target in aarch64-apple-ios aarch64-apple-ios-sim x86_64-apple-ios; do
+ if ! rustup target list --installed 2>/dev/null | grep -q "$target"; then
+ echo -e " Installing $target..."
+ rustup target add "$target"
+ fi
+done
+
+# Create output directories
+mkdir -p "$DEVICE_LIB_OUTPUT" "$SIMULATOR_LIB_OUTPUT" "$HEADERS_OUTPUT" "$SWIFT_BINDINGS_OUTPUT"
+
+# Create temp directory for intermediate files
+TEMP_DIR=$(mktemp -d)
+trap "rm -rf $TEMP_DIR" EXIT
+
+# Build for iOS device (arm64)
+echo -e "${YELLOW}Building for iOS device (aarch64-apple-ios)...${NC}"
+cargo build $CARGO_FLAGS --target aarch64-apple-ios --features uniffi
+
+# Build for iOS simulator (arm64 - Apple Silicon)
+echo -e "${YELLOW}Building for iOS simulator arm64...${NC}"
+cargo build $CARGO_FLAGS --target aarch64-apple-ios-sim --features uniffi
+
+# Build for iOS simulator (x86_64 - Intel Macs)
+echo -e "${YELLOW}Building for iOS simulator x86_64...${NC}"
+cargo build $CARGO_FLAGS --target x86_64-apple-ios --features uniffi
+
+# Copy device library
+cp "target/aarch64-apple-ios/$CARGO_PROFILE/libaliasvault_core.a" "$DEVICE_LIB_OUTPUT/"
+
+# Create universal simulator library
+echo -e "${YELLOW}Creating universal simulator library...${NC}"
+lipo -create \
+ "target/aarch64-apple-ios-sim/$CARGO_PROFILE/libaliasvault_core.a" \
+ "target/x86_64-apple-ios/$CARGO_PROFILE/libaliasvault_core.a" \
+ -output "$SIMULATOR_LIB_OUTPUT/libaliasvault_core.a"
+
+# Strip debug symbols in release mode
+if [ "$BUILD_RELEASE" = true ]; then
+ echo -e "${YELLOW}Stripping debug symbols...${NC}"
+ strip -S "$DEVICE_LIB_OUTPUT/libaliasvault_core.a" 2>/dev/null || true
+ strip -S "$SIMULATOR_LIB_OUTPUT/libaliasvault_core.a" 2>/dev/null || true
+fi
+
+# Generate Swift bindings
+echo -e "${YELLOW}Generating Swift bindings...${NC}"
+cargo run $CARGO_FLAGS --features uniffi-cli --bin uniffi-bindgen -- generate \
+ --library "target/aarch64-apple-ios/$CARGO_PROFILE/libaliasvault_core.a" \
+ --language swift \
+ --out-dir "$TEMP_DIR"
+
+# Copy headers
+cp "$TEMP_DIR/aliasvault_coreFFI.h" "$HEADERS_OUTPUT/"
+
+# Create module.modulemap for the C header
+# Note: Module name must match what UniFFI generates in Swift: aliasvault_coreFFI
+cat > "$HEADERS_OUTPUT/module.modulemap" << 'EOF'
+module aliasvault_coreFFI {
+ header "aliasvault_coreFFI.h"
+ export *
+}
+EOF
+
+# Copy Swift bindings
+cp "$TEMP_DIR/aliasvault_core.swift" "$SWIFT_BINDINGS_OUTPUT/"
+
+echo -e "${GREEN}Swift bindings copied to: $SWIFT_BINDINGS_OUTPUT${NC}"
+
+# Store checksum for incremental builds
+echo "$CURRENT_CHECKSUM" > "$CHECKSUM_FILE"
+
+# Show sizes
+DEVICE_SIZE=$(ls -lh "$DEVICE_LIB_OUTPUT/libaliasvault_core.a" 2>/dev/null | awk '{print $5}' || echo "N/A")
+SIM_SIZE=$(ls -lh "$SIMULATOR_LIB_OUTPUT/libaliasvault_core.a" 2>/dev/null | awk '{print $5}' || echo "N/A")
+
+echo ""
+echo -e "${GREEN}========================================${NC}"
+echo -e "${GREEN} Build Complete!${NC}"
+echo -e "${GREEN}========================================${NC}"
+echo -e " Device library: ${YELLOW}$DEVICE_SIZE${NC}"
+echo -e " Simulator library: ${YELLOW}$SIM_SIZE${NC}"
+echo -e " Output: ${YELLOW}$RUST_CORE_OUTPUT${NC}"
+echo ""
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultMergeService.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultMergeService.swift
new file mode 100644
index 000000000..011a1688b
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultMergeService.swift
@@ -0,0 +1,362 @@
+import Foundation
+import SQLite3
+import CryptoKit
+
+/// Service for vault merge operations using the Rust core library.
+/// Wraps UniFFI-generated bindings for LWW merge operations on SQLite vault databases.
+public class VaultMergeService {
+ public static let shared = VaultMergeService()
+
+ private init() {}
+
+ /// Error types for vault merge operations.
+ public enum VaultMergeError: Error, LocalizedError {
+ case jsonError(String)
+ case rustError(String)
+ case databaseError(String)
+ case invalidInput(String)
+ case encryptionError(String)
+
+ public var errorDescription: String? {
+ switch self {
+ case .jsonError(let msg): return "JSON error: \(msg)"
+ case .rustError(let msg): return "Rust error: \(msg)"
+ case .databaseError(let msg): return "Database error: \(msg)"
+ case .invalidInput(let msg): return "Invalid input: \(msg)"
+ case .encryptionError(let msg): return "Encryption error: \(msg)"
+ }
+ }
+ }
+
+ /// Get the list of syncable table names from Rust.
+ public func getTableNames() -> [String] {
+ // Calls UniFFI-generated function from aliasvault_core.swift
+ return getSyncableTableNames()
+ }
+
+ /// Merge local and server vaults using LWW strategy.
+ ///
+ /// - Parameters:
+ /// - localVaultBase64: Base64-encoded encrypted local vault (format: base64(encrypted(base64(sqlite))))
+ /// - serverVaultBase64: Base64-encoded encrypted server vault (format: base64(encrypted(base64(sqlite))))
+ /// - encryptionKey: The encryption key for decrypting vaults
+ /// - Returns: Base64-encoded merged vault blob (same format as input)
+ public func mergeVaults(
+ localVaultBase64: String,
+ serverVaultBase64: String,
+ encryptionKey: Data
+ ) throws -> String {
+ // Decrypt both vaults
+ // Format is: base64(encrypted(base64(rawSqlite)))
+ // Step 1: Decode outer base64 to get encrypted bytes
+ guard let localVaultData = Data(base64Encoded: localVaultBase64),
+ let serverVaultData = Data(base64Encoded: serverVaultBase64) else {
+ throw VaultMergeError.invalidInput("Invalid base64 vault data")
+ }
+
+ // Step 2: Decrypt to get inner base64 string
+ let localDecryptedBase64 = try decrypt(data: localVaultData, using: encryptionKey)
+ let serverDecryptedBase64 = try decrypt(data: serverVaultData, using: encryptionKey)
+
+ // Step 3: Decode inner base64 to get raw SQLite bytes
+ guard let localDecryptedString = String(data: localDecryptedBase64, encoding: .utf8),
+ let localDecrypted = Data(base64Encoded: localDecryptedString) else {
+ throw VaultMergeError.invalidInput("Invalid inner base64 in local vault")
+ }
+ guard let serverDecryptedString = String(data: serverDecryptedBase64, encoding: .utf8),
+ let serverDecrypted = Data(base64Encoded: serverDecryptedString) else {
+ throw VaultMergeError.invalidInput("Invalid inner base64 in server vault")
+ }
+
+ // Open both SQLite databases
+ let localDb = try openDatabase(from: localDecrypted)
+ let serverDb = try openDatabase(from: serverDecrypted)
+ defer {
+ sqlite3_close(localDb)
+ sqlite3_close(serverDb)
+ }
+
+ // Read all syncable tables from both databases
+ let tableNames = getTableNames()
+ var localTables: [[String: Any]] = []
+ var serverTables: [[String: Any]] = []
+
+ for tableName in tableNames {
+ localTables.append([
+ "name": tableName,
+ "records": try readTable(from: localDb, tableName: tableName)
+ ])
+ serverTables.append([
+ "name": tableName,
+ "records": try readTable(from: serverDb, tableName: tableName)
+ ])
+ }
+
+ // Create merge input and call Rust
+ let mergeInput: [String: Any] = [
+ "local_tables": localTables,
+ "server_tables": serverTables
+ ]
+
+ let inputJson = try serializeToJson(mergeInput)
+ // Call UniFFI-generated function from aliasvault_core.swift
+ let outputJson = try mergeVaultsJson(inputJson: inputJson)
+ let output = try parseOutput(outputJson)
+
+ // Apply SQL statements to local database
+ for statement in output.statements {
+ try executeStatement(on: localDb, sql: statement.sql, params: statement.params)
+ }
+
+ // Export, encrypt, and return in same format: base64(encrypted(base64(sqlite)))
+ let mergedData = try exportDatabase(from: localDb)
+ // Step 1: Base64 encode raw SQLite bytes
+ let innerBase64 = mergedData.base64EncodedString()
+ // Step 2: Encrypt the base64 string
+ let encryptedData = try encrypt(data: Data(innerBase64.utf8), using: encryptionKey)
+ // Step 3: Base64 encode the encrypted data
+ return encryptedData.base64EncodedString()
+ }
+
+ /// Prune expired items from trash.
+ ///
+ /// - Parameters:
+ /// - vaultBase64: Base64-encoded encrypted vault (format: base64(encrypted(base64(sqlite))))
+ /// - retentionDays: Number of days to keep items in trash (default: 30)
+ /// - encryptionKey: The encryption key for decrypting vault
+ /// - Returns: Tuple of (prunedVaultBase64, prunedCount) - same format as input
+ public func pruneVault(
+ vaultBase64: String,
+ retentionDays: Int = 30,
+ encryptionKey: Data
+ ) throws -> (vaultBase64: String, prunedCount: Int) {
+ // Decrypt vault: base64(encrypted(base64(sqlite)))
+ // Step 1: Decode outer base64 to get encrypted bytes
+ guard let vaultData = Data(base64Encoded: vaultBase64) else {
+ throw VaultMergeError.invalidInput("Invalid base64 vault data")
+ }
+
+ // Step 2: Decrypt to get inner base64 string
+ let decryptedBase64 = try decrypt(data: vaultData, using: encryptionKey)
+
+ // Step 3: Decode inner base64 to get raw SQLite bytes
+ guard let decryptedString = String(data: decryptedBase64, encoding: .utf8),
+ let decrypted = Data(base64Encoded: decryptedString) else {
+ throw VaultMergeError.invalidInput("Invalid inner base64 in vault")
+ }
+
+ let db = try openDatabase(from: decrypted)
+ defer { sqlite3_close(db) }
+
+ // Read tables needed for pruning
+ let pruneTableNames = ["Items", "FieldValues", "Attachments", "TotpCodes", "Passkeys"]
+ var tables: [[String: Any]] = []
+
+ for tableName in pruneTableNames {
+ tables.append([
+ "name": tableName,
+ "records": try readTable(from: db, tableName: tableName)
+ ])
+ }
+
+ // Call Rust prune
+ let pruneInput: [String: Any] = [
+ "tables": tables,
+ "retention_days": retentionDays
+ ]
+
+ let inputJson = try serializeToJson(pruneInput)
+ // Call UniFFI-generated function from aliasvault_core.swift
+ let outputJson = try pruneVaultJson(inputJson: inputJson)
+ let output = try parseOutput(outputJson)
+
+ // Apply SQL statements
+ for statement in output.statements {
+ try executeStatement(on: db, sql: statement.sql, params: statement.params)
+ }
+
+ // Export, encrypt, and return in same format: base64(encrypted(base64(sqlite)))
+ let prunedData = try exportDatabase(from: db)
+ // Step 1: Base64 encode raw SQLite bytes
+ let innerBase64 = prunedData.base64EncodedString()
+ // Step 2: Encrypt the base64 string
+ let encryptedData = try encrypt(data: Data(innerBase64.utf8), using: encryptionKey)
+ // Step 3: Base64 encode the encrypted data
+ return (encryptedData.base64EncodedString(), output.statements.count)
+ }
+
+ // MARK: - Encryption Helpers
+
+ private func encrypt(data: Data, using key: Data) throws -> Data {
+ let symmetricKey = SymmetricKey(data: key)
+ guard let sealedBox = try? AES.GCM.seal(data, using: symmetricKey),
+ let combined = sealedBox.combined else {
+ throw VaultMergeError.encryptionError("Encryption failed")
+ }
+ return combined
+ }
+
+ private func decrypt(data: Data, using key: Data) throws -> Data {
+ let symmetricKey = SymmetricKey(data: key)
+ guard let sealedBox = try? AES.GCM.SealedBox(combined: data),
+ let decrypted = try? AES.GCM.open(sealedBox, using: symmetricKey) else {
+ throw VaultMergeError.encryptionError("Decryption failed")
+ }
+ return decrypted
+ }
+
+ // MARK: - Database Helpers
+
+ private struct ParsedOutput {
+ let statements: [(sql: String, params: [Any])]
+ }
+
+ private func openDatabase(from data: Data) throws -> OpaquePointer {
+ var db: OpaquePointer?
+ guard sqlite3_open(":memory:", &db) == SQLITE_OK else {
+ throw VaultMergeError.databaseError("Failed to open in-memory database")
+ }
+
+ let count = Int32(data.count)
+ let result = data.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Int32 in
+ guard let baseAddress = ptr.baseAddress else { return SQLITE_ERROR }
+ let pData = sqlite3_malloc(count)
+ memcpy(pData, baseAddress, Int(count))
+ return sqlite3_deserialize(
+ db,
+ "main",
+ pData?.assumingMemoryBound(to: UInt8.self),
+ Int64(count),
+ Int64(count),
+ UInt32(SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_RESIZEABLE)
+ )
+ }
+
+ guard result == SQLITE_OK else {
+ sqlite3_close(db)
+ throw VaultMergeError.databaseError("Failed to deserialize database: \(result)")
+ }
+
+ return db!
+ }
+
+ private func exportDatabase(from db: OpaquePointer) throws -> Data {
+ var size: sqlite3_int64 = 0
+ guard let serialized = sqlite3_serialize(db, "main", &size, 0) else {
+ throw VaultMergeError.databaseError("Failed to serialize database")
+ }
+ let data = Data(bytes: serialized, count: Int(size))
+ sqlite3_free(serialized)
+ return data
+ }
+
+ private func readTable(from db: OpaquePointer, tableName: String) throws -> [[String: Any]] {
+ var records: [[String: Any]] = []
+
+ // Check if table exists
+ let checkSql = "SELECT name FROM sqlite_master WHERE type='table' AND name=?"
+ var checkStmt: OpaquePointer?
+ guard sqlite3_prepare_v2(db, checkSql, -1, &checkStmt, nil) == SQLITE_OK else { return records }
+ defer { sqlite3_finalize(checkStmt) }
+
+ sqlite3_bind_text(checkStmt, 1, tableName, -1, nil)
+ if sqlite3_step(checkStmt) != SQLITE_ROW { return records }
+
+ // Read all records
+ let sql = "SELECT * FROM \(tableName)"
+ var stmt: OpaquePointer?
+ guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK else {
+ throw VaultMergeError.databaseError("Failed to prepare statement for \(tableName)")
+ }
+ defer { sqlite3_finalize(stmt) }
+
+ let columnCount = sqlite3_column_count(stmt)
+
+ while sqlite3_step(stmt) == SQLITE_ROW {
+ var record: [String: Any] = [:]
+ for iVal in 0..<columnCount {
+ let columnName = String(cString: sqlite3_column_name(stmt, iVal))
+ switch sqlite3_column_type(stmt, iVal) {
+ case SQLITE_INTEGER:
+ record[columnName] = sqlite3_column_int64(stmt, iVal)
+ case SQLITE_FLOAT:
+ record[columnName] = sqlite3_column_double(stmt, iVal)
+ case SQLITE_TEXT:
+ if let text = sqlite3_column_text(stmt, iVal) {
+ record[columnName] = String(cString: text)
+ }
+ case SQLITE_BLOB:
+ if let blob = sqlite3_column_blob(stmt, iVal) {
+ let size = sqlite3_column_bytes(stmt, iVal)
+ record[columnName] = Data(bytes: blob, count: Int(size)).base64EncodedString()
+ }
+ case SQLITE_NULL:
+ record[columnName] = NSNull()
+ default:
+ break
+ }
+ }
+ records.append(record)
+ }
+
+ return records
+ }
+
+ private func executeStatement(on db: OpaquePointer, sql: String, params: [Any]) throws {
+ var stmt: OpaquePointer?
+ guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK else {
+ let error = String(cString: sqlite3_errmsg(db))
+ throw VaultMergeError.databaseError("Failed to prepare statement: \(error)")
+ }
+ defer { sqlite3_finalize(stmt) }
+
+ for (index, param) in params.enumerated() {
+ let bindIndex = Int32(index + 1)
+ switch param {
+ case let intValue as Int:
+ sqlite3_bind_int64(stmt, bindIndex, Int64(intValue))
+ case let int64Value as Int64:
+ sqlite3_bind_int64(stmt, bindIndex, int64Value)
+ case let doubleValue as Double:
+ sqlite3_bind_double(stmt, bindIndex, doubleValue)
+ case let stringValue as String:
+ sqlite3_bind_text(stmt, bindIndex, stringValue, -1, nil)
+ case is NSNull:
+ sqlite3_bind_null(stmt, bindIndex)
+ default:
+ sqlite3_bind_text(stmt, bindIndex, "\(param)", -1, nil)
+ }
+ }
+
+ guard sqlite3_step(stmt) == SQLITE_DONE else {
+ let error = String(cString: sqlite3_errmsg(db))
+ throw VaultMergeError.databaseError("Failed to execute statement: \(error)")
+ }
+ }
+
+ private func serializeToJson(_ dictionary: [String: Any]) throws -> String {
+ let data = try JSONSerialization.data(withJSONObject: dictionary, options: [])
+ guard let json = String(data: data, encoding: .utf8) else {
+ throw VaultMergeError.jsonError("Failed to convert to UTF-8 string")
+ }
+ return json
+ }
+
+ private func parseOutput(_ json: String) throws -> ParsedOutput {
+ guard let data = json.data(using: .utf8),
+ let rawOutput = try JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let statementsArray = rawOutput["statements"] as? [[String: Any]] else {
+ throw VaultMergeError.jsonError("Failed to parse output JSON")
+ }
+
+ let statements = try statementsArray.map { stmt -> (sql: String, params: [Any]) in
+ guard let sql = stmt["sql"] as? String,
+ let params = stmt["params"] as? [Any] else {
+ throw VaultMergeError.jsonError("Invalid statement format")
+ }
+ return (sql: sql, params: params)
+ }
+
+ return ParsedOutput(statements: statements)
+ }
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift
index e5b3f2a9c..29e38d170 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift
@@ -108,11 +108,14 @@ extension VaultStore {
/// 1. Executes the provided SQL operation (already wrapped in a transaction by caller)
/// 2. Prepares the vault for upload
/// 3. Uploads the vault to the server
- /// 4. Updates the local revision number
+ /// 4. Updates the local revision number and clears dirty flag (if no mutations during upload)
///
/// Note: The caller must wrap their database operations in beginTransaction()/commitTransaction()
- /// which will trigger the encryption and local storage of the database.
+ /// which will trigger the encryption and local storage of the database, and atomically mark dirty.
public func mutateVault(using webApiService: WebApiService) async throws {
+ // Capture mutation sequence for race detection
+ let mutationSeqAtStart = getMutationSequence()
+
// Prepare vault for upload
let vault = try prepareVault()
@@ -183,8 +186,8 @@ extension VaultStore {
// Check vault response status
if vaultResponse.status == 0 {
- // Success - update local revision number
- setCurrentVaultRevisionNumber(vaultResponse.newRevisionNumber)
+ // Success - update local revision number and clear dirty (if no mutations during upload)
+ _ = markVaultClean(mutationSeqAtStart: mutationSeqAtStart, newServerRevision: vaultResponse.newRevisionNumber)
// Clear offline mode on successful upload
setOfflineMode(false)
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
index b2c2c3cc4..841626a46 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
@@ -175,6 +175,7 @@ extension VaultStore {
/// Commit a transaction on the database. This is required for all database operations that modify the database.
/// Committing a transaction will also trigger a persist from the in-memory database to the encrypted database file.
+ /// It also atomically marks the vault as dirty and increments the mutation sequence for proper sync tracking.
public func commitTransaction() throws {
guard let dbConnection = self.dbConnection else {
throw NSError(domain: "VaultStore", code: 4, userInfo: [NSLocalizedDescriptionKey: "Database not initialized"])
@@ -182,6 +183,11 @@ extension VaultStore {
try dbConnection.execute("COMMIT")
try persistDatabaseToEncryptedStorage()
+
+ // Atomically mark vault as dirty and increment mutation sequence
+ // This ensures sync can properly detect local changes
+ setIsDirty(true)
+ _ = incrementMutationSequence()
}
/// Rollback a transaction on the database on error.
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
index ae4d77e1a..b45bca4d9 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
@@ -384,16 +384,15 @@ extension VaultStore {
)
}
- // Perform LWW merge using Rust core library
- // TODO: Call actual Rust merge function via native bindings
- // For now, we preserve local changes (same as before)
+ // Perform LWW merge using Rust core library via VaultMergeService
let mergedVault = try performLWWMerge(localVault: localVault, serverVault: serverVault.vault.blob)
// Store merged vault with race detection
+ // Set serverRevision to the server's revision so prepareVault() sends correct revision when uploading
let storeResult = try storeEncryptedVaultWithSyncState(
encryptedVault: mergedVault,
markDirty: false,
- serverRevision: nil, // Will be updated after upload
+ serverRevision: serverVault.vault.currentRevisionNumber,
expectedMutationSeq: mutationSeqAtStart
)
@@ -453,13 +452,40 @@ extension VaultStore {
}
}
- /// Perform Last-Write-Wins merge between local and server vaults
- /// TODO: Integrate with Rust core library for actual merge logic
+ /// Perform Last-Write-Wins merge between local and server vaults using Rust core library.
+ ///
+ /// This method delegates to VaultMergeService which handles:
+ /// 1. Decrypting both vaults
+ /// 2. Reading all syncable tables as JSON
+ /// 3. Calling Rust core's LWW merge function
+ /// 4. Applying resulting SQL statements
+ /// 5. Re-encrypting the merged result
+ ///
+ /// - Parameters:
+ /// - localVault: Base64-encoded encrypted local vault blob
+ /// - serverVault: Base64-encoded encrypted server vault blob
+ /// - Returns: Base64-encoded encrypted merged vault blob
+ /// - Throws: VaultSyncError if merge fails
private func performLWWMerge(localVault: String, serverVault: String) throws -> String {
- // TODO: Call Rust core's merge function via Swift bindings
- // For now, preserve local changes (temporary behavior)
- print("[VaultSync] LWW merge not yet implemented - preserving local changes")
- return localVault
+ guard let encryptionKey = self.encryptionKey else {
+ throw VaultSyncError.unknownError(message: "Encryption key not available for merge")
+ }
+
+ do {
+ let mergedVault = try VaultMergeService.shared.mergeVaults(
+ localVaultBase64: localVault,
+ serverVaultBase64: serverVault,
+ encryptionKey: encryptionKey
+ )
+ print("[VaultSync] LWW merge completed successfully via Rust core")
+ return mergedVault
+ } catch let error as VaultMergeService.VaultMergeError {
+ print("[VaultSync] Merge error: \(error.localizedDescription)")
+ throw VaultSyncError.unknownError(message: "Merge failed: \(error.localizedDescription)")
+ } catch {
+ print("[VaultSync] Unexpected merge error: \(error)")
+ throw VaultSyncError.unknownError(message: "Merge failed: \(error.localizedDescription)")
+ }
}
/// Handle sync errors and return appropriate result
diff --git a/core/rust/Cargo.lock b/core/rust/Cargo.lock
index abeb6dea9..128cf311d 100644
--- a/core/rust/Cargo.lock
+++ b/core/rust/Cargo.lock
@@ -25,6 +25,56 @@ dependencies = [
"libc",
]
+[[package]]
+name = "anstream"
+version = "0.6.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"
+
+[[package]]
+name = "anstyle-parse"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys",
+]
+
[[package]]
name = "anyhow"
version = "1.0.100"
@@ -170,6 +220,52 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "clap"
+version = "4.5.53"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9e340e012a1bf4935f5282ed1436d1489548e8f72308207ea5df0e23d2d03f8"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.5.53"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d76b5d13eaa18c901fd2f7fca939fefe3a0727a953561fefdf3b2922b8569d00"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.5.49"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a0b5487afeab2deb2ff4e03a807ad1a03ac532ff5a2cee5d86884440c7f7671"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "clap_lex"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d"
+
+[[package]]
+name = "colorchoice"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
+
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
@@ -248,6 +344,12 @@ dependencies = [
"cc",
]
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+
[[package]]
name = "itoa"
version = "1.0.15"
@@ -329,6 +431,12 @@ version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
+[[package]]
+name = "once_cell_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+
[[package]]
name = "paste"
version = "1.0.15"
@@ -479,6 +587,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
[[package]]
name = "syn"
version = "2.0.111"
@@ -547,8 +661,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cb08c58c7ed7033150132febe696bef553f891b1ede57424b40d87a89e3c170"
dependencies = [
"anyhow",
+ "camino",
"cargo_metadata",
+ "clap",
"uniffi_bindgen",
+ "uniffi_build",
"uniffi_core",
"uniffi_macros",
]
@@ -576,6 +693,17 @@ dependencies = [
"uniffi_udl",
]
+[[package]]
+name = "uniffi_build"
+version = "0.28.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c7cf32576e08104b7dc2a6a5d815f37616e66c6866c2a639fe16e6d2286b75b"
+dependencies = [
+ "anyhow",
+ "camino",
+ "uniffi_bindgen",
+]
+
[[package]]
name = "uniffi_checksum_derive"
version = "0.28.3"
@@ -656,6 +784,12 @@ dependencies = [
"weedle2",
]
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
[[package]]
name = "wasm-bindgen"
version = "0.2.106"
@@ -768,3 +902,12 @@ checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
diff --git a/core/rust/Cargo.toml b/core/rust/Cargo.toml
index 751a4e285..cc4ca6697 100644
--- a/core/rust/Cargo.toml
+++ b/core/rust/Cargo.toml
@@ -16,8 +16,10 @@ name = "aliasvault_core"
[features]
default = []
-# Feature for UniFFI bindings (Swift/Kotlin)
+# Feature for UniFFI bindings (Swift/Kotlin) - runtime only, no CLI tools
uniffi = ["dep:uniffi"]
+# Feature for UniFFI CLI bindgen tool (only for generating bindings, not for library)
+uniffi-cli = ["uniffi/cli"]
# Feature for WASM builds (browser extension)
wasm = ["dep:wasm-bindgen", "dep:serde-wasm-bindgen", "dep:console_error_panic_hook"]
# Feature for C FFI exports (.NET P/Invoke)
@@ -35,6 +37,8 @@ chrono = { version = "0.4", features = ["serde"] }
thiserror = "1.0"
# UniFFI for Swift/Kotlin bindings (optional)
+# Note: Don't add "cli" feature here - it pulls in heavy bindgen dependencies
+# The uniffi-cli feature enables CLI separately for the uniffi-bindgen binary only
uniffi = { version = "0.28", optional = true }
# WASM bindings (optional)
@@ -44,6 +48,17 @@ console_error_panic_hook = { version = "0.1", optional = true }
[dev-dependencies]
+# Build dependencies for UniFFI
+[build-dependencies]
+uniffi = { version = "0.28", features = ["build"] }
+
+# Binary for generating Swift/Kotlin bindings
+# This binary requires uniffi-cli feature which includes the heavy bindgen dependencies
+[[bin]]
+name = "uniffi-bindgen"
+path = "uniffi-bindgen.rs"
+required-features = ["uniffi-cli"]
+
# Dev profile - fast compilation
[profile.dev]
opt-level = 0
diff --git a/core/rust/build.sh b/core/rust/build.sh
index f552cca85..5013ab820 100755
--- a/core/rust/build.sh
+++ b/core/rust/build.sh
@@ -18,10 +18,14 @@ cd "$SCRIPT_DIR"
DIST_DIR="$SCRIPT_DIR/dist"
WASM_DIR="$DIST_DIR/wasm"
DOTNET_DIR="$DIST_DIR/dotnet"
+IOS_DIR="$DIST_DIR/ios"
+ANDROID_DIR="$DIST_DIR/android"
# Target directories in consumer apps
BROWSER_EXT_DIST="$SCRIPT_DIR/../../apps/browser-extension/src/utils/dist/core/rust"
BLAZOR_CLIENT_DIST="$SCRIPT_DIR/../../apps/server/AliasVault.Client/wwwroot/wasm"
+IOS_APP_DIST="$SCRIPT_DIR/../../apps/mobile-app/ios/VaultStoreKit/RustCore"
+ANDROID_APP_DIST="$SCRIPT_DIR/../../apps/mobile-app/android/app/src/main/jniLibs"
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE} AliasVault Rust Core Build Script${NC}"
@@ -50,6 +54,8 @@ echo -e " Rust version: ${GREEN}$RUST_VERSION${NC}"
BUILD_ALL=false
BUILD_BROWSER=false
BUILD_DOTNET=false
+BUILD_IOS=false
+BUILD_ANDROID=false
FAST_MODE=false
# Parse arguments
@@ -63,9 +69,24 @@ while [[ $# -gt 0 ]]; do
BUILD_DOTNET=true
shift
;;
+ --ios)
+ BUILD_IOS=true
+ shift
+ ;;
+ --android)
+ BUILD_ANDROID=true
+ shift
+ ;;
+ --mobile)
+ BUILD_IOS=true
+ BUILD_ANDROID=true
+ shift
+ ;;
--all)
BUILD_BROWSER=true
BUILD_DOTNET=true
+ BUILD_IOS=true
+ BUILD_ANDROID=true
shift
;;
--fast|--dev)
@@ -79,6 +100,9 @@ while [[ $# -gt 0 ]]; do
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) with Swift bindings"
+ echo " --android Build for Android (arm64-v8a, armeabi-v7a, x86_64) with Kotlin bindings"
+ echo " --mobile Build for both iOS and Android"
echo " --all Build all targets"
echo ""
echo "Speed options:"
@@ -97,12 +121,15 @@ while [[ $# -gt 0 ]]; do
done
# If no targets specified, show help
-if ! $BUILD_BROWSER && ! $BUILD_DOTNET; then
+if ! $BUILD_BROWSER && ! $BUILD_DOTNET && ! $BUILD_IOS && ! $BUILD_ANDROID; then
echo "No target specified. Use --help for usage."
echo ""
echo "Quick start:"
echo " ./build.sh --browser # 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"
+ echo " ./build.sh --mobile # Build for iOS and Android"
exit 0
fi
@@ -268,6 +295,319 @@ build_dotnet() {
echo -e "${GREEN}.NET build complete! (${duration}s)${NC}"
}
+# ============================================
+# iOS Build (Universal Binary + Swift Bindings)
+# ============================================
+build_ios() {
+ echo ""
+ echo -e "${BLUE}Building for iOS...${NC}"
+
+ local start_time=$(date +%s)
+
+ # Check for Xcode (required for iOS builds)
+ if ! command -v xcrun &> /dev/null; then
+ echo -e "${RED}Error: Xcode command line tools not found${NC}"
+ echo "Install with: xcode-select --install"
+ exit 1
+ fi
+
+ # Install iOS targets if needed
+ echo -e " Checking iOS build targets..."
+ for target in aarch64-apple-ios aarch64-apple-ios-sim x86_64-apple-ios; do
+ if ! rustup target list --installed 2>/dev/null | grep -q "$target"; then
+ echo -e " Installing $target..."
+ rustup target add "$target"
+ fi
+ done
+
+ # Create output directories
+ mkdir -p "$IOS_DIR/device"
+ 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
+
+ # Build for iOS device (arm64)
+ # Note: Use only 'uniffi' feature for library builds (not uniffi-cli which includes heavy bindgen deps)
+ echo -e " Building for iOS device (aarch64-apple-ios)..."
+ cargo build $cargo_flags --target aarch64-apple-ios --features uniffi
+
+ # Build for iOS simulator (arm64 - Apple Silicon)
+ echo -e " Building for iOS simulator arm64 (aarch64-apple-ios-sim)..."
+ cargo build $cargo_flags --target aarch64-apple-ios-sim --features uniffi
+
+ # Build for iOS simulator (x86_64 - Intel Macs)
+ echo -e " Building for iOS simulator x86_64 (x86_64-apple-ios)..."
+ cargo build $cargo_flags --target x86_64-apple-ios --features uniffi
+
+ # Copy device library
+ cp "target/aarch64-apple-ios/$cargo_profile/libaliasvault_core.a" "$IOS_DIR/device/"
+
+ # Create universal simulator library (arm64 + x86_64)
+ echo -e " Creating universal simulator library..."
+ lipo -create \
+ "target/aarch64-apple-ios-sim/$cargo_profile/libaliasvault_core.a" \
+ "target/x86_64-apple-ios/$cargo_profile/libaliasvault_core.a" \
+ -output "$IOS_DIR/simulator/libaliasvault_core.a"
+
+ # 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
+
+ # Generate Swift bindings using UniFFI
+ # Note: Use uniffi-cli feature here since we need the bindgen CLI tool
+ echo -e " Generating Swift bindings..."
+ cargo run $cargo_flags --features uniffi-cli --bin uniffi-bindgen -- generate \
+ --library "target/aarch64-apple-ios/$cargo_profile/libaliasvault_core.a" \
+ --language swift \
+ --out-dir "$IOS_DIR/swift"
+
+ local end_time=$(date +%s)
+ local duration=$((end_time - start_time))
+
+ # Show output sizes
+ if [ -f "$IOS_DIR/device/libaliasvault_core.a" ]; then
+ local device_size=$(ls -lh "$IOS_DIR/device/libaliasvault_core.a" | awk '{print $5}')
+ local sim_size=$(ls -lh "$IOS_DIR/simulator/libaliasvault_core.a" | awk '{print $5}')
+ echo -e "${GREEN}iOS build complete! (${duration}s)${NC}"
+ echo -e " Device library: ${YELLOW}$device_size${NC}"
+ echo -e " Simulator library: ${YELLOW}$sim_size${NC}"
+
+ if [ -d "$IOS_DIR/swift" ] && [ -n "$(ls -A "$IOS_DIR/swift" 2>/dev/null)" ]; then
+ echo -e " Swift bindings: ${GREEN}Generated${NC}"
+ ls "$IOS_DIR/swift/"
+ fi
+ fi
+}
+
+# ============================================
+# iOS Distribution
+# ============================================
+distribute_ios() {
+ echo ""
+ echo -e "${BLUE}Distributing to iOS app...${NC}"
+
+ mkdir -p "$IOS_APP_DIST/device"
+ mkdir -p "$IOS_APP_DIST/simulator"
+ mkdir -p "$IOS_APP_DIST/swift"
+
+ # Copy libraries
+ if [ -f "$IOS_DIR/device/libaliasvault_core.a" ]; then
+ cp "$IOS_DIR/device/libaliasvault_core.a" "$IOS_APP_DIST/device/"
+ echo -e " Copied device library"
+ fi
+
+ if [ -f "$IOS_DIR/simulator/libaliasvault_core.a" ]; then
+ cp "$IOS_DIR/simulator/libaliasvault_core.a" "$IOS_APP_DIST/simulator/"
+ echo -e " Copied simulator library"
+ fi
+
+ # Copy Swift bindings
+ if [ -d "$IOS_DIR/swift" ] && [ -n "$(ls -A "$IOS_DIR/swift" 2>/dev/null)" ]; then
+ cp "$IOS_DIR/swift"/*.swift "$IOS_APP_DIST/swift/" 2>/dev/null || true
+ cp "$IOS_DIR/swift"/*.h "$IOS_APP_DIST/swift/" 2>/dev/null || true
+ cp "$IOS_DIR/swift"/*.modulemap "$IOS_APP_DIST/swift/" 2>/dev/null || true
+ echo -e " Copied Swift bindings"
+ fi
+
+ # Create README
+ cat > "$IOS_APP_DIST/README.md" << 'README_EOF'
+# Rust Core iOS Library
+
+Auto-generated from `/core/rust`. Do not edit manually.
+
+## Contents
+
+- `device/libaliasvault_core.a` - Static library for iOS devices (arm64)
+- `simulator/libaliasvault_core.a` - Universal static library for iOS simulator (arm64 + x86_64)
+- `swift/` - Swift bindings generated by UniFFI
+
+## Regenerate
+
+```bash
+cd /core/rust
+./build.sh --ios
+```
+
+## Integration
+
+1. Add the static library to your Xcode project
+2. Add the Swift bindings to your project
+3. Import `aliasvault_core` in your Swift code
+README_EOF
+
+ echo -e "${GREEN}Distributed to: $IOS_APP_DIST${NC}"
+ ls -la "$IOS_APP_DIST/"
+}
+
+# ============================================
+# Android Build (Multiple ABIs + Kotlin Bindings)
+# ============================================
+build_android() {
+ echo ""
+ echo -e "${BLUE}Building for Android...${NC}"
+
+ local start_time=$(date +%s)
+
+ # Check for Android NDK
+ if [ -z "${ANDROID_NDK_HOME:-}" ]; then
+ # Try to find NDK in common locations
+ if [ -d "$HOME/Library/Android/sdk/ndk" ]; then
+ # Find the latest NDK version
+ ANDROID_NDK_HOME=$(ls -d "$HOME/Library/Android/sdk/ndk"/*/ 2>/dev/null | sort -V | tail -1)
+ ANDROID_NDK_HOME="${ANDROID_NDK_HOME%/}"
+ elif [ -d "$HOME/Android/Sdk/ndk" ]; then
+ ANDROID_NDK_HOME=$(ls -d "$HOME/Android/Sdk/ndk"/*/ 2>/dev/null | sort -V | tail -1)
+ ANDROID_NDK_HOME="${ANDROID_NDK_HOME%/}"
+ fi
+
+ if [ -z "${ANDROID_NDK_HOME:-}" ]; then
+ echo -e "${RED}Error: Android NDK not found${NC}"
+ echo "Set ANDROID_NDK_HOME environment variable or install NDK via Android Studio"
+ exit 1
+ fi
+ fi
+
+ echo -e " Using Android NDK: ${YELLOW}$ANDROID_NDK_HOME${NC}"
+
+ # Install Android targets if needed
+ echo -e " Checking Android build targets..."
+ for target in aarch64-linux-android armv7-linux-androideabi x86_64-linux-android; do
+ if ! rustup target list --installed 2>/dev/null | grep -q "$target"; then
+ echo -e " Installing $target..."
+ rustup target add "$target"
+ fi
+ done
+
+ # Create output directories
+ mkdir -p "$ANDROID_DIR/arm64-v8a"
+ mkdir -p "$ANDROID_DIR/armeabi-v7a"
+ 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
+
+ # Set up Android toolchain
+ local host_tag
+ case "$(uname -s)" in
+ Darwin) host_tag="darwin-x86_64" ;;
+ Linux) host_tag="linux-x86_64" ;;
+ *) host_tag="windows-x86_64" ;;
+ esac
+
+ local toolchain="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/$host_tag"
+ local api_level=24 # Android 7.0 minimum
+
+ # Build for each ABI
+ # Note: Use only 'uniffi' feature for library builds (not uniffi-cli which includes heavy bindgen deps)
+ echo -e " Building for arm64-v8a..."
+ AR="$toolchain/bin/llvm-ar" \
+ 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
+
+ echo -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
+
+ echo -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
+
+ # Copy libraries
+ cp "target/aarch64-linux-android/$cargo_profile/libaliasvault_core.so" "$ANDROID_DIR/arm64-v8a/"
+ cp "target/armv7-linux-androideabi/$cargo_profile/libaliasvault_core.so" "$ANDROID_DIR/armeabi-v7a/"
+ cp "target/x86_64-linux-android/$cargo_profile/libaliasvault_core.so" "$ANDROID_DIR/x86_64/"
+
+ # 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
+ fi
+
+ # Generate Kotlin bindings using UniFFI
+ # Note: Use uniffi-cli feature here since we need the bindgen CLI tool
+ echo -e " Generating Kotlin bindings..."
+ cargo run $cargo_flags --features uniffi-cli --bin uniffi-bindgen -- generate \
+ --library "target/aarch64-linux-android/$cargo_profile/libaliasvault_core.so" \
+ --language kotlin \
+ --out-dir "$ANDROID_DIR/kotlin"
+
+ local end_time=$(date +%s)
+ local duration=$((end_time - start_time))
+
+ # Show output sizes
+ echo -e "${GREEN}Android build complete! (${duration}s)${NC}"
+ for abi in arm64-v8a armeabi-v7a x86_64; do
+ if [ -f "$ANDROID_DIR/$abi/libaliasvault_core.so" ]; then
+ local size=$(ls -lh "$ANDROID_DIR/$abi/libaliasvault_core.so" | awk '{print $5}')
+ echo -e " $abi: ${YELLOW}$size${NC}"
+ fi
+ done
+
+ if [ -d "$ANDROID_DIR/kotlin" ] && [ -n "$(ls -A "$ANDROID_DIR/kotlin" 2>/dev/null)" ]; then
+ echo -e " Kotlin bindings: ${GREEN}Generated${NC}"
+ fi
+}
+
+# ============================================
+# Android Distribution
+# ============================================
+distribute_android() {
+ echo ""
+ echo -e "${BLUE}Distributing to Android app...${NC}"
+
+ # Copy native libraries to jniLibs
+ for abi in arm64-v8a armeabi-v7a x86_64; do
+ if [ -f "$ANDROID_DIR/$abi/libaliasvault_core.so" ]; then
+ mkdir -p "$ANDROID_APP_DIST/$abi"
+ cp "$ANDROID_DIR/$abi/libaliasvault_core.so" "$ANDROID_APP_DIST/$abi/"
+ echo -e " Copied $abi library"
+ fi
+ done
+
+ # Copy Kotlin bindings to app source
+ local kotlin_dist="$SCRIPT_DIR/../../apps/mobile-app/android/app/src/main/java/net/aliasvault/app/rustcore"
+ if [ -d "$ANDROID_DIR/kotlin" ] && [ -n "$(ls -A "$ANDROID_DIR/kotlin" 2>/dev/null)" ]; then
+ mkdir -p "$kotlin_dist"
+ cp "$ANDROID_DIR/kotlin"/*.kt "$kotlin_dist/" 2>/dev/null || true
+ echo -e " Copied Kotlin bindings to $kotlin_dist"
+ fi
+
+ echo -e "${GREEN}Distributed to: $ANDROID_APP_DIST${NC}"
+}
+
# ============================================
# Main Build Process
# ============================================
@@ -285,6 +625,16 @@ if $BUILD_DOTNET; then
echo -e "${YELLOW}Note: Native library built to dist/dotnet/ (for server-side .NET use)${NC}"
fi
+if $BUILD_IOS; then
+ build_ios
+ distribute_ios
+fi
+
+if $BUILD_ANDROID; then
+ build_android
+ distribute_android
+fi
+
TOTAL_END=$(date +%s)
TOTAL_DURATION=$((TOTAL_END - TOTAL_START))
diff --git a/core/rust/src/error.rs b/core/rust/src/error.rs
index 390efc1e5..4719c5ee9 100644
--- a/core/rust/src/error.rs
+++ b/core/rust/src/error.rs
@@ -3,7 +3,10 @@
use thiserror::Error;
/// Errors that can occur during vault operations.
-#[derive(Error, Debug)]
+///
+/// This enum is exposed to Swift/Kotlin via UniFFI as a flat error type,
+/// meaning the error variants are exposed as simple enum cases with string messages.
+#[derive(Error, Debug, Clone)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]
#[cfg_attr(feature = "uniffi", uniffi(flat_error))]
pub enum VaultError {
diff --git a/core/rust/src/lib.rs b/core/rust/src/lib.rs
index f4f37eb3c..59b99734c 100644
--- a/core/rust/src/lib.rs
+++ b/core/rust/src/lib.rs
@@ -54,6 +54,13 @@ pub use wasm::*;
#[cfg(feature = "ffi")]
pub mod ffi;
-// UniFFI scaffolding
+// UniFFI bindings for Swift/Kotlin
+#[cfg(feature = "uniffi")]
+pub mod uniffi_api;
+
+#[cfg(feature = "uniffi")]
+pub use uniffi_api::*;
+
+// UniFFI scaffolding - generates the FFI glue code
#[cfg(feature = "uniffi")]
uniffi::setup_scaffolding!();
diff --git a/core/rust/src/uniffi_api.rs b/core/rust/src/uniffi_api.rs
new file mode 100644
index 000000000..37fc17bb9
--- /dev/null
+++ b/core/rust/src/uniffi_api.rs
@@ -0,0 +1,164 @@
+//! UniFFI API module for Swift and Kotlin bindings.
+//!
+//! This module exposes the core vault operations via UniFFI for mobile platforms.
+//! All functions use JSON strings for input/output to simplify cross-language marshalling.
+
+use crate::error::VaultError;
+use crate::vault_merge::SYNCABLE_TABLE_NAMES;
+
+/// Get the list of syncable table names.
+/// These are the tables that need to be read from the database for merge/prune operations.
+#[uniffi::export]
+pub fn get_syncable_table_names() -> Vec<String> {
+ SYNCABLE_TABLE_NAMES
+ .iter()
+ .map(|s| s.to_string())
+ .collect()
+}
+
+/// Merge local and server vaults using Last-Write-Wins strategy.
+///
+/// # Arguments
+/// * `input_json` - JSON string with format:
+/// ```json
+/// {
+/// "local_tables": [{"name": "Items", "records": [...]}],
+/// "server_tables": [{"name": "Items", "records": [...]}]
+/// }
+/// ```
+///
+/// # Returns
+/// JSON string with format:
+/// ```json
+/// {
+/// "success": true,
+/// "statements": [{"sql": "UPDATE ...", "params": [...]}],
+/// "stats": {"tables_processed": 11, "conflicts": 0, ...}
+/// }
+/// ```
+#[uniffi::export]
+pub fn merge_vaults_json(input_json: String) -> Result<String, VaultError> {
+ crate::vault_merge::merge_vaults_json(&input_json)
+}
+
+/// Prune expired items from trash (items with DeletedAt older than retention_days).
+///
+/// # Arguments
+/// * `input_json` - JSON string with format:
+/// ```json
+/// {
+/// "tables": [{"name": "Items", "records": [...]}],
+/// "retention_days": 30
+/// }
+/// ```
+///
+/// # Returns
+/// JSON string with format:
+/// ```json
+/// {
+/// "success": true,
+/// "statements": [{"sql": "UPDATE ...", "params": [...]}],
+/// "stats": {"items_pruned": 0, ...}
+/// }
+/// ```
+#[uniffi::export]
+pub fn prune_vault_json(input_json: String) -> Result<String, VaultError> {
+ crate::vault_pruner::prune_vault_json(&input_json)
+}
+
+/// Filter credentials for autofill based on current URL/app and page title.
+///
+/// # Arguments
+/// * `input_json` - JSON string with format:
+/// ```json
+/// {
+/// "credentials": [{"Id": "...", "ServiceName": "...", "ServiceUrl": "..."}],
+/// "current_url": "https://github.com",
+/// "page_title": "GitHub",
+/// "matching_mode": "default"
+/// }
+/// ```
+///
+/// # Returns
+/// JSON string with format:
+/// ```json
+/// {
+/// "matched_ids": ["id1", "id2"],
+/// "matched_priority": 2
+/// }
+/// ```
+#[uniffi::export]
+pub fn filter_credentials_json(input_json: String) -> Result<String, VaultError> {
+ crate::credential_matcher::filter_credentials_json(&input_json)
+ .map_err(|e| VaultError::General(e))
+}
+
+/// Extract domain from a URL.
+/// Strips the www. prefix if present.
+/// Example: "https://www.example.com/path" -> "example.com"
+#[uniffi::export]
+pub fn extract_domain(url: String) -> String {
+ crate::credential_matcher::extract_domain(&url)
+}
+
+/// Extract root domain from a domain.
+/// Example: "www.example.com" -> "example.com"
+#[uniffi::export]
+pub fn extract_root_domain(domain: String) -> String {
+ crate::credential_matcher::extract_root_domain(&domain)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_get_syncable_table_names() {
+ let names = get_syncable_table_names();
+ assert!(names.contains(&"Items".to_string()));
+ assert!(names.contains(&"FieldValues".to_string()));
+ assert_eq!(names.len(), 11);
+ }
+
+ #[test]
+ fn test_merge_vaults_json() {
+ let input = r#"{
+ "local_tables": [{"name": "Items", "records": []}],
+ "server_tables": [{"name": "Items", "records": []}]
+ }"#;
+
+ let result = merge_vaults_json(input.to_string());
+ assert!(result.is_ok());
+
+ let output: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
+ assert_eq!(output["success"], true);
+ }
+
+ #[test]
+ fn test_prune_vault_json() {
+ let input = r#"{
+ "tables": [{"name": "Items", "records": []}],
+ "retention_days": 30
+ }"#;
+
+ let result = prune_vault_json(input.to_string());
+ assert!(result.is_ok());
+
+ let output: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
+ assert_eq!(output["success"], true);
+ }
+
+ #[test]
+ fn test_extract_domain() {
+ // extract_domain strips www. prefix from domains
+ assert_eq!(extract_domain("https://www.example.com/path".to_string()), "example.com");
+ assert_eq!(extract_domain("http://github.com".to_string()), "github.com");
+ assert_eq!(extract_domain("https://subdomain.example.com".to_string()), "subdomain.example.com");
+ }
+
+ #[test]
+ fn test_extract_root_domain() {
+ assert_eq!(extract_root_domain("www.example.com".to_string()), "example.com");
+ assert_eq!(extract_root_domain("github.com".to_string()), "github.com");
+ }
+}
diff --git a/core/rust/uniffi-bindgen.rs b/core/rust/uniffi-bindgen.rs
new file mode 100644
index 000000000..f6cff6cf1
--- /dev/null
+++ b/core/rust/uniffi-bindgen.rs
@@ -0,0 +1,3 @@
+fn main() {
+ uniffi::uniffi_bindgen_main()
+}