Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor core/client and Rust error handling to use uniform app error codes and translations (#2437)
Leendert de Borst43ff20c1d434
diff --git a/core/client/src/api/LogoutEventEmitter.ts b/core/client/src/api/LogoutEventEmitter.tsindex 656b61f56..eb1f1f02d 100644--- a/core/client/src/api/LogoutEventEmitter.ts+++ b/core/client/src/api/LogoutEventEmitter.ts@@ -1,6 +1,8 @@import { logDefect } from '../utilities/Diagnostics';-type LogoutListener = (errorMessage: string) => void | Promise<void>;+import type { TranslationKey } from '@aliasvault/i18n';++type LogoutListener = (messageKey: TranslationKey) => void | Promise<void>;/*** Simple event emitter for logout events to avoid circular dependencies@@ -23,12 +25,12 @@ class LogoutEventEmitter {/*** Emit a logout event to all listeners.*- * @param errorKey - The translation key of the error message to emit.+ * @param messageKey - The translation key of the message to show on the login page.*/- public emit(errorTranslationKey: string): void {+ public emit(messageKey: TranslationKey): void {this.listeners.forEach(listener => {try {- listener(errorTranslationKey);+ listener(messageKey);} catch (error) {logDefect('[Logout] A logout listener threw', error);}diff --git a/core/client/src/api/errors/ApiErrorMessage.ts b/core/client/src/api/errors/ApiErrorMessage.tsnew file mode 100644index 000000000..69f8c2152--- /dev/null+++ b/core/client/src/api/errors/ApiErrorMessage.ts@@ -0,0 +1,24 @@+import { englishTranslations, getTranslation, type TranslationKey } from '@aliasvault/i18n';++import { apiErrorCodeOf } from './ApiRequestError';++/**+ * The translation key of the API error code a failed request carries, or null when it carries none this client has words for.+ * @param error - the thrown error+ */+export function apiErrorKey(error: unknown): TranslationKey | null {+ const code = apiErrorCodeOf(error);+ const key = code ? `apiErrors.${code}` : null;+ return key && getTranslation(englishTranslations, key) !== undefined ? key as TranslationKey : null;+}++/**+ * 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 renderer's translation function+ * @param fallback - the message when no known code is present+ */+export function apiErrorMessage(error: unknown, t: (key: string) => string, fallback: string): string {+ const key = apiErrorKey(error);+ return key ? t(key) : fallback;+}diff --git a/core/client/src/api/errors/AppErrorCodes.ts b/core/client/src/api/errors/AppErrorCodes.tsindex 0ecd57fb6..3a5a8ffde 100644--- a/core/client/src/api/errors/AppErrorCodes.ts+++ b/core/client/src/api/errors/AppErrorCodes.ts@@ -1,20 +1,19 @@+import type { TranslationKey } from '@aliasvault/i18n';+/**- * Application error codes for the browser extension.+ * The error codes of all AliasVault clients: web app, browser extension and mobile app and the Rust sync engine.** These codes serve two purposes:* 1. Enable multi-language support by mapping codes to translation keys- * 2. Provide debugging information when users report "unknown errors"- *- * When displayed to users, show: "Error occurred (Code: E-XXX)"- * This allows users to report the code for debugging while keeping messages translatable.+ * 2. Provide debugging information for additional context when a user reports an error** Code ranges:* - E-0xx: Generic errors- * - E-1xx: Auth status check errors- * - E-2xx: Vault retrieval errors (handleGetVault)+ * - E-1xx: Authentication errors+ * - E-2xx: Vault retrieval and unlock errors* - E-3xx: Item/credential operations* - E-4xx: Passkey operations- * - E-5xx: Sync operations (handleFullVaultSync)+ * - E-5xx: Sync operations* - E-6xx: Storage read/write errors* - E-7xx: Merge operations* - E-8xx: Upload operations@@ -24,22 +23,36 @@ export enum AppErrorCode {// Generic errors (E-0xx)UNKNOWN_ERROR = 'E-001',BACKGROUND_UNRESPONSIVE = 'E-002', // Background service worker did not answer in time+ NETWORK_ERROR = 'E-003', // The request did not reach the server (offline, DNS, TLS)+ PARSE_ERROR = 'E-004', // Native glue could not encode or decode a JSON payload- // Auth status check errors (E-1xx) - handleCheckAuthStatus+ // Authentication errors (E-1xx)AUTH_STATUS_CHECK_FAILED = 'E-101',AUTH_STATUS_MIGRATION_CHECK_FAILED = 'E-102',AUTH_VERSION_CHECK_FAILED = 'E-103',+ AUTHENTICATION_FAILED = 'E-104', // The server refused the session tokens+ SESSION_EXPIRED = 'E-105', // The session expired; log in again+ PASSWORD_CHANGED = 'E-106', // The password was changed on another device- // Vault retrieval errors (E-2xx) - handleGetVault+ // Vault retrieval and unlock errors (E-2xx)VAULT_NOT_FOUND = 'E-201', // No encrypted vault in storageVAULT_LOCKED = 'E-202', // No encryption key availableVAULT_DECRYPT_FAILED = 'E-203', // The locally stored vault does not decrypt with the session keyVAULT_METADATA_READ_FAILED = 'E-204', // Failed to read vault metadata- UNLOCK_KEY_REJECTED = 'E-206', // The unlock key does not open the account key (wrong password)+ VAULT_UNLOCK_FAILED = 'E-205', // The vault could not be unlocked for a reason without its own code+ UNLOCK_KEY_REJECTED = 'E-206', // The unlock key does not open the account key (wrong password or PIN)KEY_CHAIN_UNREADABLE = 'E-207', // The account key opened, the vault encryption key under it did notKEY_OUT_OF_SYNC = 'E-208', // The session key does not open the key chain the server holds (re-login needed)-- // Item/credential operations (E-3xx) - handleCreateItem, handleUpdateItem, etc.+ BIOMETRIC_CANCELLED = 'E-209', // The user cancelled biometric authentication+ BIOMETRIC_FAILED = 'E-210',+ KEYSTORE_KEY_NOT_FOUND = 'E-211', // The device keystore holds no key for this vault+ KEYCHAIN_ACCESS_DENIED = 'E-212', // iOS: keychain access denied (entitlement or access group issue)+ KEYCHAIN_ITEM_NOT_FOUND = 'E-213', // Keychain or keystore item not found (may need re-login)+ BIOMETRIC_NOT_AVAILABLE = 'E-214',+ BIOMETRIC_NOT_ENROLLED = 'E-215',+ BIOMETRIC_LOCKOUT = 'E-216', // Too many failed biometric attempts++ // Item/credential operations (E-3xx)ITEM_CREATE_FAILED = 'E-301',ITEM_UPDATE_FAILED = 'E-302',ITEM_DELETE_FAILED = 'E-303',@@ -49,10 +62,10 @@ export enum AppErrorCode {PASSKEY_CREATE_FAILED = 'E-401',PASSKEY_GET_FAILED = 'E-402',- // Sync operations (E-5xx) - handleFullVaultSync+ // Sync operations (E-5xx)SYNC_STATUS_CHECK_FAILED = 'E-501', // Failed to get server status- SYNC_VAULT_FETCH_FAILED = 'E-502', // Failed to fetch vault from server- SYNC_VAULT_DECRYPT_FAILED = 'E-503', // Failed to decrypt server vault+ SYNC_VAULT_FETCH_FAILED = 'E-502', // The server's vault snapshot cannot be assembled into a vault+ SYNC_VAULT_DECRYPT_FAILED = 'E-503', // A server manifest or bucket fails its hash check or does not decryptSYNC_STORE_FAILED = 'E-504', // Failed to store synced vault locallySYNC_SERVER_UNREACHABLE = 'E-505', // Server unreachable and no local vault to fall back onSYNC_SERVER_ERROR = 'E-506', // The server answered a sync request with an unexpected HTTP failure@@ -65,10 +78,17 @@ export enum AppErrorCode {STORAGE_WRITE_FAILED = 'E-602',DATABASE_INIT_FAILED = 'E-603',ENCRYPTION_KEY_NOT_FOUND = 'E-604',+ MANIFEST_NOT_RECORDED = 'E-605', // A write was attempted before a personal manifest id was recorded+ BASE64_DECODE_FAILED = 'E-606', // Base64 decode failed after decryption+ DATABASE_TEMP_WRITE_FAILED = 'E-607',+ DATABASE_OPEN_FAILED = 'E-608',+ DATABASE_MEMORY_FAILED = 'E-609',+ DATABASE_BACKUP_FAILED = 'E-610',+ DATABASE_PRAGMA_FAILED = 'E-611',// Merge operations (E-7xx)MERGE_FAILED = 'E-701',- MERGE_CONFLICT = 'E-702',+ MERGE_CONFLICT = 'E-702', // The server kept refusing the write as outdated after the re-sync limitMERGE_UPLOAD_FAILED = 'E-703',// Upload operations (E-8xx)@@ -80,8 +100,12 @@ export enum AppErrorCode {// Migration/version errors (E-9xx)MIGRATION_CHECK_FAILED = 'E-901',- VERSION_INCOMPATIBLE = 'E-902',+ VAULT_VERSION_INCOMPATIBLE = 'E-902', // The vault is newer than this client can readSERVER_UPDATE_REQUIRED = 'E-903',+ CLIENT_VERSION_NOT_SUPPORTED = 'E-904', // The server no longer supports this client version+ SERVER_VERSION_NOT_SUPPORTED = 'E-905', // The server is too old for this client+ VAULT_OUTDATED = 'E-906', // The vault has to be upgraded before this client can use it+ VAULT_MERGE_REQUIRED = 'E-907',}/**@@ -108,6 +132,18 @@ export function extractErrorCode(message: string): AppErrorCode | null {return null;}+/**+ * The error code an error carries: the `code` of a native module rejection, or an E-XXX code in its message.+ * @param err - the error (can be Error, string, or unknown)+ */+export function getAppErrorCode(err: unknown): AppErrorCode | null {+ if (err && typeof err === 'object' && 'code' in err && typeof err.code === 'string' && isErrorCode(err.code)) {+ return err.code;+ }+ const message = err instanceof Error ? err.message : typeof err === 'string' ? err : null;+ return message ? extractErrorCode(message) : null;+}+/*** Format an error message with an error code for user display.* This allows users to report the code for debugging while keeping the message readable.@@ -121,75 +157,50 @@ export function formatErrorWithCode(message: string, code: AppErrorCode): string}/**- * Map error codes to translation keys for localized error messages.- * Returns the translation key that should be used with t() function.+ * The translation key of each code with a message of its own.+ */+const ERROR_TRANSLATION_KEYS: Partial<Record<AppErrorCode, TranslationKey>> = {+ [AppErrorCode.BACKGROUND_UNRESPONSIVE]: 'common.errors.backgroundUnresponsive',+ [AppErrorCode.NETWORK_ERROR]: 'auth.errors.networkError',++ [AppErrorCode.AUTHENTICATION_FAILED]: 'common.errors.sessionExpired',+ [AppErrorCode.SESSION_EXPIRED]: 'common.errors.sessionExpired',+ [AppErrorCode.PASSWORD_CHANGED]: 'common.errors.passwordChanged',++ [AppErrorCode.VAULT_NOT_FOUND]: 'common.errors.vaultNotAvailable',+ [AppErrorCode.VAULT_LOCKED]: 'common.errors.vaultIsLocked',+ [AppErrorCode.VAULT_DECRYPT_FAILED]: 'common.errors.vaultDataUnreadable',+ [AppErrorCode.UNLOCK_KEY_REJECTED]: 'common.errors.wrongPassword',+ [AppErrorCode.KEY_CHAIN_UNREADABLE]: 'common.errors.keyChainUnreadable',+ [AppErrorCode.KEY_OUT_OF_SYNC]: 'common.errors.sessionExpired',++ [AppErrorCode.SYNC_VAULT_FETCH_FAILED]: 'common.errors.vaultDataUnreadable',+ [AppErrorCode.SYNC_VAULT_DECRYPT_FAILED]: 'common.errors.vaultDataUnreadable',+ [AppErrorCode.SYNC_SERVER_UNREACHABLE]: 'common.errors.serverNotAvailable',+ [AppErrorCode.SYNC_CODEC_FAILED]: 'common.errors.vaultDataUnreadable',++ [AppErrorCode.ENCRYPTION_KEY_NOT_FOUND]: 'common.errors.vaultIsLocked',++ [AppErrorCode.MERGE_FAILED]: 'common.errors.mergeFailed',+ [AppErrorCode.MERGE_CONFLICT]: 'common.errors.syncConflictMaxRetries',++ [AppErrorCode.UPLOAD_TOO_LARGE]: 'common.errors.vaultTooLarge',+ [AppErrorCode.UPLOAD_TIMEOUT]: 'common.errors.vaultSyncTimeout',++ [AppErrorCode.VAULT_VERSION_INCOMPATIBLE]: 'common.errors.clientOutdated',+ [AppErrorCode.SERVER_UPDATE_REQUIRED]: 'common.errors.serverOutdated',+ [AppErrorCode.CLIENT_VERSION_NOT_SUPPORTED]: 'common.errors.clientNotSupported',+ [AppErrorCode.SERVER_VERSION_NOT_SUPPORTED]: 'common.errors.serverOutdated',+ [AppErrorCode.VAULT_OUTDATED]: 'content.vaultUpgradeRequired',+};++/**+ * Map an error code to the translation key of its message. Codes without a message of their own share the generic+ * "unexpected error" message; the code shown next to it tells them apart.+ * @param code - the error code*/-export function getErrorTranslationKey(code: AppErrorCode): string {- const codeToKeyMap: Record<AppErrorCode, string> = {- // Generic errors (E-0xx)- [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.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.vaultDataUnreadable',- [AppErrorCode.VAULT_METADATA_READ_FAILED]: 'common.errors.unexpectedErrorContactSupport',- [AppErrorCode.UNLOCK_KEY_REJECTED]: 'common.errors.wrongPassword',- [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.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.unexpectedErrorContactSupport',- [AppErrorCode.PASSKEY_GET_FAILED]: 'common.errors.unexpectedErrorContactSupport',-- // Sync operations (E-5xx)- [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.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.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.unexpectedErrorContactSupport',-- // Upload operations (E-8xx)- [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.unexpectedErrorContactSupport',- [AppErrorCode.VERSION_INCOMPATIBLE]: 'common.errors.browserExtensionOutdated',- [AppErrorCode.SERVER_UPDATE_REQUIRED]: 'common.errors.serverVersionNotSupported',- };-- return codeToKeyMap[code] || 'common.errors.unexpectedErrorContactSupport';+export function getErrorTranslationKey(code: AppErrorCode): TranslationKey {+ return ERROR_TRANSLATION_KEYS[code] ?? 'common.errors.unexpectedErrorContactSupport';}/**@@ -199,8 +210,7 @@ export function getErrorTranslationKey(code: AppErrorCode): string {* @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;+ const code = getAppErrorCode(err);return code ? formatErrorWithCode(t(getErrorTranslationKey(code)), code) : null;}diff --git a/core/client/src/auth/AuthErrorMessage.ts b/core/client/src/auth/AuthErrorMessage.tsnew file mode 100644index 000000000..ecd093b1d--- /dev/null+++ b/core/client/src/auth/AuthErrorMessage.ts@@ -0,0 +1,75 @@+import { apiErrorKey } from '../api/errors/ApiErrorMessage';+import { AppErrorCode, formatErrorWithCode, getAppErrorCode, getErrorTranslationKey } from '../api/errors/AppErrorCodes';+import { ClientUpgradeRequiredError } from '../api/errors/ClientUpgradeRequiredError';+import { ServerUpdateRequiredError } from '../api/errors/ServerUpdateRequiredError';++import { VaultKeyService } from './VaultKeyService';++import type { TranslationKey } from '@aliasvault/i18n';++/**+ * A failure as the UI shows it: the translation key of its message, and the error code to show next to it.+ */+export type ErrorMessage = {+ key: TranslationKey;+ code?: AppErrorCode;+};++/**+ * A failed login or unlock as the UI shows it.+ */+export type AuthErrorMessage = ErrorMessage & {+ /** The entered password (or PIN) was wrong; hosts that count failed attempts count this one. */+ wrongPassword: boolean;+};++/**+ * How {@link describeAuthError} reads the failure.+ */+export type AuthErrorOptions = {+ /** The message for a failure without a code, by default the "could not reach the server" message. */+ fallback?: TranslationKey;+ /** Take a failure without any code as a wrong password (or PIN): a local unlock has no other way to fail uncoded. */+ uncodedIsWrongPassword?: boolean;+};++/**+ * The message for a failed login or unlock, the same on every client.+ * @param err - the thrown error+ * @param options - how to read the failure+ */+export async function describeAuthError(err: unknown, options: AuthErrorOptions = {}): Promise<AuthErrorMessage> {+ if (err instanceof ClientUpgradeRequiredError) {+ return { key: 'common.errors.clientNotSupported', wrongPassword: false };+ }+ if (err instanceof ServerUpdateRequiredError) {+ return { key: 'common.errors.serverOutdated', wrongPassword: false };+ }++ // The server refused the login with a coded reason (wrong password, account locked).+ const apiKey = apiErrorKey(err);+ if (apiKey) {+ return { key: apiKey, wrongPassword: false };+ }++ const code = getAppErrorCode(err);+ if (await VaultKeyService.isWrongUnlockKey(code)) {+ return { key: 'common.errors.wrongPassword', wrongPassword: true };+ }+ if (code) {+ return { key: getErrorTranslationKey(code), code, wrongPassword: false };+ }+ if (options.uncodedIsWrongPassword) {+ return { key: 'common.errors.wrongPassword', wrongPassword: true };+ }+ return { key: options.fallback ?? 'common.errors.serverError', wrongPassword: false };+}++/**+ * The text of an error message, with its code appended when it has one.+ * @param message - the error message+ * @param t - the renderer's translation function+ */+export function formatErrorMessage(message: ErrorMessage, t: (key: string) => string): string {+ return message.code ? formatErrorWithCode(t(message.key), message.code) : t(message.key);+}diff --git a/core/client/src/auth/VaultKeyService.ts b/core/client/src/auth/VaultKeyService.tsindex 767a27ec2..62d91abd0 100644--- a/core/client/src/auth/VaultKeyService.ts+++ b/core/client/src/auth/VaultKeyService.ts@@ -95,7 +95,11 @@ export class VaultKeyService {* one direction (another device migrated since the last login), which the sync resolves by accepting the remote chain.*/public static async hasLocalVaultKey(): Promise<boolean> {- return (await getPlatform().storage.get(StorageKeys.ENCRYPTED_ACCOUNT_KEY) as string | null) !== null;+ const platform = getPlatform();+ if (platform.hasLocalVaultKey) {+ return platform.hasLocalVaultKey();+ }+ return (await platform.storage.get(StorageKeys.ENCRYPTED_ACCOUNT_KEY) as string | null) !== null;}/**diff --git a/core/client/src/database/SqliteClient.ts b/core/client/src/database/SqliteClient.tsindex a60fbe014..6e8f8398f 100644--- a/core/client/src/database/SqliteClient.ts+++ b/core/client/src/database/SqliteClient.ts@@ -4,7 +4,6 @@ import { VaultSqlGenerator, checkVersionCompatibility, extractVersionFromMigratiimport { VaultVersionIncompatibleError } from '../api/errors/VaultVersionIncompatibleError';import { StorageKeys } from '../constants/StorageKeys';import { getPlatform } from '../platform/ClientPlatform';-import { TranslatableMessage } from '../platform/TranslatableMessage';import { bytesToBase64 } from '../utilities/Base64';import { logDefect } from '../utilities/Diagnostics';import { detectImageMimeType } from '../utilities/ImageType';@@ -451,7 +450,7 @@ export class SqliteClient implements ISyncDatabaseClient {const compatibilityResult = checkVersionCompatibility(databaseVersion);if (!compatibilityResult.isCompatible) {- const errorMessage = await getPlatform().translate(TranslatableMessage.ClientOutdated);+ const errorMessage = await getPlatform().translate('common.errors.clientOutdated');throw new VaultVersionIncompatibleError(errorMessage);}diff --git a/core/client/src/platform/ClientPlatform.ts b/core/client/src/platform/ClientPlatform.tsindex b557c07ed..8ea2a292b 100644--- a/core/client/src/platform/ClientPlatform.ts+++ b/core/client/src/platform/ClientPlatform.ts@@ -2,8 +2,8 @@ import type { IAppIdentity } from './AppIdentity';import type { IKeyValueStore } from './KeyValueStore';import type { ILogger } from './Logger';import type { ISqliteEngine } from './SqliteEngine';-import type { TranslatableMessage } from './TranslatableMessage';import type { IRustCore } from '../rust/RustCoreBinding';+import type { TranslationKey } from '@aliasvault/i18n';/*** Everything the client core needs from the host app. Each app (browser extension, web app, mobile app) implements@@ -26,9 +26,14 @@ export interface IClientPlatform {sqlite: ISqliteEngine;/**- * Translate one of the core's own messages into the user's language.+ * Translate a message of the shared translations (core/i18n) into the user's language.*/- translate(message: TranslatableMessage): Promise<string>;+ translate(key: TranslationKey): Promise<string>;++ /**+ * Whether this device holds a key chain, for hosts that keep it outside {@link storage} (the mobile app keeps it in native storage).+ */+ hasLocalVaultKey?(): Promise<boolean>;/*** The device's UI language as a BCP 47 tag. Hosts without `navigator.language` provide it here.diff --git a/core/client/src/platform/InMemoryPlatform.ts b/core/client/src/platform/InMemoryPlatform.tsindex e017d5c07..652a4d463 100644--- a/core/client/src/platform/InMemoryPlatform.ts+++ b/core/client/src/platform/InMemoryPlatform.ts@@ -85,9 +85,9 @@ export function createInMemoryPlatform(overrides: Partial<IClientPlatform> = {})rustCore: unavailableService<IRustCore>('Rust core'),sqlite: unavailableService<ISqliteEngine>('SQLite engine'),/**- * Echo the message id.+ * Echo the translation key.*/- translate: async (message): Promise<string> => message,+ translate: async (key): Promise<string> => key,...overrides,};}diff --git a/core/client/src/platform/TranslatableMessage.ts b/core/client/src/platform/TranslatableMessage.tsdeleted file mode 100644index 27652d0bc..000000000--- a/core/client/src/platform/TranslatableMessage.ts+++ /dev/null@@ -1,12 +0,0 @@-/**- * The few user-facing strings the core produces itself. The host resolves each one through its own translation- * system, so the core carries no translation files and no key naming of any app.- * TODO: refactor this to use centralized translation system instead (on to-do list) once that is implemented.- */-export enum TranslatableMessage {- /** The local vault is newer than what this client understands; the app must be updated. */- ClientOutdated = 'client-outdated',-- /** The vault still has to walk the sqlite-blob upgrade chain before the manifest migration can run. */- VaultUpgradeRequired = 'vault-upgrade-required',-}diff --git a/core/client/src/platform/index.ts b/core/client/src/platform/index.tsindex 523be5627..b64af6390 100644--- a/core/client/src/platform/index.ts+++ b/core/client/src/platform/index.ts@@ -3,6 +3,5 @@ export { getPlatform, setPlatform, tryGetPlatform, type IClientPlatform } from 'export type { IKeyValueStore, StorageKey } from './KeyValueStore';export { devError, devLog, devWarn, type ILogger } from './Logger';export type { ISqliteDatabase, ISqliteEngine, SqliteRow, SqliteValue } from './SqliteEngine';-export { TranslatableMessage } from './TranslatableMessage';export { unavailableService } from './UnavailableService';export type { IRustCore } from '../rust/RustCoreBinding';diff --git a/core/client/src/sync/SyncErrorMessage.ts b/core/client/src/sync/SyncErrorMessage.tsindex 080a08fd8..4146e2b05 100644--- a/core/client/src/sync/SyncErrorMessage.ts+++ b/core/client/src/sync/SyncErrorMessage.ts@@ -1,6 +1,6 @@import { AppErrorCode, formatErrorWithCode, getErrorTranslationKey, isErrorCode } from '../api/errors/AppErrorCodes';-import { hasSyncError, type SyncErrorDetail } from './VaultSync';+import { hasSyncError, logoutReasonKey, type SyncErrorDetail } from './VaultSync';/*** The stored sync error, tolerating the plain string an older build left behind.@@ -23,8 +23,8 @@ export function toSyncErrorDetail(value: unknown): SyncErrorDetail | null {* @param t - the renderer's translation function*/export function syncErrorMessage(detail: SyncErrorDetail, t: (key: string) => string): string | undefined {- if (detail.errorKey) {- return t('common.errors.' + detail.errorKey);+ if (detail.logoutReason) {+ return t(logoutReasonKey(detail.logoutReason));}if (detail.errorCode) {const code = isErrorCode(detail.errorCode) ? detail.errorCode : AppErrorCode.UNKNOWN_ERROR;diff --git a/core/client/src/sync/VaultSync.ts b/core/client/src/sync/VaultSync.tsindex 1909187b6..006a377dc 100644--- a/core/client/src/sync/VaultSync.ts+++ b/core/client/src/sync/VaultSync.ts@@ -4,7 +4,7 @@* commands into host actions.** When updating this logic, make sure to update the same logic on the other platforms:- * - core/client/src/sync/VaultSync.ts (shared core client for web apps)+ * - core/client/src/sync/VaultSync.ts (shared core client for web app and browser extension)* - apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift* - apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt*/@@ -16,19 +16,19 @@ import { VaultKeyService } from '../auth/VaultKeyService';import { StorageKeys } from '../constants/StorageKeys';import { getPlatform } from '../platform/ClientPlatform';import { devError, devLog, devWarn } from '../platform/Logger';-import { TranslatableMessage } from '../platform/TranslatableMessage';import { VaultMigrationKind } from './VaultManifestMigration';import { buildVaultSyncRequest, runVaultSyncEngine } from './VaultSyncEngine';-import type { IVaultSyncEngineHost, VaultSyncEmailRouting, VaultSyncEngineRequest, VaultSyncEngineResult, VaultSyncEngineResultBase, VaultSyncMigrateManifestResult, VaultSyncMigrationStatusResult, VaultSyncOperation, VaultSyncOptions, VaultSyncSharingParams, VaultSyncSharingResult } from './VaultSyncEngine';+import type { IVaultSyncEngineHost, LogoutReason, VaultSyncEmailRouting, VaultSyncEngineRequest, VaultSyncEngineResult, VaultSyncEngineResultBase, VaultSyncMigrateManifestResult, VaultSyncMigrationStatusResult, VaultSyncOperation, VaultSyncOptions, VaultSyncSharingParams, VaultSyncSharingResult } from './VaultSyncEngine';import type { SqliteClient } from '../database/SqliteClient';+import type { TranslationKey } from '@aliasvault/i18n';/*** What a failed sync reports, in the form the UI translates for display.*/export type SyncErrorDetail = {- errorKey?: string;+ logoutReason?: LogoutReason;errorCode?: string;error?: string;};@@ -81,25 +81,33 @@ type PersistableSyncResult = VaultSyncEngineResultBase & {};/** The engine's failure fields. */-type EngineFailure = Pick<VaultSyncEngineResult, 'error' | 'errorCode' | 'errorKey'>;+type EngineFailure = Pick<VaultSyncEngineResult, 'error' | 'errorCode' | 'logoutReason'>;/**- * The `common.errors` key that translates a sync logout reason.+ * The translation key of each logout reason.*/-const LOGOUT_REASON_ERROR_KEYS: Record<string, string> = {- clientVersionNotSupported: 'clientVersionNotSupported',- serverVersionNotSupported: 'serverVersionNotSupported',- sessionExpired: 'sessionExpired',- passwordChanged: 'passwordChanged',- vaultVersionIncompatible: 'browserExtensionOutdated',+const LOGOUT_REASON_KEYS: Record<LogoutReason, TranslationKey> = {+ clientVersionNotSupported: 'common.errors.clientNotSupported',+ serverVersionNotSupported: 'common.errors.serverOutdated',+ vaultVersionIncompatible: 'common.errors.clientOutdated',+ sessionExpired: 'common.errors.sessionExpired',+ passwordChanged: 'common.errors.passwordChanged',};+/**+ * The translation key of a logout reason.+ * @param reason - the logout reason+ */+export function logoutReasonKey(reason: LogoutReason): TranslationKey {+ return LOGOUT_REASON_KEYS[reason] ?? 'common.errors.unknownError';+}+/*** 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;+ return detail.logoutReason !== undefined || detail.errorCode !== undefined || detail.error !== undefined;}/**@@ -225,7 +233,7 @@ export class VaultSync {}if (await (await this.openVault()).requiresLegacySqliteBlobMigration()) {// The sqlite-blob upgrade chain has to bring the vault to 2.0.0 first; the codec cannot canonicalize what came before.- return { success: false, pushed: false, error: await getPlatform().translate(TranslatableMessage.VaultUpgradeRequired) };+ return { success: false, pushed: false, error: await getPlatform().translate('content.vaultUpgradeRequired') };}const result = await this.run<VaultSyncMigrateManifestResult>('migrateManifest');@@ -304,19 +312,19 @@ export class VaultSync {}/**- * The engine's failure as the UI names it: the logout reason as a translation key, or the error code of an ordinary+ * The engine's failure as the UI names it: the logout reason, or the error code of an ordinary* failure. Empty when the result names no failure.* @param result - the engine's outcome*/private static syncError(result: EngineFailure): SyncErrorDetail {- if (!result.error && !result.errorCode && !result.errorKey) {+ if (!result.error && !result.errorCode && !result.logoutReason) {return {};}devWarn(`[VaultSync] Engine failure (${result.errorCode ?? 'no code'}): ${result.error ?? 'no detail'}`);- if (result.errorKey) {- return { errorKey: LOGOUT_REASON_ERROR_KEYS[result.errorKey] ?? 'unknownError' };+ if (result.logoutReason) {+ return { logoutReason: result.logoutReason };}return { errorCode: result.errorCode && isErrorCode(result.errorCode) ? result.errorCode : AppErrorCode.UNKNOWN_ERROR, error: result.error };diff --git a/core/client/src/sync/VaultSyncEngine.ts b/core/client/src/sync/VaultSyncEngine.tsindex 79ddd22c0..bd87639da 100644--- a/core/client/src/sync/VaultSyncEngine.ts+++ b/core/client/src/sync/VaultSyncEngine.ts@@ -57,6 +57,9 @@ export type VaultSyncEmailRouting = {publicEmailDomainList: string[];};+/** Why a sync ended the session (the Rust `LogoutReason`). */+export type LogoutReason = 'clientVersionNotSupported' | 'serverVersionNotSupported' | 'sessionExpired' | 'passwordChanged' | 'vaultVersionIncompatible';+/** What every engine result carries. */export type VaultSyncEngineResultBase = {vaultChanged: boolean;@@ -71,7 +74,7 @@ export type VaultSyncEngineResult = VaultSyncEngineResultBase & {manifestMigrationRequired: boolean;error?: string;errorCode?: string;- errorKey?: string;+ logoutReason?: LogoutReason;requiresLogout: boolean;serverVersion?: string;capabilities?: Record<string, string>;@@ -91,7 +94,7 @@ export type VaultSyncMigrateManifestResult = VaultSyncEngineResultBase & {pushed: boolean;error?: string;errorCode?: string;- errorKey?: string;+ logoutReason?: LogoutReason;requiresLogout: boolean;};@@ -103,7 +106,7 @@ export type VaultSyncSharingResult = VaultSyncEngineResultBase & {vaultUpgradeRequired: boolean;error?: string;errorCode?: string;- errorKey?: string;+ logoutReason?: LogoutReason;requiresLogout: boolean;};diff --git a/core/i18n/hints.json b/core/i18n/hints.jsonindex 448fa245e..74db8ebcf 100644--- a/core/i18n/hints.json+++ b/core/i18n/hints.json@@ -64,10 +64,8 @@"auth.switchAccounts": "Text before logout link","auth.unlockPage.connectionFailedError": "Error message for server connection failure","auth.unlockPage.enterMasterPasswordDescription": "Description for password unlock form",- "auth.unlockPage.incorrectPasswordError": "Error message for incorrect password","auth.unlockPage.loggingInWithWebAuthn": "Message shown while WebAuthn authentication is in progress","auth.unlockPage.quickUnlockDescription": "Description explaining WebAuthn unlock options",- "auth.unlockPage.sessionTimedOutError": "Error message for session timeout","auth.unlockPage.unlockButton": "Button text for unlock submission","auth.unlockPage.unlockWithMobileButton": "Button text for unlocking with mobile app","auth.unlockPage.unlockWithWebAuthn": "Button text for WebAuthn unlock",@@ -77,7 +75,6 @@"common.back": "Button text for going back","common.backspace": "Screen reader label of the delete-last-digit key on the PIN pad","common.cancel": "Button text for canceling an action",- "common.clientVersionUnsupported": "Shown when the server rejects the client version (HTTP 426).","common.clipboardCountdown.clearClipboardButton": "Button text to manually clear clipboard immediately","common.close": "Button text for closing a dialog or modal","common.confirm": "Button text to confirm an action",@@ -92,6 +89,9 @@"common.error": "Error status message","common.errorGeneric": "Generic error message","common.errorPasswordMismatch": "Password confirmation mismatch error",+ "common.errors.clientNotSupported": "The server rejects this app version (web app, browser extension or mobile app). Keep it generic: it is shown in every app.",+ "common.errors.clientOutdated": "The vault was upgraded by a newer AliasVault version than this one. Shown in every app, so keep it generic.",+ "common.errors.serverOutdated": "The AliasVault server is too old for this app version. Shown in every app, so keep it generic.","common.generate": "Button tooltip for generating a random value","common.help": "Screen reader label of a help button","common.hide": "Button text for hiding content",@@ -123,6 +123,7 @@"common.syncingChanges": "Status text when background sync is in progress","common.syncVaultData": "Tooltip text for sync vault data button","common.unavailable": "Shown instead of the size, or in brackets after the name, of a file whose data could not be loaded",+ "common.updateApp": "Button in the web app that reloads the page to load the latest version.","common.username": "Label for username input field","common.vaultSaveError": "Generic error shown when a vault save / sync to the server fails for an unexpected reason","common.verifyingPassword": "Message shown while verifying password",diff --git a/core/i18n/locales/en.json b/core/i18n/locales/en.jsonindex ebeadddd4..24f6c921f 100644--- a/core/i18n/locales/en.json+++ b/core/i18n/locales/en.json@@ -95,8 +95,7 @@"httpError": "HTTP error: {{status}}","networkError": "Network request failed. Please check your internet connection and try again.","networkErrorSelfHosted": "Network request failed. Check your network connection and server availability. For self-hosted instances, please ensure you have a valid SSL certificate installed. Self-signed certificates are not supported on mobile devices for security reasons.",- "serverErrorSelfHosted": "Could not reach the API. For self-hosted instances, please verify the API endpoint is reachable by navigating to it in a browser: it should display 'OK'.",- "sessionExpired": "Your session has expired. Please login again."+ "serverErrorSelfHosted": "Could not reach the API. For self-hosted instances, please verify the API endpoint is reachable by navigating to it in a browser: it should display 'OK'."},"forgotPassword": {"contactAdministrator": "If you've recently changed your password and are experiencing difficulties signing in with your new password, please note that the server administrator may be able to recover an earlier backup of your vault to assist you. If this is the case, please contact the server administrator.",@@ -192,10 +191,8 @@"unlockPage": {"connectionFailedError": "Connection with the AliasVault servers failed. Please try again (later).","enterMasterPasswordDescription": "Enter your master password to unlock your vault.",- "incorrectPasswordError": "The password is incorrect. Please try entering your password again, or log out and log in again.","loggingInWithWebAuthn": "Logging in with passkey...","quickUnlockDescription": "Quickly unlock your vault using your passkey. Or login with your password as a fallback.",- "sessionTimedOutError": "Your session has timed out. Please log in again.","unlockButton": "Unlock","unlockWithMobileButton": "Unlock with Mobile App","unlockWithWebAuthn": "Unlock with passkey",@@ -225,7 +222,6 @@"back": "Back","backspace": "Backspace","cancel": "Cancel",- "clientVersionUnsupported": "This version of the app is no longer supported by the server. Please refresh the page to load the latest version.","clipboardCountdown": {"clearClipboardButton": "Clear Clipboard"},@@ -259,8 +255,8 @@"errorPasswordMismatch": "Passwords do not match.","errors": {"backgroundUnresponsive": "The extension background service is not responding. Please close and reopen the extension, or restart your browser if the problem persists.",- "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.",+ "clientNotSupported": "This version of AliasVault is no longer supported by the server. Please update to the latest version.",+ "clientOutdated": "This version of AliasVault cannot open your vault because it was upgraded by a newer version. Please update AliasVault to continue.","contactSupportAt": "Contact support at {{email}}.","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.",@@ -270,8 +266,7 @@"passwordChanged": "Your password has changed since the last time you logged in. Please login again for security reasons.","serverError": "Could not reach AliasVault server. Please try again later or contact support if the problem persists.","serverNotAvailable": "The AliasVault server is not available. Please try again later or contact support if the problem persists.",- "serverVersionNotSupported": "The AliasVault server needs to be updated to a newer version in order to use this browser extension. Please contact support if you need help.",- "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.",+ "serverOutdated": "The AliasVault server needs to be updated to work with this version of AliasVault. Please contact support 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.",@@ -342,6 +337,7 @@"twoFactorAuthentication": "Two-factor authentication","unavailable": "Unavailable","undo": "Undo",+ "updateApp": "Update app","use": "Use","username": "Username","vaultSaveError": "Failed to save changes to the vault. Please try again.",@@ -1634,13 +1630,9 @@"checkingForVaultUpdates": "Checking for vault updates","checkingVaultUpdates": "Checking vault updates","errors": {- "appOutdated": "This app is outdated and cannot be used to access this (newer) vault version. Please update the AliasVault app to continue.","failedToGetEncryptedDatabase": "Failed to get encrypted database","passwordChangeRequiresOnline": "Password change requires an internet connection. Please try again when online.",- "serverVersionNotSupported": "The AliasVault server needs to be updated to a newer version in order to use this mobile app. Please contact support if you need help.",- "usernameNotFound": "Username not found",- "vaultOutdated": "Your vault is outdated. Please login on the AliasVault website and follow the steps.",- "versionNotSupported": "This version of the AliasVault mobile app is not supported by the server anymore. Please update your app to the latest version."+ "usernameNotFound": "Username not found"},"mergingVault": "Merging vault changes...","savingChangesToVault": "Saving changes to vault",diff --git a/core/i18n/src/index.ts b/core/i18n/src/index.tsindex 97388ccb6..61058b9f1 100644--- a/core/i18n/src/index.ts+++ b/core/i18n/src/index.ts@@ -14,6 +14,16 @@ export * from './languages';*/export type TranslationTree = { [key: string]: string | TranslationTree };+/**+ * The dotted paths to the leaves of a translation tree.+ */+type LeafKeys<T> = { [K in keyof T & string]: T[K] extends string ? K : `${K}.${LeafKeys<T[K]>}` }[keyof T & string];++/**+ * A key of the English translations, e.g. 'common.errors.unknownError'.+ */+export type TranslationKey = LeafKeys<typeof en>;+/*** The English translations, bundled so there always is a fallback.*/diff --git a/core/rust/src/vault_sync/engine.rs b/core/rust/src/vault_sync/engine.rsindex 039f0ccac..cd159592e 100644--- a/core/rust/src/vault_sync/engine.rs+++ b/core/rust/src/vault_sync/engine.rs@@ -707,11 +707,11 @@ mod tests {fn failures_carry_a_code_or_a_logout_reason_never_both() {let coded = failure(&SyncError::Timeout("slow".to_string())).failure;assert_eq!(coded.error_code, Some(ErrorCode::UploadTimeout));- assert_eq!(coded.error_key, None);+ assert_eq!(coded.logout_reason, None);assert!(!coded.requires_logout);let logout = failure(&SyncError::VaultVersionIncompatible("3.0.0".to_string())).failure;- assert_eq!(logout.error_key, Some(LogoutReason::VaultVersionIncompatible));+ assert_eq!(logout.logout_reason, Some(LogoutReason::VaultVersionIncompatible));assert_eq!(logout.error_code, None);assert!(logout.requires_logout);}diff --git a/core/rust/src/vault_sync/tests/mod.rs b/core/rust/src/vault_sync/tests/mod.rsindex 46afee9a4..55bdb5980 100644--- a/core/rust/src/vault_sync/tests/mod.rs+++ b/core/rust/src/vault_sync/tests/mod.rs@@ -234,7 +234,7 @@ fn unknown_storage_format_is_refused_not_read_as_legacy() {let result = host.drive(&SyncSession::new(&request("fullSync", &vek, false, 0)).unwrap());assert_eq!(result["success"], false, "{}", result);- assert_eq!(result["errorKey"], "vaultVersionIncompatible", "an app too old for the format is told to update");+ assert_eq!(result["logoutReason"], "vaultVersionIncompatible", "an app too old for the format is told to update");assert!(item_names(&host.local).is_empty(), "nothing is materialized");assert!(host.requests_to("Vault").iter().all(|r| r.method == "GET"), "no legacy migration push");}@@ -522,7 +522,7 @@ fn expired_session_requires_logout() {assert_eq!(result["success"], false);assert_eq!(result["requiresLogout"], true);- assert_eq!(result["errorKey"], "sessionExpired");+ assert_eq!(result["logoutReason"], "sessionExpired");}#[test]@@ -535,7 +535,7 @@ fn password_changed_elsewhere_requires_logout() {let result = host.drive(&SyncSession::new(&request("fullSync", &vek, false, 0)).unwrap());assert_eq!(result["requiresLogout"], true);- assert_eq!(result["errorKey"], "passwordChanged");+ assert_eq!(result["logoutReason"], "passwordChanged");}#[test]diff --git a/core/rust/src/vault_sync/types.rs b/core/rust/src/vault_sync/types.rsindex 773fa278f..7d5756ece 100644--- a/core/rust/src/vault_sync/types.rs+++ b/core/rust/src/vault_sync/types.rs@@ -98,14 +98,14 @@ pub struct FailureFields {#[serde(skip_serializing_if = "Option::is_none")]pub error_code: Option<ErrorCode>,#[serde(skip_serializing_if = "Option::is_none")]- pub error_key: Option<LogoutReason>,+ pub logout_reason: Option<LogoutReason>,pub requires_logout: bool,}impl FailureFields {/// A forced logout for the given reason.pub fn logout(reason: LogoutReason) -> Self {- Self { error_key: Some(reason), requires_logout: true, ..Default::default() }+ Self { logout_reason: Some(reason), requires_logout: true, ..Default::default() }}}@@ -795,12 +795,12 @@ mod tests {let logout = FailureFields::logout(LogoutReason::SessionExpired);let migrate = serde_json::to_string(&MigrateManifestResult { failure: logout.clone(), ..Default::default() }).unwrap();- assert_eq!(migrate, r#"{"success":false,"pushed":false,"errorKey":"sessionExpired","requiresLogout":true,"vaultChanged":false}"#);+ assert_eq!(migrate, r#"{"success":false,"pushed":false,"logoutReason":"sessionExpired","requiresLogout":true,"vaultChanged":false}"#);let round_trip: MigrateManifestResult = serde_json::from_str(&migrate).unwrap();assert_eq!(round_trip.failure, logout);let status = serde_json::to_value(StatusCheckResult { failure: logout.clone(), ..Default::default() }).unwrap();- assert_eq!(status["errorKey"], "sessionExpired");+ assert_eq!(status["logoutReason"], "sessionExpired");assert_eq!(status["requiresLogout"], true);assert!(status.get("error").is_none() && status.get("errorCode").is_none() && status.get("failure").is_none());let round_trip: StatusCheckResult = serde_json::from_value(status.clone()).unwrap();