Skip to content

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

Add mobile app legacy sqlite-blob migration to manifest-v1 flow (#2159)

Leendert de Borst5c2c857f14f3
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
index 182360def..98127ed67 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
@@ -1476,6 +1476,66 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
}
+ /**
+ * Classify the pending manifest migration (see VaultStore.getVaultMigrationStatus). Rejects with the native error code.
+ * @param promise The promise to resolve with the migration kind.
+ */
+ @ReactMethod
+ override fun getVaultMigrationStatus(promise: Promise) {
+ CoroutineScope(Dispatchers.IO).launch {
+ try {
+ val kind = vaultStore.getVaultMigrationStatus(webApiService)
+ withContext(Dispatchers.Main) {
+ promise.resolve(kind)
+ }
+ } catch (e: AppError) {
+ withContext(Dispatchers.Main) {
+ promise.reject(e.code, e.message, e)
+ }
+ } catch (e: Exception) {
+ withContext(Dispatchers.Main) {
+ Log.e(TAG, "Error classifying the pending vault migration", e)
+ promise.reject("VAULT_MIGRATION_STATUS_ERROR", "Failed to classify the pending vault migration: ${e.message}", e)
+ }
+ }
+ }
+ }
+
+ /**
+ * Run the pending manifest migration and push it (see VaultStore.migrateVaultManifest). Failures resolve with the error code.
+ * @param promise The promise to resolve with the migration result.
+ */
+ @ReactMethod
+ override fun migrateVaultManifest(promise: Promise) {
+ CoroutineScope(Dispatchers.IO).launch {
+ try {
+ val result = vaultStore.migrateVaultManifest(webApiService)
+ val resultMap = Arguments.createMap().apply {
+ putBoolean("success", result.success)
+ putBoolean("pushed", result.pushed)
+ if (result.error != null) {
+ putString("error", result.error)
+ } else {
+ putNull("error")
+ }
+ if (result.errorMessage != null) {
+ putString("errorMessage", result.errorMessage)
+ } else {
+ putNull("errorMessage")
+ }
+ }
+ withContext(Dispatchers.Main) {
+ promise.resolve(resultMap)
+ }
+ } catch (e: Exception) {
+ withContext(Dispatchers.Main) {
+ Log.e(TAG, "Error migrating the vault", e)
+ promise.reject("VAULT_MIGRATION_ERROR", "Failed to migrate the vault: ${e.message}", e)
+ }
+ }
+ }
+ }
+
// MARK: - PIN Unlock Methods
/**
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultData.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultData.kt
index dfc83dc08..2a9c1b041 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultData.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultData.kt
@@ -33,6 +33,8 @@ enum class SyncAction(val value: String) {
* @property wasOffline Whether the sync ran offline.
* @property error The error code, if any.
* @property errorMessage The error message, if any.
+ * @property sqliteBlobUpgradeRequired The local vault still has to walk the frozen sqlite-blob upgrade chain (pre-2.0.0); nothing was synced.
+ * @property manifestMigrationRequired The local vault still has to run the manifest migration (stale schema or no account key hierarchy); nothing was synced.
*/
data class VaultSyncResult(
val success: Boolean,
@@ -41,4 +43,21 @@ data class VaultSyncResult(
val wasOffline: Boolean,
val error: String? = null,
val errorMessage: String? = null,
+ val sqliteBlobUpgradeRequired: Boolean = false,
+ val manifestMigrationRequired: Boolean = false,
+)
+
+/**
+ * Result of the manifest migration the app's upgrade page drives.
+ *
+ * @property success Whether the migration completed locally.
+ * @property pushed Whether the migrated vault reached the server; false leaves it dirty for the next sync.
+ * @property error The error code, if any.
+ * @property errorMessage The error message, if any.
+ */
+data class VaultMigrationResult(
+ val success: Boolean,
+ val pushed: Boolean,
+ val error: String? = null,
+ val errorMessage: String? = null,
)
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
index ccb01374a..0b0d030b1 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
@@ -811,6 +811,20 @@ class VaultStore(
return sync.syncVaultWithServer(webApiService)
}
+ /**
+ * Classify the pending manifest migration (see VaultSync.getVaultMigrationStatus).
+ */
+ suspend fun getVaultMigrationStatus(webApiService: net.aliasvault.app.webapi.WebApiService): String {
+ return sync.getVaultMigrationStatus(webApiService)
+ }
+
+ /**
+ * Run the pending manifest migration and push it (see VaultSync.migrateVaultManifest).
+ */
+ suspend fun migrateVaultManifest(webApiService: net.aliasvault.app.webapi.WebApiService): VaultMigrationResult {
+ return sync.migrateVaultManifest(webApiService)
+ }
+
// endregion
// region Mutate Methods
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
index 546ce652e..6b881ecf2 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
@@ -43,9 +43,6 @@ class VaultSync(
val code = AppError.NetworkError(IllegalStateException("offline")).code
return VaultSyncResult(false, SyncAction.ERROR, metadata.getVaultRevisionNumber(), true, code)
}
- if (result.optBoolean("manifestMigrationRequired", false)) {
- runPendingManifestMigration(webApiService)
- }
val hasNewVault = result.optBoolean("hasNewVault", false)
val action = when {
@@ -54,7 +51,14 @@ class VaultSync(
wasDirty -> SyncAction.UPLOADED
else -> SyncAction.ALREADY_IN_SYNC
}
- return VaultSyncResult(true, action, metadata.getVaultRevisionNumber(), false, null)
+ return VaultSyncResult(
+ success = true,
+ action = action,
+ newRevision = metadata.getVaultRevisionNumber(),
+ wasOffline = false,
+ sqliteBlobUpgradeRequired = result.optBoolean("sqliteBlobUpgradeRequired", false),
+ manifestMigrationRequired = result.optBoolean("manifestMigrationRequired", false),
+ )
} finally {
metadata.setIsSyncing(false)
}
@@ -157,23 +161,46 @@ class VaultSync(
}
/**
- * Bring the local vault onto the current storage model when the engine reports that it has to (a schema
- * rebuild after an app update, or the one-time account-key upgrade of a legacy vault), then push it.
+ * Classify the pending manifest migration as the engine sees it: `none`, `schema-rebuild` (runs unattended) or
+ * `storage-format-upgrade` (the app asks first). A vault still on the sqlite-blob chain classifies as `none`.
*/
@Suppress("TooGenericExceptionCaught")
- private suspend fun runPendingManifestMigration(webApiService: WebApiService) {
- try {
- val status = VaultSyncEngine(vaultStore, storageProvider, webApiService).run("migrationStatus")
- val kind = status.optString("kind", "none")
- if (kind == "none") {
- return
- }
- val result = VaultSyncEngine(vaultStore, storageProvider, webApiService).run("migrateManifest")
- adoptSyncSideEffects(result)
- Log.i(TAG, "Manifest migration ($kind): success=${result.optBoolean("success")} pushed=${result.optBoolean("pushed")}")
+ suspend fun getVaultMigrationStatus(webApiService: WebApiService): String {
+ val status = try {
+ VaultSyncEngine(vaultStore, storageProvider, webApiService).run("migrationStatus")
+ } catch (e: Exception) {
+ throw driverError(e)
+ }
+ return status.optString("kind").takeIf { it.isNotEmpty() } ?: "storage-format-upgrade"
+ }
+
+ /**
+ * Bring the local vault onto the current storage model (a schema rebuild after an app update, or the one-time
+ * account-key upgrade of a legacy vault) and push it. Driven by the app's upgrade page only: a sync never runs
+ * it on its own, because the storage format move signs out every other client that predates the format.
+ */
+ @Suppress("TooGenericExceptionCaught")
+ suspend fun migrateVaultManifest(webApiService: WebApiService): VaultMigrationResult {
+ val result = try {
+ VaultSyncEngine(vaultStore, storageProvider, webApiService).run("migrateManifest")
} catch (e: Exception) {
- Log.w(TAG, "Manifest migration failed, the vault stays as it is until the next sync", e)
+ return failedMigration(driverError(e))
+ }
+ adoptSyncSideEffects(result)
+ if (!result.optBoolean("success", false)) {
+ return failedMigration(syncError(result))
}
+ val pushed = result.optBoolean("pushed", false)
+ Log.i(TAG, "Manifest migration complete: pushed=$pushed")
+ return VaultMigrationResult(true, pushed)
+ }
+
+ /**
+ * A failed migration return.
+ */
+ private fun failedMigration(error: AppError): VaultMigrationResult {
+ Log.e(TAG, "Manifest migration failed (${error.code}): ${error.message}", error.cause)
+ return VaultMigrationResult(false, false, error.code, error.message)
}
/**
diff --git a/apps/mobile-app/app/upgrade.tsx b/apps/mobile-app/app/upgrade.tsx
index b25257a98..468d25a14 100644
--- a/apps/mobile-app/app/upgrade.tsx
+++ b/apps/mobile-app/app/upgrade.tsx
@@ -1,14 +1,17 @@
+import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
+import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import { VaultSqlGenerator } from '@aliasvault/vault';
+import { MaterialIcons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
-import { useState, useEffect, useCallback } from 'react';
+import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, View, KeyboardAvoidingView, Platform, ScrollView, Dimensions, TouchableWithoutFeedback, Keyboard, Text } from 'react-native';
+import { AppErrorCode, extractErrorCode, formatErrorWithCode, getErrorTranslationKey } from '@/utils/types/errors/AppErrorCodes';
+
import { useColors } from '@/hooks/useColorScheme';
import { useLogout } from '@/hooks/useLogout';
-import { useVaultMutate } from '@/hooks/useVaultMutate';
-import { useVaultSync } from '@/hooks/useVaultSync';
import Logo from '@/assets/images/logo.svg';
import LoadingIndicator from '@/components/LoadingIndicator';
@@ -24,252 +27,301 @@ import NativeVaultManager from '@/specs/NativeVaultManager';
import type { VaultVersion } from '@aliasvault/vault';
+/** 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. 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 signs out every client that predates the format. Asks first, and says so.
+ */
+ StorageFormat = 'storage-format',
+}
+
+/** The migration kind the native engine reports for the storage format move (see NativeVaultManager.getVaultMigrationStatus). */
+const MIGRATION_STATUS_STORAGE_FORMAT_UPGRADE = 'storage-format-upgrade';
+
+/** Engine failures that end the session instead of a retry on this page. */
+const LOGOUT_ERROR_CODES: ReadonlySet<AppErrorCode> = new Set([
+ AppErrorCode.SESSION_EXPIRED,
+ AppErrorCode.AUTHENTICATION_FAILED,
+ AppErrorCode.PASSWORD_CHANGED,
+ AppErrorCode.CLIENT_VERSION_NOT_SUPPORTED,
+ AppErrorCode.SERVER_VERSION_NOT_SUPPORTED,
+ AppErrorCode.VAULT_VERSION_INCOMPATIBLE,
+]);
+
/**
- * Upgrade screen.
+ * The vault upgrade gate.
+ *
+ * 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 or sign out are the only two ways out.
*/
export default function UpgradeScreen() : React.ReactNode {
- const { username } = useApp();
- const { logoutUserInitiated } = useLogout();
+ const app = useApp();
+ const { username } = app;
+ const { logoutUserInitiated, logoutForced } = useLogout();
const webApi = useWebApi();
const dbContext = useDb();
const { sqliteClient } = dbContext;
- const [isLoading, setIsLoading] = useState(false);
+ const [stage, setStage] = useState<Stage>('classifying');
+ const [kind, setKind] = useState<UpgradeKind | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [errorDetail, setErrorDetail] = useState<string | null>(null);
const [currentVersion, setCurrentVersion] = useState<VaultVersion | null>(null);
const [latestVersion, setLatestVersion] = useState<VaultVersion | null>(null);
const colors = useColors();
const { t } = useTranslation();
const [upgradeStatus, setUpgradeStatus] = useState(() => t('upgrade.status.preparingUpgrade'));
- const { executeVaultMutation, isLoading: isVaultMutationLoading, syncStatus } = useVaultMutate();
- const { syncVault } = useVaultSync();
const { showAlert, showConfirm } = useDialog();
-
- const [isSyncingOnLoad, setIsSyncingOnLoad] = useState(true);
+ const hasStarted = useRef(false);
/**
- * 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 () => {
- try {
- if (sqliteClient) {
- const current = await sqliteClient.getDatabaseVersion();
- const latest = await sqliteClient.getLatestDatabaseVersion();
- setCurrentVersion(current);
- setLatestVersion(latest);
- }
- } catch (error) {
- console.error('Failed to load version information:', error);
+ if (!sqliteClient) {
+ return;
}
+ const current = await sqliteClient.getDatabaseVersion();
+ const latest = await sqliteClient.getLatestDatabaseVersion();
+ setCurrentVersion(current);
+ setLatestVersion(latest);
}, [sqliteClient]);
/**
- * Try to sync with the server on load. If the vault was already upgraded
- * on another device, the server may have a newer vault that doesn't need
- * local migration, allowing us to skip the upgrade entirely.
+ * Continue into the vault once the whole upgrade has landed.
*/
- useEffect(() => {
- /**
- * Sync on load to check if server has an already-upgraded vault.
- */
- const syncOnLoad = async (): Promise<void> => {
- let skipVersionLoad = false;
-
- try {
- setUpgradeStatus(t('vault.checkingVaultUpdates'));
- await syncVault({
- /**
- * Handle the status update.
- */
- onStatus: (message) => setUpgradeStatus(message),
- /**
- * Handle successful sync and check if upgrade is still needed.
- */
- onSuccess: async () => {
- // After sync, check if we still need to upgrade
- if (!(await dbContext.hasPendingMigrations())) {
- // Server had an upgraded vault, no local upgrade needed
- skipVersionLoad = true;
- dbContext.setDatabaseAvailable();
- router.replace('/(tabs)/items');
- }
- },
- });
- } catch {
- // On any error, fall through to local upgrade flow
- } finally {
- // Always load version info unless we're navigating away
- if (!skipVersionLoad) {
- await loadVersionInfo();
- }
- setIsSyncingOnLoad(false);
- setUpgradeStatus(t('upgrade.status.preparingUpgrade'));
- }
- };
+ const finish = useCallback((): void => {
+ dbContext.setDatabaseAvailable();
+ router.replace('/(tabs)/items');
+ }, [dbContext]);
- syncOnLoad();
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ /**
+ * Show a failed step on the consent screen, where the same button retries. Failures that end the session log out instead.
+ * @param code - the error code
+ * @param detail - the technical detail, shown under the translated message when it adds something
+ */
+ const failStep = useCallback(async (code: AppErrorCode, detail: string | null): Promise<void> => {
+ const message = formatErrorWithCode(t(getErrorTranslationKey(code)), code);
+ if (LOGOUT_ERROR_CODES.has(code)) {
+ await app.logout(message);
+ return;
+ }
+ setError(message);
+ setErrorDetail(detail && detail !== message ? detail : null);
+ setStage('consent');
+ }, [app, t]);
/**
- * Handle the vault upgrade.
+ * Run the manifest migration natively, 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) {
- showAlert(t('common.error'), t('upgrade.alerts.unableToGetVersionInfo'));
+ const runManifestMigration = useCallback(async (migrationKind: UpgradeKind): Promise<void> => {
+ setError(null);
+ setErrorDetail(null);
+ setKind(migrationKind);
+ setStage('upgrading');
+ setUpgradeStatus(t('upgrade.upgrading'));
+
+ const result = await NativeVaultManager.migrateVaultManifest();
+
+ if (!result.success) {
+ console.error('[Upgrade] Vault manifest migration failed:', result);
+ await failStep(extractErrorCode(result.error ?? '') ?? AppErrorCode.UNKNOWN_ERROR, result.errorMessage);
return;
}
- // Check if this is a self-hosted instance and show warning if needed
- if (await webApi.isSelfHosted()) {
- showConfirm(
- t('upgrade.alerts.selfHostedServer'),
- t('upgrade.alerts.selfHostedWarning'),
- t('upgrade.alerts.continueUpgrade'),
- performUpgrade
- );
- } else {
- await performUpgrade();
+ if (!result.pushed) {
+ // Local vault is migrated and usable; the upload stays pending and the next sync picks it up.
+ console.warn('[Upgrade] Vault manifest migration completed locally but has not reached the server yet.');
+ }
+
+ // The native store holds a rebuilt vault, so re-open it before any page queries the new schema.
+ await dbContext.unlockVault();
+ await dbContext.refreshSyncState();
+
+ try {
+ await NativeVaultManager.registerCredentialIdentities();
+ } catch (err) {
+ console.warn('[Upgrade] Failed to register credential identities:', err);
+ }
+
+ /*
+ * 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;
}
- };
+
+ finish();
+ }, [dbContext, failStep, finish, t]);
/**
- * Perform the actual vault upgrade.
+ * Ask the native engine what the manifest migration would do, and either prompt the user or run it.
*/
- const performUpgrade = async (): Promise<void> => {
+ const startManifestUpgrade = useCallback(async (): Promise<void> => {
+ const pending = await NativeVaultManager.getVaultMigrationStatus();
+
+ if (pending === MIGRATION_STATUS_STORAGE_FORMAT_UPGRADE) {
+ setKind(UpgradeKind.StorageFormat);
+ setStage('consent');
+ return;
+ }
+
+ // A local schema rebuild, or nothing left to do at all: both are safe to run unattended.
+ await runManifestMigration(UpgradeKind.SchemaRebuild);
+ }, [runManifestMigration]);
+
+ /**
+ * Walk the legacy sqlite-blob upgrade chain against the local vault. The chain brings the vault to 2.0.0, the
+ * point at which the manifest migration becomes applicable, so that is classified right after; its push carries
+ * the chain's changes along.
+ */
+ const performLegacyUpgrade = useCallback(async (): Promise<void> => {
if (!sqliteClient || !currentVersion || !latestVersion) {
showAlert(t('common.error'), t('upgrade.alerts.unableToGetVersionInfo'));
return;
}
// Ensure vault is unlocked before upgrade
- const isUnlocked = await NativeVaultManager.isVaultUnlocked();
- if (!isUnlocked) {
+ if (!(await NativeVaultManager.isVaultUnlocked())) {
try {
await NativeVaultManager.unlockVault();
- } catch (error) {
- console.error('Failed to unlock vault for upgrade:', error);
+ } catch (err) {
+ console.error('Failed to unlock vault for upgrade:', err);
showAlert(t('common.error'), t('auth.errors.enterPassword'));
return;
}
}
- setIsLoading(true);
+ setError(null);
+ setErrorDetail(null);
+ setStage('upgrading');
setUpgradeStatus(t('upgrade.status.preparingUpgrade'));
try {
// Get upgrade SQL commands from vault library
- const vaultSqlGenerator = new VaultSqlGenerator();
- const upgradeResult = vaultSqlGenerator.getUpgradeVaultSql(currentVersion.revision, latestVersion.revision);
+ const upgradeResult = new VaultSqlGenerator().getUpgradeVaultSql(currentVersion.revision, latestVersion.revision);
if (!upgradeResult.success) {
throw new Error(upgradeResult.error ?? t('upgrade.alerts.upgradeFailed'));
}
- if (upgradeResult.sqlCommands.length === 0) {
- // No upgrade needed, vault is already up to date
- setUpgradeStatus(t('upgrade.status.vaultAlreadyUpToDate'));
- await new Promise(resolve => setTimeout(resolve, 1000));
- await handleUpgradeSuccess();
- return;
- }
-
/*
- * Use the useVaultMutate hook to handle the upgrade and vault upload.
* IMPORTANT: Do NOT wrap migration SQL in beginTransaction/commitTransaction!
* The migration SQL contains PRAGMA foreign_keys statements that MUST be executed
* outside of any transaction to take effect. The SQL handles its own transactions.
*/
- await executeVaultMutation(async () => {
- // Execute each SQL command (each migration script handles its own transactions)
- setUpgradeStatus(t('upgrade.status.applyingDatabaseMigrations'));
- for (let i = 0; i < upgradeResult.sqlCommands.length; i++) {
- const sqlCommand = upgradeResult.sqlCommands[i];
- setUpgradeStatus(t('upgrade.status.applyingMigration', { current: i + 1, total: upgradeResult.sqlCommands.length }));
-
- try {
- await NativeVaultManager.executeRaw(sqlCommand);
- } catch (error) {
- console.error(`Error executing SQL command ${i + 1}:`, sqlCommand, error);
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- throw new Error(`${t('upgrade.alerts.failedToApplyMigration', { current: i + 1, total: upgradeResult.sqlCommands.length })}\n\nDetails: ${errorMessage}`);
- }
+ setUpgradeStatus(t('upgrade.status.applyingDatabaseMigrations'));
+ for (let i = 0; i < upgradeResult.sqlCommands.length; i++) {
+ setUpgradeStatus(t('upgrade.status.applyingMigration', { current: i + 1, total: upgradeResult.sqlCommands.length }));
+ try {
+ await NativeVaultManager.executeRaw(upgradeResult.sqlCommands[i]);
+ } catch (err) {
+ console.error(`Error executing SQL command ${i + 1}:`, upgradeResult.sqlCommands[i], err);
+ const detail = err instanceof Error ? err.message : 'Unknown error';
+ throw new Error(`${t('upgrade.alerts.failedToApplyMigration', { current: i + 1, total: upgradeResult.sqlCommands.length })}\n\nDetails: ${detail}`);
}
+ }
- /*
- * Persist the database to encrypted storage and mark as dirty.
- * This is needed because we're not using beginTransaction/commitTransaction.
- * The executeVaultMutation hook will handle the upload.
- */
+ if (upgradeResult.sqlCommands.length > 0) {
+ // Persist the upgraded database as a pending change; the manifest migration push that follows carries it.
setUpgradeStatus(t('upgrade.status.committingChanges'));
await NativeVaultManager.persistAndMarkDirty();
- }, {
- skipSyncCheck: true, // Skip sync check during upgrade to prevent loop
- /**
- * Handle successful upgrade completion.
- */
- onSuccess: () => {
- void handleUpgradeSuccess();
- },
- /**
- * Handle upgrade error.
- */
- onError: (error: Error) => {
- console.error('Upgrade failed:', error);
- showAlert(t('upgrade.alerts.upgradeFailed'), error.message);
- }
- });
+ await dbContext.unlockVault();
+ }
+ await startManifestUpgrade();
} catch (err) {
console.error('Upgrade failed:', err);
- showAlert(
- t('upgrade.alerts.upgradeFailed'),
- err instanceof Error ? err.message : t('common.errors.unknownError')
- );
- } finally {
- setIsLoading(false);
- setUpgradeStatus(t('upgrade.status.preparingUpgrade'));
+ setError(err instanceof Error ? err.message : t('common.errors.unknownError'));
+ setStage('consent');
}
- };
+ }, [sqliteClient, currentVersion, latestVersion, dbContext, showAlert, startManifestUpgrade, 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 {
- // Re-unlock the vault to ensure React Native sees the upgraded database
- setUpgradeStatus(t('auth.unlocking'));
- const unlockSuccess = await dbContext.unlockVault();
+ useEffect(() => {
+ if (!sqliteClient || hasStarted.current) {
+ return;
+ }
+ hasStarted.current = true;
- if (unlockSuccess) {
- // Mark database as available after successful unlock
- dbContext.setDatabaseAvailable();
- }
+ /**
+ * Classify the pending upgrade and show or run it.
+ */
+ const classify = async (): Promise<void> => {
+ try {
+ if (await dbContext.requiresLegacySqliteBlobMigration()) {
+ setKind(UpgradeKind.LegacySqliteBlob);
+ await loadVersionInfo();
+ setStage('consent');
+ return;
+ }
- // Sync vault to check for updates and verify server connection
- await syncVault({
- /**
- * Handle the status update.
- */
- onStatus: (message) => setUpgradeStatus(message),
- /**
- * Handle successful vault sync and navigate to items.
- */
- onSuccess: () => {
- router.replace('/(tabs)/items');
- },
- /**
- * Handle sync error and still navigate to items.
- */
- onError: (error) => {
- console.error('Sync error after upgrade:', error);
- // Still navigate to items even if sync fails
- router.replace('/(tabs)/items');
+ await startManifestUpgrade();
+ } catch (err) {
+ if (err instanceof VaultVersionIncompatibleError) {
+ await logoutForced();
+ return;
}
- });
- } catch (error) {
- console.error('Error during post-upgrade flow:', error);
- // Navigate to items anyway
- router.replace('/(tabs)/items');
+ console.error('Failed to determine the pending vault upgrade:', err);
+ setError(err instanceof Error ? err.message : t('common.errors.unknownError'));
+ setStage('consent');
+ }
+ };
+
+ void classify();
+ }, [sqliteClient, dbContext, loadVersionInfo, startManifestUpgrade, logoutForced, t]);
+
+ /**
+ * Handle the upgrade button, which runs whichever upgrade this vault is waiting on.
+ */
+ 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()) {
+ showConfirm(
+ t('upgrade.alerts.selfHostedServer'),
+ t('upgrade.alerts.selfHostedWarning'),
+ t('upgrade.alerts.continueUpgrade'),
+ performLegacyUpgrade
+ );
+ return;
}
+
+ await performLegacyUpgrade();
};
/**
@@ -329,6 +381,16 @@ export default function UpgradeScreen() : React.ReactNode {
currentVersionValue: {
color: colors.primary,
},
+ errorDetail: {
+ color: colors.textMuted,
+ fontSize: 12,
+ marginTop: 4,
+ },
+ errorText: {
+ color: colors.red,
+ fontSize: 14,
+ marginBottom: 16,
+ },
gradientContainer: {
height: Dimensions.get('window').height * 0.4,
left: 0,
@@ -395,6 +457,24 @@ export default function UpgradeScreen() : React.ReactNode {
opacity: 0.7,
textAlign: 'center',
},
+ successIcon: {
+ alignItems: 'center',
+ marginBottom: 16,
+ },
+ successText: {
+ color: colors.text,
+ fontSize: 14,
+ marginBottom: 24,
+ opacity: 0.7,
+ textAlign: 'center',
+ },
+ successTitle: {
+ color: colors.text,
+ fontSize: 20,
+ fontWeight: '600',
+ marginBottom: 12,
+ textAlign: 'center',
+ },
username: {
color: colors.text,
fontSize: 18,
@@ -436,73 +516,114 @@ export default function UpgradeScreen() : React.ReactNode {
fontSize: 16,
fontWeight: 'bold',
},
+ warningContainer: {
+ backgroundColor: colors.background,
+ borderRadius: 8,
+ marginBottom: 16,
+ padding: 16,
+ },
+ warningText: {
+ color: colors.text,
+ fontSize: 14,
+ opacity: 0.8,
+ },
});
- return (
- <ThemedView style={styles.container}>
- {(isLoading || isVaultMutationLoading || isSyncingOnLoad) ? (
+ if (stage === 'classifying' || stage === 'upgrading') {
+ return (
+ <ThemedView style={styles.container}>
<View style={styles.loadingContainer}>
- <LoadingIndicator status={syncStatus || upgradeStatus} />
+ <LoadingIndicator status={stage === 'upgrading' ? upgradeStatus : t('upgrade.status.preparingUpgrade')} />
</View>
- ) : (
- <KeyboardAvoidingView
- behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
- style={styles.keyboardAvoidingView}
- >
- <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
- <ScrollView
- contentContainerStyle={styles.scrollContent}
- keyboardShouldPersistTaps="handled"
- >
- <LinearGradient
- colors={[colors.loginHeader, colors.background]}
- style={styles.gradientContainer}
- />
- <View style={styles.mainContent}>
- <View style={styles.headerSection}>
- <View style={styles.logoContainer}>
- <Logo width={80} height={80} />
- <Text style={styles.appName}>{t('upgrade.title')}</Text>
+ </ThemedView>
+ );
+ }
+
+ return (
+ <ThemedView style={styles.container}>
+ <KeyboardAvoidingView
+ behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
+ style={styles.keyboardAvoidingView}
+ >
+ <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
+ <ScrollView
+ contentContainerStyle={styles.scrollContent}
+ keyboardShouldPersistTaps="handled"
+ >
+ <LinearGradient
+ colors={[colors.loginHeader, colors.background]}
+ style={styles.gradientContainer}
+ />
+ <View style={styles.mainContent}>
+ <View style={styles.headerSection}>
+ <View style={styles.logoContainer}>
+ <Logo width={80} height={80} />
+ <Text style={styles.appName}>{t('upgrade.title')}</Text>
+ </View>
+ </View>
+ {stage === 'success' ? (
+ <View style={styles.content}>
+ <View style={styles.successIcon}>
+ <MaterialIcons name="check-circle" size={48} color={colors.greenBackground} />
</View>
+ <ThemedText style={styles.successTitle}>{t('upgrade.successTitle')}</ThemedText>
+ <ThemedText style={styles.successText}>{t('upgrade.successOtherDevices')}</ThemedText>
+ <RobustPressable style={styles.button} onPress={finish}>
+ <ThemedText style={styles.buttonText}>{t('common.continue')}</ThemedText>
+ </RobustPressable>
</View>
+ ) : (
<View style={styles.content}>
<View style={styles.avatarContainer}>
<Avatar />
<ThemedText style={styles.username}>{username}</ThemedText>
</View>
<ThemedText style={styles.subtitle}>{t('upgrade.subtitle')}</ThemedText>
- <View style={styles.versionContainer}>
- <View style={styles.versionHeader}>
- <ThemedText style={styles.versionTitle}>{t('upgrade.versionInformation')}</ThemedText>
- <RobustPressable
- style={styles.helpButton}
- onPress={showVersionDialog}
- >
- <ThemedText style={styles.helpButtonText}>?</ThemedText>
- </RobustPressable>
+
+ {error && (
+ <View>
+ <ThemedText style={styles.errorText}>{error}</ThemedText>
+ {errorDetail && <ThemedText style={styles.errorDetail}>{errorDetail}</ThemedText>}
</View>
- <View style={styles.versionRow}>
- <ThemedText style={styles.versionLabel}>{t('upgrade.yourVault')}</ThemedText>
- <ThemedText style={[styles.versionValue, styles.currentVersionValue]}>
- {currentVersion?.compatibleUpToVersion ?? '...'}
- </ThemedText>
+ )}
+
+ {kind === UpgradeKind.LegacySqliteBlob && (
+ <View style={styles.versionContainer}>
+ <View style={styles.versionHeader}>
+ <ThemedText style={styles.versionTitle}>{t('upgrade.versionInformation')}</ThemedText>
+ <RobustPressable
+ style={styles.helpButton}
+ onPress={showVersionDialog}
+ >
+ <ThemedText style={styles.helpButtonText}>?</ThemedText>
+ </RobustPressable>
+ </View>
+ <View style={styles.versionRow}>
+ <ThemedText style={styles.versionLabel}>{t('upgrade.yourVault')}</ThemedText>
+ <ThemedText style={[styles.versionValue, styles.currentVersionValue]}>
+ {currentVersion?.compatibleUpToVersion ?? '...'}
+ </ThemedText>
+ </View>
+ <View style={styles.versionRow}>
+ <ThemedText style={styles.versionLabel}>{t('upgrade.newVersion')}</ThemedText>
+ <ThemedText style={[styles.versionValue, styles.latestVersionValue]}>
+ {latestVersion?.releaseVersion ?? '...'}
+ </ThemedText>
+ </View>
</View>
- <View style={styles.versionRow}>
- <ThemedText style={styles.versionLabel}>{t('upgrade.newVersion')}</ThemedText>
- <ThemedText style={[styles.versionValue, styles.latestVersionValue]}>
- {latestVersion?.releaseVersion ?? '...'}
- </ThemedText>
+ )}
+
+ {kind === UpgradeKind.StorageFormat && (
+ <View style={styles.warningContainer}>
+ <ThemedText style={styles.warningText}>{t('upgrade.otherDevicesWarning', { version: AppInfo.API_VERSION })}</ThemedText>
</View>
- </View>
+ )}
<RobustPressable
style={styles.button}
onPress={handleUpgrade}
- disabled={isLoading || isVaultMutationLoading}
>
- <ThemedText style={styles.buttonText}>
- {isLoading || isVaultMutationLoading ? (syncStatus || t('upgrade.upgrading')) : t('upgrade.upgrade')}
- </ThemedText>
+ <ThemedText style={styles.buttonText}>{t('upgrade.upgrade')}</ThemedText>
</RobustPressable>
<RobustPressable
@@ -512,11 +633,11 @@ export default function UpgradeScreen() : React.ReactNode {
<ThemedText style={styles.logoutButtonText}>{t('upgrade.logout')}</ThemedText>
</RobustPressable>
</View>
- </View>
- </ScrollView>
- </TouchableWithoutFeedback>
- </KeyboardAvoidingView>
- )}
+ )}
+ </View>
+ </ScrollView>
+ </TouchableWithoutFeedback>
+ </KeyboardAvoidingView>
</ThemedView>
);
-}
\ No newline at end of file
+}
diff --git a/apps/mobile-app/context/DbContext.tsx b/apps/mobile-app/context/DbContext.tsx
index bc258cef7..127026aad 100644
--- a/apps/mobile-app/context/DbContext.tsx
+++ b/apps/mobile-app/context/DbContext.tsx
@@ -27,6 +27,7 @@ type DbContextType = {
refreshSyncState: () => Promise<void>;
storeEncryptionKey: (derivedKey: string) => Promise<void>;
storeEncryptionKeyDerivationParams: (keyDerivationParams: EncryptionKeyDerivationParams) => Promise<void>;
+ requiresLegacySqliteBlobMigration: () => Promise<boolean>;
hasPendingMigrations: () => Promise<boolean>;
clearDatabase: () => void;
getVaultMetadata: () => Promise<VaultMetadata | null>;
@@ -119,14 +120,24 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
}, [sqliteClient]);
/**
- * Check if there are any pending migrations. This method also checks if the current vault version is known to the client.
- * If the current vault version is not known to the client, the method will throw an exception which causes the app to logout.
+ * Whether the vault still has to walk the legacy sqlite-blob upgrade chain (pre-2.0.0). Throws when the vault version
+ * is unknown to this app, which makes the caller log out.
+ */
+ const requiresLegacySqliteBlobMigration = useCallback(async () => {
+ return await sqliteClient.requiresLegacySqliteBlobMigration();
+ }, [sqliteClient]);
+
+ /**
+ * Whether the vault has to go through the upgrade page before any other page may query it: the legacy sqlite-blob
+ * chain, a schema older than this app's, or an account without its key hierarchy yet (the manifest migration). The
+ * upgrade page classifies which applies. Throws when the vault version is unknown to this app, which makes the caller log out.
*/
const hasPendingMigrations = useCallback(async () => {
- const currentVersion = await sqliteClient.getDatabaseVersion();
- const latestVersion = await sqliteClient.getLatestDatabaseVersion();
+ if (await sqliteClient.requiresLegacySqliteBlobMigration()) {
+ return true;
+ }
- return currentVersion.revision < latestVersion.revision;
+ return await sqliteClient.requiresSchemaMigration() || (await NativeVaultManager.getAccountKeyChain()) === null;
}, [sqliteClient]);
const checkStoredVault = useCallback(async () => {
@@ -301,6 +312,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
setIsOffline,
shouldSuppressEmailErrors,
refreshSyncState,
+ requiresLegacySqliteBlobMigration,
hasPendingMigrations,
clearDatabase,
getVaultMetadata,
@@ -311,7 +323,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
storeEncryptionKeyDerivationParams,
checkStoredVault,
setDatabaseAvailable,
- }), [sqliteClient, dbInitialized, dbAvailable, isDirty, isSyncing, isUploading, isOffline, setIsSyncing, setIsUploading, setIsOffline, shouldSuppressEmailErrors, refreshSyncState, hasPendingMigrations, clearDatabase, getVaultMetadata, testDatabaseConnection, verifyEncryptionKey, unlockVault, storeEncryptionKey, storeEncryptionKeyDerivationParams, checkStoredVault, setDatabaseAvailable]);
+ }), [sqliteClient, dbInitialized, dbAvailable, isDirty, isSyncing, isUploading, isOffline, setIsSyncing, setIsUploading, setIsOffline, shouldSuppressEmailErrors, refreshSyncState, requiresLegacySqliteBlobMigration, hasPendingMigrations, clearDatabase, getVaultMetadata, testDatabaseConnection, verifyEncryptionKey, unlockVault, storeEncryptionKey, storeEncryptionKeyDerivationParams, checkStoredVault, setDatabaseAvailable]);
return (
<DbContext.Provider value={contextValue}>
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index 32f086704..72da528d7 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -37,8 +37,11 @@ export interface Spec extends TurboModule {
// Store the encrypted vault blob for persistence and which is also accessed by the native autofill extensions.
storeEncryptedDatabase(base64EncryptedDb: string): Promise<void>;
- // Vault sync
- syncVaultWithServer(): Promise<{ success: boolean; action: 'uploaded' | 'downloaded' | 'merged' | 'already_in_sync' | 'error'; newRevision: number; wasOffline: boolean; error: string | null; errorMessage: string | null }>;
+ // Vault sync. A vault that still has to be upgraded is reported through the two *Required flags and not synced.
+ syncVaultWithServer(): Promise<{ success: boolean; action: 'uploaded' | 'downloaded' | 'merged' | 'already_in_sync' | 'error'; newRevision: number; wasOffline: boolean; error: string | null; errorMessage: string | null; sqliteBlobUpgradeRequired: boolean; manifestMigrationRequired: boolean }>;
+
+ getVaultMigrationStatus(): Promise<string>;
+ migrateVaultManifest(): Promise<{ success: boolean; pushed: boolean; error: string | null; errorMessage: string | null }>;
// Quick check if sync is needed
checkSyncStatus(): Promise<{ success: boolean; hasNewerVault: boolean; hasDirtyChanges: boolean; isOffline: boolean; requiresLogout: boolean; errorKey: string | null }>;
diff --git a/apps/mobile-app/utils/SqliteClient.ts b/apps/mobile-app/utils/SqliteClient.ts
index 46ea873de..3abf25537 100644
--- a/apps/mobile-app/utils/SqliteClient.ts
+++ b/apps/mobile-app/utils/SqliteClient.ts
@@ -9,6 +9,7 @@ import { PasskeyRepository } from '@aliasvault/client/database/repositories/Pass
import { SettingsRepository } from '@aliasvault/client/database/repositories/SettingsRepository';
import { VaultSqlGenerator, VaultVersion, checkVersionCompatibility, extractVersionFromMigrationId } from '@aliasvault/vault';
import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
+import { VaultCodec } from '@aliasvault/client/sync/VaultCodec';
import NativeVaultManager from '@/specs/NativeVaultManager';
import { NativeDatabaseClient } from '@/platform/NativeDatabaseClient';
@@ -218,19 +219,12 @@ class SqliteClient {
* Uses semantic versioning to allow backwards-compatible minor/patch versions.
*/
public async getDatabaseVersion(): Promise<VaultVersion> {
- // Query the migrations history table for the latest migration
- const results = await this.database.executeQuery<{ MigrationId: string }>(`
- SELECT MigrationId
- FROM __EFMigrationsHistory
- ORDER BY MigrationId DESC
- LIMIT 1`);
-
- if (results.length === 0) {
+ const migrationId = await this.getLatestMigrationId();
+ if (!migrationId) {
throw new Error('No migrations found');
}
// Extract version from migration ID (e.g., "20240917191243_1.4.1-RenameAttachmentsPlural" -> "1.4.1")
- const migrationId = results[0].MigrationId;
const databaseVersion = extractVersionFromMigrationId(migrationId);
if (!databaseVersion) {
@@ -275,6 +269,50 @@ class SqliteClient {
const allVersions = vaultSqlGenerator.getAllVersions();
return allVersions[allVersions.length - 1];
}
+
+ /**
+ * Whether the vault still has to walk the sqlite-blob upgrade chain (VAULT_VERSIONS, frozen at 2.0.0) via the upgrade
+ * page before it is eligible for anything else. Throws VaultVersionIncompatibleError for a vault newer than this app.
+ *
+ * TODO: this is the legacy sqlite-blob migration path; delete once all users have migrated.
+ */
+ public async requiresLegacySqliteBlobMigration(): Promise<boolean> {
+ const currentVersion = await this.getDatabaseVersion();
+ const latestVersion = await this.getLatestDatabaseVersion();
+ return currentVersion.revision < latestVersion.revision;
+ }
+
+ /**
+ * Whether the local database schema is older than the current full schema (COMPLETE_SCHEMA_SQL), which the manifest
+ * migration rebuilds. Not applicable while the sqlite-blob chain is still pending.
+ */
+ public async requiresSchemaMigration(): Promise<boolean> {
+ if (await this.requiresLegacySqliteBlobMigration()) {
+ return false;
+ }
+
+ const localMigrationId = await this.getLatestMigrationId();
+ const schemaMigrationId = VaultCodec.getSchemaMigrationId(new VaultSqlGenerator().getCompleteSchemaSql());
+
+ // An unstamped database or an unreadable schema constant gives no evidence of staleness; don't block on a guess.
+ if (!localMigrationId || !schemaMigrationId) {
+ return false;
+ }
+
+ return localMigrationId < schemaMigrationId;
+ }
+
+ /**
+ * The latest EF migration id the vault is stamped with, or null when it carries none.
+ */
+ private async getLatestMigrationId(): Promise<string | null> {
+ const results = await this.database.executeQuery<{ MigrationId: string }>(`
+ SELECT MigrationId
+ FROM __EFMigrationsHistory
+ ORDER BY MigrationId DESC
+ LIMIT 1`);
+ return results[0]?.MigrationId ?? null;
+ }
}
export default SqliteClient;