Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Make iOS vault init more robust to prevent cold boot errors (#520)
Leendert de Borst5f4901323598
diff --git a/apps/mobile-app/context/DbContext.tsx b/apps/mobile-app/context/DbContext.tsxindex 1dae0c3a1..68d05d3e3 100644--- a/apps/mobile-app/context/DbContext.tsx+++ b/apps/mobile-app/context/DbContext.tsx@@ -49,8 +49,11 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }try {await NativeVaultManager.unlockVault();return true;- } catch (error) {+ } catch (error: any) {console.error('Failed to unlock vault:', error);+ if (error?.code === 'DATABASE_SETUP_ERROR') {+ console.error('Database setup error:', error.message);+ }return false;}}, []);diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.tsindex 88c8690c3..75ab5b021 100644--- a/apps/mobile-app/hooks/useVaultSync.ts+++ b/apps/mobile-app/hooks/useVaultSync.ts@@ -163,13 +163,20 @@ export const useVaultSync = () : {}return hasNewVault;- } catch (err) {+ } catch (err: any) {if (err instanceof VaultVersionIncompatibleError) {await app.logout(t(err.message));return false;}+ // Log detailed error information for database setup failures+ if (err?.code === 'DATABASE_SETUP_ERROR') {+ console.error('Database setup error during unlock:', err.message);+ throw new Error(`${t('vault.errors.vaultDecryptFailed')}: ${err.message}`);+ }+// Vault could not be unlocked+ console.error('Failed to unlock vault:', err);throw new Error(t('vault.errors.vaultDecryptFailed'));}} catch (err) {diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swiftindex 8e735e519..69a20f419 100644--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift@@ -240,17 +240,22 @@ public class VaultManager: NSObject {do {try vaultStore.unlockVault()resolve(true)- } catch {- // Check if the error is related to Face ID or decryption- if let nsError = error as NSError? {- if nsError.domain == "VaultStore" {- // These are our known error codes for initialization failures- if nsError.code == 1 || nsError.code == 2 || nsError.code == 8 || nsError.code == 10 {- resolve(false)- return- }+ } catch let error as NSError {+ if error.domain == "VaultStore" {+ // These are our known error codes for initialization failures (non-critical)+ if error.code == 1 || error.code == 2 || error.code == 8 || error.code == 10 {+ resolve(false)+ return+ }++ // Pass through detailed error messages for database setup failures (codes 11-18)+ if error.code >= 11 && error.code <= 18 {+ reject("DATABASE_SETUP_ERROR", error.localizedDescription, error)+ return}}++ // Default error handlingreject("INIT_ERROR", "Failed to unlock vault: \(error.localizedDescription)", error)}}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swiftindex c86473422..617f369f4 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift@@ -35,9 +35,21 @@ extension VaultStore {do {let decryptedDbBase64 = try decrypt(data: encryptedDbData)try setupDatabaseWithDecryptedData(decryptedDbBase64)- } catch {- print("Decryption failed: \(error)")- throw NSError(domain: "VaultStore", code: 5, userInfo: [NSLocalizedDescriptionKey: "Could not unlock vault"])+ } catch let error as NSError {+ // If it's already a VaultStore error with detailed info, pass it through+ if error.domain == "VaultStore" && error.code >= 10 {+ throw error+ }++ // Otherwise, it's a decryption error+ throw NSError(+ domain: "VaultStore",+ code: 5,+ userInfo: [+ NSLocalizedDescriptionKey: "Could not unlock vault: Decryption failed",+ NSUnderlyingErrorKey: error+ ]+ )}}@@ -56,34 +68,188 @@ extension VaultStore {/// Setup the database with the decrypted dataprivate func setupDatabaseWithDecryptedData(_ decryptedDbBase64: Data) throws {+ // Step 1: Decode base64guard let decryptedDbData = Data(base64Encoded: decryptedDbBase64) else {- throw NSError(domain: "VaultStore", code: 10, userInfo: [NSLocalizedDescriptionKey: "Failed to decode base64 data after decryption"])+ throw NSError(+ domain: "VaultStore",+ code: 10,+ userInfo: [NSLocalizedDescriptionKey: "Database setup failed: Could not decode base64 data after decryption"]+ )}+ // Step 2: Write decrypted data to temp filelet tempDbPath = FileManager.default.temporaryDirectory.appendingPathComponent("temp_db.sqlite")- try decryptedDbData.write(to: tempDbPath)+ do {+ try decryptedDbData.write(to: tempDbPath)+ } catch {+ throw NSError(+ domain: "VaultStore",+ code: 11,+ userInfo: [+ NSLocalizedDescriptionKey: "Database setup failed: Could not write decrypted data to temp file",+ NSUnderlyingErrorKey: error+ ]+ )+ }++ // Step 3: Create in-memory database connection+ do {+ self.dbConnection = try Connection(":memory:")+ } catch {+ try? FileManager.default.removeItem(at: tempDbPath)+ throw NSError(+ domain: "VaultStore",+ code: 12,+ userInfo: [+ NSLocalizedDescriptionKey: "Database setup failed: Could not create in-memory database connection",+ NSUnderlyingErrorKey: error+ ]+ )+ }- self.dbConnection = try Connection(":memory:")+ // Step 4: Attach temp database+ do {+ try self.dbConnection?.attach(.uri(tempDbPath.path, parameters: [.mode(.readOnly)]), as: "source")+ } catch {+ try? FileManager.default.removeItem(at: tempDbPath)+ throw NSError(+ domain: "VaultStore",+ code: 13,+ userInfo: [+ NSLocalizedDescriptionKey: "Database setup failed: Could not attach temp database (file may be corrupt)",+ NSUnderlyingErrorKey: error+ ]+ )+ }- try self.dbConnection?.attach(.uri(tempDbPath.path, parameters: [.mode(.readOnly)]), as: "source")- try self.dbConnection?.execute("BEGIN TRANSACTION")+ // Step 5: Begin transaction+ do {+ try self.dbConnection?.execute("BEGIN TRANSACTION")+ } catch {+ try? FileManager.default.removeItem(at: tempDbPath)+ throw NSError(+ domain: "VaultStore",+ code: 14,+ userInfo: [+ NSLocalizedDescriptionKey: "Database setup failed: Could not begin transaction",+ NSUnderlyingErrorKey: error+ ]+ )+ }- let tables = try self.dbConnection?.prepare("SELECT name FROM source.sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")- for table in tables! {- guard let tableName = table[0] as? String else {- print("Warning: Unexpected value in table name column")- continue+ // Step 6: Copy tables+ do {+ // Collect table names first, then iterate+ // This ensures the prepared statement is finalized before we start creating tables+ var tableNames: [String] = []+ let tables = try self.dbConnection?.prepare("SELECT name FROM source.sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")+ for table in tables! {+ guard let tableName = table[0] as? String else {+ continue+ }+ tableNames.append(tableName)+ }++ // Now create tables from the collected names+ for tableName in tableNames {+ try self.dbConnection?.execute("CREATE TABLE \(tableName) AS SELECT * FROM source.\(tableName)")}- try self.dbConnection?.execute("CREATE TABLE \(tableName) AS SELECT * FROM source.\(tableName)")+ } catch {+ try? self.dbConnection?.execute("ROLLBACK")+ try? FileManager.default.removeItem(at: tempDbPath)+ throw NSError(+ domain: "VaultStore",+ code: 15,+ userInfo: [+ NSLocalizedDescriptionKey: "Database setup failed: Could not copy tables from source database",+ NSUnderlyingErrorKey: error+ ]+ )}- try self.dbConnection?.execute("COMMIT")- try self.dbConnection?.execute("DETACH DATABASE source")+ // Step 7: Commit transaction+ do {+ try self.dbConnection?.execute("COMMIT")+ } catch {+ try? self.dbConnection?.execute("ROLLBACK")+ try? FileManager.default.removeItem(at: tempDbPath)+ throw NSError(+ domain: "VaultStore",+ code: 16,+ userInfo: [+ NSLocalizedDescriptionKey: "Database setup failed: Could not commit transaction",+ NSUnderlyingErrorKey: error+ ]+ )+ }+ // Step 8: Detach source database with retry logic+ var detachSuccess = false+ var lastDetachError: Error?++ for attempt in 1...5 {+ do {+ // First check if source database is still attached+ let attachedDbs = try self.dbConnection?.prepare("PRAGMA database_list")+ var isSourceAttached = false+ if let attachedDbs = attachedDbs {+ for db in attachedDbs {+ if let dbName = db[1] as? String, dbName == "source" {+ isSourceAttached = true+ break+ }+ }+ }++ if !isSourceAttached {+ detachSuccess = true+ break+ }++ // Close any open statements or cursors+ try self.dbConnection?.execute("PRAGMA optimize")++ // Try to detach+ try self.dbConnection?.execute("DETACH DATABASE source")+ detachSuccess = true+ break+ } catch {+ lastDetachError = error+ if attempt < 5 {+ Thread.sleep(forTimeInterval: Double(attempt) * 0.01)+ }+ }+ }++ if !detachSuccess {+ try? FileManager.default.removeItem(at: tempDbPath)+ throw NSError(+ domain: "VaultStore",+ code: 17,+ userInfo: [+ NSLocalizedDescriptionKey: "Database setup failed: Could not detach source database after 5 attempts",+ NSUnderlyingErrorKey: lastDetachError as Any+ ]+ )+ }++ // Clean up temp filetry? FileManager.default.removeItem(at: tempDbPath)- try self.dbConnection?.execute("PRAGMA journal_mode = WAL")- try self.dbConnection?.execute("PRAGMA synchronous = NORMAL")- try self.dbConnection?.execute("PRAGMA foreign_keys = ON")+ // Step 9: Set pragmas+ do {+ try self.dbConnection?.execute("PRAGMA journal_mode = WAL")+ try self.dbConnection?.execute("PRAGMA synchronous = NORMAL")+ try self.dbConnection?.execute("PRAGMA foreign_keys = ON")+ } catch {+ throw NSError(+ domain: "VaultStore",+ code: 18,+ userInfo: [+ NSLocalizedDescriptionKey: "Database setup failed: Could not set database pragmas",+ NSUnderlyingErrorKey: error+ ]+ )+ }}}