Skip to content

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

Update web app error handling and display (#2437)

Leendert de Borst05e3c931d42d
diff --git a/apps/web/src/components/alerts/ServerValidationErrors.tsx b/apps/web/src/components/alerts/ServerValidationErrors.tsx
index e06ec5373..af4b3b271 100644
--- a/apps/web/src/components/alerts/ServerValidationErrors.tsx
+++ b/apps/web/src/components/alerts/ServerValidationErrors.tsx
@@ -1,11 +1,15 @@
import React from 'react';
+import { useTranslation } from 'react-i18next';
import AlertMessageError from '@/components/alerts/AlertMessageError';
+import Button from '@/components/shared/Button';
+import { asksForClientUpdate, updateApp } from '@/utils/ClientUpdate';
/**
- * List of form-level errors.
+ * List of form-level errors, with an update button when one asks the user to update the app.
*/
const ServerValidationErrors: React.FC<{ errors: string[]; className?: string }> = ({ errors, className = '' }) => {
+ const { t } = useTranslation();
if (errors.length === 0) {
return null;
}
@@ -14,6 +18,9 @@ const ServerValidationErrors: React.FC<{ errors: string[]; className?: string }>
{errors.map((error, index) => (
<AlertMessageError key={index} message={error} />
))}
+ {errors.some(asksForClientUpdate) && (
+ <Button onClick={updateApp} color="primary" additionalClasses="mt-2">{t('common.updateApp')}</Button>
+ )}
</div>
);
};
diff --git a/apps/web/src/components/auth/setup/SetupSteps.tsx b/apps/web/src/components/auth/setup/SetupSteps.tsx
index 6028bcaef..2549fe086 100644
--- a/apps/web/src/components/auth/setup/SetupSteps.tsx
+++ b/apps/web/src/components/auth/setup/SetupSteps.tsx
@@ -1,3 +1,4 @@
+import { apiErrorMessage } from '@aliasvault/client/api/errors/ApiErrorMessage';
import { ApiRequestError } from '@aliasvault/client/api/errors/ApiRequestError';
import { MIN_ACCEPTED_PASSWORD_LENGTH } from '@aliasvault/client/utilities/PasswordStrength';
import React, { useEffect, useRef, useState } from 'react';
@@ -12,7 +13,6 @@ import { useAuth } from '@/context/AuthContext';
import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
import { RegistrationService } from '@/services/RegistrationService';
-import { apiErrorMessage } from '@/utils/ApiErrors';
const STEP_LOADING_MS = 300;
const USERNAME_DEBOUNCE_MS = 300;
diff --git a/apps/web/src/context/AuthContext.tsx b/apps/web/src/context/AuthContext.tsx
index 37bde0588..b11eb24e6 100644
--- a/apps/web/src/context/AuthContext.tsx
+++ b/apps/web/src/context/AuthContext.tsx
@@ -128,8 +128,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
* Log out when the API reports the session is gone.
*/
useEffect(() => {
- return logoutEventEmitter.subscribe(async (errorKey: string) => {
- await logout({ errorMessage: t(errorKey) });
+ return logoutEventEmitter.subscribe(async (messageKey) => {
+ await logout({ errorMessage: t(messageKey) });
});
}, [logout, t]);
diff --git a/apps/web/src/pages/auth/Login.tsx b/apps/web/src/pages/auth/Login.tsx
index d80355e22..fa53a051e 100644
--- a/apps/web/src/pages/auth/Login.tsx
+++ b/apps/web/src/pages/auth/Login.tsx
@@ -1,7 +1,5 @@
-import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
-import { extractErrorCode, translateCodedError } from '@aliasvault/client/api/errors/AppErrorCodes';
-import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';
-import { ServerUpdateRequiredError } from '@aliasvault/client/api/errors/ServerUpdateRequiredError';
+import { extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
+import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';
import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';
import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';
@@ -23,7 +21,7 @@ import { useLoading } from '@/context/LoadingContext';
import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
import { usePageTitle } from '@/hooks/usePageTitle';
-import { apiErrorMessage } from '@/utils/ApiErrors';
+import { asksForClientUpdate } from '@/utils/ClientUpdate';
import { focusWhenVisible } from '@/utils/FocusWhenVisible';
import { StorageKeys } from '@/utils/StorageKeys';
import { vaultStore } from '@/vault/VaultStore';
@@ -74,8 +72,8 @@ const Login: React.FC = () => {
// Show the message a forced logout left behind, and prefill the username it kept.
useEffect(() => {
if (auth.globalMessage) {
- // A coded message shows as a critical error in place of the form.
- if (extractErrorCode(auth.globalMessage)) {
+ // A coded message shows as a critical error in place of the form; an update request shows with its update button.
+ if (extractErrorCode(auth.globalMessage) || asksForClientUpdate(auth.globalMessage)) {
setErrors([auth.globalMessage]);
} else {
notifications.addErrorMessage(auth.globalMessage, true);
@@ -101,25 +99,13 @@ const Login: React.FC = () => {
/**
* Turn a failure into the message(s) the form shows.
*/
- const toErrorMessages = (err: unknown): string[] => {
+ const toErrorMessages = async (err: unknown): Promise<string[]> => {
console.error('Login error:', err);
- if (err instanceof ClientUpgradeRequiredError) {
- return [t('common.errors.clientVersionNotSupported')];
- }
- if (err instanceof ServerUpdateRequiredError) {
- return [t('common.errors.serverVersionNotSupported')];
- }
- if (apiErrorCodeOf(err)) {
- return [apiErrorMessage(err, t, t('auth.loginForm.loginErrorMessage'))];
- }
- const codedError = translateCodedError(err, t);
- if (codedError) {
- return [codedError];
- }
- if (import.meta.env.DEV && err instanceof Error) {
+ const message = await describeAuthError(err, { fallback: 'auth.loginForm.loginErrorMessage' });
+ if (import.meta.env.DEV && err instanceof Error && message.key === 'auth.loginForm.loginErrorMessage') {
return [err.message];
}
- return [t('auth.loginForm.loginErrorMessage')];
+ return [formatErrorMessage(message, t)];
};
/**
@@ -171,7 +157,7 @@ const Login: React.FC = () => {
const params = { salt: result.salt, encryptionType: result.encryptionType, encryptionSettings: result.encryptionSettings };
await completeLogin(result.username, result.token, result.refreshToken, result.unlockKey, params);
} catch (err) {
- setErrors(toErrorMessages(err));
+ setErrors(await toErrorMessages(err));
} finally {
hideLoading();
}
@@ -204,7 +190,7 @@ const Login: React.FC = () => {
await processLoginVerify(validateLoginResponse, prepared.passwordHashBase64, response);
} catch (err) {
- setErrors(toErrorMessages(err));
+ setErrors(await toErrorMessages(err));
} finally {
hideLoading();
}
@@ -229,7 +215,7 @@ const Login: React.FC = () => {
const validateLoginResponse = await srpUtil.validateLogin2Fa(username, passwordHashString, rememberMe || rememberMachine, loginResponse, parseInt(code, 10));
await processLoginVerify(validateLoginResponse, passwordHashBase64, loginResponse);
} catch (err) {
- setErrors(toErrorMessages(err));
+ setErrors(await toErrorMessages(err));
} finally {
hideLoading();
}
@@ -250,7 +236,7 @@ const Login: React.FC = () => {
const validateLoginResponse = await srpUtil.validateLoginRecoveryCode(username, passwordHashString, rememberMe, loginResponse, recoveryCode.trim());
await processLoginVerify(validateLoginResponse, passwordHashBase64, loginResponse);
} catch (err) {
- setErrors(toErrorMessages(err));
+ setErrors(await toErrorMessages(err));
} finally {
hideLoading();
}
diff --git a/apps/web/src/pages/auth/Unlock.tsx b/apps/web/src/pages/auth/Unlock.tsx
index a9070ddbd..9743b79d5 100644
--- a/apps/web/src/pages/auth/Unlock.tsx
+++ b/apps/web/src/pages/auth/Unlock.tsx
@@ -1,5 +1,6 @@
-import { extractErrorCode, translateCodedError } from '@aliasvault/client/api/errors/AppErrorCodes';
+import { extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';
+import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';
import { MasterPasswordService } from '@aliasvault/client/auth/MasterPasswordService';
import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';
@@ -88,7 +89,7 @@ const Unlock: React.FC = () => {
*/
const statusCheck = async (): Promise<void> => {
if (!auth.isLoggedIn) {
- notifications.addErrorMessage(t('auth.unlockPage.sessionTimedOutError'));
+ notifications.addErrorMessage(t('common.errors.sessionExpired'));
navigate('/user/login', { replace: true });
return;
}
@@ -107,7 +108,7 @@ const Unlock: React.FC = () => {
}
} catch (err) {
if (err instanceof ClientUpgradeRequiredError) {
- await auth.logout({ errorMessage: t('common.errors.clientVersionNotSupported') });
+ await auth.logout({ errorMessage: t('common.errors.clientNotSupported') });
return;
}
setErrors([t('auth.unlockPage.connectionFailedError')]);
@@ -173,16 +174,11 @@ const Unlock: React.FC = () => {
navigate('/sync', { replace: true });
} catch (err) {
console.error('Unlock error:', err);
- const code = err instanceof Error ? extractErrorCode(err.message) : null;
- if (await VaultKeyService.isWrongUnlockKey(code)) {
- setErrors([t('auth.unlockPage.incorrectPasswordError')]);
- } else if (code) {
- // A coded failure keeps its code, so the user can report it.
- setErrors([translateCodedError(err, t) ?? t('auth.loginForm.loginErrorMessage')]);
- } else if (import.meta.env.DEV && err instanceof Error) {
+ const message = await describeAuthError(err, { fallback: 'auth.loginForm.loginErrorMessage' });
+ if (import.meta.env.DEV && err instanceof Error && message.key === 'auth.loginForm.loginErrorMessage') {
setErrors([err.message]);
} else {
- setErrors([t('auth.loginForm.loginErrorMessage')]);
+ setErrors([formatErrorMessage(message, t)]);
}
} finally {
hideLoading();
@@ -215,16 +211,13 @@ const Unlock: React.FC = () => {
navigate('/sync', { replace: true });
} catch (err) {
console.error('Mobile unlock error:', err);
- const codedError = translateCodedError(err, t);
+ const message = await describeAuthError(err, { fallback: 'auth.loginForm.loginErrorMessage' });
if (err instanceof ClientUpgradeRequiredError) {
- await auth.logout({ errorMessage: t('common.errors.clientVersionNotSupported') });
- } else if (codedError) {
- // A coded failure keeps its code, so the user can report it.
- setErrors([codedError]);
- } else if (import.meta.env.DEV && err instanceof Error) {
+ await auth.logout({ errorMessage: formatErrorMessage(message, t) });
+ } else if (import.meta.env.DEV && err instanceof Error && message.key === 'auth.loginForm.loginErrorMessage') {
setErrors([err.message]);
} else {
- setErrors([t('auth.loginForm.loginErrorMessage')]);
+ setErrors([formatErrorMessage(message, t)]);
}
} finally {
hideLoading();
diff --git a/apps/web/src/pages/settings/security/ChangePassword.tsx b/apps/web/src/pages/settings/security/ChangePassword.tsx
index ec9e7c4ba..e00352d05 100644
--- a/apps/web/src/pages/settings/security/ChangePassword.tsx
+++ b/apps/web/src/pages/settings/security/ChangePassword.tsx
@@ -1,3 +1,4 @@
+import { apiErrorMessage } from '@aliasvault/client/api/errors/ApiErrorMessage';
import { IncorrectPasswordError, MasterPasswordService, PasswordChangedElsewhereError } from '@aliasvault/client/auth/MasterPasswordService';
import { MIN_ACCEPTED_PASSWORD_LENGTH } from '@aliasvault/client/utilities/PasswordStrength';
import React, { useRef, useState } from 'react';
@@ -15,7 +16,6 @@ import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
import { usePageTitle } from '@/hooks/usePageTitle';
import { useVaultSync } from '@/hooks/useVaultSync';
-import { apiErrorMessage } from '@/utils/ApiErrors';
const VALIDATION_DEBOUNCE_MS = 800;
diff --git a/apps/web/src/pages/settings/security/DeleteAccount.tsx b/apps/web/src/pages/settings/security/DeleteAccount.tsx
index fe27cf94b..d435f396e 100644
--- a/apps/web/src/pages/settings/security/DeleteAccount.tsx
+++ b/apps/web/src/pages/settings/security/DeleteAccount.tsx
@@ -1,3 +1,4 @@
+import { apiErrorMessage } from '@aliasvault/client/api/errors/ApiErrorMessage';
import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -15,7 +16,6 @@ import { useLoading } from '@/context/LoadingContext';
import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
import { usePageTitle } from '@/hooks/usePageTitle';
-import { apiErrorMessage } from '@/utils/ApiErrors';
import type { DeleteAccountInitiateRequest, DeleteAccountInitiateResponse, DeleteAccountRequest } from '@aliasvault/models/webapi';
diff --git a/apps/web/src/pages/sync/Sync.tsx b/apps/web/src/pages/sync/Sync.tsx
index eae28ab1a..77f8cd3d4 100644
--- a/apps/web/src/pages/sync/Sync.tsx
+++ b/apps/web/src/pages/sync/Sync.tsx
@@ -10,10 +10,12 @@ import { Link, useNavigate } from 'react-router-dom';
import AlertMessageError from '@/components/alerts/AlertMessageError';
import CriticalErrorPanel from '@/components/alerts/CriticalErrorPanel';
import BoldLoadingIndicator from '@/components/loading/BoldLoadingIndicator';
+import Button from '@/components/shared/Button';
import { useAuth } from '@/context/AuthContext';
import { useDb } from '@/context/DbContext';
import { usePageTitle } from '@/hooks/usePageTitle';
import { useVaultMutate } from '@/hooks/useVaultMutate';
+import { updateApp } from '@/utils/ClientUpdate';
import { waitForMinimumDuration } from '@/utils/Delay';
import { getLocalPreference, removeLocalPreference } from '@/utils/LocalPreferences';
import { LocalPreferenceKeys } from '@/utils/StorageKeys';
@@ -146,7 +148,7 @@ const Sync: React.FC = () => {
if (!authStatus.hasStoredVault) {
const result = await vaultStore.fullVaultSync({ forcePull: true, reportErrorToPopup: false });
- if (result.requiresLogout || result.errorKey) {
+ if (result.requiresLogout || result.logoutReason) {
await auth.logout({ errorMessage: syncErrorMessage(result, t) });
navigate('/user/login', { replace: true });
return;
@@ -224,6 +226,7 @@ const Sync: React.FC = () => {
<p className="mt-4 text-sm text-gray-500 dark:text-gray-400">
{t('sync.versionNotSupported.contactSupport')}
</p>
+ <Button onClick={updateApp} color="primary" additionalClasses="mt-4">{t('common.updateApp')}</Button>
</div>
</div>
);
diff --git a/apps/web/src/platform/WebPlatform.ts b/apps/web/src/platform/WebPlatform.ts
index b4f30248e..d1c33261c 100644
--- a/apps/web/src/platform/WebPlatform.ts
+++ b/apps/web/src/platform/WebPlatform.ts
@@ -3,7 +3,7 @@
*/
import { createRustSqliteEngine } from '@aliasvault/client/database/RustSqliteEngine';
-import { type IClientPlatform, TranslatableMessage } from '@aliasvault/client/platform';
+import { type IClientPlatform } from '@aliasvault/client/platform';
import { createWasmRustCore } from '@aliasvault/client/rust/WasmRustCore';
import wasmUrl from '@aliasvault/client/wasm/aliasvault_core_bg.wasm?url';
@@ -11,13 +11,7 @@ import i18n from '@/i18n/i18n';
import { WebKeyValueStore } from '@/platform/WebKeyValueStore';
import { devError, devLog, devWarn } from '@/utils/DevLogger';
-/**
- * Which translation key backs each of the core's own messages.
- */
-const TRANSLATION_KEYS: Record<TranslatableMessage, string> = {
- [TranslatableMessage.ClientOutdated]: 'common.clientVersionUnsupported',
- [TranslatableMessage.VaultUpgradeRequired]: 'content.vaultUpgradeRequired',
-};
+import type { TranslationKey } from '@aliasvault/i18n';
/**
* The Rust core, streamed into WebAssembly.instantiateStreaming; it also hosts the SQLite engine.
@@ -42,7 +36,7 @@ export const webPlatform: IClientPlatform = {
rustCore,
sqlite: createRustSqliteEngine(rustCore),
/**
- * Translate one of the core's own messages through the app's i18n.
+ * Translate a shared message through the app's i18n.
*/
- translate: async (message: TranslatableMessage): Promise<string> => i18n.t(TRANSLATION_KEYS[message]),
+ translate: async (key: TranslationKey): Promise<string> => i18n.t(key),
};
diff --git a/apps/web/src/utils/ApiErrors.ts b/apps/web/src/utils/ApiErrors.ts
deleted file mode 100644
index 542eac341..000000000
--- a/apps/web/src/utils/ApiErrors.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
-
-import type { TFunction } from 'i18next';
-
-/**
- * The message for a failed API call: the translated API error code when the server sent one, else the fallback.
- * @param error - the thrown error
- * @param t - the translation function
- * @param fallback - the message when no known code is present
- */
-export function apiErrorMessage(error: unknown, t: TFunction, fallback: string): string {
- const code = apiErrorCodeOf(error);
- if (code) {
- const key = `apiErrors.${code}`;
- const translated = t(key);
- return translated === key ? fallback : translated;
- }
- return fallback;
-}
diff --git a/apps/web/src/utils/ClientUpdate.ts b/apps/web/src/utils/ClientUpdate.ts
new file mode 100644
index 000000000..bc7872d02
--- /dev/null
+++ b/apps/web/src/utils/ClientUpdate.ts
@@ -0,0 +1,23 @@
+import i18n from '@/i18n/i18n';
+
+import type { TranslationKey } from '@aliasvault/i18n';
+
+/*
+ * The messages that ask the user to update AliasVault, which triggers to show a reload page button.
+ */
+const CLIENT_UPDATE_KEYS: TranslationKey[] = ['common.errors.clientNotSupported', 'common.errors.clientOutdated'];
+
+/**
+ * Whether a message asks the user to update AliasVault.
+ * @param message - the translated message, possibly followed by an error code
+ */
+export function asksForClientUpdate(message: string): boolean {
+ return CLIENT_UPDATE_KEYS.some(key => message.startsWith(i18n.t(key)));
+}
+
+/**
+ * Load the latest version of the web app.
+ */
+export function updateApp(): void {
+ window.location.reload();
+}
diff --git a/apps/web/src/vault/VaultStore.ts b/apps/web/src/vault/VaultStore.ts
index f3aa177d3..077d49c78 100644
--- a/apps/web/src/vault/VaultStore.ts
+++ b/apps/web/src/vault/VaultStore.ts
@@ -248,7 +248,7 @@ async function persistSyncErrorState(result: FullVaultSyncResult): Promise<void>
const storage = getPlatform().storage;
const dedicatedError = result.requiresLogout || result.wasOffline;
if (hasSyncError(result) && !dedicatedError) {
- await storage.set(StorageKeys.LAST_SYNC_ERROR, { errorKey: result.errorKey, errorCode: result.errorCode, error: result.error });
+ await storage.set(StorageKeys.LAST_SYNC_ERROR, { logoutReason: result.logoutReason, errorCode: result.errorCode, error: result.error });
} else {
await storage.remove(StorageKeys.LAST_SYNC_ERROR);
}