Skip to content

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

Refactor Kotlin to use Item structure methods instead of deprecated Credential (#1404)

Leendert de Borst7eb37160db37
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillService.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillService.kt
index e153bd03a..59ac26cda 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillService.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillService.kt
@@ -1,9 +1,9 @@
/**
* AliasVault Autofill Service Implementation
*
- * This service implements the Android Autofill framework to provide AliasVault credentials
+ * This service implements the Android Autofill framework to provide AliasVault items
* to forms. It identifies username and password fields in apps and websites,
- * then offers stored credentials from AliasVault.
+ * then offers stored items from AliasVault.
*
*/
package net.aliasvault.app.autofill
@@ -29,11 +29,11 @@ import net.aliasvault.app.R
import net.aliasvault.app.autofill.models.FieldType
import net.aliasvault.app.autofill.utils.FieldFinder
import net.aliasvault.app.autofill.utils.ImageUtils
-import net.aliasvault.app.autofill.utils.RustCredentialMatcher
+import net.aliasvault.app.autofill.utils.RustItemMatcher
import net.aliasvault.app.utils.ItemTypeIcon
import net.aliasvault.app.vaultstore.VaultStore
-import net.aliasvault.app.vaultstore.interfaces.CredentialOperationCallback
-import net.aliasvault.app.vaultstore.models.Credential
+import net.aliasvault.app.vaultstore.interfaces.ItemOperationCallback
+import net.aliasvault.app.vaultstore.models.Item
/**
* The AutofillService class.
@@ -118,7 +118,7 @@ class AutofillService : AutofillService() {
// In a full implementation, you would:
// 1. Extract the username/password from the SaveRequest
// 2. Launch an activity to let the user confirm saving
- // 3. Save the credential using the VaultStore
+ // 3. Save the item using the VaultStore
// For now, just acknowledge the request
callback.onSuccess()
@@ -138,37 +138,37 @@ class AutofillService : AutofillService() {
val store = VaultStore.getExistingInstance()
if (store != null) {
- // We have an existing instance, try to get credentials
- if (store.tryGetAllCredentials(object : CredentialOperationCallback {
- override fun onSuccess(result: List<Credential>) {
+ // We have an existing instance, try to get items
+ if (store.tryGetAllItems(object : ItemOperationCallback {
+ override fun onSuccess(result: List<Item>) {
try {
if (result.isEmpty()) {
- // No credentials available
- Log.d(TAG, "No credentials available")
+ // No items available
+ Log.d(TAG, "No items available")
callback(null)
return
}
- // Filter credentials based on app/website info
+ // Filter items based on app/website info
val filteredByApp = if (appInfo != null) {
- RustCredentialMatcher.filterCredentialsByAppInfo(result, appInfo)
+ RustItemMatcher.filterItemsByAppInfo(result, appInfo)
} else {
result
}
- // Further filter to only include credentials with autofillable data.
- // This prevents from showing non-autofillable credentials like passkeys.
- val filteredCredentials = filteredByApp.filter { credential ->
- val hasUsername = !credential.username.isNullOrEmpty()
- val hasEmail = credential.alias?.email?.isNotEmpty() == true
- val hasPassword = !credential.password?.value.isNullOrEmpty()
+ // Further filter to only include items with autofillable data.
+ // This prevents from showing non-autofillable items like passkeys.
+ val filteredItems = filteredByApp.filter { item ->
+ val hasUsername = !item.username.isNullOrEmpty()
+ val hasEmail = !item.email.isNullOrEmpty()
+ val hasPassword = !item.password.isNullOrEmpty()
(hasUsername || hasEmail) && hasPassword
}
Log.d(
TAG,
- "Credentials after filtering: app matches=${filteredByApp.size}, with data=${filteredCredentials.size}",
+ "Items after filtering: app matches=${filteredByApp.size}, with data=${filteredItems.size}",
)
val responseBuilder = FillResponse.Builder()
@@ -181,17 +181,17 @@ class AutofillService : AutofillService() {
}
// If there are no results, return "no matches" placeholder option.
- if (filteredCredentials.isEmpty()) {
+ if (filteredItems.isEmpty()) {
Log.d(
TAG,
- "No credentials found for this app, showing 'no matches' option",
+ "No items found for this app, showing 'no matches' option",
)
responseBuilder.addDataset(createNoMatchesDataset(fieldFinder))
} else {
// If there are matches, add them to the dataset
- for (credential in filteredCredentials) {
+ for (item in filteredItems) {
responseBuilder.addDataset(
- createCredentialDataset(fieldFinder, credential),
+ createItemDataset(fieldFinder, item),
)
}
@@ -203,7 +203,7 @@ class AutofillService : AutofillService() {
callback(responseBuilder.build())
} catch (e: Exception) {
- Log.e(TAG, "Error parsing credentials", e)
+ Log.e(TAG, "Error parsing items", e)
// Show "Failed to retrieve, open app" option instead of failing
val responseBuilder = FillResponse.Builder()
val sharedPreferences = getSharedPreferences("AliasVaultPrefs", android.content.Context.MODE_PRIVATE)
@@ -217,7 +217,7 @@ class AutofillService : AutofillService() {
}
override fun onError(e: Exception) {
- Log.e(TAG, "Error getting credentials", e)
+ Log.e(TAG, "Error getting items", e)
// Show "Failed to retrieve, open app" option instead of failing
val responseBuilder = FillResponse.Builder()
val sharedPreferences = getSharedPreferences("AliasVaultPrefs", android.content.Context.MODE_PRIVATE)
@@ -245,112 +245,94 @@ class AutofillService : AutofillService() {
}
/**
- * Create a dataset from a credential.
+ * Create a dataset from an item.
* @param fieldFinder The field finder
- * @param credential The credential
+ * @param item The item
* @return The dataset
*/
- private fun createCredentialDataset(fieldFinder: FieldFinder, credential: Credential): Dataset {
+ private fun createItemDataset(fieldFinder: FieldFinder, item: Item): Dataset {
// Always use icon layout (will show logo or placeholder icon)
val layoutId = R.layout.autofill_dataset_item_icon
- // Create presentation for this credential using our custom layout
+ // Create presentation for this item using our custom layout
val presentation = RemoteViews(packageName, layoutId)
val dataSetBuilder = Dataset.Builder(presentation)
// Add autofill values for all fields
- var presentationDisplayValue = credential.service.name
+ var presentationDisplayValue = item.name
var hasSetValue = false
for (field in fieldFinder.autofillableFields) {
val fieldType = field.second
when (fieldType) {
FieldType.PASSWORD -> {
- if (credential.password != null) {
+ if (!item.password.isNullOrEmpty()) {
dataSetBuilder.setValue(
field.first,
- AutofillValue.forText(credential.password.value as CharSequence),
+ AutofillValue.forText(item.password as CharSequence),
)
hasSetValue = true
}
}
FieldType.EMAIL -> {
- if (credential.alias?.email != null && credential.alias.email.isNotEmpty()) {
+ if (!item.email.isNullOrEmpty()) {
dataSetBuilder.setValue(
field.first,
- AutofillValue.forText(credential.alias.email),
+ AutofillValue.forText(item.email),
)
hasSetValue = true
- if (credential.alias.email.isNotEmpty()) {
- presentationDisplayValue += " (${credential.alias.email})"
- } else if (!credential.username.isNullOrEmpty()) {
- presentationDisplayValue += " (${credential.username})"
- }
- } else if (!credential.username.isNullOrEmpty()) {
+ presentationDisplayValue += " (${item.email})"
+ } else if (!item.username.isNullOrEmpty()) {
dataSetBuilder.setValue(
field.first,
- AutofillValue.forText(credential.username),
+ AutofillValue.forText(item.username),
)
hasSetValue = true
- if (credential.username.isNotEmpty()) {
- presentationDisplayValue += " (${credential.username})"
- } else if ((credential.alias?.email ?: "").isNotEmpty()) {
- presentationDisplayValue += " (${credential.alias?.email})"
- }
+ presentationDisplayValue += " (${item.username})"
}
}
FieldType.USERNAME -> {
- if (!credential.username.isNullOrEmpty()) {
+ if (!item.username.isNullOrEmpty()) {
dataSetBuilder.setValue(
field.first,
- AutofillValue.forText(credential.username),
+ AutofillValue.forText(item.username),
)
hasSetValue = true
- if (credential.username.isNotEmpty()) {
- presentationDisplayValue += " (${credential.username})"
- } else if ((credential.alias?.email ?: "").isNotEmpty()) {
- presentationDisplayValue += " (${credential.alias?.email})"
- }
- } else if (credential.alias?.email != null && credential.alias.email.isNotEmpty()) {
+ presentationDisplayValue += " (${item.username})"
+ } else if (!item.email.isNullOrEmpty()) {
dataSetBuilder.setValue(
field.first,
- AutofillValue.forText(credential.alias.email),
+ AutofillValue.forText(item.email),
)
hasSetValue = true
- if (credential.alias.email.isNotEmpty()) {
- presentationDisplayValue += " (${credential.alias?.email})"
- }
+ presentationDisplayValue += " (${item.email})"
}
}
else -> {
// For unknown field types, try both email and username
- if (credential.alias?.email != null && credential.alias.email.isNotEmpty()) {
+ if (!item.email.isNullOrEmpty()) {
dataSetBuilder.setValue(
field.first,
- AutofillValue.forText(credential.alias.email),
+ AutofillValue.forText(item.email),
)
hasSetValue = true
- if (credential.alias.email.isNotEmpty()) {
- presentationDisplayValue += " (${credential.alias.email})"
- }
- } else if (!credential.username.isNullOrEmpty()) {
+ presentationDisplayValue += " (${item.email})"
+ } else if (!item.username.isNullOrEmpty()) {
dataSetBuilder.setValue(
field.first,
- AutofillValue.forText(credential.username),
+ AutofillValue.forText(item.username),
)
hasSetValue = true
- if (credential.username.isNotEmpty()) {
- presentationDisplayValue += " (${credential.username})"
- }
+ presentationDisplayValue += " (${item.username})"
}
}
}
}
- // If no value was set, this shouldn't happen now since we filter credentials
+ // If no value was set, this shouldn't happen now since we filter items
// but keep as safety measure
if (!hasSetValue && fieldFinder.autofillableFields.isNotEmpty()) {
- Log.w(TAG, "Credential ${credential.service.name} has no autofillable data - this should have been filtered")
+ Log.w(TAG, "Item ${item.name} has no autofillable data - this should have been filtered")
dataSetBuilder.setValue(
fieldFinder.autofillableFields.first().first,
AutofillValue.forText(""),
@@ -364,7 +346,7 @@ class AutofillService : AutofillService() {
)
// Set the logo if available, otherwise use placeholder icon
- val logoBytes = credential.service.logo
+ val logoBytes = item.logo
val bitmap = if (logoBytes != null) {
ImageUtils.bytesToBitmap(logoBytes)
} else {
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustCredentialMatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt
similarity index 53%
rename from apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustCredentialMatcher.kt
rename to apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt
index 96dc236c0..66e77f40f 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustCredentialMatcher.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt
@@ -2,15 +2,15 @@ package net.aliasvault.app.autofill.utils
import android.util.Log
import net.aliasvault.app.rustcore.JnaInitializer
-import net.aliasvault.app.vaultstore.models.Credential
+import net.aliasvault.app.vaultstore.models.Item
import org.json.JSONArray
import org.json.JSONObject
/**
- * Wrapper for the Rust credential matcher using UniFFI bindings.
+ * Wrapper for the Rust item matcher using UniFFI bindings.
*/
-object RustCredentialMatcher {
- private const val TAG = "RustCredentialMatcher"
+object RustItemMatcher {
+ private const val TAG = "RustItemMatcher"
init {
// Ensure JNA is initialized before any UniFFI calls
@@ -18,36 +18,36 @@ object RustCredentialMatcher {
}
/**
- * Filter credentials based on app/website info using the Rust core credential matcher.
+ * Filter items based on app/website info using the Rust core credential matcher.
*
- * @param credentials List of credentials to filter
+ * @param items List of items to filter
* @param searchText Search term (app package name, URL, or text)
- * @return Filtered list of credentials
+ * @return Filtered list of items
*/
- fun filterCredentialsByAppInfo(
- credentials: List<Credential>,
+ fun filterItemsByAppInfo(
+ items: List<Item>,
searchText: String,
- ): List<Credential> {
+ ): List<Item> {
// Early return for empty search
if (searchText.isEmpty()) {
- return credentials
+ return items
}
try {
- // Convert credentials to JSON format expected by Rust
+ // Convert items to JSON format expected by Rust
val rustCredentials = JSONArray()
- val credentialMap = mutableMapOf<String, Credential>()
+ val itemMap = mutableMapOf<String, Item>()
- for (credential in credentials) {
- val idString = credential.id.toString()
+ for (item in items) {
+ val idString = item.id.toString()
val credJson = JSONObject().apply {
put("Id", idString)
- put("ServiceName", credential.service.name ?: JSONObject.NULL)
- put("ServiceUrl", credential.service.url ?: JSONObject.NULL)
- put("Username", credential.username ?: JSONObject.NULL)
+ put("ServiceName", item.name ?: JSONObject.NULL)
+ put("ServiceUrl", item.url ?: JSONObject.NULL)
+ put("Username", item.username ?: JSONObject.NULL)
}
rustCredentials.put(credJson)
- credentialMap[idString] = credential
+ itemMap[idString] = item
}
// Prepare input JSON for Rust
@@ -70,18 +70,18 @@ object RustCredentialMatcher {
return emptyList()
}
- // Convert matched IDs back to credentials, maintaining order
- val filtered = mutableListOf<Credential>()
+ // Convert matched IDs back to items, maintaining order
+ val filtered = mutableListOf<Item>()
for (i in 0 until matchedIds.length()) {
val id = matchedIds.getString(i)
- credentialMap[id]?.let { filtered.add(it) }
+ itemMap[id]?.let { filtered.add(it) }
}
return filtered
} catch (e: Exception) {
- Log.e(TAG, "Error filtering credentials with Rust matcher: ${e.message}", e)
- // Fallback to returning all credentials on error
- return credentials
+ Log.e(TAG, "Error filtering items with Rust matcher: ${e.message}", e)
+ // Fallback to returning all items on error
+ return items
}
}
}
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 46196026e..9ce812b7d 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
@@ -3,15 +3,11 @@ package net.aliasvault.app.vaultstore
import android.util.Base64
import android.util.Log
import net.aliasvault.app.utils.DateHelpers
-import net.aliasvault.app.vaultstore.interfaces.CredentialOperationCallback
-import net.aliasvault.app.vaultstore.models.Alias
-import net.aliasvault.app.vaultstore.models.Credential
+import net.aliasvault.app.vaultstore.interfaces.ItemOperationCallback
import net.aliasvault.app.vaultstore.models.FieldKey
import net.aliasvault.app.vaultstore.models.FieldType
import net.aliasvault.app.vaultstore.models.Item
import net.aliasvault.app.vaultstore.models.ItemField
-import net.aliasvault.app.vaultstore.models.Password
-import net.aliasvault.app.vaultstore.models.Service
import java.util.Calendar
import java.util.Date
import java.util.TimeZone
@@ -369,79 +365,12 @@ class VaultQuery(
// endregion
- // region Legacy Credential Operations (Compatibility Layer)
+ // region Item Operations
/**
- * Get all credentials from the vault.
- * This method converts the new Items model back to the legacy Credential model for compatibility.
+ * Attempts to get all items using only the cached encryption key.
*/
- fun getAllCredentials(): List<Credential> {
- val items = getAllItems()
- return items.mapNotNull { convertItemToCredential(it) }
- }
-
- /**
- * Convert an Item to the legacy Credential format.
- */
- private fun convertItemToCredential(item: Item): Credential? {
- // Create a Service from the item
- val service = Service(
- id = item.id,
- name = item.name,
- url = item.url,
- logo = item.logo,
- createdAt = item.createdAt,
- updatedAt = item.updatedAt,
- isDeleted = false,
- )
-
- // Create an Alias if the item has alias fields
- var alias: Alias? = null
- if (item.firstName != null || item.lastName != null || item.email != null) {
- alias = Alias(
- id = item.id,
- gender = item.getFieldValue(FieldKey.ALIAS_GENDER),
- firstName = item.firstName,
- lastName = item.lastName,
- nickName = null,
- birthDate = MIN_DATE, // TODO: Parse birthdate from field value
- email = item.email,
- createdAt = item.createdAt,
- updatedAt = item.updatedAt,
- isDeleted = false,
- )
- }
-
- // Create a Password if the item has a password field
- var password: Password? = null
- item.password?.let { passwordValue ->
- password = Password(
- id = UUID.randomUUID(),
- credentialId = item.id,
- value = passwordValue,
- createdAt = item.createdAt,
- updatedAt = item.updatedAt,
- isDeleted = false,
- )
- }
-
- return Credential(
- id = item.id,
- alias = alias,
- service = service,
- username = item.username,
- notes = item.getFieldValue("login.notes"),
- password = password,
- createdAt = item.createdAt,
- updatedAt = item.updatedAt,
- isDeleted = false,
- )
- }
-
- /**
- * Attempts to get all credentials using only the cached encryption key.
- */
- fun tryGetAllCredentials(callback: CredentialOperationCallback, crypto: VaultCrypto, unlockVault: () -> Unit): Boolean {
+ fun tryGetAllItems(callback: ItemOperationCallback, crypto: VaultCrypto, unlockVault: () -> Unit): Boolean {
if (crypto.encryptionKey == null) {
Log.d(TAG, "Encryption key not in memory, authentication required")
return false
@@ -452,10 +381,10 @@ class VaultQuery(
unlockVault()
}
- callback.onSuccess(getAllCredentials())
+ callback.onSuccess(getAllItems())
return true
} catch (e: Exception) {
- Log.e(TAG, "Error retrieving credentials", e)
+ Log.e(TAG, "Error retrieving items", e)
callback.onError(e)
return 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 5585e4fa2..e4c264c4d 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
@@ -5,11 +5,11 @@ import android.os.Looper
import android.util.Log
import io.requery.android.database.sqlite.SQLiteDatabase
import kotlinx.coroutines.suspendCancellableCoroutine
-import net.aliasvault.app.vaultstore.interfaces.CredentialOperationCallback
import net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallback
+import net.aliasvault.app.vaultstore.interfaces.ItemOperationCallback
import net.aliasvault.app.vaultstore.keystoreprovider.BiometricAuthCallback
import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreProvider
-import net.aliasvault.app.vaultstore.models.Credential
+import net.aliasvault.app.vaultstore.models.Item
import net.aliasvault.app.vaultstore.models.StoreVaultResult
import net.aliasvault.app.vaultstore.storageprovider.StorageProvider
import kotlin.coroutines.resume
@@ -73,7 +73,7 @@ class VaultStore(
private val query = VaultQuery(databaseComponent)
internal val metadata = VaultMetadataManager(storageProvider)
private val auth = VaultAuth(storageProvider) { cache.clearCache() }
- private val sync = VaultSync(databaseComponent, metadata, crypto, storageProvider)
+ private val sync = VaultSync(databaseComponent, metadata, crypto, storageProvider, query)
private val mutate = VaultMutate(databaseComponent, query, metadata)
private val cache = VaultCache(crypto, databaseComponent, keystoreProvider, storageProvider)
private val passkey = VaultPasskey(databaseComponent, query)
@@ -302,17 +302,17 @@ class VaultStore(
}
/**
- * Get all credentials from the vault.
+ * Get all items from the vault.
*/
- fun getAllCredentials(): List<Credential> {
- return query.getAllCredentials()
+ fun getAllItems(): List<Item> {
+ return query.getAllItems()
}
/**
- * Attempts to get all credentials using only the cached encryption key.
+ * Attempts to get all items using only the cached encryption key.
*/
- fun tryGetAllCredentials(callback: CredentialOperationCallback): Boolean {
- return query.tryGetAllCredentials(callback, crypto) { unlockVault() }
+ fun tryGetAllItems(callback: ItemOperationCallback): Boolean {
+ return query.tryGetAllItems(callback, crypto) { unlockVault() }
}
// endregion
@@ -560,7 +560,7 @@ class VaultStore(
* Unified vault sync method that handles all sync scenarios.
*/
suspend fun syncVaultWithServer(webApiService: net.aliasvault.app.webapi.WebApiService): VaultSyncResult {
- val result = sync.syncVaultWithServer(webApiService, mutate)
+ val result = sync.syncVaultWithServer(webApiService)
// Re-unlock vault if it was unlocked before sync and action was download/merge
if (result.success && (result.action == SyncAction.DOWNLOADED || result.action == SyncAction.MERGED) && isVaultUnlocked()) {
unlockVault()
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 21ecb3b7d..b38fe87a6 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
@@ -7,6 +7,7 @@ import net.aliasvault.app.rustcore.VaultMergeService
import net.aliasvault.app.utils.AppInfo
import net.aliasvault.app.vaultstore.storageprovider.StorageProvider
import net.aliasvault.app.vaultstore.utils.VersionComparison
+import org.json.JSONArray
import org.json.JSONObject
/**
@@ -17,6 +18,7 @@ class VaultSync(
private val metadata: VaultMetadataManager,
private val crypto: VaultCrypto,
private val storageProvider: StorageProvider,
+ private val query: VaultQuery,
) {
companion object {
private const val TAG = "VaultSync"
@@ -71,7 +73,6 @@ class VaultSync(
*/
suspend fun syncVaultWithServer(
webApiService: net.aliasvault.app.webapi.WebApiService,
- mutate: VaultMutate,
retryCount: Int = 0,
): VaultSyncResult {
val maxRetries = 3
@@ -104,7 +105,7 @@ class VaultSync(
// Server has newer vault
if (isDirty) {
// MERGE: Local changes + server changes
- performMergeSync(webApiService, mutate, serverRevision, mutationSeqAtStart, retryCount)
+ performMergeSync(webApiService, serverRevision, mutationSeqAtStart, retryCount)
} else {
// DOWNLOAD: No local changes, safe to overwrite
performDownloadSync(webApiService, serverRevision, mutationSeqAtStart, retryCount)
@@ -112,7 +113,7 @@ class VaultSync(
}
serverRevision == syncState.serverRevision && isDirty -> {
// UPLOAD: Local changes at same revision
- performUploadSync(webApiService, mutate, mutationSeqAtStart, retryCount)
+ performUploadSync(webApiService, mutationSeqAtStart, retryCount)
}
serverRevision < syncState.serverRevision -> {
/**
@@ -127,7 +128,7 @@ class VaultSync(
"Server data loss detected! Server at rev $serverRevision, " +
"client at rev ${syncState.serverRevision}. Uploading to recover server state.",
)
- performUploadSync(webApiService, mutate, mutationSeqAtStart, retryCount)
+ performUploadSync(webApiService, mutationSeqAtStart, retryCount)
}
else -> {
// Already in sync
@@ -182,7 +183,7 @@ class VaultSync(
// Race detected - retry
Log.d(TAG, "Race detected during download, retrying")
metadata.setIsSyncing(false)
- return syncVaultWithServer(webApiService, VaultMutate(database, VaultQuery(database), metadata), retryCount + 1)
+ return syncVaultWithServer(webApiService, retryCount + 1)
}
// Store vault metadata
@@ -227,12 +228,11 @@ class VaultSync(
*/
private suspend fun performUploadSync(
webApiService: net.aliasvault.app.webapi.WebApiService,
- mutate: VaultMutate,
mutationSeqAtStart: Int,
retryCount: Int,
): VaultSyncResult {
return try {
- val uploadResult = mutate.uploadVault(webApiService)
+ val uploadResult = uploadVault(webApiService)
when {
uploadResult.success -> {
@@ -251,7 +251,7 @@ class VaultSync(
// Vault outdated - server moved forward, retry to merge
Log.d(TAG, "Vault outdated during upload, retrying")
metadata.setIsSyncing(false)
- syncVaultWithServer(webApiService, mutate, retryCount + 1)
+ syncVaultWithServer(webApiService, retryCount + 1)
}
else -> {
metadata.setIsSyncing(false)
@@ -282,7 +282,6 @@ class VaultSync(
@Suppress("UnusedParameter") // serverRevision will be used for conflict resolution metadata in the future
private suspend fun performMergeSync(
webApiService: net.aliasvault.app.webapi.WebApiService,
- mutate: VaultMutate,
serverRevision: Int,
mutationSeqAtStart: Int,
retryCount: Int,
@@ -306,10 +305,11 @@ class VaultSync(
val mergedVault = performLWWMerge(localVault, serverVault.vault.blob)
// Store merged vault with race detection
+ // Set serverRevision to the server's revision so prepareVault() sends correct revision when uploading
val storeResult = storeEncryptedVaultWithSyncState(
encryptedVault = mergedVault,
markDirty = false,
- serverRevision = null, // Will be updated after upload
+ serverRevision = serverVault.vault.currentRevisionNumber,
expectedMutationSeq = mutationSeqAtStart,
)
@@ -317,11 +317,17 @@ class VaultSync(
// Race detected - retry
Log.d(TAG, "Race detected during merge, retrying")
metadata.setIsSyncing(false)
- return syncVaultWithServer(webApiService, mutate, retryCount + 1)
+ return syncVaultWithServer(webApiService, retryCount + 1)
+ }
+
+ // Re-unlock immediately after merge to load merged vault into memory
+ // This ensures prepareVault() gets correct item counts and the UI shows merged data
+ if (database.isVaultUnlocked()) {
+ // Note: unlock requires auth methods from VaultStore - handled there
}
// Upload merged vault
- val uploadResult = mutate.uploadVault(webApiService)
+ val uploadResult = uploadVault(webApiService)
when {
uploadResult.success -> {
@@ -339,7 +345,7 @@ class VaultSync(
// Vault outdated again - retry
Log.d(TAG, "Vault outdated after merge, retrying")
metadata.setIsSyncing(false)
- syncVaultWithServer(webApiService, mutate, retryCount + 1)
+ syncVaultWithServer(webApiService, retryCount + 1)
}
else -> {
metadata.setIsSyncing(false)
@@ -391,6 +397,159 @@ class VaultSync(
}
}
+ /**
+ * Upload the vault to the server and return detailed result.
+ * This is used for sync operations where race detection is needed.
+ */
+ private suspend fun uploadVault(webApiService: net.aliasvault.app.webapi.WebApiService): VaultUploadResult {
+ val mutationSeqAtStart = metadata.getMutationSequence()
+
+ return try {
+ val vault = prepareVault()
+
+ val json = JSONObject()
+ json.put("blob", vault.blob)
+ json.put("createdAt", vault.createdAt)
+ json.put("credentialsCount", vault.credentialsCount)
+ json.put("currentRevisionNumber", vault.currentRevisionNumber)
+ json.put("emailAddressList", JSONArray(vault.emailAddressList))
+ json.put("encryptionPublicKey", vault.encryptionPublicKey)
+ json.put("updatedAt", vault.updatedAt)
+ json.put("username", vault.username)
+ json.put("version", vault.version)
+
+ val response = try {
+ webApiService.executeRequest(
+ method = "POST",
+ endpoint = "Vault",
+ body = json.toString(),
+ headers = mapOf("Content-Type" to "application/json"),
+ requiresAuth = true,
+ )
+ } catch (e: Exception) {
+ return VaultUploadResult(
+ success = false,
+ status = -1,
+ newRevisionNumber = 0,
+ mutationSeqAtStart = mutationSeqAtStart,
+ error = "Network error: ${e.message}",
+ )
+ }
+
+ if (response.statusCode != 200) {
+ return VaultUploadResult(
+ success = false,
+ status = -1,
+ newRevisionNumber = 0,
+ mutationSeqAtStart = mutationSeqAtStart,
+ error = "Server returned error: ${response.statusCode}",
+ )
+ }
+
+ val vaultResponse = try {
+ val responseJson = JSONObject(response.body)
+ VaultPostResponse(
+ status = responseJson.getInt("status"),
+ newRevisionNumber = responseJson.getInt("newRevisionNumber"),
+ )
+ } catch (e: Exception) {
+ return VaultUploadResult(
+ success = false,
+ status = -1,
+ newRevisionNumber = 0,
+ mutationSeqAtStart = mutationSeqAtStart,
+ error = "Failed to parse response: ${e.message}",
+ )
+ }
+
+ if (vaultResponse.status == 0) {
+ // Success - update local revision number and clear offline mode
+ metadata.setVaultRevisionNumber(vaultResponse.newRevisionNumber)
+ metadata.setOfflineMode(false)
+ }
+
+ VaultUploadResult(
+ success = vaultResponse.status == 0,
+ status = vaultResponse.status,
+ newRevisionNumber = vaultResponse.newRevisionNumber,
+ mutationSeqAtStart = mutationSeqAtStart,
+ error = if (vaultResponse.status != 0) "Vault upload returned status ${vaultResponse.status}" else null,
+ )
+ } catch (e: Exception) {
+ Log.e(TAG, "Error uploading vault", e)
+ VaultUploadResult(
+ success = false,
+ status = -1,
+ newRevisionNumber = 0,
+ mutationSeqAtStart = mutationSeqAtStart,
+ error = "Error uploading vault: ${e.message}",
+ )
+ }
+ }
+
+ /**
+ * Prepare the vault for upload by assembling all metadata.
+ */
+ private fun prepareVault(): VaultUpload {
+ val currentRevision = metadata.getVaultRevisionNumber()
+
+ val encryptedDb = database.getEncryptedDatabase()
+
+ val username = metadata.getUsername()
+ ?: throw VaultOperationException("Username not found")
+
+ if (!database.isVaultUnlocked()) {
+ throw VaultOperationException("Vault must be unlocked to prepare for upload")
+ }
+
+ // Get all items to count them and extract private email addresses
+ val items = query.getAllItems()
+
+ val metadataObj = metadata.getVaultMetadataObject()
+ val privateEmailDomains = metadataObj?.privateEmailDomains ?: emptyList()
+
+ // Extract private email addresses from items using the email field
+ val privateEmailAddresses = items
+ .mapNotNull { it.email }
+ .filter { email ->
+ privateEmailDomains.any { domain ->
+ email.lowercase().endsWith("@${domain.lowercase()}")
+ }
+ }
+ .distinct()
+
+ val dbVersion = query.getDatabaseVersion()
+
+ @Suppress("SwallowedException")
+ val version = try {
+ // Try to get version from storage provider context
+ val context = database.javaClass.getDeclaredField("storageProvider")
+ .get(database) as? net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
+ val pm = context?.javaClass?.getDeclaredField("context")?.get(context)
+ as? android.content.Context
+ pm?.packageManager?.getPackageInfo(pm.packageName, 0)?.versionName ?: "0.0.0"
+ } catch (e: Exception) {
+ "0.0.0"
+ }
+
+ val dateFormat = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", java.util.Locale.US)
+ dateFormat.timeZone = java.util.TimeZone.getTimeZone("UTC")
+ val now = dateFormat.format(java.util.Date())
+
+ return VaultUpload(
+ blob = encryptedDb,
+ createdAt = now,
+ credentialsCount = items.size,
+ currentRevisionNumber = currentRevision,
+ emailAddressList = privateEmailAddresses,
+ // TODO: add public RSA encryption key to payload when implementing vault creation from mobile app.
+ encryptionPublicKey = "",
+ updatedAt = now,
+ username = username,
+ version = dbVersion,
+ )
+ }
+
/**
* Store encrypted vault with sync state atomically.
*/
@@ -757,5 +916,22 @@ class VaultSync(
val vault: InternalVaultData,
)
+ private data class VaultUpload(
+ val blob: String,
+ val createdAt: String,
+ val credentialsCount: Int,
+ val currentRevisionNumber: Int,
+ val emailAddressList: List<String>,
+ val encryptionPublicKey: String,
+ val updatedAt: String,
+ val username: String,
+ val version: String,
+ )
+
+ private data class VaultPostResponse(
+ val status: Int,
+ val newRevisionNumber: Int,
+ )
+
// endregion
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/interfaces/CredentialOperationCallback.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/interfaces/ItemOperationCallback.kt
similarity index 59%
rename from apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/interfaces/CredentialOperationCallback.kt
rename to apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/interfaces/ItemOperationCallback.kt
index 5a00b8e46..88ab3ebd6 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/interfaces/CredentialOperationCallback.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/interfaces/ItemOperationCallback.kt
@@ -1,16 +1,16 @@
package net.aliasvault.app.vaultstore.interfaces
-import net.aliasvault.app.vaultstore.models.Credential
+import net.aliasvault.app.vaultstore.models.Item
/**
- * Interface for operations that need callbacks for credentials.
+ * Interface for operations that need callbacks for items.
*/
-interface CredentialOperationCallback {
+interface ItemOperationCallback {
/**
* Called when the operation is successful.
* @param result The result of the operation
*/
- fun onSuccess(result: List<Credential>)
+ fun onSuccess(result: List<Item>)
/**
* Called when the operation fails.
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Credential.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Credential.kt
deleted file mode 100644
index 3ce0c011e..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Credential.kt
+++ /dev/null
@@ -1,246 +0,0 @@
-package net.aliasvault.app.vaultstore.models
-
-import java.util.Date
-import java.util.UUID
-
-/**
- * Credential object.
- */
-data class Credential(
- /**
- * The ID of the credential.
- */
- val id: UUID,
-
- /**
- * The alias of the credential.
- */
- val alias: Alias?,
-
- /**
- * The service of the credential.
- */
- val service: Service,
-
- /**
- * The username of the credential.
- */
- val username: String?,
-
- /**
- * The notes of the credential.
- */
- val notes: String?,
-
- /**
- * The password of the credential.
- */
- val password: Password?,
-
- /**
- * The creation date of the credential.
- */
- val createdAt: Date,
-
- /**
- * The update date of the credential.
- */
- val updatedAt: Date,
-
- /**
- * Whether the credential is deleted.
- */
- val isDeleted: Boolean,
-)
-
-/**
- * Service object.
- */
-data class Service(
- /**
- * The ID of the service.
- */
- val id: UUID,
-
- /**
- * The name of the service.
- */
- val name: String?,
-
- /**
- * The URL of the service.
- */
- val url: String?,
-
- /**
- * The logo of the service.
- */
- val logo: ByteArray?,
-
- /**
- * The creation date of the service.
- */
- val createdAt: Date,
-
- /**
- * The update date of the service.
- */
- val updatedAt: Date,
-
- /**
- * Whether the service is deleted.
- */
- val isDeleted: Boolean,
-) {
- override fun equals(other: Any?): Boolean {
- if (this === other) return true
- if (javaClass != other?.javaClass) return false
-
- other as Service
-
- if (id != other.id) return false
- if (name != other.name) return false
- if (url != other.url) return false
- if (!logo.contentEquals(other.logo)) return false
- if (createdAt != other.createdAt) return false
- if (updatedAt != other.updatedAt) return false
- if (isDeleted != other.isDeleted) return false
-
- return true
- }
-
- override fun hashCode(): Int {
- var result = id.hashCode()
- result = 31 * result + (name?.hashCode() ?: 0)
- result = 31 * result + (url?.hashCode() ?: 0)
- result = 31 * result + (logo?.contentHashCode() ?: 0)
- result = 31 * result + createdAt.hashCode()
- result = 31 * result + updatedAt.hashCode()
- result = 31 * result + isDeleted.hashCode()
- return result
- }
-}
-
-/**
- * Password object.
- */
-data class Password(
- /**
- * The ID of the password.
- */
- val id: UUID,
-
- /**
- * The credential ID of the password.
- */
- val credentialId: UUID,
-
- /**
- * The value of the password.
- */
- val value: String,
-
- /**
- * The creation date of the password.
- */
- val createdAt: Date,
-
- /**
- * The update date of the password.
- */
- val updatedAt: Date,
-
- /**
- * Whether the password is deleted.
- */
- val isDeleted: Boolean,
-)
-
-/**
- * Alias object.
- */
-data class Alias(
- /**
- * The ID of the alias.
- */
- val id: UUID,
-
- /**
- * The gender of the alias.
- */
- val gender: String?,
-
- /**
- * The first name of the alias.
- */
- val firstName: String?,
-
- /**
- * The last name of the alias.
- */
- val lastName: String?,
-
- /**
- * The nick name of the alias.
- */
- val nickName: String?,
-
- /**
- * The birth date of the alias.
- */
- val birthDate: Date,
-
- /**
- * The email of the alias.
- */
- val email: String?,
-
- /**
- * The creation date of the alias.
- */
- val createdAt: Date,
-
- /**
- * The update date of the alias.
- */
- val updatedAt: Date,
-
- /**
- * Whether the alias is deleted.
- */
- val isDeleted: Boolean,
-) {
- override fun equals(other: Any?): Boolean {
- if (this === other) return true
- if (javaClass != other?.javaClass) return false
-
- other as Alias
-
- if (id != other.id) return false
- if (gender != other.gender) return false
- if (firstName != other.firstName) return false
- if (lastName != other.lastName) return false
- if (nickName != other.nickName) return false
- if (birthDate != other.birthDate) return false
- if (email != other.email) return false
- if (createdAt != other.createdAt) return false
- if (updatedAt != other.updatedAt) return false
- if (isDeleted != other.isDeleted) return false
-
- return true
- }
-
- override fun hashCode(): Int {
- var result = id.hashCode()
- result = 31 * result + (gender?.hashCode() ?: 0)
- result = 31 * result + (firstName?.hashCode() ?: 0)
- result = 31 * result + (lastName?.hashCode() ?: 0)
- result = 31 * result + (nickName?.hashCode() ?: 0)
- result = 31 * result + birthDate.hashCode()
- result = 31 * result + (email?.hashCode() ?: 0)
- result = 31 * result + createdAt.hashCode()
- result = 31 * result + updatedAt.hashCode()
- result = 31 * result + isDeleted.hashCode()
- return result
- }
-}
diff --git a/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt
index bd8bb4202..7ef15a330 100644
--- a/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt
+++ b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt
@@ -50,45 +50,44 @@ class VaultStoreTest {
}
@Test
- fun testGetAllCredentials() {
- val credentials = vaultStore.getAllCredentials()
-
- // Verify we got some credentials back
- assertFalse(credentials.isEmpty(), "Should have retrieved some credentials")
-
- // Verify the structure of the first credential
- if (credentials.isNotEmpty()) {
- val firstCredential = credentials.first()
- assertNotNull(firstCredential.id, "Credential should have an ID")
- assertNotNull(firstCredential.service, "Credential should have a service")
- assertNotNull(firstCredential.password, "Credential should have a password")
- assertNotNull(firstCredential.username, "Credential should have a username")
- assertNotNull(firstCredential.createdAt, "Credential should have a creation date")
- assertNotNull(firstCredential.updatedAt, "Credential should have an update date")
+ fun testGetAllItems() {
+ val items = vaultStore.getAllItems()
+
+ // Verify we got some items back
+ assertFalse(items.isEmpty(), "Should have retrieved some items")
+
+ // Verify the structure of the first item
+ if (items.isNotEmpty()) {
+ val firstItem = items.first()
+ assertNotNull(firstItem.id, "Item should have an ID")
+ assertNotNull(firstItem.name, "Item should have a name")
+ assertNotNull(firstItem.password, "Item should have a password")
+ assertNotNull(firstItem.username, "Item should have a username")
+ assertNotNull(firstItem.createdAt, "Item should have a creation date")
+ assertNotNull(firstItem.updatedAt, "Item should have an update date")
}
}
@Test
- fun testGetGmailCredentialDetails() {
- // Get all credentials
- val credentials = vaultStore.getAllCredentials()
+ fun testGetGmailItemDetails() {
+ // Get all items
+ val items = vaultStore.getAllItems()
- // Find the Gmail credential
- val gmailCredential = credentials.find { it.service.name == "Gmail Test Account" }
- assertNotNull(gmailCredential, "Gmail Test Account credential should exist")
+ // Find the Gmail item
+ val gmailItem = items.find { it.name == "Gmail Test Account" }
+ assertNotNull(gmailItem, "Gmail Test Account item should exist")
// Verify all expected properties
- assertEquals("Gmail Test Account", gmailCredential.service.name)
- assertEquals("https://google.com", gmailCredential.service.url)
- assertEquals("[email protected]", gmailCredential.username)
- assertEquals("Test", gmailCredential.alias?.firstName)
- assertEquals("User", gmailCredential.alias?.lastName)
- assertEquals("Test Gmail account for unit testing", gmailCredential.notes)
+ assertEquals("Gmail Test Account", gmailItem.name)
+ assertEquals("https://google.com", gmailItem.url)
+ assertEquals("[email protected]", gmailItem.username)
+ assertEquals("Test", gmailItem.firstName)
+ assertEquals("User", gmailItem.lastName)
// Verify logo exists and has sufficient size
- val logo = gmailCredential.service.logo
+ val logo = gmailItem.logo
- assertNotNull(logo, "Service logo should not be nil")
+ assertNotNull(logo, "Item logo should not be nil")
assertTrue(logo.size > 1024, "Logo data should exceed 1KB in size")
}