Skip to content

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

Refactor console.error to custom log methods for better reporting (#2159)

Leendert de Borst53300dd1fbb2
diff --git a/apps/browser-extension/eslint.config.js b/apps/browser-extension/eslint.config.js
index 17a5a421d..f62802bb0 100644
--- a/apps/browser-extension/eslint.config.js
+++ b/apps/browser-extension/eslint.config.js
@@ -66,7 +66,8 @@ export default [
"ignoreComments": false
}],
"no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 1, "maxBOF": 0 }],
- "no-console": ["error", { allow: ["warn", "error", "info", "debug"] }],
+ // Log through the Diagnostics utility helper instead of raw console.error.
+ "no-console": ["error", { allow: ["warn", "info", "debug"] }],
"jsdoc/require-jsdoc": ["error", {
"require": {
"FunctionDeclaration": true,
@@ -160,6 +161,13 @@ export default [
},
},
},
+ {
+ // The Diagnostics utility helper and the dev-only trace channel are the two modules allowed to reach the console directly.
+ files: ["src/utils/Diagnostics.ts", "src/utils/devLogger/DevLogger.ts"],
+ rules: {
+ "no-console": "off",
+ },
+ },
{
languageOptions: {
globals: {
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index 787c4e549..e3923b8b0 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -13,6 +13,7 @@ import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePr
import { handleStoreTwoFactorState, handleGetTwoFactorState, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetUnlockKeyDerivationParams, handleGetPasswordSettings, handleGeneratePassword, handleGetPersistedFormValues, handleGetVault, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreUnlockKey, handleStoreUnlockKeyDerivationParams, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupUpdateVault, handleGroupRevokeAccess, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleSetLoginSaveEnabled, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleGetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';
+import { logFailure } from '@/utils/Diagnostics';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { onMessage, sendMessage } from "@/utils/messaging/ExtensionMessaging";
import type { MatchingPasskeysResponse, WebAuthnAssertionResponse, WebAuthnPublicKeyGetPayload } from '@/utils/passkey/types';
@@ -227,7 +228,7 @@ export default defineBackground({
sendMessage('OPEN_AUTOFILL_POPUP', { elementIdentifier }, tab.id);
}
} catch (error) {
- console.error('Error handling show-autofill-popup command:', error);
+ logFailure('Error handling show-autofill-popup command', error);
}
});
@@ -368,7 +369,7 @@ export default defineBackground({
*/
await runStartupMigrations();
} catch (error) {
- console.error('Error running startup migrations:', error);
+ logFailure('Error running startup migrations', error);
}
try {
@@ -377,7 +378,7 @@ export default defineBackground({
await setupContextMenus();
}
} catch (error) {
- console.error('Error setting up context menus:', error);
+ logFailure('Error setting up context menus', error);
}
try {
@@ -388,7 +389,7 @@ export default defineBackground({
*/
await initializeAutoLockAlarm();
} catch (error) {
- console.error('Error initializing auto-lock alarm:', error);
+ logFailure('Error initializing auto-lock alarm', error);
}
})();
}
diff --git a/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts b/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts
index f95dc905d..fcfa90fe9 100644
--- a/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts
@@ -1,6 +1,7 @@
import { handleLockVault } from '@/entrypoints/background/VaultMessageHandler';
import { StorageKeys } from '@/utils/constants/storageKeys';
+import { logFailure } from '@/utils/Diagnostics';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import type { Browser } from 'wxt/browser';
@@ -35,7 +36,7 @@ async function lockVaultDueToInactivity(): Promise<void> {
await handleLockVault();
console.info('[AUTO_LOCK] Vault locked due to inactivity');
} catch (error) {
- console.error('[AUTO_LOCK] Error locking vault:', error);
+ logFailure('[AUTO_LOCK] Error locking vault', error);
}
}
diff --git a/apps/browser-extension/src/entrypoints/background/ClipboardClearHandler.ts b/apps/browser-extension/src/entrypoints/background/ClipboardClearHandler.ts
index 2af269ecf..10d876a17 100644
--- a/apps/browser-extension/src/entrypoints/background/ClipboardClearHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/ClipboardClearHandler.ts
@@ -1,3 +1,4 @@
+import { logFailure } from '@/utils/Diagnostics';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
@@ -46,7 +47,7 @@ async function createOffscreenDocument(): Promise<void> {
offscreenDocumentCreated = true;
} catch (error) {
- console.error('[CLIPBOARD] Failed to create offscreen document:', error);
+ logFailure('[CLIPBOARD] Failed to create offscreen document', error);
offscreenDocumentCreated = false;
}
}
@@ -149,7 +150,7 @@ export async function handleClipboardCopied() : Promise<void> {
sendMessage('CLIPBOARD_CLEARED', {}).catch(() => {});
} catch (error) {
- console.error('[CLIPBOARD] Error during clipboard clear:', error);
+ logFailure('[CLIPBOARD] Error during clipboard clear', error);
// Clean up even on error
clipboardClearTimer = null;
diff --git a/apps/browser-extension/src/entrypoints/background/ContextMenu.ts b/apps/browser-extension/src/entrypoints/background/ContextMenu.ts
index f47058fde..a9f718dfe 100644
--- a/apps/browser-extension/src/entrypoints/background/ContextMenu.ts
+++ b/apps/browser-extension/src/entrypoints/background/ContextMenu.ts
@@ -4,6 +4,7 @@ import { type Browser } from '@wxt-dev/browser';
import { handleGetPasswordSettings } from '@/entrypoints/background/VaultMessageHandler';
import { POPUP_TYPES, type PopupType, isPopupType } from '@/utils/autofill/PopupTypes';
+import { logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { t } from '@/i18n/StandaloneI18n';
@@ -66,7 +67,7 @@ export async function setupContextMenus() : Promise<void> {
try {
await browser.contextMenus.removeAll();
} catch (error) {
- console.error('Failed to remove existing context menus:', error);
+ logFailure('Failed to remove existing context menus', error);
}
const popupEntries = Object.entries(POPUP_TYPES) as [PopupType, typeof POPUP_TYPES[PopupType]][];
@@ -104,7 +105,7 @@ export async function setupContextMenus() : Promise<void> {
}),
]);
} catch (error) {
- console.error('Failed to create context menus:', error);
+ logFailure('Failed to create context menus', error);
}
}
diff --git a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
index 94ae05064..e3fef4db5 100644
--- a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
@@ -7,6 +7,7 @@ import { extractDomain } from '@aliasvault/client/rust/RustCore';
import { createVaultSqliteClient, handleGetEncryptionKey, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';
+import { logFailure } from '@/utils/Diagnostics';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { buildPasskeyAssertion } from '@/utils/passkey/PasskeyAssertionService';
import { PasskeyHelper } from '@/utils/passkey/PasskeyHelper';
@@ -238,7 +239,7 @@ export async function handleGetMatchingPasskeys(
return { success: true, locked: false, passkeys: options };
} catch (error) {
- console.error('Error getting matching passkeys:', error);
+ logFailure('Error getting matching passkeys', error);
return { success: false, locked: false, passkeys: [] };
}
}
@@ -263,7 +264,7 @@ export async function handleWebAuthnGetAssertion(
return { success: true, credential };
} catch (error) {
- console.error('Error building passkey assertion:', error);
+ logFailure('Error building passkey assertion', error);
return { success: false, error: error instanceof Error ? error.message : 'Unknown error' };
}
}
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index f94563788..9637dceca 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -28,6 +28,7 @@ import { handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorSta
import { AUTH_STORAGE_KEYS, dirtyScopeStorageKey, SESSION_STORAGE_KEYS, StorageKeys, vaultDataStorageKeys, VAULT_LOCK_STORAGE_KEYS } from '@/utils/constants/storageKeys';
import { devLog } from '@/utils/devLogger/DevLogger';
+import { logExpected, logFailure } from '@/utils/Diagnostics';
import { isSameItem } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage, type TotpSecret } from '@/utils/messaging/ExtensionMessaging';
@@ -206,7 +207,7 @@ export async function handleStoreUnlockKey(
await storage.setItem(StorageKeys.UNLOCK_KEY, unlockKey);
return { success: true };
} catch (error) {
- console.error('Failed to store unlock key:', error);
+ logFailure('Failed to store unlock key', error);
// E-602: Storage write failed during unlock key store
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownErrorTryAgain'), AppErrorCode.STORAGE_WRITE_FAILED) };
}
@@ -223,7 +224,7 @@ export async function handleStoreUnlockKeyDerivationParams(
await storage.setItem(StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS, params);
return { success: true };
} catch (error) {
- console.error('Failed to store encryption key derivation params:', error);
+ logFailure('Failed to store encryption key derivation params', error);
// E-602: Storage write failed during derivation params store
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownErrorTryAgain'), AppErrorCode.STORAGE_WRITE_FAILED) };
}
@@ -244,7 +245,7 @@ export async function handleGetVault(
const hiddenPrivateEmailDomains = await getStorageItem<string[]>(StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS) ?? [];
if (!encryptedVault) {
- console.error('Vault not available');
+ logExpected('[Vault] No encrypted vault in storage');
// E-201: No encrypted vault in storage
return { success: false, error: formatErrorWithCode(await t('common.errors.vaultNotAvailable'), AppErrorCode.VAULT_NOT_FOUND) };
}
@@ -265,7 +266,7 @@ export async function handleGetVault(
hiddenPrivateEmailDomains: hiddenPrivateEmailDomains ?? []
};
} catch (error) {
- console.error('Failed to get vault:', error);
+ logFailure('Failed to get vault', error);
// E-203: Vault decryption failed during get
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.VAULT_DECRYPT_FAILED) };
}
@@ -480,7 +481,7 @@ export async function handleGetFilteredItems(
return { success: true, items: filteredItems };
} catch (error) {
- console.error('Error getting filtered items:', error);
+ logFailure('Error getting filtered items', error);
// E-304: Item read failed
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };
}
@@ -509,7 +510,7 @@ export async function handleGetSearchItems(
return { success: true, items: searchResults };
} catch (error) {
- console.error('Error searching items:', error);
+ logFailure('Error searching items', error);
// E-304: Item read failed during search
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };
}
@@ -534,7 +535,7 @@ export function handleGetDefaultEmailDomain(): Promise<stringResponse> {
return { success: true, value: domain || undefined };
} catch (error) {
- console.error('Error getting default email domain:', error);
+ logFailure('Error getting default email domain', error);
// E-601: Storage read failed
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.STORAGE_READ_FAILED) };
}
@@ -560,7 +561,7 @@ export async function handleGetDefaultIdentitySettings(
}
};
} catch (error) {
- console.error('Error getting default identity settings:', error);
+ logFailure('Error getting default identity settings', error);
// E-601: Storage read failed
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.STORAGE_READ_FAILED) };
}
@@ -577,7 +578,7 @@ export async function handleGetPasswordSettings(
return { success: true, settings: passwordSettings };
} catch (error) {
- console.error('Error getting password settings:', error);
+ logFailure('Error getting password settings', error);
// E-601: Storage read failed
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.STORAGE_READ_FAILED) };
}
@@ -593,7 +594,7 @@ export async function handleGeneratePassword(
const password = await generatePassword(settings);
return { success: true, password };
} catch (error) {
- console.error('Error generating password:', error);
+ logFailure('Error generating password', error);
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.UNKNOWN_ERROR) };
}
}
@@ -655,7 +656,7 @@ export async function handleGetPersistedFormValues(): Promise<any | null> {
);
return JSON.parse(decryptedData);
} catch (error) {
- console.error('Failed to decrypt or parse persisted form values:', error);
+ logFailure('Failed to decrypt or parse persisted form values', error);
return null;
}
}
@@ -688,7 +689,7 @@ async function persistLocalVaultMutation(sqliteClient: SqliteClient, encryptionK
cachedVaultBlob = encryptedVault;
void handleFullVaultSync().catch(error => {
- console.error('Background sync after local vault mutation failed:', error);
+ logFailure('Background sync after local vault mutation failed', error);
});
}
@@ -925,7 +926,7 @@ async function handleFullVaultSyncInternal(options?: VaultSyncOptions): Promise<
hasPendingSync = false;
handleFullVaultSync().catch(err => {
- console.error('[VaultSync] Follow-up sync failed:', err);
+ logFailure('[VaultSync] Follow-up sync failed', err);
});
}
}
@@ -1022,7 +1023,7 @@ export async function handleCheckLoginDuplicate(
return { success: true, isDuplicate: false };
} catch (error) {
- console.error('Error checking for duplicate login:', error);
+ logFailure('Error checking for duplicate login', error);
return { success: false, isDuplicate: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };
}
}
@@ -1115,7 +1116,7 @@ export async function handleSaveLoginCredential(
return { success: true, itemId: created.Id, manifestId: created.ManifestId };
} catch (error) {
- console.error('Failed to save login credential:', error);
+ logFailure('Failed to save login credential', error);
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_CREATE_FAILED) };
}
}
@@ -1183,7 +1184,7 @@ export async function handleAddUrlToCredential(message: { itemId: string; manife
return { success: true };
} catch (error) {
- console.error('Failed to add URL to credential:', error);
+ logFailure('Failed to add URL to credential', error);
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_UPDATE_FAILED) };
}
}
@@ -1274,7 +1275,7 @@ export async function handleGetLoginSaveSettings(): Promise<{
autoDismissSeconds
};
} catch (error) {
- console.error('Error getting login save settings:', error);
+ logFailure('Error getting login save settings', error);
return { success: false, enabled: false, autoDismissSeconds: 15, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.STORAGE_READ_FAILED) };
}
}
@@ -1291,7 +1292,7 @@ export async function handleSetLoginSaveEnabled(
await LocalPreferencesService.setLoginSaveEnabled(enabled);
return { success: true };
} catch (error) {
- console.error('Error setting login save enabled:', error);
+ logFailure('Error setting login save enabled', error);
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.STORAGE_WRITE_FAILED) };
}
}
@@ -1327,7 +1328,7 @@ export async function handleGetItemsWithTotp(
return { success: true, items: prioritized.items, recentlySelected: prioritized.recentlySelected };
} catch (error) {
- console.error('Error getting items with TOTP:', error);
+ logFailure('Error getting items with TOTP', error);
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };
}
}
@@ -1359,7 +1360,7 @@ export async function handleSearchItemsWithTotp(
return { success: true, items: searchResults };
} catch (error) {
- console.error('Error searching items with TOTP:', error);
+ logFailure('Error searching items with TOTP', error);
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };
}
}
@@ -1398,7 +1399,7 @@ export async function handleGetTotpSecrets(
return { success: true, secrets };
} catch (error) {
- console.error('Error getting TOTP secrets:', error);
+ logFailure('Error getting TOTP secrets', error);
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };
}
}
@@ -1433,7 +1434,7 @@ export async function handleGenerateTotpCode(
return { success: true, code };
} catch (error) {
- console.error('Error generating TOTP code:', error);
+ logFailure('Error generating TOTP code', error);
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };
}
}
@@ -1460,7 +1461,7 @@ export async function handleRecordItemUsage(
await persistLocalVaultMutation(sqliteClient, encryptionKey);
return { success: true };
} catch (error) {
- console.error('Failed to record item usage:', error);
+ logFailure('Failed to record item usage', error);
return { success: false };
}
}
@@ -1476,7 +1477,7 @@ export async function handleSetRecentlySelected(
await RecentlySelectedItemService.setRecentlySelected({ Id: message.itemId, ManifestId: message.manifestId }, rootDomain);
return { success: true };
} catch (error) {
- console.error('Error setting recently selected item:', error);
+ logFailure('Error setting recently selected item', error);
return { success: false };
}
}
@@ -1492,7 +1493,7 @@ export async function handleGetRecentlySelected(
const item = await RecentlySelectedItemService.getRecentlySelected(rootDomain);
return { success: true, itemId: item?.Id ?? null, manifestId: item?.ManifestId ?? null };
} catch (error) {
- console.error('Error getting recently selected item:', error);
+ logFailure('Error getting recently selected item', error);
return { success: false, itemId: null };
}
}
@@ -1543,7 +1544,7 @@ export async function handleGroupCreateVault(message: { groupId: string; name: s
const result = await vaultSync.createSharedManifest(message.groupId, message.name);
if (result.success) {
// The engine left the new folder and keypair in a dirty vault; this pushes them.
- void handleFullVaultSync().catch(error => console.error('Background sync after creating a shared manifest failed:', error));
+ void handleFullVaultSync().catch(error => logFailure('Background sync after creating a shared manifest failed', error));
}
return sharingActionResponse(result, 'sharing.family.errors.createVaultFailed');
@@ -1580,7 +1581,7 @@ export async function handleGroupRevokeAccess(message: { groupId: string; manife
await SharingService.revokeAccess(webApi, message.groupId, message.manifestId, message.userId);
devLog(`[Sharing] Revoked ${message.userId}'s access to vault ${message.manifestId}; syncing to pick up whatever the server left for this client to finish.`);
- void handleFullVaultSync().catch(error => console.error('Background sync after a vault access change failed:', error));
+ void handleFullVaultSync().catch(error => logFailure('Background sync after a vault access change failed', error));
return { success: true };
} catch (error) {
@@ -1588,7 +1589,7 @@ export async function handleGroupRevokeAccess(message: { groupId: string; manife
return { success: false, apiErrorCode: error.apiErrorCode };
}
- console.error('Failed to revoke shared manifest access:', error);
+ logFailure('Failed to revoke shared manifest access', error);
return { success: false, error: await t('sharing.family.errors.revokeAccessFailed') };
}
}
diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.ts
index 36285a311..ae12630f4 100644
--- a/apps/browser-extension/src/entrypoints/content.ts
+++ b/apps/browser-extension/src/entrypoints/content.ts
@@ -15,6 +15,7 @@ import { isAvAutofillAllowed, isAvSuppressSave } from '@/utils/autofill/Autofill
import { DEFAULT_POPUP_TYPE, isPopupType, popupTypeForFieldType, POPUP_TYPES, type PopupType } from '@/utils/autofill/PopupTypes';
import { StorageKeys } from '@/utils/constants/storageKeys';
import { devLog } from '@/utils/devLogger/DevLogger';
+import { logFailure } from '@/utils/Diagnostics';
import { FormDetector } from '@/utils/formDetector/FormDetector';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { LoginDetector } from '@/utils/loginDetector';
@@ -80,13 +81,13 @@ async function handleSaveLogin(login: CapturedLogin, serviceName: string): Promi
});
if (!response.success) {
- console.error('[AliasVault] Failed to save login:', response.error);
+ logFailure('[AliasVault] Failed to save login', response.error);
}
// Clear the last autofilled state after save
await sendMessage('CLEAR_LAST_AUTOFILLED');
} catch (error) {
- console.error('[AliasVault] Error saving login:', error);
+ logFailure('[AliasVault] Error saving login', error);
}
}
@@ -103,7 +104,7 @@ async function handleNeverSaveForDomain(domain: string): Promise<void> {
await storage.setItem(StorageKeys.LOGIN_SAVE_BLOCKED_DOMAINS, blockedDomains);
}
} catch (error) {
- console.error('[AliasVault] Error saving blocked domain:', error);
+ logFailure('[AliasVault] Error saving blocked domain', error);
}
}
@@ -129,13 +130,13 @@ async function handleAddUrlToCredential(item: ItemRef, url: string): Promise<voi
});
if (!response.success) {
- console.error('[AliasVault] Failed to add URL to credential:', response.error);
+ logFailure('[AliasVault] Failed to add URL to credential', response.error);
}
// Clear the last autofilled state after successful add
await sendMessage('CLEAR_LAST_AUTOFILLED');
} catch (error) {
- console.error('[AliasVault] Error adding URL to credential:', error);
+ logFailure('[AliasVault] Error adding URL to credential', error);
}
}
@@ -283,7 +284,7 @@ async function checkAndRestoreSavePromptEarly(ctx: Parameters<typeof createShado
ui.mount();
} catch (error) {
- console.error('[AliasVault] Error in early save prompt restore:', error);
+ logFailure('[AliasVault] Error in early save prompt restore', error);
}
}
@@ -346,7 +347,7 @@ async function checkAndRestorePersistedSavePrompt(container: HTMLElement): Promi
);
}
} catch (error) {
- console.error('[AliasVault] Error restoring persisted save prompt:', error);
+ logFailure('[AliasVault] Error restoring persisted save prompt', error);
}
}
@@ -861,7 +862,7 @@ export default defineContentScript({
}
// If disabled, don't show any popup (user can rely on clipboard auto-copy for TOTP)
} catch (error) {
- console.error('[AliasVault] Error checking vault status:', error);
+ logFailure('[AliasVault] Error checking vault status', error);
// Fall back to normal autofill popup if check fails
POPUP_RUNTIME[DEFAULT_POPUP_TYPE].open(inputElement, container);
}
diff --git a/apps/browser-extension/src/entrypoints/contentScript/Form.ts b/apps/browser-extension/src/entrypoints/contentScript/Form.ts
index 18793ab41..5289da52f 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/Form.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/Form.ts
@@ -4,6 +4,7 @@ import { itemToCredential, FieldKey } from '@aliasvault/models/vault';
import { openAutofillPopup, openTotpPopup, removeExistingPopup } from '@/entrypoints/contentScript/Popup';
import { LOGO_MARK_SVG } from '@/utils/constants/logo';
+import { logFailure } from '@/utils/Diagnostics';
import { FormDetector } from '@/utils/formDetector/FormDetector';
import { FormFiller } from '@/utils/formDetector/FormFiller';
import { DetectedFieldType } from '@/utils/formDetector/types/FormFields';
@@ -430,7 +431,7 @@ export async function fillTotpCode(item: ItemRef, input: HTMLInputElement): Prom
const response = await sendMessage('GENERATE_TOTP_CODE', { itemId: item.Id, manifestId: item.ManifestId });
if (!response.success || !response.code) {
- console.error('Failed to generate TOTP code:', response.error);
+ logFailure('Failed to generate TOTP code', response.error);
return;
}
diff --git a/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts b/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts
index 092878a79..8284cd07d 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts
@@ -4,6 +4,7 @@
*/
import { getLogoMarkSvg } from '@/utils/constants/logo';
+import { logExpected, logFailure } from '@/utils/Diagnostics';
import type { CapturedLogin, SavePromptOptions, SavePromptPersistedState, AddUrlPromptOptions, LastAutofilledCredential } from '@/utils/loginDetector';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
@@ -414,7 +415,7 @@ export async function restoreAddUrlPromptFromState(
const { login, remainingTimeMs: restoredRemainingTime, initialAutoDismissMs: restoredInitialMs, existingCredential } = state;
if (!existingCredential) {
- console.error('[AliasVault] Cannot restore Add URL prompt without existing credential');
+ logExpected('[AliasVault] Cannot restore the Add URL prompt, its credential is gone');
return;
}
@@ -738,7 +739,7 @@ async function persistSavePromptState(): Promise<void> {
try {
await sendMessage('STORE_SAVE_PROMPT_STATE', state);
} catch (error) {
- console.error('[AliasVault] Error persisting save prompt state:', error);
+ logFailure('[AliasVault] Error persisting save prompt state', error);
}
}
@@ -790,7 +791,7 @@ export async function getPersistedSavePromptState(): Promise<SavePromptPersisted
return state;
} catch (error) {
- console.error('[AliasVault] Error reading persisted save prompt state:', error);
+ logFailure('[AliasVault] Error reading persisted save prompt state', error);
return null;
}
}
@@ -802,7 +803,7 @@ export async function clearPersistedSavePromptState(): Promise<void> {
try {
await sendMessage('CLEAR_SAVE_PROMPT_STATE');
} catch (error) {
- console.error('[AliasVault] Error clearing persisted save prompt state:', error);
+ logFailure('[AliasVault] Error clearing persisted save prompt state', error);
}
}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/LogoutConfirmModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/LogoutConfirmModal.tsx
index 14ff82a84..a1467a969 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/LogoutConfirmModal.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/LogoutConfirmModal.tsx
@@ -4,6 +4,8 @@ import { useTranslation } from 'react-i18next';
import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';
+import { logFailure } from '@/utils/Diagnostics';
+
interface ILogoutConfirmModalProps {
isOpen: boolean;
onClose: () => void;
@@ -47,7 +49,7 @@ const LogoutConfirmModal: React.FC<ILogoutConfirmModalProps> = ({
setHasPendingChanges(pending);
}
} catch (error) {
- console.error('Failed to check sync state:', error);
+ logFailure('Failed to check sync state', error);
if (!cancelled) {
// Default to showing the simple logout confirmation on error
setHasPendingChanges(false);
diff --git a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
index e9e4b218a..6f7ba97d5 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
@@ -1,6 +1,7 @@
import { EncryptionUtility } from '@aliasvault/client/crypto/EncryptionUtility';
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
-import React, { useState, useEffect } from 'react';
+import { mailboxPollDelayMs } from '@aliasvault/client/utilities/PollBackoff';
+import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useLocation } from 'react-router-dom';
@@ -9,6 +10,7 @@ import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { StorageKeys } from '@/utils/constants/storageKeys';
+import { logExpected } from '@/utils/Diagnostics';
import { getStorageItem } from '@/utils/StorageUtility';
import type { ApiErrorResponse, MailboxEmail } from '@aliasvault/models/webapi';
@@ -33,7 +35,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
const webApi = useWebApi();
const dbContext = useDb();
const location = useLocation();
-
+ const consecutiveFailuresRef = useRef(0);
const emailsPerLoad = 3;
const canLoadMore = displayedCount < emails.length;
@@ -73,6 +75,21 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
};
useEffect(() => {
+ let cancelled = false;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+
+ /**
+ * Record that a poll failed for the incremental backoff to work.
+ * @param reason - what did not work
+ * @param error - the underlying error, when there is one
+ */
+ const markPollFailed = (reason: string, error?: unknown): void => {
+ if (consecutiveFailuresRef.current === 0) {
+ logExpected(`[EmailPreview] ${reason}`, error);
+ }
+ consecutiveFailuresRef.current++;
+ };
+
/**
* Loads the latest emails from the server and decrypts them locally if needed.
*/
@@ -110,6 +127,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
});
if (!response.ok) {
+ markPollFailed(`The mailbox request returned HTTP ${response.status}`);
setError(t('common.errors.unknownError'));
return;
}
@@ -134,6 +152,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
}
return prevEmails;
});
+ consecutiveFailuresRef.current = 0;
} else if (isPrivate) {
// For private domains, use existing encrypted email logic
try {
@@ -173,6 +192,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
// Clear any previous error on successful load
setError(null);
+ consecutiveFailuresRef.current = 0;
}
} catch {
// Try to parse as error response instead
@@ -187,30 +207,47 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
return;
}
+ markPollFailed(`The server rejected the mailbox request: ${apiErrorResponse?.code ?? 'unknown'}`);
setError(t('emails.apiErrors.' + apiErrorResponse?.code));
return;
}
- } catch {
+ } catch (err) {
// Suppress errors while vault has unsynced changes
if (dbContext.shouldSuppressEmailErrors()) {
return;
}
+ markPollFailed('The mailbox request failed', err);
setError(t('common.errors.unknownError'));
return;
}
}
} catch (err) {
- console.error('Error loading emails:', err);
+ markPollFailed('Loading the mailbox failed', err);
setError(t('common.errors.unknownError'));
}
setLoading(false);
};
- loadEmails();
- // Set up auto-refresh interval
- const interval = setInterval(loadEmails, 2000);
- return () : void => clearInterval(interval);
+ /**
+ * Poll, then schedule the next poll.
+ */
+ const poll = async (): Promise<void> => {
+ await loadEmails();
+ if (cancelled) {
+ return;
+ }
+ timer = setTimeout(poll, mailboxPollDelayMs(consecutiveFailuresRef.current));
+ };
+
+ void poll();
+
+ return () : void => {
+ cancelled = true;
+ if (timer) {
+ clearTimeout(timer);
+ }
+ };
}, [email, loading, webApi, dbContext, t, displayedCount]);
// Don't render anything if the domain is not supported
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Folders/DeleteFolderModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Folders/DeleteFolderModal.tsx
index 6b23fac6a..4674755a4 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Folders/DeleteFolderModal.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Folders/DeleteFolderModal.tsx
@@ -3,6 +3,8 @@ import { useTranslation } from 'react-i18next';
import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';
+import { logFailure } from '@/utils/Diagnostics';
+
type DeleteFolderModalProps = {
isOpen: boolean;
onClose: () => void;
@@ -33,7 +35,7 @@ const DeleteFolderModal: React.FC<DeleteFolderModalProps> = ({
await onDeleteFolderOnly();
onClose();
} catch (err) {
- console.error('Error deleting folder:', err);
+ logFailure('Error deleting folder', err);
} finally {
setIsSubmitting(false);
}
@@ -48,7 +50,7 @@ const DeleteFolderModal: React.FC<DeleteFolderModalProps> = ({
await onDeleteFolderAndContents();
onClose();
} catch (err) {
- console.error('Error deleting folder with contents:', err);
+ logFailure('Error deleting folder with contents', err);
} finally {
setIsSubmitting(false);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Folders/FolderModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Folders/FolderModal.tsx
index 6222dc20b..90fb29e78 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Folders/FolderModal.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Folders/FolderModal.tsx
@@ -4,6 +4,8 @@ import { useTranslation } from 'react-i18next';
import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';
+import { logFailure } from '@/utils/Diagnostics';
+
type FolderModalProps = {
isOpen: boolean;
onClose: () => void;
@@ -58,7 +60,7 @@ const FolderModal: React.FC<FolderModalProps> = ({
} else {
setError(t('common.errors.unknownErrorTryAgain'));
}
- console.error('Error saving folder:', err);
+ logFailure('Error saving folder', err);
} finally {
setIsSubmitting(false);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Forms/FormInputCopyToClipboard.tsx b/apps/browser-extension/src/entrypoints/popup/components/Forms/FormInputCopyToClipboard.tsx
index 1e34948d4..6b693b30f 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Forms/FormInputCopyToClipboard.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Forms/FormInputCopyToClipboard.tsx
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { ClipboardCopyService } from '@/entrypoints/popup/utils/ClipboardCopyService';
+import { logExpected } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
/**
@@ -108,7 +109,7 @@ export const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> =
}
}, 2000);
} catch (err) {
- console.error('Failed to copy text:', err);
+ logExpected('[Clipboard] Copying the value failed', err);
}
};
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Forms/PasswordField.tsx b/apps/browser-extension/src/entrypoints/popup/components/Forms/PasswordField.tsx
index 15f4a961b..bbe9743e3 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Forms/PasswordField.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Forms/PasswordField.tsx
@@ -7,6 +7,8 @@ import { useTranslation } from 'react-i18next';
import PasswordConfigDialog from '@/entrypoints/popup/components/Dialogs/PasswordConfigDialog';
import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { logFailure } from '@/utils/Diagnostics';
+
import type { PasswordSettings } from '@aliasvault/models/vault';
interface IPasswordFieldProps {
@@ -79,7 +81,7 @@ const PasswordField: React.FC<IPasswordFieldProps> = ({
setIsLoaded(true);
}
} catch (error) {
- console.error('Error loading password settings:', error);
+ logFailure('Error loading password settings', error);
}
};
void loadSettings();
@@ -91,7 +93,7 @@ const PasswordField: React.FC<IPasswordFieldProps> = ({
onChange(password);
setShowPassword(true);
} catch (error) {
- console.error('Error generating password:', error);
+ logFailure('Error generating password', error);
}
}, [onChange, setShowPassword]);
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx
index 5456d758c..077a6dc2c 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx
@@ -3,6 +3,8 @@ import { useTranslation } from 'react-i18next';
import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { logFailure } from '@/utils/Diagnostics';
+
import type { Attachment } from '@aliasvault/models/vault';
type AttachmentBlockProps = {
@@ -42,7 +44,7 @@ const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ itemId, manifestId })
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (error) {
- console.error('Error downloading attachment:', error);
+ logFailure('Error downloading attachment', error);
}
};
@@ -59,7 +61,7 @@ const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ itemId, manifestId })
const attachmentList = dbContext.sqliteClient.items.getAttachmentsForItem({ Id: itemId, ManifestId: manifestId });
setAttachments(attachmentList);
} catch (error) {
- console.error('Error loading attachments:', error);
+ logFailure('Error loading attachments', error);
} finally {
setLoading(false);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentUploader.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentUploader.tsx
index f46670e21..411f0747b 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentUploader.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentUploader.tsx
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
+import { logFailure } from '@/utils/Diagnostics';
import { itemRoute } from '@/utils/ItemRoute';
import type { Attachment } from '@aliasvault/models/vault';
@@ -67,7 +68,7 @@ const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
// Clear status message after 3 seconds
setTimeout(() => setStatusMessage(''), 3000);
} catch (error) {
- console.error('Error uploading files:', error);
+ logFailure('Error uploading files', error);
setStatusMessage(t('common.errors.unknownErrorTryAgain'));
setTimeout(() => setStatusMessage(''), 3000);
}
@@ -93,7 +94,7 @@ const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
setStatusMessage(t('attachmentUploader.deleteSuccess'));
setTimeout(() => setStatusMessage(''), 3000);
} catch (error) {
- console.error('Error deleting attachment:', error);
+ logFailure('Error deleting attachment', error);
setStatusMessage(t('common.errors.unknownErrorTryAgain'));
setTimeout(() => setStatusMessage(''), 3000);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldBlock.tsx
index e5ecfd228..b74501506 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldBlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldBlock.tsx
@@ -5,6 +5,8 @@ import { useTranslation } from 'react-i18next';
import { FormInputCopyToClipboard } from '@/entrypoints/popup/components/Forms/FormInputCopyToClipboard';
import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { logFailure } from '@/utils/Diagnostics';
+
import FieldHistoryModal from './FieldHistoryModal';
import type { ItemField } from '@aliasvault/models/vault';
@@ -129,7 +131,7 @@ const FieldBlock: React.FC<FieldBlockProps> = ({ field, itemId, manifestId, hide
setHistoryCount(0);
}
} catch (error) {
- console.error('[FieldBlock] Error checking history:', error);
+ logFailure('[FieldBlock] Error checking history', error);
}
}
}, [hasHistoryEnabled, itemId, manifestId, field.FieldKey, field.Value, dbContext?.sqliteClient]);
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldHistoryModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldHistoryModal.tsx
index 44500f2fa..e5084c169 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldHistoryModal.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldHistoryModal.tsx
@@ -7,6 +7,8 @@ import { FormInputCopyToClipboard } from '@/entrypoints/popup/components/Forms/F
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
+import { logFailure } from '@/utils/Diagnostics';
+
import type { FieldHistory, FieldType } from '@aliasvault/models/vault';
type FieldHistoryModalProps = {
@@ -59,7 +61,7 @@ const FieldHistoryModal: React.FC<FieldHistoryModalProps> = ({
const historyRecords = dbContext.sqliteClient.items.getFieldHistory({ Id: itemId, ManifestId: manifestId }, fieldKey);
setHistory(historyRecords);
} catch (error) {
- console.error('Error loading field history:', error);
+ logFailure('Error loading field history', error);
} finally {
setLoading(false);
}
@@ -118,7 +120,7 @@ const FieldHistoryModal: React.FC<FieldHistoryModalProps> = ({
loadHistory();
setConfirmDeleteId(null);
} catch (error) {
- console.error('Error deleting field history:', error);
+ logFailure('Error deleting field history', error);
}
};
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyBlock.tsx
index 0f0b20009..d91dd9bfd 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyBlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyBlock.tsx
@@ -4,6 +4,8 @@ import { useTranslation } from 'react-i18next';
import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';
import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { logFailure } from '@/utils/Diagnostics';
+
import type { Passkey } from '@aliasvault/models/vault';
type PasskeyBlockProps = {
@@ -47,7 +49,7 @@ const PasskeyBlock: React.FC<PasskeyBlockProps> = ({ itemId, manifestId }) => {
const itemPasskeys = dbContext.sqliteClient.passkeys.getByItemId({ Id: itemId, ManifestId: manifestId });
setPasskeys(itemPasskeys);
} catch (err) {
- console.error('Error loading passkeys:', err);
+ logFailure('Error loading passkeys', err);
} finally {
setLoading(false);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyEditor.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyEditor.tsx
index 0d097fe01..00a36fd0c 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyEditor.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyEditor.tsx
@@ -4,6 +4,8 @@ import { useTranslation } from 'react-i18next';
import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';
import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { logFailure } from '@/utils/Diagnostics';
+
import { PasskeyIcon } from './PasskeyBlock';
import type { Passkey } from '@aliasvault/models/vault';
@@ -40,7 +42,7 @@ const PasskeyEditor: React.FC<PasskeyEditorProps> = ({
const itemPasskeys = dbContext.sqliteClient.passkeys.getByItemId({ Id: itemId, ManifestId: manifestId });
setPasskeys(itemPasskeys);
} catch (err) {
- console.error('Error loading passkeys:', err);
+ logFailure('Error loading passkeys', err);
} finally {
setLoading(false);
}
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.tsx
index 54b011780..94a68af56 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
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { logExpected, logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import type { TotpCode } from '@aliasvault/models/vault';
@@ -62,7 +63,7 @@ const TotpBlock: React.FC<TotpBlockProps> = ({ itemId, manifestId }) => {
setCopiedId(null);
}, 2000);
} catch (error) {
- console.error('Failed to copy:', error);
+ logExpected('[Clipboard] Copying the TOTP code failed', error);
}
};
@@ -79,7 +80,7 @@ const TotpBlock: React.FC<TotpBlockProps> = ({ itemId, manifestId }) => {
const codes = dbContext.sqliteClient.items.getTotpCodesForItem({ Id: itemId, ManifestId: manifestId });
setTotpCodes(codes);
} catch (error) {
- console.error('Error loading TOTP codes:', error);
+ logFailure('Error loading TOTP codes', error);
} finally {
setLoading(false);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpEditor.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpEditor.tsx
index dd060402f..d7dd64dba 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpEditor.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpEditor.tsx
@@ -7,6 +7,8 @@ import { useTranslation } from 'react-i18next';
import ConfirmDeleteModal from '@/entrypoints/popup/components/Dialogs/ConfirmDeleteModal';
import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';
+import { logFailure } from '@/utils/Diagnostics';
+
import type { TotpCode } from '@aliasvault/models/vault';
type TotpFormData = {
@@ -304,7 +306,7 @@ const TotpEditor: React.FC<TotpEditorProps> = ({
}
})
.then(url => setQrCodeDataUrl(url))
- .catch(err => console.error('Failed to generate QR code:', err));
+ .catch(err => logFailure('Failed to generate QR code', err));
}
setShowQrCode(!showQrCode);
};
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx b/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
index d79315043..ad1ae02eb 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
import { useApp } from '@/entrypoints/popup/context/AppContext';
import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { syncErrorMessage } from '@/utils/SyncError';
@@ -136,7 +137,7 @@ const ServerSyncIndicator: React.FC = () => {
await dbContext.refreshSyncState();
} catch (error) {
- console.error('Retry sync error:', error);
+ logFailure('Retry sync error', error);
} finally {
setIsRetrying(false);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/VaultErrorReport.tsx b/apps/browser-extension/src/entrypoints/popup/components/VaultErrorReport.tsx
index c45c304c3..2e3c5cce1 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/VaultErrorReport.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/VaultErrorReport.tsx
@@ -3,6 +3,8 @@ import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { logFailure } from '@/utils/Diagnostics';
+
/**
* Vault error report props.
*/
@@ -47,7 +49,7 @@ const VaultErrorReport: React.FC<VaultErrorReportProps> = ({ error }) => {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (err) {
- console.error('Failed to copy error report:', err);
+ logFailure('Failed to copy error report', err);
}
};
diff --git a/apps/browser-extension/src/entrypoints/popup/context/AppContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/AppContext.tsx
index b2931b447..94a771540 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/AppContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/AppContext.tsx
@@ -5,6 +5,8 @@ import { useTranslation } from 'react-i18next';
import { useAuth } from '@/entrypoints/popup/context/AuthContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
+import { logExpected } from '@/utils/Diagnostics';
+
import { vaultStateEvents } from '@/events/VaultStateEvents';
type AppContextType = {
@@ -48,7 +50,7 @@ export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children
// Use forced logout, which keeps the username for the login prefill
await auth.clearAuthForced(errorMessage);
} catch (error) {
- console.error('Error during logout:', error);
+ logExpected('[Auth] Logout did not complete cleanly', error);
} finally {
isLoggingOutRef.current = false;
setIsLoggedIn(false);
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index 0f1d88d0c..8e66a991f 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -7,6 +7,7 @@ import React, { createContext, useContext, useState, useEffect, useCallback, use
import { useTranslation } from 'react-i18next';
import { StorageKeys } from '@/utils/constants/storageKeys';
+import { logFailure } from '@/utils/Diagnostics';
import { onMessage, sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { getStorageItem } from '@/utils/StorageUtility';
import { syncErrorMessage, toSyncErrorDetail } from '@/utils/SyncError';
@@ -292,7 +293,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
if (message.includes(AppErrorCode.VAULT_LOCKED)) {
// Vault is locked which is expected when the popup is opened after auto-lock timeout or browser restart.
} else {
- console.error('Error retrieving vault from background:', error);
+ logFailure('Error retrieving vault from background', error);
}
setDbInitialized(true);
setDbAvailable(false);
@@ -321,7 +322,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
hiddenPrivateEmailDomains: hiddenPrivateEmailDomains ?? [],
};
} catch (error) {
- console.error('Error getting vault metadata from local storage:', error);
+ logFailure('Error getting vault metadata from local storage', error);
return null;
}
}, []);
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useAliasGenerator.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useAliasGenerator.ts
index e4f600941..95137e510 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useAliasGenerator.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useAliasGenerator.ts
@@ -3,6 +3,8 @@ import { useCallback, useState, type Dispatch, type SetStateAction } from 'react
import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { logFailure } from '@/utils/Diagnostics';
+
/**
* Generated alias data returned by the hook.
*/
@@ -119,7 +121,7 @@ const useAliasGenerator = (): {
return generatedData;
} catch (error) {
- console.error('Error generating random alias:', error);
+ logFailure('Error generating random alias', error);
return null;
}
}, [dbContext?.sqliteClient, resolveDefaultEmailDomain]);
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useFormPersistence.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useFormPersistence.ts
index 28d09b039..2fe08d9dd 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useFormPersistence.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useFormPersistence.ts
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef } from 'react';
+import { logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
/**
@@ -153,7 +154,7 @@ const useFormPersistence = <T>({
try {
wrapper = JSON.parse(persistedData) as PersistedDataWrapper<T>;
} catch (error) {
- console.error('Error parsing persisted form data:', error);
+ logFailure('Error parsing persisted form data', error);
return false;
}
@@ -167,7 +168,7 @@ const useFormPersistence = <T>({
onRestore(wrapper.data);
return true;
} catch (error) {
- console.error('Error loading persisted form data:', error);
+ logFailure('Error loading persisted form data', error);
return false;
}
}, [formId, onRestore, skipRestore]);
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/usePasswordConfig.ts b/apps/browser-extension/src/entrypoints/popup/hooks/usePasswordConfig.ts
index 87099cc1a..7dcf352d3 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/usePasswordConfig.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/usePasswordConfig.ts
@@ -1,6 +1,8 @@
import * as RustCore from '@aliasvault/client/rust/RustCore';
import { useState, useEffect, useCallback, useRef } from 'react';
+import { logFailure } from '@/utils/Diagnostics';
+
import type { PasswordSettings } from '@aliasvault/models/vault';
/**
@@ -42,7 +44,7 @@ export function usePasswordConfig(
const password = await RustCore.generatePassword(currentSettings, currentSeed);
setPreviewPassword(password);
} catch (error) {
- console.error('Error generating preview password:', error);
+ logFailure('Error generating preview password', error);
setPreviewPassword('');
}
}, []);
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useServiceDetection.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useServiceDetection.ts
index 3db53728d..ae6c8ab7e 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useServiceDetection.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useServiceDetection.ts
@@ -1,6 +1,7 @@
import { useCallback } from 'react';
import { useSearchParams } from 'react-router-dom';
+import { logFailure } from '@/utils/Diagnostics';
import { ServiceDetectionUtility, type ServiceInfo } from '@/utils/serviceDetection/ServiceDetectionUtility';
import { browser } from '#imports';
@@ -85,7 +86,7 @@ const useServiceDetection = (): {
}
}
} catch (error) {
- console.error('Error detecting service information:', error);
+ logFailure('Error detecting service information', error);
}
return {
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
index 29a5d7b88..130bb9e2f 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
@@ -6,8 +6,12 @@ import { useCallback, useRef } from 'react';
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { devLog } from '@/utils/devLogger/DevLogger';
+import { logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
+/** How many unanswered sync-state polls in a row before the poll gives up on the background context. */
+const MAX_POLL_FAILURES = 10;
+
/**
* Hook to execute a vault mutation.
*
@@ -85,6 +89,9 @@ export function useVaultMutate(): {
devLog('[VaultMutate] Starting to poll for sync completion');
+ /** How many consecutive poll failures before giving up. */
+ let consecutiveFailures = 0;
+
pollIntervalRef.current = setInterval(async () => {
try {
/*
@@ -92,6 +99,7 @@ export function useVaultMutate(): {
* and isSyncInProgress status from the background script
*/
const syncState = await sendMessage('GET_SYNC_STATE');
+ consecutiveFailures = 0;
/*
* Only clear uploading indicator when:
@@ -115,7 +123,17 @@ export function useVaultMutate(): {
}
}
} catch (error) {
- console.error('[VaultMutate] Error polling sync state:', error);
+ consecutiveFailures++;
+ if (consecutiveFailures === 1) {
+ logFailure('[VaultMutate] Reading the sync state failed', error);
+ }
+ if (consecutiveFailures >= MAX_POLL_FAILURES && pollIntervalRef.current) {
+ devLog('[VaultMutate] Giving up on the sync completion poll, the background is not answering');
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ dbContext.setIsUploading(false);
+ dbContext.setIsSyncing(false);
+ }
}
}, 200); /* Poll every 200ms */
}, [dbContext]);
@@ -163,7 +181,7 @@ export function useVaultMutate(): {
await dbContext.loadStoredDatabase();
}
}).catch((error) => {
- console.error('Background sync error:', error);
+ logFailure('Background sync error', error);
});
// Start polling for completion (nothing to clear when no indicator was shown)
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
index 8de6232a5..3b16a895b 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
import { useApp } from '@/entrypoints/popup/context/AppContext';
import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { syncErrorMessage } from '@/utils/SyncError';
@@ -108,7 +109,7 @@ export const useVaultSync = (): { syncVault: (options?: VaultSyncOptions) => Pro
return true;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error during vault sync';
- console.error('Vault sync error:', err);
+ logFailure('Vault sync error', err);
onError?.(errorMessage);
return false;
}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx b/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx
index fc2f55786..fc753e053 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx
@@ -9,6 +9,7 @@ import useCurrentTabInfo from '@/entrypoints/popup/hooks/useCurrentTabInfo';
import { consumePendingRedirectUrl } from '@/entrypoints/popup/hooks/useVaultLockRedirect';
import { useVaultSync } from '@/entrypoints/popup/hooks/useVaultSync';
+import { logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { NavigationStateService } from '@/utils/NavigationStateService';
@@ -153,7 +154,7 @@ const Reinitialize: React.FC = () => {
* @param error Error message
*/
onError: (error) => {
- console.error('Background vault sync error:', error);
+ logFailure('Background vault sync error', error);
}
});
}, [syncVault, refreshSyncState, navigate]);
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
index 8d1b2efdc..db2231650 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
@@ -25,6 +25,7 @@ import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
import { StorageKeys } from '@/utils/constants/storageKeys';
+import { logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { syncErrorMessage } from '@/utils/SyncError';
import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';
@@ -93,7 +94,7 @@ const Login: React.FC = () => {
* @param err - the error
*/
const showLoginError = (context: string, err: unknown): void => {
- console.error(`${context}:`, err);
+ logFailure(context, err);
if (err instanceof ClientUpgradeRequiredError) {
// Server refused this client version (HTTP 426).
setError(t('common.errors.clientVersionNotSupported'));
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
index ec8eb0e10..ad266e1fd 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
@@ -24,6 +24,7 @@ import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
+import { logExpected, logFailure } from '@/utils/Diagnostics';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import {
@@ -371,7 +372,7 @@ const Unlock: React.FC = () => {
} else {
await handlePasswordFailedAttempt();
}
- console.error('Unlock error:', err);
+ logFailure('Unlock error', err);
} finally {
hideLoading();
}
@@ -489,16 +490,16 @@ const Unlock: React.FC = () => {
const errorCode = extractErrorCode(getErrorMessage(err, ''));
if (errorCode === AppErrorCode.VAULT_DECRYPT_FAILED) {
// Decryption failed during PIN unlock = wrong PIN, treat as incorrect PIN
- console.error('PIN unlock failed (decryption error):', err);
+ logExpected('[Unlock] The entered PIN did not decrypt the vault', err);
setError(t('settings.unlockMethod.incorrectPin', { attemptsRemaining: 3 }));
} else {
// Other error codes: show the formatted message as-is
- console.error('PIN unlock failed:', err);
+ logFailure('PIN unlock failed', err);
setError(getErrorMessage(err, t('common.errors.unknownErrorTryAgain')));
}
setPin('');
} else {
- console.error('PIN unlock failed:', err);
+ logFailure('PIN unlock failed', err);
setError(t('common.errors.unknownErrorTryAgain'));
setPin('');
}
@@ -552,7 +553,7 @@ const Unlock: React.FC = () => {
await webApi.revokeTokens();
await authContext.clearAuthUserInitiated();
} catch (error) {
- console.error('Error during logout:', error);
+ logFailure('Error during logout', error);
}
};
@@ -640,7 +641,7 @@ const Unlock: React.FC = () => {
} else {
setError(t('common.errors.unknownErrorTryAgain'));
}
- console.error('Mobile unlock error:', err);
+ logFailure('Mobile unlock error', err);
} finally {
hideLoading();
}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Upgrade.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Upgrade.tsx
index 7116542ce..3fee8aa40 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Upgrade.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Upgrade.tsx
@@ -22,6 +22,7 @@ import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
import { useVaultSync } from '@/entrypoints/popup/hooks/useVaultSync';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
+import { logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { syncErrorMessage } from '@/utils/SyncError';
@@ -146,7 +147,7 @@ const Upgrade: React.FC = () => {
setLatestVersion(latest);
}
} catch (error) {
- console.error('Failed to load version information:', error);
+ logFailure('Failed to load version information', error);
setError(t('upgrade.alerts.unableToGetVersionInfo'));
}
}, [sqliteClient, t]);
@@ -165,7 +166,7 @@ const Upgrade: React.FC = () => {
if (!result.success) {
// Back to the consent screen, where the same button retries and the error says why it has to.
- console.error('[Upgrade] Vault manifest migration failed:', result);
+ logFailure('[Upgrade] Vault manifest migration failed', result);
const message = syncErrorMessage(result, t) ?? t('common.errors.unknownError');
setError(message);
setErrorDetail(result.error && result.error !== message ? result.error : null);
@@ -247,13 +248,13 @@ const Upgrade: React.FC = () => {
* @param error Error message
*/
onError: (error: string) => {
- console.error('Sync error after upgrade:', error);
+ logFailure('Sync error after upgrade', error);
// Still navigate to items even if sync fails
finish();
}
});
} catch (error) {
- console.error('Error during post-upgrade sync:', error);
+ logFailure('Error during post-upgrade sync', error);
// Navigate to items even if sync fails
finish();
}
@@ -301,7 +302,7 @@ const Upgrade: React.FC = () => {
try {
sqliteClient.executeRaw(sqlCommand);
} catch (error) {
- console.error(`Error executing SQL command ${i + 1}:`, sqlCommand, error);
+ logFailure(`[Upgrade] Migration SQL command ${i + 1} failed: ${sqlCommand}`, error);
throw new Error(t('upgrade.alerts.failedToApplyMigration', { current: i + 1, total: upgradeResult.sqlCommands.length }));
}
}
@@ -309,7 +310,7 @@ const Upgrade: React.FC = () => {
await handleLegacyUpgradeSuccess();
} catch (error) {
- console.error('Upgrade failed:', error);
+ logFailure('Upgrade failed', error);
setError(error instanceof Error ? error.message : t('common.errors.unknownError'));
setStage('consent');
setIsInitialLoading(false);
@@ -341,7 +342,7 @@ const Upgrade: React.FC = () => {
await startManifestUpgrade();
} catch (error) {
- console.error('Failed to determine the pending vault upgrade:', error);
+ logFailure('Failed to determine the pending vault upgrade', error);
setError(error instanceof Error ? error.message : t('common.errors.unknownError'));
setStage('consent');
setIsInitialLoading(false);
@@ -379,7 +380,7 @@ const Upgrade: React.FC = () => {
await webApi.revokeTokens();
await auth.clearAuthUserInitiated();
} catch (error) {
- console.error('Error during logout:', error);
+ logFailure('Error during logout', error);
}
};
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
index 52e843179..837c3bc5d 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
@@ -14,6 +14,7 @@ import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import ConversionUtility from '@/entrypoints/popup/utils/ConversionUtility';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
+import { logFailure } from '@/utils/Diagnostics';
import { itemRoute } from '@/utils/ItemRoute';
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
@@ -241,7 +242,7 @@ const EmailDetails: React.FC = (): React.ReactElement => {
const bytes = await extractEmailAttachment(sourceBytes, index, detachedBody);
triggerAttachmentDownload(bytes, attachment.mimeType, attachment.filename);
} catch (err) {
- console.error('handleDownloadParsedAttachment error', err);
+ logFailure('[Email] Downloading the attachment failed', err);
setError(err instanceof Error ? err.message : 'Failed to download attachment');
}
};
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
index d0a28a7de..1496c6e83 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
@@ -16,6 +16,7 @@ import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
import { StorageKeys } from '@/utils/constants/storageKeys';
+import { logFailure } from '@/utils/Diagnostics';
import { getStorageItem } from '@/utils/StorageUtility';
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
@@ -99,7 +100,7 @@ const EmailsList: React.FC = () => {
setTotalRecords(data.totalRecords);
}
} catch (error) {
- console.error(error);
+ logFailure('[Emails] Loading the mailbox failed', error);
throw new Error(t('common.errors.unknownError'));
}
} catch (err) {
@@ -141,7 +142,7 @@ const EmailsList: React.FC = () => {
setTotalRecords(data.totalRecords);
} catch (err) {
setError(err instanceof Error ? err.message : t('common.errors.unknownError'));
- console.error('Failed to load more emails:', err);
+ logFailure('Failed to load more emails', err);
} finally {
setIsLoadingMore(false);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
index 5af51a2bb..07429985d 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
@@ -35,6 +35,7 @@ import useItemLogo from '@/entrypoints/popup/hooks/useItemLogo';
import useServiceDetection from '@/entrypoints/popup/hooks/useServiceDetection';
import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
+import { logExpected, logFailure } from '@/utils/Diagnostics';
import { FaviconService } from '@/utils/FaviconService';
import { itemRoute } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
@@ -432,7 +433,7 @@ const ItemAddEdit: React.FC = () => {
try {
const result = sqliteClient.items.getById({ Id: id, ManifestId: manifestId });
if (!result) {
- console.error('Item not found');
+ logExpected('[Item] The item to edit no longer exists');
navigate('/items');
return;
}
@@ -499,7 +500,7 @@ const ItemAddEdit: React.FC = () => {
setLocalLoading(false);
setIsInitialLoading(false);
} catch (err) {
- console.error('Error loading item:', err);
+ logFailure('Error loading item', err);
setLocalLoading(false);
setIsInitialLoading(false);
}
@@ -716,7 +717,7 @@ const ItemAddEdit: React.FC = () => {
elementIdentifier: fillBackElementIdentifier ?? undefined
}, tabId);
} catch (err) {
- console.error('Error autofilling created item into page:', err);
+ logFailure('Error autofilling created item into page', err);
}
/*
@@ -726,7 +727,7 @@ const ItemAddEdit: React.FC = () => {
try {
await NavigationStateService.clearNavigationState();
} catch (err) {
- console.error('Error clearing persisted navigation state:', err);
+ logFailure('Error clearing persisted navigation state', err);
}
// Close this popup window (it was opened as a standalone window from the content script).
@@ -886,7 +887,7 @@ const ItemAddEdit: React.FC = () => {
navigate(itemRoute(savedItem), { replace: true });
}
} catch (err) {
- console.error('Error saving item:', err);
+ logFailure('Error saving item', err);
setIsSaving(false);
}
}, [item, manifestId, isSaving, fieldValues, applicableSystemFields, customFields, dbContext, isEditMode, executeVaultMutationAsync, navigate, location.state, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyIdsMarkedForDeletion, logoSelection, resolvedFaviconSource, webApi, clearPersistedValues, fillBackAndCloseWindow]);
@@ -906,7 +907,7 @@ const ItemAddEdit: React.FC = () => {
navigate('/items');
} catch (err) {
- console.error('Error deleting item:', err);
+ logFailure('Error deleting item', err);
} finally {
setShowDeleteModal(false);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemDetails.tsx
index 29da26cc4..ee4f87ed6 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemDetails.tsx
@@ -19,6 +19,7 @@ import { useHeaderButtons } from '@/entrypoints/popup/context/HeaderButtonsConte
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
+import { logExpected, logFailure } from '@/utils/Diagnostics';
import { itemRoute } from '@/utils/ItemRoute';
import { EmailPreview } from '../../components/EmailPreview';
@@ -72,11 +73,11 @@ const ItemDetails: React.FC = (): React.ReactElement => {
setItem(result);
setIsInitialLoading(false);
} else {
- console.error('Item not found');
+ logExpected('[Item] The requested item no longer exists');
navigate('/items');
}
} catch (err) {
- console.error('Error loading item:', err);
+ logFailure('Error loading item', err);
}
}, [dbContext.sqliteClient, id, manifestId, navigate, setIsInitialLoading]);
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
index 7036e6ea0..ee8efdfe3 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
@@ -29,6 +29,8 @@ import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
import { useVaultSync } from '@/entrypoints/popup/hooks/useVaultSync';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
+import { devLog } from '@/utils/devLogger/DevLogger';
+import { logFailure } from '@/utils/Diagnostics';
import { isSameItem, itemRoute } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
@@ -264,7 +266,7 @@ const ItemsList: React.FC = () => {
*/
const handleSaveFolder = useCallback(async (folderName: string) : Promise<void> => {
if (!dbContext?.sqliteClient) {
- console.error('[FOLDER DEBUG] No sqliteClient available');
+ devLog('[Folders] No sqliteClient available, skipping the folder save');
return;
}
@@ -443,11 +445,11 @@ const ItemsList: React.FC = () => {
* On error.
*/
onError: async (error) => {
- console.error('Error syncing vault:', error);
+ logFailure('Error syncing vault', error);
},
});
} catch (err) {
- console.error('Error refreshing items:', err);
+ logFailure('Error refreshing items', err);
await app.logout('Error while syncing vault, please re-authenticate.');
}
}, [dbContext, app, syncVault]);
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
index 5d3e78d8d..aa2b9ac58 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
@@ -11,6 +11,7 @@ import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { useVaultLockRedirect } from '@/entrypoints/popup/hooks/useVaultLockRedirect';
+import { logFailure } from '@/utils/Diagnostics';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { buildPasskeyAssertion } from '@/utils/passkey/PasskeyAssertionService';
@@ -94,7 +95,7 @@ const PasskeyAuthenticate: React.FC = () => {
})));
}
} catch (error) {
- console.error('Failed to fetch request data:', error);
+ logFailure('Failed to fetch request data', error);
setError(t('common.errors.unknownError'));
}
}
@@ -168,7 +169,7 @@ const PasskeyAuthenticate: React.FC = () => {
credential
});
} catch (error) {
- console.error('PasskeyAuthenticate: Error during authentication', error);
+ logFailure('PasskeyAuthenticate: Error during authentication', error);
setLoading(false);
setError(t('common.errors.unknownError'));
}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
index 39953df41..8216672fe 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
@@ -17,6 +17,7 @@ import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { useVaultLockRedirect } from '@/entrypoints/popup/hooks/useVaultLockRedirect';
import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
+import { logFailure } from '@/utils/Diagnostics';
import { isSameItem } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
@@ -173,7 +174,7 @@ const PasskeyCreate: React.FC = () => {
}
}
} catch (error) {
- console.error('Failed to fetch request data:', error);
+ logFailure('Failed to fetch request data', error);
setError(t('common.errors.unknownError'));
}
}
@@ -486,7 +487,7 @@ const PasskeyCreate: React.FC = () => {
setLocalLoading(false);
} catch (error) {
- console.error('PasskeyCreate: Error creating passkey', error);
+ logFailure('PasskeyCreate: Error creating passkey', error);
/*
* Always clear the loading overlay; otherwise it stays up and hides the error,
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx
index eaad274ca..e9d41306b 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx
@@ -18,6 +18,7 @@ import { useApiUrl } from '@/entrypoints/popup/utils/ApiUrlUtility';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
import { StorageKeys } from '@/utils/constants/storageKeys';
+import { logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { browser, storage } from "#imports";
@@ -148,7 +149,7 @@ const Settings: React.FC = () => {
await webApi.revokeTokens();
await auth.clearAuthUserInitiated();
} catch (error) {
- console.error('Error during logout:', error);
+ logFailure('Error during logout', error);
}
};
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx
index ffa58dc28..f43faeced 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx
@@ -9,6 +9,7 @@ import PageTitle from '@/entrypoints/popup/components/PageTitle';
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
+import { logFailure } from '@/utils/Diagnostics';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import {
isPinEnabled,
@@ -50,7 +51,7 @@ const VaultUnlockSettings: React.FC = () => {
setIsLocked(locked);
setIsInitialLoading(false);
} catch (err: unknown) {
- console.error('Failed to load PIN settings:', err);
+ logFailure('Failed to load PIN settings', err);
setError(t('common.errors.unknownErrorTryAgain'));
setIsInitialLoading(false);
}
@@ -139,7 +140,7 @@ const VaultUnlockSettings: React.FC = () => {
setSuccess(t('settings.unlockMethod.enableSuccess'));
hideLoading();
} catch (err: unknown) {
- console.error('Failed to enable PIN:', err);
+ logFailure('Failed to enable PIN', err);
if (err instanceof InvalidPinFormatError) {
setError(t('settings.unlockMethod.invalidPinFormat'));
@@ -165,7 +166,7 @@ const VaultUnlockSettings: React.FC = () => {
setIsLocked(false);
hideLoading();
} catch (err: unknown) {
- console.error('Failed to disable PIN:', err);
+ logFailure('Failed to disable PIN', err);
setError(t('common.errors.unknownErrorTryAgain'));
hideLoading();
}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx
index f195ffdb4..b9e514d4a 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/security/ChangePasswordSettings.tsx
@@ -13,6 +13,7 @@ import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { useVaultSync } from '@/entrypoints/popup/hooks/useVaultSync';
+import { logFailure } from '@/utils/Diagnostics';
import { removeAndDisablePin } from '@/utils/PinUnlockService';
type PasswordInputProps = {
@@ -126,15 +127,17 @@ const ChangePasswordSettings: React.FC = () => {
showLoading();
await MasterPasswordService.changePassword(webApi, currentPassword, newPassword);
- // The PIN protects the key derived from the old password, which no longer opens the account key chain.
- // TODO: refactor this to automatically update the PIN instead of disabling it?
+ /*
+ * The PIN protects the key derived from the old password, which no longer opens the account key chain.
+ * TODO: refactor this to automatically update the PIN instead of disabling it?
+ */
await removeAndDisablePin();
setCurrentPassword('');
setNewPassword('');
setConfirmPassword('');
setSuccess(t('settings.securitySettings.changePassword.success'));
} catch (err) {
- console.error('Password change failed:', err);
+ logFailure('Password change failed', err);
setError(errorMessage(err));
} finally {
hideLoading();
diff --git a/apps/browser-extension/src/entrypoints/popup/utils/ConversionUtility.ts b/apps/browser-extension/src/entrypoints/popup/utils/ConversionUtility.ts
index 810a2f0bb..103a6c7b7 100644
--- a/apps/browser-extension/src/entrypoints/popup/utils/ConversionUtility.ts
+++ b/apps/browser-extension/src/entrypoints/popup/utils/ConversionUtility.ts
@@ -1,5 +1,7 @@
import DOMPurify from 'dompurify';
+import { logExpected } from '@/utils/Diagnostics';
+
/**
* DOMPurify configuration for email viewing.
* Allows safe HTML elements for email display while blocking XSS vectors.
@@ -56,7 +58,7 @@ class ConversionUtility {
try {
return DOMPurify.sanitize(html, EMAIL_SANITIZER_CONFIG);
} catch (ex) {
- console.error(`Error in sanitizeHtmlForEmailViewing: ${ex instanceof Error ? ex.message : String(ex)}`);
+ logExpected(`[Email] Sanitizing the email HTML failed: ${ex instanceof Error ? ex.message : String(ex)}`);
// Return empty string on error to prevent potential XSS
return '';
}
@@ -121,7 +123,7 @@ class ConversionUtility {
return doc.documentElement.outerHTML;
} catch (ex) {
// Log the exception
- console.error(`Error in convertAnchorTagsToOpenInNewTab: ${ex instanceof Error ? ex.message : String(ex)}`);
+ logExpected(`[Email] Rewriting the email's links failed: ${ex instanceof Error ? ex.message : String(ex)}`);
// Return the original HTML if an error occurs
return html;
diff --git a/apps/browser-extension/src/i18n/StandaloneI18n.ts b/apps/browser-extension/src/i18n/StandaloneI18n.ts
index 2396810ce..da0487e91 100644
--- a/apps/browser-extension/src/i18n/StandaloneI18n.ts
+++ b/apps/browser-extension/src/i18n/StandaloneI18n.ts
@@ -4,6 +4,7 @@
*/
import { StorageKeys } from '@/utils/constants/storageKeys';
+import { logFailure } from '@/utils/Diagnostics';
import {
DEFAULT_LANGUAGE,
@@ -34,7 +35,7 @@ export async function getCurrentLanguage(): Promise<string> {
return detectedLanguage;
} catch (error) {
- console.error('Failed to get current language:', error);
+ logFailure('Failed to get current language', error);
return DEFAULT_LANGUAGE;
}
}
@@ -74,7 +75,7 @@ export async function t(
// Return fallback or key if no translation found
return fallback || key;
} catch (error) {
- console.error('Translation error:', error);
+ logFailure('Translation error', error);
return fallback || key;
}
}
diff --git a/apps/browser-extension/src/i18n/i18n.ts b/apps/browser-extension/src/i18n/i18n.ts
index 24ceee8ee..bdb34e07a 100644
--- a/apps/browser-extension/src/i18n/i18n.ts
+++ b/apps/browser-extension/src/i18n/i18n.ts
@@ -2,6 +2,7 @@ import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import { StorageKeys } from '@/utils/constants/storageKeys';
+import { logFailure } from '@/utils/Diagnostics';
import {
DEFAULT_LANGUAGE,
@@ -56,7 +57,7 @@ const initI18n = async (): Promise<void> => {
// Initialize immediately and handle potential errors
initI18n().catch((error) => {
- console.error('Failed to initialize i18n:', error);
+ logFailure('Failed to initialize i18n', error);
// Even if initialization fails, emit initialized event to prevent app from hanging
i18n.emit('initialized');
});
diff --git a/apps/browser-extension/src/migrations/0.29.7-LegacyApiUrlMigration.ts b/apps/browser-extension/src/migrations/0.29.7-LegacyApiUrlMigration.ts
index 308b401bd..bc1a1cc6e 100644
--- a/apps/browser-extension/src/migrations/0.29.7-LegacyApiUrlMigration.ts
+++ b/apps/browser-extension/src/migrations/0.29.7-LegacyApiUrlMigration.ts
@@ -1,6 +1,7 @@
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import { StorageKeys } from '@/utils/constants/storageKeys';
+import { logFailure } from '@/utils/Diagnostics';
import { storage } from '#imports';
@@ -31,6 +32,6 @@ export async function migrateLegacyApiUrl(): Promise<void> {
await storage.setItem(StorageKeys.CLIENT_URL, AppInfo.DEFAULT_CLIENT_URL);
}
} catch (error) {
- console.error('Failed to migrate legacy API URL:', error);
+ logFailure('Failed to migrate legacy API URL', error);
}
}
diff --git a/apps/browser-extension/src/utils/Diagnostics.ts b/apps/browser-extension/src/utils/Diagnostics.ts
new file mode 100644
index 000000000..befd6adf4
--- /dev/null
+++ b/apps/browser-extension/src/utils/Diagnostics.ts
@@ -0,0 +1,79 @@
+/**
+ * Diagnostics helper functions to log errors and warnings centrally.
+ */
+
+import { AppErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
+import { isExpectedFailure } from '@aliasvault/client/api/errors/ExpectedFailure';
+import { logDefect, logExpected } from '@aliasvault/client/utilities/Diagnostics';
+
+/**
+ * Common messages the browser produces when a message crosses to a context that is not there (any more).
+ * These are routinely expected during normal lifecycle events, and no not indicate a defect.
+ */
+const LIFECYCLE_FAILURE_MESSAGES = [
+ 'could not establish connection',
+ 'receiving end does not exist',
+ 'extension context invalidated',
+ 'message port closed',
+ 'no tab with id',
+ 'no window with id',
+ 'the browser is shutting down',
+ 'only a single offscreen document',
+];
+
+/**
+ * Error codes that, on a sync or migration outcome, name something the environment did rather than a defect.
+ */
+const EXPECTED_ERROR_CODES = new Set<string>([
+ AppErrorCode.SYNC_SERVER_UNREACHABLE,
+ AppErrorCode.SYNC_SERVER_ERROR,
+ AppErrorCode.UPLOAD_OUTDATED,
+ AppErrorCode.UPLOAD_TIMEOUT,
+ AppErrorCode.UPLOAD_TOO_LARGE,
+ AppErrorCode.SERVER_UPDATE_REQUIRED,
+ AppErrorCode.VERSION_INCOMPATIBLE,
+]);
+
+/**
+ * Whether a failed sync or migration outcome names an expected condition.
+ * @param error - the value to inspect
+ */
+function isExpectedOutcome(error: unknown): boolean {
+ if (!error || typeof error !== 'object') {
+ return false;
+ }
+ const code = (error as { errorCode?: unknown }).errorCode;
+ return typeof code === 'string' && EXPECTED_ERROR_CODES.has(code);
+}
+
+/**
+ * Whether a failure is the browser tearing a context down rather than a defect.
+ * @param error - the error to inspect
+ */
+function isLifecycleFailure(error: unknown): boolean {
+ const message = (error instanceof Error ? error.message : String(error ?? '')).toLowerCase();
+ return LIFECYCLE_FAILURE_MESSAGES.some(candidate => message.includes(candidate));
+}
+
+/**
+ * Whether a failure is one the environment can cause on its own.
+ * @param error - the error to classify
+ */
+export function isExpectedExtensionFailure(error: unknown): boolean {
+ return isExpectedFailure(error) || isLifecycleFailure(error) || isExpectedOutcome(error);
+}
+
+/**
+ * Report a failure to the channel its classification calls for.
+ * @param message - what failed, e.g. '[Autofill] Reading the vault failed'
+ * @param error - the error to classify and report
+ */
+export function logFailure(message: string, error: unknown): void {
+ if (isExpectedExtensionFailure(error)) {
+ logExpected(message, error);
+ return;
+ }
+ logDefect(message, error);
+}
+
+export { logDefect, logExpected };
diff --git a/apps/browser-extension/src/utils/FaviconService.ts b/apps/browser-extension/src/utils/FaviconService.ts
index 7a13bee63..51c817916 100644
--- a/apps/browser-extension/src/utils/FaviconService.ts
+++ b/apps/browser-extension/src/utils/FaviconService.ts
@@ -2,6 +2,8 @@ import { Buffer } from 'buffer';
import { selectFaviconTarget, toUrlList } from '@aliasvault/client/rust/RustCore';
+import { logExpected } from '@/utils/Diagnostics';
+
import type { WebApiService } from '@aliasvault/client/api/WebApiService';
import type { SqliteClient } from '@aliasvault/client/database/SqliteClient';
import type { FaviconTarget } from '@aliasvault/client/rust/RustCore';
@@ -100,7 +102,7 @@ export class FaviconService {
} catch (err) {
// Favicon extraction failed or timed out - not critical
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
- console.error('[Favicon] Error extracting favicon:', errorMessage);
+ logExpected('[Favicon] Extracting the favicon failed', errorMessage);
return { success: false, error: errorMessage };
}
}
diff --git a/apps/browser-extension/src/utils/PinUnlockService.ts b/apps/browser-extension/src/utils/PinUnlockService.ts
index cc7acef84..8c44fc17b 100644
--- a/apps/browser-extension/src/utils/PinUnlockService.ts
+++ b/apps/browser-extension/src/utils/PinUnlockService.ts
@@ -3,6 +3,7 @@ import { base64ToBytes, bytesToBase64 } from '@aliasvault/client/utilities/Base6
import { browser } from 'wxt/browser';
import { PIN_STORAGE_KEYS, StorageKeys } from '@/utils/constants/storageKeys';
+import { logFailure } from '@/utils/Diagnostics';
import { storage } from '#imports';
@@ -195,7 +196,7 @@ export async function setupPin(pin: string, unlockKey: string): Promise<void> {
throw error;
}
/* Log internal errors and throw generic error for user */
- console.error('[PinUnlockService] Failed to setup PIN:', error);
+ logFailure('[PinUnlockService] Failed to setup PIN', error);
throw error;
}
}
@@ -278,7 +279,7 @@ export async function removeAndDisablePin(): Promise<void> {
try {
await storage.removeItems([...PIN_STORAGE_KEYS]);
} catch (error) {
- console.error('[PinUnlockService] Failed to disable PIN:', error);
+ logFailure('[PinUnlockService] Failed to disable PIN', error);
throw error;
}
}
@@ -291,7 +292,7 @@ export async function resetFailedAttempts(): Promise<void> {
try {
await storage.setItem(StorageKeys.PIN_FAILED_ATTEMPTS, 0);
} catch (error) {
- console.error('[PinUnlockService] Failed to reset failed attempts:', error);
+ logFailure('[PinUnlockService] Failed to reset failed attempts', error);
}
}
diff --git a/apps/browser-extension/src/utils/formDetector/FormFiller.ts b/apps/browser-extension/src/utils/formDetector/FormFiller.ts
index c3c38b44d..7d018939e 100644
--- a/apps/browser-extension/src/utils/formDetector/FormFiller.ts
+++ b/apps/browser-extension/src/utils/formDetector/FormFiller.ts
@@ -1,5 +1,6 @@
import { Gender, IdentityHelperUtils } from "@aliasvault/models/identity";
+import { logFailure } from '@/utils/Diagnostics';
import { CombinedDateOptionPatterns, CombinedGenderOptionPatterns } from "@/utils/formDetector/FieldPatterns";
import { type FormFields } from "@/utils/formDetector/types/FormFields";
import { ClickValidator } from "@/utils/security/ClickValidator";
@@ -105,7 +106,7 @@ export class FormFiller {
return results;
} catch (error) {
- console.error('[AliasVault Security] Form security validation error:', error);
+ logFailure('[AliasVault Security] Form security validation error', error);
// Fail safely - mark all fields as unsafe if validation fails
this.getAllFormFields().forEach(field => results.set(field, false));
return results;
diff --git a/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts b/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts
index 179629ac2..d2aba1aa6 100644
--- a/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts
+++ b/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts
@@ -1,4 +1,5 @@
import { isAvAutofillAllowed, isAvSuppressSave } from '@/utils/autofill/Autofill';
+import { logFailure } from '@/utils/Diagnostics';
import { extractFaviconUrlSimple } from '@/utils/favicon';
import { FormDetector } from '@/utils/formDetector/FormDetector';
import { closestAcrossShadow, collectShadowRoots, queryAllDeep } from '@/utils/ShadowDom';
@@ -499,7 +500,7 @@ export class LoginDetector {
try {
callback(login);
} catch (error) {
- console.error('[AliasVault] Error in login capture callback:', error);
+ logFailure('[AliasVault] Error in login capture callback', error);
}
}
}
diff --git a/apps/browser-extension/src/utils/security/ClickValidator.ts b/apps/browser-extension/src/utils/security/ClickValidator.ts
index e0e521afa..216c5ebe2 100644
--- a/apps/browser-extension/src/utils/security/ClickValidator.ts
+++ b/apps/browser-extension/src/utils/security/ClickValidator.ts
@@ -1,3 +1,4 @@
+import { logFailure } from '@/utils/Diagnostics';
/**
* ClickValidator - Simplified click validation system for content script security
*
@@ -41,7 +42,7 @@ export class ClickValidator {
return true;
} catch (error) {
- console.error('[AliasVault Security] Click validation error:', error);
+ logFailure('[AliasVault Security] Click validation error', error);
return false;
}
}
diff --git a/apps/browser-extension/src/utils/serviceDetection/ServiceDetectionUtility.ts b/apps/browser-extension/src/utils/serviceDetection/ServiceDetectionUtility.ts
index 2c7868bfc..c074ba988 100644
--- a/apps/browser-extension/src/utils/serviceDetection/ServiceDetectionUtility.ts
+++ b/apps/browser-extension/src/utils/serviceDetection/ServiceDetectionUtility.ts
@@ -1,3 +1,5 @@
+import { logExpected } from '@/utils/Diagnostics';
+
import { FormDetector } from '../formDetector/FormDetector';
/**
@@ -32,7 +34,7 @@ export class ServiceDetectionUtility {
}
return url.origin;
} catch (error) {
- console.error('Error parsing URL:', error);
+ logExpected('[ServiceDetection] The URL could not be parsed', error);
return '';
}
}
@@ -100,7 +102,7 @@ export class ServiceDetectionUtility {
domain: url.hostname.replace(/^www\./, '')
};
} catch (error) {
- console.error('Error parsing tab URL:', error);
+ logExpected('[ServiceDetection] The tab URL could not be parsed, falling back to hostname detection', error);
// Fallback to basic hostname detection
const domain = tabUrl.replace(/^https?:\/\/(www\.)?/, '').split('/')[0];
return {
diff --git a/apps/mobile-app/components/items/details/EmailPreview.tsx b/apps/mobile-app/components/items/details/EmailPreview.tsx
index b67b96821..1640c8f60 100644
--- a/apps/mobile-app/components/items/details/EmailPreview.tsx
+++ b/apps/mobile-app/components/items/details/EmailPreview.tsx
@@ -1,10 +1,12 @@
import { MaterialIcons } from '@expo/vector-icons';
import { router, useFocusEffect } from 'expo-router';
-import React, { useState, useEffect, useCallback } from 'react';
+import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { View, StyleSheet, TouchableOpacity, Linking, AppState } from 'react-native';
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
+import { logExpected } from '@aliasvault/client/utilities/Diagnostics';
+import { mailboxPollDelayMs } from '@aliasvault/client/utilities/PollBackoff';
import type { ApiErrorResponse, MailboxEmail } from '@aliasvault/models/webapi';
import EncryptionUtility from '@/utils/EncryptionUtility';
@@ -37,6 +39,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
const dbContext = useDb();
const colors = useColors();
const { t } = useTranslation();
+ const consecutiveFailuresRef = useRef(0);
const emailsPerLoad = 3;
const canLoadMore = displayedCount < emails.length;
@@ -108,6 +111,21 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
);
useEffect(() => {
+ let cancelled = false;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+
+ /**
+ * Record that a poll failed for the exponential backoff to work.
+ * @param reason - what did not work
+ * @param error - the underlying error, when there is one
+ */
+ const markPollFailed = (reason: string, error?: unknown): void => {
+ if (consecutiveFailuresRef.current === 0) {
+ logExpected(`[EmailPreview] ${reason}`, error);
+ }
+ consecutiveFailuresRef.current++;
+ };
+
/**
* Load the emails.
*/
@@ -147,6 +165,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
});
if (!response.ok) {
+ markPollFailed(`The mailbox request returned HTTP ${response.status}`);
setError(t('items.emailLoadError'));
return;
}
@@ -164,6 +183,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
setEmails(allMails);
updateDisplayedEmails(allMails, displayedCount);
+ consecutiveFailuresRef.current = 0;
} else if (isPrivate) {
// For private domains, use existing encrypted email logic
if (!dbContext?.sqliteClient) {
@@ -200,6 +220,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
// Reset error
setError(null);
+ consecutiveFailuresRef.current = 0;
}
} catch {
// Try to parse as error response instead
@@ -212,32 +233,45 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
return;
}
+ markPollFailed(`The server rejected the mailbox request: ${apiErrorResponse?.code ?? 'unknown'}`);
setError(t(`apiErrors.${apiErrorResponse?.code}`));
return;
}
- } catch {
+ } catch (err) {
// Suppress errors while vault has unsynced changes
if (dbContext.shouldSuppressEmailErrors()) {
return;
}
+ markPollFailed('The mailbox request failed', err);
setError(t('items.emailLoadError'));
}
}
} catch (err) {
- console.error('Error loading emails:', err);
+ markPollFailed('Loading the mailbox failed', err);
setError(t('items.emailUnexpectedError'));
} finally {
setLoading(false);
}
};
- loadEmails();
- // Set up auto-refresh interval only when component is visible
- const interval = isComponentVisible ? setInterval(loadEmails, 2000) : null;
+ /**
+ * Poll, then schedule the next poll while the component is on screen.
+ */
+ const poll = async () : Promise<void> => {
+ await loadEmails();
+ if (cancelled || !isComponentVisible) {
+ return;
+ }
+ timer = setTimeout(poll, mailboxPollDelayMs(consecutiveFailuresRef.current));
+ };
+
+ void poll();
+
return () : void => {
- if (interval) {
- clearInterval(interval);
+ cancelled = true;
+ if (timer) {
+ clearTimeout(timer);
}
};
}, [email, loading, webApi, dbContext, isPublicDomain, isPrivateDomain, isComponentVisible, t, displayedCount, updateDisplayedEmails]);
diff --git a/core/client/eslint.config.mjs b/core/client/eslint.config.mjs
index 89685d760..f0147d655 100644
--- a/core/client/eslint.config.mjs
+++ b/core/client/eslint.config.mjs
@@ -63,7 +63,8 @@ export default [
"ignoreComments": false
}],
"no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 1, "maxBOF": 0 }],
- "no-console": ["error", { allow: ["warn", "error", "info", "debug"] }],
+ // Log through the Diagnostics utility helper instead of raw console.error.
+ "no-console": ["error", { allow: ["warn", "info", "debug"] }],
"jsdoc/require-jsdoc": ["error", {
"require": {
"FunctionDeclaration": true,
@@ -117,6 +118,13 @@ export default [
},
},
},
+ {
+ // The one module allowed to reach the console directly; everything else routes through it.
+ files: ["src/utilities/Diagnostics.ts"],
+ rules: {
+ "no-console": "off",
+ },
+ },
{
// Repositories are written as DbOps (src/database/DbOp.ts): a DbOp or a Promise left unhandled never runs or loses its error.
files: ["src/database/**/*.ts"],
diff --git a/core/client/src/api/LogoutEventEmitter.ts b/core/client/src/api/LogoutEventEmitter.ts
index 3150a36da..656b61f56 100644
--- a/core/client/src/api/LogoutEventEmitter.ts
+++ b/core/client/src/api/LogoutEventEmitter.ts
@@ -1,3 +1,5 @@
+import { logDefect } from '../utilities/Diagnostics';
+
type LogoutListener = (errorMessage: string) => void | Promise<void>;
/**
@@ -28,7 +30,7 @@ class LogoutEventEmitter {
try {
listener(errorTranslationKey);
} catch (error) {
- console.error('Error in logout listener:', error);
+ logDefect('[Logout] A logout listener threw', error);
}
});
}
diff --git a/core/client/src/api/WebApiService.ts b/core/client/src/api/WebApiService.ts
index 4d59591f2..9b554f5cb 100644
--- a/core/client/src/api/WebApiService.ts
+++ b/core/client/src/api/WebApiService.ts
@@ -1,11 +1,13 @@
import { StorageKeys } from '../constants/StorageKeys';
import { AppInfo } from "../platform/AppInfo";
import { getPlatform } from '../platform/ClientPlatform';
+import { logDefect, logExpected } from '../utilities/Diagnostics';
import { CapabilityService } from './CapabilityService';
import { ApiAuthError } from './errors/ApiAuthError';
import { ApiRequestError } from './errors/ApiRequestError';
import { ClientUpgradeRequiredError } from './errors/ClientUpgradeRequiredError';
+import { logFailure } from './errors/ExpectedFailure';
import { NetworkError } from './errors/NetworkError';
import { PayloadTooLargeError } from './errors/PayloadTooLargeError';
import { RequestTimeoutError } from './errors/RequestTimeoutError';
@@ -129,6 +131,8 @@ export class WebApiService {
/**
* Fetch data from the API with authentication headers and access token refresh retry.
+ *
+ * Failures are thrown as typed errors to let the caller decide whether its own failure is expected or a defect.
*/
public async authFetch<T>(
endpoint: string,
@@ -149,55 +153,46 @@ export class WebApiService {
headers,
};
- try {
- const response = await this.rawFetch(endpoint, requestOptions);
+ const response = await this.rawFetch(endpoint, requestOptions);
- if (response.status === 401) {
- const refreshResult = await this.refreshAccessToken();
+ if (response.status === 401) {
+ const refreshResult = await this.refreshAccessToken();
- if (refreshResult.token) {
- // Token refresh succeeded - retry the request
- headers.set('Authorization', `Bearer ${refreshResult.token}`);
- const retryResponse = await this.rawFetch(endpoint, {
- ...requestOptions,
- headers,
- });
-
- if (!retryResponse.ok) {
- // Only auth failures after a successful token refresh mean the session is invalid.
- if (retryResponse.status === 401 || retryResponse.status === 403) {
- throw new ApiAuthError('Request failed after token refresh');
- }
- if (retryResponse.status === 413) {
- throw new PayloadTooLargeError(`Request rejected with HTTP 413: payload exceeds server limit`);
- }
- throw new ApiRequestError(retryResponse.status, await this.extractApiErrorCode(retryResponse));
- }
+ if (refreshResult.token) {
+ headers.set('Authorization', `Bearer ${refreshResult.token}`);
+ const retryResponse = await this.rawFetch(endpoint, {
+ ...requestOptions,
+ headers,
+ });
- return parseJson ? retryResponse.json() : retryResponse as unknown as T;
- } else if (refreshResult.isAuthError) {
- // Token refresh failed due to auth error (401/403) - session is truly expired
- logoutEventEmitter.emit('common.errors.sessionExpired');
- throw new ApiAuthError('Session expired');
- } else {
- // Token refresh failed due to network/server error.
- throw new NetworkError('Token refresh failed due to network error');
+ if (!retryResponse.ok) {
+ if (retryResponse.status === 401 || retryResponse.status === 403) {
+ throw new ApiAuthError('Request failed after token refresh');
+ }
+ if (retryResponse.status === 413) {
+ throw new PayloadTooLargeError(`Request rejected with HTTP 413: payload exceeds server limit`);
+ }
+ throw new ApiRequestError(retryResponse.status, await this.extractApiErrorCode(retryResponse));
}
- }
- if (response.status === 413 && throwOnError) {
- throw new PayloadTooLargeError(`Request rejected with HTTP 413: payload exceeds server limit`);
+ return parseJson ? retryResponse.json() : retryResponse as unknown as T;
+ } else if (refreshResult.isAuthError) {
+ logoutEventEmitter.emit('common.errors.sessionExpired');
+ throw new ApiAuthError('Session expired');
+ } else {
+ throw new NetworkError('Token refresh failed due to network error');
}
+ }
- if (!response.ok && throwOnError) {
- throw new ApiRequestError(response.status, await this.extractApiErrorCode(response));
- }
+ if (response.status === 413 && throwOnError) {
+ throw new PayloadTooLargeError(`Request rejected with HTTP 413: payload exceeds server limit`);
+ }
- return parseJson ? response.json() : response as unknown as T;
- } catch (error) {
- console.error('API request failed:', error);
- throw error;
+ if (!response.ok && throwOnError) {
+ throw new ApiRequestError(response.status, await this.extractApiErrorCode(response));
}
+
+ return parseJson ? response.json() : response as unknown as T;
}
/**
@@ -293,14 +288,10 @@ export class WebApiService {
try {
response = await fetch(url, requestOptions);
} catch (error) {
- console.error('API request failed:', error);
- /*
- * The timeout signal aborts with a DOMException.
- */
+ logExpected(`[WebApi] Request failed: ${endpoint}`, error);
if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
throw new RequestTimeoutError(`Request timed out: ${endpoint}`, error);
}
- // Convert fetch errors to NetworkError for proper error handling
throw new NetworkError(
error instanceof Error ? error.message : 'Network request failed',
error instanceof Error ? error : undefined
@@ -335,21 +326,16 @@ export class WebApiService {
* Issue GET request to the API expecting a file download and return it as raw bytes.
*/
public async downloadBlob(endpoint: string): Promise<Uint8Array> {
- try {
- const response = await this.authFetch<Response>(endpoint, {
- method: 'GET',
- headers: {
- 'Accept': 'application/octet-stream',
- }
- }, false);
+ const response = await this.authFetch<Response>(endpoint, {
+ method: 'GET',
+ headers: {
+ 'Accept': 'application/octet-stream',
+ }
+ }, false);
- // Get the response as an ArrayBuffer
- const arrayBuffer = await response.arrayBuffer();
- return new Uint8Array(arrayBuffer);
- } catch (error) {
- console.error('Error downloading blob:', error);
- throw error;
- }
+ // Get the response as an ArrayBuffer
+ const arrayBuffer = await response.arrayBuffer();
+ return new Uint8Array(arrayBuffer);
}
/**
@@ -404,7 +390,7 @@ export class WebApiService {
}, false);
}
} catch (err) {
- console.error('WebApi revoke tokens error:', err);
+ logFailure('[WebApi] Revoking tokens failed', err);
}
}
@@ -422,7 +408,7 @@ export class WebApiService {
}, false);
}
} catch (err) {
- console.error('WebApi revoke current token error:', err);
+ logFailure('[WebApi] Revoking the current token failed', err);
}
}
@@ -541,7 +527,7 @@ export class WebApiService {
}
// Server errors (5xx) or other non-auth errors, treat as offline/transient
- console.warn(`Token refresh failed with status ${response.status}, treating as offline`);
+ logExpected(`[WebApi] Token refresh failed with status ${response.status}, treating as offline`);
return { token: null, isAuthError: false };
} catch (error) {
// Server refused this client version.
@@ -551,12 +537,12 @@ export class WebApiService {
// Network errors (server unreachable, timeout, DNS, etc.), treat as offline
if (error instanceof NetworkError) {
- console.warn('Token refresh failed due to network error, treating as offline');
+ logExpected('[WebApi] Token refresh failed due to network error, treating as offline');
return { token: null, isAuthError: false };
}
// Unexpected errors, treat as auth error so logout is triggered
- console.error('Unexpected error during token refresh:', error);
+ logDefect('[WebApi] Unexpected error during token refresh', error);
return { token: null, isAuthError: true };
}
}
diff --git a/core/client/src/api/errors/ExpectedFailure.ts b/core/client/src/api/errors/ExpectedFailure.ts
new file mode 100644
index 000000000..64bc8c4be
--- /dev/null
+++ b/core/client/src/api/errors/ExpectedFailure.ts
@@ -0,0 +1,53 @@
+import { logDefect, logExpected } from '../../utilities/Diagnostics';
+
+import { ApiAuthError } from './ApiAuthError';
+import { ApiRequestError } from './ApiRequestError';
+import { ClientUpgradeRequiredError } from './ClientUpgradeRequiredError';
+import { NetworkError } from './NetworkError';
+import { PayloadTooLargeError } from './PayloadTooLargeError';
+import { ServerUpdateRequiredError } from './ServerUpdateRequiredError';
+
+/**
+ * HTTP statuses that fall into expected failure categories and describe server behavior instead of client error.
+ */
+const EXPECTED_STATUS_CODES = new Set([401, 403, 404, 409, 413, 426, 429]);
+
+/**
+ * Whether an error is an abort: a timeout signal firing, the popup closing mid-request, or a caller cancelling.
+ * @param error - the error to inspect
+ */
+function isAbort(error: unknown): boolean {
+ return error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError');
+}
+
+/**
+ * Whether a failure is one the environment can cause on its own.
+ * @param error - the error to classify
+ */
+export function isExpectedFailure(error: unknown): boolean {
+ // NetworkError also covers RequestTimeoutError, which extends it.
+ if (error instanceof NetworkError || error instanceof ApiAuthError || error instanceof PayloadTooLargeError) {
+ return true;
+ }
+ if (error instanceof ClientUpgradeRequiredError || error instanceof ServerUpdateRequiredError) {
+ return true;
+ }
+ if (error instanceof ApiRequestError) {
+ return error.statusCode >= 500 || EXPECTED_STATUS_CODES.has(error.statusCode);
+ }
+ return isAbort(error);
+}
+
+/**
+ * Report a failure on the channel its classification calls for: {@link logExpected} for anything the
+ * environment can cause, {@link logDefect} for the rest.
+ * @param message - what failed, e.g. 'Vault sync failed'
+ * @param error - the error to classify and report
+ */
+export function logFailure(message: string, error: unknown): void {
+ if (isExpectedFailure(error)) {
+ logExpected(message, error);
+ return;
+ }
+ logDefect(message, error);
+}
diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.ts
index ec05ef317..135cb618f 100644
--- a/core/client/src/auth/MasterPasswordService.ts
+++ b/core/client/src/auth/MasterPasswordService.ts
@@ -3,6 +3,7 @@ import { StorageKeys } from '../constants/StorageKeys';
import { EncryptionUtility } from '../crypto/EncryptionUtility';
import { getPlatform } from '../platform/ClientPlatform';
import { VaultSyncHoldReason, withVaultSyncHold } from '../sync/VaultSyncHold';
+import { logDefect } from '../utilities/Diagnostics';
import { SrpAuthService, type SrpClientProof } from './SrpAuthService';
import { VaultKeyService } from './VaultKeyService';
@@ -95,7 +96,7 @@ export class MasterPasswordService {
return code === AppErrorCode.VAULT_DECRYPT_FAILED ? PasswordVerificationResult.InvalidPassword : PasswordVerificationResult.VerificationError;
}
} catch (error) {
- console.error('Password verification failed unexpectedly.', error);
+ logDefect('[MasterPassword] Password verification failed unexpectedly', error);
return PasswordVerificationResult.VerificationError;
}
}
diff --git a/core/client/src/crypto/EncryptionUtility.ts b/core/client/src/crypto/EncryptionUtility.ts
index c4ee2cf35..4efee44ab 100644
--- a/core/client/src/crypto/EncryptionUtility.ts
+++ b/core/client/src/crypto/EncryptionUtility.ts
@@ -1,6 +1,7 @@
import { devWarn } from '../platform/Logger';
import { argon2DeriveKey, parseEmailSource, type ParsedEmailAttachment } from '../rust/RustCore';
import { base64ToBytes, bytesToBase64 } from '../utilities/Base64';
+import { logDefect } from '../utilities/Diagnostics';
import type { EncryptionKey } from '@aliasvault/models/vault';
import type { Email, EmailDecryptionKey, MailboxEmail } from '@aliasvault/models/webapi';
@@ -42,7 +43,7 @@ export class EncryptionUtility {
try {
return await argon2DeriveKey(password, salt, encryptionSettings);
} catch (error) {
- console.error('Argon2 hashing failed:', error);
+ logDefect('[Crypto] Argon2 hashing failed', error);
throw error;
}
}
@@ -288,7 +289,7 @@ export class EncryptionUtility {
return await EncryptionUtility.decryptWithPrivateKeyObject(ciphertext, privateKeyObj);
} catch (error) {
- console.error('RSA decryption failed:', error);
+ logDefect('[Crypto] RSA decryption failed', error);
throw new Error(`Failed to decrypt: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
diff --git a/core/client/src/database/SqliteClient.ts b/core/client/src/database/SqliteClient.ts
index 442064719..5efc3d28d 100644
--- a/core/client/src/database/SqliteClient.ts
+++ b/core/client/src/database/SqliteClient.ts
@@ -7,6 +7,7 @@ import { getPlatform } from '../platform/ClientPlatform';
import { TranslatableMessage } from '../platform/TranslatableMessage';
import { VaultCodec } from '../sync/VaultCodec';
import { base64ToBytes, bytesToBase64 } from '../utilities/Base64';
+import { logDefect } from '../utilities/Diagnostics';
import { syncRepository } from './DbOp';
@@ -211,7 +212,7 @@ export class SqliteClient implements ISyncDatabaseClient {
this._settings = null;
this._logos = null;
} catch (error) {
- console.error('Error initializing SQLite database:', error);
+ logDefect('[Sqlite] Initializing the database failed', error);
throw error;
}
}
@@ -239,7 +240,7 @@ export class SqliteClient implements ISyncDatabaseClient {
this.db.exec('BEGIN TRANSACTION');
this.transactionOpen = true;
} catch (error) {
- console.error('Error beginning transaction:', error);
+ logDefect('[Sqlite] BEGIN TRANSACTION failed', error);
throw error;
}
}
@@ -260,7 +261,7 @@ export class SqliteClient implements ISyncDatabaseClient {
this.db.exec('COMMIT');
this.transactionOpen = false;
} catch (error) {
- console.error('Error committing transaction:', error);
+ logDefect('[Sqlite] COMMIT failed', error);
throw error;
}
}
@@ -302,7 +303,7 @@ export class SqliteClient implements ISyncDatabaseClient {
this.db.exec('ROLLBACK');
this.transactionOpen = false;
} catch (error) {
- console.error('Error rolling back transaction:', error);
+ logDefect('[Sqlite] ROLLBACK failed', error);
throw error;
}
}
@@ -328,7 +329,7 @@ export class SqliteClient implements ISyncDatabaseClient {
this.vacuumIfFragmented();
return this.db.export();
} catch (error) {
- console.error('Error exporting SQLite database:', error);
+ logDefect('[Sqlite] Exporting the database failed', error);
throw error;
}
}
@@ -359,7 +360,7 @@ export class SqliteClient implements ISyncDatabaseClient {
try {
return this.db.query<T>(query, params);
} catch (error) {
- console.error('Error executing query:', error);
+ logDefect(`[Sqlite] Query failed: ${query}`, error);
throw error;
}
}
@@ -388,7 +389,7 @@ export class SqliteClient implements ISyncDatabaseClient {
try {
return this.db.run(query, params);
} catch (error) {
- console.error('Error executing update:', error);
+ logDefect(`[Sqlite] Update failed: ${query}`, error);
throw error;
}
}
@@ -419,7 +420,7 @@ export class SqliteClient implements ISyncDatabaseClient {
this.db.exec(trimmedStatement);
}
} catch (error) {
- console.error('Error executing raw SQL:', error);
+ logDefect('[Sqlite] Raw SQL failed', error);
throw error;
}
}
@@ -486,7 +487,7 @@ export class SqliteClient implements ISyncDatabaseClient {
compatibleUpToVersion: latestClientVersion.compatibleUpToVersion
};
} catch (error) {
- console.error('Error getting database version:', error);
+ logDefect('[Sqlite] Reading the database version failed', error);
throw error;
}
}
@@ -519,7 +520,7 @@ export class SqliteClient implements ISyncDatabaseClient {
return currentVersion.revision < latestVersion.revision;
} catch (error) {
- console.error('Error checking pending migrations:', error);
+ logDefect('[Sqlite] Checking for pending migrations failed', error);
throw error;
}
}
@@ -568,7 +569,7 @@ export class SqliteClient implements ISyncDatabaseClient {
const mimeType = this.detectMimeType(logoBytes);
return `data:${mimeType};base64,${base64Logo}`;
} catch (error) {
- console.error('Error setting logo:', error);
+ logDefect('[Sqlite] Building the logo data URL failed', error);
return null;
}
}
@@ -649,7 +650,7 @@ export class SqliteClient implements ISyncDatabaseClient {
try {
return bytesToBase64(this.toUint8Array(buffer));
} catch (error) {
- console.error('Error encoding to base64:', error);
+ logDefect('[Sqlite] Base64 encoding failed', error);
return null;
}
}
diff --git a/core/client/src/database/repositories/LogoRepository.ts b/core/client/src/database/repositories/LogoRepository.ts
index 34d8f4e7a..9e4fa2173 100644
--- a/core/client/src/database/repositories/LogoRepository.ts
+++ b/core/client/src/database/repositories/LogoRepository.ts
@@ -1,6 +1,7 @@
import { LogoKinds } from '@aliasvault/models/vault';
import { vaultCodecLogoContentHash, vaultCodecLogoIdFor } from '../../rust/RustCore';
+import { logExpected } from '../../utilities/Diagnostics';
import { BaseRepository } from '../BaseRepository';
import { LogoQueries } from '../queries/LogoQueries';
@@ -150,7 +151,7 @@ export class LogoRepository extends BaseRepository {
return new Uint8Array(image as ArrayLike<number>);
}
} catch (error) {
- console.warn('Failed to convert logo image to Uint8Array:', error);
+ logExpected('[Logos] Converting a logo image to bytes failed', error);
}
return null;
diff --git a/core/client/src/database/repositories/SettingsRepository.ts b/core/client/src/database/repositories/SettingsRepository.ts
index fad2e5d08..184f118ec 100644
--- a/core/client/src/database/repositories/SettingsRepository.ts
+++ b/core/client/src/database/repositories/SettingsRepository.ts
@@ -2,6 +2,7 @@ import { DEFAULT_PASSWORD_LENGTH, DEFAULT_WORD_COUNT, DEFAULT_LANGUAGE_CODE, mat
import { deviceLanguage } from '../../platform/DeviceLanguage';
import { getIdentityLanguages } from '../../rust/RustCore';
+import { logExpected } from '../../utilities/Diagnostics';
import { BaseRepository } from '../BaseRepository';
import { SettingsQueries } from '../queries/SettingsQueries';
@@ -86,7 +87,7 @@ export class SettingsRepository extends BaseRepository {
return { ...defaultSettings, ...JSON.parse(settingsJson) };
}
} catch (error) {
- console.warn('Failed to parse password settings:', error);
+ logExpected('[Settings] Parsing the stored password settings failed, falling back to defaults', error);
}
return defaultSettings;
diff --git a/core/client/src/items/TotpUtility.ts b/core/client/src/items/TotpUtility.ts
index e20a2ce33..6fa391b86 100644
--- a/core/client/src/items/TotpUtility.ts
+++ b/core/client/src/items/TotpUtility.ts
@@ -1,6 +1,8 @@
import { normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod } from '@aliasvault/models/vault';
import * as OTPAuth from 'otpauth';
+import { logExpected } from '../utilities/Diagnostics';
+
/**
* The RFC 6238 parameters a TOTP code was created with, as stored on the vault row.
*/
@@ -41,7 +43,7 @@ export function generateTotpCode(secretKey: string, parameters?: TotpParameters)
try {
return createTotp(secretKey, parameters).generate();
} catch (error) {
- console.error('Error generating TOTP code:', error);
+ logExpected('[Totp] The stored secret cannot generate a code', error);
return null;
}
}
diff --git a/core/client/src/utilities/Diagnostics.ts b/core/client/src/utilities/Diagnostics.ts
new file mode 100644
index 000000000..4ac2c4383
--- /dev/null
+++ b/core/client/src/utilities/Diagnostics.ts
@@ -0,0 +1,31 @@
+/**
+ * Diagnostics helper functions to log errors and warnings centrally.
+ *
+ * See {@link isExpectedFailure} for the classification of API failures.
+ */
+
+/**
+ * Report a failure that means this build has a defect. Reaches the browser's extension error list.
+ * @param message - what failed, e.g. 'Vault merge failed'
+ * @param error - the underlying error, when there is one
+ */
+export function logDefect(message: string, error?: unknown): void {
+ if (error === undefined) {
+ console.error(message);
+ return;
+ }
+ console.error(message, error);
+}
+
+/**
+ * Report a failure the environment can cause on its own. Stays out of the browser's extension error list.
+ * @param message - what failed, e.g. 'Status check failed, going offline'
+ * @param error - the underlying error, when there is one
+ */
+export function logExpected(message: string, error?: unknown): void {
+ if (error === undefined) {
+ console.warn(message);
+ return;
+ }
+ console.warn(message, error);
+}
diff --git a/core/client/src/utilities/PollBackoff.ts b/core/client/src/utilities/PollBackoff.ts
new file mode 100644
index 000000000..ea818ad3d
--- /dev/null
+++ b/core/client/src/utilities/PollBackoff.ts
@@ -0,0 +1,24 @@
+/**
+ * Poll with exponential backoff in case of server unreachability.
+ */
+
+/** How often a client asks the server for new mail while polls are succeeding. */
+export const MAILBOX_POLL_INTERVAL_MS = 2000;
+
+/** Longest a client waits between mailbox polls, reached by doubling while polls keep failing. */
+export const MAILBOX_POLL_MAX_INTERVAL_MS = 30000;
+
+/**
+ * How long to wait before the next mailbox poll.
+ * @param consecutiveFailures - how many polls in a row have failed, 0 while polls are succeeding
+ */
+export function mailboxPollDelayMs(consecutiveFailures: number): number {
+ if (consecutiveFailures <= 0) {
+ return MAILBOX_POLL_INTERVAL_MS;
+ }
+
+ return Math.min(
+ MAILBOX_POLL_INTERVAL_MS * 2 ** consecutiveFailures,
+ MAILBOX_POLL_MAX_INTERVAL_MS
+ );
+}