Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Merge manifest migrate with existing upgrade page in browser extension (#2159)
Leendert de Borst65caad621c2b
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.tsindex a0a703560..168801f8a 100644--- a/apps/browser-extension/src/entrypoints/background.ts+++ b/apps/browser-extension/src/entrypoints/background.ts@@ -9,7 +9,7 @@ import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, hanimport { handleOpenPopup, handlePopupWithItem, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePromptState, handleStoreLastAutofilled, handleGetLastAutofilled, handleClearLastAutofilled } from '@/entrypoints/background/SavePromptStateHandler';import { handleStoreTwoFactorState, handleGetTwoFactorState, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';-import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGeneratePassword, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVaultMetadata, handleSyncVault, handleUploadVault, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleMigrateVaultManifest, handleFullVaultSync, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleSetLoginSaveEnabled, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleGetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';+import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGeneratePassword, handleGetPersistedFormValues, handleGetVault, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVaultMetadata, handleSyncVault, handleUploadVault, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleMigrateVaultManifest, handleFullVaultSync, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleSetLoginSaveEnabled, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleGetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';import { LocalPreferencesService } from '@/utils/LocalPreferencesService';import { onMessage, sendMessage } from "@/utils/messaging/ExtensionMessaging";@@ -247,6 +247,7 @@ export default defineBackground({onMessage('UPLOAD_VAULT', () => handleUploadVault());onMessage('SYNC_VAULT', () => handleSyncVault());onMessage('FULL_VAULT_SYNC', () => handleFullVaultSync());+ onMessage('GET_VAULT_MIGRATION_STATUS', () => handleGetVaultMigrationStatus());onMessage('MIGRATE_VAULT_MANIFEST', () => handleMigrateVaultManifest());onMessage('LOCK_VAULT', () => handleLockVault());onMessage('CLEAR_SESSION', () => handleClearSession());diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex 1ac04e4f3..c58f14d05 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -43,7 +43,7 @@ import { type VaultMutationScope, DEFAULT_VAULT_MUTATION_SCOPE, hasUserVisibleScimport { VaultCodec } from '@/utils/VaultCodec';import { clearDirtyScopes, getDirtyScopes } from '@/utils/VaultDirtyState';import { VaultKeyService } from '@/utils/VaultKeyService';-import { vaultRequiresManifestMigration } from '@/utils/VaultManifestMigration';+import { vaultRequiresManifestMigration, VaultMigrationKind, type VaultMigrationStatus } from '@/utils/VaultManifestMigration';import { vaultMergeService } from '@/utils/VaultMergeService';import { vaultSyncService, invalidateCanonicalizeCache } from '@/utils/VaultSyncService';import { WebApiService } from '@/utils/WebApiService';@@ -96,7 +96,7 @@ let hasPendingSync = false;/*** Check if the user is logged in and if the vault is locked, and also check for both kinds of pending vault.*/-export async function handleCheckAuthStatus() : Promise<{ isLoggedIn: boolean, isVaultLocked: boolean, requiresLegacySqliteBlobMigration: boolean, requiresSchemaMigration: boolean, error?: string }> {+export async function handleCheckAuthStatus() : Promise<{ isLoggedIn: boolean, isVaultLocked: boolean, requiresLegacySqliteBlobMigration: boolean, requiresManifestMigration: boolean, error?: string }> {const [username, accessToken, vaultData, encryptionKey] = await Promise.all([storage.getItem(StorageKeys.USERNAME), storage.getItem(StorageKeys.ACCESS_TOKEN), storage.getItem(StorageKeys.ENCRYPTED_VAULT), handleGetEncryptionKey()]);const isLoggedIn = username !== null && accessToken !== null;@@ -104,27 +104,27 @@ export async function handleCheckAuthStatus() : Promise<{ isLoggedIn: boolean, i// A locked or logged-out vault can't be opened, so neither upgrade state can be determined.if (isVaultLocked || !isLoggedIn) {- return { isLoggedIn, isVaultLocked, requiresLegacySqliteBlobMigration: false, requiresSchemaMigration: false };+ return { isLoggedIn, isVaultLocked, requiresLegacySqliteBlobMigration: false, requiresManifestMigration: false };}// Vault is unlocked, check for pending migrationstry {const sqliteClient = await createVaultSqliteClient();const requiresLegacySqliteBlobMigration = await sqliteClient.requiresLegacySqliteBlobMigration();- const requiresSchemaMigration = await sqliteClient.requiresSchemaMigration();- return { isLoggedIn, isVaultLocked, requiresLegacySqliteBlobMigration, requiresSchemaMigration };+ const requiresManifestMigration = await vaultRequiresManifestMigration(sqliteClient);+ return { isLoggedIn, isVaultLocked, requiresLegacySqliteBlobMigration, requiresManifestMigration };} catch (error) {// If it's a version incompatibility error, we need to handle it speciallyif (error instanceof VaultVersionIncompatibleError) {// Return the error so the UI can handle it appropriately (logout user)- return { isLoggedIn, isVaultLocked, requiresLegacySqliteBlobMigration: false, requiresSchemaMigration: false, error: error.message };+ return { isLoggedIn, isVaultLocked, requiresLegacySqliteBlobMigration: false, requiresManifestMigration: false, error: error.message };}return {isLoggedIn,isVaultLocked,requiresLegacySqliteBlobMigration: false,- requiresSchemaMigration: false,+ requiresManifestMigration: false,error: error instanceof Error ? error.message : await t('common.errors.unknownError')};}@@ -1123,6 +1123,45 @@ export type VaultManifestMigrationResult = {error?: string;};+/**+ * Classify the pending migration so the migration gate logic knows whether it may run on its own.+ */+export async function handleGetVaultMigrationStatus(): Promise<VaultMigrationStatus> {+ try {+ const sqliteClient = await createVaultSqliteClient();++ if (await sqliteClient.requiresLegacySqliteBlobMigration()) {+ // The frozen sqlite-blob chain runs first, under its own /upgrade gate; nothing here applies yet.+ return { kind: VaultMigrationKind.None, serverConfirmed: true };+ }++ // Ask the server whether it holds a key hierarchy for this account, and adopt it when it does.+ let serverConfirmed = false;+ try {+ const probe = await VaultKeyService.fetchVaultKey();+ serverConfirmed = probe.supported;+ if (probe.vaultKey) {+ await adoptRemoteVaultKeyIfNeeded();+ }+ } catch (probeError) {+ devWarn('[ManifestMigration] Vault key probe failed, classifying from local state:', probeError);+ }++ if (await requiresLegacyAccountKeyMigration()) {+ return { kind: VaultMigrationKind.StorageFormatUpgrade, serverConfirmed };+ }++ if (await sqliteClient.requiresSchemaMigration()) {+ return { kind: VaultMigrationKind.SchemaRebuild, serverConfirmed: true };+ }++ return { kind: VaultMigrationKind.None, serverConfirmed: true };+ } catch (error) {+ devWarn('[ManifestMigration] Could not classify the pending migration, assuming it crosses the storage format:', error);+ return { kind: VaultMigrationKind.StorageFormatUpgrade, serverConfirmed: false };+ }+}+/*** Upgrade local manifest-v1 storage model to the current schema (if needed).*/diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.tsindex 8e1a444da..dcca634b0 100644--- a/apps/browser-extension/src/entrypoints/content.ts+++ b/apps/browser-extension/src/entrypoints/content.ts@@ -214,6 +214,9 @@ async function checkAndRestoreSavePromptEarly(ctx: Parameters<typeof createShadoif (!authStatus.isLoggedIn || authStatus.isVaultLocked) {return;}+ if (authStatus.requiresLegacySqliteBlobMigration || authStatus.requiresManifestMigration) {+ return;+ }} catch {return;}@@ -304,6 +307,9 @@ async function checkAndRestorePersistedSavePrompt(container: HTMLElement): Promiif (!authStatus.isLoggedIn || authStatus.isVaultLocked) {return;}+ if (authStatus.requiresLegacySqliteBlobMigration || authStatus.requiresManifestMigration) {+ return;+ }} catch {return;}@@ -361,6 +367,9 @@ function initializeLoginDetector(container: HTMLElement): void {if (!authStatus.isLoggedIn || authStatus.isVaultLocked) {return;}+ if (authStatus.requiresLegacySqliteBlobMigration || authStatus.requiresManifestMigration) {+ return;+ }} catch {return;}@@ -821,7 +830,7 @@ export default defineContentScript({/** Check if the vault requires a migration, if so, show a popup to the user.*/- if (authStatus.requiresLegacySqliteBlobMigration || authStatus.requiresSchemaMigration) {+ if (authStatus.requiresLegacySqliteBlobMigration || authStatus.requiresManifestMigration) {// Show upgrade required popupawait createUpgradeRequiredPopup(inputElement, container, await t('content.vaultUpgradeRequired'));return;diff --git a/apps/browser-extension/src/entrypoints/popup/App.tsx b/apps/browser-extension/src/entrypoints/popup/App.tsxindex f984c5b7c..e00886535 100644--- a/apps/browser-extension/src/entrypoints/popup/App.tsx+++ b/apps/browser-extension/src/entrypoints/popup/App.tsx@@ -12,7 +12,6 @@ import { useLoading } from '@/entrypoints/popup/context/LoadingContext';import { NavigationProvider } from '@/entrypoints/popup/context/NavigationContext';import AuthSettings from '@/entrypoints/popup/pages/auth/AuthSettings';import Login from '@/entrypoints/popup/pages/auth/Login';-import ManifestMigration from '@/entrypoints/popup/pages/auth/ManifestMigration';import Unlock from '@/entrypoints/popup/pages/auth/Unlock';import UnlockSuccess from '@/entrypoints/popup/pages/auth/UnlockSuccess';import Upgrade from '@/entrypoints/popup/pages/auth/Upgrade';@@ -188,7 +187,6 @@ const App: React.FC = () => {{ path: '/unlock', element: <Unlock />, showBackButton: false, layout: LayoutType.AUTH },{ path: '/unlock-success', element: <UnlockSuccess />, showBackButton: false },{ path: '/upgrade', element: <Upgrade />, showBackButton: false },- { path: '/manifest-migration', element: <ManifestMigration />, showBackButton: false },{ path: '/auth-settings', element: <AuthSettings />, showBackButton: true, title: t('common.settings') },{ path: '/items', element: <ItemsList />, showBackButton: false },{ path: '/items/folder/:folderId', element: <ItemsList />, showBackButton: true },diff --git a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/MobileUnlockModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/MobileUnlockModal.tsxindex 9541367a3..93a6ad357 100644--- a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/MobileUnlockModal.tsx+++ b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/MobileUnlockModal.tsx@@ -41,6 +41,8 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({switch (errorCode) {case MobileLoginErrorCode.TIMEOUT:return t('common.errors.mobileLoginRequestExpired');+ case MobileLoginErrorCode.SERVER_OUTDATED:+ return t('common.errors.serverVersionNotSupported');case MobileLoginErrorCode.GENERIC:default:return t('common.errors.unknownError');diff --git a/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx b/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsxindex 970c4dbc3..4eb9f9474 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx@@ -142,10 +142,10 @@ const Reinitialize: React.FC = () => {navigate('/upgrade', { replace: true });},/**- * Handle sqlite-blob to manifest-v1 migration.+ * Handle the manifest migration, which the same gate serves.*/onManifestMigrationRequired: () => {- navigate('/manifest-migration', { replace: true });+ navigate('/upgrade', { replace: true });},/*** Handle sync errors silently - user already has local vault.@@ -186,23 +186,12 @@ const Reinitialize: React.FC = () => {return;}- /*- * Check both vault upgrade gates before navigating. Order matters: a pre-2.0.0 vault has to walk the- * sqlite-blob upgrade chain (/upgrade, user-confirmed) before it is eligible for the manifest migration- * (/manifest-migration, automatic). The apps queries assume the current schema, so rendering any other page- * before running the migrations would throw on the missing columns.- */- if (await requiresLegacySqliteBlobMigration()) {- setIsInitialLoading(false);+ // Check if the vault requires a migration. If so, navigate to the upgrade page.+ if (await requiresLegacySqliteBlobMigration() || await requiresManifestMigration()) {navigate('/upgrade', { replace: true });return;}- if (await requiresManifestMigration()) {- navigate('/manifest-migration', { replace: true });- return;- }-/*** Navigate immediately using local vault without waiting for sync.* This ensures the UI is responsive even if server is slow to respond.diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsxindex 9879ac5dd..b319e588c 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx@@ -125,7 +125,7 @@ const Login: React.FC = () => {/** Navigate to reinitialize page which will:* 1. Call syncVault() to check version compatibility- * 2. Send the vault through /upgrade (legacy sqlite-blob chain) and/or /manifest-migration when those gates apply+ * 2. Send the vault through /upgrade when either the legacy sqlite-blob chain or the manifest migration applies* 3. Navigate to appropriate page** Other windows on /login or /unlock pick up the encryption-key storage@@ -428,7 +428,7 @@ const Login: React.FC = () => {/** Navigate to reinitialize page which will:* 1. Call syncVault() to check version compatibility- * 2. Send the vault through /upgrade (legacy sqlite-blob chain) and/or /manifest-migration when those gates apply+ * 2. Send the vault through /upgrade when either the legacy sqlite-blob chain or the manifest migration applies* 3. Navigate to appropriate page*/hideLoading();diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/ManifestMigration.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/ManifestMigration.tsxdeleted file mode 100644index 8375a21fb..000000000--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/ManifestMigration.tsx+++ /dev/null@@ -1,160 +0,0 @@-import React, { useState, useEffect, useCallback, useRef } from 'react';-import { useTranslation } from 'react-i18next';-import { useNavigate } from 'react-router-dom';--import Button from '@/entrypoints/popup/components/Button';-import LogoutConfirmModal from '@/entrypoints/popup/components/Dialogs/LogoutConfirmModal';-import HeaderButton from '@/entrypoints/popup/components/HeaderButton';-import { HeaderIconType } from '@/entrypoints/popup/components/Icons/HeaderIcons';-import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';-import { useAuth } from '@/entrypoints/popup/context/AuthContext';-import { useDb } from '@/entrypoints/popup/context/DbContext';-import { useHeaderButtons } from '@/entrypoints/popup/context/HeaderButtonsContext';-import { useLoading } from '@/entrypoints/popup/context/LoadingContext';-import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';-import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';--import { sendMessage } from '@/utils/messaging/ExtensionMessaging';--/**- * Manifest migration page.- *- * Rebuilds the local vault onto the current storage schema — the delivery path for all post-2.0.0 schema- * changes, including the initial legacy `sqlite-blob` to manifest-v1 transition. Migration is automatic by design.- */-const ManifestMigration: React.FC = () => {- const { t } = useTranslation();- const auth = useAuth();- const webApi = useWebApi();- const navigate = useNavigate();- const { setHeaderButtons } = useHeaderButtons();- const { setIsInitialLoading } = useLoading();- const { loadStoredDatabase, refreshSyncState } = useDb();-- const [error, setError] = useState<string | null>(null);- const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);- const hasStarted = useRef(false);-- // Set header buttons on mount and clear on unmount- useEffect((): (() => void) => {- const headerButtonsJSX = !PopoutUtility.isPopup() ? (- <HeaderButton- onClick={() => PopoutUtility.openInNewPopup()}- title={t('common.openInNewWindow')}- iconType={HeaderIconType.EXPAND}- />- ) : null;-- setHeaderButtons(headerButtonsJSX);-- return () => {- setHeaderButtons(null);- };- }, [setHeaderButtons, t]);-- /**- * Run the migration and continue into the app as soon as the local vault is on the current schema.- */- const runMigration = useCallback(async (): Promise<void> => {- setError(null);-- const result = await sendMessage('MIGRATE_VAULT_MANIFEST');-- if (!result.success) {- setError(result.error ?? t('common.errors.unknownError'));- setIsInitialLoading(false);- return;- }-- /*- * The background stored a new vault blob, so the popup's in-memory copy is stale. Reload before navigating,- * otherwise the items list would run its queries against the pre-migration database.- */- await loadStoredDatabase();- await refreshSyncState();-- if (!result.pushed) {- // Local vault is migrated and usable; the upload stays pending and the next sync picks it up.- console.warn('Vault manifest migration completed locally but has not reached the server yet.');- }-- navigate('/items', { replace: true });- }, [loadStoredDatabase, refreshSyncState, navigate, setIsInitialLoading, t]);-- // Start automatically on mount; the ref keeps a re-render from launching a second migration.- useEffect(() => {- if (hasStarted.current) {- return;- }- hasStarted.current = true;- runMigration();- }, [runMigration]);-- /**- * Retry after a failed migration.- */- const handleRetry = useCallback((): void => {- setIsInitialLoading(true);- runMigration();- }, [runMigration, setIsInitialLoading]);-- /**- * Handle the logout (after confirmation).- * Uses clearAuthUserInitiated to fully clear vault data since user explicitly chose to logout.- */- const handleLogout = async (): Promise<void> => {- setShowLogoutConfirm(false);- try {- await webApi.revokeTokens();- await auth.clearAuthUserInitiated();- } catch (error) {- console.error('Error during logout:', error);- }- };-- if (!error) {- return (- <div className="flex flex-col justify-center items-center py-12">- <LoadingSpinner />- <div className="text-sm text-gray-500 dark:text-gray-400 mt-4 px-6 text-center">- {t('manifestMigration.migrating')}- </div>- </div>- );- }-- return (- <div className="w-full px-2 pt-2 pb-2 mb-4">- <LogoutConfirmModal- isOpen={showLogoutConfirm}- onClose={() => setShowLogoutConfirm(false)}- onConfirm={handleLogout}- />-- <h2 className="text-xl font-bold dark:text-gray-200 mb-4">{t('manifestMigration.failedTitle')}</h2>-- <p className="mb-4 text-sm text-gray-600 dark:text-gray-300">- {t('manifestMigration.failedDescription')}- </p>-- <div className="mb-6 bg-gray-50 dark:bg-gray-800 rounded p-4 text-sm text-red-500 dark:text-red-400 break-words">- {error}- </div>-- <div className="flex flex-col w-full space-y-2">- <Button type="button" id="manifest-migration-retry-button" onClick={handleRetry}>- {t('common.retry')}- </Button>- <button- type="button"- onClick={() => setShowLogoutConfirm(true)}- className="text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 text-sm font-medium py-2"- >- {t('common.logout')}- </button>- </div>- </div>- );-};--export default ManifestMigration;diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Upgrade.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Upgrade.tsxindex ac2a3a43e..02f64b3f2 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Upgrade.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Upgrade.tsx@@ -1,8 +1,9 @@-import React, { useState, useEffect, useCallback } from 'react';+import React, { useState, useEffect, useCallback, useRef } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';import Button from '@/entrypoints/popup/components/Button';+import { CountdownBar, type ICountdownBarHandle } from '@/entrypoints/popup/components/CountdownBar';import LogoutConfirmModal from '@/entrypoints/popup/components/Dialogs/LogoutConfirmModal';import Modal from '@/entrypoints/popup/components/Dialogs/Modal';import HeaderButton from '@/entrypoints/popup/components/HeaderButton';@@ -18,46 +19,89 @@ import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';import { useVaultSync } from '@/entrypoints/popup/hooks/useVaultSync';import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';+import { AppInfo } from '@/utils/AppInfo';import type { VaultVersion } from '@/utils/dist/core/vault';import { VaultSqlGenerator } from '@/utils/dist/core/vault';+import { sendMessage } from '@/utils/messaging/ExtensionMessaging';+import { VaultMigrationKind } from '@/utils/VaultManifestMigration';++/** How long the success confirmation stays up before the vault opens by itself. */+const SUCCESS_COUNTDOWN_SECONDS = 5;++/** What the page is currently showing. */+type Stage = 'classifying' | 'consent' | 'upgrading' | 'success';++/**+ * Which upgrade the page is serving. All three land the vault on the current storage model; they differ in what+ * they cost the user, which is what decides whether the page asks first.+ */+enum UpgradeKind {+ /**+ * The legacy sqlite-blob upgrade chain (VAULT_VERSIONS, frozen at 2.0.0), applied as SQL against the local+ * vault. Asks first, and shows which vault version it moves the user to.+ *+ * TODO: delete this branch together with requiresLegacySqliteBlobMigration once all users have migrated.+ */+ LegacySqliteBlob = 'legacy-sqlite-blob',++ /**+ * A rebuild of the local database onto the current schema. Purely local and invisible to the rest of the+ * account: every other client materializes the vault into its own schema and carries columns it does not know+ * about in the codec overflow table. Runs unattended.+ */+ SchemaRebuild = 'schema-rebuild',++ /**+ * The one-way move of the account itself onto the manifest storage format and the account key hierarchy. The+ * push that completes it makes the server refuse every v1 vault endpoint, which signs out every client that+ * predates the format. Asks first, and says so.+ */+ StorageFormat = 'storage-format',+}/**- * Upgrade page for handling vault version upgrades.+ * The vault upgrade gate.*- * TODO: this page walks the sqlite-blob upgrade chain (frozen at 2.0.0) and can be deleted, together with- * requiresLegacySqliteBlobMigration, once all users have migrated. New schema changes are handled via the automatic- * /manifest-migration flow (requiresSchemaMigration / migrateVaultToCurrentSchema) instead.+ * A single screen for every reason the local vault cannot be opened yet, in the order they apply: first the+ * legacy sqlite-blob chain that brings a pre-2.0.0 vault to 2.0.0, then the manifest migration that puts it on+ * the current storage model. When both are pending they run back to back here, so the user sees one upgrade.+ *+ * This is a hard gate: until it finishes, the local database is still on the old schema and every other page+ * would query columns that do not exist yet. `/upgrade` is therefore listed among the pages that hide the bottom+ * nav and block the header logo, leaving upgrade or sign out as the only two ways out.*/const Upgrade: React.FC = () => {const { t } = useTranslation();const { username } = useApp();const auth = useAuth();- const dbContext = useDb();- const { sqliteClient } = dbContext;+ const navigate = useNavigate();+ const webApi = useWebApi();+ const { sqliteClient, requiresLegacySqliteBlobMigration, loadStoredDatabase, refreshSyncState } = useDb();const { setHeaderButtons } = useHeaderButtons();- const [isLoading, setIsLoading] = useState(false);+ const { setIsInitialLoading } = useLoading();+ const { executeVaultMutationAsync } = useVaultMutate();+ const { syncVault } = useVaultSync();++ const [stage, setStage] = useState<Stage>('classifying');+ const [kind, setKind] = useState<UpgradeKind | null>(null);+ const [error, setError] = useState<string | null>(null);const [currentVersion, setCurrentVersion] = useState<VaultVersion | null>(null);const [latestVersion, setLatestVersion] = useState<VaultVersion | null>(null);- const [error, setError] = useState<string | null>(null);const [showSelfHostedWarning, setShowSelfHostedWarning] = useState(false);const [showVersionInfo, setShowVersionInfo] = useState(false);const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);- const { setIsInitialLoading } = useLoading();- const webApi = useWebApi();- const { executeVaultMutationAsync } = useVaultMutate();- const { syncVault } = useVaultSync();- const navigate = useNavigate();+ const hasStarted = useRef(false);+ const countdownTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const countdownBarRef = useRef<ICountdownBarHandle>(null);// Set header buttons on mount and clear on unmountuseEffect((): (() => void) => {const headerButtonsJSX = !PopoutUtility.isPopup() ? (- <>- <HeaderButton- onClick={() => PopoutUtility.openInNewPopup()}- title={t('common.openInNewWindow')}- iconType={HeaderIconType.EXPAND}- />- </>+ <HeaderButton+ onClick={() => PopoutUtility.openInNewPopup()}+ title={t('common.openInNewWindow')}+ iconType={HeaderIconType.EXPAND}+ />) : null;setHeaderButtons(headerButtonsJSX);@@ -67,10 +111,30 @@ const Upgrade: React.FC = () => {};}, [setHeaderButtons, t]);+ // Clear the auto-continue timer if the page goes away before it fires.+ useEffect((): (() => void) => {+ return () => {+ if (countdownTimerRef.current) {+ clearTimeout(countdownTimerRef.current);+ }+ };+ }, []);++ /**+ * Run the countdown once the confirmation is on screen; the bar only mounts with that stage.+ */+ useEffect(() => {+ if (stage !== 'success') {+ return;+ }+ countdownBarRef.current?.startAnimation(SUCCESS_COUNTDOWN_SECONDS);+ countdownTimerRef.current = setTimeout(() => navigate('/items', { replace: true }), SUCCESS_COUNTDOWN_SECONDS * 1000);+ }, [stage, navigate]);+/**- * Load version information from the database.+ * Load version information from the database, which the legacy chain shows the user before it runs.*/- const loadVersionInfo = useCallback(async () => {+ const loadVersionInfo = useCallback(async (): Promise<void> => {try {if (sqliteClient) {const current = await sqliteClient.getDatabaseVersion();@@ -81,44 +145,124 @@ const Upgrade: React.FC = () => {} catch (error) {console.error('Failed to load version information:', error);setError(t('upgrade.alerts.unableToGetVersionInfo'));- } finally {- setIsInitialLoading(false);}- }, [sqliteClient, setIsInitialLoading, t]);-- useEffect(() => {- loadVersionInfo();- }, [loadVersionInfo]);+ }, [sqliteClient, t]);/**- * Handle the vault upgrade.+ * Hand the manifest migration to the background, then continue into the vault.+ * @param migrationKind - what the pending migration does, which decides what is shown afterwards*/- const handleUpgrade = async (): Promise<void> => {- if (!sqliteClient || !currentVersion || !latestVersion) {- setError(t('upgrade.alerts.unableToGetVersionInfo'));+ const runManifestMigration = useCallback(async (migrationKind: UpgradeKind): Promise<void> => {+ setError(null);+ setKind(migrationKind);+ setStage('upgrading');++ const result = await sendMessage('MIGRATE_VAULT_MANIFEST');++ if (!result.success) {+ // Back to the consent screen, where the same button retries and the error says why it has to.+ setError(result.error ?? t('common.errors.unknownError'));+ setStage('consent');+ setIsInitialLoading(false);return;}- // Check if this is a self-hosted instance and show warning if needed- if (await webApi.isSelfHosted()) {- setShowSelfHostedWarning(true);+ /*+ * The background stored a new vault blob, so the popup's in-memory copy is stale. Reload before navigating,+ * otherwise the items list would run its queries against the pre-migration database.+ */+ await loadStoredDatabase();+ await refreshSyncState();++ if (!result.pushed) {+ // Local vault is migrated and usable; the upload stays pending and the next sync picks it up.+ console.warn('Vault manifest migration completed locally but has not reached the server yet.');+ }++ setIsInitialLoading(false);++ /*+ * Only the storage format move leaves the user with something to do: their other devices need updating.+ * A schema rebuild changed nothing they can see, so it opens the vault without comment.+ */+ if (migrationKind === UpgradeKind.StorageFormat) {+ setStage('success');return;}- await performUpgrade();- };+ navigate('/items', { replace: true });+ }, [loadStoredDatabase, refreshSyncState, navigate, setIsInitialLoading, t]);++ /**+ * Ask the background what the manifest migration would do, and either put it to the user or run it.+ */+ const startManifestUpgrade = useCallback(async (): Promise<void> => {+ const plan = await sendMessage('GET_VAULT_MIGRATION_STATUS');++ if (plan.kind === VaultMigrationKind.StorageFormatUpgrade) {+ setKind(UpgradeKind.StorageFormat);+ setStage('consent');+ setIsInitialLoading(false);+ return;+ }++ // A local schema rebuild, or nothing left to do at all: both are safe to run unattended.+ await runManifestMigration(UpgradeKind.SchemaRebuild);+ }, [runManifestMigration, setIsInitialLoading]);++ /**+ * Continue into the vault once the whole upgrade has landed.+ */+ const finish = useCallback((): void => {+ navigate('/items', { replace: true });+ }, [navigate]);/**- * Perform the actual vault upgrade.+ * Pick up whatever is left after the legacy chain has run. The sqlite-blob upgrade brings the vault to 2.0.0,+ * which is the point at which the manifest migration becomes applicable, so it is classified only now.*/- const performUpgrade = async (): Promise<void> => {+ const handleLegacyUpgradeSuccess = useCallback(async (): Promise<void> => {+ try {+ // Sync vault to ensure we have the latest data+ await syncVault({+ /**+ * Handle successful sync completion.+ */+ onSuccess: finish,+ /**+ * Continue into the manifest migration, which the sync reports as still pending.+ */+ onManifestMigrationRequired: () => {+ void startManifestUpgrade();+ },+ /**+ * Handle sync error.+ * @param error Error message+ */+ onError: (error: string) => {+ console.error('Sync error after upgrade:', error);+ // Still navigate to items even if sync fails+ finish();+ }+ });+ } catch (error) {+ console.error('Error during post-upgrade sync:', error);+ // Navigate to items even if sync fails+ finish();+ }+ }, [syncVault, finish, startManifestUpgrade]);++ /**+ * Walk the legacy sqlite-blob upgrade chain against the local vault.+ */+ const performLegacyUpgrade = useCallback(async (): Promise<void> => {if (!sqliteClient || !currentVersion || !latestVersion) {setError(t('upgrade.alerts.unableToGetVersionInfo'));return;}- setIsLoading(true);setError(null);+ setStage('upgrading');try {// Get upgrade SQL commands from vault library@@ -131,7 +275,7 @@ const Upgrade: React.FC = () => {if (upgradeResult.sqlCommands.length === 0) {// No upgrade needed, vault is already up to date- await handleUpgradeSuccess();+ await handleLegacyUpgradeSuccess();return;}@@ -155,57 +299,66 @@ const Upgrade: React.FC = () => {}});- await handleUpgradeSuccess();+ await handleLegacyUpgradeSuccess();} catch (error) {console.error('Upgrade failed:', error);setError(error instanceof Error ? error.message : t('common.errors.unknownError'));- } finally {- setIsLoading(false);+ setStage('consent');+ setIsInitialLoading(false);}- };+ }, [sqliteClient, currentVersion, latestVersion, executeVaultMutationAsync, handleLegacyUpgradeSuccess, setIsInitialLoading, t]);/**- * Handle successful upgrade completion.+ * Work out what this vault needs and route to the matching stage. Order matters: a pre-2.0.0 vault has to walk+ * the sqlite-blob chain before the manifest migration can be classified at all.*/- const handleUpgradeSuccess = async (): Promise<void> => {- try {- // Sync vault to ensure we have the latest data- await syncVault({- /**- * Handle successful sync completion.- */- onSuccess: () => {- // Navigate to items page- navigate('/items');- },- /**- * Handle the manifest migration that follows this upgrade.- */- onManifestMigrationRequired: () => {- navigate('/manifest-migration', { replace: true });- },- /**- * Handle sync error.- * @param error Error message- */- onError: (error: string) => {- console.error('Sync error after upgrade:', error);- // Still navigate to items even if sync fails- navigate('/items');- }- });- } catch (error) {- console.error('Error during post-upgrade sync:', error);- // Navigate to items even if sync fails- navigate('/items');+ useEffect(() => {+ if (!sqliteClient || hasStarted.current) {+ return;}- };+ hasStarted.current = true;++ /**+ * Classify the pending upgrade and show or run it.+ */+ const classify = async (): Promise<void> => {+ try {+ if (await requiresLegacySqliteBlobMigration()) {+ setKind(UpgradeKind.LegacySqliteBlob);+ await loadVersionInfo();+ setStage('consent');+ setIsInitialLoading(false);+ return;+ }++ await startManifestUpgrade();+ } catch (error) {+ console.error('Failed to determine the pending vault upgrade:', error);+ setError(error instanceof Error ? error.message : t('common.errors.unknownError'));+ setStage('consent');+ setIsInitialLoading(false);+ }+ };++ classify();+ }, [sqliteClient, requiresLegacySqliteBlobMigration, loadVersionInfo, startManifestUpgrade, setIsInitialLoading, t]);/**- * Handle logout click - opens the logout confirmation modal.+ * Handle the upgrade button, which runs whichever upgrade this vault is waiting on.*/- const handleLogoutClick = (): void => {- setShowLogoutConfirm(true);+ const handleUpgrade = async (): Promise<void> => {+ if (kind !== UpgradeKind.LegacySqliteBlob) {+ await runManifestMigration(kind ?? UpgradeKind.StorageFormat);+ return;+ }++ // Check if this is a self-hosted instance and show warning if needed+ if (await webApi.isSelfHosted()) {+ setShowSelfHostedWarning(true);+ return;+ }++ await performLegacyUpgrade();};/**@@ -222,32 +375,46 @@ const Upgrade: React.FC = () => {}};- /**- * Show version description dialog.- */- const showVersionDialog = (): void => {- setShowVersionInfo(true);- };+ if (stage === 'classifying' || stage === 'upgrading') {+ return (+ <div className="flex flex-col justify-center items-center py-12">+ <LoadingSpinner />+ <div className="text-sm text-gray-500 dark:text-gray-400 mt-4 px-6 text-center">+ {t('upgrade.upgrading')}+ </div>+ </div>+ );+ }++ if (stage === 'success') {+ return (+ <div className="flex flex-col items-center justify-center p-6 text-center">+ <CountdownBar ref={countdownBarRef} isVisible={true} colorClass="bg-primary-500" />++ <div className="mb-4 text-green-600 dark:text-green-400">+ <svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />+ </svg>+ </div>+ <h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-white">{t('upgrade.successTitle')}</h2>+ <p className="mb-6 text-gray-600 dark:text-gray-400">{t('upgrade.successOtherDevices')}</p>++ <Button type="button" id="upgrade-continue-button" onClick={finish}>+ {t('auth.browseVault')}+ </Button>+ </div>+ );+ }return (<div>- {/* Full loading screen overlay */}- {isLoading && (- <div className="fixed inset-0 flex flex-col justify-center items-center bg-white dark:bg-gray-900 bg-opacity-90 dark:bg-opacity-90 z-50">- <LoadingSpinner />- <div className="text-sm text-gray-500 mt-2">- {t('upgrade.upgrading')}- </div>- </div>- )}-{/* Self-hosted warning modal */}<ModalisOpen={showSelfHostedWarning}onClose={() => setShowSelfHostedWarning(false)}onConfirm={() => {setShowSelfHostedWarning(false);- void performUpgrade();+ void performLegacyUpgrade();}}title={t('upgrade.alerts.selfHostedServer')}message={t('upgrade.alerts.selfHostedWarning')}@@ -266,7 +433,7 @@ const Upgrade: React.FC = () => {<form className="w-full px-2 pt-2 pb-2 mb-4">{error && (- <div className="mb-4 text-red-500 dark:text-red-400">+ <div className="mb-4 text-red-500 dark:text-red-400 break-words">{error}</div>)}@@ -293,48 +460,52 @@ const Upgrade: React.FC = () => {<p className="text-gray-700 dark:text-gray-200 mb-4">{t('upgrade.subtitle')}</p>- <div className="bg-gray-50 dark:bg-gray-800 rounded p-4 mb-4">- <div className="flex items-center justify-between mb-2">- <span className="font-medium text-gray-700 dark:text-gray-200">{t('upgrade.versionInformation')}</span>- <button- type="button"- onClick={showVersionDialog}- className="bg-gray-200 dark:bg-gray-600 text-gray-800 dark:text-gray-200 rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold hover:bg-gray-300 dark:hover:bg-gray-500"- title={t('upgrade.whatsNew')}- >- ?- </button>- </div>- <div className="space-y-2">- <div className="flex justify-between items-center">- <span className="text-sm text-gray-600 dark:text-gray-400">{t('upgrade.yourVault')}</span>- <span className="text-sm font-bold text-orange-600 dark:text-orange-400">- {currentVersion?.compatibleUpToVersion ?? '...'}- </span>++ {kind === UpgradeKind.LegacySqliteBlob && (+ <div className="bg-gray-50 dark:bg-gray-800 rounded p-4 mb-4">+ <div className="flex items-center justify-between mb-2">+ <span className="font-medium text-gray-700 dark:text-gray-200">{t('upgrade.versionInformation')}</span>+ <button+ type="button"+ onClick={() => setShowVersionInfo(true)}+ className="bg-gray-200 dark:bg-gray-600 text-gray-800 dark:text-gray-200 rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold hover:bg-gray-300 dark:hover:bg-gray-500"+ title={t('upgrade.whatsNew')}+ >+ ?+ </button></div>- <div className="flex justify-between items-center">- <span className="text-sm text-gray-600 dark:text-gray-400">{t('upgrade.newVersion')}</span>- <span className="text-sm font-bold text-green-600 dark:text-green-400">- {latestVersion?.releaseVersion ?? '...'}- </span>+ <div className="space-y-2">+ <div className="flex justify-between items-center">+ <span className="text-sm text-gray-600 dark:text-gray-400">{t('upgrade.yourVault')}</span>+ <span className="text-sm font-bold text-orange-600 dark:text-orange-400">+ {currentVersion?.compatibleUpToVersion ?? '...'}+ </span>+ </div>+ <div className="flex justify-between items-center">+ <span className="text-sm text-gray-600 dark:text-gray-400">{t('upgrade.newVersion')}</span>+ <span className="text-sm font-bold text-green-600 dark:text-green-400">+ {latestVersion?.releaseVersion ?? '...'}+ </span>+ </div></div></div>- </div>+ )}++ {kind === UpgradeKind.StorageFormat && (+ <div className="bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-900 rounded p-4 text-sm text-orange-800 dark:text-orange-300">+ {t('upgrade.otherDevicesWarning', { version: AppInfo.API_VERSION })}+ </div>+ )}</div><div className="flex flex-col w-full space-y-2">- <Button- type="button"- id="upgrade-button"- onClick={handleUpgrade}- >- {isLoading ? t('upgrade.upgrading') : t('upgrade.upgrade')}+ <Button type="button" id="upgrade-button" onClick={handleUpgrade}>+ {t('upgrade.upgrade')}</Button><buttontype="button"- onClick={handleLogoutClick}+ onClick={() => setShowLogoutConfirm(true)}className="text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 text-sm font-medium py-2"- disabled={isLoading}>{t('common.logout')}</button>diff --git a/apps/browser-extension/src/entrypoints/popup/types/MobileLoginErrorCode.ts b/apps/browser-extension/src/entrypoints/popup/types/MobileLoginErrorCode.tsindex 53ad241cf..07d836c8b 100644--- a/apps/browser-extension/src/entrypoints/popup/types/MobileLoginErrorCode.ts+++ b/apps/browser-extension/src/entrypoints/popup/types/MobileLoginErrorCode.ts@@ -8,6 +8,11 @@ export enum MobileLoginErrorCode {*/TIMEOUT = 'TIMEOUT',+ /**+ * The server is outdated and does not support mobile login.+ */+ SERVER_OUTDATED = 'SERVER_OUTDATED',+/*** A generic error occurred during mobile login.*/diff --git a/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts b/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.tsindex 245758b6b..53111723b 100644--- a/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts+++ b/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts@@ -4,6 +4,7 @@ import { MobileLoginErrorCode } from '@/entrypoints/popup/types/MobileLoginErrorimport type { LoginResponse, MobileLoginInitiateResponse, MobileLoginPollResponse } from '@/utils/dist/core/models/webapi';import EncryptionUtility from '@/utils/EncryptionUtility';+import { serverPredatesV2Api } from '@/utils/legacy/LegacyStorageModelMigration';import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';import type { WebApiService } from '@/utils/WebApiService';@@ -63,6 +64,14 @@ export class MobileLoginUtility {}),});+ /*+ * A 404 on this initiating call means the v2 API is missing altogether. Only this call may read a 404 that+ * way: the poll below answers 404 for an expired request, which is a normal outcome.+ */+ if (response.status === 404 && await serverPredatesV2Api(await this.webApi.getApiUrl())) {+ throw MobileLoginErrorCode.SERVER_OUTDATED;+ }+if (!response.ok) {throw MobileLoginErrorCode.GENERIC;}diff --git a/apps/browser-extension/src/entrypoints/popup/utils/SrpUtility.ts b/apps/browser-extension/src/entrypoints/popup/utils/SrpUtility.tsindex d0ed55cf8..7552d4cd0 100644--- a/apps/browser-extension/src/entrypoints/popup/utils/SrpUtility.ts+++ b/apps/browser-extension/src/entrypoints/popup/utils/SrpUtility.ts@@ -1,5 +1,6 @@import { SrpAuthService } from '@/utils/auth/SrpAuthService';import type { LoginResponse, ValidateLoginResponse, ValidateLoginRequest, ValidateLoginRequest2Fa, BadRequestResponse } from '@/utils/dist/core/models/webapi';+import { throwIfServerPredatesV2Api } from '@/utils/legacy/LegacyStorageModelMigration';import { ApiAuthError } from '@/utils/types/errors/ApiAuthError';import { WebApiService } from '@/utils/WebApiService';@@ -21,6 +22,15 @@ class SrpUtility {this.webApiService = webApiService;}+ /**+ * Reject a response that a server predating the v2 API produced.+ * TODO: can be deleted later once all users have migrated to the new storage format and we don't support v1 API anymore.+ * @param response - the raw auth response+ */+ private async assertServerSupportsV2Api(response: Response): Promise<void> {+ await throwIfServerPredatesV2Api(response.status, await this.webApiService.getApiUrl());+ }+/*** Initiate login with server.*/@@ -35,6 +45,8 @@ class SrpUtility {body: JSON.stringify({ username: normalizedUsername }),});+ await this.assertServerSupportsV2Api(response);+// Check if response is a bad request (400)if (response.status === 400) {const badRequestResponse = await response.json() as BadRequestResponse;@@ -97,6 +109,8 @@ class SrpUtility {body: JSON.stringify(model),});+ await this.assertServerSupportsV2Api(response);+// Check if response is a bad request (400)if (response.status === 400) {const badRequestResponse = await response.json() as BadRequestResponse;@@ -161,6 +175,8 @@ class SrpUtility {body: JSON.stringify(model),});+ await this.assertServerSupportsV2Api(response);+// Check if response is a bad request (400)if (response.status === 400) {const badRequestResponse = await response.json() as BadRequestResponse;diff --git a/apps/browser-extension/src/i18n/locales/en.json b/apps/browser-extension/src/i18n/locales/en.jsonindex ec3a589a7..8a80e3ae2 100644--- a/apps/browser-extension/src/i18n/locales/en.json+++ b/apps/browser-extension/src/i18n/locales/en.json@@ -608,6 +608,9 @@"whatsNew": "What's New","whatsNewDescription": "An upgrade is required to support the following changes:","noDescriptionAvailable": "No description available for this version.",+ "otherDevicesWarning": "After this upgrade, your other AliasVault apps need version {{version}} or newer. Older apps and browser extensions sign out and ask to be updated before they can open your vault again.",+ "successTitle": "Vault upgraded",+ "successOtherDevices": "Your vault is ready to use. Make sure to update the AliasVault app on your other devices as well.","alerts": {"unableToGetVersionInfo": "Unable to get version information. Please try again.","selfHostedServer": "Self-Hosted Server",@@ -617,11 +620,6 @@"failedToApplyMigration": "Failed to apply migration ({{current}} of {{total}})"}},- "manifestMigration": {- "migrating": "Automatically migrating your vault to the new data model. This should only take a few seconds...",- "failedTitle": "Vault Migration Failed",- "failedDescription": "Your vault could not be migrated to the new data model. Your existing data is untouched. Please try again, or log out and log back in. If the problem persists, please contact support."- },"logout": {"unsyncedChangesTitle": "Unsynced Changes","unsyncedChangesWarning": "You have unsynced changes that will be lost if you log out now. Are you sure you want to continue?",diff --git a/apps/browser-extension/src/utils/VaultManifestMigration.ts b/apps/browser-extension/src/utils/VaultManifestMigration.tsindex e28f5f80a..49c219b17 100644--- a/apps/browser-extension/src/utils/VaultManifestMigration.ts+++ b/apps/browser-extension/src/utils/VaultManifestMigration.ts@@ -2,7 +2,7 @@ import { requiresLegacyAccountKeyMigration } from '@/utils/legacy/LegacyStorageMimport type { SqliteClient } from '@/utils/SqliteClient';/**- * Whether the vault still has to run the manifest migration. The predicate behind the /manifest-migration gate,+ * Whether the vault still has to run the manifest migration. One of the two predicates behind the /upgrade gate,* answered entirely from local state.** Two conditions, carried independently of each other:@@ -10,9 +10,39 @@ import type { SqliteClient } from '@/utils/SqliteClient';* it delivered the initial sqlite-blob to manifest-v1 transition and fires again after every schema change we ship.* 2. A missing account key hierarchy ({@link requiresLegacyAccountKeyMigration}), one-time and deletable.*- * Callers must check `requiresLegacySqliteBlobMigration()` FIRST — a pre-2.0.0 vault has to walk the sqlite-blob upgrade chain before either condition here can be acted on.+ * Callers must check `requiresLegacySqliteBlobMigration()` first: a pre-2.0.0 vault has to walk the sqlite-blob upgrade chain before either condition here can be acted on.* @param sqliteClient - the open local vault*/export async function vaultRequiresManifestMigration(sqliteClient: SqliteClient): Promise<boolean> {return await sqliteClient.requiresSchemaMigration() || await requiresLegacyAccountKeyMigration();}++/**+ * What a pending migration will actually do, which decides whether it may run on its own.+ */+export enum VaultMigrationKind {+ /** No migration pending. */+ None = 'none',++ /**+ * Rebuild the local database onto the current schema. Runs automatically.+ */+ SchemaRebuild = 'schema-rebuild',++ /**+ * Upgrades from sqlite-blob to manifest-v1 (api v1 to api v2) storage format.+ */+ StorageFormatUpgrade = 'storage-format-upgrade',+}++/**+ * A pending migration, classified.+ */+export type VaultMigrationStatus = {+ kind: VaultMigrationKind;++ /**+ * Whether the classification could be confirmed against the server. False when the vault key probe could not reach the server.+ */+ serverConfirmed: boolean;+};diff --git a/apps/browser-extension/src/utils/WebApiService.ts b/apps/browser-extension/src/utils/WebApiService.tsindex 5fe93bc71..af4b48553 100644--- a/apps/browser-extension/src/utils/WebApiService.ts+++ b/apps/browser-extension/src/utils/WebApiService.ts@@ -448,7 +448,7 @@ export class WebApiService {/*** Get the API URL from settings.*/- private async getApiUrl(): Promise<string> {+ public async getApiUrl(): Promise<string> {const result = await storage.getItem(StorageKeys.API_URL) as string;if (!result || result.length === 0) {return AppInfo.DEFAULT_API_URL;diff --git a/apps/browser-extension/src/utils/legacy/LegacyStorageModelMigration.ts b/apps/browser-extension/src/utils/legacy/LegacyStorageModelMigration.tsindex 15b3778dc..aa28ae7de 100644--- a/apps/browser-extension/src/utils/legacy/LegacyStorageModelMigration.ts+++ b/apps/browser-extension/src/utils/legacy/LegacyStorageModelMigration.ts@@ -10,6 +10,7 @@ import { StorageKeys } from '@/utils/constants/storageKeys';import { devLog } from '@/utils/devLogger/DevLogger';import { EncryptionUtility } from '@/utils/EncryptionUtility';import { replaceManifestRevisions } from '@/utils/ManifestRevisions';+import { ApiRequestError } from '@/utils/types/errors/ApiRequestError';import { ServerUpdateRequiredError } from '@/utils/types/errors/ServerUpdateRequiredError';import { VaultKeyService } from '@/utils/VaultKeyService';@@ -17,19 +18,56 @@ import { VaultKeyService } from '@/utils/VaultKeyService';* -- 1. Servers predating the v2 vault API --*/+/** How long the legacy-API probe may take before we stop blaming the server version. */+const V1_PROBE_TIMEOUT_MS = 3000;+/**- * True when an error from WebApiService is an HTTP 404. WebApiService surfaces non-2xx responses as a generic- * Error whose message carries the status code (`HTTP error! status: 404`).+ * True when an error from WebApiService is an HTTP 404. Every non-2xx response from authFetch surfaces as an+ * {@link ApiRequestError} carrying the status code.* @param e - the caught error*/function isNotFoundError(e: unknown): boolean {- return e instanceof Error && e.message.includes('status: 404');+ return e instanceof ApiRequestError && e.statusCode === 404;+}++/**+ * Probe whether the configured server answers on the v1 API while v2 does not respond.+ * @param apiBaseUrl - the configured API base URL, without a version segment+ */+export async function serverPredatesV2Api(apiBaseUrl: string): Promise<boolean> {+ try {+ const response = await fetch(`${apiBaseUrl.replace(/\/$/, '')}/v1/Auth/login`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: '{}',+ signal: AbortSignal.timeout(V1_PROBE_TIMEOUT_MS),+ });++ return response.status !== 404;+ } catch {+ // Unreachable or timed out: we cannot prove the server is outdated, so let the caller report the original failure.+ return false;+ }+}++/**+ * Translate a 404 from a v2 endpoint into {@link ServerUpdateRequiredError} when the server turns out to be an+ * outdated AliasVault install.+ * @param status - the HTTP status of the v2 response+ * @param apiBaseUrl - the configured API base URL, without a version segment+ */+export async function throwIfServerPredatesV2Api(status: number, apiBaseUrl: string): Promise<void> {+ if (status !== 404) {+ return;+ }++ if (await serverPredatesV2Api(apiBaseUrl)) {+ throw new ServerUpdateRequiredError();+ }}/**- * Run a v2 API call, translating the outdated-server 404 into {@link ServerUpdateRequiredError}. Such a server- * answers every v2 endpoint with a 404, which is indistinguishable from a routing error unless we translate it,- * so the UI can surface "update your server" (E-903) instead. Every other failure propagates unchanged.+ * Run a v2 API call, translating the outdated-server 404 into {@link ServerUpdateRequiredError}.* @param fn - the call to run*/export async function withOutdatedServerGuard<T>(fn: () => Promise<T>): Promise<T> {diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.tsindex 7b6d81a2e..8efe3e5df 100644--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts@@ -36,6 +36,7 @@ import type { StringResponse } from '@/utils/types/messaging/StringResponse';import type { VaultResponse } from '@/utils/types/messaging/VaultResponse';import type { VaultUploadResponse } from '@/utils/types/messaging/VaultUploadResponse';import type { VaultMutationScope } from '@/utils/types/VaultMutationScope';+import type { VaultMigrationStatus } from '@/utils/VaultManifestMigration';/* eslint-disable @typescript-eslint/no-explicit-any *//**@@ -48,7 +49,7 @@ export interface IExtensionMessageProtocol {ADD_URL_TO_CREDENTIAL(data: { itemId: string; url: string }): { success: boolean; error?: string };AUTOFILL_CREATED_ITEM(data: { item: any; elementIdentifier?: string }): BoolResponse;CANCEL_CLIPBOARD_CLEAR(): void;- CHECK_AUTH_STATUS(): { isLoggedIn: boolean; isVaultLocked: boolean; requiresLegacySqliteBlobMigration: boolean; requiresSchemaMigration: boolean; error?: string };+ CHECK_AUTH_STATUS(): { isLoggedIn: boolean; isVaultLocked: boolean; requiresLegacySqliteBlobMigration: boolean; requiresManifestMigration: boolean; error?: string };CHECK_LOGIN_DUPLICATE(data: { domain: string; username: string }): DuplicateCheckResponse;CLEAR_LAST_AUTOFILLED(): { success: boolean };CLEAR_PERSISTED_FORM_VALUES(): void;@@ -86,6 +87,7 @@ export interface IExtensionMessageProtocol {GET_TOTP_SECRETS(data: { itemIds: string[] }): { success: boolean; secrets?: Record<string, TotpSecret>; error?: string };GET_TWO_FACTOR_STATE(): TwoFactorState | null;GET_VAULT(): VaultResponse;+ GET_VAULT_MIGRATION_STATUS(): VaultMigrationStatus;GET_WEBAUTHN_SETTINGS(data: any): WebAuthnSettingsResponse;IS_URL_LINKED_TO_CREDENTIAL(data: { itemId: string; url: string }): { linked: boolean };LOCK_VAULT(): BoolResponse;