Skip to content

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

Refactor sync result and error handling (#2159)

Leendert de Borstdbb81ba264d3
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 24b551af0..b1506395b 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { ApiRequestError } from '@aliasvault/client/api/errors/ApiRequestError';
-import { AppErrorCode, formatErrorWithCode, getErrorTranslationKey, isErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
+import { AppErrorCode, formatErrorWithCode } from '@aliasvault/client/api/errors/AppErrorCodes';
import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
import { WebApiService } from '@aliasvault/client/api/WebApiService';
import { MasterPasswordService } from '@aliasvault/client/auth/MasterPasswordService';
@@ -17,7 +17,7 @@ import { recordManifestRevisions } from '@aliasvault/client/sync/ManifestRevisio
import { clearDirtyScopes, getDirtyScopes } from '@aliasvault/client/sync/VaultDirtyState';
import { vaultRequiresManifestMigration, VaultMigrationKind, type VaultMigrationStatus } from '@aliasvault/client/sync/VaultManifestMigration';
import { type VaultMutationScope, DEFAULT_VAULT_MUTATION_SCOPE, hasUserVisibleScope } from '@aliasvault/client/sync/VaultMutationScope';
-import { runFullVaultSync, runVaultManifestMigration, runVaultMigrationStatus, type IVaultSyncEngineHost, type VaultSyncEngineResult, type VaultSyncOptions, type VaultSyncPhase as EngineSyncPhase, type VaultSyncStoreOutcome, type VaultSyncStoreRequest } from '@aliasvault/client/sync/VaultSyncEngine';
+import { runFullVaultSync, runVaultManifestMigration, runVaultMigrationStatus, type IVaultSyncEngineHost, type VaultSyncOptions, type VaultSyncPhase as EngineSyncPhase, type VaultSyncStoreOutcome, type VaultSyncStoreRequest } from '@aliasvault/client/sync/VaultSyncEngine';
import { getVaultSyncHoldReason } from '@aliasvault/client/sync/VaultSyncHold';
import { base64ToBytes, bytesToBase64 } from '@aliasvault/client/utilities/Base64';
import { FieldKey, ItemTypes, VaultDataBucketCategory, createSystemField, type Item, type PasswordSettings } from '@aliasvault/models/vault';
@@ -26,6 +26,7 @@ import { storage } from 'wxt/utils/storage';
import { clearAllSavePromptState } from '@/entrypoints/background/SavePromptStateHandler';
import { handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
+import { syncResult, toFullVaultSyncResult, toSyncErrorDetail } from '@/entrypoints/background/VaultSyncResultMapper';
import { AUTH_STORAGE_KEYS, dirtyScopeStorageKey, SESSION_STORAGE_KEYS, StorageKeys, vaultDataStorageKeys, VAULT_LOCK_STORAGE_KEYS } from '@/utils/constants/storageKeys';
import { devError, devLog, devWarn } from '@/utils/devLogger/DevLogger';
@@ -34,6 +35,7 @@ import { sendMessage, type TotpSecret } from '@/utils/messaging/ExtensionMessagi
import { RecentlySelectedItemService } from '@/utils/RecentlySelectedItemService';
import { ServiceDetectionUtility } from '@/utils/serviceDetection/ServiceDetectionUtility';
import { getStorageItem } from '@/utils/StorageUtility';
+import { hasSyncError } from '@/utils/SyncError';
import type { BoolResponse as messageBoolResponse } from '@/utils/types/messaging/BoolResponse';
import type { DuplicateCheckResponse } from '@/utils/types/messaging/DuplicateCheckResponse';
import type { FullVaultSyncRequest } from '@/utils/types/messaging/FullVaultSyncRequest';
@@ -69,6 +71,13 @@ import type { EncryptionKeyDerivationParams } from '@aliasvault/models/metadata'
let cachedSqliteClient: SqliteClient | null = null;
let cachedVaultBlob: string | null = null;
+/**
+ * Global sync queue state.
+ * Prevents multiple simultaneous sync operations and ensures pending changes are synced.
+ */
+let isSyncInProgress = false;
+let hasPendingSync = false;
+
/**
* Define Rust sync engine host interface to bridge the engine to the extension.
*/
@@ -151,13 +160,6 @@ function clearInMemoryVaultState(): void {
handleClearTwoFactorState();
}
-/**
- * Global sync queue state.
- * Prevents multiple simultaneous sync operations and ensures pending changes are synced.
- */
-let isSyncInProgress = false;
-let hasPendingSync = false;
-
/**
* Check if the user is logged in and if the vault is locked, and also check for both kinds of pending vault.
*/
@@ -812,8 +814,7 @@ export async function handleMigrateVaultManifest(): Promise<VaultManifestMigrati
try {
const encryptionKey = await handleGetEncryptionKey();
if (!encryptionKey) {
- // E-202: Vault is locked
- return { success: false, pushed: false, error: formatErrorWithCode(await t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED) };
+ return { success: false, pushed: false, errorCode: AppErrorCode.VAULT_LOCKED };
}
const sqliteClient = await createVaultSqliteClient();
@@ -826,11 +827,10 @@ export async function handleMigrateVaultManifest(): Promise<VaultManifestMigrati
if (result.success) {
devLog(result.pushed ? '[ManifestMigration] Migration pushed to the server.' : '[ManifestMigration] Migration stored locally; the vault stays dirty for the next sync.');
}
- const error = result.errorKey ? await t('common.errors.' + logoutErrorKey(result.errorKey)) : await localizeSyncError(result.error, result.errorCode);
- return { success: result.success, pushed: result.pushed, error };
+ return { success: result.success, pushed: result.pushed, ...toSyncErrorDetail(result) };
} catch (error) {
devError('[ManifestMigration] Manifest migration failed:', error);
- return { success: false, pushed: false, error: error instanceof Error ? error.message : await t('common.errors.unknownError') };
+ return { success: false, pushed: false, error: error instanceof Error ? error.message : undefined };
}
}
@@ -888,15 +888,11 @@ function broadcastSyncPhase(phase: VaultSyncPhase): void {
* error cannot keep re-opening the dialog after it stopped applying.
*/
async function persistSyncErrorState(result: FullVaultSyncResult): Promise<void> {
- const errorMessage = result.errorKey
- ? await t('common.errors.' + result.errorKey)
- : result.error;
-
// requiresLogout and wasOffline have dedicated UX: the forced re-login flow and the offline indicator.
const dedicatedError = result.requiresLogout || result.wasOffline;
- if (errorMessage && !dedicatedError) {
- await storage.setItem(StorageKeys.LAST_SYNC_ERROR, errorMessage);
+ if (hasSyncError(result) && !dedicatedError) {
+ await storage.setItem(StorageKeys.LAST_SYNC_ERROR, { errorKey: result.errorKey, errorCode: result.errorCode, error: result.error });
} else {
await storage.removeItem(StorageKeys.LAST_SYNC_ERROR);
}
@@ -916,64 +912,6 @@ export async function handleFullVaultSync(options?: FullVaultSyncRequest): Promi
return result;
}
-/**
- * Build a sync result.
- * @param overrides - the fields that differ from an uneventful, successful sync
- */
-function syncResult(overrides: Partial<FullVaultSyncResult> = {}): FullVaultSyncResult {
- return { success: true, hasNewVault: false, wasOffline: false, sqliteBlobUpgradeRequired: false, requiresLogout: false, ...overrides };
-}
-
-/**
- * The message the popup shows for a sync failure: the translation of its error code, tagged with the code.
- * @param error - the sync engine's diagnostic message
- * @param errorCode - the client error code the sync engine attached
- */
-async function localizeSyncError(error: string | undefined, errorCode: string | undefined): Promise<string | undefined> {
- if (!error && !errorCode) {
- return undefined;
- }
- devWarn(`[VaultSync] Engine failure (${errorCode ?? 'no code'}): ${error ?? 'no detail'}`);
- const code = errorCode && isErrorCode(errorCode) ? errorCode : AppErrorCode.UNKNOWN_ERROR;
- return formatErrorWithCode(await t(getErrorTranslationKey(code)), code);
-}
-
-/**
- * The `common.errors` key that translates a sync logout reason.
- */
-const LOGOUT_REASON_ERROR_KEYS: Record<string, string> = {
- clientVersionNotSupported: 'clientVersionNotSupported',
- serverVersionNotSupported: 'serverVersionNotSupported',
- sessionExpired: 'sessionExpired',
- passwordChanged: 'passwordChanged',
- vaultVersionIncompatible: 'browserExtensionOutdated',
-};
-
-/**
- * The `common.errors` key for an engine logout reason, `unknownError` for a reason this build does not know.
- * @param reason - the engine's logout reason
- */
-function logoutErrorKey(reason: string): string {
- return LOGOUT_REASON_ERROR_KEYS[reason] ?? 'unknownError';
-}
-
-/**
- * The full sync as the popup reads it.
- * @param result - the engine's outcome
- */
-async function toFullVaultSyncResult(result: VaultSyncEngineResult): Promise<FullVaultSyncResult> {
- return {
- success: result.success,
- hasNewVault: result.hasNewVault,
- wasOffline: result.wasOffline,
- sqliteBlobUpgradeRequired: result.sqliteBlobUpgradeRequired,
- manifestMigrationRequired: result.manifestMigrationRequired,
- requiresLogout: result.requiresLogout,
- errorKey: result.errorKey ? logoutErrorKey(result.errorKey) : undefined,
- error: await localizeSyncError(result.error, result.errorCode),
- };
-}
-
/**
* Full vault sync which does both push and pull based on revision counters.
* @param options - what the caller asks of the sync beyond what the revisions decide
@@ -1001,10 +939,9 @@ async function handleFullVaultSyncInternal(options?: VaultSyncOptions): Promise<
return syncResult({ success: false });
}
if (!encryptionKey) {
- // E-202: Vault is locked
- return syncResult({ success: false, error: formatErrorWithCode(await t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED) });
+ return syncResult({ success: false, errorCode: AppErrorCode.VAULT_LOCKED });
}
- return await toFullVaultSyncResult(await runFullVaultSync(syncEngineHost, options));
+ return toFullVaultSyncResult(await runFullVaultSync(syncEngineHost, options));
} catch (err) {
console.error('Vault sync error:', err);
const message = err instanceof Error ? err.message : 'Unknown error during vault sync';
diff --git a/apps/browser-extension/src/entrypoints/background/VaultSyncResultMapper.ts b/apps/browser-extension/src/entrypoints/background/VaultSyncResultMapper.ts
new file mode 100644
index 000000000..0668ae264
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/background/VaultSyncResultMapper.ts
@@ -0,0 +1,72 @@
+/**
+ * Vault sync result mapper that handles the sync engine's outcome and the result the popup reads.
+ */
+
+import { AppErrorCode, isErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
+
+import { devWarn } from '@/utils/devLogger/DevLogger';
+import type { FullVaultSyncResult } from '@/utils/types/messaging/FullVaultSyncResult';
+import type { SyncErrorDetail } from '@/utils/types/messaging/SyncErrorDetail';
+
+import type { VaultSyncEngineResult } from '@aliasvault/client/sync/VaultSyncEngine';
+
+/**
+ * The `common.errors` key that translates a sync logout reason.
+ */
+const LOGOUT_REASON_ERROR_KEYS: Record<string, string> = {
+ clientVersionNotSupported: 'clientVersionNotSupported',
+ serverVersionNotSupported: 'serverVersionNotSupported',
+ sessionExpired: 'sessionExpired',
+ passwordChanged: 'passwordChanged',
+ vaultVersionIncompatible: 'browserExtensionOutdated',
+};
+
+/**
+ * Build a sync result.
+ * @param overrides - the fields that differ from an uneventful, successful sync
+ */
+export function syncResult(overrides: Partial<FullVaultSyncResult> = {}): FullVaultSyncResult {
+ return { success: true, hasNewVault: false, wasOffline: false, sqliteBlobUpgradeRequired: false, requiresLogout: false, ...overrides };
+}
+
+/**
+ * The `common.errors` key for an engine logout reason, `unknownError` for a reason this build does not know.
+ * @param reason - the engine's logout reason
+ */
+export function logoutErrorKey(reason: string): string {
+ return LOGOUT_REASON_ERROR_KEYS[reason] ?? 'unknownError';
+}
+
+/**
+ * What the popup needs to name a sync failure: the logout reason as a translation key, or the error code of an ordinary failure.
+ * @param result - the engine's outcome
+ */
+export function toSyncErrorDetail(result: Pick<VaultSyncEngineResult, 'error' | 'errorCode' | 'errorKey'>): SyncErrorDetail {
+ if (!result.error && !result.errorCode && !result.errorKey) {
+ return {};
+ }
+
+ devWarn(`[VaultSync] Engine failure (${result.errorCode ?? 'no code'}): ${result.error ?? 'no detail'}`);
+
+ if (result.errorKey) {
+ return { errorKey: logoutErrorKey(result.errorKey) };
+ }
+
+ return { errorCode: result.errorCode && isErrorCode(result.errorCode) ? result.errorCode : AppErrorCode.UNKNOWN_ERROR };
+}
+
+/**
+ * The full sync as the popup reads it.
+ * @param result - the engine's outcome
+ */
+export function toFullVaultSyncResult(result: VaultSyncEngineResult): FullVaultSyncResult {
+ return {
+ success: result.success,
+ hasNewVault: result.hasNewVault,
+ wasOffline: result.wasOffline,
+ sqliteBlobUpgradeRequired: result.sqliteBlobUpgradeRequired,
+ manifestMigrationRequired: result.manifestMigrationRequired,
+ requiresLogout: result.requiresLogout,
+ ...toSyncErrorDetail(result),
+ };
+}
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 d8e84d263..d79315043 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
@@ -5,6 +5,7 @@ import { useApp } from '@/entrypoints/popup/context/AppContext';
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
+import { syncErrorMessage } from '@/utils/SyncError';
/**
* Minimum time (ms) an in-flight indicator stays visible once it has appeared.
@@ -116,10 +117,7 @@ const ServerSyncIndicator: React.FC = () => {
// Handle logout requirement
if (result.requiresLogout) {
- const errorMessage = result.errorKey
- ? t('common.errors.' + result.errorKey)
- : result.error;
- await app.logout(errorMessage);
+ await app.logout(syncErrorMessage(result, t));
return;
}
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index 606588e4c..18910e717 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -4,10 +4,13 @@ import SqliteClient from '@aliasvault/client/database/SqliteClient';
import { hasUnsyncedUserChanges as hasUnsyncedUserChangesInStorage } from '@aliasvault/client/sync/VaultDirtyState';
import { vaultRequiresManifestMigration } from '@aliasvault/client/sync/VaultManifestMigration';
import React, { createContext, useContext, useState, useEffect, useCallback, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
import { StorageKeys } from '@/utils/constants/storageKeys';
import { onMessage, sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { getStorageItem } from '@/utils/StorageUtility';
+import { syncErrorMessage, toSyncErrorDetail } from '@/utils/SyncError';
+import type { SyncErrorDetail } from '@/utils/types/messaging/SyncErrorDetail';
import type { VaultResponse as messageVaultResponse } from '@/utils/types/messaging/VaultResponse';
import { markOwnEncryptionKey, vaultStateEvents } from '@/events/VaultStateEvents';
@@ -85,8 +88,8 @@ type DbContextType = {
requiresLegacySqliteBlobMigration: () => Promise<boolean>;
requiresManifestMigration: () => Promise<boolean>;
/**
- * Last sync error message persisted by the background sync. Surfaced as a popup
- * alert. Null when no error is pending. Updated reactively via storage.watch so
+ * Last sync error persisted by the background sync, translated here so it follows the display language.
+ * Surfaced as a popup alert. Null when no error is pending. Updated reactively via storage.watch so
* background-initiated sync failures show up immediately while popup is open.
*/
syncError: string | null;
@@ -102,6 +105,8 @@ const DbContext = createContext<DbContextType | undefined>(undefined);
* DbProvider to provide the SQLite client to the app that components can use to make database queries.
*/
export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const { t } = useTranslation();
+
/**
* SQLite client.
*/
@@ -140,10 +145,16 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
const [isUploading, setIsUploading] = useState(false);
/**
- * Last sync error written by the background sync. Driven by storage so background-only
- * syncs (e.g. follow-up syncs after pending mutations) reach the user.
+ * Last sync error written by the background sync, as the key and code it reported. Driven by storage so
+ * background-only syncs (e.g. follow-up syncs after pending mutations) reach the user.
+ */
+ const [syncErrorDetail, setSyncErrorDetail] = useState<SyncErrorDetail | null>(null);
+
+ /**
+ * The stored sync error in the current display language. Translated on read, so switching language
+ * re-renders the message instead of leaving the one the background happened to write.
*/
- const [syncError, setSyncError] = useState<string | null>(null);
+ const syncError = useMemo(() => syncErrorDetail ? syncErrorMessage(syncErrorDetail, t) ?? null : null, [syncErrorDetail, t]);
/**
* Check if email errors should be suppressed.
@@ -175,12 +186,12 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
const [offlineMode, pendingUserChanges, lastError] = await Promise.all([
storage.getItem(StorageKeys.IS_OFFLINE_MODE) as Promise<boolean | null>,
hasUnsyncedUserChangesInStorage(),
- storage.getItem(StorageKeys.LAST_SYNC_ERROR) as Promise<string | null>
+ storage.getItem(StorageKeys.LAST_SYNC_ERROR)
]);
isOfflineRef.current = offlineMode ?? false;
setIsOfflineState(offlineMode ?? false);
setHasUnsyncedUserChanges(pendingUserChanges);
- setSyncError(lastError ?? null);
+ setSyncErrorDetail(toSyncErrorDetail(lastError));
};
loadSyncState();
}, []);
@@ -190,8 +201,8 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
* even when the failing sync wasn't triggered by anything in the popup itself.
*/
useEffect(() => {
- const unwatch = storage.watch<string | null>(StorageKeys.LAST_SYNC_ERROR, (newValue) => {
- setSyncError(newValue ?? null);
+ const unwatch = storage.watch(StorageKeys.LAST_SYNC_ERROR, (newValue) => {
+ setSyncErrorDetail(toSyncErrorDetail(newValue));
});
return (): void => {
unwatch();
@@ -213,7 +224,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
* Dismiss the current sync error from both React state and persisted storage.
*/
const clearSyncError = useCallback(async (): Promise<void> => {
- setSyncError(null);
+ setSyncErrorDetail(null);
await storage.removeItem(StorageKeys.LAST_SYNC_ERROR);
}, []);
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
index 60bc2fa49..532390bc6 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
@@ -6,6 +6,7 @@ import { useDb } from '@/entrypoints/popup/context/DbContext';
import { devLog } from '@/utils/devLogger/DevLogger';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
+import { hasSyncError } from '@/utils/SyncError';
/**
* Hook to execute a vault mutation.
@@ -130,7 +131,7 @@ export function useVaultMutate(): {
* After sending message, we start polling to detect completion.
*/
void sendMessage('FULL_VAULT_SYNC', {}).then(async (syncResult) => {
- if (!silent && !syncResult.success && (syncResult.error || syncResult.errorKey)) {
+ if (!silent && !syncResult.success && hasSyncError(syncResult)) {
/*
* Permanent failure (e.g. HTTP 413 vault too large). Stop polling and clear the upload
* spinner. Skipped for a silent scope: it owns neither the poll nor the spinner, both of
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
index cfc277651..8de6232a5 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
@@ -5,6 +5,7 @@ import { useApp } from '@/entrypoints/popup/context/AppContext';
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
+import { syncErrorMessage } from '@/utils/SyncError';
type VaultSyncOptions = {
onSuccess?: (hasNewVault: boolean) => void;
@@ -56,8 +57,7 @@ export const useVaultSync = (): { syncVault: (options?: VaultSyncOptions) => Pro
// Handle logout requirement
if (result.requiresLogout) {
- const errorMessage = result.errorKey ? t('common.errors.' + result.errorKey) : result.error;
- await app.logout(errorMessage);
+ await app.logout(syncErrorMessage(result, t));
return false;
}
@@ -91,8 +91,7 @@ export const useVaultSync = (): { syncVault: (options?: VaultSyncOptions) => Pro
// Handle errors
if (!result.success) {
- const errorMessage = result.errorKey ? t('common.errors.' + result.errorKey) : result.error ?? t('common.errors.unknownError');
- onError?.(errorMessage);
+ onError?.(syncErrorMessage(result, t) ?? t('common.errors.unknownError'));
return false;
}
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 b9516d5fd..c36ac48f4 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
@@ -26,6 +26,7 @@ import SrpUtility from '@/entrypoints/popup/utils/SrpUtility';
import { StorageKeys } from '@/utils/constants/storageKeys';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
+import { syncErrorMessage } from '@/utils/SyncError';
import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';
import { vaultStateEvents } from '@/events/VaultStateEvents';
@@ -80,7 +81,7 @@ const Login: React.FC = () => {
throw new ServerUpdateRequiredError();
}
if (!result.success) {
- throw new VaultProcessingError('vault-pull', new Error(result.errorKey ? t('common.errors.' + result.errorKey) : result.error ?? t('common.errors.unknownError')));
+ throw new VaultProcessingError('vault-pull', new Error(syncErrorMessage(result, t) ?? t('common.errors.unknownError')));
}
await dbContext.loadStoredDatabase();
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 def8c7a22..21b40760f 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Upgrade.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Upgrade.tsx
@@ -23,6 +23,7 @@ import { useVaultSync } from '@/entrypoints/popup/hooks/useVaultSync';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
+import { syncErrorMessage } from '@/utils/SyncError';
import type { VaultVersion } from '@aliasvault/vault';
@@ -162,7 +163,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.
- setError(result.error ?? t('common.errors.unknownError'));
+ setError(syncErrorMessage(result, t) ?? t('common.errors.unknownError'));
setStage('consent');
setIsInitialLoading(false);
return;
diff --git a/apps/browser-extension/src/utils/SyncError.ts b/apps/browser-extension/src/utils/SyncError.ts
new file mode 100644
index 000000000..148fc1331
--- /dev/null
+++ b/apps/browser-extension/src/utils/SyncError.ts
@@ -0,0 +1,44 @@
+import { AppErrorCode, formatErrorWithCode, getErrorTranslationKey, isErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
+
+import type { SyncErrorDetail } from '@/utils/types/messaging/SyncErrorDetail';
+
+import type { TFunction } from 'i18next';
+
+/**
+ * Whether a sync outcome carries a failure the user should be told about.
+ * @param detail - the sync outcome
+ */
+export function hasSyncError(detail: SyncErrorDetail): boolean {
+ return detail.errorKey !== undefined || detail.errorCode !== undefined || detail.error !== undefined;
+}
+
+/**
+ * The stored sync error, tolerating the plain string an older build left behind.
+ * @param value - what came out of storage
+ */
+export function toSyncErrorDetail(value: unknown): SyncErrorDetail | null {
+ if (typeof value === 'string') {
+ return { error: value };
+ }
+ if (value && typeof value === 'object') {
+ const detail = value as SyncErrorDetail;
+ return hasSyncError(detail) ? detail : null;
+ }
+ return null;
+}
+
+/**
+ * The message to show for a failed sync, or undefined when the outcome names no failure.
+ * @param detail - the sync outcome
+ * @param t - the renderer's translation function
+ */
+export function syncErrorMessage(detail: SyncErrorDetail, t: TFunction): string | undefined {
+ if (detail.errorKey) {
+ return t('common.errors.' + detail.errorKey);
+ }
+ if (detail.errorCode) {
+ const code = isErrorCode(detail.errorCode) ? detail.errorCode : AppErrorCode.UNKNOWN_ERROR;
+ return formatErrorWithCode(t(getErrorTranslationKey(code)), code);
+ }
+ return detail.error;
+}
diff --git a/apps/browser-extension/src/utils/types/messaging/FullVaultSyncResult.ts b/apps/browser-extension/src/utils/types/messaging/FullVaultSyncResult.ts
index 7da6826cf..0a2139e97 100644
--- a/apps/browser-extension/src/utils/types/messaging/FullVaultSyncResult.ts
+++ b/apps/browser-extension/src/utils/types/messaging/FullVaultSyncResult.ts
@@ -1,13 +1,13 @@
+import type { SyncErrorDetail } from '@/utils/types/messaging/SyncErrorDetail';
+
/**
* Result of a full vault sync operation.
*/
-export type FullVaultSyncResult = {
+export type FullVaultSyncResult = SyncErrorDetail & {
success: boolean;
hasNewVault: boolean;
wasOffline: boolean;
sqliteBlobUpgradeRequired: boolean;
manifestMigrationRequired?: boolean;
- error?: string;
- errorKey?: string;
requiresLogout: boolean;
};
diff --git a/apps/browser-extension/src/utils/types/messaging/SyncErrorDetail.ts b/apps/browser-extension/src/utils/types/messaging/SyncErrorDetail.ts
new file mode 100644
index 000000000..34e88dc7f
--- /dev/null
+++ b/apps/browser-extension/src/utils/types/messaging/SyncErrorDetail.ts
@@ -0,0 +1,11 @@
+/**
+ * What a failed sync reports, in the form the popup translates for display.
+ */
+export type SyncErrorDetail = {
+ /** Translation key under `common.errors` naming the failure reason. */
+ errorKey?: string;
+ /** Client error code (`E-xxx`) whose translation is shown, tagged with the code. */
+ errorCode?: string;
+ /** Message shown as-is when neither a key nor a code applies. */
+ error?: string;
+};
diff --git a/apps/browser-extension/src/utils/types/messaging/VaultManifestMigrationResult.ts b/apps/browser-extension/src/utils/types/messaging/VaultManifestMigrationResult.ts
index 6c1d8c47d..04355fa42 100644
--- a/apps/browser-extension/src/utils/types/messaging/VaultManifestMigrationResult.ts
+++ b/apps/browser-extension/src/utils/types/messaging/VaultManifestMigrationResult.ts
@@ -1,8 +1,9 @@
+import type { SyncErrorDetail } from '@/utils/types/messaging/SyncErrorDetail';
+
/**
* Result of the manifest migration.
*/
-export type VaultManifestMigrationResult = {
+export type VaultManifestMigrationResult = SyncErrorDetail & {
success: boolean;
pushed: boolean;
- error?: string;
};