Skip to content

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

Refactor Rust core calls to work via generic call mechanism (#2159)

Leendert de Borst3ae33432d555
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 7f4e8b492..182360def 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
@@ -25,6 +25,7 @@ import kotlinx.coroutines.withContext
import net.aliasvault.app.qrscanner.QRScannerActivity
import net.aliasvault.app.vaultstore.AppError
import net.aliasvault.app.vaultstore.VaultStore
+import net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallback
import net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider
import net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
import net.aliasvault.app.webapi.WebApiService
@@ -322,6 +323,65 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
}
+ /**
+ * Store the account-key chain the native password unlock unwraps (null for a legacy account).
+ * @param chainJson The chain as JSON, or null
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun storeAccountKeyChain(chainJson: String?, promise: Promise) {
+ try {
+ vaultStore.storeAccountKeyChain(chainJson)
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error storing account key chain", e)
+ promise.reject("ERR_STORE_ACCOUNT_KEY_CHAIN", "Failed to store account key chain: ${e.message}", e)
+ }
+ }
+
+ /**
+ * The id of the user's personal manifest as the last sync recorded it, or null before the first pull.
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun getPersonalManifestId(promise: Promise) {
+ promise.resolve(vaultStore.database.getPersonalManifestId())
+ }
+
+ /**
+ * Resolve and store the vault key right after login from the password-derived key (see VaultStore.resolveVaultKey).
+ * Resolves with the stored key; rejects with the native error code when the chain does not open or the session is gone.
+ * @param base64DerivedKey The password-derived key as base64
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun resolveVaultKey(base64DerivedKey: String, promise: Promise) {
+ CoroutineScope(Dispatchers.IO).launch {
+ try {
+ val key = vaultStore.resolveVaultKey(webApiService, base64DerivedKey)
+ withContext(Dispatchers.Main) { promise.resolve(key) }
+ } catch (e: AppError) {
+ withContext(Dispatchers.Main) { promise.reject(e.code, e.message, e) }
+ } catch (e: Exception) {
+ withContext(Dispatchers.Main) { promise.reject("E-001", "Failed to resolve the vault key: ${e.message}", e) }
+ }
+ }
+ }
+
+ /**
+ * Get the stored account-key chain JSON, or null for a legacy account.
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun getAccountKeyChain(promise: Promise) {
+ try {
+ promise.resolve(vaultStore.getAccountKeyChain())
+ } catch (e: Exception) {
+ Log.e(TAG, "Error getting account key chain", e)
+ promise.reject("ERR_GET_ACCOUNT_KEY_CHAIN", "Failed to get account key chain: ${e.message}", e)
+ }
+ }
+
/**
* Encrypt the decryption key for mobile login.
* @param publicKeyJWK The public key in JWK format
@@ -405,9 +465,10 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
is Float -> rowMap.putDouble(key, value.toDouble())
is Double -> rowMap.putDouble(key, value)
is String -> rowMap.putString(key, value)
+ // Tagged so the JS client can decode BLOB columns back to bytes.
is ByteArray -> rowMap.putString(
key,
- android.util.Base64.encodeToString(value, android.util.Base64.NO_WRAP),
+ "av-blob-base64:" + android.util.Base64.encodeToString(value, android.util.Base64.NO_WRAP),
)
else -> rowMap.putString(key, value.toString())
}
@@ -1397,6 +1458,11 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
} else {
putNull("error")
}
+ if (result.errorMessage != null) {
+ putString("errorMessage", result.errorMessage)
+ } else {
+ putNull("errorMessage")
+ }
}
withContext(Dispatchers.Main) {
promise.resolve(resultMap)
@@ -1883,6 +1949,7 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
// Reset sync state - set isDirty=false and revision=0 so sync sees server as newer
vaultStore.metadata.setIsDirty(false)
vaultStore.setVaultRevisionNumber(0)
+ vaultStore.clearSyncEngineState()
promise.resolve(null)
} catch (e: Exception) {
@@ -1891,266 +1958,66 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
}
- // MARK: - SRP Functions (via Rust Core UniFFI)
-
- /**
- * Generate a cryptographic salt for SRP.
- * @param promise The promise to resolve with the generated salt (hex string).
- */
- @ReactMethod
- override fun srpGenerateSalt(promise: Promise) {
- try {
- val salt = uniffi.aliasvault_core.srpGenerateSalt()
- promise.resolve(salt)
- } catch (e: Exception) {
- Log.e(TAG, "Error generating SRP salt", e)
- promise.reject("ERR_SRP_GENERATE_SALT", "Failed to generate SRP salt: ${e.message}", e)
- }
- }
-
- /**
- * Derive the SRP private key (x) from credentials.
- * @param salt The salt (hex string).
- * @param identity The identity (username).
- * @param passwordHash The password hash (hex string).
- * @param promise The promise to resolve with the private key (hex string).
- */
- @ReactMethod
- override fun srpDerivePrivateKey(salt: String, identity: String, passwordHash: String, promise: Promise) {
- try {
- val privateKey = uniffi.aliasvault_core.srpDerivePrivateKey(salt, identity, passwordHash)
- promise.resolve(privateKey)
- } catch (e: Exception) {
- Log.e(TAG, "Error deriving SRP private key", e)
- promise.reject("ERR_SRP_DERIVE_PRIVATE_KEY", "Failed to derive SRP private key: ${e.message}", e)
- }
- }
-
- /**
- * Derive the SRP verifier (v) from a private key.
- * @param privateKey The private key (hex string).
- * @param promise The promise to resolve with the verifier (hex string).
- */
- @ReactMethod
- override fun srpDeriveVerifier(privateKey: String, promise: Promise) {
- try {
- val verifier = uniffi.aliasvault_core.srpDeriveVerifier(privateKey)
- promise.resolve(verifier)
- } catch (e: Exception) {
- Log.e(TAG, "Error deriving SRP verifier", e)
- promise.reject("ERR_SRP_DERIVE_VERIFIER", "Failed to derive SRP verifier: ${e.message}", e)
- }
- }
-
- /**
- * Generate client ephemeral values (a, A) for SRP.
- * @param promise The promise to resolve with JSON containing public and secret values.
- */
- @ReactMethod
- override fun srpGenerateEphemeral(promise: Promise) {
- try {
- val ephemeral = uniffi.aliasvault_core.srpGenerateEphemeral()
- val result = Arguments.createMap()
- result.putString("public", ephemeral.public)
- result.putString("secret", ephemeral.secret)
- promise.resolve(result)
- } catch (e: Exception) {
- Log.e(TAG, "Error generating SRP ephemeral", e)
- promise.reject("ERR_SRP_GENERATE_EPHEMERAL", "Failed to generate SRP ephemeral: ${e.message}", e)
- }
- }
-
- /**
- * Derive the SRP session key and proof.
- * @param clientSecret The client secret (a, hex string).
- * @param serverPublic The server public value (B, hex string).
- * @param salt The salt (hex string).
- * @param identity The identity (username).
- * @param privateKey The private key (x, hex string).
- * @param promise The promise to resolve with JSON containing key and proof.
- */
- @ReactMethod
- override fun srpDeriveSession(
- clientSecret: String,
- serverPublic: String,
- salt: String,
- identity: String,
- privateKey: String,
- promise: Promise,
- ) {
- try {
- val session = uniffi.aliasvault_core.srpDeriveSession(
- clientSecret,
- serverPublic,
- salt,
- identity,
- privateKey,
- )
- val result = Arguments.createMap()
- result.putString("key", session.key)
- result.putString("proof", session.proof)
- promise.resolve(result)
- } catch (e: Exception) {
- Log.e(TAG, "Error deriving SRP session", e)
- promise.reject("ERR_SRP_DERIVE_SESSION", "Failed to derive SRP session: ${e.message}", e)
- }
- }
+ // region Client core bridge
/**
- * Pick which of an item's URLs a favicon should be fetched from, and the Logos.Source
- * key it is stored under.
- * @param urls The item's URLs, in the order the item lists them.
- * @param promise Resolves with a JSON string, or null when no URL qualifies.
+ * Call one Rust core function by name with JSON-encoded positional arguments. The client core's Rust
+ * binding (platform/NativeRustCore.ts) routes every call through here.
+ * @param name The uniffi function name in camelCase.
+ * @param argsJson The positional arguments as a JSON array.
+ * @param promise Resolves with the result as JSON text.
*/
@ReactMethod
- override fun selectFaviconTarget(urls: ReadableArray, promise: Promise) {
- try {
- val urlList = (0 until urls.size()).mapNotNull { urls.getString(it) }
- val target = uniffi.aliasvault_core.selectFaviconTarget(urlList)
- if (target == null) {
- promise.resolve(null)
- return
+ override fun rustCall(name: String, argsJson: String, promise: Promise) {
+ CoroutineScope(Dispatchers.Default).launch {
+ try {
+ promise.resolve(RustCoreDispatcher.call(name, argsJson))
+ } catch (e: Exception) {
+ Log.e(TAG, "Rust core call '$name' failed", e)
+ promise.reject("RUST_CORE_ERROR", "Rust core call '$name' failed: ${e.message}", e)
}
-
- val json = JSONObject()
- .put("url", target.url)
- .put("source", target.source)
- promise.resolve(json.toString())
- } catch (e: Exception) {
- Log.e(TAG, "Error selecting favicon target", e)
- promise.reject("ERR_SELECT_FAVICON_TARGET", "Failed to select favicon target: ${e.message}", e)
- }
- }
-
- /**
- * Generate a password or passphrase from a JSON-serialized PasswordSettings object.
- * The "Type" field selects the generator ("basic" or "diceware").
- * @param settingsJson The JSON-serialized password settings.
- * @param promise The promise to resolve with the generated password/passphrase.
- */
- @ReactMethod
- override fun generatePassword(settingsJson: String, promise: Promise) {
- try {
- val password = uniffi.aliasvault_core.generatePassword(settingsJson)
- promise.resolve(password)
- } catch (e: Exception) {
- Log.e(TAG, "Error generating password", e)
- promise.reject("ERR_GENERATE_PASSWORD", "Failed to generate password: ${e.message}", e)
}
}
/**
- * List the bundled Diceware wordlist language codes (first is the default, English).
- * @param promise The promise to resolve with the array of language codes.
- */
- @ReactMethod
- override fun getDicewareLanguages(promise: Promise) {
- try {
- val languages = uniffi.aliasvault_core.getDicewareLanguages()
- val result = Arguments.createArray()
- languages.forEach { result.pushString(it) }
- promise.resolve(result)
- } catch (e: Exception) {
- Log.e(TAG, "Error getting diceware languages", e)
- promise.reject("ERR_GET_DICEWARE_LANGUAGES", "Failed to get diceware languages: ${e.message}", e)
- }
- }
-
- /**
- * Generate a random identity from a JSON-serialized request.
- * @param requestJson The JSON-serialized identity request (language, gender, ageRange).
- * @param promise The promise to resolve with the identity as a JSON string.
- */
- @ReactMethod
- override fun generateIdentity(requestJson: String, promise: Promise) {
- try {
- val identityJson = uniffi.aliasvault_core.generateIdentity(requestJson)
- promise.resolve(identityJson)
- } catch (e: Exception) {
- Log.e(TAG, "Error generating identity", e)
- promise.reject("ERR_GENERATE_IDENTITY", "Failed to generate identity: ${e.message}", e)
- }
- }
-
- /**
- * Generate a username from a JSON-serialized name input (firstName, lastName, birthDate).
- * @param inputJson The JSON-serialized name input.
- * @param promise The promise to resolve with the generated username.
- */
- @ReactMethod
- override fun generateIdentityUsername(inputJson: String, promise: Promise) {
- try {
- val username = uniffi.aliasvault_core.generateIdentityUsername(inputJson)
- promise.resolve(username)
- } catch (e: Exception) {
- Log.e(TAG, "Error generating identity username", e)
- promise.reject("ERR_GENERATE_IDENTITY_USERNAME", "Failed to generate username: ${e.message}", e)
- }
- }
-
- /**
- * Generate an email prefix from a JSON-serialized name input (firstName, lastName, birthDate).
- * @param inputJson The JSON-serialized name input.
- * @param promise The promise to resolve with the generated email prefix.
+ * Store the encrypted vault blob the app produced, so the native store and the autofill service read it.
+ * @param base64EncryptedDb The encrypted vault as base64.
+ * @param promise The promise to resolve.
*/
@ReactMethod
- override fun generateIdentityEmailPrefix(inputJson: String, promise: Promise) {
+ override fun storeEncryptedDatabase(base64EncryptedDb: String, promise: Promise) {
try {
- val emailPrefix = uniffi.aliasvault_core.generateIdentityEmailPrefix(inputJson)
- promise.resolve(emailPrefix)
+ vaultStore.storeEncryptedDatabase(base64EncryptedDb)
+ promise.resolve(null)
} catch (e: Exception) {
- Log.e(TAG, "Error generating identity email prefix", e)
- promise.reject("ERR_GENERATE_IDENTITY_EMAIL_PREFIX", "Failed to generate email prefix: ${e.message}", e)
+ Log.e(TAG, "Error storing encrypted database", e)
+ promise.reject("ERR_STORE_DATABASE", "Failed to store encrypted database: ${e.message}", e)
}
}
/**
- * Generate a random alphanumeric email prefix that is not based on any identity.
- * @param length The desired prefix length.
- * @param promise The promise to resolve with the generated prefix.
+ * The vault encryption key as base64, for the app to open the vault after a biometric or PIN unlock.
+ * @param promise Resolves with the key, rejects with the native error code when the store holds none.
*/
@ReactMethod
- override fun generateRandomEmailPrefix(length: Double, promise: Promise) {
- try {
- val prefix = uniffi.aliasvault_core.generateRandomEmailPrefix(length.toUInt())
- promise.resolve(prefix)
- } catch (e: Exception) {
- Log.e(TAG, "Error generating random email prefix", e)
- promise.reject("ERR_GENERATE_RANDOM_EMAIL_PREFIX", "Failed to generate random email prefix: ${e.message}", e)
- }
- }
+ override fun getEncryptionKey(promise: Promise) {
+ vaultStore.getEncryptionKey(
+ object : CryptoOperationCallback {
+ override fun onSuccess(result: String) {
+ promise.resolve(result)
+ }
- /**
- * List the bundled identity dictionary language codes.
- * @param promise The promise to resolve with the array of language codes.
- */
- @ReactMethod
- override fun getIdentityLanguages(promise: Promise) {
- try {
- val languages = uniffi.aliasvault_core.getIdentityLanguages()
- val result = Arguments.createArray()
- languages.forEach { result.pushString(it) }
- promise.resolve(result)
- } catch (e: Exception) {
- Log.e(TAG, "Error getting identity languages", e)
- promise.reject("ERR_GET_IDENTITY_LANGUAGES", "Failed to get identity languages: ${e.message}", e)
- }
+ override fun onError(e: Exception) {
+ Log.e(TAG, "Error getting encryption key", e)
+ if (e is AppError) {
+ promise.reject(e.code, e.message, e)
+ } else {
+ promise.reject("E-001", "Failed to get encryption key: ${e.message}", e)
+ }
+ }
+ },
+ )
}
- /**
- * List the identity age range option values ("random" plus 5-year ranges).
- * @param promise The promise to resolve with the array of age range values.
- */
- @ReactMethod
- override fun getIdentityAgeRanges(promise: Promise) {
- try {
- val ageRanges = uniffi.aliasvault_core.getIdentityAgeRanges()
- val result = Arguments.createArray()
- ageRanges.forEach { result.pushString(it) }
- promise.resolve(result)
- } catch (e: Exception) {
- Log.e(TAG, "Error getting identity age ranges", e)
- promise.reject("ERR_GET_IDENTITY_AGE_RANGES", "Failed to get identity age ranges: ${e.message}", e)
- }
- }
+ // endregion
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt
new file mode 100644
index 000000000..2302f0dfa
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt
@@ -0,0 +1,163 @@
+package net.aliasvault.app.nativevaultmanager
+
+import android.util.Base64
+import org.json.JSONArray
+import org.json.JSONObject
+import uniffi.aliasvault_core.argon2DeriveKey
+import uniffi.aliasvault_core.decodeEmailSource
+import uniffi.aliasvault_core.extractDomain
+import uniffi.aliasvault_core.extractEmailAttachment
+import uniffi.aliasvault_core.extractRootDomain
+import uniffi.aliasvault_core.filterCredentialsJson
+import uniffi.aliasvault_core.generateIdentity
+import uniffi.aliasvault_core.generateIdentityEmailPrefix
+import uniffi.aliasvault_core.generateIdentityUsername
+import uniffi.aliasvault_core.generatePassword
+import uniffi.aliasvault_core.generateRandomEmailPrefix
+import uniffi.aliasvault_core.getDicewareLanguages
+import uniffi.aliasvault_core.getIdentityAgeRanges
+import uniffi.aliasvault_core.getIdentityLanguages
+import uniffi.aliasvault_core.getPruneTableQueries
+import uniffi.aliasvault_core.getSyncableTableNames
+import uniffi.aliasvault_core.mergeCanonicalJson
+import uniffi.aliasvault_core.parseEmailSource
+import uniffi.aliasvault_core.pruneVaultJson
+import uniffi.aliasvault_core.selectFaviconTarget
+import uniffi.aliasvault_core.srpDerivePrivateKey
+import uniffi.aliasvault_core.srpDeriveSession
+import uniffi.aliasvault_core.srpDeriveVerifier
+import uniffi.aliasvault_core.srpGenerateEphemeral
+import uniffi.aliasvault_core.srpGenerateSalt
+import uniffi.aliasvault_core.vaultCodecBucketLayout
+import uniffi.aliasvault_core.vaultCodecCanonicalizeFromSqlite
+import uniffi.aliasvault_core.vaultCodecComputeCiphertextHash
+import uniffi.aliasvault_core.vaultCodecComputeContentFingerprint
+import uniffi.aliasvault_core.vaultCodecExtractBuckets
+import uniffi.aliasvault_core.vaultCodecExtractEncryptionKeyForPublicKey
+import uniffi.aliasvault_core.vaultCodecGenerateManifestSalt
+import uniffi.aliasvault_core.vaultCodecLogoContentHash
+import uniffi.aliasvault_core.vaultCodecLogoIdFor
+import uniffi.aliasvault_core.vaultCodecLogoIdForSource
+import uniffi.aliasvault_core.vaultCodecMaterializeAsSqlite
+import uniffi.aliasvault_core.vaultCodecOverflowTable
+import uniffi.aliasvault_core.vaultCodecPackPayload
+import uniffi.aliasvault_core.vaultCodecUnpackPayload
+import uniffi.aliasvault_core.vaultCodecValidateDataBucket
+import uniffi.aliasvault_core.vaultCodecValidateManifest
+import uniffi.aliasvault_core.vaultSharingPartitionManifestAccess
+import uniffi.aliasvault_core.vaultSharingResolveManifestWriteSet
+
+/**
+ * Routes `rustCall` invocations from React Native onto the uniffi bindings: one case per exported core
+ * function and no logic. Arguments arrive as a JSON array (bytes as base64); results leave as JSON text.
+ * Functions that already return JSON text pass it through unchanged, everything else is JSON-encoded here.
+ */
+@Suppress("TooManyFunctions", "LongMethod", "CyclomaticComplexMethod")
+object RustCoreDispatcher {
+ /**
+ * Dispatch one call.
+ * @param name The uniffi function name in camelCase.
+ * @param argsJson The positional arguments as a JSON array.
+ * @return The result as JSON text.
+ */
+ fun call(name: String, argsJson: String): String {
+ val args = Args(JSONArray(argsJson))
+
+ return when (name) {
+ "extractDomain" -> json(extractDomain(args.string(0)))
+ "extractRootDomain" -> json(extractRootDomain(args.string(0)))
+ "selectFaviconTarget" -> {
+ val target = selectFaviconTarget(args.strings(0)) ?: return "null"
+ JSONObject().put("url", target.url).put("source", target.source).toString()
+ }
+ "filterCredentialsJson" -> filterCredentialsJson(args.string(0))
+
+ "generatePassword" -> json(generatePassword(args.string(0)))
+ "getDicewareLanguages" -> json(getDicewareLanguages())
+ "generateIdentity" -> json(generateIdentity(args.string(0)))
+ "generateIdentityUsername" -> json(generateIdentityUsername(args.string(0)))
+ "generateIdentityEmailPrefix" -> json(generateIdentityEmailPrefix(args.string(0)))
+ "generateRandomEmailPrefix" -> json(generateRandomEmailPrefix(args.uint(0)))
+ "getIdentityLanguages" -> json(getIdentityLanguages())
+ "getIdentityAgeRanges" -> json(getIdentityAgeRanges())
+
+ "parseEmailSource" -> parseEmailSource(args.bytes(0))
+ "decodeEmailSource" -> json(decodeEmailSource(args.bytes(0)))
+ "extractEmailAttachment" -> json(extractEmailAttachment(args.bytes(0), args.uint(1), args.optionalBytes(2)))
+
+ "argon2DeriveKey" -> json(argon2DeriveKey(args.string(0), args.string(1), args.string(2)))
+
+ "srpGenerateSalt" -> json(srpGenerateSalt())
+ "srpDerivePrivateKey" -> json(srpDerivePrivateKey(args.string(0), args.string(1), args.string(2)))
+ "srpDeriveVerifier" -> json(srpDeriveVerifier(args.string(0)))
+ "srpGenerateEphemeral" -> {
+ val ephemeral = srpGenerateEphemeral()
+ JSONObject().put("public", ephemeral.public).put("secret", ephemeral.secret).toString()
+ }
+ "srpDeriveSession" -> {
+ val session = srpDeriveSession(args.string(0), args.string(1), args.string(2), args.string(3), args.string(4))
+ JSONObject().put("proof", session.proof).put("key", session.key).toString()
+ }
+
+ "getSyncableTableNames" -> json(getSyncableTableNames())
+ "mergeCanonicalJson" -> mergeCanonicalJson(args.string(0))
+ "pruneVaultJson" -> pruneVaultJson(args.string(0))
+ "getPruneTableQueries" -> {
+ val queries = JSONArray()
+ getPruneTableQueries().forEach { queries.put(JSONObject().put("name", it.name).put("query", it.query)) }
+ queries.toString()
+ }
+
+ "vaultCodecCanonicalizeFromSqlite" -> vaultCodecCanonicalizeFromSqlite(args.string(0))
+ "vaultCodecMaterializeAsSqlite" -> vaultCodecMaterializeAsSqlite(args.string(0))
+ "vaultCodecExtractBuckets" -> vaultCodecExtractBuckets(args.string(0))
+ "vaultCodecBucketLayout" -> vaultCodecBucketLayout()
+ "vaultCodecOverflowTable" -> json(vaultCodecOverflowTable())
+ "vaultCodecGenerateManifestSalt" -> json(vaultCodecGenerateManifestSalt())
+ "vaultCodecLogoIdForSource" -> json(vaultCodecLogoIdForSource(args.string(0), args.string(1)))
+ "vaultCodecLogoIdFor" -> json(vaultCodecLogoIdFor(args.string(0), args.string(1), args.string(2)))
+ "vaultCodecLogoContentHash" -> json(vaultCodecLogoContentHash(args.bytes(0)))
+ "vaultCodecPackPayload" -> json(vaultCodecPackPayload(args.string(0)))
+ "vaultCodecUnpackPayload" -> json(vaultCodecUnpackPayload(args.bytes(0)))
+ "vaultCodecValidateManifest" -> vaultCodecValidateManifest(args.string(0))
+ "vaultCodecValidateDataBucket" -> vaultCodecValidateDataBucket(args.string(0))
+ "vaultCodecComputeCiphertextHash" -> json(vaultCodecComputeCiphertextHash(args.string(0)))
+ "vaultCodecComputeContentFingerprint" -> json(vaultCodecComputeContentFingerprint(args.string(0)))
+ "vaultCodecExtractEncryptionKeyForPublicKey" -> vaultCodecExtractEncryptionKeyForPublicKey(args.string(0), args.string(1))
+
+ "vaultSharingResolveManifestWriteSet" -> vaultSharingResolveManifestWriteSet(args.string(0))
+ "vaultSharingPartitionManifestAccess" -> vaultSharingPartitionManifestAccess(args.string(0))
+
+ else -> throw IllegalArgumentException("Unknown Rust core function '$name'")
+ }
+ }
+
+ /**
+ * The positional arguments of one call.
+ */
+ private class Args(private val values: JSONArray) {
+ fun string(index: Int): String = values.getString(index)
+
+ fun optionalString(index: Int): String? = if (index < values.length() && !values.isNull(index)) values.getString(index) else null
+
+ fun uint(index: Int): UInt = values.getInt(index).toUInt()
+
+ fun strings(index: Int): List<String> {
+ val array = values.getJSONArray(index)
+ return (0 until array.length()).map { array.getString(it) }
+ }
+
+ fun bytes(index: Int): ByteArray = Base64.decode(string(index), Base64.NO_WRAP)
+
+ fun optionalBytes(index: Int): ByteArray? = optionalString(index)?.let { Base64.decode(it, Base64.NO_WRAP) }
+ }
+
+ /** JSON-encode a plain string. */
+ private fun json(value: String): String = JSONObject.quote(value)
+
+ /** JSON-encode a list of strings. */
+ private fun json(values: List<String>): String = JSONArray(values).toString()
+
+ /** JSON-encode raw bytes as a base64 string. */
+ private fun json(bytes: ByteArray): String = json(Base64.encodeToString(bytes, Base64.NO_WRAP))
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultData.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultData.kt
index 8d932efd2..dfc83dc08 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultData.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultData.kt
@@ -32,6 +32,7 @@ enum class SyncAction(val value: String) {
* @property newRevision The vault revision after the sync.
* @property wasOffline Whether the sync ran offline.
* @property error The error code, if any.
+ * @property errorMessage The error message, if any.
*/
data class VaultSyncResult(
val success: Boolean,
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
index 9bf252a6a..546ce652e 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
@@ -74,7 +74,7 @@ class VaultSync(
private fun driverError(e: Exception): AppError = e as? AppError ?: AppError.SyncEngineFailed(e.toString(), e)
/**
- * Resolve the vault key right after login: the account's key chain is opened with the password-derived key and the VEK
+ * Resolve the vault key right after login: the account's key chain is opened with the password-derived key and the VEK
* is stored as the session key; a legacy account keeps the derived key. Every sync assumes the key this stored. Returns the stored key (base64).
*/
@Suppress("TooGenericExceptionCaught")
diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.ts
new file mode 100644
index 000000000..8d79c7ce1
--- /dev/null
+++ b/apps/mobile-app/platform/NativeRustCore.ts
@@ -0,0 +1,91 @@
+import { Buffer } from 'buffer';
+
+import type { IRustCore } from '@aliasvault/client/rust/RustCoreBinding';
+
+import NativeVaultManager from '@/specs/NativeVaultManager';
+
+/**
+ * Call one Rust core function through the native dispatcher: positional arguments travel as a JSON array, the result
+ * comes back as JSON text.
+ */
+async function call<T>(name: string, ...args: unknown[]): Promise<T> {
+ return JSON.parse(await NativeVaultManager.rustCall(name, JSON.stringify(args))) as T;
+}
+
+/**
+ * Call a function that returns bytes, which the dispatcher sends as a base64 string.
+ */
+async function callForBytes(name: string, ...args: unknown[]): Promise<Uint8Array> {
+ return new Uint8Array(Buffer.from(await call<string>(name, ...args), 'base64'));
+}
+
+/**
+ * Encode bytes as the base64 string the dispatcher expects for a byte argument.
+ */
+function base64(bytes: Uint8Array): string {
+ return Buffer.from(bytes).toString('base64');
+}
+
+/*
+ * The client core's Rust binding on mobile: the uniffi Swift/Kotlin bindings, reached through the one generic
+ * `NativeVaultManager.rustCall` method. Swift and Kotlin hold a case per function and no logic. Functions that take a
+ * document receive it as a single JSON argument, matching their `*Json` uniffi exports; vault codec documents already
+ * carry byte columns as `{ __b64 }`, so they serialize as is. The vault sync engine is driven natively on mobile, so it
+ * has no JavaScript session.
+ */
+export const nativeRustCore: IRustCore = {
+ init: async (): Promise<void> => {},
+
+ extractDomain: (url) => call('extractDomain', url),
+ extractRootDomain: (domain) => call('extractRootDomain', domain),
+ selectFaviconTarget: (urls) => call('selectFaviconTarget', urls),
+ filterCredentials: (input) => call('filterCredentialsJson', JSON.stringify(input)),
+
+ generatePassword: (settingsJson) => call('generatePassword', settingsJson),
+ getDicewareLanguages: () => call('getDicewareLanguages'),
+ generateIdentity: (requestJson) => call('generateIdentity', requestJson),
+ generateIdentityUsername: (inputJson) => call('generateIdentityUsername', inputJson),
+ generateIdentityEmailPrefix: (inputJson) => call('generateIdentityEmailPrefix', inputJson),
+ generateRandomEmailPrefix: (length) => call('generateRandomEmailPrefix', length),
+ getIdentityLanguages: () => call('getIdentityLanguages'),
+ getIdentityAgeRanges: () => call('getIdentityAgeRanges'),
+
+ parseEmailSource: (source) => call('parseEmailSource', base64(source)),
+ decodeEmailSource: (source) => callForBytes('decodeEmailSource', base64(source)),
+ extractEmailAttachment: (source, index, detachedBody) => callForBytes('extractEmailAttachment', base64(source), index, detachedBody ? base64(detachedBody) : null),
+
+ argon2DeriveKey: (password, salt, encryptionSettings) => callForBytes('argon2DeriveKey', password, salt, encryptionSettings),
+
+ srpGenerateSalt: () => call('srpGenerateSalt'),
+ srpDerivePrivateKey: (salt, identity, passwordHash) => call('srpDerivePrivateKey', salt, identity, passwordHash),
+ srpDeriveVerifier: (privateKey) => call('srpDeriveVerifier', privateKey),
+ srpGenerateEphemeral: () => call('srpGenerateEphemeral'),
+ srpDeriveSession: (clientSecret, serverPublic, salt, identity, privateKey) => call('srpDeriveSession', clientSecret, serverPublic, salt, identity, privateKey),
+
+ getSyncableTableNames: () => call('getSyncableTableNames'),
+ mergeCanonical: (input) => call('mergeCanonicalJson', JSON.stringify(input)),
+ pruneVault: (input) => call('pruneVaultJson', JSON.stringify(input)),
+ getPruneTableQueries: () => call('getPruneTableQueries'),
+
+ vaultCodecCanonicalizeFromSqlite: (input) => call('vaultCodecCanonicalizeFromSqlite', JSON.stringify(input)),
+ vaultCodecMaterializeAsSqlite: (input) => call('vaultCodecMaterializeAsSqlite', JSON.stringify(input)),
+ vaultCodecExtractBuckets: (input) => call('vaultCodecExtractBuckets', JSON.stringify(input)),
+ vaultCodecBucketLayout: () => call('vaultCodecBucketLayout'),
+ vaultCodecOverflowTable: () => call('vaultCodecOverflowTable'),
+ vaultCodecGenerateManifestSalt: () => call('vaultCodecGenerateManifestSalt'),
+ vaultCodecLogoIdForSource: (manifestId, source) => call('vaultCodecLogoIdForSource', manifestId, source),
+ vaultCodecLogoIdFor: (manifestId, kind, source) => call('vaultCodecLogoIdFor', manifestId, kind, source),
+ vaultCodecLogoContentHash: (bytes) => call('vaultCodecLogoContentHash', base64(bytes)),
+ vaultCodecPackPayload: (payloadJson) => callForBytes('vaultCodecPackPayload', payloadJson),
+ vaultCodecUnpackPayload: (plainBytes) => call('vaultCodecUnpackPayload', base64(plainBytes)),
+ vaultCodecValidateManifest: (manifest) => call('vaultCodecValidateManifest', JSON.stringify(manifest)),
+ vaultCodecValidateDataBucket: (bucket) => call('vaultCodecValidateDataBucket', JSON.stringify(bucket)),
+ vaultCodecComputeCiphertextHash: (base64Ciphertext) => call('vaultCodecComputeCiphertextHash', base64Ciphertext),
+ vaultCodecComputeContentFingerprint: (payloadJson) => call('vaultCodecComputeContentFingerprint', payloadJson),
+ vaultCodecExtractEncryptionKeyForPublicKey: (manifest, publicKey) => call('vaultCodecExtractEncryptionKeyForPublicKey', JSON.stringify(manifest), publicKey),
+
+ vaultSharingResolveManifestWriteSet: (input) => call('vaultSharingResolveManifestWriteSet', JSON.stringify(input)),
+ vaultSharingPartitionManifestAccess: (input) => call('vaultSharingPartitionManifestAccess', JSON.stringify(input)),
+
+ createVaultSyncSession: () => Promise.reject(new Error('The vault sync engine is driven natively on mobile and has no JavaScript session.')),
+};
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index c0d6fa10a..32f086704 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -25,8 +25,20 @@ export interface Spec extends TurboModule {
clearSession(): Promise<void>; // Clears session only, preserves vault for potential RPO recovery
clearVault(): Promise<void>; // Clears everything including vault data
+ // Rust core dispatch. The client core's Rust binding routes every call through here: `name` is the uniffi
+ // function name in camelCase, `argsJson` a JSON array of its positional arguments (bytes as base64), and the
+ // result is JSON text. Swift/Kotlin hold one case per function and no logic; see platform/NativeRustCore.ts.
+ rustCall(name: string, argsJson: string): Promise<string>;
+
+ // The vault encryption key as base64, for the app to decrypt the vault after a biometric or PIN unlock. Throws
+ // when the native store holds no key (locked); may prompt for biometrics when the key lives in the keychain.
+ getEncryptionKey(): Promise<string>;
+
+ // Store the encrypted vault blob for persistence and which is also accessed by the native autofill extensions.
+ storeEncryptedDatabase(base64EncryptedDb: string): Promise<void>;
+
// Vault sync
- syncVaultWithServer(): Promise<{ success: boolean; action: 'uploaded' | 'downloaded' | 'merged' | 'already_in_sync' | 'error'; newRevision: number; wasOffline: boolean; error: string | null }>;
+ syncVaultWithServer(): Promise<{ success: boolean; action: 'uploaded' | 'downloaded' | 'merged' | 'already_in_sync' | 'error'; newRevision: number; wasOffline: boolean; error: string | null; errorMessage: string | null }>;
// Quick check if sync is needed
checkSyncStatus(): Promise<{ success: boolean; hasNewerVault: boolean; hasDirtyChanges: boolean; isOffline: boolean; requiresLogout: boolean; errorKey: string | null }>;
@@ -36,7 +48,7 @@ export interface Spec extends TurboModule {
markVaultClean(mutationSeqAtStart: number, newServerRevision: number): Promise<boolean>;
clearEncryptedVaultForFreshDownload(): Promise<void>;
- // Vault SQL operations
+ // Vault SQL operations. executeQuery returns BLOB columns as base64 behind an "av-blob-base64:" prefix.
executeQuery(query: string, params: (string | number | null)[]): Promise<string[]>;
executeUpdate(query: string, params:(string | number | null)[]): Promise<number>;
executeRaw(query: string): Promise<void>;
@@ -57,6 +69,10 @@ export interface Spec extends TurboModule {
storeEncryptionKey(base64EncryptionKey: string): Promise<void>;
storeEncryptionKeyDerivationParams(keyDerivationParams: string): Promise<void>;
getEncryptionKeyDerivationParams(): Promise<string | null>;
+ storeAccountKeyChain(chainJson: string | null): Promise<void>;
+ getAccountKeyChain(): Promise<string | null>;
+ resolveVaultKey(base64DerivedKey: string): Promise<string>;
+ getPersonalManifestId(): Promise<string | null>;
hasEncryptedDatabase(): Promise<boolean>;
getEncryptedDatabase(): Promise<string | null>;
@@ -148,52 +164,6 @@ export interface Spec extends TurboModule {
requestAppReview(): Promise<boolean>;
// The install date as a unix timestamp in milliseconds, or 0 when it cannot be determined.
getAppInstallDate(): Promise<number>;
-
- // Favicon URL handling and selection.
- selectFaviconTarget(urls: string[]): Promise<string | null>;
-
- // Password generator (uses the native Rust core, shared with the other AliasVault clients)
- // Generate a password or passphrase from a JSON-serialized PasswordSettings object.
- generatePassword(settingsJson: string): Promise<string>;
- // List the bundled Diceware wordlist language codes (first is the default, English).
- getDicewareLanguages(): Promise<string[]>;
-
- // Identity generator (uses the native Rust core, shared with the other AliasVault clients)
- // Generate a random identity from a JSON-serialized request
- // (e.g. {"language":"en","gender":"random","ageRange":"21-25"}).
- // Returns the identity as a JSON string with camelCase fields.
- generateIdentity(requestJson: string): Promise<string>;
- // Generate a username from a JSON-serialized name input ({"firstName","lastName","birthDate"}).
- generateIdentityUsername(inputJson: string): Promise<string>;
- // Generate an email prefix from a JSON-serialized name input ({"firstName","lastName","birthDate"}).
- generateIdentityEmailPrefix(inputJson: string): Promise<string>;
- // Generate a random alphanumeric email prefix that is not based on any identity.
- generateRandomEmailPrefix(length: number): Promise<string>;
- // List the bundled identity dictionary language codes.
- getIdentityLanguages(): Promise<string[]>;
- // List the identity age range option values ("random" plus 5-year ranges).
- getIdentityAgeRanges(): Promise<string[]>;
-
- // SRP (Secure Remote Password) operations
- // These methods use the native Rust SRP implementation for secure authentication.
- // All hex values are uppercase strings.
-
- // Generate a 32-byte random salt as uppercase hex string
- srpGenerateSalt(): Promise<string>;
-
- // Derive SRP private key: x = H(salt | H(identity | ":" | passwordHash))
- // passwordHash should be uppercase hex string (from Argon2id derivation)
- srpDerivePrivateKey(salt: string, identity: string, passwordHash: string): Promise<string>;
-
- // Derive SRP verifier: v = g^x mod N (for registration)
- srpDeriveVerifier(privateKey: string): Promise<string>;
-
- // Generate client ephemeral key pair (public A and secret a)
- srpGenerateEphemeral(): Promise<{public: string; secret: string}>;
-
- // Derive client session from server response
- // Returns proof (M1) and shared key (K) as uppercase hex strings
- srpDeriveSession(clientSecret: string, serverPublic: string, salt: string, identity: string, privateKey: string): Promise<{proof: string; key: string}>;
}
export default TurboModuleRegistry.getEnforcing<Spec>('NativeVaultManager');