Skip to content

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

Update Android logic and queries with manifest scoping (#2159)

Leendert de Borst0d7b794698f1
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillFillActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillFillActivity.kt
index 31db23c0f..59d0afc6a 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillFillActivity.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillFillActivity.kt
@@ -14,6 +14,7 @@ import net.aliasvault.app.autofill.models.FieldType
import net.aliasvault.app.autofill.utils.AutofillFieldMapper
import net.aliasvault.app.utils.TotpClipboard
import net.aliasvault.app.vaultstore.VaultStore
+import net.aliasvault.app.vaultstore.repositories.ItemUsageAction
/**
* Transparent activity launched by the OS when the user picks an autofill
@@ -30,6 +31,9 @@ class AutofillFillActivity : Activity() {
/** Intent extra for the vault item ID whose credentials should be filled. */
const val EXTRA_ITEM_ID = "net.aliasvault.app.autofill.EXTRA_ITEM_ID"
+ /** Intent extra for the manifest the item belongs to; only (manifest, id) names one item. */
+ const val EXTRA_MANIFEST_ID = "net.aliasvault.app.autofill.EXTRA_MANIFEST_ID"
+
/** Intent extra holding the parceled `AutofillId`s for the target form fields. */
const val EXTRA_AUTOFILL_IDS = "net.aliasvault.app.autofill.EXTRA_AUTOFILL_IDS"
@@ -45,11 +49,12 @@ class AutofillFillActivity : Activity() {
try {
val itemId = intent.getStringExtra(EXTRA_ITEM_ID)
+ val manifestId = intent.getStringExtra(EXTRA_MANIFEST_ID)
val autofillIds = parseAutofillIds(intent)
val fieldTypeOrdinals = intent.getIntArrayExtra(EXTRA_FIELD_TYPES)
val copyTotp = intent.getBooleanExtra(EXTRA_COPY_TOTP, false)
- if (itemId == null || autofillIds == null || fieldTypeOrdinals == null ||
+ if (itemId == null || manifestId == null || autofillIds == null || fieldTypeOrdinals == null ||
autofillIds.size != fieldTypeOrdinals.size
) {
Log.w(TAG, "AutofillFillActivity: missing or mismatched extras, finishing")
@@ -66,7 +71,9 @@ class AutofillFillActivity : Activity() {
return
}
- val item = store.getAllItems().firstOrNull { it.id.toString().equals(itemId, ignoreCase = true) }
+ val item = store.getAllItems().firstOrNull {
+ it.id.toString().equals(itemId, ignoreCase = true) && it.manifestId.equals(manifestId, ignoreCase = true)
+ }
if (item == null) {
Log.w(TAG, "AutofillFillActivity: item not found, finishing")
setResult(RESULT_CANCELED)
@@ -74,14 +81,21 @@ class AutofillFillActivity : Activity() {
return
}
+ // Count the fill in the item's usage statistics
+ try {
+ store.recordItemUsage(itemId, item.manifestId, ItemUsageAction.AUTOFILL)
+ } catch (e: Exception) {
+ Log.w(TAG, "AutofillFillActivity: failed to record item usage", e)
+ }
+
if (copyTotp) {
- TotpClipboard.copyCodeForItem(this, store, itemId)
+ TotpClipboard.copyCodeForItem(this, store, itemId, item.manifestId)
}
val fields = pairFields(autofillIds, fieldTypeOrdinals)
// Presentation passed to the inner Dataset.Builder is never displayed
- // — the OS already showed the outer dataset's presentation in the
- // picker — but the legacy constructor requires a valid RemoteViews.
+ // (the OS already showed the outer dataset's presentation in the
+ // picker) but the legacy constructor requires a valid RemoteViews.
val presentation = RemoteViews(packageName, R.layout.autofill_dataset_item_icon)
val builder = Dataset.Builder(presentation)
AutofillFieldMapper.applyItem(builder, item, fields)
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/AutofillDatasetBuilder.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/AutofillDatasetBuilder.kt
index 14f44dcb3..33839ba84 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/AutofillDatasetBuilder.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/AutofillDatasetBuilder.kt
@@ -81,6 +81,7 @@ object AutofillDatasetBuilder {
val fieldTypeOrdinals = IntArray(fields.size) { i -> fields[i].second.ordinal }
val authIntent = Intent(context, AutofillFillActivity::class.java).apply {
putExtra(AutofillFillActivity.EXTRA_ITEM_ID, item.id.toString().lowercase())
+ putExtra(AutofillFillActivity.EXTRA_MANIFEST_ID, item.manifestId)
putExtra(AutofillFillActivity.EXTRA_AUTOFILL_IDS, autofillIds)
putExtra(AutofillFillActivity.EXTRA_FIELD_TYPES, fieldTypeOrdinals)
putExtra(AutofillFillActivity.EXTRA_COPY_TOTP, copyTotpOnSelect)
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt
index aaf33983c..213b55317 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt
@@ -56,7 +56,7 @@ object RustItemMatcher {
val itemMap = mutableMapOf<String, Item>()
for (item in items) {
- val idString = item.id.toString()
+ val idString = "${item.manifestId}${item.id}"
val urlsArray = JSONArray()
item.urls.forEach { urlsArray.put(it) }
val credJson = JSONObject().apply {
@@ -132,7 +132,7 @@ object RustItemMatcher {
val itemMap = mutableMapOf<String, ItemWithCredentialInfo>()
for (item in items) {
- val idString = item.itemId.toString()
+ val idString = "${item.manifestId}${item.itemId}"
val urlsArray = JSONArray()
item.urls.forEach { urlsArray.put(it) }
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt
index 5df36438c..981a91f4e 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt
@@ -21,6 +21,7 @@ import net.aliasvault.app.vaultstore.VaultStore
import net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider
import net.aliasvault.app.vaultstore.passkey.PasskeyAuthenticator
import net.aliasvault.app.vaultstore.passkey.PasskeyHelper
+import net.aliasvault.app.vaultstore.repositories.ItemUsageAction
import net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
import org.json.JSONObject
import java.security.MessageDigest
@@ -260,13 +261,24 @@ class PasskeyAuthenticationActivity : FragmentActivity() {
clientDataJson = clientDataJson,
)
+ // Count the assertion in the item's usage statistics.
+ val manifestId = passkey.manifestId
+ if (manifestId != null) {
+ try {
+ vaultStore.recordItemUsage(passkey.parentItemId.toString(), manifestId, ItemUsageAction.PASSKEY)
+ } catch (e: Exception) {
+ Log.w(TAG, "Failed to record passkey usage", e)
+ }
+ }
+
// If the item behind this passkey also has a TOTP code and the user has the
// copy-on-fill setting enabled (default), write the current code to the clipboard.
- if (TotpClipboard.isCopyOnFillEnabled(this@PasskeyAuthenticationActivity)) {
+ if (manifestId != null && TotpClipboard.isCopyOnFillEnabled(this@PasskeyAuthenticationActivity)) {
TotpClipboard.copyCodeForItem(
context = this@PasskeyAuthenticationActivity,
store = vaultStore,
itemId = passkey.parentItemId.toString(),
+ manifestId = manifestId,
)
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt
index 03865ea29..69785af47 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt
@@ -276,9 +276,10 @@ class PasskeyFormFragment : Fragment() {
}
// Try to extract favicon from the website URL if possible
+ val url = loginUrl()
var logo: ByteArray? = null
try {
- logo = webApiService.extractFavicon("https://${viewModel.rpId}")
+ logo = webApiService.extractFavicon(url)
} catch (e: Exception) {
Log.w(TAG, "Favicon extraction failed", e)
// Continue without logo
@@ -323,6 +324,7 @@ class PasskeyFormFragment : Fragment() {
val passkey = Passkey(
id = passkeyId,
parentItemId = UUID.randomUUID(), // Will be set by createItemWithPasskey
+ manifestId = null, // Stamped from the item on insert
rpId = viewModel.rpId,
userHandle = viewModel.userId,
userName = viewModel.userName,
@@ -341,7 +343,7 @@ class PasskeyFormFragment : Fragment() {
}
vaultStore.createItemWithPasskey(
- rpId = viewModel.rpId,
+ url = url,
userName = viewModel.userName,
displayName = displayName,
passkeyObj = passkey,
@@ -481,9 +483,10 @@ class PasskeyFormFragment : Fragment() {
}
// Extract favicon (optional)
+ val url = loginUrl()
var logo: ByteArray? = null
try {
- logo = webApiService.extractFavicon("https://${viewModel.rpId}")
+ logo = webApiService.extractFavicon(url)
} catch (e: Exception) {
Log.w(TAG, "Favicon extraction failed", e)
// Continue without logo
@@ -526,6 +529,7 @@ class PasskeyFormFragment : Fragment() {
val newPasskey = Passkey(
id = newPasskeyId,
parentItemId = passkeyToReplace.passkey.parentItemId,
+ manifestId = passkeyToReplace.passkey.manifestId,
rpId = viewModel.rpId,
userHandle = viewModel.userId,
userName = viewModel.userName,
@@ -547,6 +551,7 @@ class PasskeyFormFragment : Fragment() {
oldPasskeyId = passkeyToReplace.passkey.id,
newPasskey = newPasskey,
displayName = displayName,
+ url = url,
logo = logo,
)
@@ -690,9 +695,10 @@ class PasskeyFormFragment : Fragment() {
}
// Extract favicon (optional)
+ val url = loginUrl()
var logo: ByteArray? = null
try {
- logo = webApiService.extractFavicon("https://${viewModel.rpId}")
+ logo = webApiService.extractFavicon(url)
} catch (e: Exception) {
Log.w(TAG, "Favicon extraction failed", e)
// Continue without logo
@@ -735,6 +741,7 @@ class PasskeyFormFragment : Fragment() {
val passkey = Passkey(
id = passkeyId,
parentItemId = item.itemId, // Link to existing Item
+ manifestId = item.manifestId,
rpId = viewModel.rpId,
userHandle = viewModel.userId,
userName = viewModel.userName,
@@ -754,7 +761,9 @@ class PasskeyFormFragment : Fragment() {
vaultStore.addPasskeyToExistingItem(
itemId = item.itemId,
+ manifestId = item.manifestId,
passkeyObj = passkey,
+ url = url,
logo = logo,
)
@@ -862,6 +871,15 @@ class PasskeyFormFragment : Fragment() {
}
}
+ /**
+ * The login URL written on the item, which is also what the favicon is fetched for: the request origin
+ * when the caller is a browser (what the extension writes), else https:// plus the rpId.
+ */
+ private fun loginUrl(): String {
+ val origin = viewModel.origin
+ return if (origin != null && (origin.startsWith("https://") || origin.startsWith("http://"))) origin else "https://${viewModel.rpId}"
+ }
+
/**
* Pick the credential algorithm from the RP's pubKeyCredParams.
* Honors the RP's preference order; defaults to ES256 when absent.
@@ -957,7 +975,9 @@ class PasskeyFormFragment : Fragment() {
message = getString(R.string.version_not_supported_message)
}
- is net.aliasvault.app.vaultstore.AppError.ServerVersionNotSupported -> {
+ is net.aliasvault.app.vaultstore.AppError.ServerVersionNotSupported,
+ is net.aliasvault.app.vaultstore.AppError.ServerUpdateRequired,
+ -> {
title = getString(R.string.server_version_not_supported_title)
message = getString(R.string.server_version_not_supported_message)
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/TotpClipboard.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/TotpClipboard.kt
index c85448b80..6a58d54bc 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/TotpClipboard.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/TotpClipboard.kt
@@ -37,9 +37,10 @@ object TotpClipboard {
* @param context The context used for the clipboard service.
* @param store The unlocked vault store to read the TOTP secret from.
* @param itemId The ID of the item being filled.
+ * @param manifestId The manifest the item belongs to.
*/
- fun copyCodeForItem(context: Context, store: VaultStore, itemId: String) {
- val totp = store.getTotpForItem(itemId) ?: return
+ fun copyCodeForItem(context: Context, store: VaultStore, itemId: String, manifestId: String) {
+ val totp = store.getTotpForItem(itemId, manifestId) ?: return
val code = TotpGenerator.generateCode(
secret = totp.secretKey,
period = totp.period,
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt
index 925c2b234..21d0003b4 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt
@@ -96,6 +96,14 @@ sealed class AppError(message: String, cause: Throwable? = null) : Exception(mes
cause: Throwable? = null,
) : AppError(message, cause)
+ /**
+ * Error indicating the server predates the API this app needs; shown as an error, not a logout.
+ */
+ class ServerUpdateRequired(
+ message: String = "Server update required",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
// Vault status errors
/**
* Error indicating vault merge required.
@@ -275,6 +283,14 @@ sealed class AppError(message: String, cause: Throwable? = null) : Exception(mes
cause: Throwable? = null,
) : AppError("Database init failed: $message", cause)
+ /**
+ * Error indicating no manifest is recorded yet, so nothing can be written until the vault has synced once.
+ */
+ class ManifestNotRecorded(
+ message: String = "No personal manifest recorded yet; sync once before writing",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
/**
* Error indicating failed to store vault.
*/
@@ -403,6 +419,7 @@ sealed class AppError(message: String, cause: Throwable? = null) : Exception(mes
is ClientVersionNotSupported -> "E-301"
is ServerVersionNotSupported -> "E-302"
is VaultVersionIncompatible -> "E-303"
+ is ServerUpdateRequired -> "E-304"
is VaultMergeRequired -> "E-401"
is VaultOutdated -> "E-402"
is SyncVaultFetchFailed -> "E-404"
@@ -426,6 +443,7 @@ sealed class AppError(message: String, cause: Throwable? = null) : Exception(mes
is StorageWriteFailed -> "E-602"
is DatabaseInitFailed -> "E-603"
is VaultStoreFailed -> "E-604"
+ is ManifestNotRecorded -> "E-605"
is VaultMergeFailed -> "E-701"
is MergeUploadFailed -> "E-705"
is VaultUploadFailed -> "E-801"
@@ -458,11 +476,11 @@ sealed class AppError(message: String, cause: Throwable? = null) : Exception(mes
}
/**
- * Check if this is a network error (offline mode).
+ * Check if this is a network error (offline mode). A timeout is not: the sync engine reports it as a failed sync.
*/
val isNetworkError: Boolean
get() = when (this) {
- is ServerUnavailable, is NetworkError, is Timeout -> true
+ is ServerUnavailable, is NetworkError -> true
else -> false
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
index 1f5acd5e3..c14accf2d 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
@@ -1,7 +1,5 @@
package net.aliasvault.app.vaultstore
-import android.database.Cursor
-import android.database.MatrixCursor
import android.util.Base64
import android.util.Log
import net.aliasvault.app.rustcore.JnaInitializer
@@ -15,6 +13,7 @@ import uniffi.aliasvault_core.SqliteMemoryDatabase
class VaultDatabase(
private val storageProvider: StorageProvider,
private val crypto: VaultCrypto,
+ private val metadata: VaultMetadataManager,
) {
companion object {
private const val TAG = "VaultDatabase"
@@ -126,18 +125,6 @@ class VaultDatabase(
return result.rows.map { row -> row.indices.associate { result.columns[it] to fromSqlValue(row[it]) } }
}
- /**
- * Run a SELECT and return its rows as a cursor, for positional column access.
- */
- fun queryCursor(sql: String, params: List<Any?> = emptyList()): Cursor {
- val result = connection().queryValues(sql, params.map(::toSqlValue))
- return MatrixCursor(result.columns.toTypedArray(), result.rows.size).also { cursor ->
- for (row in result.rows) {
- cursor.addRow(row.map(::fromSqlValue).toTypedArray())
- }
- }
- }
-
/**
* Run one INSERT, UPDATE or DELETE and return the number of rows it changed.
*/
@@ -181,11 +168,12 @@ class VaultDatabase(
}
/**
- * Commit a SQL transaction and persist the encrypted vault.
+ * Commit a SQL transaction, persist the encrypted vault and mark it as changed locally.
*/
fun commitTransaction() {
connection().executeBatch("COMMIT")
persistDatabaseToEncryptedStorage()
+ markMutated()
}
/**
@@ -195,6 +183,15 @@ class VaultDatabase(
connection().executeBatch("ROLLBACK")
}
+ /**
+ * Persist the in-memory database and mark it as changed locally, without committing a SQL transaction.
+ * Used after migrations, whose scripts manage their own transactions.
+ */
+ fun persistAndMarkDirty() {
+ persistDatabaseToEncryptedStorage()
+ markMutated()
+ }
+
/**
* Persist the in-memory database to encrypted local storage.
* This method can be called independently to persist the database without committing a transaction.
@@ -211,6 +208,15 @@ class VaultDatabase(
}
}
+ /**
+ * Mark the vault dirty and bump the mutation sequence, atomically from the sync engine's point of view,
+ * so the next sync pushes the local change instead of reporting the vault in sync.
+ */
+ private fun markMutated() {
+ metadata.setIsDirty(true)
+ metadata.incrementMutationSequence()
+ }
+
/**
* The database as SQLite file bytes, compacted first when no transaction is open.
*/
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPasskey.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPasskey.kt
index 084e928c6..347e63d09 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPasskey.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPasskey.kt
@@ -30,10 +30,10 @@ class VaultPasskey(
}
/**
- * Get all passkeys for an item.
+ * Get all passkeys for an item. Resolves the item's manifest when the caller does not hold it.
*/
- fun getPasskeysForItem(itemId: UUID): List<Passkey> {
- return passkeyRepository.getForItem(itemId)
+ fun getPasskeysForItem(itemId: UUID, manifestId: String? = null): List<Passkey> {
+ return passkeyRepository.getForItem(itemId, manifestId)
}
/**
@@ -94,49 +94,51 @@ class VaultPasskey(
/**
* Create a new item with an associated passkey.
+ *
+ * @param url The item's login URL, which the favicon was fetched for.
*/
fun createItemWithPasskey(
- rpId: String,
+ url: String,
userName: String?,
displayName: String,
passkey: Passkey,
logo: ByteArray? = null,
): Item {
- return passkeyRepository.createItemWithPasskey(rpId, userName, displayName, passkey, logo)
- }
-
- /**
- * Insert a new passkey into the database.
- */
- fun insertPasskey(passkey: Passkey) {
- passkeyRepository.insert(passkey)
+ return passkeyRepository.createItemWithPasskey(url, userName, displayName, passkey, logo)
}
/**
* Replace an existing passkey with a new one.
+ *
+ * @param url The login URL the favicon was fetched for.
*/
fun replacePasskey(
oldPasskeyId: UUID,
newPasskey: Passkey,
displayName: String,
+ url: String,
logo: ByteArray? = null,
) {
- passkeyRepository.replace(oldPasskeyId, newPasskey, displayName, logo)
+ passkeyRepository.replace(oldPasskeyId, newPasskey, displayName, url, logo)
}
/**
* Add a passkey to an existing Item (merge passkey into existing credential).
*
* @param itemId The UUID of the existing Item to add the passkey to.
+ * @param manifestId The manifest the item belongs to.
* @param passkey The passkey to add.
+ * @param url The login URL the favicon was fetched for.
* @param logo Optional logo to update/add.
*/
fun addPasskeyToExistingItem(
itemId: UUID,
+ manifestId: String,
passkey: Passkey,
+ url: String,
logo: ByteArray? = null,
) {
- passkeyRepository.addPasskeyToExistingItem(itemId, passkey, logo)
+ passkeyRepository.addPasskeyToExistingItem(itemId, manifestId, passkey, url, logo)
}
// endregion
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 bab42933f..dcc15236c 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
@@ -113,9 +113,10 @@ class VaultStore(
// region Composed Components
private val crypto = VaultCrypto(keystoreProvider, storageProvider)
- internal val database = VaultDatabase(storageProvider, crypto)
- private val itemRepository = net.aliasvault.app.vaultstore.repositories.ItemRepository(database)
internal val metadata = VaultMetadataManager(storageProvider)
+ internal val database = VaultDatabase(storageProvider, crypto, metadata)
+ private val itemRepository = net.aliasvault.app.vaultstore.repositories.ItemRepository(database)
+ private val itemStatsRepository = net.aliasvault.app.vaultstore.repositories.ItemStatsRepository(database)
private val auth = VaultAuth(
storageProvider,
onClearCache = {
@@ -399,17 +400,10 @@ 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.
+ * Commit a SQL transaction on the vault. The commit persists the vault and marks it dirty for the sync.
*/
fun commitTransaction() {
database.commitTransaction()
-
- // Atomically mark vault as dirty and increment mutation sequence
- // This ensures sync can properly detect local changes
- metadata.setIsDirty(true)
- metadata.incrementMutationSequence()
}
/**
@@ -420,17 +414,11 @@ class VaultStore(
}
/**
- * Persist the in-memory database to encrypted storage and mark as dirty.
- * Used after migrations where SQL handles its own transactions but we need to persist and sync.
- * This does NOT commit any SQL transaction - it just persists the current state of the database.
+ * Persist the in-memory database to encrypted storage and mark as dirty, without committing a SQL
+ * transaction. Used after migrations whose scripts manage their own transactions.
*/
fun persistAndMarkDirty() {
- database.persistDatabaseToEncryptedStorage()
-
- // Atomically mark vault as dirty and increment mutation sequence
- // This ensures sync can properly detect local changes
- metadata.setIsDirty(true)
- metadata.incrementMutationSequence()
+ database.persistAndMarkDirty()
}
/**
@@ -441,37 +429,31 @@ class VaultStore(
return itemRepository.getAll()
}
- /**
- * Get all archived items from the vault.
- */
- fun getArchivedItems(): List<Item> {
- return itemRepository.getArchived()
- }
-
- /**
- * Get the number of archived items in the vault.
- */
- fun getArchivedCount(): Int {
- return itemRepository.getArchivedCount()
- }
-
/**
* Get the first non-deleted TOTP code for an item, or null when none exists.
* Used by the autofill service to copy a credential's current TOTP code to
* the clipboard at fill time.
*/
- fun getTotpForItem(itemId: String): TotpCode? {
+ fun getTotpForItem(itemId: String, manifestId: String): TotpCode? {
if (!database.isVaultUnlocked()) {
return null
}
return try {
- itemRepository.getTotpForItem(itemId)
+ itemRepository.getTotpForItem(itemId, manifestId)
} catch (e: Exception) {
android.util.Log.e(TAG, "Error getting TOTP code for item", e)
null
}
}
+ /**
+ * Record one use of an item (autofill, copy or passkey assertion) in its usage statistics.
+ * Persists the vault and marks it dirty, so the next sync pushes it.
+ */
+ fun recordItemUsage(itemId: String, manifestId: String, action: net.aliasvault.app.vaultstore.repositories.ItemUsageAction) {
+ itemStatsRepository.recordUsage(itemId, manifestId, action)
+ }
+
/**
* Attempts to get all items using only the cached encryption key.
*/
@@ -780,10 +762,10 @@ class VaultStore(
}
/**
- * Get all passkeys for an item.
+ * Get all passkeys for an item. Resolves the item's manifest when the caller does not hold it.
*/
- fun getPasskeysForItem(itemId: java.util.UUID): List<net.aliasvault.app.vaultstore.models.Passkey> {
- return passkey.getPasskeysForItem(itemId)
+ fun getPasskeysForItem(itemId: java.util.UUID, manifestId: String? = null): List<net.aliasvault.app.vaultstore.models.Passkey> {
+ return passkey.getPasskeysForItem(itemId, manifestId)
}
/**
@@ -821,35 +803,29 @@ class VaultStore(
}
/**
- * Insert a new passkey into the database.
- */
- fun insertPasskey(passkeyObj: net.aliasvault.app.vaultstore.models.Passkey) {
- passkey.insertPasskey(passkeyObj)
- }
-
- /**
- * Create an item with a passkey.
+ * Create an item with a passkey. The url is written as the item's login URL and names the favicon's domain.
*/
fun createItemWithPasskey(
- rpId: String,
+ url: String,
userName: String?,
displayName: String,
passkeyObj: net.aliasvault.app.vaultstore.models.Passkey,
logo: ByteArray? = null,
): net.aliasvault.app.vaultstore.models.Item {
- return passkey.createItemWithPasskey(rpId, userName, displayName, passkeyObj, logo)
+ return passkey.createItemWithPasskey(url, userName, displayName, passkeyObj, logo)
}
/**
- * Replace an existing passkey with a new one.
+ * Replace an existing passkey with a new one. The url names the domain the favicon was fetched for.
*/
fun replacePasskey(
oldPasskeyId: java.util.UUID,
newPasskey: net.aliasvault.app.vaultstore.models.Passkey,
displayName: String,
+ url: String,
logo: ByteArray? = null,
) {
- passkey.replacePasskey(oldPasskeyId, newPasskey, displayName, logo)
+ passkey.replacePasskey(oldPasskeyId, newPasskey, displayName, url, logo)
}
/**
@@ -865,14 +841,17 @@ class VaultStore(
}
/**
- * Add a passkey to an existing Item (merge passkey into existing credential).
+ * Add a passkey to an existing Item (merge passkey into existing credential). The url names the domain
+ * the favicon was fetched for.
*/
fun addPasskeyToExistingItem(
itemId: java.util.UUID,
+ manifestId: String,
passkeyObj: net.aliasvault.app.vaultstore.models.Passkey,
+ url: String,
logo: ByteArray? = null,
) {
- passkey.addPasskeyToExistingItem(itemId, passkeyObj, logo)
+ passkey.addPasskeyToExistingItem(itemId, manifestId, passkeyObj, url, logo)
}
// endregion
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 4bfb1e818..bb7b698b0 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
@@ -8,7 +8,14 @@ import org.json.JSONArray
import org.json.JSONObject
/**
- * Vault sync runs through the Rust sync engine which handles the decision making and is cross-platform.
+ * The vault sync wrapper: one method per engine operation, adoption of what the engine reported, and the mapping of
+ * its failures into the native error. The driver below it is VaultSyncEngine, which turns the Rust engine's
+ * commands into host actions.
+ *
+ * When updating this logic, make sure to update the same logic on the other platforms:
+ * - core/client/src/sync/VaultSync.ts (shared core client for web apps)
+ * - apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
+ * - apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt (this file)
*/
class VaultSync(
private val vaultStore: VaultStore,
@@ -19,9 +26,8 @@ class VaultSync(
}
/**
- * Full vault sync: status check, then pull (and merge) or push as the server and local revisions decide.
+ * Full vault sync: status check, then pull (and merge) or push as the server and local revisions decide. Never throws.
*/
- @Suppress("TooGenericExceptionCaught")
suspend fun syncVaultWithServer(webApiService: WebApiService): VaultSyncResult {
val startNanos = System.nanoTime()
val metadata = vaultStore.metadata
@@ -29,13 +35,11 @@ class VaultSync(
try {
val wasDirty = metadata.getIsDirty()
val result = try {
- VaultSyncEngine(vaultStore, storageProvider, webApiService).run("fullSync")
- } catch (e: Exception) {
- return failedSync(driverError(e), metadata.getOfflineMode())
+ run("fullSync", webApiService)
+ } catch (e: AppError) {
+ return failedSync(e, metadata.getOfflineMode())
}
- adoptSyncSideEffects(result)
-
val wasOffline = result.optBoolean("wasOffline", false)
if (!result.optBoolean("success", false)) {
return failedSync(syncError(result), wasOffline)
@@ -45,6 +49,10 @@ class VaultSync(
return VaultSyncResult(false, SyncAction.ERROR, metadata.getVaultRevisionNumber(), true, code)
}
+ /*
+ * A vault that still has to be upgraded is reported, never migrated here: the app routes it to the upgrade
+ * page, which asks first when the migration signs out every other pre-format client (see migrateVaultManifest).
+ */
val hasNewVault = result.optBoolean("hasNewVault", false)
val action = when {
hasNewVault && wasDirty -> SyncAction.MERGED
@@ -67,40 +75,65 @@ class VaultSync(
}
/**
- * A failed sync return.
+ * One status call: whether the server holds newer state than this device.
*/
- private fun failedSync(error: AppError, wasOffline: Boolean): VaultSyncResult {
- Log.e(TAG, "Sync failed (${error.code}): ${error.message}", error.cause)
- return VaultSyncResult(false, SyncAction.ERROR, vaultStore.metadata.getVaultRevisionNumber(), wasOffline, error.code, error.message)
+ suspend fun checkVaultVersion(webApiService: WebApiService): VaultVersionCheckResult {
+ val result = run("statusCheck", webApiService)
+ if (result.optBoolean("isOffline", false)) {
+ vaultStore.metadata.setOfflineMode(true)
+ throw AppError.ServerUnavailable(0)
+ }
+ if (result.optBoolean("requiresLogout", false) || !result.optBoolean("success", false)) {
+ throw syncError(result)
+ }
+ vaultStore.metadata.setOfflineMode(false)
+ return VaultVersionCheckResult(result.optBoolean("hasNewerVault", false), vaultStore.getSyncState())
}
- /**
- * An error the driver itself threw (a request it could not build, a command it could not decode).
- */
- 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
* 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")
suspend fun resolveVaultKey(webApiService: WebApiService, derivedKeyBase64: String): String {
- val result = try {
- VaultSyncEngine(vaultStore, storageProvider, webApiService).run("resolveVaultKey", encryptionKey = derivedKeyBase64)
- } catch (e: Exception) {
- throw driverError(e)
- }
+ val result = run("resolveVaultKey", webApiService, encryptionKey = derivedKeyBase64)
if (!result.optBoolean("success", false)) {
throw syncError(result)
}
val key = result.optString("encryptionKey").takeIf { it.isNotEmpty() } ?: derivedKeyBase64
vaultStore.adoptEncryptionKey(key)
- result.optJSONObject("sessionUpdates")?.optString("accountPrivateKey")?.takeIf { it.isNotEmpty() }?.let { vaultStore.accountPrivateKey = it }
return key
}
/**
- * Push any pending local changes.
+ * Classify the pending manifest migration as the engine sees it: `none`, `schema-rebuild` (runs unattended) or
+ * `storage-format-upgrade` (the app asks first). A vault still on the sqlite-blob chain classifies as `none`.
+ */
+ suspend fun getVaultMigrationStatus(webApiService: WebApiService): String {
+ val status = run("migrationStatus", webApiService)
+ return status.optString("kind").takeIf { it.isNotEmpty() } ?: "storage-format-upgrade"
+ }
+
+ /**
+ * Bring the local vault onto the current storage model (a schema rebuild after an app update, or the one-time
+ * account-key upgrade of a legacy vault) and push it. Driven by the app's upgrade page only: a sync never runs
+ * it on its own, because the storage format move signs out every other client that predates the format. Never throws.
+ */
+ suspend fun migrateVaultManifest(webApiService: WebApiService): VaultMigrationResult {
+ val result = try {
+ run("migrateManifest", webApiService)
+ } catch (e: AppError) {
+ return failedMigration(e)
+ }
+ if (!result.optBoolean("success", false)) {
+ return failedMigration(syncError(result))
+ }
+ val pushed = result.optBoolean("pushed", false)
+ Log.i(TAG, "Manifest migration complete: pushed=$pushed")
+ return VaultMigrationResult(true, pushed)
+ }
+
+ /**
+ * Push the pending local changes (after a native mutation such as an autofill link or a passkey creation).
*/
suspend fun mutateVault(webApiService: WebApiService): Boolean {
val result = syncVaultWithServer(webApiService)
@@ -111,31 +144,24 @@ class VaultSync(
}
/**
- * Issue a status call.
+ * Run one engine operation and adopt what it reported. A driver failure surfaces as the native error.
*/
@Suppress("TooGenericExceptionCaught")
- suspend fun checkVaultVersion(webApiService: WebApiService): VaultVersionCheckResult {
+ private suspend fun run(operation: String, webApiService: WebApiService, encryptionKey: String? = null): JSONObject {
val result = try {
- VaultSyncEngine(vaultStore, storageProvider, webApiService).run("statusCheck")
+ VaultSyncEngine(vaultStore, storageProvider, webApiService).run(operation, encryptionKey = encryptionKey)
} catch (e: Exception) {
throw driverError(e)
}
- result.optString("serverVersion").takeIf { it.isNotEmpty() }?.let { vaultStore.metadata.setServerVersion(it) }
- if (result.optBoolean("isOffline", false)) {
- vaultStore.metadata.setOfflineMode(true)
- throw AppError.ServerUnavailable(0)
- }
- if (result.optBoolean("requiresLogout", false) || !result.optBoolean("success", false)) {
- throw syncError(result)
- }
- vaultStore.metadata.setOfflineMode(false)
- return VaultVersionCheckResult(result.optBoolean("hasNewerVault", false), vaultStore.getSyncState())
+ adoptSyncResult(result)
+ return result
}
/**
- * Persist sync results.
+ * Persist what the engine reported: server version, offline mode, session values it changed, and the email
+ * routing a pulled vault came with. Capabilities are not stored: the mobile app has no capability gate yet.
*/
- private fun adoptSyncSideEffects(result: JSONObject) {
+ private fun adoptSyncResult(result: JSONObject) {
result.optString("serverVersion").takeIf { it.isNotEmpty() }?.let { vaultStore.metadata.setServerVersion(it) }
if (result.has("isOfflineMode")) {
vaultStore.metadata.setOfflineMode(result.optBoolean("isOfflineMode", false))
@@ -163,38 +189,11 @@ class VaultSync(
}
/**
- * Classify the pending manifest migration as the engine sees it: `none`, `schema-rebuild` (runs unattended) or
- * `storage-format-upgrade` (the app asks first). A vault still on the sqlite-blob chain classifies as `none`.
- */
- @Suppress("TooGenericExceptionCaught")
- suspend fun getVaultMigrationStatus(webApiService: WebApiService): String {
- val status = try {
- VaultSyncEngine(vaultStore, storageProvider, webApiService).run("migrationStatus")
- } catch (e: Exception) {
- throw driverError(e)
- }
- return status.optString("kind").takeIf { it.isNotEmpty() } ?: "storage-format-upgrade"
- }
-
- /**
- * Bring the local vault onto the current storage model (a schema rebuild after an app update, or the one-time
- * account-key upgrade of a legacy vault) and push it. Driven by the app's upgrade page only: a sync never runs
- * it on its own, because the storage format move signs out every other client that predates the format.
+ * A failed sync return.
*/
- @Suppress("TooGenericExceptionCaught")
- suspend fun migrateVaultManifest(webApiService: WebApiService): VaultMigrationResult {
- val result = try {
- VaultSyncEngine(vaultStore, storageProvider, webApiService).run("migrateManifest")
- } catch (e: Exception) {
- return failedMigration(driverError(e))
- }
- adoptSyncSideEffects(result)
- if (!result.optBoolean("success", false)) {
- return failedMigration(syncError(result))
- }
- val pushed = result.optBoolean("pushed", false)
- Log.i(TAG, "Manifest migration complete: pushed=$pushed")
- return VaultMigrationResult(true, pushed)
+ private fun failedSync(error: AppError, wasOffline: Boolean): VaultSyncResult {
+ Log.e(TAG, "Sync failed (${error.code}): ${error.message}", error.cause)
+ return VaultSyncResult(false, SyncAction.ERROR, vaultStore.metadata.getVaultRevisionNumber(), wasOffline, error.code, error.message)
}
/**
@@ -206,7 +205,12 @@ class VaultSync(
}
/**
- * Convert JSON result to AppError.
+ * An error the driver itself threw (a request it could not build, a command it could not decode).
+ */
+ private fun driverError(e: Exception): AppError = e as? AppError ?: AppError.SyncEngineFailed(e.toString(), e)
+
+ /**
+ * The engine's failure as the native error: a forced logout by its reason, else by its error code.
*/
private fun syncError(result: JSONObject): AppError {
when (result.optString("errorKey")) {
@@ -221,7 +225,7 @@ class VaultSync(
return when (result.optString("errorCode")) {
"E-805" -> AppError.Timeout()
"E-804" -> AppError.VaultTooLarge()
- "E-903" -> AppError.ServerVersionNotSupported()
+ "E-903" -> AppError.ServerUpdateRequired()
"E-901" -> AppError.MigrationCheckFailed(message)
"E-505" -> AppError.ServerUnavailable(0)
"E-506" -> AppError.ServerError(message)
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 7b00f552e..887fadb3d 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
@@ -6,7 +6,8 @@ import java.util.UUID
/**
* Item model representing vault entries in the new field-based data model.
*
- * @property id The unique identifier of the item.
+ * @property id The identifier of the item within its manifest; only (manifestId, id) names one row.
+ * @property manifestId The manifest the item belongs to.
* @property name The display name of the item.
* @property itemType The type of item (Login, Alias, CreditCard, Note).
* @property logo The logo image data in bytes.
@@ -21,6 +22,7 @@ import java.util.UUID
*/
data class Item(
val id: UUID,
+ val manifestId: String,
val name: String?,
val itemType: String,
val logo: ByteArray?,
@@ -87,11 +89,11 @@ data class Item(
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Item
- return id == other.id
+ return id == other.id && manifestId.equals(other.manifestId, ignoreCase = true)
}
override fun hashCode(): Int {
- return id.hashCode()
+ return 31 * id.hashCode() + manifestId.lowercase().hashCode()
}
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Passkey.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Passkey.kt
index 6021e2729..a2eac24e4 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Passkey.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Passkey.kt
@@ -21,6 +21,12 @@ data class Passkey(
*/
val parentItemId: UUID,
+ /**
+ * The manifest the passkey and its item belong to. Null on a passkey not yet written: the INSERT stamps
+ * it from the item.
+ */
+ val manifestId: String?,
+
/**
* Relying party identifier (domain).
*/
@@ -56,6 +62,11 @@ data class Passkey(
*/
val displayName: String,
+ /**
+ * Opaque extra data, not written by any client today.
+ */
+ val additionalData: ByteArray? = null,
+
/**
* The creation date of the passkey.
*/
@@ -79,6 +90,7 @@ data class Passkey(
if (id != other.id) return false
if (parentItemId != other.parentItemId) return false
+ if (manifestId != other.manifestId) return false
if (rpId != other.rpId) return false
if (userHandle != null) {
if (other.userHandle == null) return false
@@ -92,6 +104,10 @@ data class Passkey(
if (!prfKey.contentEquals(other.prfKey)) return false
} else if (other.prfKey != null) return false
if (displayName != other.displayName) return false
+ if (additionalData != null) {
+ if (other.additionalData == null) return false
+ if (!additionalData.contentEquals(other.additionalData)) return false
+ } else if (other.additionalData != null) return false
if (createdAt != other.createdAt) return false
if (updatedAt != other.updatedAt) return false
if (isDeleted != other.isDeleted) return false
@@ -102,6 +118,7 @@ data class Passkey(
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + parentItemId.hashCode()
+ result = 31 * result + (manifestId?.hashCode() ?: 0)
result = 31 * result + rpId.hashCode()
result = 31 * result + (userHandle?.contentHashCode() ?: 0)
result = 31 * result + (userName?.hashCode() ?: 0)
@@ -109,6 +126,7 @@ data class Passkey(
result = 31 * result + privateKey.contentHashCode()
result = 31 * result + (prfKey?.contentHashCode() ?: 0)
result = 31 * result + displayName.hashCode()
+ result = 31 * result + (additionalData?.contentHashCode() ?: 0)
result = 31 * result + createdAt.hashCode()
result = 31 * result + updatedAt.hashCode()
result = 31 * result + isDeleted.hashCode()
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemQueries.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemQueries.kt
index 36e512729..94a4bad52 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemQueries.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemQueries.kt
@@ -1,30 +1,36 @@
package net.aliasvault.app.vaultstore.queries
/**
- * SQL query constants for Item operations.
- * Centralizes all item-related queries to avoid duplication.
- * Mirrors the browser extension and React Native implementation.
+ * SQL query constants for the item reads the autofill service needs.
+ * Every join and lookup is keyed by (ManifestId, Id) because the same id can exist in more than one manifest.
*/
object ItemQueries {
/**
* Base SELECT for items with common fields.
- * Includes LEFT JOIN to Logos and subqueries for HasPasskey/HasAttachment/HasTotp.
+ * Includes a LEFT JOIN to the item's logo row and scoped subqueries for HasPasskey/HasAttachment/HasTotp.
*/
const val BASE_SELECT = """
SELECT DISTINCT
i.Id,
+ i.ManifestId,
i.Name,
i.ItemType,
i.FolderId,
l.FileData as Logo,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
+ CASE WHEN EXISTS (
+ SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.ManifestId = i.ManifestId AND pk.IsDeleted = 0
+ ) THEN 1 ELSE 0 END as HasPasskey,
+ CASE WHEN EXISTS (
+ SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.ManifestId = i.ManifestId AND att.IsDeleted = 0
+ ) THEN 1 ELSE 0 END as HasAttachment,
+ CASE WHEN EXISTS (
+ SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.ManifestId = i.ManifestId AND tc.IsDeleted = 0
+ ) THEN 1 ELSE 0 END as HasTotp,
i.CreatedAt,
i.UpdatedAt,
i.ArchivedAt
FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id
+ LEFT JOIN Logos l ON i.LogoId = l.Id AND l.ManifestId = i.ManifestId
"""
/**
@@ -37,42 +43,16 @@ object ItemQueries {
"""
/**
- * Get all archived items. Trashed items are excluded: an item that is both archived and
- * trashed belongs in "Recently Deleted", which is the more urgent of the two states.
- */
- const val GET_ARCHIVED = """
- $BASE_SELECT
- WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NOT NULL
- ORDER BY i.ArchivedAt DESC
- """
-
- /**
- * Count of archived items.
- */
- const val COUNT_ARCHIVED = """
- SELECT COUNT(*) as count
- FROM Items
- WHERE IsDeleted = 0 AND DeletedAt IS NULL AND ArchivedAt IS NOT NULL
- """
-
- /**
- * Get a single item by ID.
- */
- const val GET_BY_ID = """
- $BASE_SELECT
- WHERE i.Id = ? AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- """
-
- /**
- * Get field values for multiple items.
- * @param itemCount Number of items (for placeholder generation)
+ * Get field values for multiple items, matched on the whole (ManifestId, ItemId) key.
+ * @param itemCount Number of items (one `(?, ?)` pair each, bound as manifestId, itemId, ...)
* @return Query with placeholders
*/
fun getFieldValuesForItems(itemCount: Int): String {
- val placeholders = Array(itemCount) { "?" }.joinToString(",")
+ val placeholders = Array(itemCount) { "(?, ?)" }.joinToString(", ")
return """
SELECT
fv.ItemId,
+ fv.ManifestId,
fv.FieldKey,
fv.FieldDefinitionId,
fd.Label as CustomLabel,
@@ -82,74 +62,20 @@ object ItemQueries {
fv.Value,
fv.Weight as DisplayOrder
FROM FieldValues fv
- LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id
- WHERE fv.ItemId IN ($placeholders)
+ LEFT JOIN FieldDefinitions fd ON fd.ManifestId = fv.ManifestId AND fd.Id = fv.FieldDefinitionId
+ WHERE (fv.ManifestId, fv.ItemId) IN (VALUES $placeholders)
AND fv.IsDeleted = 0
ORDER BY fv.ItemId, fv.Weight
""".trimIndent()
}
/**
- * Get field values for a single item.
+ * Get an item's TOTP codes. Binds (itemId, manifestId).
*/
- const val GET_FIELD_VALUES_FOR_ITEM = """
- SELECT
- fv.FieldKey,
- fv.FieldDefinitionId,
- fd.Label as CustomLabel,
- fd.FieldType as CustomFieldType,
- fd.IsHidden as CustomIsHidden,
- fd.EnableHistory as CustomEnableHistory,
- fv.Value,
- fv.Weight as DisplayOrder
- FROM FieldValues fv
- LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id
- WHERE fv.ItemId = ? AND fv.IsDeleted = 0
- ORDER BY fv.Weight
- """
-
- /**
- * Get all unique email addresses from field values.
- */
- const val GET_ALL_EMAIL_ADDRESSES = """
- SELECT DISTINCT fv.Value as Email
- FROM FieldValues fv
- INNER JOIN Items i ON fv.ItemId = i.Id
- WHERE fv.FieldKey = ?
- AND fv.IsDeleted = 0
- AND i.IsDeleted = 0
- AND i.DeletedAt IS NULL
- """
-
- /**
- * Get all recently deleted items (in trash).
- */
- const val GET_RECENTLY_DELETED = """
- SELECT DISTINCT
- i.Id,
- i.Name,
- i.ItemType,
- i.FolderId,
- l.FileData as Logo,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
- i.CreatedAt,
- i.UpdatedAt,
- i.DeletedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id
- WHERE i.IsDeleted = 0 AND i.DeletedAt IS NOT NULL
- ORDER BY i.DeletedAt DESC
- """
-
- /**
- * Count of recently deleted items.
- */
- const val COUNT_RECENTLY_DELETED = """
- SELECT COUNT(*) as count
- FROM Items
- WHERE IsDeleted = 0 AND DeletedAt IS NOT NULL
+ const val GET_TOTP_CODES_FOR_ITEM = """
+ SELECT Id, Name, SecretKey, Algorithm, Digits, Period, ItemId
+ FROM TotpCodes
+ WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0
"""
/**
@@ -160,53 +86,9 @@ object ItemQueries {
"""
/**
- * Move item to trash (set DeletedAt).
- */
- const val TRASH_ITEM = """
- UPDATE Items SET DeletedAt = ?, UpdatedAt = ? WHERE Id = ?
- """
-
- /**
- * Restore item from trash (clear DeletedAt).
- */
- const val RESTORE_ITEM = """
- UPDATE Items SET DeletedAt = NULL, UpdatedAt = ? WHERE Id = ?
- """
-
- /**
- * Archive an item (set ArchivedAt).
- */
- const val ARCHIVE_ITEM = """
- UPDATE Items SET ArchivedAt = ?, UpdatedAt = ? WHERE Id = ? AND IsDeleted = 0 AND ArchivedAt IS NULL
- """
-
- /**
- * Unarchive an item (clear ArchivedAt).
- */
- const val UNARCHIVE_ITEM = """
- UPDATE Items SET ArchivedAt = NULL, UpdatedAt = ? WHERE Id = ? AND IsDeleted = 0 AND ArchivedAt IS NOT NULL
- """
-
- /**
- * Convert item to tombstone for permanent deletion.
- */
- const val TOMBSTONE_ITEM = """
- UPDATE Items
- SET Name = NULL,
- ItemType = NULL,
- LogoId = NULL,
- FolderId = NULL,
- DeletedAt = NULL,
- ArchivedAt = NULL,
- IsDeleted = 1,
- UpdatedAt = ?
- WHERE Id = ?
- """
-
- /**
- * Get folder data for building folder paths.
+ * Get folder data for building folder paths, one tree per manifest.
*/
const val GET_ALL_FOLDERS = """
- SELECT Id, Name, ParentFolderId FROM Folders WHERE IsDeleted = 0
+ SELECT Id, ManifestId, Name, ParentFolderId FROM Folders WHERE IsDeleted = 0
"""
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemStatsQueries.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemStatsQueries.kt
new file mode 100644
index 000000000..9036e2928
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemStatsQueries.kt
@@ -0,0 +1,35 @@
+package net.aliasvault.app.vaultstore.queries
+
+/**
+ * SQL query constants for per-item usage statistics.
+ */
+object ItemStatsQueries {
+ /**
+ * Create the stats row for an item on its first recorded use. Binds (manifestId, itemId, now, now).
+ */
+ const val INSERT_ROW = """
+ INSERT OR IGNORE INTO ItemStats (
+ ManifestId, Id, LastUsedAt, UseCount, LastAutofilledAt, AutofillCount,
+ LastCopiedAt, CopyCount, LastPasskeyAuthAt, PasskeyAuthCount, CreatedAt, UpdatedAt, IsDeleted
+ )
+ VALUES (?, ?, NULL, 0, NULL, 0, NULL, 0, NULL, 0, ?, ?, 0)
+ """
+
+ /**
+ * Record one use of an item, bumping the aggregate and the per-action pair. The column names come from
+ * a closed set, never from caller input. IsDeleted is cleared because a use resurrects a row the pruner
+ * tombstoned. Binds (now, now, now, manifestId, itemId).
+ */
+ fun forAction(lastColumn: String, countColumn: String): String {
+ return """
+ UPDATE ItemStats
+ SET LastUsedAt = ?,
+ UseCount = UseCount + 1,
+ $lastColumn = ?,
+ $countColumn = $countColumn + 1,
+ UpdatedAt = ?,
+ IsDeleted = 0
+ WHERE ManifestId = ? AND Id = ?
+ """.trimIndent()
+ }
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt
index 86eed7838..972b2121a 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt
@@ -1,144 +1,130 @@
package net.aliasvault.app.vaultstore.queries
+import net.aliasvault.app.vaultstore.models.FieldKey
+
/**
* SQL query constants for Passkey operations.
- * Centralizes all passkey-related queries to avoid duplication.
*/
object PasskeyQueries {
/**
- * Base SELECT for passkeys with common fields.
+ * Base SELECT for passkeys without item information.
*/
const val BASE_SELECT = """
- SELECT Id, ItemId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey,
- DisplayName, CreatedAt, UpdatedAt, IsDeleted
- FROM Passkeys
+ SELECT p.Id, p.ItemId, p.ManifestId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey,
+ p.DisplayName, p.AdditionalData, p.CreatedAt, p.UpdatedAt, p.IsDeleted
+ FROM Passkeys p
+ """
+
+ /**
+ * Base SELECT for passkeys joined to their live (not trashed, not tombstoned) item.
+ */
+ const val BASE_SELECT_WITH_ITEM = """
+ SELECT p.Id, p.ItemId, p.ManifestId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey,
+ p.DisplayName, p.AdditionalData, p.CreatedAt, p.UpdatedAt, p.IsDeleted,
+ i.Name as ServiceName,
+ i.CreatedAt as ItemCreatedAt,
+ i.UpdatedAt as ItemUpdatedAt,
+ (SELECT fv.Value FROM FieldValues fv
+ WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = '${FieldKey.LOGIN_USERNAME}' AND fv.IsDeleted = 0
+ LIMIT 1) as Username,
+ (SELECT fv.Value FROM FieldValues fv
+ WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = '${FieldKey.LOGIN_EMAIL}' AND fv.IsDeleted = 0
+ LIMIT 1) as Email
+ FROM Passkeys p
+ INNER JOIN Items i ON p.ItemId = i.Id AND i.ManifestId = p.ManifestId
"""
/**
- * Get a passkey by its credential ID.
+ * Get a passkey by its ID (which is also the WebAuthn credential ID), only while its item is live.
*/
- const val GET_BY_CREDENTIAL_ID = """
- $BASE_SELECT
- WHERE Id = ? AND IsDeleted = 0
+ const val GET_BY_ID = """
+ $BASE_SELECT_WITH_ITEM
+ WHERE p.Id = ? AND p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
LIMIT 1
"""
/**
- * Get all passkeys for an item.
+ * Get all passkeys for an item. Binds (itemId, manifestId).
*/
const val GET_BY_ITEM_ID = """
$BASE_SELECT
- WHERE ItemId = ? AND IsDeleted = 0
- ORDER BY CreatedAt DESC
+ WHERE p.ItemId = ? AND p.ManifestId = ? AND p.IsDeleted = 0
+ ORDER BY p.CreatedAt DESC
"""
/**
- * Get all passkeys for a relying party (rpId).
+ * Get all passkeys for a relying party (rpId) whose item is live.
*/
const val GET_BY_RP_ID = """
- $BASE_SELECT
- WHERE RpId = ? AND IsDeleted = 0
- ORDER BY CreatedAt DESC
+ $BASE_SELECT_WITH_ITEM
+ WHERE p.RpId = ? AND p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
+ ORDER BY p.CreatedAt DESC
"""
/**
- * Get a passkey by its ID.
+ * Get every passkey whose item is live, with the item's display info.
*/
- const val GET_BY_ID = """
- $BASE_SELECT
- WHERE Id = ? AND IsDeleted = 0
- LIMIT 1
+ const val GET_ALL_WITH_ITEMS = """
+ $BASE_SELECT_WITH_ITEM
+ WHERE p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
+ ORDER BY p.CreatedAt DESC
"""
/**
- * Insert a new passkey.
+ * Insert a new passkey, stamped with the manifest of the item it hangs off. Binds the item id twice:
+ * once for the column, once for the manifest lookup, followed by the fallback manifest.
*/
const val INSERT = """
- INSERT INTO Passkeys (Id, ItemId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey,
- DisplayName, CreatedAt, UpdatedAt, IsDeleted, ManifestId)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE((SELECT ManifestId FROM Items WHERE Id = ?), ?))
+ INSERT INTO Passkeys (Id, ItemId, ManifestId, RpId, UserHandle, PublicKey, PrivateKey,
+ PrfKey, DisplayName, AdditionalData, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, COALESCE((SELECT ManifestId FROM Items WHERE Id = ?), ?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
/**
- * Get passkeys with item info for a specific rpId.
- * Joins with Items and FieldValues to get display info.
+ * Soft delete a passkey. Binds (now, id, manifestId).
*/
- val GET_WITH_CREDENTIAL_INFO = """
- SELECT p.Id, p.ItemId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey,
- p.DisplayName, p.CreatedAt, p.UpdatedAt, p.IsDeleted,
- i.Name,
- fv_username.Value as Username,
- fv_email.Value as Email
- FROM Passkeys p
- INNER JOIN Items i ON p.ItemId = i.Id
- LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
- AND fv_username.FieldKey = ?
- AND fv_username.IsDeleted = 0
- LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id
- AND fv_email.FieldKey = ?
- AND fv_email.IsDeleted = 0
- WHERE p.RpId = ? AND p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- ORDER BY p.CreatedAt DESC
- """.trimIndent()
+ const val SOFT_DELETE = """
+ UPDATE Passkeys SET IsDeleted = 1, UpdatedAt = ? WHERE Id = ? AND ManifestId = ?
+ """
/**
- * Get ALL Login items that don't have a passkey yet (no URL filtering).
- * Used with RustCredentialMatcher for intelligent, cross-platform consistent filtering.
+ * Get ALL active Login items that don't have a passkey yet (no URL filtering).
+ * Used with RustItemMatcher for intelligent, cross-platform consistent filtering.
*/
val GET_ALL_ITEMS_WITHOUT_PASSKEY = """
- SELECT i.Id, i.Name, i.CreatedAt, i.UpdatedAt,
+ SELECT i.Id, i.ManifestId, i.Name, i.CreatedAt, i.UpdatedAt,
GROUP_CONCAT(DISTINCT fv_url.Value) as Urls,
fv_username.Value as Username,
fv_email.Value as Email,
fv_password.Value as Password
FROM Items i
- LEFT JOIN FieldValues fv_url ON fv_url.ItemId = i.Id
+ LEFT JOIN FieldValues fv_url ON fv_url.ItemId = i.Id AND fv_url.ManifestId = i.ManifestId
AND fv_url.FieldKey = ?
AND fv_url.IsDeleted = 0
- LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
+ LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id AND fv_username.ManifestId = i.ManifestId
AND fv_username.FieldKey = ?
AND fv_username.IsDeleted = 0
- LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id
+ LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id AND fv_email.ManifestId = i.ManifestId
AND fv_email.FieldKey = ?
AND fv_email.IsDeleted = 0
- LEFT JOIN FieldValues fv_password ON fv_password.ItemId = i.Id
+ LEFT JOIN FieldValues fv_password ON fv_password.ItemId = i.Id AND fv_password.ManifestId = i.ManifestId
AND fv_password.FieldKey = ?
AND fv_password.IsDeleted = 0
WHERE i.IsDeleted = 0
AND i.DeletedAt IS NULL
+ AND i.ArchivedAt IS NULL
AND i.ItemType = 'Login'
AND NOT EXISTS (
SELECT 1 FROM Passkeys p
- WHERE p.ItemId = i.Id AND p.IsDeleted = 0
+ WHERE p.ItemId = i.Id AND p.ManifestId = i.ManifestId AND p.IsDeleted = 0
)
- GROUP BY i.Id
+ GROUP BY i.ManifestId, i.Id
ORDER BY i.UpdatedAt DESC
""".trimIndent()
/**
- * Get all passkeys with their associated items in a single query.
- */
- val GET_ALL_WITH_ITEMS = """
- SELECT
- p.Id, p.ItemId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey,
- p.DisplayName, p.CreatedAt as PasskeyCreatedAt, p.UpdatedAt as PasskeyUpdatedAt, p.IsDeleted as PasskeyIsDeleted,
- i.Id as ItemId, i.Name, i.CreatedAt as ItemCreatedAt, i.UpdatedAt as ItemUpdatedAt,
- fv_username.Value as Username,
- fv_email.Value as Email
- FROM Passkeys p
- INNER JOIN Items i ON p.ItemId = i.Id
- LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
- AND fv_username.FieldKey = ?
- AND fv_username.IsDeleted = 0
- LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id
- AND fv_email.FieldKey = ?
- AND fv_email.IsDeleted = 0
- WHERE p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- ORDER BY p.CreatedAt DESC
- """.trimIndent()
-
- /**
- * Create an Item record for passkey registration.
+ * Create an Item record for passkey registration, stamped with the manifest of its folder (or the
+ * fallback manifest when it has none).
*/
const val CREATE_ITEM = """
INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted, DeletedAt, ManifestId)
@@ -146,7 +132,7 @@ object PasskeyQueries {
"""
/**
- * Insert a URL field value.
+ * Insert a field value, stamped with the manifest of its item.
*/
const val INSERT_FIELD_VALUE = """
INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted, ManifestId)
@@ -154,60 +140,71 @@ object PasskeyQueries {
"""
/**
- * Update item's UpdatedAt timestamp.
+ * Update an item's UpdatedAt timestamp. Binds (now, id, manifestId).
*/
const val UPDATE_ITEM_TIMESTAMP = """
- UPDATE Items SET UpdatedAt = ? WHERE Id = ?
+ UPDATE Items SET UpdatedAt = ? WHERE Id = ? AND ManifestId = ?
"""
/**
- * Get logo ID from an item.
+ * Get the logo ID of an item. Binds (id, manifestId).
*/
const val GET_LOGO_ID_FROM_ITEM = """
- SELECT LogoId FROM Items WHERE Id = ?
+ SELECT LogoId FROM Items WHERE Id = ? AND ManifestId = ?
"""
}
/**
- * SQL query constants for Logo operations used during passkey/item creation.
+ * SQL query constants for the Logos rows the passkey flows read and write.
+ * Mirrors core/client LogoQueries.ts.
*/
object LogoQueries {
/**
- * Insert a new logo.
+ * The id of the logo with this kind and key inside one manifest. Binds (manifestId, kind, source).
*/
- const val INSERT = """
- INSERT INTO Logos (Id, Kind, Source, ManifestId, FileData, MimeType, FetchedAt, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, 'favicon', ?, ?, ?, ?, ?, ?, ?, ?)
+ const val GET_ID_FOR_KEY = """
+ SELECT Id FROM Logos
+ WHERE ManifestId = ? AND Kind = ? AND Source = ? AND IsDeleted = 0
+ LIMIT 1
"""
/**
- * Update logo file data.
+ * The best row to copy from when a manifest needs a logo it does not have but the vault does. Binds (kind, source).
*/
- const val UPDATE_FILE_DATA = """
- UPDATE Logos
- SET FileData = ?,
- UpdatedAt = ?
- WHERE Id = ?
+ const val GET_BEST_FOR_KEY = """
+ SELECT FileData, MimeType, Name FROM Logos
+ WHERE Kind = ? AND Source = ? AND IsDeleted = 0
+ ORDER BY (FileData IS NOT NULL AND LENGTH(FileData) > 0) DESC, UpdatedAt DESC
+ LIMIT 1
"""
/**
- * Get logo by source.
+ * The kind and key of an existing logo. Binds (id, manifestId).
*/
- const val GET_BY_SOURCE = """
- SELECT Id, IsDeleted FROM Logos WHERE Source = ? LIMIT 1
+ const val GET_BY_ID = """
+ SELECT Id, Kind, Source, Name FROM Logos
+ WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0
+ LIMIT 1
"""
/**
- * Restore a soft-deleted logo.
+ * Insert or refresh a logo. Binds (id, kind, source, manifestId, fileData, mimeType, name, now, now).
*/
- const val RESTORE = """
- UPDATE Logos SET IsDeleted = 0, UpdatedAt = ? WHERE Id = ?
+ const val UPSERT = """
+ INSERT INTO Logos (Id, Kind, Source, ManifestId, FileData, MimeType, Name, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
+ ON CONFLICT(ManifestId, Id) DO UPDATE SET
+ FileData = excluded.FileData,
+ MimeType = excluded.MimeType,
+ Name = COALESCE(excluded.Name, Logos.Name),
+ UpdatedAt = excluded.UpdatedAt,
+ IsDeleted = 0
"""
/**
- * Update item logo ID.
+ * Point an item at a logo. Binds (logoId, now, itemId, manifestId).
*/
const val UPDATE_ITEM_LOGO_ID = """
- UPDATE Items SET LogoId = ?, UpdatedAt = ? WHERE Id = ?
+ UPDATE Items SET LogoId = ?, UpdatedAt = ? WHERE Id = ? AND ManifestId = ?
"""
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt
index fd4cceed9..9a2500877 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt
@@ -1,12 +1,12 @@
package net.aliasvault.app.vaultstore.repositories
import net.aliasvault.app.utils.DateHelpers
+import net.aliasvault.app.vaultstore.AppError
import net.aliasvault.app.vaultstore.VaultDatabase
import java.util.UUID
/**
* Base repository class with common database operations.
- * Provides transaction handling, soft delete, and other shared functionality.
*/
open class BaseRepository(
/** The database component used for executing queries. */
@@ -14,17 +14,37 @@ open class BaseRepository(
) {
/**
* The manifest new rows outside any folder or item are stamped with: the personal manifest. Rows inside a
- * folder or item take that parent's manifest through the SQL instead.
+ * folder or item take that parent's manifest through the SQL instead. Throws when no manifest has been
+ * recorded yet, since an unstamped row would make every later push of the vault fail.
*/
protected fun activeManifestId(): String {
- return database.getPersonalManifestId() ?: ""
+ return database.getPersonalManifestId() ?: throw AppError.ManifestNotRecorded()
+ }
+
+ /**
+ * The manifest a manifest-scoped row belongs to, looked up from the row itself: the personal manifest when
+ * the row exists there, else the lowest manifest id holding it. Null when no such row exists.
+ */
+ protected fun resolveRowManifestId(table: String, id: String, column: String = "Id"): String? {
+ val rows = executeQuery("SELECT ManifestId FROM $table WHERE $column = ? ORDER BY ManifestId", arrayOf(id))
+ val manifestIds = rows.mapNotNull { it["ManifestId"] as? String }
+ if (manifestIds.isEmpty()) return null
+ val personal = database.getPersonalManifestId()
+ return manifestIds.firstOrNull { it == personal } ?: manifestIds.first()
+ }
+
+ /**
+ * The grouping key of a manifest-scoped row, for joining rows of one query to rows of another in memory.
+ */
+ protected fun scopedKey(manifestId: String, id: String): String {
+ return "${manifestId.lowercase()}${id.lowercase()}"
}
// MARK: - Transaction Helpers
/**
- * Execute a function within a transaction.
- * Automatically handles begin, commit, and rollback.
+ * Execute a function within a transaction. The commit persists the vault and marks it dirty, so every
+ * repository write reaches the next sync.
* @param operation The function to execute within the transaction
* @return The result of the function
*/
@@ -40,81 +60,8 @@ open class BaseRepository(
}
}
- // MARK: - Soft Delete Helpers
-
- /**
- * Soft delete a record by setting IsDeleted = 1.
- * @param table The table name
- * @param id The record ID
- * @return Number of rows affected
- */
- fun softDelete(table: String, id: String): Int {
- val timestamp = now()
- return executeUpdate(
- "UPDATE $table SET IsDeleted = 1, UpdatedAt = ? WHERE Id = ?",
- arrayOf(timestamp, id),
- )
- }
-
- /**
- * Soft delete records by a foreign key.
- * @param table The table name
- * @param foreignKey The foreign key column name
- * @param foreignKeyValue The foreign key value
- * @return Number of rows affected
- */
- fun softDeleteByForeignKey(table: String, foreignKey: String, foreignKeyValue: String): Int {
- val timestamp = now()
- return executeUpdate(
- "UPDATE $table SET IsDeleted = 1, UpdatedAt = ? WHERE $foreignKey = ?",
- arrayOf(timestamp, foreignKeyValue),
- )
- }
-
- // MARK: - Hard Delete Helpers
-
- /**
- * Hard delete a record permanently.
- * @param table The table name
- * @param id The record ID
- * @return Number of rows affected
- */
- fun hardDelete(table: String, id: String): Int {
- return executeUpdate(
- "DELETE FROM $table WHERE Id = ?",
- arrayOf(id),
- )
- }
-
- /**
- * Hard delete records by a foreign key.
- * @param table The table name
- * @param foreignKey The foreign key column name
- * @param foreignKeyValue The foreign key value
- * @return Number of rows affected
- */
- fun hardDeleteByForeignKey(table: String, foreignKey: String, foreignKeyValue: String): Int {
- return executeUpdate(
- "DELETE FROM $table WHERE $foreignKey = ?",
- arrayOf(foreignKeyValue),
- )
- }
-
// MARK: - Utility Methods
- /**
- * Check if a table exists in the database.
- * @param tableName The name of the table to check
- * @return True if the table exists
- */
- fun tableExists(tableName: String): Boolean {
- val results = executeQuery(
- "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
- arrayOf(tableName),
- )
- return results.isNotEmpty()
- }
-
/**
* Generate a new id.
* @return A new UUID string
@@ -131,16 +78,6 @@ open class BaseRepository(
return DateHelpers.now()
}
- /**
- * Build a parameterized IN clause for SQL queries.
- * @param values Array of values for the IN clause
- * @return Pair with placeholders string and values array
- */
- fun buildInClause(values: List<String>): Pair<String, Array<String>> {
- val placeholders = values.joinToString(",") { "?" }
- return Pair(placeholders, values.toTypedArray())
- }
-
// MARK: - Database Operation Helpers
/**
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemRepository.kt
index 3e09f7753..a9b735ab9 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemRepository.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemRepository.kt
@@ -16,8 +16,7 @@ import java.util.TimeZone
import java.util.UUID
/**
- * Repository for Item CRUD operations.
- * Handles fetching, creating, updating, and deleting items with their related data.
+ * Repository for the item reads the autofill service needs.
*/
class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
companion object {
@@ -37,40 +36,40 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
// MARK: - Read Operations
/**
- * Build folder paths for all folders.
- * Returns a map of FolderId -> path array.
+ * Build folder paths for all folders, keyed by the folder's scoped key (manifest + id). The tree is walked
+ * one manifest at a time: a parent link only ever resolves inside its own namespace.
*
- * @return Map of folder ID to folder path array.
+ * @return Map of scoped folder key to folder path array.
*/
- private fun buildFolderPaths(): Map<UUID, List<String>> {
- val folderPathMap = mutableMapOf<UUID, List<String>>()
+ private fun buildFolderPaths(): Map<String, List<String>> {
+ val folderPathMap = mutableMapOf<String, List<String>>()
try {
- // Get all folders from database
val folderResults = executeQuery(ItemQueries.GET_ALL_FOLDERS, emptyArray())
-
if (folderResults.isEmpty()) {
return folderPathMap
}
- // Convert to FolderUtils.Folder format
- val folders = folderResults.mapNotNull { row ->
+ val foldersByManifest = mutableMapOf<String, MutableList<FolderUtils.Folder>>()
+ for (row in folderResults) {
try {
- val id = UUID.fromString(row["Id"] as? String ?: return@mapNotNull null)
- val name = row["Name"] as? String ?: return@mapNotNull null
+ val idString = row["Id"] as? String
+ val manifestId = row["ManifestId"] as? String
+ val name = row["Name"] as? String
+ if (idString == null || manifestId == null || name == null) continue
val parentFolderId = (row["ParentFolderId"] as? String)?.let { UUID.fromString(it) }
- FolderUtils.Folder(id, name, parentFolderId)
+ foldersByManifest.getOrPut(manifestId) { mutableListOf() }.add(FolderUtils.Folder(UUID.fromString(idString), name, parentFolderId))
} catch (e: Exception) {
Log.e(TAG, "Error parsing folder row", e)
- null
}
}
- // Use shared utility to build paths for all folders
- for (folder in folders) {
- val path = FolderUtils.getFolderPath(folder.id, folders)
- if (path.isNotEmpty()) {
- folderPathMap[folder.id] = path
+ for ((manifestId, folders) in foldersByManifest) {
+ for (folder in folders) {
+ val path = FolderUtils.getFolderPath(folder.id, folders)
+ if (path.isNotEmpty()) {
+ folderPathMap[scopedKey(manifestId, folder.id.toString())] = path
+ }
}
}
@@ -83,14 +82,13 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
}
/**
- * Fetch all active items (not deleted, not in trash) with their fields.
+ * Fetch all active items (not deleted, not in trash, not archived) with their fields.
*
* @return List of Item objects.
*/
@Suppress("LongMethod", "NestedBlockDepth", "LoopWithTooManyJumpStatements")
fun getAll(): List<Item> {
val items = mutableListOf<Item>()
- val itemIds = mutableListOf<String>()
// Build folder paths
val folderPaths = buildFolderPaths()
@@ -99,6 +97,7 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
for (row in itemResults) {
try {
val idString = row["Id"] as? String ?: continue
+ val manifestId = row["ManifestId"] as? String ?: continue
val name = row["Name"] as? String
val itemType = row["ItemType"] as? String ?: continue
val folderId = row["FolderId"] as? String
@@ -111,24 +110,25 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
// Get folder path if item is in a folder
val folderUuid = folderId?.let { UUID.fromString(it) }
- val folderPath = folderUuid?.let { folderPaths[it] }
-
- val item = Item(
- id = UUID.fromString(idString),
- name = name,
- itemType = itemType,
- logo = logo,
- folderId = folderUuid,
- folderPath = folderPath,
- fields = emptyList(), // Will be populated below
- hasPasskey = hasPasskey,
- hasAttachment = hasAttachment,
- hasTotp = hasTotp,
- createdAt = createdAt,
- updatedAt = updatedAt,
+ val folderPath = folderId?.let { folderPaths[scopedKey(manifestId, it)] }
+
+ items.add(
+ Item(
+ id = UUID.fromString(idString),
+ manifestId = manifestId,
+ name = name,
+ itemType = itemType,
+ logo = logo,
+ folderId = folderUuid,
+ folderPath = folderPath,
+ fields = emptyList(), // Will be populated below
+ hasPasskey = hasPasskey,
+ hasAttachment = hasAttachment,
+ hasTotp = hasTotp,
+ createdAt = createdAt,
+ updatedAt = updatedAt,
+ ),
)
- items.add(item)
- itemIds.add(idString)
} catch (e: Exception) {
Log.e(TAG, "Error parsing item row", e)
}
@@ -139,16 +139,18 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
return emptyList()
}
- // Get all field values for these items
- val fieldQuery = ItemQueries.getFieldValuesForItems(itemIds.size)
+ // Get all field values for these items, matched on the whole (manifest, id) key
+ val fieldQuery = ItemQueries.getFieldValuesForItems(items.size)
+ val keyBindings = items.flatMap { listOf<Any?>(it.manifestId, it.id.toString().lowercase()) }.toTypedArray()
- // Build a map of itemId -> [ItemField]
- val fieldsByItemId = mutableMapOf<String, MutableList<ItemField>>()
+ // Build a map of scoped item key -> [ItemField]
+ val fieldsByItem = mutableMapOf<String, MutableList<ItemField>>()
- val fieldResults = executeQuery(fieldQuery, itemIds.toTypedArray())
+ val fieldResults = executeQuery(fieldQuery, keyBindings)
for (row in fieldResults) {
try {
val itemIdString = row["ItemId"] as? String ?: continue
+ val manifestId = row["ManifestId"] as? String ?: continue
val fieldKey = row["FieldKey"] as? String
val fieldDefinitionId = row["FieldDefinitionId"] as? String
val customLabel = row["CustomLabel"] as? String
@@ -185,7 +187,7 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
enableHistory = metadata.enableHistory,
)
- fieldsByItemId.getOrPut(itemIdString) { mutableListOf() }.add(field)
+ fieldsByItem.getOrPut(scopedKey(manifestId, itemIdString)) { mutableListOf() }.add(field)
} catch (e: Exception) {
Log.e(TAG, "Error parsing field row", e)
}
@@ -193,183 +195,11 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
// Assign fields to items
return items.map { item ->
- val fields = fieldsByItemId[item.id.toString().lowercase()] ?: emptyList()
+ val fields = fieldsByItem[scopedKey(item.manifestId, item.id.toString())] ?: emptyList()
item.copy(fields = fields)
}
}
- /**
- * Fetch a single item by ID with its fields.
- *
- * @param itemId The ID of the item to fetch.
- * @return Item object or null if not found.
- */
- fun getById(itemId: String): Item? {
- val itemResults = executeQuery(ItemQueries.GET_BY_ID, arrayOf(itemId.lowercase()))
- val row = itemResults.firstOrNull() ?: return null
-
- // Build folder paths
- val folderPaths = buildFolderPaths()
-
- return try {
- val idString = row["Id"] as? String ?: return null
- val name = row["Name"] as? String
- val itemType = row["ItemType"] as? String ?: return null
- val folderId = row["FolderId"] as? String
- val logo = row["Logo"] as? ByteArray
- val hasPasskey = (row["HasPasskey"] as? Long) == 1L
- val hasAttachment = (row["HasAttachment"] as? Long) == 1L
- val hasTotp = (row["HasTotp"] as? Long) == 1L
- val createdAt = DateHelpers.parseDateString(row["CreatedAt"] as? String ?: "") ?: MIN_DATE
- val updatedAt = DateHelpers.parseDateString(row["UpdatedAt"] as? String ?: "") ?: MIN_DATE
-
- // Get folder path if item is in a folder
- val folderUuid = folderId?.let { UUID.fromString(it) }
- val folderPath = folderUuid?.let { folderPaths[it] }
-
- // Get field values for this item
- val fields = mutableListOf<ItemField>()
- val fieldResults = executeQuery(ItemQueries.GET_FIELD_VALUES_FOR_ITEM, arrayOf(idString))
- for (fieldRow in fieldResults) {
- val fieldKey = fieldRow["FieldKey"] as? String
- val fieldDefinitionId = fieldRow["FieldDefinitionId"] as? String
- val customLabel = fieldRow["CustomLabel"] as? String
- val customFieldType = fieldRow["CustomFieldType"] as? String
- val customIsHidden = (fieldRow["CustomIsHidden"] as? Long) == 1L
- val customEnableHistory = (fieldRow["CustomEnableHistory"] as? Long) == 1L
- val value = fieldRow["Value"] as? String ?: ""
- val displayOrder = (fieldRow["DisplayOrder"] as? Long)?.toInt() ?: 0
-
- val isCustomField = fieldDefinitionId != null && fieldKey == null
- val effectiveFieldKey = fieldKey ?: fieldDefinitionId ?: ""
-
- val metadata = resolveFieldMetadata(
- fieldKey = effectiveFieldKey,
- customLabel = customLabel,
- customFieldType = customFieldType,
- customIsHidden = customIsHidden,
- customEnableHistory = customEnableHistory,
- isCustomField = isCustomField,
- )
-
- fields.add(
- ItemField(
- fieldKey = effectiveFieldKey,
- label = metadata.label,
- fieldType = metadata.fieldType,
- value = value,
- isHidden = metadata.isHidden,
- displayOrder = displayOrder,
- isCustomField = isCustomField,
- enableHistory = metadata.enableHistory,
- ),
- )
- }
-
- Item(
- id = UUID.fromString(idString),
- name = name,
- itemType = itemType,
- logo = logo,
- folderId = folderUuid,
- folderPath = folderPath,
- fields = fields,
- hasPasskey = hasPasskey,
- hasAttachment = hasAttachment,
- hasTotp = hasTotp,
- createdAt = createdAt,
- updatedAt = updatedAt,
- )
- } catch (e: Exception) {
- Log.e(TAG, "Error parsing item by ID", e)
- null
- }
- }
-
- /**
- * Fetch all unique email addresses from field values.
- *
- * @return List of email addresses.
- */
- fun getAllEmailAddresses(): List<String> {
- val results = executeQuery(ItemQueries.GET_ALL_EMAIL_ADDRESSES, arrayOf(FieldKey.LOGIN_EMAIL))
- return results.mapNotNull { it["Email"] as? String }
- }
-
- /**
- * Get recently deleted items (in trash).
- *
- * @return List of items in trash.
- */
- fun getRecentlyDeleted(): List<Item> {
- return getItemsWithoutFields(ItemQueries.GET_RECENTLY_DELETED, "recently deleted")
- }
-
- /**
- * Get archived items.
- *
- * @return List of archived items.
- */
- fun getArchived(): List<Item> {
- return getItemsWithoutFields(ItemQueries.GET_ARCHIVED, "archived")
- }
-
- /**
- * Run an item list query and map the rows to Item objects without loading their fields.
- *
- * @param query The item query to run.
- * @param label What the query returns, used in the parse-failure log line.
- * @return The mapped items, skipping any row that fails to parse.
- */
- @Suppress("LoopWithTooManyJumpStatements")
- private fun getItemsWithoutFields(query: String, label: String): List<Item> {
- val items = mutableListOf<Item>()
- val results = executeQuery(query, emptyArray())
-
- // Build folder paths
- val folderPaths = buildFolderPaths()
-
- for (row in results) {
- try {
- val idString = row["Id"] as? String ?: continue
- val name = row["Name"] as? String
- val itemType = row["ItemType"] as? String ?: continue
- val folderId = row["FolderId"] as? String
- val logo = row["Logo"] as? ByteArray
- val hasPasskey = (row["HasPasskey"] as? Long) == 1L
- val hasAttachment = (row["HasAttachment"] as? Long) == 1L
- val hasTotp = (row["HasTotp"] as? Long) == 1L
- val createdAt = DateHelpers.parseDateString(row["CreatedAt"] as? String ?: "") ?: MIN_DATE
- val updatedAt = DateHelpers.parseDateString(row["UpdatedAt"] as? String ?: "") ?: MIN_DATE
-
- // Get folder path if item is in a folder
- val folderUuid = folderId?.let { UUID.fromString(it) }
- val folderPath = folderUuid?.let { folderPaths[it] }
-
- items.add(
- Item(
- id = UUID.fromString(idString),
- name = name,
- itemType = itemType,
- logo = logo,
- folderId = folderUuid,
- folderPath = folderPath,
- fields = emptyList(), // Not loading fields for list-only items
- hasPasskey = hasPasskey,
- hasAttachment = hasAttachment,
- hasTotp = hasTotp,
- createdAt = createdAt,
- updatedAt = updatedAt,
- ),
- )
- } catch (e: Exception) {
- Log.e(TAG, "Error parsing $label item row", e)
- }
- }
-
- return items
- }
-
/**
* Get the database version from the __EFMigrationsHistory table.
*
@@ -399,39 +229,17 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
}
}
- /**
- * Get count of items in trash.
- *
- * @return Number of items in trash.
- */
- fun getRecentlyDeletedCount(): Int {
- val results = executeQuery(ItemQueries.COUNT_RECENTLY_DELETED, emptyArray())
- return (results.firstOrNull()?.get("count") as? Long)?.toInt() ?: 0
- }
-
- /**
- * Get count of archived items.
- *
- * @return Number of archived items.
- */
- fun getArchivedCount(): Int {
- val results = executeQuery(ItemQueries.COUNT_ARCHIVED, emptyArray())
- return (results.firstOrNull()?.get("count") as? Long)?.toInt() ?: 0
- }
-
/**
* Get the first non-deleted TOTP code for an item, or null when there is none.
* Used by the autofill service to copy the current TOTP code to the clipboard
* when the user selects a credential to fill.
*
* @param itemId The UUID of the item.
+ * @param manifestId The manifest the item belongs to.
* @return The TOTP code with its RFC 6238 parameters, or null.
*/
- fun getTotpForItem(itemId: String): TotpCode? {
- val results = executeQuery(
- "SELECT SecretKey, Algorithm, Digits, Period FROM TotpCodes WHERE ItemId = ? AND IsDeleted = 0 ORDER BY Name ASC LIMIT 1",
- arrayOf(itemId.lowercase()),
- )
+ fun getTotpForItem(itemId: String, manifestId: String): TotpCode? {
+ val results = executeQuery("${ItemQueries.GET_TOTP_CODES_FOR_ITEM} LIMIT 1", arrayOf(itemId.lowercase(), manifestId))
val row = results.firstOrNull() ?: return null
val secretKey = row["SecretKey"] as? String ?: return null
@@ -443,121 +251,6 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
)
}
- // MARK: - Write Operations
-
- /**
- * Move an item to trash (set DeletedAt timestamp).
- *
- * @param itemId The ID of the item to trash.
- * @return Number of rows affected.
- */
- fun trash(itemId: String): Int {
- return withTransaction {
- val now = now()
- executeUpdate(ItemQueries.TRASH_ITEM, arrayOf(now, now, itemId))
- }
- }
-
- /**
- * Restore an item from trash (clear DeletedAt).
- *
- * @param itemId The ID of the item to restore.
- * @return Number of rows affected.
- */
- fun restore(itemId: String): Int {
- return withTransaction {
- val now = now()
- executeUpdate(ItemQueries.RESTORE_ITEM, arrayOf(now, itemId))
- }
- }
-
- /**
- * Archive an item: it disappears from the main list and from autofill, but keeps all of its
- * data and its email aliases, and is never auto-pruned.
- *
- * @param itemId The ID of the item to archive.
- * @return Number of rows affected.
- */
- fun archive(itemId: String): Int {
- return withTransaction {
- val now = now()
- executeUpdate(ItemQueries.ARCHIVE_ITEM, arrayOf(now, now, itemId))
- }
- }
-
- /**
- * Unarchive an item, returning it to the main list and to autofill.
- *
- * @param itemId The ID of the item to unarchive.
- * @return Number of rows affected.
- */
- fun unarchive(itemId: String): Int {
- return withTransaction {
- val now = now()
- executeUpdate(ItemQueries.UNARCHIVE_ITEM, arrayOf(now, itemId))
- }
- }
-
- /**
- * Permanently delete an item (tombstone).
- * Converts item to tombstone and soft deletes all related data.
- *
- * @param itemId The ID of the item to permanently delete.
- * @return Number of rows affected.
- */
- fun permanentlyDelete(itemId: String): Int {
- return withTransaction {
- val now = now()
-
- // Soft delete related FieldValues
- softDeleteByForeignKey("FieldValues", "ItemId", itemId)
-
- // Soft delete related data
- softDeleteByForeignKey("TotpCodes", "ItemId", itemId)
-
- // Soft delete attachments AND zero their blob bytes — tombstone stays
- // for sync but storage is reclaimed immediately.
- executeUpdate(
- "UPDATE Attachments SET IsDeleted = 1, Blob = NULL, UpdatedAt = ? WHERE ItemId = ? AND IsDeleted = 0",
- arrayOf(now, itemId),
- )
-
- softDeleteByForeignKey("Passkeys", "ItemId", itemId)
-
- if (tableExists("ItemTags")) {
- softDeleteByForeignKey("ItemTags", "ItemId", itemId)
- }
- if (tableExists("FieldHistories")) {
- softDeleteByForeignKey("FieldHistories", "ItemId", itemId)
- }
-
- // Convert item to tombstone
- executeUpdate(ItemQueries.TOMBSTONE_ITEM, arrayOf(now, itemId))
- }
- }
-
- /**
- * Create a new item with its fields.
- *
- * @param item The item to create.
- * @return The ID of the created item.
- */
- @Suppress("UNUSED_PARAMETER") // Method under construction, will be implemented
- fun create(item: Item): String {
- error("Create operations should use VaultMutate - repository pattern under construction")
- }
-
- /**
- * Update an existing item with its fields.
- *
- * @param item The item to update.
- * @return Number of rows affected.
- */
- @Suppress("UNUSED_PARAMETER") // Method under construction, will be implemented
- fun update(item: Item): Int {
- error("Update operations should use VaultMutate - repository pattern under construction")
- }
-
// MARK: - Helper Methods
/**
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemStatsRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemStatsRepository.kt
new file mode 100644
index 000000000..987dfcb8b
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemStatsRepository.kt
@@ -0,0 +1,43 @@
+package net.aliasvault.app.vaultstore.repositories
+
+import net.aliasvault.app.vaultstore.VaultDatabase
+import net.aliasvault.app.vaultstore.queries.ItemStatsQueries
+
+/**
+ * The actions whose use of an item is recorded, each with its own timestamp + counter pair.
+ */
+enum class ItemUsageAction(
+ /** The per-action timestamp column. */
+ val lastColumn: String,
+ /** The per-action counter column. */
+ val countColumn: String,
+) {
+ /** The item was filled into a form. */
+ AUTOFILL("LastAutofilledAt", "AutofillCount"),
+
+ /** A value of the item was copied. */
+ COPY("LastCopiedAt", "CopyCount"),
+
+ /** The item's passkey signed an assertion. */
+ PASSKEY("LastPasskeyAuthAt", "PasskeyAuthCount"),
+}
+
+/**
+ * Repository for per-item usage statistics.
+ */
+class ItemStatsRepository(database: VaultDatabase) : BaseRepository(database) {
+ /**
+ * Record one use of an item, in its own transaction so the vault is persisted and marked dirty.
+ * @param itemId The item that was used
+ * @param manifestId The manifest the item belongs to
+ * @param action What the user did with it
+ */
+ fun recordUsage(itemId: String, manifestId: String, action: ItemUsageAction) {
+ withTransaction {
+ val now = now()
+ val id = itemId.lowercase()
+ executeUpdate(ItemStatsQueries.INSERT_ROW, arrayOf(manifestId, id, now, now))
+ executeUpdate(ItemStatsQueries.forAction(action.lastColumn, action.countColumn), arrayOf(now, now, now, manifestId, id))
+ }
+ }
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt
index b3ae4e54f..983427b49 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt
@@ -1,6 +1,5 @@
package net.aliasvault.app.vaultstore.repositories
-import android.database.Cursor
import android.util.Log
import net.aliasvault.app.autofill.utils.RustItemMatcher
import net.aliasvault.app.utils.DateHelpers
@@ -11,6 +10,7 @@ import net.aliasvault.app.vaultstore.models.Passkey
import net.aliasvault.app.vaultstore.passkey.PasskeyHelper
import net.aliasvault.app.vaultstore.queries.LogoQueries
import net.aliasvault.app.vaultstore.queries.PasskeyQueries
+import uniffi.aliasvault_core.faviconSourceKey
import uniffi.aliasvault_core.vaultCodecLogoIdFor
import java.util.Calendar
import java.util.Date
@@ -19,11 +19,19 @@ import java.util.UUID
/**
* Repository for Passkey operations on Items.
- * Handles fetching, creating, updating, and deleting passkeys with their parent items.
*/
class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
companion object {
private const val TAG = "PasskeyRepository"
+ private const val LOGO_KIND_FAVICON = "favicon"
+ private const val FAVICON_MIME_TYPE = "image/x-icon"
+
+ /*
+ * FieldValues.Weight of the two system fields a passkey item gets: the DefaultDisplayOrder of
+ * login.url and login.username in core/models/src/vault/SystemFieldRegistry.ts.
+ */
+ private const val LOGIN_URL_WEIGHT = 5
+ private const val LOGIN_USERNAME_WEIGHT = 15
private val MIN_DATE: Date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
set(Calendar.YEAR, 1)
@@ -36,6 +44,11 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
}.time
}
+ /**
+ * The identity of a logo row: its kind and the natural key within that kind.
+ */
+ private data class LogoRef(val kind: String, val source: String)
+
// MARK: - Read Operations
/**
@@ -51,30 +64,25 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
return null
}
- val results = executeQuery(
- PasskeyQueries.GET_BY_CREDENTIAL_ID,
- arrayOf(credentialIdString.lowercase()),
- )
-
+ val results = executeQuery(PasskeyQueries.GET_BY_ID, arrayOf(credentialIdString.lowercase()))
return results.firstOrNull()?.let { parsePasskeyRow(it) }
}
/**
- * Get all passkeys for an item.
+ * Get all passkeys for an item. Resolves the item's manifest when the caller does not hold it.
* @param itemId The UUID of the parent item
+ * @param manifestId The manifest the item belongs to, when known
* @return List of Passkey objects
*/
- fun getForItem(itemId: UUID): List<Passkey> {
- val results = executeQuery(
- PasskeyQueries.GET_BY_ITEM_ID,
- arrayOf(itemId.toString().lowercase()),
- )
-
+ fun getForItem(itemId: UUID, manifestId: String? = null): List<Passkey> {
+ val id = itemId.toString().lowercase()
+ val scope = manifestId ?: resolveRowManifestId("Items", id) ?: return emptyList()
+ val results = executeQuery(PasskeyQueries.GET_BY_ITEM_ID, arrayOf(id, scope))
return results.mapNotNull { parsePasskeyRow(it) }
}
/**
- * Get all passkeys for a specific relying party identifier (RP ID).
+ * Get all passkeys for a specific relying party identifier (RP ID) whose item is live.
* @param rpId The relying party identifier
* @return List of Passkey objects
*/
@@ -84,7 +92,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
}
/**
- * Get a passkey by its ID.
+ * Get a passkey by its ID, only while its item is live.
* @param passkeyId The UUID of the passkey
* @return Passkey object or null if not found
*/
@@ -96,133 +104,82 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
// MARK: - Write Operations
/**
- * Insert a new passkey into the database.
+ * Insert a new passkey, stamped with the manifest of its item.
* @param passkey The passkey to insert
*/
- fun insert(passkey: Passkey) {
- val publicKeyString = String(passkey.publicKey, Charsets.UTF_8)
- val privateKeyString = String(passkey.privateKey, Charsets.UTF_8)
-
- database.execute(
+ private fun insert(passkey: Passkey) {
+ val itemId = passkey.parentItemId.toString().lowercase()
+ executeUpdate(
PasskeyQueries.INSERT,
- listOf(
+ arrayOf(
passkey.id.toString().lowercase(),
- passkey.parentItemId.toString().lowercase(), // Note: still called parentItemId but references ItemId
+ itemId,
+ itemId,
+ activeManifestId(),
passkey.rpId,
passkey.userHandle,
- publicKeyString,
- privateKeyString,
+ String(passkey.publicKey, Charsets.UTF_8),
+ String(passkey.privateKey, Charsets.UTF_8),
passkey.prfKey,
passkey.displayName,
+ passkey.additionalData,
DateHelpers.toStandardFormat(passkey.createdAt),
DateHelpers.toStandardFormat(passkey.updatedAt),
if (passkey.isDeleted) 1L else 0L,
- passkey.parentItemId.toString().lowercase(),
- activeManifestId(),
),
)
}
/**
- * Create a new item with an associated passkey.
- * @param rpId The relying party identifier
+ * Create a new item with an associated passkey, in the personal manifest.
+ * @param url The item's login URL, which the favicon was fetched for
* @param userName The username (optional)
* @param displayName The display name
* @param passkey The passkey to associate
- * @param logo The logo bytes (optional)
+ * @param logo The favicon bytes fetched for the url (optional)
* @return The created Item
*/
fun createItemWithPasskey(
- rpId: String,
+ url: String,
userName: String?,
displayName: String,
passkey: Passkey,
logo: ByteArray? = null,
): Item {
return withTransaction {
- val itemId = passkey.parentItemId
+ val manifestId = activeManifestId()
+ val itemId = passkey.parentItemId.toString().lowercase()
val now = Date()
val timestamp = DateHelpers.toStandardFormat(now)
- // Create or reuse logo if provided
- val logoId = if (logo != null) {
- val source = rpId.lowercase().replace("www.", "")
- getOrCreateLogo(source, logo, timestamp)
- } else {
- null
- }
+ val logoId = resolveLogoId(manifestId, null, url, logo, timestamp)
// Create the Item
executeUpdate(
PasskeyQueries.CREATE_ITEM,
- arrayOf(
- itemId.toString().lowercase(),
- displayName,
- "Login", // Passkey items are Login type
- logoId,
- null, // FolderId
- timestamp,
- timestamp,
- 0,
- null,
- null, // FolderId again, for the manifest lookup
- activeManifestId(),
- ),
+ arrayOf(itemId, displayName, "Login", logoId, null, timestamp, timestamp, 0, null, null, manifestId),
)
- // Insert URL field value
- if (rpId.isNotEmpty()) {
- executeUpdate(
- PasskeyQueries.INSERT_FIELD_VALUE,
- arrayOf(
- generateId(),
- itemId.toString().lowercase(),
- null, // FieldDefinitionId for system fields
- FieldKey.LOGIN_URL,
- "https://$rpId",
- 0,
- timestamp,
- timestamp,
- 0,
- itemId.toString().lowercase(),
- activeManifestId(),
- ),
- )
+ // Insert URL and username field values
+ if (url.isNotEmpty()) {
+ insertFieldValue(itemId, manifestId, FieldKey.LOGIN_URL, url, LOGIN_URL_WEIGHT, timestamp)
}
-
- // Insert username field value if provided
if (userName != null) {
- executeUpdate(
- PasskeyQueries.INSERT_FIELD_VALUE,
- arrayOf(
- generateId(),
- itemId.toString().lowercase(),
- null,
- FieldKey.LOGIN_USERNAME,
- userName,
- 100,
- timestamp,
- timestamp,
- 0,
- itemId.toString().lowercase(),
- activeManifestId(),
- ),
- )
+ insertFieldValue(itemId, manifestId, FieldKey.LOGIN_USERNAME, userName, LOGIN_USERNAME_WEIGHT, timestamp)
}
- // Insert the passkey
- insert(passkey)
+ insert(passkey.copy(manifestId = manifestId))
- // Return a minimal Item object
- // Full item will be loaded via getAllItems() or getItemById()
+ // Return a minimal Item object; the full item is loaded via getAllItems()
Item(
- id = itemId,
+ id = passkey.parentItemId,
+ manifestId = manifestId,
name = displayName,
itemType = "Login",
logo = logo,
folderId = null,
folderPath = null,
- fields = emptyList(), // Will be populated when loaded from DB
+ fields = emptyList(),
hasPasskey = true,
hasAttachment = false,
hasTotp = false,
@@ -233,58 +190,47 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
}
/**
- * Replace an existing passkey with a new one.
+ * Replace an existing passkey with a new one on the same item.
*
* @param oldPasskeyId The UUID of the passkey to replace.
* @param newPasskey The new passkey.
* @param displayName The updated display name.
- * @param logo The updated logo bytes (optional).
+ * @param url The login URL the favicon was fetched for.
+ * @param logo The favicon bytes fetched for the url (optional).
*/
fun replace(
oldPasskeyId: UUID,
newPasskey: Passkey,
displayName: String,
+ url: String,
logo: ByteArray? = null,
) {
withTransaction {
val now = Date()
val timestamp = DateHelpers.toStandardFormat(now)
- // Get the old passkey to find its item
- val oldPasskey = getById(oldPasskeyId)
- ?: error("Passkey not found: $oldPasskeyId")
-
- val itemId = oldPasskey.parentItemId
-
- // Update the item's timestamp
- executeUpdate(PasskeyQueries.UPDATE_ITEM_TIMESTAMP, arrayOf(timestamp, itemId.toString().lowercase()))
+ // Get the old passkey to find its item and manifest
+ val oldPasskey = getById(oldPasskeyId) ?: error("Passkey not found: $oldPasskeyId")
+ val manifestId = oldPasskey.manifestId ?: error("Passkey has no manifest: $oldPasskeyId")
+ val itemId = oldPasskey.parentItemId.toString().lowercase()
- if (logo != null) {
- val source = newPasskey.rpId.lowercase().replace("www.", "")
- val itemResults = executeQuery(PasskeyQueries.GET_LOGO_ID_FROM_ITEM, arrayOf(itemId.toString().lowercase()))
- val existingLogoId = itemResults.firstOrNull()?.get("LogoId") as? String
-
- if (existingLogoId != null) {
- executeUpdate(LogoQueries.UPDATE_FILE_DATA, arrayOf(logo, timestamp, existingLogoId))
- } else {
- val newLogoId = getOrCreateLogo(source, logo, timestamp)
- executeUpdate(LogoQueries.UPDATE_ITEM_LOGO_ID, arrayOf(newLogoId, timestamp, itemId.toString().lowercase()))
- }
- }
+ executeUpdate(PasskeyQueries.UPDATE_ITEM_TIMESTAMP, arrayOf(timestamp, itemId, manifestId))
+ updateItemLogo(itemId, manifestId, url, logo, timestamp)
// Soft delete the old passkey
- softDelete("Passkeys", oldPasskeyId.toString().lowercase())
+ executeUpdate(PasskeyQueries.SOFT_DELETE, arrayOf(timestamp, oldPasskeyId.toString().lowercase(), manifestId))
// Create the new passkey with the same item ID
- val updatedPasskey = newPasskey.copy(
- parentItemId = itemId,
- displayName = displayName,
- createdAt = now,
- updatedAt = now,
- isDeleted = false,
+ insert(
+ newPasskey.copy(
+ parentItemId = oldPasskey.parentItemId,
+ manifestId = manifestId,
+ displayName = displayName,
+ createdAt = now,
+ updatedAt = now,
+ isDeleted = false,
+ ),
)
-
- insert(updatedPasskey)
}
}
@@ -292,50 +238,35 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
* Add a passkey to an existing Item (merge passkey into existing credential).
*
* @param itemId The UUID of the existing Item to add the passkey to.
+ * @param manifestId The manifest the item belongs to.
* @param passkey The passkey to add (will have its parentItemId updated).
- * @param logo Optional logo to update/add to the item.
+ * @param url The login URL the favicon was fetched for.
+ * @param logo The favicon bytes fetched for the url (optional).
*/
fun addPasskeyToExistingItem(
itemId: UUID,
+ manifestId: String,
passkey: Passkey,
+ url: String,
logo: ByteArray? = null,
) {
withTransaction {
val now = Date()
val timestamp = DateHelpers.toStandardFormat(now)
-
- // Optionally update/add logo
- if (logo != null) {
- val rpId = passkey.rpId
- val source = rpId.lowercase().replace("www.", "")
-
- // Check if item already has a logo
- val itemResults = executeQuery(PasskeyQueries.GET_LOGO_ID_FROM_ITEM, arrayOf(itemId.toString().lowercase()))
- val existingLogoId = itemResults.firstOrNull()?.get("LogoId") as? String
-
- if (existingLogoId != null) {
- // Update existing logo
- executeUpdate(LogoQueries.UPDATE_FILE_DATA, arrayOf(logo, timestamp, existingLogoId))
- } else {
- // Create or reuse logo with unique source check
- val newLogoId = getOrCreateLogo(source, logo, timestamp)
- // Link logo to item
- executeUpdate(LogoQueries.UPDATE_ITEM_LOGO_ID, arrayOf(newLogoId, timestamp, itemId.toString().lowercase()))
- }
- }
-
- // Update item's UpdatedAt timestamp
- executeUpdate(PasskeyQueries.UPDATE_ITEM_TIMESTAMP, arrayOf(timestamp, itemId.toString().lowercase()))
-
- // Create the passkey with the existing item ID
- val passkeyToInsert = passkey.copy(
- parentItemId = itemId,
- createdAt = now,
- updatedAt = now,
- isDeleted = false,
+ val id = itemId.toString().lowercase()
+
+ updateItemLogo(id, manifestId, url, logo, timestamp)
+ executeUpdate(PasskeyQueries.UPDATE_ITEM_TIMESTAMP, arrayOf(timestamp, id, manifestId))
+
+ insert(
+ passkey.copy(
+ parentItemId = itemId,
+ manifestId = manifestId,
+ createdAt = now,
+ updatedAt = now,
+ isDeleted = false,
+ ),
)
-
- insert(passkeyToInsert)
}
}
@@ -357,46 +288,26 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
): List<PasskeyWithCredentialInfo> {
if (!database.isOpen()) return emptyList()
- val results = mutableListOf<PasskeyWithCredentialInfo>()
- val cursor = database.queryCursor(
- PasskeyQueries.GET_WITH_CREDENTIAL_INFO,
- listOf(FieldKey.LOGIN_USERNAME, FieldKey.LOGIN_EMAIL, rpId),
- )
+ return executeQuery(PasskeyQueries.GET_BY_RP_ID, arrayOf(rpId)).mapNotNull { row ->
+ val passkey = parsePasskeyRow(row) ?: return@mapNotNull null
+ val itemUsername = row["Username"] as? String
- cursor.use {
- while (it.moveToNext()) {
- val passkey = parsePasskeyFromCursor(it) ?: continue
- val itemName = if (!it.isNull(11)) it.getString(11) else null
- val itemUsername = if (!it.isNull(12)) it.getString(12) else null
- val itemEmail = if (!it.isNull(13)) it.getString(13) else null
-
- // Filter by username or userId if provided
- var matches = true
- if (userName != null && itemUsername != userName) {
- matches = false
- }
- if (userId != null && passkey.userHandle != null && !userId.contentEquals(passkey.userHandle)) {
- matches = false
- }
-
- if (matches) {
- results.add(
- PasskeyWithCredentialInfo(
- passkey = passkey,
- serviceName = itemName,
- username = itemUsername,
- email = itemEmail,
- ),
- )
- }
- }
- }
+ // Filter by username or userId if provided
+ val usernameMatches = userName == null || itemUsername == userName
+ val userIdMatches = userId == null || passkey.userHandle == null || userId.contentEquals(passkey.userHandle)
+ if (!usernameMatches || !userIdMatches) return@mapNotNull null
- return results
+ PasskeyWithCredentialInfo(
+ passkey = passkey,
+ serviceName = row["ServiceName"] as? String,
+ username = itemUsername,
+ email = row["Email"] as? String,
+ )
+ }
}
/**
- * Get ALL Login items that don't have a passkey yet (no URL filtering).
+ * Get ALL active Login items that don't have a passkey yet (no URL filtering).
* Used with RustCredentialMatcher for intelligent, cross-platform consistent filtering.
*
* @return List of ItemWithCredentialInfo objects with all URLs.
@@ -405,43 +316,36 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
if (!database.isOpen()) return emptyList()
val results = mutableListOf<ItemWithCredentialInfo>()
- val cursor = database.queryCursor(
+ val rows = executeQuery(
PasskeyQueries.GET_ALL_ITEMS_WITHOUT_PASSKEY,
- listOf(FieldKey.LOGIN_URL, FieldKey.LOGIN_USERNAME, FieldKey.LOGIN_EMAIL, FieldKey.LOGIN_PASSWORD),
+ arrayOf(FieldKey.LOGIN_URL, FieldKey.LOGIN_USERNAME, FieldKey.LOGIN_EMAIL, FieldKey.LOGIN_PASSWORD),
)
- cursor.use {
- while (it.moveToNext()) {
- val itemIdString = it.getString(0)
- val itemName = if (!it.isNull(1)) it.getString(1) else null
- val itemCreatedAt = if (!it.isNull(2)) it.getString(2) else null
- val itemUpdatedAt = if (!it.isNull(3)) it.getString(3) else null
- val urlsString = if (!it.isNull(4)) it.getString(4) else null
- val itemUsername = if (!it.isNull(5)) it.getString(5) else null
- val itemEmail = if (!it.isNull(6)) it.getString(6) else null
- val hasPassword = !it.isNull(7) && it.getString(7).isNotEmpty()
-
- try {
- val itemId = UUID.fromString(itemIdString)
- val createdAt = DateHelpers.parseDateString(itemCreatedAt ?: "") ?: MIN_DATE
- val updatedAt = DateHelpers.parseDateString(itemUpdatedAt ?: "") ?: MIN_DATE
- val urls = urlsString?.split(",")?.filter { it.isNotEmpty() } ?: emptyList()
-
- results.add(
- ItemWithCredentialInfo(
- itemId = itemId,
- serviceName = itemName,
- urls = urls,
- username = itemUsername,
- email = itemEmail,
- hasPassword = hasPassword,
- createdAt = createdAt,
- updatedAt = updatedAt,
- ),
- )
- } catch (e: Exception) {
- Log.e(TAG, "Error parsing item row", e)
- }
+ for (row in rows) {
+ try {
+ val itemIdString = row["Id"] as? String
+ val manifestId = row["ManifestId"] as? String
+ if (itemIdString == null || manifestId == null) continue
+ val itemId = UUID.fromString(itemIdString)
+ val createdAt = DateHelpers.parseDateString(row["CreatedAt"] as? String ?: "") ?: MIN_DATE
+ val updatedAt = DateHelpers.parseDateString(row["UpdatedAt"] as? String ?: "") ?: MIN_DATE
+ val urls = (row["Urls"] as? String)?.split(",")?.filter { it.isNotEmpty() } ?: emptyList()
+
+ results.add(
+ ItemWithCredentialInfo(
+ itemId = itemId,
+ manifestId = manifestId,
+ serviceName = row["Name"] as? String,
+ urls = urls,
+ username = row["Username"] as? String,
+ email = row["Email"] as? String,
+ hasPassword = !(row["Password"] as? String).isNullOrEmpty(),
+ createdAt = createdAt,
+ updatedAt = updatedAt,
+ ),
+ )
+ } catch (e: Exception) {
+ Log.e(TAG, "Error parsing item row", e)
}
}
@@ -486,46 +390,34 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
if (!database.isOpen()) return emptyList()
val results = mutableListOf<PasskeyWithItem>()
- val cursor = database.queryCursor(PasskeyQueries.GET_ALL_WITH_ITEMS, listOf(FieldKey.LOGIN_USERNAME, FieldKey.LOGIN_EMAIL))
-
- cursor.use {
- while (it.moveToNext()) {
- try {
- // Parse passkey (columns 0-10)
- val passkey = parsePasskeyFromJoinCursor(it) ?: continue
-
- // Parse item info (columns 11-14)
- val itemId = UUID.fromString(it.getString(11))
- val itemName = if (!it.isNull(12)) it.getString(12) else null
- val itemCreatedAt = DateHelpers.parseDateString(it.getString(13)) ?: MIN_DATE
- val itemUpdatedAt = DateHelpers.parseDateString(it.getString(14)) ?: MIN_DATE
-
- @Suppress("UNUSED_VARIABLE") // Username field loaded for potential future use
- val username = if (!it.isNull(15)) it.getString(15) else null
-
- @Suppress("UNUSED_VARIABLE") // Email field loaded for potential future use
- val email = if (!it.isNull(16)) it.getString(16) else null
-
- // Create a minimal Item object with the data we have
- val item = Item(
- id = itemId,
- name = itemName,
- itemType = "Login",
- logo = null,
- folderId = null,
- folderPath = null,
- fields = emptyList(), // Not loading all fields for performance
- hasPasskey = true,
- hasAttachment = false,
- hasTotp = false,
- createdAt = itemCreatedAt,
- updatedAt = itemUpdatedAt,
- )
-
- results.add(PasskeyWithItem(passkey, item))
- } catch (e: Exception) {
- Log.e(TAG, "Error parsing passkey with item row", e)
- }
+ for (row in executeQuery(PasskeyQueries.GET_ALL_WITH_ITEMS, emptyArray())) {
+ try {
+ val passkey = parsePasskeyRow(row)
+ val manifestId = passkey?.manifestId
+ if (passkey == null || manifestId == null) continue
+ val itemCreatedAt = DateHelpers.parseDateString(row["ItemCreatedAt"] as? String) ?: MIN_DATE
+ val itemUpdatedAt = DateHelpers.parseDateString(row["ItemUpdatedAt"] as? String) ?: MIN_DATE
+
+ // Create a minimal Item object with the data we have
+ val item = Item(
+ id = passkey.parentItemId,
+ manifestId = manifestId,
+ name = row["ServiceName"] as? String,
+ itemType = "Login",
+ logo = null,
+ folderId = null,
+ folderPath = null,
+ fields = emptyList(), // Not loading all fields for performance
+ hasPasskey = true,
+ hasAttachment = false,
+ hasTotp = false,
+ createdAt = itemCreatedAt,
+ updatedAt = itemUpdatedAt,
+ )
+
+ results.add(PasskeyWithItem(passkey, item))
+ } catch (e: Exception) {
+ Log.e(TAG, "Error parsing passkey with item row", e)
}
}
@@ -535,40 +427,98 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
// MARK: - Helper Methods
/**
- * Get an existing logo ID for a source, or create a new logo if none exists.
- * This prevents UNIQUE constraint violations on Logos.Source.
+ * Insert one system field value on an item.
+ */
+ @Suppress("LongParameterList") // One argument per column written
+ private fun insertFieldValue(itemId: String, manifestId: String, fieldKey: String, value: String, weight: Int, timestamp: String) {
+ executeUpdate(
+ PasskeyQueries.INSERT_FIELD_VALUE,
+ arrayOf(generateId(), itemId, null, fieldKey, value, weight, timestamp, timestamp, 0, itemId, manifestId),
+ )
+ }
+
+ /**
+ * Point the item at the logo the item-logo rules pick for its url and the fetched bytes, when that differs
+ * from the logo it has. A null pick keeps the current logo, like the COALESCE in the TS item update.
+ */
+ private fun updateItemLogo(itemId: String, manifestId: String, url: String, logo: ByteArray?, timestamp: String) {
+ val existingLogoId = executeQuery(PasskeyQueries.GET_LOGO_ID_FROM_ITEM, arrayOf(itemId, manifestId)).firstOrNull()?.get("LogoId") as? String
+ val logoId = resolveLogoId(manifestId, existingLogoId, url, logo, timestamp) ?: return
+ if (logoId != existingLogoId) {
+ executeUpdate(LogoQueries.UPDATE_ITEM_LOGO_ID, arrayOf(logoId, timestamp, itemId, manifestId))
+ }
+ }
+
+ /**
+ * The logo an item should point at, following ItemRepository.ts resolveLogoId without an explicit selection:
+ * a logo the user chose earlier (built-in or uploaded) is kept; a favicon the item already has for this
+ * domain is kept; fresh bytes create or refresh this domain's favicon row in the item's manifest; otherwise
+ * the favicon this domain already has anywhere in the vault is adopted, or none at all.
*
- * @param source The normalized source domain (e.g., 'github.com')
- * @param logoData The logo image data as ByteArray
- * @param timestamp The current timestamp for CreatedAt/UpdatedAt
- * @return The logo ID (existing or newly created)
+ * @return The logo id, or null when the item should keep what it has (update) or get none (create)
*/
- private fun getOrCreateLogo(source: String, logoData: ByteArray, timestamp: String): String {
- // Check if a logo for this source already exists
- val existingLogos = executeQuery(LogoQueries.GET_BY_SOURCE, arrayOf(source))
-
- val existingLogo = existingLogos.firstOrNull()
- if (existingLogo != null) {
- val existingLogoId = existingLogo["Id"] as String
- val isDeleted = (existingLogo["IsDeleted"] as? Long) == 1L
-
- // Sanity check: restore if soft-deleted
- if (isDeleted) {
- executeUpdate(LogoQueries.RESTORE, arrayOf(timestamp, existingLogoId))
- executeUpdate(LogoQueries.UPDATE_FILE_DATA, arrayOf(logoData, timestamp, existingLogoId))
- }
- return existingLogoId
+ private fun resolveLogoId(scope: String, existingLogoId: String?, url: String, logo: ByteArray?, timestamp: String): String? {
+ val existing = existingLogoId?.let { getLogoById(it, scope) }
+ if (existing != null && existing.kind != LOGO_KIND_FAVICON) {
+ return adoptIntoScope(scope, existing.kind, existing.source, timestamp)
}
- // Create new logo entry. The id is derived from (manifest, kind, source) by the Rust core, like every other
- // client does, so the same favicon never produces two rows across devices.
- val manifestId = activeManifestId()
- val logoId = vaultCodecLogoIdFor(manifestId, "favicon", source)
- executeUpdate(
- LogoQueries.INSERT,
- arrayOf(logoId, source, manifestId, logoData, "image/png", null, timestamp, timestamp, 0),
- )
+ // Without a domain there is no natural key to store a favicon under.
+ val source = faviconSourceKey(url)
+ if (source.isEmpty()) {
+ return null
+ }
+
+ if (existing != null && existing.source == source) {
+ return adoptIntoScope(scope, LOGO_KIND_FAVICON, source, timestamp)
+ }
+
+ if (logo != null && logo.isNotEmpty()) {
+ return upsertLogo(scope, LOGO_KIND_FAVICON, source, logo, FAVICON_MIME_TYPE, null, timestamp)
+ }
+
+ return adoptIntoScope(scope, LOGO_KIND_FAVICON, source, timestamp)
+ }
+
+ /**
+ * The kind and key of a logo row inside one manifest, or null when it no longer exists.
+ */
+ private fun getLogoById(logoId: String, manifestId: String): LogoRef? {
+ val row = executeQuery(LogoQueries.GET_BY_ID, arrayOf(logoId, manifestId)).firstOrNull() ?: return null
+ val source = row["Source"] as? String ?: return null
+ return LogoRef(row["Kind"] as? String ?: LOGO_KIND_FAVICON, source)
+ }
+ /**
+ * The id this logo has inside the manifest, copying it in from another manifest when it is not there yet.
+ * Null when the vault holds no such logo at all.
+ */
+ private fun adoptIntoScope(manifestId: String, kind: String, source: String, timestamp: String): String? {
+ val inScope = executeQuery(LogoQueries.GET_ID_FOR_KEY, arrayOf(manifestId, kind, source)).firstOrNull()?.get("Id") as? String
+ if (inScope != null) {
+ return inScope
+ }
+
+ val origin = executeQuery(LogoQueries.GET_BEST_FOR_KEY, arrayOf(kind, source)).firstOrNull() ?: return null
+ return upsertLogo(manifestId, kind, source, origin["FileData"] as? ByteArray, origin["MimeType"] as? String, origin["Name"] as? String, timestamp)
+ }
+
+ /**
+ * Insert or refresh the logo for a kind and key inside one manifest. The id is derived from (manifest, kind,
+ * source) by the Rust core, like every other client does, so the same logo never produces two rows.
+ */
+ @Suppress("LongParameterList") // One argument per column written
+ private fun upsertLogo(
+ manifestId: String,
+ kind: String,
+ source: String,
+ fileData: ByteArray?,
+ mimeType: String?,
+ name: String?,
+ timestamp: String,
+ ): String {
+ val logoId = vaultCodecLogoIdFor(manifestId, kind, source)
+ executeUpdate(LogoQueries.UPSERT, arrayOf(logoId, kind, source, manifestId, fileData, mimeType, name, timestamp, timestamp))
return logoId
}
@@ -580,36 +530,32 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
return try {
val idString = row["Id"] as? String ?: return null
val itemIdString = row["ItemId"] as? String ?: return null
+ val manifestId = row["ManifestId"] as? String ?: return null
val rpId = row["RpId"] as? String ?: return null
val userHandle = row["UserHandle"] as? ByteArray
val publicKeyString = row["PublicKey"] as? String ?: return null
val privateKeyString = row["PrivateKey"] as? String ?: return null
val prfKey = row["PrfKey"] as? ByteArray
val displayName = row["DisplayName"] as? String ?: return null
+ val additionalData = row["AdditionalData"] as? ByteArray
val createdAtString = row["CreatedAt"] as? String ?: return null
val updatedAtString = row["UpdatedAt"] as? String ?: return null
val isDeleted = (row["IsDeleted"] as? Long) == 1L
- val id = UUID.fromString(idString)
- val itemId = UUID.fromString(itemIdString)
- val createdAt = DateHelpers.parseDateString(createdAtString) ?: MIN_DATE
- val updatedAt = DateHelpers.parseDateString(updatedAtString) ?: MIN_DATE
-
- val publicKeyData = publicKeyString.toByteArray(Charsets.UTF_8)
- val privateKeyData = privateKeyString.toByteArray(Charsets.UTF_8)
-
Passkey(
- id = id,
- parentItemId = itemId, // Note: field name still parentItemId but now refers to ItemId
+ id = UUID.fromString(idString),
+ parentItemId = UUID.fromString(itemIdString),
+ manifestId = manifestId,
rpId = rpId,
userHandle = userHandle,
userName = null,
- publicKey = publicKeyData,
- privateKey = privateKeyData,
+ publicKey = publicKeyString.toByteArray(Charsets.UTF_8),
+ privateKey = privateKeyString.toByteArray(Charsets.UTF_8),
prfKey = prfKey,
displayName = displayName,
- createdAt = createdAt,
- updatedAt = updatedAt,
+ additionalData = additionalData,
+ createdAt = DateHelpers.parseDateString(createdAtString) ?: MIN_DATE,
+ updatedAt = DateHelpers.parseDateString(updatedAtString) ?: MIN_DATE,
isDeleted = isDeleted,
)
} catch (e: Exception) {
@@ -617,100 +563,6 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
null
}
}
-
- /**
- * Parse a passkey from a cursor (for direct database queries).
- * Expects columns 0-10 to be passkey fields.
- */
- private fun parsePasskeyFromCursor(cursor: Cursor): Passkey? {
- return try {
- val idString = cursor.getString(0)
- val itemIdString = cursor.getString(1)
- val rpId = cursor.getString(2)
- val userHandle = if (!cursor.isNull(3)) cursor.getBlob(3) else null
- val publicKeyString = cursor.getString(4)
- val privateKeyString = cursor.getString(5)
- val prfKey = if (!cursor.isNull(6)) cursor.getBlob(6) else null
- val displayName = cursor.getString(7)
- val createdAtString = cursor.getString(8)
- val updatedAtString = cursor.getString(9)
- val isDeleted = cursor.getInt(10) == 1
-
- val id = UUID.fromString(idString)
- val itemId = UUID.fromString(itemIdString)
-
- val createdAt = DateHelpers.parseDateString(createdAtString) ?: MIN_DATE
- val updatedAt = DateHelpers.parseDateString(updatedAtString) ?: MIN_DATE
-
- val publicKeyData = publicKeyString.toByteArray(Charsets.UTF_8)
- val privateKeyData = privateKeyString.toByteArray(Charsets.UTF_8)
-
- Passkey(
- id = id,
- parentItemId = itemId,
- rpId = rpId,
- userHandle = userHandle,
- userName = null,
- publicKey = publicKeyData,
- privateKey = privateKeyData,
- prfKey = prfKey,
- displayName = displayName,
- createdAt = createdAt,
- updatedAt = updatedAt,
- isDeleted = isDeleted,
- )
- } catch (e: Exception) {
- Log.e(TAG, "Error parsing passkey from cursor", e)
- null
- }
- }
-
- /**
- * Parse a passkey from a JOIN query cursor.
- * Expects columns 0-10 to be passkey fields.
- */
- private fun parsePasskeyFromJoinCursor(cursor: Cursor): Passkey? {
- return try {
- val idString = cursor.getString(0)
- val itemIdString = cursor.getString(1)
- val rpId = cursor.getString(2)
- val userHandle = if (!cursor.isNull(3)) cursor.getBlob(3) else null
- val publicKeyString = cursor.getString(4)
- val privateKeyString = cursor.getString(5)
- val prfKey = if (!cursor.isNull(6)) cursor.getBlob(6) else null
- val displayName = cursor.getString(7)
- val createdAtString = cursor.getString(8)
- val updatedAtString = cursor.getString(9)
- val isDeleted = cursor.getInt(10) == 1
-
- val id = UUID.fromString(idString)
- val itemId = UUID.fromString(itemIdString)
-
- val createdAt = DateHelpers.parseDateString(createdAtString) ?: MIN_DATE
- val updatedAt = DateHelpers.parseDateString(updatedAtString) ?: MIN_DATE
-
- val publicKeyData = publicKeyString.toByteArray(Charsets.UTF_8)
- val privateKeyData = privateKeyString.toByteArray(Charsets.UTF_8)
-
- Passkey(
- id = id,
- parentItemId = itemId,
- rpId = rpId,
- userHandle = userHandle,
- userName = null,
- publicKey = publicKeyData,
- privateKey = privateKeyData,
- prfKey = prfKey,
- displayName = displayName,
- createdAt = createdAt,
- updatedAt = updatedAt,
- isDeleted = isDeleted,
- )
- } catch (e: Exception) {
- Log.e(TAG, "Error parsing passkey from JOIN cursor", e)
- null
- }
- }
}
// MARK: - Data Classes
@@ -750,6 +602,7 @@ data class PasskeyWithItem(
* Used for showing existing credentials that can have a passkey added.
*
* @property itemId The UUID of the item.
+ * @property manifestId The manifest the item belongs to.
* @property serviceName The service name (Item.Name).
* @property urls All login URLs associated with this item.
* @property username The username from field values.
@@ -760,6 +613,7 @@ data class PasskeyWithItem(
*/
data class ItemWithCredentialInfo(
val itemId: UUID,
+ val manifestId: String,
val serviceName: String?,
val urls: List<String>,
val username: String?,
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 475288d45..2b8951e6b 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
@@ -93,7 +93,8 @@ class VaultStoreTest {
@Test
fun testDatabaseWriteOperation() {
- // Create a test setting
+ // Create a test setting. Settings are keyed by (ManifestId, Key).
+ val testManifestId = "00000000-0000-0000-0000-000000000001"
val testKey = "test_setting_key"
val testValue = "test_setting_value"
@@ -101,16 +102,16 @@ class VaultStoreTest {
vaultStore.beginTransaction()
try {
// Insert the setting using raw SQL with parameters
- val insertSql = "INSERT INTO Settings (Key, Value, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, ?)"
+ val insertSql = "INSERT INTO Settings (ManifestId, Key, Value, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, ?, ?)"
val insertResult = vaultStore.executeUpdate(
insertSql,
- arrayOf(testKey, testValue, "2025-01-01 00:00:00", "2025-01-01 00:00:00", 0),
+ arrayOf(testManifestId, testKey, testValue, "2025-01-01 00:00:00", "2025-01-01 00:00:00", 0),
)
assertTrue(insertResult > 0, "Setting insertion should succeed")
// Verify the setting was inserted by querying it
- val querySql = "SELECT Value FROM Settings WHERE Key = ?"
- val results = vaultStore.executeQuery(querySql, arrayOf(testKey))
+ val querySql = "SELECT Value FROM Settings WHERE ManifestId = ? AND Key = ?"
+ val results = vaultStore.executeQuery(querySql, arrayOf(testManifestId, testKey))
assertTrue(results.isNotEmpty(), "Should get a result (amount of updated rows)")