Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add explicit error status response UI and tests (#2413)
Leendert de Borst4dac831bbe66
diff --git a/apps/web/src/components/alerts/CriticalErrorPanel.tsx b/apps/web/src/components/alerts/CriticalErrorPanel.tsxnew file mode 100644index 000000000..8668a01f5--- /dev/null+++ b/apps/web/src/components/alerts/CriticalErrorPanel.tsx@@ -0,0 +1,78 @@+import React, { useState } from 'react';+import { useTranslation } from 'react-i18next';++import AlertMessageError from '@/components/alerts/AlertMessageError';+import SupportContact from '@/components/alerts/SupportContact';++type CriticalErrorPanelProps = {+ report?: string | null;+ title?: string;+ description?: string;+ onBack?: () => void;+ footer?: React.ReactNode;+};++/**+ * A blocking error that takes over the whole screen and shows the error details.+ */+const CriticalErrorPanel: React.FC<CriticalErrorPanelProps> = ({ report, title, description, onBack, footer }) => {+ const { t } = useTranslation();+ const [copied, setCopied] = useState(false);+ const [message, ...detailLines] = report?.split('\n') ?? [];+ const details = detailLines.join('\n').trim();++ /**+ * Copy the report and confirm it for a moment.+ */+ const copyReport = async (): Promise<void> => {+ if (!report) {+ return;+ }+ try {+ await navigator.clipboard.writeText(report);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ } catch (error) {+ console.error('Failed to copy the error report:', error);+ }+ };++ return (+ <div className="fixed inset-0 z-50 flex flex-col items-center justify-center px-6 py-8 overflow-y-auto bg-gray-100 dark:bg-gray-900">+ <div id="critical-error" className="relative p-6 sm:p-8 bg-white dark:bg-gray-700 rounded-lg sm:shadow-xl max-w-md w-full mx-auto">+ <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">{title ?? t('common.errors.vaultLoadErrorTitle')}</h2>+ <p className="text-sm text-gray-500 dark:text-gray-400">{description ?? t('common.errors.vaultLoadError')}</p>++ {report && (+ <div id="critical-error-report">+ <AlertMessageError message={message} />+ {details && (+ <pre className="mt-3 max-h-48 overflow-auto rounded-lg border border-gray-200 bg-gray-50 p-3 font-mono text-xs text-gray-700 whitespace-pre-wrap break-all select-all dark:border-gray-600 dark:bg-gray-900/40 dark:text-gray-300">{details}</pre>+ )}+ <div className="mt-2 flex justify-end">+ <button type="button" id="copy-error-report" onClick={copyReport} className={`inline-flex items-center gap-1.5 text-sm font-medium hover:underline ${copied ? 'text-green-600 dark:text-green-400' : 'text-primary-700 dark:text-primary-500'}`}>+ <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">+ <path d="M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z"></path>+ <path d="M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z"></path>+ </svg>+ {copied ? t('components.main.components.totpCodes.totpViewer.CopiedMessage') : t('common.errors.copyErrorDetails')}+ </button>+ </div>+ </div>+ )}++ <SupportContact report={report} className="mt-3" />++ {onBack && (+ <button type="button" id="critical-error-back" onClick={onBack} className="mt-6 w-full px-5 py-2 text-base font-medium text-center text-white bg-primary-700 rounded-lg hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">+ {t('sharedResources.Back')}+ </button>+ )}+ </div>++ {footer && <div className="text-sm font-medium text-gray-500 dark:text-gray-400 mt-6">{footer}</div>}+ </div>+ );+};++export default CriticalErrorPanel;diff --git a/apps/web/src/components/alerts/SupportContact.tsx b/apps/web/src/components/alerts/SupportContact.tsxnew file mode 100644index 000000000..07e0cb475--- /dev/null+++ b/apps/web/src/components/alerts/SupportContact.tsx@@ -0,0 +1,28 @@+import React from 'react';+import { useTranslation } from 'react-i18next';++import { getAppConfig } from '@/config/AppConfig';++/** Marker put in the string's placeholder so the mail link can be put in its place. */+const EMAIL_MARKER = '%%EMAIL%%';++/**+ * The configured support address as a mail link, prefilled with the error report. Renders empty without an address.+ */+const SupportContact: React.FC<{ report?: string | null; className?: string }> = ({ report, className = '' }) => {+ const { t } = useTranslation();+ const supportEmail = getAppConfig().supportEmail;+ if (supportEmail.length === 0) {+ return null;+ }++ const [before, after] = t('common.errors.contactSupportAt', { 0: EMAIL_MARKER }).split(EMAIL_MARKER);+ const href = report ? `mailto:${supportEmail}?body=${encodeURIComponent(report)}` : `mailto:${supportEmail}`;+ return (+ <p id="support-contact" className={`text-sm text-gray-500 dark:text-gray-400 ${className}`.trim()}>+ {before}<a href={href} className="text-primary-600 hover:underline dark:text-primary-400">{supportEmail}</a>{after ?? ''}+ </p>+ );+};++export default SupportContact;diff --git a/apps/web/src/i18n/locales/en.json b/apps/web/src/i18n/locales/en.jsonindex 84360566e..df36e8afb 100644--- a/apps/web/src/i18n/locales/en.json+++ b/apps/web/src/i18n/locales/en.json@@ -33,7 +33,10 @@"errors": {"browserExtensionOutdated": "This browser extension is outdated and cannot be used to access this vault. Please update this browser extension to continue.","clientVersionNotSupported": "This version of the AliasVault browser extension is not supported by the server anymore. Please update your browser extension to the latest version.",+ "contactSupportAt": "Contact support at {{0}}.",+ "copyErrorDetails": "Copy error details","invalidCode": "Please enter a valid 6-digit authentication code.",+ "keyChainUnreadable": "Your password is correct, but the encryption keys of your vault could not be opened. Please contact support.","mergeFailed": "Failed to merge vault changes. Please try again.","mobileLoginRequestExpired": "Mobile login request timed out. Please reload the page and try again.","passwordChanged": "Your password has changed since the last time you logged in. Please login again for security reasons.",@@ -43,10 +46,13 @@"serverVersionTooOld": "The AliasVault server needs to be updated to a newer version in order to use this feature. Please contact the server admin if you need help.","sessionExpired": "Your session has expired. Please log in again.","syncConflictMaxRetries": "Could not sync vault after multiple attempts. Please try again later.",+ "unexpectedErrorContactSupport": "An unexpected error occurred. Please try again, and contact support if the problem persists.","unknownError": "An unknown error occurred","unknownErrorTryAgain": "An unknown error occurred. Please try again.",+ "vaultDataUnreadable": "Your vault data could not be read, so your data is not accessible at this moment. Please contact support.","vaultIsLocked": "Vault is locked","vaultLoadError": "Something went wrong while loading your vault. Please copy the error details below and contact support for help.",+ "vaultLoadErrorTitle": "Your vault could not be loaded","vaultNotAvailable": "Vault not available","vaultSyncTimeout": "Vault sync timed out. This can happen when the vault is large or the internet connection is slow. Please try again.","vaultTooLarge": "The vault is too large for the server to accept. Try to remove some items or attachments to reduce the size and try again.",diff --git a/apps/web/src/pages/auth/Login.tsx b/apps/web/src/pages/auth/Login.tsxindex 1a6d0a7e5..fb2f938d6 100644--- a/apps/web/src/pages/auth/Login.tsx+++ b/apps/web/src/pages/auth/Login.tsx@@ -1,5 +1,5 @@import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';-import { getErrorMessage, hasErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';+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 { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';@@ -10,6 +10,7 @@ import React, { useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Link, useNavigate } from 'react-router-dom';+import CriticalErrorPanel from '@/components/alerts/CriticalErrorPanel';import ServerValidationErrors from '@/components/alerts/ServerValidationErrors';import PasswordInputField from '@/components/auth/PasswordInputField';import FooterLogin from '@/components/layout/FooterLogin';@@ -68,7 +69,12 @@ const Login: React.FC = () => {// Show the message a forced logout left behind, and prefill the username it kept.useEffect(() => {if (auth.globalMessage) {- notifications.addErrorMessage(auth.globalMessage, true);+ // A coded message shows as a critical error in place of the form.+ if (extractErrorCode(auth.globalMessage)) {+ setErrors([auth.globalMessage]);+ } else {+ notifications.addErrorMessage(auth.globalMessage, true);+ }auth.clearGlobalMessage();}getPlatform().storage.get<string>(StorageKeys.USERNAME).then((saved) => {@@ -101,8 +107,9 @@ const Login: React.FC = () => {if (apiErrorCodeOf(err)) {return [apiErrorMessage(err, t, t('components.auth.login.LoginErrorMessage'))];}- if (hasErrorCode(err)) {- return [getErrorMessage(err, t('components.auth.login.LoginErrorMessage'))];+ const codedError = translateCodedError(err, t);+ if (codedError) {+ return [codedError];}if (import.meta.env.DEV && err instanceof Error) {return [err.message];@@ -212,6 +219,19 @@ const Login: React.FC = () => {const inputClass = 'bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500';const submitClass = 'w-full text-white bg-primary-600 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800';+ // A coded error is critical: it replaces the form.+ const criticalError = errors.find(error => extractErrorCode(error) !== null);+ if (criticalError) {+ /**+ * Dismiss the error and start the login over.+ */+ const backToLogin = (): void => {+ setErrors([]);+ setStep('credentials');+ };+ return <CriticalErrorPanel report={criticalError} onBack={backToLogin} />;+ }+if (step === 'two-factor') {return (<>diff --git a/apps/web/src/pages/auth/Unlock.tsx b/apps/web/src/pages/auth/Unlock.tsxindex 0e00ded7a..cb2c2a004 100644--- a/apps/web/src/pages/auth/Unlock.tsx+++ b/apps/web/src/pages/auth/Unlock.tsx@@ -1,4 +1,4 @@-import { extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';+import { extractErrorCode, translateCodedError } from '@aliasvault/client/api/errors/AppErrorCodes';import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';import { MasterPasswordService } from '@aliasvault/client/auth/MasterPasswordService';import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';@@ -8,6 +8,7 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next';import { Link, useNavigate, useParams } from 'react-router-dom';+import CriticalErrorPanel from '@/components/alerts/CriticalErrorPanel';import ServerValidationErrors from '@/components/alerts/ServerValidationErrors';import PasswordInputField from '@/components/auth/PasswordInputField';import FooterLogin from '@/components/layout/FooterLogin';@@ -173,6 +174,19 @@ const Unlock: React.FC = () => {const code = err instanceof Error ? extractErrorCode(err.message) : null;if (await VaultKeyService.isWrongUnlockKey(code)) {setErrors([t('pages.auth.unlock.IncorrectPasswordError')]);+ } else if (code) {+ // A coded failure keeps its code, so the user can report it.+ setErrors([translateCodedError(err, t) ?? t('pages.auth.unlock.GenericUnlockError')]);+ } else if (import.meta.env.DEV && err instanceof Error) {+ setErrors([err.message]);+ } else {+ setErrors([t('pages.auth.unlock.GenericUnlockError')]);+ }+ } finally {+ hideLoading();+ }+ };+} else if (import.meta.env.DEV && err instanceof Error) {setErrors([err.message]);} else {@@ -202,6 +216,13 @@ const Unlock: React.FC = () => {);}+ // A coded error is critical: it replaces the form.+ const criticalError = errors.find(error => extractErrorCode(error) !== null);+ if (criticalError) {+ const logoutLink = <>{t('pages.auth.unlock.SwitchAccountsText')} <Link to="/user/logout" className="text-primary-700 hover:underline dark:text-primary-500">{t('pages.auth.unlock.LogOutLink')}</Link></>;+ return <CriticalErrorPanel report={criticalError} onBack={() => setErrors([])} footer={logoutLink} />;+ }+return (<><div className="flex space-x-4">diff --git a/apps/web/src/pages/sync/Sync.tsx b/apps/web/src/pages/sync/Sync.tsxindex 2f16f4c1f..1143bb9d3 100644--- a/apps/web/src/pages/sync/Sync.tsx+++ b/apps/web/src/pages/sync/Sync.tsx@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';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 { useAuth } from '@/context/AuthContext';import { useDb } from '@/context/DbContext';@@ -204,18 +205,6 @@ const Sync: React.FC = () => {*/const renderStatus = (): React.ReactNode => {switch (status) {- case 'decryption-failed':- return (- <div className="relative p-6 sm:p-8 bg-white dark:bg-gray-700 rounded-lg sm:shadow-xl max-w-md w-full mx-auto">- <div className="text-center">- <h2 className="mt-4 text-xl font-semibold text-gray-900 dark:text-white">{t('pages.main.sync.statusMessages.errorVaultDecrypt.ErrorTitle')}</h2>- <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">{t('pages.main.sync.statusMessages.errorVaultDecrypt.ErrorDescription')}</p>- </div>- {errorDetails && (- <pre id="vault-error-report" className="mt-4 max-h-48 overflow-auto rounded bg-gray-100 dark:bg-gray-800 p-3 text-left text-xs text-gray-700 dark:text-gray-300 whitespace-pre-wrap break-all select-all">{errorDetails}</pre>- )}- </div>- );case 'version-unrecognized':return (<div className="relative p-6 sm:p-8 bg-white dark:bg-gray-700 rounded-lg sm:shadow-xl max-w-md w-full mx-auto">@@ -294,12 +283,24 @@ const Sync: React.FC = () => {}};+ const logoutLink = (+ <>+ {t('pages.main.sync.sync.SwitchAccountsText')} <Link to="/user/logout" className="text-primary-700 hover:underline dark:text-primary-500">{t('pages.main.sync.sync.LogoutLink')}</Link>+ </>+ );++ if (status === 'decryption-failed') {+ return errorDetails+ ? <CriticalErrorPanel report={errorDetails} footer={logoutLink} />+ : <CriticalErrorPanel title={t('pages.main.sync.statusMessages.errorVaultDecrypt.ErrorTitle')} description={t('pages.main.sync.statusMessages.errorVaultDecrypt.ErrorDescription')} footer={logoutLink} />;+ }+return (<div className="fixed inset-0 flex flex-col items-center justify-center px-6 pt-8 pb-8 h-full w-full">{renderStatus()}<div className="text-sm font-medium text-gray-500 dark:text-gray-400 mt-6">- {t('pages.main.sync.sync.SwitchAccountsText')} <Link to="/user/logout" className="text-primary-700 hover:underline dark:text-primary-500">{t('pages.main.sync.sync.LogoutLink')}</Link>+ {logoutLink}</div></div>);diff --git a/apps/web/tests/e2e/04-vault-errors.spec.ts b/apps/web/tests/e2e/04-vault-errors.spec.tsnew file mode 100644index 000000000..4a6b56654--- /dev/null+++ b/apps/web/tests/e2e/04-vault-errors.spec.ts@@ -0,0 +1,93 @@+/**+ * Category 4: Vault errors (requires API)+ *+ * Each test breaks the account's server vault on purpose, then checks the app correctly reports it to the user.+ */+import { test, expect } from '../fixtures';+import { createTestUserWithDamagedKeyChain } from '../helpers/test-api';+import { writeManifestWithBrokenRow, writeUndecryptableManifest } from '../helpers/vault-tamper';++import type { Page } from '@playwright/test';++const KEY_CHAIN_UNREADABLE_MESSAGE = 'Your password is correct, but the encryption keys of your vault could not be opened. Please contact support.';+const VAULT_DATA_UNREADABLE_MESSAGE = 'Your vault data could not be read, so your data is not accessible at this moment. Please contact support.';++/**+ * Check the page shows only the critical error: its message and code in a copyable report, and the support address.+ */+async function expectCriticalError(page: Page, message: string, code: string): Promise<void> {+ await expect(page.getByRole('heading', { name: 'Your vault could not be loaded' })).toBeVisible();+ await expect(page.getByText('copy the error details below and contact support')).toBeVisible();+ await expect(page.locator('#critical-error-report')).toContainText(`${message} (Code: ${code})`);+ await expect(page.locator('#copy-error-report')).toBeVisible();+ await expect(page.locator('#support-contact').getByRole('link', { name: '[email protected]' })).toBeVisible();+ await expect(page.locator('#password')).toHaveCount(0);+}++test.describe('4. Vault errors', () => {+ test('4.1 should report a server vault that does not decrypt', async ({ app, apiUrl, testUser }) => {+ await writeUndecryptableManifest(apiUrl, testUser);++ await app.page.goto('/user/login');+ await app.submitLogin(testUser.username, testUser.password);++ await expect(app.page).toHaveURL(/\/sync$/);+ await expectCriticalError(app.page, VAULT_DATA_UNREADABLE_MESSAGE, 'E-503');+ await expect(app.page.locator('#critical-error-report')).toContainText('AES-GCM decryption failed');+ });++ test('4.2 should report a server vault that does not load into the local database', async ({ app, apiUrl, testUser }) => {+ // Decrypts and passes the codec, but the row misses required columns, so materializing it fails.+ await writeManifestWithBrokenRow(apiUrl, testUser, 'Items', { Id: crypto.randomUUID(), Name: 'Broken row' });++ await app.page.goto('/user/login');+ await app.submitLogin(testUser.username, testUser.password);++ await expect(app.page).toHaveURL(/\/sync$/);+ await expectCriticalError(app.page, VAULT_DATA_UNREADABLE_MESSAGE, 'E-508');+ await expect(app.page.locator('#critical-error-report')).toContainText('NOT NULL constraint failed');+ });++ test('4.3 should report a key chain the password does not fully open', async ({ app, apiUrl }) => {+ const user = await createTestUserWithDamagedKeyChain(apiUrl);++ await app.page.goto('/user/login');+ await app.submitLogin(user.username, user.password);++ // The error replaces the login form instead of landing on the unlock page without explanation.+ await expect(app.page).toHaveURL(/\/user\/login$/);+ await expectCriticalError(app.page, KEY_CHAIN_UNREADABLE_MESSAGE, 'E-207');++ await test.step('going back shows the login form again', async () => {+ await app.page.locator('#critical-error-back').click();+ await expect(app.page.locator('#login-button')).toBeVisible();+ });+ });++ test('4.4 should report a key chain the password does not fully open on unlock', async ({ app, testUser }) => {+ await app.login(testUser.username, testUser.password);++ await test.step('reloading locks the vault', async () => {+ await app.page.reload();+ await expect(app.page).toHaveURL(/\/unlock$/);+ });++ // Unlock fetches the key chain again; damage the encrypted vault key in that response.+ await app.page.route(/\/VaultKey\/[^/]+$/, async (route) => {+ const response = await route.fetch();+ const body = await response.json() as { vaultKey?: { encryptedVek?: string } };+ if (body.vaultKey?.encryptedVek) {+ const encryptedVek = Buffer.from(body.vaultKey.encryptedVek, 'base64');+ encryptedVek[encryptedVek.length - 1] ^= 0xff;+ body.vaultKey.encryptedVek = encryptedVek.toString('base64');+ }+ await route.fulfill({ response, json: body });+ });++ await app.page.locator('#password').fill(testUser.password);+ await app.page.locator('#unlock-button').click();++ await expect(app.page).toHaveURL(/\/unlock$/);+ await expectCriticalError(app.page, KEY_CHAIN_UNREADABLE_MESSAGE, 'E-207');+ });+});diff --git a/apps/web/tests/fixtures/WebApp.ts b/apps/web/tests/fixtures/WebApp.tsindex 4c4e4a79f..c4076eaaa 100644--- a/apps/web/tests/fixtures/WebApp.ts+++ b/apps/web/tests/fixtures/WebApp.ts@@ -1,4 +1,4 @@-import { expect, type Page } from '@playwright/test';+import { expect, type Locator, type Page } from '@playwright/test';/*** Page object for the web app: the user-level flows tests are written in.@@ -34,11 +34,17 @@ export class WebApp {await this.page.getByRole('link', { name: 'Log in with existing account' }).click();await expect(this.page).toHaveURL(/\/user\/login$/);+ await this.submitLogin(username, password);+ await this.expectVaultOpen(username);+ }++ /**+ * Fill in and submit the login form on the current page, without waiting for the result.+ */+ public async submitLogin(username: string, password: string): Promise<void> {await this.page.locator('#email').fill(username);await this.page.locator('#password').fill(password);await this.page.locator('#login-button').click();-- await this.expectVaultOpen(username);}/**@@ -49,4 +55,44 @@ export class WebApp {await expect(this.page.locator('#mobileMenuDropdown').getByText(username, { exact: true })).toBeAttached();}+ /**+ * Create a login item with only a name via the top bar widget, and wait for its view page.+ */+ public async createItem(name: string): Promise<void> {+ await this.page.locator('#quickIdentityButton').click();+ await this.page.locator('#serviceName').fill(name);+ await this.page.locator('#quickIdentitySubmit').click();+ await expect(this.page.locator('#service-name')).toHaveValue(name);+ await this.saveItemButton().click();+ await expect(this.page.getByText('Item created successfully.')).toBeVisible();+ await this.expectItemView(name);+ }++ /**+ * Open the vault list via the top menu; a full page load (goto, reload) would lock the vault.+ */+ public async openVault(): Promise<void> {+ await this.page.getByRole('link', { name: 'Vault', exact: true }).click();+ await expect(this.page).toHaveURL(/\/items(\?.*)?$/);+ }++ /**+ * Wait until the view page of the item with the given name shows.+ */+ public async expectItemView(name: string): Promise<void> {+ await expect(this.page).toHaveURL(ITEM_VIEW_URL);+ await expect(this.page.getByRole('heading', { name, exact: true })).toBeVisible();+ }++ /**+ * The Save Item button of the add/edit page.+ */+ public saveItemButton(): Locator {+ return this.page.getByRole('button', { name: 'Save Item' }).first();+ }}++/**+ * The view page of an item: /items/{manifestId}/{id}.+ */+export const ITEM_VIEW_URL = /\/items\/[0-9a-f-]{36}\/[0-9a-f-]{36}$/;diff --git a/apps/web/tests/fixtures/fixtures.ts b/apps/web/tests/fixtures/fixtures.tsindex f59168a20..808414646 100644--- a/apps/web/tests/fixtures/fixtures.ts+++ b/apps/web/tests/fixtures/fixtures.ts@@ -1,7 +1,7 @@import { test as base } from '@playwright/test';import { resolveApiUrl } from '../helpers/api-url';-import { createTestUser, generateTestUsername, TEST_PASSWORD } from '../helpers/test-api';+import { createTestUser, generateTestUsername, TEST_PASSWORD, type TestUser } from '../helpers/test-api';import { WebApp } from './WebApp';@@ -20,7 +20,7 @@ type TestFixtures = {apiUrl: string;app: WebApp;credentials: TestCredentials;- testUser: TestCredentials;+ testUser: TestUser;};/**diff --git a/apps/web/tests/fixtures/index.ts b/apps/web/tests/fixtures/index.tsindex 3c562c2fd..4681e94d5 100644--- a/apps/web/tests/fixtures/index.ts+++ b/apps/web/tests/fixtures/index.ts@@ -2,4 +2,4 @@* Test fixtures: `test`/`expect` with the web app fixtures, and the WebApp page object tests are written in.*/export { test, expect, type TestCredentials } from './fixtures';-export { WebApp } from './WebApp';+export { WebApp, ITEM_VIEW_URL } from './WebApp';diff --git a/apps/web/tests/helpers/test-api.ts b/apps/web/tests/helpers/test-api.tsindex c769a1160..55e252deb 100644--- a/apps/web/tests/helpers/test-api.ts+++ b/apps/web/tests/helpers/test-api.ts@@ -3,6 +3,7 @@*/import { WebApiService } from '@aliasvault/client/api/WebApiService';+import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';import './client-platform';@@ -20,10 +21,20 @@ export function generateTestUsername(): string {return `test_${randomPart}@example.tld`;}+/**+ * An account registered via the API, with the session and key a test needs to reach its vault directly.+ */+export type TestUser = {+ username: string;+ password: string;+ token: string;+ vaultEncryptionKey: string;+};+/*** Register an account via the API, skipping the setup wizard. The first login writes its empty vault.*/-export async function createTestUser(apiUrl: string): Promise<{ username: string; password: string }> {+export async function createTestUser(apiUrl: string): Promise<TestUser> {const username = generateTestUsername();const baseUrl = WebApiService.versionedBaseUrl(apiUrl);const api = {@@ -32,7 +43,29 @@ export async function createTestUser(apiUrl: string): Promise<{ username: string*/rawFetch: (endpoint: string, options?: RequestInit): Promise<Response> => fetch(`${baseUrl}${endpoint}`, options),};- await new SrpLoginService(api).register(username, TEST_PASSWORD);+ const { token, keys } = await new SrpLoginService(api).register(username, TEST_PASSWORD);+ return { username, password: TEST_PASSWORD, token: token.token, vaultEncryptionKey: keys.vaultEncryptionKey };+}++/**+ * Register an account whose server key chain is damaged: the password opens the account key, but the vault+ * encryption key stored under it does not decrypt.+ */+export async function createTestUserWithDamagedKeyChain(apiUrl: string): Promise<{ username: string; password: string }> {+ const username = generateTestUsername();+ const prepared = await SrpAuthService.prepareRegistration(username, TEST_PASSWORD);+ const encryptedVek = Buffer.from(prepared.request.encryptedVek, 'base64');+ encryptedVek[encryptedVek.length - 1] ^= 0xff;+ const request = { ...prepared.request, encryptedVek: encryptedVek.toString('base64') };++ const response = await fetch(`${WebApiService.versionedBaseUrl(apiUrl)}Auth/register`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(request),+ });+ if (!response.ok) {+ throw new Error(`Register failed with status ${response.status}: ${await response.text()}`);+ }return { username, password: TEST_PASSWORD };}diff --git a/apps/web/tests/helpers/vault-tamper.ts b/apps/web/tests/helpers/vault-tamper.tsnew file mode 100644index 000000000..01a3d2744--- /dev/null+++ b/apps/web/tests/helpers/vault-tamper.ts@@ -0,0 +1,91 @@+/**+ * Breaks a test account's server vault on purpose, through the same API a client writes with, so tests can check+ * how the app reports a vault it cannot open.+ */++import { createHash, randomBytes } from 'node:crypto';++import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';+import { EncryptionUtility } from '@aliasvault/client/crypto/EncryptionUtility';+import { getSyncableTableNames, vaultCodecCanonicalizeFromSqlite, vaultCodecGenerateManifestSalt, vaultCodecPackPayload } from '@aliasvault/client/rust/RustCore';++import './client-platform';++import type { TestUser } from './test-api';++/**+ * The part of GET /v2/Vault these helpers read.+ */+type VaultSnapshot = {+ personalManifestId?: string | null;+ manifests?: Array<{ manifestId: string; revision: number }>;+};++/**+ * Replace the personal manifest with bytes that do not decrypt with the account's vault key.+ */+export async function writeUndecryptableManifest(apiUrl: string, user: TestUser): Promise<void> {+ await writePersonalManifest(apiUrl, user, randomBytes(256).toString('base64'));+}++/**+ * Replace the personal manifest with a well-formed one that decrypts, holding a row the client cannot load.+ */+export async function writeManifestWithBrokenRow(apiUrl: string, user: TestUser, table: string, row: Record<string, unknown>): Promise<void> {+ const { manifestId } = await getPersonalManifest(apiUrl, user);+ const canonicalized = await vaultCodecCanonicalizeFromSqlite({+ tables: (await getSyncableTableNames()).map((name) => ({ name, records: [] })),+ canonicalizedAt: new Date().toISOString(),+ manifests: [{ manifestId, manifestSalt: await vaultCodecGenerateManifestSalt(), name: null }],+ });+ const manifest = canonicalized.manifests[0].manifest as { tables: Record<string, unknown[]> };+ manifest.tables[table] = [...(manifest.tables[table] ?? []), row];++ const packed = await vaultCodecPackPayload(JSON.stringify(manifest));+ await writePersonalManifest(apiUrl, user, await EncryptionUtility.symmetricEncryptBytes(packed, user.vaultEncryptionKey));+}++/**+ * The account's personal manifest id and current revision.+ */+async function getPersonalManifest(apiUrl: string, user: TestUser): Promise<{ manifestId: string; revision: number }> {+ const response = await fetch(`${apiUrl}/v2/Vault`, { headers: { Authorization: `Bearer ${user.token}` } });+ if (!response.ok) {+ throw new Error(`GET /v2/Vault failed with status ${response.status}: ${await response.text()}`);+ }+ const snapshot = (await response.json()) as VaultSnapshot;+ const current = snapshot.manifests?.find((m) => m.manifestId === snapshot.personalManifestId);+ if (!current) {+ throw new Error('Test account has no personal manifest to overwrite.');+ }+ return current;+}++/**+ * Write the given ciphertext as the next revision of the account's personal manifest.+ */+async function writePersonalManifest(apiUrl: string, user: TestUser, blob: string): Promise<void> {+ const { manifestId, revision } = await getPersonalManifest(apiUrl, user);+ const response = await fetch(`${apiUrl}/v2/Vault`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${user.token}` },+ body: JSON.stringify({+ username: SrpAuthService.normalizeUsername(user.username),+ manifests: [{+ manifestId,+ manifestBlob: blob,+ manifestCiphertextHash: createHash('sha256').update(Buffer.from(blob, 'base64')).digest('hex'),+ currentRevision: revision,+ credentialsCount: 0,+ blobReferences: [],+ }],+ buckets: [],+ newBlobs: [],+ emailRouting: null,+ }),+ });+ const result = response.ok ? (await response.json()) as { status: number } : null;+ if (!result || result.status !== 0) {+ throw new Error(`POST /v2/Vault did not accept the manifest (HTTP ${response.status}, status ${result?.status}).`);+ }+}diff --git a/core/client/src/api/errors/AppErrorCodes.ts b/core/client/src/api/errors/AppErrorCodes.tsindex afc2d33fe..b07456de9 100644--- a/core/client/src/api/errors/AppErrorCodes.ts+++ b/core/client/src/api/errors/AppErrorCodes.ts@@ -128,70 +128,82 @@ export function formatErrorWithCode(message: string, code: AppErrorCode): stringexport function getErrorTranslationKey(code: AppErrorCode): string {const codeToKeyMap: Record<AppErrorCode, string> = {// Generic errors (E-0xx)- [AppErrorCode.UNKNOWN_ERROR]: 'common.errors.unknownErrorTryAgain',+ [AppErrorCode.UNKNOWN_ERROR]: 'common.errors.unexpectedErrorContactSupport',[AppErrorCode.BACKGROUND_UNRESPONSIVE]: 'common.errors.backgroundUnresponsive',// Auth status check errors (E-1xx)- [AppErrorCode.AUTH_STATUS_CHECK_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.AUTH_STATUS_MIGRATION_CHECK_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.AUTH_VERSION_CHECK_FAILED]: 'common.errors.unknownErrorTryAgain',+ [AppErrorCode.AUTH_STATUS_CHECK_FAILED]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.AUTH_STATUS_MIGRATION_CHECK_FAILED]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.AUTH_VERSION_CHECK_FAILED]: 'common.errors.unexpectedErrorContactSupport',// Vault retrieval errors (E-2xx)[AppErrorCode.VAULT_NOT_FOUND]: 'common.errors.vaultNotAvailable',[AppErrorCode.VAULT_LOCKED]: 'common.errors.vaultIsLocked',- [AppErrorCode.VAULT_DECRYPT_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.VAULT_METADATA_READ_FAILED]: 'common.errors.unknownErrorTryAgain',+ [AppErrorCode.VAULT_DECRYPT_FAILED]: 'common.errors.vaultDataUnreadable',+ [AppErrorCode.VAULT_METADATA_READ_FAILED]: 'common.errors.unexpectedErrorContactSupport',[AppErrorCode.VAULT_LOAD_TIMEOUT]: 'common.errors.vaultLoadTimeout',[AppErrorCode.UNLOCK_KEY_REJECTED]: 'common.errors.wrongPassword',- [AppErrorCode.KEY_CHAIN_UNREADABLE]: 'common.errors.unknownErrorTryAgain',+ [AppErrorCode.KEY_CHAIN_UNREADABLE]: 'common.errors.keyChainUnreadable',[AppErrorCode.KEY_OUT_OF_SYNC]: 'common.errors.sessionExpired',// Item/credential operations (E-3xx)- [AppErrorCode.ITEM_CREATE_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.ITEM_UPDATE_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.ITEM_DELETE_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.ITEM_READ_FAILED]: 'common.errors.unknownErrorTryAgain',+ [AppErrorCode.ITEM_CREATE_FAILED]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.ITEM_UPDATE_FAILED]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.ITEM_DELETE_FAILED]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.ITEM_READ_FAILED]: 'common.errors.unexpectedErrorContactSupport',// Passkey operations (E-4xx)- [AppErrorCode.PASSKEY_CREATE_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.PASSKEY_GET_FAILED]: 'common.errors.unknownErrorTryAgain',+ [AppErrorCode.PASSKEY_CREATE_FAILED]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.PASSKEY_GET_FAILED]: 'common.errors.unexpectedErrorContactSupport',// Sync operations (E-5xx)- [AppErrorCode.SYNC_STATUS_CHECK_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.SYNC_VAULT_FETCH_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.SYNC_VAULT_DECRYPT_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.SYNC_STORE_FAILED]: 'common.errors.unknownErrorTryAgain',+ [AppErrorCode.SYNC_STATUS_CHECK_FAILED]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.SYNC_VAULT_FETCH_FAILED]: 'common.errors.vaultDataUnreadable',+ [AppErrorCode.SYNC_VAULT_DECRYPT_FAILED]: 'common.errors.vaultDataUnreadable',+ [AppErrorCode.SYNC_STORE_FAILED]: 'common.errors.unexpectedErrorContactSupport',[AppErrorCode.SYNC_SERVER_UNREACHABLE]: 'common.errors.serverNotAvailable',- [AppErrorCode.SYNC_SERVER_ERROR]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.SYNC_RESPONSE_INVALID]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.SYNC_CODEC_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.SYNC_ENGINE_FAILED]: 'common.errors.unknownErrorTryAgain',+ [AppErrorCode.SYNC_SERVER_ERROR]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.SYNC_RESPONSE_INVALID]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.SYNC_CODEC_FAILED]: 'common.errors.vaultDataUnreadable',+ [AppErrorCode.SYNC_ENGINE_FAILED]: 'common.errors.unexpectedErrorContactSupport',// Storage read/write errors (E-6xx)- [AppErrorCode.STORAGE_READ_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.STORAGE_WRITE_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.DATABASE_INIT_FAILED]: 'common.errors.unknownErrorTryAgain',+ [AppErrorCode.STORAGE_READ_FAILED]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.STORAGE_WRITE_FAILED]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.DATABASE_INIT_FAILED]: 'common.errors.unexpectedErrorContactSupport',[AppErrorCode.ENCRYPTION_KEY_NOT_FOUND]: 'common.errors.vaultIsLocked',// Merge operations (E-7xx)[AppErrorCode.MERGE_FAILED]: 'common.errors.mergeFailed',[AppErrorCode.MERGE_CONFLICT]: 'common.errors.syncConflictMaxRetries',- [AppErrorCode.MERGE_UPLOAD_FAILED]: 'common.errors.unknownErrorTryAgain',+ [AppErrorCode.MERGE_UPLOAD_FAILED]: 'common.errors.unexpectedErrorContactSupport',// Upload operations (E-8xx)- [AppErrorCode.UPLOAD_FAILED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.UPLOAD_OUTDATED]: 'common.errors.unknownErrorTryAgain',- [AppErrorCode.UPLOAD_ENCRYPT_FAILED]: 'common.errors.unknownErrorTryAgain',+ [AppErrorCode.UPLOAD_FAILED]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.UPLOAD_OUTDATED]: 'common.errors.unexpectedErrorContactSupport',+ [AppErrorCode.UPLOAD_ENCRYPT_FAILED]: 'common.errors.unexpectedErrorContactSupport',[AppErrorCode.UPLOAD_TOO_LARGE]: 'common.errors.vaultTooLarge',[AppErrorCode.UPLOAD_TIMEOUT]: 'common.errors.vaultSyncTimeout',// Migration/version errors (E-9xx)- [AppErrorCode.MIGRATION_CHECK_FAILED]: 'common.errors.unknownErrorTryAgain',+ [AppErrorCode.MIGRATION_CHECK_FAILED]: 'common.errors.unexpectedErrorContactSupport',[AppErrorCode.VERSION_INCOMPATIBLE]: 'common.errors.browserExtensionOutdated',[AppErrorCode.SERVER_UPDATE_REQUIRED]: 'common.errors.serverVersionNotSupported',};- return codeToKeyMap[code] || 'common.errors.unknownErrorTryAgain';+ return codeToKeyMap[code] || 'common.errors.unexpectedErrorContactSupport';+}++/**+ * The translated message for an error that carries a code, with the code appended, or null when it carries none.+ *+ * @param err - The error (can be Error, string, or unknown)+ * @param t - The renderer's translation function+ */+export function translateCodedError(err: unknown, t: (key: string) => string): string | null {+ const message = err instanceof Error ? err.message : typeof err === 'string' ? err : null;+ const code = message ? extractErrorCode(message) : null;+ return code ? formatErrorWithCode(t(getErrorTranslationKey(code)), code) : null;}/**diff --git a/core/rust/src/vault_sync/db.rs b/core/rust/src/vault_sync/db.rsindex 6f5d7470a..ebdef0bd2 100644--- a/core/rust/src/vault_sync/db.rs+++ b/core/rust/src/vault_sync/db.rs@@ -190,20 +190,28 @@ pub(crate) async fn insert_materialized(host: &Host, materialized: &Materializedlet placeholders = vec!["?"; columns.len()].join(", ");batch.push(SqlStatement { sql: format!("INSERT INTO \"{}\" ({}) VALUES ({})", table.name, quoted.join(", "), placeholders), params });if batch.len() >= INSERT_BATCH_ROWS {- exec(host, Db::Staging, std::mem::take(&mut batch)).await?;+ exec(host, Db::Staging, std::mem::take(&mut batch)).await.map_err(|e| rows_rejected(&table.name, e))?;}}- exec(host, Db::Staging, batch).await?;+ exec(host, Db::Staging, batch).await.map_err(|e| rows_rejected(&table.name, e))?;}let violations = query(host, Db::Staging, "PRAGMA foreign_key_check", vec![]).await?;if !violations.is_empty() {let sample: Vec<String> = violations.iter().take(5).map(|v| format!("{} row {} > missing parent in {}", cell_string(v, "table"), cell_string(v, "rowid"), cell_string(v, "parent"))).collect();- return Err(SyncError::Other(format!("VaultCodec: materialized database fails foreign key check ({} violations): {}", violations.len(), sample.join("; "))));+ return Err(SyncError::VaultDataRejected(format!("foreign key check fails ({} violations): {}", violations.len(), sample.join("; "))));}Ok(())}+/// A failed insert into the fresh staging database is a row the schema refuses (the vault data), not a storage failure.+fn rows_rejected(table: &str, error: SyncError) -> SyncError {+ match error {+ SyncError::Host { message, .. } => SyncError::VaultDataRejected(format!("table {}: {}", table, message)),+ other => other,+ }+}+/// A materialized cell as a bind parameter: blob markers become bytes (NULL while the bytes are not loaded; the row's/// hash column says which blob it is),/// inline `{ __b64 }` payloads bind as bytes, everything else binds as is.diff --git a/core/rust/src/vault_sync/errors.rs b/core/rust/src/vault_sync/errors.rsindex 8169228f5..86d10c165 100644--- a/core/rust/src/vault_sync/errors.rs+++ b/core/rust/src/vault_sync/errors.rs@@ -142,6 +142,9 @@ pub enum SyncError {/// The server's snapshot is inconsistent and cannot be assembled.#[error("Server snapshot cannot be assembled: {0}")]Snapshot(String),+ /// The vault data decrypted and decoded, but its rows do not load into the database.+ #[error("Vault data does not load into the database: {0}")]+ VaultDataRejected(String),/// The server kept refusing the write as outdated after the re-sync limit.#[error("The server keeps refusing the write as outdated")]ResyncLimitReached,@@ -187,6 +190,7 @@ impl SyncError {SyncError::KeyOutOfSync => Failure::Coded(ErrorCode::KeyOutOfSync),SyncError::ServerVaultUnreadable(_) => Failure::Coded(ErrorCode::SyncVaultDecryptFailed),SyncError::Snapshot(_) => Failure::Coded(ErrorCode::SyncVaultFetchFailed),+ SyncError::VaultDataRejected(_) => Failure::Coded(ErrorCode::SyncCodecFailed),SyncError::ResyncLimitReached => Failure::Coded(ErrorCode::MergeConflict),SyncError::UploadRejected(_) | SyncError::MissingBlobs(_) => Failure::Coded(ErrorCode::UploadFailed),SyncError::LegacyUpgradePending => Failure::Coded(ErrorCode::MigrationCheckFailed),@@ -234,6 +238,7 @@ mod tests {fn engine_internal_failures_carry_their_own_codes() {assert_eq!(SyncError::Other("no rule".to_string()).failure(), Failure::Coded(ErrorCode::SyncEngineFailed));assert_eq!(SyncError::Core(VaultError::General("codec".to_string())).failure(), Failure::Coded(ErrorCode::SyncCodecFailed));+ assert_eq!(SyncError::VaultDataRejected("NOT NULL".to_string()).failure(), Failure::Coded(ErrorCode::SyncCodecFailed));assert_eq!(serde_json::from_str::<serde_json::Value>("nope").map_err(SyncError::Json).unwrap_err().failure(), Failure::Coded(ErrorCode::SyncResponseInvalid));assert_eq!(serde_json::to_string(&ErrorCode::SyncEngineFailed).unwrap(), "\"E-509\"");}