Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add device identifier to stats usage buckets and improve sync in mobile app
Leendert de Borstced905c0dd0d
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex fdd981203..cd63acdb1 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -13,6 +13,7 @@ import { SqliteClient } from '@aliasvault/client/database/SqliteClient';import { FaviconService } from '@aliasvault/client/items/FaviconService';import { applySearchFilter } from '@aliasvault/client/items/ItemFilters';import { generateTotpCode } from '@aliasvault/client/items/TotpUtility';+import { getOrCreateDeviceId } from '@aliasvault/client/platform/DeviceId';import { filterItems, AutofillMatchingMode, extractRootDomain, isUrlAlreadyLinked } from '@aliasvault/client/rust/RustCore';import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';import { SharingService } from '@aliasvault/client/sharing/SharingService';@@ -1377,7 +1378,7 @@ export async function handleRecordItemUsage(}const sqliteClient = await createVaultSqliteClient();- if (!sqliteClient.itemStats.recordUsage({ Id: message.itemId, ManifestId: message.manifestId }, message.action)) {+ if (!sqliteClient.itemStats.recordUsage({ Id: message.itemId, ManifestId: message.manifestId }, message.action, await getOrCreateDeviceId())) {// No such item (deleted between use and record); nothing to attribute the use to.return { success: false };}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.ktindex 96fd2f17f..1bf2119d0 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt@@ -32,6 +32,7 @@ import net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProviderimport net.aliasvault.app.webapi.WebApiServiceimport org.json.JSONArrayimport org.json.JSONObject+import uniffi.aliasvault_core.ItemUsageAction/*** The native vault manager that manages the vault store and all input/output operations on it.@@ -1171,6 +1172,23 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}}+ /**+ * Record a copied value in its item's usage statistics (this device's row); the next sync pushes it.+ * @param itemId The item the value belongs to+ * @param manifestId The manifest the item belongs to+ * @param promise The promise to resolve+ */+ @ReactMethod+ override fun recordItemCopy(itemId: String, manifestId: String, promise: Promise) {+ try {+ vaultStore.recordItemUsage(itemId, manifestId, ItemUsageAction.COPY)+ promise.resolve(null)+ } catch (e: Exception) {+ Log.e(TAG, "Error recording item usage", e)+ promise.reject("ERR_RECORD_ITEM_USAGE", "Failed to record item usage: ${e.message}", e)+ }+ }+/*** Register credential identities in the Native Autofill API cache.* This stores passkey metadata so they can be shown without unlocking the vault.diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMetadataManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMetadataManager.ktindex 1a347afe4..03f2fcbaf 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMetadataManager.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMetadataManager.kt@@ -187,6 +187,16 @@ class VaultMetadataManager(storageProvider.setDirtyScopes(scopes + known)}+ /**+ * The random id of this install, created on first use. Per-device vault rows (item usage statistics) are keyed by it.+ */+ fun getOrCreateDeviceId(): String {+ storageProvider.getDeviceId()?.takeIf { it.isNotEmpty() }?.let { return it }+ val deviceId = java.util.UUID.randomUUID().toString().lowercase()+ storageProvider.setDeviceId(deviceId)+ return deviceId+ }+/*** Get the dirty flag.*/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.ktindex ec29b3b9e..ac00ff6f7 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@@ -478,7 +478,8 @@ class VaultStore(*/fun recordItemUsage(itemId: String, manifestId: String, action: ItemUsageAction) {// Usage statistics live in their own data bucket, pushed without a full manifest write.- database.withTransaction(VaultDataBucketCategory.STATS) { db -> db.recordItemUse(itemId.lowercase(), manifestId, action) }+ val deviceId = metadata.getOrCreateDeviceId()+ database.withTransaction(VaultDataBucketCategory.STATS) { db -> db.recordItemUse(itemId.lowercase(), manifestId, deviceId, action) }}/**diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.ktindex c18bcb9a9..e10a6f574 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt@@ -187,6 +187,18 @@ class AndroidStorageProvider(private val context: Context) : StorageProvider {}}+ override fun getDeviceId(): String? {+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)+ return sharedPreferences.getString("device_id", null)+ }++ override fun setDeviceId(deviceId: String) {+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)+ sharedPreferences.edit {+ putString("device_id", deviceId)+ }+ }+override fun getIsDirty(): Boolean {val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)return sharedPreferences.getBoolean("is_dirty", false)diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.ktindex c5052ae47..b2864ac26 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt@@ -162,6 +162,18 @@ interface StorageProvider {*/fun getCapabilities(): String?+ /**+ * Get the random id of this install, which per-device vault rows are keyed by.+ * @return The device id, or null when none was created yet+ */+ fun getDeviceId(): String?++ /**+ * Set the random id of this install.+ * @param deviceId The device id+ */+ fun setDeviceId(deviceId: String)+// region Sync State/**diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.ktindex bd3d8f249..f6d2377da 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt@@ -21,6 +21,7 @@ class TestStorageProvider : StorageProvider {private var serverVersion: String? = nullprivate var capabilities: String? = nullprivate var isDirty: Boolean = false+ private var deviceId: String? = nullprivate var dirtyScopes: List<String> = emptyList()private var mutationSequence: Int = 0private var isSyncing: Boolean = false@@ -136,6 +137,14 @@ class TestStorageProvider : StorageProvider {this.isDirty = isDirty}+ override fun getDeviceId(): String? {+ return deviceId+ }++ override fun setDeviceId(deviceId: String) {+ this.deviceId = deviceId+ }+override fun getIsDirty(): Boolean {return isDirty}diff --git a/apps/mobile-app/app/(tabs)/_layout.tsx b/apps/mobile-app/app/(tabs)/_layout.tsxindex 291191d85..c4c6f18ba 100644--- a/apps/mobile-app/app/(tabs)/_layout.tsx+++ b/apps/mobile-app/app/(tabs)/_layout.tsx@@ -6,6 +6,7 @@ import { Platform, StyleSheet, View } from 'react-native';import emitter from '@/utils/EventEmitter';import { useColors } from '@/hooks/useColorScheme';+import { useForegroundSync } from '@/hooks/useForegroundSync';import { ServerSyncIndicator } from '@/components/ServerSyncIndicator';import { ThemedText } from '@/components/themed/ThemedText';@@ -24,6 +25,8 @@ export default function TabLayout() : React.ReactNode {const dbContext = useDb();const { t } = useTranslation();+ useForegroundSync();+// Check if user is authenticated and database is availableconst isFullyInitialized = authContext.isInitialized && dbContext.dbInitialized;const isAuthenticated = authContext.isLoggedIn;diff --git a/apps/mobile-app/components/form/FormInputCopyToClipboard.tsx b/apps/mobile-app/components/form/FormInputCopyToClipboard.tsxindex 8f0ccf793..4fce8fba3 100644--- a/apps/mobile-app/components/form/FormInputCopyToClipboard.tsx+++ b/apps/mobile-app/components/form/FormInputCopyToClipboard.tsx@@ -4,9 +4,12 @@ import { useTranslation } from 'react-i18next';import { View, Text, Platform, TouchableOpacity, StyleSheet, Animated, Easing } from 'react-native';import Toast from 'react-native-toast-message';+import type { ItemRef } from '@aliasvault/client/database/ItemRef';+import { copyToClipboardWithExpiration } from '@/utils/ClipboardUtility';import { useColors } from '@/hooks/useColorScheme';+import { useRecordItemCopy } from '@/hooks/useRecordItemCopy';import { useClipboardCountdown } from '@/context/ClipboardCountdownContext';import { LocalPreferencesService } from '@/services/LocalPreferencesService';@@ -17,6 +20,8 @@ type FormInputCopyToClipboardProps = {type?: 'text' | 'password';/** Optional element to render next to the label (e.g., history button) */labelSuffix?: React.ReactNode;+ /** The item the value belongs to, whose usage statistics count the copy */+ item?: ItemRef;}/**@@ -27,11 +32,13 @@ const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> = ({value,type = 'text',labelSuffix,+ item,}) : React.ReactNode => {const [isPasswordVisible, setIsPasswordVisible] = useState(false);const colors = useColors();const { t } = useTranslation();const { activeField, startCountdown, clearCountdown } = useClipboardCountdown();+ const recordItemCopy = useRecordItemCopy();const animatedWidth = useRef(new Animated.Value(0)).current;// Create a stable unique ID based on label and value@@ -78,6 +85,7 @@ const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> = ({// Use centralized clipboard utilityawait copyToClipboardWithExpiration(value, timeoutSeconds);+ recordItemCopy(item);// Handle animation stateif (timeoutSeconds > 0) {diff --git a/apps/mobile-app/components/items/ItemCard.tsx b/apps/mobile-app/components/items/ItemCard.tsxindex 91d6e2f36..316f971c1 100644--- a/apps/mobile-app/components/items/ItemCard.tsx+++ b/apps/mobile-app/components/items/ItemCard.tsx@@ -14,6 +14,7 @@ import { useDb } from '@/context/DbContext';import { LocalPreferencesService } from '@/services/LocalPreferencesService';import { useColors } from '@/hooks/useColorScheme';import { useNavigationDebounce } from '@/hooks/useNavigationDebounce';+import { useRecordItemCopy } from '@/hooks/useRecordItemCopy';import { copyToClipboardWithExpiration } from '@/utils/ClipboardUtility';import type { DisplayItem } from '@/utils/DisplayItem';import { itemEditRoute, itemRoute } from '@/utils/ItemRoute';@@ -38,6 +39,7 @@ export function ItemCard({ item, onItemDelete, onItemDuplicate, showFolderPath =const { showConfirm } = useDialog();const dbContext = useDb();const navigate = useNavigationDebounce();+ const recordItemCopy = useRecordItemCopy();/*** Get the display text for an item, showing username by default,@@ -81,6 +83,7 @@ export function ItemCard({ item, onItemDelete, onItemDuplicate, showFolderPath =// Use centralized clipboard utilityawait copyToClipboardWithExpiration(text, timeoutSeconds);+ recordItemCopy({ Id: item.Id, ManifestId: item.ManifestId });} catch (error) {console.error('Failed to copy to clipboard:', error);}diff --git a/apps/mobile-app/components/items/details/AliasDetails.tsx b/apps/mobile-app/components/items/details/AliasDetails.tsxindex 30b304944..44df59da1 100644--- a/apps/mobile-app/components/items/details/AliasDetails.tsx+++ b/apps/mobile-app/components/items/details/AliasDetails.tsx@@ -33,24 +33,28 @@ export const AliasDetails: React.FC<AliasDetailsProps> = ({ item }) : React.Reac<ThemedText type="subtitle">{t('common.alias')}</ThemedText>{hasName && (<FormInputCopyToClipboard+ item={item}label={t('items.fullName')}value={fullName}/>)}{firstName && (<FormInputCopyToClipboard+ item={item}label={t('fieldLabels.alias.first_name')}value={firstName}/>)}{lastName && (<FormInputCopyToClipboard+ item={item}label={t('fieldLabels.alias.last_name')}value={lastName}/>)}{IdentityHelperUtils.isValidBirthDate(birthDate) && (<FormInputCopyToClipboard+ item={item}label={t('fieldLabels.alias.birthdate')}value={IdentityHelperUtils.normalizeBirthDate(birthDate!)}/>diff --git a/apps/mobile-app/components/items/details/FieldBlock.tsx b/apps/mobile-app/components/items/details/FieldBlock.tsxindex 63bb8061f..a0c5251a8 100644--- a/apps/mobile-app/components/items/details/FieldBlock.tsx+++ b/apps/mobile-app/components/items/details/FieldBlock.tsx@@ -264,6 +264,7 @@ const FieldBlock: React.FC<FieldBlockProps> = ({ field, item, hideLabel = falsevalue={value}type={field.FieldType === FieldTypes.Password || field.IsHidden ? 'password' : 'text'}labelSuffix={idx === 0 ? HistoryButton : undefined}+ item={item}/>))}{HistoryModal}@@ -284,6 +285,7 @@ const FieldBlock: React.FC<FieldBlockProps> = ({ field, item, hideLabel = falsevalue={value}type="password"labelSuffix={HistoryButton}+ item={item}/>{HistoryModal}</>@@ -311,6 +313,7 @@ const FieldBlock: React.FC<FieldBlockProps> = ({ field, item, hideLabel = falsevalue={value}type="text"labelSuffix={HistoryButton}+ item={item}/>{HistoryModal}</>diff --git a/apps/mobile-app/components/items/details/TotpSection.tsx b/apps/mobile-app/components/items/details/TotpSection.tsxindex 4ea9320b4..bee3c3699 100644--- a/apps/mobile-app/components/items/details/TotpSection.tsx+++ b/apps/mobile-app/components/items/details/TotpSection.tsx@@ -9,6 +9,7 @@ import { generateTotpCode } from '@aliasvault/client/items/TotpUtility';import type { Item, TotpCode } from '@aliasvault/models/vault';import { useColors } from '@/hooks/useColorScheme';+import { useRecordItemCopy } from '@/hooks/useRecordItemCopy';import { ThemedText } from '@/components/themed/ThemedText';import { ThemedView } from '@/components/themed/ThemedView';import { useDb } from '@/context/DbContext';@@ -40,6 +41,7 @@ export const TotpSection: React.FC<TotpSectionProps> = ({ item }) : React.ReactNconst colors = useColors();const dbContext = useDb();const { t } = useTranslation();+ const recordItemCopy = useRecordItemCopy();/*** Get the remaining seconds in the current TOTP window.@@ -66,6 +68,7 @@ export const TotpSection: React.FC<TotpSectionProps> = ({ item }) : React.ReactN// Use centralized clipboard utilityawait copyToClipboardWithExpiration(code, timeoutSeconds);+ recordItemCopy({ Id: item.Id, ManifestId: item.ManifestId });if (Platform.OS !== 'android') {// Only show toast on iOS, Android already shows a native toast on clipboard interactions.diff --git a/apps/mobile-app/hooks/useForegroundSync.ts b/apps/mobile-app/hooks/useForegroundSync.tsnew file mode 100644index 000000000..549e40ddc--- /dev/null+++ b/apps/mobile-app/hooks/useForegroundSync.ts@@ -0,0 +1,45 @@+import { useEffect, useRef } from 'react';+import { AppState } from 'react-native';++import { useVaultSync } from '@/hooks/useVaultSync';++import { useDb } from '@/context/DbContext';+import NativeVaultManager from '@/specs/NativeVaultManager';++/**+ * Push pending local changes when the app returns to the foreground. The autofill and passkey layers only record+ * a use locally (they may be stopped by the OS at any time), so this is where those writes reach the server.+ */+export function useForegroundSync(): void {+ const dbContext = useDb();+ const { syncVault } = useVaultSync();+ const appState = useRef(AppState.currentState);++ useEffect(() => {+ const subscription = AppState.addEventListener('change', async (nextAppState) => {+ const cameToForeground = appState.current.match(/inactive|background/) && nextAppState === 'active';+ appState.current = nextAppState;+ if (!cameToForeground) {+ return;+ }++ try {+ // A locked vault goes through the reinitialize flow, which syncs by itself.+ if (!(await NativeVaultManager.isVaultUnlocked())) {+ return;+ }+ const syncState = await NativeVaultManager.getSyncState();+ if (!syncState.isDirty || syncState.isSyncing) {+ return;+ }+ await syncVault({ onSuccess: () => void dbContext.refreshSyncState() });+ } catch (error) {+ console.warn('[useForegroundSync] Failed to push pending changes:', error);+ }+ });++ return (): void => {+ subscription.remove();+ };+ }, [dbContext, syncVault]);+}diff --git a/apps/mobile-app/hooks/useRecordItemCopy.ts b/apps/mobile-app/hooks/useRecordItemCopy.tsnew file mode 100644index 000000000..0f38a8316--- /dev/null+++ b/apps/mobile-app/hooks/useRecordItemCopy.ts@@ -0,0 +1,42 @@+import { useCallback } from 'react';++import type { ItemRef } from '@aliasvault/client/database/ItemRef';++import { useVaultSync } from '@/hooks/useVaultSync';++import { useDb } from '@/context/DbContext';+import NativeVaultManager from '@/specs/NativeVaultManager';++/** How long to wait after a copy before pushing, so a burst of copies goes up in one sync. */+const PUSH_DELAY_MS = 2000;++let pendingPush: ReturnType<typeof setTimeout> | null = null;++/**+ * Record a copied value in its item's usage statistics and push it silently shortly after (Stats scope, no indicator).+ */+export function useRecordItemCopy(): (item?: ItemRef) => void {+ const dbContext = useDb();+ const { syncVault } = useVaultSync();++ return useCallback((item?: ItemRef): void => {+ if (!item?.Id || !item.ManifestId) {+ return;+ }+ NativeVaultManager.recordItemCopy(item.Id, item.ManifestId)+ .then(() => {+ if (pendingPush) {+ clearTimeout(pendingPush);+ }+ pendingPush = setTimeout(() => {+ pendingPush = null;+ void NativeVaultManager.getSyncState().then((state) => {+ if (state.isDirty && !state.isSyncing) {+ return syncVault({ onSuccess: () => void dbContext.refreshSyncState() });+ }+ });+ }, PUSH_DELAY_MS);+ })+ .catch((error) => console.warn('[useRecordItemCopy] Failed to record item usage:', error));+ }, [dbContext, syncVault]);+}diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.tsindex f836d5553..46c3a36ec 100644--- a/apps/mobile-app/hooks/useVaultSync.ts+++ b/apps/mobile-app/hooks/useVaultSync.ts@@ -8,6 +8,7 @@ import { useDb } from '@/context/DbContext';import NativeVaultManager from '@/specs/NativeVaultManager';import emitter from '@/utils/EventEmitter';import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';+import { hasUserVisibleScope, type VaultMutationScope } from '@aliasvault/client/sync/VaultMutationScope';import {AppErrorCode,getAppErrorCode,@@ -119,7 +120,8 @@ export const useVaultSync = (): {// Show appropriate indicator based on what sync will doif (statusCheck.hasNewerVault) {dbContext.setIsSyncing(true);- } else if (statusCheck.hasDirtyChanges && !statusCheck.isOffline) {+ } else if (statusCheck.hasDirtyChanges && !statusCheck.isOffline && hasUserVisibleScope((await NativeVaultManager.getSyncState()).dirtyScopes as VaultMutationScope[])) {+ // Silent scopes (usage statistics) upload without the indicator.dbContext.setIsUploading(true);}diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swiftindex c827845c7..a54574d6b 100644--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift@@ -65,6 +65,13 @@ extension CredentialProviderViewController: CredentialProviderDelegate {} catch {print("[Autofill] Failed to record credential usage: \(error)")}+ },+ copyRecorder: { credential in+ do {+ try vaultStore.recordItemUsage(itemId: credential.id, manifestId: credential.manifestId, action: .copy)+ } catch {+ print("[Autofill] Failed to record credential copy: \(error)")+ }})diff --git a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swiftindex 42ce6de8a..f545da9ee 100644--- a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift@@ -477,6 +477,24 @@ public class NativeVaultManager: NSObject {}}+ /// Record a copied value in its item's usage statistics (this device's row); the next sync pushes it.+ @objc+ func recordItemCopy(_ itemId: String,+ manifestId: String,+ resolver resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ guard let id = UUID(uuidString: itemId) else {+ reject("RECORD_ITEM_USAGE_ERROR", "Invalid item id", nil)+ return+ }+ do {+ try vaultStore.recordItemUsage(itemId: id, manifestId: manifestId, action: .copy)+ resolve(nil)+ } catch {+ reject("RECORD_ITEM_USAGE_ERROR", "Failed to record item usage: \(error.localizedDescription)", error)+ }+ }+@objcfunc registerCredentialIdentities(_ resolve: @escaping RCTPromiseResolveBlock,rejecter reject: @escaping RCTPromiseRejectBlock) {diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mmindex 566864f5c..12dca8212 100644--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm@@ -187,6 +187,10 @@resolve(@"Not applicable on iOS");}+- (void)recordItemCopy:(NSString *)itemId manifestId:(NSString *)manifestId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager recordItemCopy:itemId manifestId:manifestId resolver:resolve rejecter:reject];+}+- (void)registerCredentialIdentities:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {[vaultManager registerCredentialIdentities:resolve rejecter:reject];}diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swiftindex eca4d7c0e..46ec105cb 100644--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift@@ -40,6 +40,8 @@ public final class VaultSyncEngine {public func run(operation: String, forcePull: Bool = false, encryptionKey: String? = nil, sharing: [String: Any]? = nil) async throws -> [String: Any] {let log = VaultSyncRunLog(operation: operation)runLog = log+ // The engine reads and pushes from the live database, so it must hold what the other process last stored.+ try vaultStore.reloadIfStoredVaultChanged()var finalResult: [String: Any]?let session = try VaultSyncSession(requestJson: try buildRequest(operation: operation, forcePull: forcePull, encryptionKey: encryptionKey, sharing: sharing))defer {diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swiftindex 83d7d605b..91e20f07f 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift@@ -12,6 +12,7 @@ extension VaultStore {/// Store the encrypted databasepublic func storeEncryptedDatabase(_ base64EncryptedDb: String) throws {try base64EncryptedDb.write(to: getEncryptedDbPath(), atomically: true, encoding: .utf8)+ loadedVaultStamp = storedVaultStamp()}/// Get the encrypted database@@ -25,6 +26,8 @@ extension VaultStore {/// Unlock the vault - decrypt the database and setup the database connection.public func unlockVault() throws {+ // Taken before the read: a write landing in between leaves the stamp behind, which only causes one extra reload.+ let stamp = storedVaultStamp()guard let encryptedDbBase64 = getEncryptedDatabase() else {throw AppError.encryptionKeyNotFound}@@ -36,6 +39,7 @@ extension VaultStore {do {let decrypted = try decrypt(data: encryptedDbData)try setupDatabaseWithDecryptedData(decrypted)+ loadedVaultStamp = stamp} catch let vaultError as AppError {// Pass through AppError typesthrow vaultError@@ -45,6 +49,21 @@ extension VaultStore {}}+ /// Reload the live database when another process (the app or the autofill extension) stored the vault since this+ /// one loaded it, so a write never builds on, or a sync never pushes from, a stale copy. A no-op while locked.+ public func reloadIfStoredVaultChanged() throws {+ guard dbConnection != nil, let stamp = storedVaultStamp(), stamp != loadedVaultStamp else {+ return+ }+ print("[VaultStore] Stored vault changed in another process, reloading the live database")+ try unlockVault()+ }++ /// The modification date of the stored vault file, which every store replaces atomically.+ private func storedVaultStamp() -> Date? {+ return (try? FileManager.default.attributesOfItem(atPath: getEncryptedDbPath().path))?[.modificationDate] as? Date+ }+/// Remove the encrypted database from the local filesystempublic func removeEncryptedDatabase() throws {try FileManager.default.removeItem(at: getEncryptedDbPath())diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swiftindex a8f2200af..54d9a56b7 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift@@ -161,6 +161,17 @@ extension VaultStore {userDefaults.synchronize()}+ /// The random id of this install, created on first use and shared by the app and the autofill extension.+ /// Per-device vault rows (item usage statistics) are keyed by it.+ public func getOrCreateDeviceId() -> String {+ if let deviceId = userDefaults.string(forKey: VaultConstants.deviceIdKey), !deviceId.isEmpty {+ return deviceId+ }+ let deviceId = UUID().uuidString.lowercased()+ userDefaults.set(deviceId, forKey: VaultConstants.deviceIdKey)+ return deviceId+ }+/// Get the dirty flagpublic func getIsDirty() -> Bool {return userDefaults.bool(forKey: VaultConstants.isDirtyKey)diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swiftindex fc291b84a..e3f87f4fb 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift@@ -44,6 +44,7 @@ extension VaultStore {/// Begin a transaction on the database. This is required for all database operations that modify the database.public func beginTransaction() throws {+ try reloadIfStoredVaultChanged()try requireDatabase().executeBatch(sql: "BEGIN TRANSACTION")}@@ -172,8 +173,9 @@ extension VaultStore {/// - action: What the user did with itpublic func recordItemUsage(itemId: UUID, manifestId: String, action: ItemUsageAction) throws {// Usage statistics live in their own data bucket, pushed without a full manifest write.+ let deviceId = getOrCreateDeviceId()try withTransaction(scope: VaultDataBucketCategory.stats) {- _ = try requireDatabase().recordItemUse(itemId: itemId.uuidString.lowercased(), manifestId: manifestId, action: action)+ _ = try requireDatabase().recordItemUse(itemId: itemId.uuidString.lowercased(), manifestId: manifestId, deviceId: deviceId, action: action)}}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swiftindex c1088bacd..681e41ea9 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift@@ -32,6 +32,9 @@ public class VaultStore {/// The live vault, held in the Rust core's memory. Nil while vault is locked.internal var dbConnection: SqliteMemoryDatabase?+ /// The modification date of the stored vault file the live database was loaded from or last written to.+ internal var loadedVaultStamp: Date?+/// The Account Key the unlocked session holds and the keychain and PIN protect (see `VaultStore+LegacyKeyConversion`).internal var accountKey: Data?diff --git a/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift b/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swiftindex ee09979b5..9cbb3a607 100644--- a/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift+++ b/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift@@ -92,7 +92,10 @@ public struct CredentialProviderView: View {password: password)},- onCopy: presentToast+ onCopy: { message in+ viewModel.recordCopy(of: credential)+ presentToast(message)+ })}}@@ -341,13 +344,17 @@ public class CredentialProviderViewModel: ObservableObject {/// vault can record the use.private let usageRecorder: ((AutofillCredential) -> Void)?+ /// Optional handler called when the user copies a value of a credential from the picker's menu.+ private let copyRecorder: ((AutofillCredential) -> Void)?+public init(loader: @escaping () async throws -> [AutofillCredential],selectionHandler: @escaping (String, String) -> Void,cancelHandler: @escaping () -> Void,serviceUrl: String? = nil,urlLinker: ((AutofillCredential, String) async -> Void)? = nil,- usageRecorder: ((AutofillCredential) -> Void)? = nil+ usageRecorder: ((AutofillCredential) -> Void)? = nil,+ copyRecorder: ((AutofillCredential) -> Void)? = nil) {self.loader = loaderself.selectionHandler = selectionHandler@@ -355,6 +362,7 @@ public class CredentialProviderViewModel: ObservableObject {self.serviceUrl = serviceUrlself.urlLinker = urlLinkerself.usageRecorder = usageRecorder+ self.copyRecorder = copyRecorderif let url = serviceUrl {self.searchText = url}@@ -469,6 +477,11 @@ public class CredentialProviderViewModel: ObservableObject {selectionHandler(username, password)}+ /// Record that a value of the credential was copied from the picker's menu.+ func recordCopy(of credential: AutofillCredential) {+ copyRecorder?(credential)+ }+func handleSelection(username: String, password: String) {selectionHandler(username, password)}diff --git a/apps/mobile-app/ios/VaultUtils/VaultConstants.swift b/apps/mobile-app/ios/VaultUtils/VaultConstants.swiftindex 7c9d7e485..08104a196 100644--- a/apps/mobile-app/ios/VaultUtils/VaultConstants.swift+++ b/apps/mobile-app/ios/VaultUtils/VaultConstants.swift@@ -26,6 +26,7 @@ public struct VaultConstants {public static let vaultSyncHoldKey = "aliasvault_vault_sync_hold"public static let dirtyScopesKey = "aliasvault_dirty_scopes"public static let syncLogsKey = "aliasvault_sync_logs"+ public static let deviceIdKey = "aliasvault_device_id"public static let defaultAutoLockTimeout: Int = 3600 // 1 hour in secondsdiff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.tsindex 586fc6a1b..c07099fa3 100644--- a/apps/mobile-app/specs/NativeVaultManager.ts+++ b/apps/mobile-app/specs/NativeVaultManager.ts@@ -91,6 +91,9 @@ export interface Spec extends TurboModule {isIgnoringBatteryOptimizations(): Promise<boolean>;requestIgnoreBatteryOptimizations(): Promise<string>;+ // Item usage statistics+ recordItemCopy(itemId: string, manifestId: string): Promise<void>;+// Credential identity managementregisterCredentialIdentities(): Promise<void>;removeCredentialIdentities(): Promise<void>;diff --git a/apps/mobile-app/utils/SqliteClient.ts b/apps/mobile-app/utils/SqliteClient.tsindex 337223f1e..b58361591 100644--- a/apps/mobile-app/utils/SqliteClient.ts+++ b/apps/mobile-app/utils/SqliteClient.ts@@ -5,7 +5,6 @@ import { EncryptionKeyRepository } from '@aliasvault/client/database/repositorieimport { FolderRepository } from '@aliasvault/client/database/repositories/FolderRepository';import { ImportExportRepository } from '@aliasvault/client/database/repositories/ImportExportRepository';import { ItemRepository } from '@aliasvault/client/database/repositories/ItemRepository';-import { ItemStatsRepository } from '@aliasvault/client/database/repositories/ItemStatsRepository';import { LogoRepository } from '@aliasvault/client/database/repositories/LogoRepository';import { PasskeyRepository } from '@aliasvault/client/database/repositories/PasskeyRepository';import { SettingsRepository } from '@aliasvault/client/database/repositories/SettingsRepository';@@ -66,11 +65,6 @@ class SqliteClient {*/public readonly importExport = asyncRepository(new ImportExportRepository(this.database, this.logoRepository), this.database);- /**- * Repository for per-item usage statistics.- */- public readonly itemStats = asyncRepository(new ItemStatsRepository(this.database), this.database, VaultDataBucketCategory.Stats);-/*** The id of the user's personal manifest, or null when no pull has recorded one yet.*/diff --git a/apps/server/Databases/AliasClientDb/AliasClientDbContext.cs b/apps/server/Databases/AliasClientDb/AliasClientDbContext.csindex c135e62f6..f35be20e2 100644--- a/apps/server/Databases/AliasClientDb/AliasClientDbContext.cs+++ b/apps/server/Databases/AliasClientDb/AliasClientDbContext.cs@@ -149,7 +149,8 @@ public class AliasClientDbContext : DbContextmodelBuilder.Entity<Attachment>().HasKey(e => new { e.ManifestId, e.Id });modelBuilder.Entity<Passkey>().HasKey(e => new { e.ManifestId, e.Id });modelBuilder.Entity<TotpCode>().HasKey(e => new { e.ManifestId, e.Id });- modelBuilder.Entity<ItemStat>().HasKey(e => new { e.ManifestId, e.Id });+ modelBuilder.Entity<ItemStat>().HasKey(e => new { e.ManifestId, e.Id, e.DeviceId });+ modelBuilder.Entity<ItemStat>().Property(e => e.DeviceId).HasDefaultValue(string.Empty).UseCollation("NOCASE");modelBuilder.Entity<Setting>().HasKey(e => new { e.ManifestId, e.Key });modelBuilder.Entity<ItemTag>().HasKey(e => new { e.ManifestId, e.ItemId, e.TagId });diff --git a/apps/server/Databases/AliasClientDb/ItemStat.cs b/apps/server/Databases/AliasClientDb/ItemStat.csindex 29a193456..00254b6e7 100644--- a/apps/server/Databases/AliasClientDb/ItemStat.cs+++ b/apps/server/Databases/AliasClientDb/ItemStat.cs@@ -11,28 +11,32 @@ using System.ComponentModel.DataAnnotations;using AliasClientDb.Abstracts;/// <summary>-/// Usage statistics for a single item: when it was last used and how often.+/// Usage statistics of one item on one device: when it was last used and how often./// </summary>+/// <remarks>+/// A device only ever writes its own row, so the last-write-wins merge never has to resolve two devices' counts+/// against each other. A reader sums the counts and takes the latest timestamps over an item's rows.+/// </remarks>public class ItemStat : ManifestScopedEntity{/// <summary>- /// Gets or sets the id of the item these statistics describe. Also this row's own primary key.+ /// Gets or sets the id of the item these statistics describe./// </summary>[Key]public Guid Id { get; set; }+ /// <summary>+ /// Gets or sets the id of the device that recorded these uses (a random id per install, kept outside the vault).+ /// </summary>+ public string DeviceId { get; set; } = string.Empty;+/// <summary>/// Gets or sets the moment the item was last used by any of the tracked actions, or null when never used.- /// This is the aggregate a client sorts and reports on./// </summary>public DateTime? LastUsedAt { get; set; }/// <summary>/// Gets or sets how often the item was used, across all tracked actions.- /// <para>- /// Approximate by design: the merge resolves conflicts last-write-wins, which cannot sum counters, so the- /// newest writer's value wins wholesale and uses made on a device that syncs later are lost.- /// </para>/// </summary>public int UseCount { get; set; }@@ -42,7 +46,7 @@ public class ItemStat : ManifestScopedEntitypublic DateTime? LastAutofilledAt { get; set; }/// <summary>- /// Gets or sets how often the item was autofilled. Approximate, for the reason given on <see cref="UseCount"/>.+ /// Gets or sets how often the item was autofilled./// </summary>public int AutofillCount { get; set; }@@ -52,7 +56,7 @@ public class ItemStat : ManifestScopedEntitypublic DateTime? LastCopiedAt { get; set; }/// <summary>- /// Gets or sets how often a field of the item was copied. Approximate, for the reason given on <see cref="UseCount"/>.+ /// Gets or sets how often a field of the item was copied./// </summary>public int CopyCount { get; set; }@@ -62,7 +66,7 @@ public class ItemStat : ManifestScopedEntitypublic DateTime? LastPasskeyAuthAt { get; set; }/// <summary>- /// Gets or sets how often the item's passkey served an assertion. Approximate, for the reason given on <see cref="UseCount"/>.+ /// Gets or sets how often the item's passkey served an assertion./// </summary>public int PasskeyAuthCount { get; set; }}diff --git a/apps/server/Databases/AliasClientDb/Migrations/20260918090000_2.1.0-ManifestScopedStorage.Designer.cs b/apps/server/Databases/AliasClientDb/Migrations/20261009150000_2.1.0-ManifestScopedStorage.Designer.cssimilarity index 98%rename from apps/server/Databases/AliasClientDb/Migrations/20260918090000_2.1.0-ManifestScopedStorage.Designer.csrename to apps/server/Databases/AliasClientDb/Migrations/20261009150000_2.1.0-ManifestScopedStorage.Designer.csindex 79477ccbf..fcb86b897 100644--- a/apps/server/Databases/AliasClientDb/Migrations/20260918090000_2.1.0-ManifestScopedStorage.Designer.cs+++ b/apps/server/Databases/AliasClientDb/Migrations/20261009150000_2.1.0-ManifestScopedStorage.Designer.cs@@ -11,7 +11,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;namespace AliasClientDb.Migrations{[DbContext(typeof(AliasClientDbContext))]- [Migration("20260918090000_2.1.0-ManifestScopedStorage")]+ [Migration("20261009150000_2.1.0-ManifestScopedStorage")]partial class _210ManifestScopedStorage{/// <inheritdoc />@@ -391,6 +391,12 @@ namespace AliasClientDb.Migrations.HasColumnType("TEXT").UseCollation("NOCASE");+ b.Property<string>("DeviceId")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT")+ .HasDefaultValue("")+ .UseCollation("NOCASE");+b.Property<int>("AutofillCount").HasColumnType("INTEGER");@@ -424,7 +430,7 @@ namespace AliasClientDb.Migrationsb.Property<int>("UseCount").HasColumnType("INTEGER");- b.HasKey("ManifestId", "Id");+ b.HasKey("ManifestId", "Id", "DeviceId");b.ToTable("ItemStats");});diff --git a/apps/server/Databases/AliasClientDb/Migrations/20260918090000_2.1.0-ManifestScopedStorage.cs b/apps/server/Databases/AliasClientDb/Migrations/20261009150000_2.1.0-ManifestScopedStorage.cssimilarity index 99%rename from apps/server/Databases/AliasClientDb/Migrations/20260918090000_2.1.0-ManifestScopedStorage.csrename to apps/server/Databases/AliasClientDb/Migrations/20261009150000_2.1.0-ManifestScopedStorage.csindex 91b57a72d..e5f4ac148 100644--- a/apps/server/Databases/AliasClientDb/Migrations/20260918090000_2.1.0-ManifestScopedStorage.cs+++ b/apps/server/Databases/AliasClientDb/Migrations/20261009150000_2.1.0-ManifestScopedStorage.cs@@ -643,6 +643,7 @@ namespace AliasClientDb.Migrations{ManifestId = table.Column<string>(type: "TEXT", nullable: false, collation: "NOCASE"),Id = table.Column<string>(type: "TEXT", nullable: false, collation: "NOCASE"),+ DeviceId = table.Column<string>(type: "TEXT", nullable: false, defaultValue: "", collation: "NOCASE"),LastUsedAt = table.Column<DateTime>(type: "TEXT", nullable: true),UseCount = table.Column<int>(type: "INTEGER", nullable: false),LastAutofilledAt = table.Column<DateTime>(type: "TEXT", nullable: true),@@ -657,7 +658,7 @@ namespace AliasClientDb.Migrations},constraints: table =>{- table.PrimaryKey("PK_ItemStats", x => new { x.ManifestId, x.Id });+ table.PrimaryKey("PK_ItemStats", x => new { x.ManifestId, x.Id, x.DeviceId });});migrationBuilder.CreateTable(diff --git a/apps/server/Databases/AliasClientDb/Migrations/20260918090100_2.1.1-ItemChildManifestTrigger.Designer.cs b/apps/server/Databases/AliasClientDb/Migrations/20261009150100_2.1.1-ItemChildManifestTrigger.Designer.cssimilarity index 99%rename from apps/server/Databases/AliasClientDb/Migrations/20260918090100_2.1.1-ItemChildManifestTrigger.Designer.csrename to apps/server/Databases/AliasClientDb/Migrations/20261009150100_2.1.1-ItemChildManifestTrigger.Designer.csindex 3b5e2b145..82692c4ce 100644--- a/apps/server/Databases/AliasClientDb/Migrations/20260918090100_2.1.1-ItemChildManifestTrigger.Designer.cs+++ b/apps/server/Databases/AliasClientDb/Migrations/20261009150100_2.1.1-ItemChildManifestTrigger.Designer.cs@@ -11,7 +11,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;namespace AliasClientDb.Migrations{[DbContext(typeof(AliasClientDbContext))]- [Migration("20260918090100_2.1.1-ItemChildManifestTrigger")]+ [Migration("20261009150100_2.1.1-ItemChildManifestTrigger")]partial class _211ItemChildManifestTrigger{/// <inheritdoc />diff --git a/apps/server/Databases/AliasClientDb/Migrations/20260918090100_2.1.1-ItemChildManifestTrigger.cs b/apps/server/Databases/AliasClientDb/Migrations/20261009150100_2.1.1-ItemChildManifestTrigger.cssimilarity index 100%rename from apps/server/Databases/AliasClientDb/Migrations/20260918090100_2.1.1-ItemChildManifestTrigger.csrename to apps/server/Databases/AliasClientDb/Migrations/20261009150100_2.1.1-ItemChildManifestTrigger.csdiff --git a/apps/server/Databases/AliasClientDb/Migrations/AliasClientDbContextModelSnapshot.cs b/apps/server/Databases/AliasClientDb/Migrations/AliasClientDbContextModelSnapshot.csindex bbc3158b4..fe302e358 100644--- a/apps/server/Databases/AliasClientDb/Migrations/AliasClientDbContextModelSnapshot.cs+++ b/apps/server/Databases/AliasClientDb/Migrations/AliasClientDbContextModelSnapshot.cs@@ -388,6 +388,12 @@ namespace AliasClientDb.Migrations.HasColumnType("TEXT").UseCollation("NOCASE");+ b.Property<string>("DeviceId")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT")+ .HasDefaultValue("")+ .UseCollation("NOCASE");+b.Property<int>("AutofillCount").HasColumnType("INTEGER");@@ -421,7 +427,7 @@ namespace AliasClientDb.Migrationsb.Property<int>("UseCount").HasColumnType("INTEGER");- b.HasKey("ManifestId", "Id");+ b.HasKey("ManifestId", "Id", "DeviceId");b.ToTable("ItemStats");});diff --git a/apps/server/Databases/AliasClientDb/Models/VaultTableRegistry.cs b/apps/server/Databases/AliasClientDb/Models/VaultTableRegistry.csindex 6fbb9f805..0a286f652 100644--- a/apps/server/Databases/AliasClientDb/Models/VaultTableRegistry.cs+++ b/apps/server/Databases/AliasClientDb/Models/VaultTableRegistry.cs@@ -22,7 +22,7 @@ public static class VaultTableRegistrypublic static IReadOnlyList<VaultTableDefinition> Tables { get; } = new VaultTableDefinition[]{new("Items", new[] { "Id" }, ManifestScoped: true, ItemChild: false),- new("ItemStats", new[] { "Id" }, ManifestScoped: true, ItemChild: true),+ new("ItemStats", new[] { "Id", "DeviceId" }, ManifestScoped: true, ItemChild: true),new("FieldValues", new[] { "Id" }, ManifestScoped: true, ItemChild: true),new("Folders", new[] { "Id" }, ManifestScoped: true, ItemChild: false),new("Tags", new[] { "Id" }, ManifestScoped: true, ItemChild: false),diff --git a/apps/server/Databases/AliasClientDb/Scripts/MigrationSql/000_FullSchema.sql b/apps/server/Databases/AliasClientDb/Scripts/MigrationSql/000_FullSchema.sqlindex 41c0b1b66..63a2bed65 100644--- a/apps/server/Databases/AliasClientDb/Scripts/MigrationSql/000_FullSchema.sql+++ b/apps/server/Databases/AliasClientDb/Scripts/MigrationSql/000_FullSchema.sql@@ -73,13 +73,13 @@ CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");CREATE INDEX "IX_Passwords_CredentialId" ON "Passwords" ("CredentialId");INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240708094944_1.0.0-InitialMigration', '10.0.10');+VALUES ('20240708094944_1.0.0-InitialMigration', '10.0.12');COMMIT;BEGIN TRANSACTION;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240708224522_1.0.1-EmptyTestMigration', '10.0.10');+VALUES ('20240708224522_1.0.1-EmptyTestMigration', '10.0.12');COMMIT;@@ -87,7 +87,7 @@ BEGIN TRANSACTION;ALTER TABLE "Aliases" RENAME COLUMN "EmailPrefix" TO "Email";INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '10.0.10');+VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '10.0.12');COMMIT;@@ -102,7 +102,7 @@ CREATE TABLE "EncryptionKeys" ();INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240729105618_1.1.0-AddPkiTables', '10.0.10');+VALUES ('20240729105618_1.1.0-AddPkiTables', '10.0.12');COMMIT;@@ -115,7 +115,7 @@ CREATE TABLE "Settings" ();INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240805073413_1.2.0-AddSettingsTable', '10.0.10');+VALUES ('20240805073413_1.2.0-AddSettingsTable', '10.0.12');COMMIT;@@ -150,7 +150,7 @@ COMMIT;PRAGMA foreign_keys = 1;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '10.0.10');+VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '10.0.12');BEGIN TRANSACTION;CREATE TABLE "ef_temp_Credentials" (@@ -190,7 +190,7 @@ CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");COMMIT;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '10.0.10');+VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '10.0.12');BEGIN TRANSACTION;ALTER TABLE "Settings" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;@@ -208,7 +208,7 @@ ALTER TABLE "Attachment" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;ALTER TABLE "Aliases" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240916105320_1.4.0-AddSyncSupport', '10.0.10');+VALUES ('20240916105320_1.4.0-AddSyncSupport', '10.0.12');COMMIT;@@ -249,7 +249,7 @@ CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");COMMIT;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '10.0.10');+VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '10.0.12');BEGIN TRANSACTION;CREATE TABLE "TotpCodes" (@@ -266,7 +266,7 @@ CREATE TABLE "TotpCodes" (CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20250310131554_1.5.0-AddTotpCodes', '10.0.10');+VALUES ('20250310131554_1.5.0-AddTotpCodes', '10.0.12');COMMIT;@@ -689,7 +689,7 @@ CREATE INDEX "IX_Passkeys_CredentialId" ON "Passkeys" ("CredentialId");CREATE INDEX "IX_Passkeys_RpId" ON "Passkeys" ("RpId");INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20251014122838_1.6.0-AddPasskeys', '10.0.10');+VALUES ('20251014122838_1.6.0-AddPasskeys', '10.0.12');COMMIT;@@ -1288,11 +1288,11 @@ CREATE INDEX "IX_TotpCodes_ItemId" ON "TotpCodes" ("ItemId");COMMIT;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20251213111207_1.7.0-FieldBasedDataModelUpdate', '10.0.10');+VALUES ('20251213111207_1.7.0-FieldBasedDataModelUpdate', '10.0.12');BEGIN TRANSACTION;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20260130221620_2.0.0-MajorVersionBump', '10.0.10');+VALUES ('20260130221620_2.0.0-MajorVersionBump', '10.0.12');COMMIT;@@ -1371,6 +1371,7 @@ CREATE TABLE "CodecOverflows" (CREATE TABLE "ItemStats" ("ManifestId" TEXT COLLATE NOCASE NOT NULL,"Id" TEXT COLLATE NOCASE NOT NULL,+ "DeviceId" TEXT COLLATE NOCASE NOT NULL DEFAULT '',"LastUsedAt" TEXT NULL,"UseCount" INTEGER NOT NULL,"LastAutofilledAt" TEXT NULL,@@ -1382,7 +1383,7 @@ CREATE TABLE "ItemStats" ("CreatedAt" TEXT NOT NULL,"UpdatedAt" TEXT NOT NULL,"IsDeleted" INTEGER NOT NULL,- CONSTRAINT "PK_ItemStats" PRIMARY KEY ("ManifestId", "Id")+ CONSTRAINT "PK_ItemStats" PRIMARY KEY ("ManifestId", "Id", "DeviceId"));CREATE TABLE "Manifests" (@@ -1776,7 +1777,7 @@ CREATE INDEX "IX_EncryptionKeys_ManifestId_IsPrimary" ON "EncryptionKeys" ("ManiCOMMIT;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20260918090000_2.1.0-ManifestScopedStorage', '10.0.10');+VALUES ('20261009150000_2.1.0-ManifestScopedStorage', '10.0.12');BEGIN TRANSACTION;CREATE TRIGGER IF NOT EXISTS "TR_Items_ClearTombstoneBeforeReturn"@@ -1822,5 +1823,5 @@ COMMIT;PRAGMA foreign_keys = ON;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20260918090100_2.1.1-ItemChildManifestTrigger', '10.0.10');+VALUES ('20261009150100_2.1.1-ItemChildManifestTrigger', '10.0.12');diff --git a/apps/web/src/hooks/useClipboardCopy.ts b/apps/web/src/hooks/useClipboardCopy.tsindex d9e8ad997..f29c4bc72 100644--- a/apps/web/src/hooks/useClipboardCopy.ts+++ b/apps/web/src/hooks/useClipboardCopy.ts@@ -1,3 +1,4 @@+import { getOrCreateDeviceId } from '@aliasvault/client/platform/DeviceId';import { useCallback, useEffect, useState } from 'react';import { useDb } from '@/context/DbContext';@@ -33,7 +34,8 @@ export function useClipboardCopy(id: string, item?: ItemRef): { copied: boolean;// Stats-only writes push silently, without the sync indicator.executeVaultMutationInBackground(async () => {- if (!dbContext.sqliteClient?.itemStats.recordUsage({ Id: itemId, ManifestId: manifestId }, 'copy')) {+ const deviceId = await getOrCreateDeviceId();+ if (!dbContext.sqliteClient?.itemStats.recordUsage({ Id: itemId, ManifestId: manifestId }, 'copy', deviceId)) {throw new Error('Item not found');}}).catch((error) => devLog('[Clipboard] Failed to record item usage', error));diff --git a/core/client/src/constants/StorageKeys.ts b/core/client/src/constants/StorageKeys.tsindex 7a15ac313..dd86a5fad 100644--- a/core/client/src/constants/StorageKeys.ts+++ b/core/client/src/constants/StorageKeys.ts@@ -24,6 +24,8 @@ export const StorageKeys = {API_URL: 'local:apiUrl',/** Base URL of the web client, used for deep links. */CLIENT_URL: 'local:clientUrl',+ /** Random id of this install, which per-device vault rows (item usage statistics) are keyed by. */+ DEVICE_ID: 'local:deviceId',/** Version reported by the server on the last status call. */SERVER_VERSION: 'local:serverVersion',/** The capabilities that are enabled for this account passed from the server. */diff --git a/core/client/src/database/queries/ItemStatsQueries.ts b/core/client/src/database/queries/ItemStatsQueries.tsindex 51184a6c6..13d1fef92 100644--- a/core/client/src/database/queries/ItemStatsQueries.ts+++ b/core/client/src/database/queries/ItemStatsQueries.ts@@ -1,8 +1,8 @@/*** SQL query constants for per-item usage statistics.*- * A stats row is addressed by `(ManifestId, Id)` where `Id` *is* the item's id, so recording a use is an- * upsert against the item itself rather than a lookup through a foreign key.+ * A stats row is addressed by `(ManifestId, Id, DeviceId)` where `Id` *is* the item's id, so each device upserts its+ * own row of an item and never overwrites another device's counts.*/export class ItemStatsQueries {/**@@ -14,14 +14,14 @@ export class ItemStatsQueries {WHERE Id = ? AND ManifestId = ?`;/**- * Create the stats row for an item on its first recorded use.+ * Create this device's stats row for an item on its first recorded use.*/public static readonly INSERT_ROW = `INSERT OR IGNORE INTO ItemStats (- ManifestId, Id, LastUsedAt, UseCount, LastAutofilledAt, AutofillCount,+ ManifestId, Id, DeviceId, LastUsedAt, UseCount, LastAutofilledAt, AutofillCount,LastCopiedAt, CopyCount, LastPasskeyAuthAt, PasskeyAuthCount, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?, ?, NULL, 0, NULL, 0, NULL, 0, NULL, 0, ?, ?, 0)`;+ VALUES (?, ?, ?, NULL, 0, NULL, 0, NULL, 0, NULL, 0, ?, ?, 0)`;/*** Record one use of an item, bumping the aggregate and the per-action pair for `action`.@@ -31,7 +31,7 @@ export class ItemStatsQueries {* item was last emptied out of the trash.* @param lastColumn - The per-action timestamp column* @param countColumn - The per-action counter column- * @returns The UPDATE statement, taking (now, now, ManifestId, Id)+ * @returns The UPDATE statement, taking (now, now, now, ManifestId, Id, DeviceId)*/public static forAction(lastColumn: string, countColumn: string): string {return `@@ -42,6 +42,6 @@ export class ItemStatsQueries {${countColumn} = ${countColumn} + 1,UpdatedAt = ?,IsDeleted = 0- WHERE ManifestId = ? AND Id = ?`;+ WHERE ManifestId = ? AND Id = ? AND DeviceId = ?`;}}diff --git a/core/client/src/database/repositories/ItemStatsRepository.ts b/core/client/src/database/repositories/ItemStatsRepository.tsindex 20f95959a..544990e00 100644--- a/core/client/src/database/repositories/ItemStatsRepository.ts+++ b/core/client/src/database/repositories/ItemStatsRepository.ts@@ -23,21 +23,22 @@ const ACTION_COLUMNS: Record<ItemUsageAction, { last: string; count: string }> =*/export class ItemStatsRepository extends BaseRepository {/**- * Record one use of an item.+ * Record one use of an item in this device's row.* @param item - The item that was used, named by its manifest and id* @param action - What the user did with it- * @returns True when a use was recorded, false when no such item exists+ * @param deviceId - The random id of this install+ * @returns True when a use was recorded, false when no such item exists or no device id is given*/- public *recordUsage(item: ItemRef, action: ItemUsageAction): DbOp<boolean> {- if ((yield* this.query<{ Found: number }>(ItemStatsQueries.ITEM_EXISTS, [item.Id, item.ManifestId])).length === 0) {+ public *recordUsage(item: ItemRef, action: ItemUsageAction, deviceId: string): DbOp<boolean> {+ if (!deviceId || (yield* this.query<{ Found: number }>(ItemStatsQueries.ITEM_EXISTS, [item.Id, item.ManifestId])).length === 0) {return false;}const now = this.now();const columns = ACTION_COLUMNS[action];- yield* this.execute(ItemStatsQueries.INSERT_ROW, [item.ManifestId, item.Id, now, now]);- yield* this.execute(ItemStatsQueries.forAction(columns.last, columns.count), [now, now, now, item.ManifestId, item.Id]);+ yield* this.execute(ItemStatsQueries.INSERT_ROW, [item.ManifestId, item.Id, deviceId, now, now]);+ yield* this.execute(ItemStatsQueries.forAction(columns.last, columns.count), [now, now, now, item.ManifestId, item.Id, deviceId]);return true;}}diff --git a/core/client/src/platform/DeviceId.ts b/core/client/src/platform/DeviceId.tsnew file mode 100644index 000000000..00ac02165--- /dev/null+++ b/core/client/src/platform/DeviceId.ts@@ -0,0 +1,18 @@+import { StorageKeys } from '../constants/StorageKeys';++import { getPlatform } from './ClientPlatform';++/**+ * The random id of this install, created on first use. Per-device vault rows (item usage statistics) are keyed by it.+ * @returns The lowercase device id+ */+export async function getOrCreateDeviceId(): Promise<string> {+ const storage = getPlatform().storage;+ const stored = await storage.get<string>(StorageKeys.DEVICE_ID);+ if (stored) {+ return stored;+ }+ const deviceId = crypto.randomUUID().toLowerCase();+ await storage.set(StorageKeys.DEVICE_ID, deviceId);+ return deviceId;+}diff --git a/core/client/src/platform/index.ts b/core/client/src/platform/index.tsindex b64af6390..b6baee79b 100644--- a/core/client/src/platform/index.ts+++ b/core/client/src/platform/index.ts@@ -1,5 +1,6 @@export type { IAppIdentity } from './AppIdentity';export { getPlatform, setPlatform, tryGetPlatform, type IClientPlatform } from './ClientPlatform';+export { getOrCreateDeviceId } from './DeviceId';export type { IKeyValueStore, StorageKey } from './KeyValueStore';export { devError, devLog, devWarn, type ILogger } from './Logger';export type { ISqliteDatabase, ISqliteEngine, SqliteRow, SqliteValue } from './SqliteEngine';diff --git a/core/models/src/vault/VaultTableRegistry.ts b/core/models/src/vault/VaultTableRegistry.tsindex 2e25cdf92..5b674c7db 100644--- a/core/models/src/vault/VaultTableRegistry.ts+++ b/core/models/src/vault/VaultTableRegistry.ts@@ -60,11 +60,11 @@ export type VaultTableDefinition = {export const VAULT_TABLES: VaultTableDefinition[] = [{ Name: 'Items', ManifestScoped: true, PrimaryKey: ['Id'], ItemChild: false },/*- * ItemStats is keyed by the item it describes: Id is the item's id, so recording a use is an- * upsert and two devices never create competing rows. Listed after Items so a merge inserts the- * item first.+ * ItemStats holds one row per item per device: Id is the item's id and DeviceId the recording install, so a+ * device only ever updates its own row and last-write-wins never drops another device's counts. Listed after+ * Items so a merge inserts the item first.*/- { Name: 'ItemStats', ManifestScoped: true, PrimaryKey: ['Id'], ItemChild: true, BucketCategory: 'stats' },+ { Name: 'ItemStats', ManifestScoped: true, PrimaryKey: ['Id', 'DeviceId'], ItemChild: true, BucketCategory: 'stats' },/** FieldValues: a field value matches on the field it belongs to (FieldKey for system fields,* FieldDefinitionId for custom ones; exactly one is set), so independently created rows of the@@ -154,6 +154,7 @@ export const VAULT_COLUMN_NAMES: string[] = ['ParentFolderId','FolderId','LogoId',+ 'DeviceId','Kind','Source','FileData',diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rsindex 36001052a..211f84c8e 100644--- a/core/rust/src/bindings/uniffi_api.rs+++ b/core/rust/src/bindings/uniffi_api.rs@@ -484,9 +484,9 @@ impl SqliteMemoryDatabase {self.inner.with_connection(|conn| vault_items::replace_passkey(conn, &old_passkey_id, &manifest_id, &passkey, &url, logo.as_deref()))}- /// Record one use of an item; false when the item does not exist.- pub fn record_item_use(&self, item_id: String, manifest_id: String, action: vault_items::ItemUsageAction) -> Result<bool, VaultError> {- self.inner.with_connection(|conn| vault_items::record_item_use(conn, &item_id, &manifest_id, action))+ /// Record one use of an item by this device; false when the item does not exist.+ pub fn record_item_use(&self, item_id: String, manifest_id: String, device_id: String, action: vault_items::ItemUsageAction) -> Result<bool, VaultError> {+ self.inner.with_connection(|conn| vault_items::record_item_use(conn, &item_id, &manifest_id, &device_id, action))}}diff --git a/core/rust/src/sqlite_host/vault_schema.sql b/core/rust/src/sqlite_host/vault_schema.sqlindex bf7bd37ce..6b8888954 100644--- a/core/rust/src/sqlite_host/vault_schema.sql+++ b/core/rust/src/sqlite_host/vault_schema.sql@@ -75,13 +75,13 @@ CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");CREATE INDEX "IX_Passwords_CredentialId" ON "Passwords" ("CredentialId");INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240708094944_1.0.0-InitialMigration', '10.0.10');+VALUES ('20240708094944_1.0.0-InitialMigration', '10.0.12');COMMIT;BEGIN TRANSACTION;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240708224522_1.0.1-EmptyTestMigration', '10.0.10');+VALUES ('20240708224522_1.0.1-EmptyTestMigration', '10.0.12');COMMIT;@@ -89,7 +89,7 @@ BEGIN TRANSACTION;ALTER TABLE "Aliases" RENAME COLUMN "EmailPrefix" TO "Email";INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '10.0.10');+VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '10.0.12');COMMIT;@@ -104,7 +104,7 @@ CREATE TABLE "EncryptionKeys" ();INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240729105618_1.1.0-AddPkiTables', '10.0.10');+VALUES ('20240729105618_1.1.0-AddPkiTables', '10.0.12');COMMIT;@@ -117,7 +117,7 @@ CREATE TABLE "Settings" ();INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240805073413_1.2.0-AddSettingsTable', '10.0.10');+VALUES ('20240805073413_1.2.0-AddSettingsTable', '10.0.12');COMMIT;@@ -152,7 +152,7 @@ COMMIT;PRAGMA foreign_keys = 1;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '10.0.10');+VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '10.0.12');BEGIN TRANSACTION;CREATE TABLE "ef_temp_Credentials" (@@ -192,7 +192,7 @@ CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");COMMIT;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '10.0.10');+VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '10.0.12');BEGIN TRANSACTION;ALTER TABLE "Settings" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;@@ -210,7 +210,7 @@ ALTER TABLE "Attachment" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;ALTER TABLE "Aliases" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240916105320_1.4.0-AddSyncSupport', '10.0.10');+VALUES ('20240916105320_1.4.0-AddSyncSupport', '10.0.12');COMMIT;@@ -251,7 +251,7 @@ CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");COMMIT;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '10.0.10');+VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '10.0.12');BEGIN TRANSACTION;CREATE TABLE "TotpCodes" (@@ -268,7 +268,7 @@ CREATE TABLE "TotpCodes" (CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20250310131554_1.5.0-AddTotpCodes', '10.0.10');+VALUES ('20250310131554_1.5.0-AddTotpCodes', '10.0.12');COMMIT;@@ -691,7 +691,7 @@ CREATE INDEX "IX_Passkeys_CredentialId" ON "Passkeys" ("CredentialId");CREATE INDEX "IX_Passkeys_RpId" ON "Passkeys" ("RpId");INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20251014122838_1.6.0-AddPasskeys', '10.0.10');+VALUES ('20251014122838_1.6.0-AddPasskeys', '10.0.12');COMMIT;@@ -1290,11 +1290,11 @@ CREATE INDEX "IX_TotpCodes_ItemId" ON "TotpCodes" ("ItemId");COMMIT;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20251213111207_1.7.0-FieldBasedDataModelUpdate', '10.0.10');+VALUES ('20251213111207_1.7.0-FieldBasedDataModelUpdate', '10.0.12');BEGIN TRANSACTION;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20260130221620_2.0.0-MajorVersionBump', '10.0.10');+VALUES ('20260130221620_2.0.0-MajorVersionBump', '10.0.12');COMMIT;@@ -1373,6 +1373,7 @@ CREATE TABLE "CodecOverflows" (CREATE TABLE "ItemStats" ("ManifestId" TEXT COLLATE NOCASE NOT NULL,"Id" TEXT COLLATE NOCASE NOT NULL,+ "DeviceId" TEXT COLLATE NOCASE NOT NULL DEFAULT '',"LastUsedAt" TEXT NULL,"UseCount" INTEGER NOT NULL,"LastAutofilledAt" TEXT NULL,@@ -1384,7 +1385,7 @@ CREATE TABLE "ItemStats" ("CreatedAt" TEXT NOT NULL,"UpdatedAt" TEXT NOT NULL,"IsDeleted" INTEGER NOT NULL,- CONSTRAINT "PK_ItemStats" PRIMARY KEY ("ManifestId", "Id")+ CONSTRAINT "PK_ItemStats" PRIMARY KEY ("ManifestId", "Id", "DeviceId"));CREATE TABLE "Manifests" (@@ -1778,7 +1779,7 @@ CREATE INDEX "IX_EncryptionKeys_ManifestId_IsPrimary" ON "EncryptionKeys" ("ManiCOMMIT;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20260918090000_2.1.0-ManifestScopedStorage', '10.0.10');+VALUES ('20261009150000_2.1.0-ManifestScopedStorage', '10.0.12');BEGIN TRANSACTION;CREATE TRIGGER IF NOT EXISTS "TR_Items_ClearTombstoneBeforeReturn"@@ -1824,4 +1825,4 @@ COMMIT;PRAGMA foreign_keys = ON;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20260918090100_2.1.1-ItemChildManifestTrigger', '10.0.10');+VALUES ('20261009150100_2.1.1-ItemChildManifestTrigger', '10.0.12');diff --git a/core/rust/src/vault_codec/canonicalize.rs b/core/rust/src/vault_codec/canonicalize.rsindex f6b738b64..f1def1d7e 100644--- a/core/rust/src/vault_codec/canonicalize.rs+++ b/core/rust/src/vault_codec/canonicalize.rs@@ -15,7 +15,7 @@ use std::collections::HashMap;use serde_json::{json, Value};use super::integrity;-use super::normalize::{normalize_id_spelling, normalize_row_shapes};+use super::normalize::{drop_deviceless_item_stats, normalize_id_spelling, normalize_row_shapes};use super::hash::salted_blob_hash;use super::row::{blob_ref, inline_b64, is_deleted, str_col};use super::manifest::{BlobEntry, CanonicalizeInput, CanonicalizedManifest, CanonicalizedVault, CodecOverflow, DataBucket, Manifest, CodecRecord};@@ -67,7 +67,8 @@ pub fn canonicalize_from_sqlite(input: CanonicalizeInput) -> VaultResult<Canonic}let bucketed_names: Vec<String> = all_tables.keys().filter(|name| is_bucketed_table(name)).cloned().collect();- let bucketed_rows: Tables = bucketed_names.into_iter().filter_map(|name| all_tables.remove_entry(&name)).collect();+ let mut bucketed_rows: Tables = bucketed_names.into_iter().filter_map(|name| all_tables.remove_entry(&name)).collect();+ drop_deviceless_item_stats(&mut bucketed_rows);let snapshots: Tables = referenced_tables().into_iter().filter_map(|name| all_tables.get(name).map(|rows| (name.to_string(), rows.clone()))).collect();let manifest_ids: Vec<String> = input.manifests.iter().map(|spec| spec.manifest_id.clone()).collect();@@ -258,6 +259,7 @@ pub fn extract_buckets(category: String, manifest_ids: Vec<String>, mut tables:fold_overflow_tables(&mut tables, overflow.bucket_tables.get(&category));normalize_id_spelling(&mut tables);reject_unstamped_rows(&tables)?;+ drop_deviceless_item_stats(&mut tables);let mut buckets: Vec<DataBucket> = group_category_rows(tables, &manifest_ids).into_iter().map(|(manifest_id, tables)| bucket_with_extra(manifest_id, &category, tables, &overflow)).collect();buckets.sort_by(|a, b| a.manifest_id.cmp(&b.manifest_id));diff --git a/core/rust/src/vault_codec/normalize.rs b/core/rust/src/vault_codec/normalize.rsindex 508c23751..1d72f4b1e 100644--- a/core/rust/src/vault_codec/normalize.rs+++ b/core/rust/src/vault_codec/normalize.rs@@ -11,8 +11,8 @@ use super::types::{is_guid, is_id_column};use crate::common::timestamp::updated_at;use crate::vault_model::{id_key, MANIFEST_ID_COL, MULTI_VALUE_FIELD_KEYS, SINGLE_VALUE_FIELD_KEYS};use crate::vault_model::names::{- CHANGED_AT_COL, FIELD_DEFINITIONS_TABLE, FIELD_DEFINITION_ID_COL, FIELD_HISTORIES_TABLE, FIELD_KEY_COL,- FIELD_VALUES_TABLE, ID_COL, IS_MULTI_VALUE_COL, ITEM_ID_COL, ITEM_TAGS_TABLE, TAG_ID_COL, VALUE_INDEX_COL,+ CHANGED_AT_COL, DEVICE_ID_COL, FIELD_DEFINITIONS_TABLE, FIELD_DEFINITION_ID_COL, FIELD_HISTORIES_TABLE, FIELD_KEY_COL,+ FIELD_VALUES_TABLE, ID_COL, IS_MULTI_VALUE_COL, ITEM_ID_COL, ITEM_STATS_TABLE, ITEM_TAGS_TABLE, TAG_ID_COL, VALUE_INDEX_COL,};/// Domain-separation prefix for derived field value ids.@@ -76,6 +76,15 @@ pub(crate) fn normalize_row_shapes(tables: &mut HashMap<String, Vec<CodecRecord>if let Some(rows) = tables.get_mut(ITEM_TAGS_TABLE) {normalize_item_tags(rows);}+ drop_deviceless_item_stats(tables);+}++/// Drop ItemStats rows written before stats were kept per device. They carry no DeviceId, so on materialize they+/// would take the column default and collide with the same item's other device-less row.+pub(crate) fn drop_deviceless_item_stats(tables: &mut HashMap<String, Vec<CodecRecord>>) {+ if let Some(rows) = tables.get_mut(ITEM_STATS_TABLE) {+ rows.retain(|row| str_col(row, DEVICE_ID_COL).is_some_and(|device| !device.is_empty()));+ }}/// The materialize direction: a FieldValues or FieldHistories row without an `Id` is a row whosediff --git a/core/rust/src/vault_items/stats.rs b/core/rust/src/vault_items/stats.rsindex eac69bc60..ca880349d 100644--- a/core/rust/src/vault_items/stats.rs+++ b/core/rust/src/vault_items/stats.rs@@ -1,4 +1,4 @@-//! Per-item usage statistics.+//! Per-item usage statistics, one row per item per device.use rusqlite::{params, Connection, OptionalExtension};@@ -22,9 +22,9 @@ impl ItemUsageAction {/// The UPDATE for this action. The column names are a closed set, never caller input.fn update_sql(self) -> &'static str {match self {- Self::Autofill => "UPDATE ItemStats SET LastUsedAt = ?1, UseCount = UseCount + 1, LastAutofilledAt = ?1, AutofillCount = AutofillCount + 1, UpdatedAt = ?1, IsDeleted = 0 WHERE ManifestId = ?2 AND Id = ?3",- Self::Copy => "UPDATE ItemStats SET LastUsedAt = ?1, UseCount = UseCount + 1, LastCopiedAt = ?1, CopyCount = CopyCount + 1, UpdatedAt = ?1, IsDeleted = 0 WHERE ManifestId = ?2 AND Id = ?3",- Self::Passkey => "UPDATE ItemStats SET LastUsedAt = ?1, UseCount = UseCount + 1, LastPasskeyAuthAt = ?1, PasskeyAuthCount = PasskeyAuthCount + 1, UpdatedAt = ?1, IsDeleted = 0 WHERE ManifestId = ?2 AND Id = ?3",+ Self::Autofill => "UPDATE ItemStats SET LastUsedAt = ?1, UseCount = UseCount + 1, LastAutofilledAt = ?1, AutofillCount = AutofillCount + 1, UpdatedAt = ?1, IsDeleted = 0 WHERE ManifestId = ?2 AND Id = ?3 AND DeviceId = ?4",+ Self::Copy => "UPDATE ItemStats SET LastUsedAt = ?1, UseCount = UseCount + 1, LastCopiedAt = ?1, CopyCount = CopyCount + 1, UpdatedAt = ?1, IsDeleted = 0 WHERE ManifestId = ?2 AND Id = ?3 AND DeviceId = ?4",+ Self::Passkey => "UPDATE ItemStats SET LastUsedAt = ?1, UseCount = UseCount + 1, LastPasskeyAuthAt = ?1, PasskeyAuthCount = PasskeyAuthCount + 1, UpdatedAt = ?1, IsDeleted = 0 WHERE ManifestId = ?2 AND Id = ?3 AND DeviceId = ?4",}}}@@ -33,20 +33,24 @@ const ITEM_EXISTS: &str = "SELECT 1 FROM Items WHERE Id = ?1 AND ManifestId = ?2const INSERT_ROW: &str = "INSERT OR IGNORE INTO ItemStats (- ManifestId, Id, LastUsedAt, UseCount, LastAutofilledAt, AutofillCount,+ ManifestId, Id, DeviceId, LastUsedAt, UseCount, LastAutofilledAt, AutofillCount,LastCopiedAt, CopyCount, LastPasskeyAuthAt, PasskeyAuthCount, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?1, ?2, NULL, 0, NULL, 0, NULL, 0, NULL, 0, ?3, ?3, 0)";+ VALUES (?1, ?2, ?3, NULL, 0, NULL, 0, NULL, 0, NULL, 0, ?4, ?4, 0)";-/// Record one use of an item. Returns false, writing nothing, when the item does not exist. Clearing-/// `IsDeleted` revives a row the pruner tombstoned.-pub fn record_item_use(conn: &Connection, item_id: &str, manifest_id: &str, action: ItemUsageAction) -> VaultResult<bool> {+/// Record one use of an item in this device's row. Returns false, writing nothing, when the item does not exist or+/// no device id is given. Clearing `IsDeleted` revives a row the pruner tombstoned.+pub fn record_item_use(conn: &Connection, item_id: &str, manifest_id: &str, device_id: &str, action: ItemUsageAction) -> VaultResult<bool> {let item_id = crate::vault_model::id_key(item_id);+ let device_id = crate::vault_model::id_key(device_id);+ if device_id.is_empty() {+ return Ok(false);+ }if conn.query_row(ITEM_EXISTS, params![item_id, manifest_id], |_| Ok(())).optional().map_err(sql_error)?.is_none() {return Ok(false);}let now = now_vault_datetime();- conn.execute(INSERT_ROW, params![manifest_id, item_id, now]).map_err(sql_error)?;- conn.execute(action.update_sql(), params![now, manifest_id, item_id]).map_err(sql_error)?;+ conn.execute(INSERT_ROW, params![manifest_id, item_id, device_id, now]).map_err(sql_error)?;+ conn.execute(action.update_sql(), params![now, manifest_id, item_id, device_id]).map_err(sql_error)?;Ok(true)}diff --git a/core/rust/src/vault_items/tests.rs b/core/rust/src/vault_items/tests.rsindex 4541abc10..b54299e37 100644--- a/core/rust/src/vault_items/tests.rs+++ b/core/rust/src/vault_items/tests.rs@@ -7,6 +7,8 @@ use crate::vault_codec::logo_id_for;const PERSONAL: &str = "11111111-1111-4111-8111-111111111111";const SHARED: &str = "22222222-2222-4222-8222-222222222222";const ITEM: &str = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";+const DEVICE: &str = "6f1c1a2e-3b4d-4c5e-8f60-718293a4b5c6";+const OTHER_DEVICE: &str = "0a9b8c7d-6e5f-4a3b-9c2d-1e0f2a3b4c5d";const T0: &str = "2026-01-01 10:00:00.000";const T1: &str = "2026-01-02 10:00:00.000";@@ -190,15 +192,29 @@ fn merge_candidates_are_matched_by_rp_id_and_stay_apart_per_manifest() {fn recording_a_use_counts_per_action_and_ignores_missing_items() {with_vault(|conn| {insert_item(conn, PERSONAL, ITEM, "Example", T0);- assert!(record_item_use(conn, ITEM, PERSONAL, ItemUsageAction::Autofill).unwrap());- assert!(record_item_use(conn, ITEM, PERSONAL, ItemUsageAction::Passkey).unwrap());- assert!(!record_item_use(conn, ITEM, SHARED, ItemUsageAction::Copy).unwrap());+ assert!(record_item_use(conn, ITEM, PERSONAL, DEVICE, ItemUsageAction::Autofill).unwrap());+ assert!(record_item_use(conn, ITEM, PERSONAL, DEVICE, ItemUsageAction::Passkey).unwrap());+ assert!(!record_item_use(conn, ITEM, SHARED, DEVICE, ItemUsageAction::Copy).unwrap());+ assert!(!record_item_use(conn, ITEM, PERSONAL, "", ItemUsageAction::Copy).unwrap(), "a use without a device is not recorded");let counts: (i64, i64, i64) = conn.query_row("SELECT UseCount, AutofillCount, PasskeyAuthCount FROM ItemStats", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).unwrap();assert_eq!(counts, (2, 1, 1));});}+#[test]+fn each_device_counts_the_uses_of_an_item_in_its_own_row() {+ with_vault(|conn| {+ insert_item(conn, PERSONAL, ITEM, "Example", T0);+ assert!(record_item_use(conn, ITEM, PERSONAL, DEVICE, ItemUsageAction::Autofill).unwrap());+ assert!(record_item_use(conn, ITEM, PERSONAL, OTHER_DEVICE, ItemUsageAction::Copy).unwrap());+ assert!(record_item_use(conn, ITEM, PERSONAL, OTHER_DEVICE, ItemUsageAction::Copy).unwrap());++ let rows = conn.query_row("SELECT COUNT(*), SUM(UseCount) FROM ItemStats WHERE Id = ?1", [ITEM], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?))).unwrap();+ assert_eq!(rows, (2, 3));+ });+}+#[test]fn appended_values_go_after_the_existing_ones() {with_vault(|conn| {diff --git a/core/rust/src/vault_merge/tests.rs b/core/rust/src/vault_merge/tests.rsindex 4b83a18c1..24d466c0d 100644--- a/core/rust/src/vault_merge/tests.rs+++ b/core/rust/src/vault_merge/tests.rs@@ -45,7 +45,7 @@ fn schema() -> HashMap<String, Vec<String>> {("Items".to_string(), columns(&["ManifestId", "Id", "Name", "IsDeleted", "DeletedAt", "UpdatedAt"])),("TotpCodes".to_string(), columns(&["ManifestId", "Id", "ItemId", "SecretKey", "IsDeleted", "UpdatedAt"])),("Settings".to_string(), columns(&["ManifestId", "Key", "Value", "UpdatedAt"])),- ("ItemStats".to_string(), columns(&["ManifestId", "Id", "LastUsedAt", "UpdatedAt"])),+ ("ItemStats".to_string(), columns(&["ManifestId", "Id", "DeviceId", "UseCount", "LastUsedAt", "UpdatedAt"])),("FieldValues".to_string(), columns(&["ManifestId", "Id", "ItemId", "FieldKey", "FieldDefinitionId", "ValueIndex", "Value", "IsDeleted", "UpdatedAt"])),("ItemTags".to_string(), columns(&["ManifestId", "ItemId", "TagId", "UpdatedAt"])),("Attachments".to_string(), columns(&["ManifestId", "Id", "Blob", "UpdatedAt"])),@@ -361,7 +361,7 @@ fn a_permanent_delete_is_settled_against_the_item_as_a_unit_both_ways() {#[test]fn a_usage_counter_does_not_outlive_a_delete() {// ItemStats ticks on every autofill; that is not an edit and must not undo a delete.- let stats = at(T_NEW, &[("Id", json!("item-1")), ("LastUsedAt", json!(T_NEW))]);+ let stats = at(T_NEW, &[("Id", json!("item-1")), ("DeviceId", json!("device-a")), ("LastUsedAt", json!(T_NEW))]);let output = merge_with_buckets(vec![item_manifest(vec![tombstone("item-1", T_MID)], vec![])], vec![], vec![item_manifest(vec![item("item-1", "item", T_OLD)], vec![])], vec![DataBucket::new(PERSONAL, "stats", [("ItemStats".to_string(), vec![stats])].into_iter().collect())]);let merged = &output.manifests[0];assert_eq!(merged.manifest.tables["Items"][0]["IsDeleted"], json!(1));@@ -380,3 +380,30 @@ fn an_item_moved_to_another_manifest_does_not_stay_behind_in_the_one_it_left() {assert_eq!(by_id[SHARED].manifest.tables["Items"][0]["IsDeleted"], json!(0));assert_eq!(live_values(by_id[SHARED]), vec!["secret"], "and the moved item arrives whole");}++#[test]+fn two_devices_using_one_item_keep_both_counts() {+ // Each device writes only its own row, so the newer device's row cannot replace the other's count.+ let use_row = |device: &str, count: i64, updated_at: &str| at(updated_at, &[("Id", json!("item-1")), ("DeviceId", json!(device)), ("UseCount", json!(count)), ("LastUsedAt", json!(updated_at))]);+ let stats_bucket = |rows: Vec<CodecRecord>| DataBucket::new(PERSONAL, "stats", [("ItemStats".to_string(), rows)].into_iter().collect());+ let items = || item_manifest(vec![item("item-1", "item", T_OLD)], vec![]);++ let output = merge_with_buckets(vec![items()], vec![stats_bucket(vec![use_row("device-web", 51, T_NEW)])], vec![items()], vec![stats_bucket(vec![use_row("device-phone", 55, T_MID)])]);++ let stats = output.manifests[0].buckets.iter().find(|b| b.category == "stats").expect("stats bucket");+ let mut counts: Vec<(String, i64)> = stats.tables["ItemStats"].iter().map(|r| (r["DeviceId"].as_str().unwrap().to_string(), r["UseCount"].as_i64().unwrap())).collect();+ counts.sort();+ assert_eq!(counts, vec![("device-phone".to_string(), 55), ("device-web".to_string(), 51)]);+}++#[test]+fn a_stats_row_without_a_device_is_dropped() {+ // Rows from before stats were kept per device would collide on materialize, so they do not survive a merge.+ let legacy = at(T_NEW, &[("Id", json!("item-1")), ("UseCount", json!(9)), ("LastUsedAt", json!(T_NEW))]);+ let stats_bucket = |rows: Vec<CodecRecord>| DataBucket::new(PERSONAL, "stats", [("ItemStats".to_string(), rows)].into_iter().collect());+ let items = || item_manifest(vec![item("item-1", "item", T_OLD)], vec![]);++ let output = merge_with_buckets(vec![items()], vec![stats_bucket(vec![legacy])], vec![items()], vec![]);++ assert!(output.manifests[0].buckets.iter().all(|b| b.tables.get("ItemStats").is_none_or(Vec::is_empty)));+}diff --git a/core/rust/src/vault_model/generated.rs b/core/rust/src/vault_model/generated.rsindex 85c759e9c..95d74fc01 100644--- a/core/rust/src/vault_model/generated.rs+++ b/core/rust/src/vault_model/generated.rs@@ -11,7 +11,7 @@ use super::{BlobColumn, SystemField, TableConfig};/// Per-table rationale (merge key choices, natural keys) is documented in the TypeScript source.pub static SYNCABLE_TABLES: &[TableConfig] = &[TableConfig::new("Items").manifest_scoped(),- TableConfig::new("ItemStats").manifest_scoped().item_child(),+ TableConfig::new("ItemStats").manifest_scoped().item_child().with_primary_key(&["Id", "DeviceId"]),TableConfig::new("FieldValues").manifest_scoped().item_child()@@ -195,6 +195,8 @@ pub mod names {pub const FOLDER_ID_COL: &str = "FolderId";/// The `LogoId` column.pub const LOGO_ID_COL: &str = "LogoId";+ /// The `DeviceId` column.+ pub const DEVICE_ID_COL: &str = "DeviceId";/// The `Kind` column.pub const KIND_COL: &str = "Kind";/// The `Source` column.diff --git a/core/rust/src/vault_sync/tests/mod.rs b/core/rust/src/vault_sync/tests/mod.rsindex 1dfb2c876..3c4b6f1ea 100644--- a/core/rust/src/vault_sync/tests/mod.rs+++ b/core/rust/src/vault_sync/tests/mod.rs@@ -66,8 +66,8 @@ pub fn insert_attachment(conn: &Connection, item_id: &str, bytes: Option<&[u8]>)conn.execute("INSERT INTO Attachments (ManifestId, Id, ItemId, Filename, Blob, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, 'passport.pdf', ?, ?, ?, 0)", rusqlite::params![PERSONAL_MANIFEST_ID, ATTACHMENT, item_id, bytes, now(), now()]).unwrap();}-pub fn insert_item_stats(conn: &Connection, item_id: &str, use_count: i64) {- conn.execute("INSERT INTO ItemStats (ManifestId, Id, UseCount, AutofillCount, CopyCount, PasskeyAuthCount, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, 0, 0, 0, ?, ?, 0)", rusqlite::params![PERSONAL_MANIFEST_ID, item_id, use_count, now(), now()]).unwrap();+pub fn insert_item_stats(conn: &Connection, item_id: &str, device_id: &str, use_count: i64) {+ conn.execute("INSERT INTO ItemStats (ManifestId, Id, DeviceId, UseCount, AutofillCount, CopyCount, PasskeyAuthCount, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, 0, 0, 0, ?, ?, 0)", rusqlite::params![PERSONAL_MANIFEST_ID, item_id, device_id, use_count, now(), now()]).unwrap();}/// Rename every item, stamped now: a local edit newer than the synced state.diff --git a/core/rust/src/vault_sync/tests/sync.rs b/core/rust/src/vault_sync/tests/sync.rsindex 07a77e87e..352e2ce11 100644--- a/core/rust/src/vault_sync/tests/sync.rs+++ b/core/rust/src/vault_sync/tests/sync.rs@@ -9,6 +9,10 @@ use crate::crypto;use crate::vault_codec;use crate::vault_sync::session::SyncSession;+/// The install ids the stats tests record uses under.+const THIS_DEVICE: &str = "6f1c1a2e-3b4d-4c5e-8f60-718293a4b5c6";+const OTHER_DEVICE: &str = "0a9b8c7d-6e5f-4a3b-9c2d-1e0f2a3b4c5d";+#[test]fn fresh_client_pulls_and_materializes_the_server_vault() {let vek = crypto::generate_key_base64();@@ -255,7 +259,7 @@ fn bucket_only_push_writes_the_manifest_while_the_personal_delivery_key_is_missilet mut s = synced(|db| insert_item(db, ITEM_A, "Server item"));let category = vault_codec::bucket_layout()[0].category.clone();- s.host.edit(|db| insert_item_stats(db, ITEM_A, 1));+ s.host.edit(|db| insert_item_stats(db, ITEM_A, THIS_DEVICE, 1));let result = s.host.sync_scoped(&[category.as_str()]);assert_eq!(result["success"], true, "{}", result);@@ -298,10 +302,10 @@ fn outdated_bucket_only_push_merges_the_server_bucket_instead_of_overwriting_it(// Another device writes the stats of item B after this client's status check, while this one used item A.let stale_status = s.server.borrow().status();- insert_item_stats(&s.db, ITEM_B, 5);+ insert_item_stats(&s.db, ITEM_B, OTHER_DEVICE, 5);s.publish(8);s.host.respond_once("GET", "Status", stale_status);- s.host.edit(|db| insert_item_stats(db, ITEM_A, 1));+ s.host.edit(|db| insert_item_stats(db, ITEM_A, THIS_DEVICE, 1));let result = s.host.sync_scoped(&["stats"]);diff --git a/core/vault/src/sql/SqlConstants.ts b/core/vault/src/sql/SqlConstants.tsindex 1d6ebc3c2..00a6e534e 100644--- a/core/vault/src/sql/SqlConstants.ts+++ b/core/vault/src/sql/SqlConstants.ts@@ -80,13 +80,13 @@ CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");CREATE INDEX "IX_Passwords_CredentialId" ON "Passwords" ("CredentialId");INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240708094944_1.0.0-InitialMigration', '10.0.10');+VALUES ('20240708094944_1.0.0-InitialMigration', '10.0.12');COMMIT;BEGIN TRANSACTION;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240708224522_1.0.1-EmptyTestMigration', '10.0.10');+VALUES ('20240708224522_1.0.1-EmptyTestMigration', '10.0.12');COMMIT;@@ -94,7 +94,7 @@ BEGIN TRANSACTION;ALTER TABLE "Aliases" RENAME COLUMN "EmailPrefix" TO "Email";INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '10.0.10');+VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '10.0.12');COMMIT;@@ -109,7 +109,7 @@ CREATE TABLE "EncryptionKeys" ();INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240729105618_1.1.0-AddPkiTables', '10.0.10');+VALUES ('20240729105618_1.1.0-AddPkiTables', '10.0.12');COMMIT;@@ -122,7 +122,7 @@ CREATE TABLE "Settings" ();INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240805073413_1.2.0-AddSettingsTable', '10.0.10');+VALUES ('20240805073413_1.2.0-AddSettingsTable', '10.0.12');COMMIT;@@ -157,7 +157,7 @@ COMMIT;PRAGMA foreign_keys = 1;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '10.0.10');+VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '10.0.12');BEGIN TRANSACTION;CREATE TABLE "ef_temp_Credentials" (@@ -197,7 +197,7 @@ CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");COMMIT;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '10.0.10');+VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '10.0.12');BEGIN TRANSACTION;ALTER TABLE "Settings" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;@@ -215,7 +215,7 @@ ALTER TABLE "Attachment" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;ALTER TABLE "Aliases" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240916105320_1.4.0-AddSyncSupport', '10.0.10');+VALUES ('20240916105320_1.4.0-AddSyncSupport', '10.0.12');COMMIT;@@ -256,7 +256,7 @@ CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");COMMIT;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '10.0.10');+VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '10.0.12');BEGIN TRANSACTION;CREATE TABLE "TotpCodes" (@@ -273,7 +273,7 @@ CREATE TABLE "TotpCodes" (CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20250310131554_1.5.0-AddTotpCodes', '10.0.10');+VALUES ('20250310131554_1.5.0-AddTotpCodes', '10.0.12');COMMIT;@@ -696,7 +696,7 @@ CREATE INDEX "IX_Passkeys_CredentialId" ON "Passkeys" ("CredentialId");CREATE INDEX "IX_Passkeys_RpId" ON "Passkeys" ("RpId");INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20251014122838_1.6.0-AddPasskeys', '10.0.10');+VALUES ('20251014122838_1.6.0-AddPasskeys', '10.0.12');COMMIT;@@ -1295,11 +1295,11 @@ CREATE INDEX "IX_TotpCodes_ItemId" ON "TotpCodes" ("ItemId");COMMIT;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20251213111207_1.7.0-FieldBasedDataModelUpdate', '10.0.10');+VALUES ('20251213111207_1.7.0-FieldBasedDataModelUpdate', '10.0.12');BEGIN TRANSACTION;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20260130221620_2.0.0-MajorVersionBump', '10.0.10');+VALUES ('20260130221620_2.0.0-MajorVersionBump', '10.0.12');COMMIT;@@ -1378,6 +1378,7 @@ CREATE TABLE "CodecOverflows" (CREATE TABLE "ItemStats" ("ManifestId" TEXT COLLATE NOCASE NOT NULL,"Id" TEXT COLLATE NOCASE NOT NULL,+ "DeviceId" TEXT COLLATE NOCASE NOT NULL DEFAULT '',"LastUsedAt" TEXT NULL,"UseCount" INTEGER NOT NULL,"LastAutofilledAt" TEXT NULL,@@ -1389,7 +1390,7 @@ CREATE TABLE "ItemStats" ("CreatedAt" TEXT NOT NULL,"UpdatedAt" TEXT NOT NULL,"IsDeleted" INTEGER NOT NULL,- CONSTRAINT "PK_ItemStats" PRIMARY KEY ("ManifestId", "Id")+ CONSTRAINT "PK_ItemStats" PRIMARY KEY ("ManifestId", "Id", "DeviceId"));CREATE TABLE "Manifests" (@@ -1783,7 +1784,7 @@ CREATE INDEX "IX_EncryptionKeys_ManifestId_IsPrimary" ON "EncryptionKeys" ("ManiCOMMIT;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20260918090000_2.1.0-ManifestScopedStorage', '10.0.10');+VALUES ('20261009150000_2.1.0-ManifestScopedStorage', '10.0.12');BEGIN TRANSACTION;CREATE TRIGGER IF NOT EXISTS "TR_Items_ClearTombstoneBeforeReturn"@@ -1829,7 +1830,7 @@ COMMIT;PRAGMA foreign_keys = ON;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")-VALUES ('20260918090100_2.1.1-ItemChildManifestTrigger', '10.0.10');+VALUES ('20261009150100_2.1.1-ItemChildManifestTrigger', '10.0.12');`;/*** Individual migration SQL scripts