Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Tweak item usage trigger to be applied to browser extension popup context instead of via background
Leendert de Borst00d4ca41ec45
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex 9620635e4..0e8ea4516 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -738,6 +738,7 @@ export async function handleStoreEncryptedVault(request: {markDirty?: boolean;expectedMutationSeq?: number;scopes?: VaultMutationScope[];+ sourceId?: string;}): Promise<{ success: boolean; mutationSequence: number }> {let mutationSequence = await storage.getItem(StorageKeys.MUTATION_SEQUENCE) as number | null ?? 0;@@ -777,6 +778,8 @@ export async function handleStoreEncryptedVault(request: {cachedSqliteClient = null;cachedVaultBlob = null;+ sendMessage('VAULT_STORED', { sourceId: request.sourceId }).catch(() => {});+return { success: true, mutationSequence };}diff --git a/apps/browser-extension/src/entrypoints/popup/components/Forms/FormInputCopyToClipboard.tsx b/apps/browser-extension/src/entrypoints/popup/components/Forms/FormInputCopyToClipboard.tsxindex 99ee4f642..8894caed7 100644--- a/apps/browser-extension/src/entrypoints/popup/components/Forms/FormInputCopyToClipboard.tsx+++ b/apps/browser-extension/src/entrypoints/popup/components/Forms/FormInputCopyToClipboard.tsx@@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';import { useTranslation } from 'react-i18next';import Icon from '@/entrypoints/popup/components/Icons/Icon';+import { useRecordItemCopy } from '@/entrypoints/popup/hooks/useRecordItemCopy';import { ClipboardCopyService } from '@/entrypoints/popup/utils/ClipboardCopyService';import { logExpected } from '@/utils/Diagnostics';@@ -37,6 +38,7 @@ export const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> =}) => {const { t } = useTranslation();const [showPassword, setShowPassword] = useState(false);+ const recordItemCopy = useRecordItemCopy();const [copied, setCopied] = useState(false);useEffect(() => {@@ -60,11 +62,7 @@ export const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> =await sendMessage('CLIPBOARD_COPIED');// Record the use against the item this field belongs to, where one is known.- if (itemId && manifestId) {- sendMessage('RECORD_ITEM_USAGE', { itemId, manifestId, action: 'copy' }).catch(() => {- // Ignore errors- });- }+ recordItemCopy(itemId, manifestId);// Reset copied state after 2 secondssetTimeout(() => {diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsxindex 48e4dc3ab..a159cc16c 100644--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx@@ -3,6 +3,7 @@ import React, { useState, useEffect } from 'react';import { useTranslation } from 'react-i18next';import { useDb } from '@/entrypoints/popup/context/DbContext';+import { useRecordItemCopy } from '@/entrypoints/popup/hooks/useRecordItemCopy';import { logExpected, logFailure } from '@/utils/Diagnostics';import { sendMessage } from '@/utils/messaging/ExtensionMessaging';@@ -38,6 +39,7 @@ const TotpBlock: React.FC<TotpBlockProps> = ({ itemId, manifestId }) => {const [currentCodes, setCurrentCodes] = useState<Record<string, string>>({});const [copiedId, setCopiedId] = useState<string | null>(null);const dbContext = useDb();+ const recordItemCopy = useRecordItemCopy();/*** Copies a TOTP code to the clipboard.@@ -54,9 +56,7 @@ const TotpBlock: React.FC<TotpBlockProps> = ({ itemId, manifestId }) => {* Record the use against the item. The auto-copy that follows an autofill deliberately does not go* through here: that interaction is already counted as an autofill, and would otherwise count twice.*/- sendMessage('RECORD_ITEM_USAGE', { itemId, manifestId, action: 'copy' }).catch(() => {- // Ignore errors- });+ recordItemCopy(itemId, manifestId);// Reset copied state after 2 secondssetTimeout(() => {diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsxindex 9df384456..532efa89b 100644--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';import { StorageKeys } from '@/utils/constants/storageKeys';import { logFailure } from '@/utils/Diagnostics';import { onMessage, sendMessage } from '@/utils/messaging/ExtensionMessaging';+import { VAULT_STORE_SOURCE_ID } from '@/utils/messaging/VaultBlobTransfer';import { markOwnAccountKey, vaultStateEvents } from '@/events/VaultStateEvents';import { t } from '@/i18n/StandaloneI18n';@@ -111,6 +112,10 @@ type DbContextType = {* Dismiss the current sync error (clears both React state and persisted storage).*/clearSyncError: () => Promise<void>;+ /**+ * Run a write of this window's vault; stores by others are not loaded over it while it runs.+ */+ runLocalVaultWrite: <T>(write: () => Promise<T>) => Promise<T>;}const DbContext = createContext<DbContextType | undefined>(undefined);@@ -126,6 +131,9 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }*/const [sqliteClient, setSqliteClient] = useState<SqliteClient | null>(null);+ /** Writes of this window still in progress; see runLocalVaultWrite. */+ const localWritesInFlightRef = useRef(0);+/*** Database initialization state. If true, the database has been initialized and the dbAvailable state is correct.*/@@ -395,6 +403,30 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }await sendMessage('STORE_UNLOCK_KEY_DERIVATION_PARAMS', params);}, []);+ const runLocalVaultWrite = useCallback(async <T,>(write: () => Promise<T>): Promise<T> => {+ localWritesInFlightRef.current++;+ try {+ return await write();+ } finally {+ localWritesInFlightRef.current--;+ }+ }, []);++ /**+ * Reload the loaded vault when the background stores one this window did not write.+ */+ useEffect(() => {+ if (!sqliteClient) {+ return undefined;+ }+ return onMessage('VAULT_STORED', ({ data }) => {+ if (data.sourceId === VAULT_STORE_SOURCE_ID || localWritesInFlightRef.current > 0) {+ return;+ }+ loadStoredDatabase().catch((error) => logFailure('Reloading the vault after a background write failed', error));+ });+ }, [sqliteClient, loadStoredDatabase]);+/*** Clear database and remove from background worker, called when logging out.*/@@ -433,7 +465,8 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }requiresManifestMigration,syncError,clearSyncError,- }), [sqliteClient, dbInitialized, dbAvailable, isOffline, getIsOffline, hasUnsyncedUserChanges, isSyncing, isUploading, setIsOffline, shouldSuppressEmailErrors, loadStoredDatabase, storeAccountKey, storeUnlockKeyDerivationParams, clearDatabase, getVaultMetadata, refreshSyncState, requiresLegacySqliteBlobMigration, requiresManifestMigration, syncError, clearSyncError]);+ runLocalVaultWrite,+ }), [sqliteClient, dbInitialized, dbAvailable, isOffline, getIsOffline, hasUnsyncedUserChanges, isSyncing, isUploading, setIsOffline, shouldSuppressEmailErrors, loadStoredDatabase, storeAccountKey, storeUnlockKeyDerivationParams, clearDatabase, getVaultMetadata, refreshSyncState, requiresLegacySqliteBlobMigration, requiresManifestMigration, syncError, clearSyncError, runLocalVaultWrite]);return (<DbContext.Provider value={contextValue}>diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useRecordItemCopy.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useRecordItemCopy.tsnew file mode 100644index 000000000..2f6a1945a--- /dev/null+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useRecordItemCopy.ts@@ -0,0 +1,26 @@+import { getOrCreateDeviceId } from '@aliasvault/client/platform/DeviceId';+import { useCallback } from 'react';++import { useDb } from '@/entrypoints/popup/context/DbContext';+import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';++import { logExpected } from '@/utils/Diagnostics';++/**+ * Record a copied value in its item's usage statistics.+ */+export function useRecordItemCopy(): (itemId?: string, manifestId?: string) => void {+ const dbContext = useDb();+ const { executeVaultMutationAsync } = useVaultMutate();++ return useCallback((itemId?: string, manifestId?: string): void => {+ const client = dbContext.sqliteClient;+ if (!itemId || !manifestId || !client) {+ return;+ }+ executeVaultMutationAsync(async () => {+ // No such item (deleted between copy and record) leaves nothing to attribute the use to.+ client.itemStats.recordUsage({ Id: itemId, ManifestId: manifestId }, 'copy', await getOrCreateDeviceId());+ }).catch((error) => logExpected('[Clipboard] Recording the item usage failed', error));+ }, [dbContext.sqliteClient, executeVaultMutationAsync]);+}diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.tsindex cab24e8b7..802baac8a 100644--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts@@ -41,7 +41,7 @@ export function useVaultMutate(): {* Atomically increments mutation sequence and marks dirty.* @returns The scopes the operation wrote into*/- const saveLocally = useCallback(async (operation: () => Promise<void>): Promise<VaultMutationScope[]> => {+ const saveLocally = useCallback((operation: () => Promise<void>): Promise<VaultMutationScope[]> => dbContext.runLocalVaultWrite(async () => {// Execute the provided operation (e.g. create/update/delete credential)await operation();@@ -72,7 +72,7 @@ export function useVaultMutate(): {// Refresh the sync state in Reactawait dbContext.refreshSyncState();return scopes;- }, [dbContext]);+ }), [dbContext]);/*** Start polling to detect when background sync completes.diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.tsindex f40d99118..d57f6e17b 100644--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts@@ -43,6 +43,7 @@ export type VaultBlobStoreOptions = {markDirty?: boolean;expectedMutationSeq?: number;scopes?: VaultMutationScope[];+ sourceId?: string;};/* eslint-disable @typescript-eslint/no-explicit-any */@@ -123,6 +124,7 @@ export interface IExtensionMessageProtocol {STORE_UNLOCK_KEY_DERIVATION_PARAMS(data: UnlockKeyDerivationParams): BoolResponse;STORE_SAVE_PROMPT_STATE(data: SavePromptPersistedState): { success: boolean };TOGGLE_CONTEXT_MENU(data: any): BoolResponse;+ VAULT_STORED(data: { sourceId?: string }): void;VAULT_SYNC_PHASE(data: { phase: VaultSyncPhase }): void;VAULT_UNLOCKED(): void;WEBAUTHN_CREATE(data: any): any;diff --git a/apps/browser-extension/src/utils/messaging/VaultBlobTransfer.ts b/apps/browser-extension/src/utils/messaging/VaultBlobTransfer.tsindex c5293661e..6255fc02f 100644--- a/apps/browser-extension/src/utils/messaging/VaultBlobTransfer.ts+++ b/apps/browser-extension/src/utils/messaging/VaultBlobTransfer.ts@@ -6,6 +6,11 @@ import { sendMessage, type VaultBlobStoreOptions } from '@/utils/messaging/Exten*/const VAULT_BLOB_CHUNK_CHARS = 8 * 1024 * 1024;+/**+ * Identifies this extension page in the stores it makes, see VAULT_STORED.+ */+export const VAULT_STORE_SOURCE_ID = crypto.randomUUID();+/*** Send an encrypted vault blob to the background in chunks and store it there. The last chunk carries the store options.* @param vaultBlob - the encrypted vault blob@@ -21,5 +26,5 @@ export async function storeEncryptedVault(vaultBlob: string, options: VaultBlobSconst lastIndex = chunkCount - 1;// A chunk that carries the store options always gets the store result back, never null.- return (await sendMessage('STORE_ENCRYPTED_VAULT', { transferId, index: lastIndex, chunk: vaultBlob.slice(lastIndex * VAULT_BLOB_CHUNK_CHARS), commit: options }))!;+ return (await sendMessage('STORE_ENCRYPTED_VAULT', { transferId, index: lastIndex, chunk: vaultBlob.slice(lastIndex * VAULT_BLOB_CHUNK_CHARS), commit: { ...options, sourceId: VAULT_STORE_SOURCE_ID } }))!;}diff --git a/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsx b/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsxindex 38bff113f..0ad2aa8e9 100644--- a/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsx+++ b/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsx@@ -211,9 +211,13 @@ export default function FolderViewScreen(): React.ReactNode {const itemChangedSub = emitter.addListener('itemChanged', async () => {await loadItems();});+ const itemUsedSub = emitter.addListener('itemUsed', async () => {+ await loadItems();+ });return (): void => {itemChangedSub.remove();+ itemUsedSub.remove();};}, [loadItems]);diff --git a/apps/mobile-app/app/(tabs)/items/index.tsx b/apps/mobile-app/app/(tabs)/items/index.tsxindex 6122b08cf..f96fd332c 100644--- a/apps/mobile-app/app/(tabs)/items/index.tsx+++ b/apps/mobile-app/app/(tabs)/items/index.tsx@@ -307,10 +307,14 @@ export default function ItemsScreen(): React.ReactNode {const itemChangedSub = emitter.addListener('itemChanged', async () => {await loadItems();});+ const itemUsedSub = emitter.addListener('itemUsed', async () => {+ await loadItems();+ });return (): void => {tabPressSub.remove();itemChangedSub.remove();+ itemUsedSub.remove();unsubscribeFocus();unsubscribeBlur();};diff --git a/apps/mobile-app/hooks/useRecordItemCopy.ts b/apps/mobile-app/hooks/useRecordItemCopy.tsindex 0f38a8316..201f54710 100644--- a/apps/mobile-app/hooks/useRecordItemCopy.ts+++ b/apps/mobile-app/hooks/useRecordItemCopy.ts@@ -6,6 +6,7 @@ import { useVaultSync } from '@/hooks/useVaultSync';import { useDb } from '@/context/DbContext';import NativeVaultManager from '@/specs/NativeVaultManager';+import emitter from '@/utils/EventEmitter';/** How long to wait after a copy before pushing, so a burst of copies goes up in one sync. */const PUSH_DELAY_MS = 2000;@@ -25,6 +26,7 @@ export function useRecordItemCopy(): (item?: ItemRef) => void {}NativeVaultManager.recordItemCopy(item.Id, item.ManifestId).then(() => {+ emitter.emit('itemUsed');if (pendingPush) {clearTimeout(pendingPush);}