Skip to content

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

Move vault sync/mutate to swift/kotlin layer (#520)

Leendert de Borstafab20f59bb3
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 d9e7072a9..509e0b32d 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
@@ -1031,4 +1031,152 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
Log.d(TAG, "registerCredentialIdentities: Not yet implemented on Android")
promise.resolve(null)
}
+
+ // MARK: - Username Management
+
+ /**
+ * Set the username
+ * @param username The username to set
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun setUsername(username: String, promise: Promise) {
+ try {
+ // TODO: Implement username storage in VaultStore (similar to iOS)
+ // vaultStore.setUsername(username)
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error setting username", e)
+ promise.reject("ERR_SET_USERNAME", "Failed to set username: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Get the username
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun getUsername(promise: Promise) {
+ try {
+ // TODO: Implement username retrieval from VaultStore (similar to iOS)
+ // val username = vaultStore.getUsername()
+ // promise.resolve(username)
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error getting username", e)
+ promise.reject("ERR_GET_USERNAME", "Failed to get username: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Clear the username
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun clearUsername(promise: Promise) {
+ try {
+ // TODO: Implement username clearing in VaultStore (similar to iOS)
+ // vaultStore.clearUsername()
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error clearing username", e)
+ promise.reject("ERR_CLEAR_USERNAME", "Failed to clear username: ${e.message}", e)
+ }
+ }
+
+ // MARK: - Offline Mode Management
+
+ /**
+ * Set offline mode flag
+ * @param isOffline Whether app is offline
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun setOfflineMode(isOffline: Boolean, promise: Promise) {
+ try {
+ // TODO: Implement offline mode storage in VaultStore (similar to iOS)
+ // vaultStore.setOfflineMode(isOffline)
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error setting offline mode", e)
+ promise.reject("ERR_SET_OFFLINE_MODE", "Failed to set offline mode: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Get offline mode flag
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun getOfflineMode(promise: Promise) {
+ try {
+ // TODO: Implement offline mode retrieval from VaultStore (similar to iOS)
+ // val isOffline = vaultStore.getOfflineMode()
+ // promise.resolve(isOffline)
+ promise.resolve(false)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error getting offline mode", e)
+ promise.reject("ERR_GET_OFFLINE_MODE", "Failed to get offline mode: ${e.message}", e)
+ }
+ }
+
+ // MARK: - Vault Sync and Mutate
+
+ /**
+ * Sync vault with server
+ * Returns true if new vault was downloaded
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun syncVault(promise: Promise) {
+ CoroutineScope(Dispatchers.IO).launch {
+ try {
+ // TODO: Implement vault sync in VaultStore (similar to iOS)
+ // This should:
+ // 1. Call WebApiService to get Auth/status
+ // 2. Compare vault revisions
+ // 3. Download vault if server has newer version
+ // 4. Store encrypted vault and update revision
+ // 5. Return true if new vault downloaded, false otherwise
+ //
+ // val hasNewVault = vaultStore.syncVault(webApiService)
+ withContext(Dispatchers.Main) {
+ promise.resolve(false)
+ }
+ } catch (e: Exception) {
+ withContext(Dispatchers.Main) {
+ Log.e(TAG, "Error syncing vault", e)
+ promise.reject("ERR_SYNC_VAULT", "Failed to sync vault: ${e.message}", e)
+ }
+ }
+ }
+ }
+
+ /**
+ * Mutate vault (upload changes to server)
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun mutateVault(promise: Promise) {
+ CoroutineScope(Dispatchers.IO).launch {
+ try {
+ // TODO: Implement vault mutate in VaultStore (similar to iOS)
+ // This should:
+ // 1. Prepare vault for upload (assemble metadata)
+ // 2. POST vault to server
+ // 3. Update local revision number
+ // 4. Clear offline mode on success
+ //
+ // vaultStore.mutateVault(webApiService)
+ withContext(Dispatchers.Main) {
+ promise.resolve(null)
+ }
+ } catch (e: Exception) {
+ withContext(Dispatchers.Main) {
+ Log.e(TAG, "Error mutating vault", e)
+ promise.reject("ERR_MUTATE_VAULT", "Failed to mutate vault: ${e.message}", e)
+ }
+ }
+ }
+ }
}
diff --git a/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx b/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx
index 6e51235c5..1663b28bd 100644
--- a/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx
+++ b/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx
@@ -349,35 +349,57 @@ export default function AddEditCredentialScreen() : React.ReactNode {
// Emit an event to notify list and detail views to refresh
emitter.emit('credentialChanged', credentialToSave.Id);
- });
+ },
+ {
+ /**
+ * Handle successful vault mutation.
+ */
+ onSuccess: () => {
+ // If this was created from autofill (serviceUrl param), show confirmation screen
+ if (serviceUrl && !isEditMode) {
+ router.replace('/credentials/autofill-credential-created');
+ } else {
+ // First close the modal
+ router.dismiss();
- // If this was created from autofill (serviceUrl param), show confirmation screen
- if (serviceUrl && !isEditMode) {
- router.replace('/credentials/autofill-credential-created');
- } else {
- // First close the modal
- router.dismiss();
+ // Then navigate after a short delay to ensure the modal has closed
+ setTimeout(() => {
+ if (isEditMode) {
+ Toast.show({
+ type: 'success',
+ text1: t('credentials.toasts.credentialUpdated'),
+ position: 'bottom'
+ });
- // Then navigate after a short delay to ensure the modal has closed
- setTimeout(() => {
- if (isEditMode) {
- // Do nothing, as the original screen will update itself.
- } else {
- router.push(`/credentials/${credentialToSave.Id}`);
- }
- }, 100);
+ // Do not navigate away, the original screen will update itself after modal is closed.
+ } else {
+ Toast.show({
+ type: 'success',
+ text1: t('credentials.toasts.credentialSaved'),
+ position: 'bottom'
+ });
- // Show success toast
- setTimeout(() => {
+ router.push(`/credentials/${credentialToSave.Id}`);
+ }
+ }, 100);
+ }
+ },
+ /**
+ * Handle error during vault mutation.
+ */
+ onError: (error) => {
Toast.show({
- type: 'success',
- text1: isEditMode ? t('credentials.toasts.credentialUpdated') : t('credentials.toasts.credentialCreated'),
+ type: 'error',
+ text1: t('credentials.errors.saveFailed'),
+ text2: error.message,
position: 'bottom'
});
- }, 200);
+ console.error('Error saving credential:', error.message);
+ }
+ });
- setIsSyncing(false);
- }
+ setIsSyncing(false);
+ setIsSaveDisabled(false);
}, [isEditMode, id, serviceUrl, router, executeVaultMutation, dbContext.sqliteClient, mode, generateRandomAlias, webApi, watch, setIsSaveDisabled, setIsSyncing, isSaveDisabled, t, originalAttachmentIds, attachments]);
/**
diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsx
index 876e8d57e..69de2d157 100644
--- a/apps/mobile-app/context/AuthContext.tsx
+++ b/apps/mobile-app/context/AuthContext.tsx
@@ -126,6 +126,11 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
* Set auth tokens in storage as part of the login process. After db is initialized, the login method should be called as well.
*/
const setAuthTokens = useCallback(async (username: string, accessToken: string, refreshToken: string): Promise<void> => {
+ // Store username in native layer (new approach)
+ await NativeVaultManager.setUsername(username);
+
+ // Keep AsyncStorage for backward compatibility / migration
+ // TODO: Remove AsyncStorage username storage in future version
await AsyncStorage.setItem('username', username);
await AsyncStorage.setItem('accessToken', accessToken);
await AsyncStorage.setItem('refreshToken', refreshToken);
@@ -147,7 +152,23 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
const initializeAuth = useCallback(async (): Promise<{ isLoggedIn: boolean; enabledAuthMethods: AuthMethod[] }> => {
const accessToken = await AsyncStorage.getItem('accessToken') as string;
const refreshToken = await AsyncStorage.getItem('refreshToken') as string;
- const username = await AsyncStorage.getItem('username') as string;
+
+ // Try to get username from native layer first (new approach)
+ let username = await NativeVaultManager.getUsername();
+
+ // Fallback to AsyncStorage for migration
+ if (!username) {
+ username = await AsyncStorage.getItem('username');
+ // Migrate to native storage
+ if (username) {
+ await NativeVaultManager.setUsername(username);
+ }
+ }
+
+ // Load offline mode from native layer
+ const offline = await NativeVaultManager.getOfflineMode();
+ setIsOffline(offline);
+
let isAuthenticated = false;
let methods: AuthMethod[] = ['password'];
@@ -173,18 +194,18 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
* This is called by AppContext after revoking tokens on the server.
*/
const clearAuth = useCallback(async (errorMessage?: string): Promise<void> => {
+ // Clear from native layer
+ await NativeVaultManager.clearUsername();
+ await NativeVaultManager.clearAuthTokens();
+
+ // Clear from AsyncStorage (for backward compatibility)
+ // TODO: Remove AsyncStorage cleanup in future version
await AsyncStorage.removeItem('username');
await AsyncStorage.removeItem('accessToken');
await AsyncStorage.removeItem('refreshToken');
await AsyncStorage.removeItem('authMethods');
- dbContext?.clearDatabase();
- // Clear tokens from native layer
- try {
- await NativeVaultManager.clearAuthTokens();
- } catch (error) {
- console.error('Failed to clear auth tokens from native layer:', error);
- }
+ dbContext?.clearDatabase();
if (errorMessage) {
// Show alert
@@ -433,6 +454,14 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
loadAutofillState();
}, [loadAutofillState]);
+ /**
+ * Set offline mode and sync to native layer
+ */
+ const setOfflineMode = useCallback(async (offline: boolean) => {
+ setIsOffline(offline);
+ await NativeVaultManager.setOfflineMode(offline);
+ }, []);
+
const contextValue = useMemo(() => ({
isLoggedIn,
isInitialized,
@@ -458,7 +487,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
setReturnUrl,
verifyPassword,
getEncryptionKeyDerivationParams,
- setOfflineMode: setIsOffline,
+ setOfflineMode,
}), [
isLoggedIn,
isInitialized,
@@ -484,6 +513,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
setReturnUrl,
verifyPassword,
getEncryptionKeyDerivationParams,
+ setOfflineMode,
]);
return (
diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.ts
index 036b304d5..c1356cd42 100644
--- a/apps/mobile-app/hooks/useVaultMutate.ts
+++ b/apps/mobile-app/hooks/useVaultMutate.ts
@@ -45,23 +45,17 @@ export function useVaultMutate() : {
const { syncVault } = useVaultSync();
/**
- * Prepare the vault for upload, returns the new vault object with the updated revision number and encrypted database.
+ * Prepare vault for password change operation.
+ * TODO: Move this to native layer as well when implementing native password change support.
*/
- const prepareVault = useCallback(async () : Promise<Vault> => {
- // Get the current vault revision number
+ const prepareVaultForPasswordChange = useCallback(async (): Promise<Vault> => {
const currentRevision = await NativeVaultManager.getCurrentVaultRevisionNumber();
-
- // Get the encrypted database
const encryptedDb = await NativeVaultManager.getEncryptedDatabase();
if (!encryptedDb) {
throw new Error(t('vault.errors.failedToGetEncryptedDatabase'));
}
- setSyncStatus(t('vault.uploadingVaultToServer'));
-
- // Get all private email domains from credentials in order to claim them on server
const privateEmailDomains = await dbContext.sqliteClient!.getPrivateEmailDomains();
-
const credentials = await dbContext.sqliteClient!.getAllCredentials();
const privateEmailAddresses = credentials
.filter(cred => cred.Alias?.Email != null)
@@ -71,23 +65,21 @@ export function useVaultMutate() : {
return privateEmailDomains.some(domain => email.toLowerCase().endsWith(`@${domain.toLowerCase()}`));
});
- // Get username from the auth context
const username = authContext.username;
if (!username) {
throw new Error(t('vault.errors.usernameNotFound'));
}
- // Create vault object for upload
return {
blob: encryptedDb,
createdAt: new Date().toISOString(),
credentialsCount: credentials.length,
currentRevisionNumber: currentRevision,
emailAddressList: privateEmailAddresses,
- privateEmailDomainList: [], // Empty on purpose, API will not use this for vault updates
- publicEmailDomainList: [], // Empty on purpose, API will not use this for vault updates
- encryptionPublicKey: '', // Empty on purpose, only required if new public/private key pair is generated
- client: '', // Empty on purpose, API will not use this for vault updates
+ privateEmailDomainList: [],
+ publicEmailDomainList: [],
+ encryptionPublicKey: '',
+ client: '',
updatedAt: new Date().toISOString(),
username: username,
version: (await dbContext.sqliteClient!.getDatabaseVersion())?.version ?? '0.0.0'
@@ -96,6 +88,7 @@ export function useVaultMutate() : {
/**
* Execute the provided operation (e.g. create/update/delete credential)
+ * Now delegates to native layer for vault upload.
*/
const executeMutateOperation = useCallback(async (
operation: () => Promise<void>,
@@ -104,40 +97,48 @@ export function useVaultMutate() : {
setSyncStatus(t('vault.savingChangesToVault'));
// Execute the provided operation (e.g. create/update/delete credential)
+ // The operation should wrap its changes in beginTransaction/commitTransaction
await operation();
setSyncStatus(t('vault.uploadingVaultToServer'));
- const newVault = await prepareVault();
try {
- // Upload to server
- const response = await webApi.post<typeof newVault, VaultPostResponse>('Vault', newVault);
-
- // If we get here, it means we have a valid connection to the server.
- authContext.setOfflineMode(false);
-
- if (response.status === 0) {
- await NativeVaultManager.setCurrentVaultRevisionNumber(response.newRevisionNumber);
- options.onSuccess?.();
- } else if (response.status === 1) {
- // Note: vault merge is no longer allowed by the API as of 0.20.0, updates with the same revision number are rejected. So this check can be removed later.
- throw new Error(t('vault.errors.vaultMergeRequired'));
- } else if (response.status === 2) {
- throw new Error(t('vault.errors.vaultOutdated'));
- } else {
- throw new Error(t('vault.errors.failedToUploadVault'));
+ // Call native mutateVault which handles:
+ // - Preparing vault metadata (credentials count, email addresses, etc.)
+ // - Uploading to server
+ // - Updating revision number
+ // - Clearing offline mode on success
+ const result = await NativeVaultManager.mutateVault();
+
+ // Verify success
+ if (result !== true) {
+ console.error('VaultMutate: Native mutateVault did not return true, result:', result);
+ throw new Error('Vault mutation did not complete successfully');
}
+
+ // Success
+ options.onSuccess?.();
} catch (error) {
+ console.error('VaultMutate: Error during vault mutation:', error);
+
// Check if it's a network error
if (error instanceof Error && (error.message.includes('network') || error.message.includes('timeout'))) {
// Network error, mark as offline and track pending changes
- authContext.setOfflineMode(true);
+ await NativeVaultManager.setOfflineMode(true);
options.onSuccess?.();
return;
}
- throw error;
+
+ // Check for vault outdated error
+ if (error instanceof Error && error.message.includes('Vault is outdated')) {
+ options.onError?.(new Error(t('vault.errors.vaultOutdated')));
+ return;
+ }
+
+ // Re-throw the error so it's handled by the caller
+ options.onError?.(new Error(t('common.errors.unknownError')));
}
- }, [authContext, webApi, prepareVault, t]);
+ }, [t]);
/**
* Execute the provided operation (e.g. create/update/delete credential)
@@ -208,8 +209,8 @@ export function useVaultMutate() : {
const newPrivateKey = srp.derivePrivateKey(newSalt, username, newPasswordHashString);
const newVerifier = srp.deriveVerifier(newPrivateKey);
- // Get the current vault revision number
- const vault = await prepareVault();
+ // Prepare vault for password change
+ const vault = await prepareVaultForPasswordChange();
setSyncStatus(t('vault.uploadingVaultToServer'));
// Convert default vault object to password change vault object
@@ -232,7 +233,7 @@ export function useVaultMutate() : {
const newRevisionNumber = response.newRevisionNumber ?? passwordChangeVault.currentRevisionNumber + 1;
// If we get here, it means we have a valid connection to the server.
- authContext.setOfflineMode(false);
+ await NativeVaultManager.setOfflineMode(false);
await NativeVaultManager.setCurrentVaultRevisionNumber(newRevisionNumber);
options.onSuccess?.();
@@ -240,7 +241,7 @@ export function useVaultMutate() : {
console.error('Error during password change operation:', error);
throw error;
}
- }, [dbContext, authContext, webApi, prepareVault, t]);
+ }, [dbContext, authContext, webApi, prepareVaultForPasswordChange, t]);
/**
* Hook to execute a vault mutation which uploads a new encrypted vault to the server
diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.ts
index cdf602e77..536d44061 100644
--- a/apps/mobile-app/hooks/useVaultSync.ts
+++ b/apps/mobile-app/hooks/useVaultSync.ts
@@ -47,6 +47,7 @@ type VaultSyncOptions = {
/**
* Hook to sync the vault with the server.
+ * Now delegates core sync logic to native layer while keeping UI orchestration in React Native.
*/
export const useVaultSync = () : {
syncVault: (options?: VaultSyncOptions) => Promise<boolean>;
@@ -54,7 +55,6 @@ export const useVaultSync = () : {
const { t } = useTranslation();
const app = useApp();
const dbContext = useDb();
- const webApi = useWebApi();
const syncVault = useCallback(async (options: VaultSyncOptions = {}) => {
const { initialSync = false, onSuccess, onError, onStatus, onOffline, onUpgradeRequired } = options;
@@ -70,62 +70,72 @@ export const useVaultSync = () : {
return false;
}
- // Check app status and vault revision
+ // Update status
onStatus?.(t('vault.checkingVaultUpdates'));
- const statusResponse = await withMinimumDelay(() => webApi.getStatus(), 300, enableDelay);
- if (statusResponse.serverVersion === '0.0.0') {
- // Server is not available, go into offline mode
- onOffline?.();
- return false;
+ // Add artificial delay for initial sync UX
+ if (enableDelay) {
+ await new Promise(resolve => setTimeout(resolve, 300));
}
- if (!statusResponse.clientVersionSupported) {
- const statusError = t('vault.errors.versionNotSupported');
- onError?.(statusError);
- return false;
- }
+ // Call native syncVault which handles:
+ // - Calling Auth/status endpoint
+ // - Comparing vault revisions
+ // - Downloading vault if needed
+ // - Storing encrypted vault
+ // - Updating revision number
+ // - Setting offline mode
+ let hasNewVault = false;
- if (!AppInfo.isServerVersionSupported(statusResponse.serverVersion)) {
- const statusError = t('vault.errors.serverNeedsUpdate');
- onError?.(statusError);
- return false;
- }
+ try {
+ onStatus?.(t('vault.syncingUpdatedVault'));
+ hasNewVault = await NativeVaultManager.syncVault();
- // Check if the SRP salt has changed compared to locally stored encryption key derivation params
- const keyDerivationParams = await app.getEncryptionKeyDerivationParams();
- if (keyDerivationParams && statusResponse.srpSalt && statusResponse.srpSalt !== keyDerivationParams.salt) {
- /**
- * Server SRP salt has changed compared to locally stored value, which means the user has changed
- * their password since the last time they logged in. This means that the local encryption key is no
- * longer valid and the user needs to re-authenticate. We trigger a logout but do not revoke tokens
- * as these were already revoked by the server upon password change.
- */
- await app.logout(t('vault.errors.passwordChanged'));
- return false;
- }
+ // Add artificial delay for initial sync UX
+ if (enableDelay && hasNewVault) {
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ }
+ } catch (err) {
+ const errorMessage = err instanceof Error ? err.message : t('common.errors.unknownError');
- // If we get here, it means we have a valid connection to the server.
- app.setOfflineMode(false);
+ // Check for authentication failure (401) - logout user
+ if (errorMessage.includes('Authentication failed') || errorMessage.includes('please login again')) {
+ await app.logout('Your session has expired. Please login again.');
+ return false;
+ }
- // Compare vault revisions
- const vaultMetadata = await dbContext.getVaultMetadata();
- const vaultRevisionNumber = vaultMetadata?.vaultRevisionNumber ?? 0;
+ // Check for specific error conditions from native layer
+ if (errorMessage.includes('Server not available')) {
+ onOffline?.();
+ return false;
+ }
- if (statusResponse.vaultRevision > vaultRevisionNumber) {
- onStatus?.(t('vault.syncingUpdatedVault'));
- const vaultResponseJson = await withMinimumDelay(() => webApi.get<VaultResponse>('Vault'), 1000, enableDelay);
+ if (errorMessage.includes('Client version not supported')) {
+ onError?.(t('vault.errors.versionNotSupported'));
+ return false;
+ }
+
+ if (errorMessage.includes('Password has changed')) {
+ await app.logout(t('vault.errors.passwordChanged'));
+ return false;
+ }
- const vaultError = webApi.validateVaultResponse(vaultResponseJson as VaultResponse);
- if (vaultError) {
- // Throw authentication error which will be caught and handled
- throw new VaultAuthenticationError(vaultError);
+ // Network error - go offline but don't fail
+ if (errorMessage.includes('network') || errorMessage.includes('timeout')) {
+ await NativeVaultManager.setOfflineMode(true);
+ return true;
}
+ throw err;
+ }
+
+ // If a new vault was downloaded, we need to unlock it
+ if (hasNewVault) {
try {
- await dbContext.initializeDatabase(vaultResponseJson as VaultResponse);
+ // Vault was already stored by native layer, now unlock it
+ await NativeVaultManager.unlockVault();
- // Check if the current vault version is known and up to date, if not known trigger an exception, if not up to date redirect to the upgrade page.
+ // Check if the current vault version is known and up to date
if (await NativeVaultManager.isVaultUnlocked() && await dbContext.hasPendingMigrations()) {
onUpgradeRequired?.();
return false;
@@ -136,9 +146,7 @@ export const useVaultSync = () : {
// Register credential identities after successful vault sync
try {
await NativeVaultManager.registerCredentialIdentities();
- console.log('Vault sync: Successfully registered credential identities');
} catch (error) {
- console.warn('Vault sync: Failed to register credential identities:', error);
// Don't fail the sync if credential registration fails
}
@@ -149,18 +157,24 @@ export const useVaultSync = () : {
return false;
}
- // Vault could not be decrypted, throw an error
+ // Vault could not be unlocked
throw new Error(t('vault.errors.vaultDecryptFailed'));
}
}
- // Check if the vault is up to date, if not, redirect to the upgrade page.
+ // Vault already up to date
+ // Check if the vault needs migration
if (await NativeVaultManager.isVaultUnlocked() && await dbContext.hasPendingMigrations()) {
onUpgradeRequired?.();
return false;
}
- await withMinimumDelay(() => Promise.resolve(onSuccess?.(false)), 300, enableDelay);
+ // Add artificial delay for initial sync UX
+ if (enableDelay) {
+ await new Promise(resolve => setTimeout(resolve, 300));
+ }
+
+ onSuccess?.(false);
// Register credential identities even when vault is up to date
try {
@@ -190,14 +204,14 @@ export const useVaultSync = () : {
// Check if it's a network error
if (errorMessage.includes('network') || errorMessage.includes('timeout')) {
- app.setOfflineMode(true);
+ await NativeVaultManager.setOfflineMode(true);
return true;
}
onError?.(errorMessage);
return false;
}
- }, [app, dbContext, webApi, t]);
+ }, [app, dbContext, t]);
return { syncVault };
};
\ No newline at end of file
diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.json
index 21fbef55c..dac6b9de1 100644
--- a/apps/mobile-app/i18n/locales/en.json
+++ b/apps/mobile-app/i18n/locales/en.json
@@ -165,6 +165,7 @@
"createNewAliasFor": "Create new alias for",
"errors": {
"loadFailed": "Failed to load credential",
+ "saveFailed": "Failed to save credential",
"generateUsernameFailed": "Failed to generate username",
"generatePasswordFailed": "Failed to generate password"
},
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index bc60b85e0..a53851547 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -205,4 +205,38 @@
[vaultManager executeWebApiRequest:method endpoint:endpoint body:body headers:headers requiresAuth:requiresAuth resolver:resolve rejecter:reject];
}
+// MARK: - Username Management
+
+- (void)setUsername:(NSString *)username resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager setUsername:username resolver:resolve rejecter:reject];
+}
+
+- (void)getUsername:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager getUsername:resolve rejecter:reject];
+}
+
+- (void)clearUsername:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager clearUsername:resolve rejecter:reject];
+}
+
+// MARK: - Offline Mode Management
+
+- (void)setOfflineMode:(BOOL)isOffline resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager setOfflineMode:isOffline resolver:resolve rejecter:reject];
+}
+
+- (void)getOfflineMode:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager getOfflineMode:resolve rejecter:reject];
+}
+
+// MARK: - Vault Sync and Mutate
+
+- (void)syncVault:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager syncVault:resolve rejecter:reject];
+}
+
+- (void)mutateVault:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager mutateVault:resolve rejecter:reject];
+}
+
@end
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 38c874ba1..c1516322c 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -585,6 +585,91 @@ public class VaultManager: NSObject {
}
}
+ // MARK: - Username Management
+
+ @objc
+ func setUsername(_ username: String,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ vaultStore.setUsername(username)
+ resolve(nil)
+ }
+
+ @objc
+ func getUsername(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ if let username = vaultStore.getUsername() {
+ resolve(username)
+ } else {
+ resolve(nil)
+ }
+ }
+
+ @objc
+ func clearUsername(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ vaultStore.clearUsername()
+ resolve(nil)
+ }
+
+ // MARK: - Offline Mode Management
+
+ @objc
+ func setOfflineMode(_ isOffline: Bool,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ vaultStore.setOfflineMode(isOffline)
+ resolve(nil)
+ }
+
+ @objc
+ func getOfflineMode(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ resolve(vaultStore.getOfflineMode())
+ }
+
+ // MARK: - Vault Sync and Mutate
+
+ @objc
+ func syncVault(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ Task {
+ do {
+ print("VaultManager: Starting vault sync")
+ let hasNewVault = try await vaultStore.syncVault(using: webApiService)
+ print("VaultManager: Vault sync succeeded, hasNewVault: \(hasNewVault)")
+ await MainActor.run {
+ resolve(hasNewVault)
+ }
+ } catch {
+ print("VaultManager: Vault sync failed: \(error)")
+ await MainActor.run {
+ reject("SYNC_ERROR", "Failed to sync vault: \(error.localizedDescription)", error)
+ }
+ }
+ }
+ }
+
+ @objc
+ func mutateVault(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ Task {
+ do {
+ print("VaultManager: Starting vault mutation")
+ try await vaultStore.mutateVault(using: webApiService)
+ print("VaultManager: Vault mutation succeeded")
+ await MainActor.run {
+ resolve(true) // Return explicit success
+ }
+ } catch {
+ print("VaultManager: Vault mutation failed: \(error)")
+ await MainActor.run {
+ reject("MUTATE_ERROR", "Failed to mutate vault: \(error.localizedDescription)", error)
+ }
+ }
+ }
+ }
+
@objc
func requiresMainQueueSetup() -> Bool {
return false
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultConstants.swift b/apps/mobile-app/ios/VaultStoreKit/VaultConstants.swift
index 6db2ad395..2474900da 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultConstants.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultConstants.swift
@@ -13,6 +13,8 @@ public struct VaultConstants {
static let authMethodsKey = "aliasvault_auth_methods"
static let autoLockTimeoutKey = "aliasvault_auto_lock_timeout"
static let encryptionKeyDerivationParamsKey = "aliasvault_encryption_key_derivation_params"
+ static let usernameKey = "aliasvault_username"
+ static let offlineModeKey = "aliasvault_offline_mode"
static let defaultAutoLockTimeout: Int = 3600 // 1 hour in seconds
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift
index 08a6c2f65..42fcb05dd 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift
@@ -15,7 +15,7 @@ extension VaultStore {
}
/// Get the metadata object - the metadata for the vault
- private func getVaultMetadataObject() -> VaultMetadata? {
+ internal func getVaultMetadataObject() -> VaultMetadata? {
guard let jsonString = getVaultMetadata(),
let data = jsonString.data(using: .utf8),
let metadata = try? JSONDecoder().decode(VaultMetadata.self, from: data) else {
@@ -53,4 +53,36 @@ extension VaultStore {
userDefaults.synchronize()
}
}
+
+ // MARK: - Username Storage
+
+ /// Store the username
+ public func setUsername(_ username: String) {
+ userDefaults.set(username, forKey: VaultConstants.usernameKey)
+ userDefaults.synchronize()
+ }
+
+ /// Get the username
+ public func getUsername() -> String? {
+ return userDefaults.string(forKey: VaultConstants.usernameKey)
+ }
+
+ /// Clear the username
+ public func clearUsername() {
+ userDefaults.removeObject(forKey: VaultConstants.usernameKey)
+ userDefaults.synchronize()
+ }
+
+ // MARK: - Offline Mode Storage
+
+ /// Set offline mode flag
+ public func setOfflineMode(_ isOffline: Bool) {
+ userDefaults.set(isOffline, forKey: VaultConstants.offlineModeKey)
+ userDefaults.synchronize()
+ }
+
+ /// Get offline mode flag
+ public func getOfflineMode() -> Bool {
+ return userDefaults.bool(forKey: VaultConstants.offlineModeKey)
+ }
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift
new file mode 100644
index 000000000..a8d2953ef
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift
@@ -0,0 +1,248 @@
+import Foundation
+import VaultModels
+
+/// Vault upload model that matches the API contract
+public struct VaultUpload: Codable {
+ public let blob: String
+ public let createdAt: String
+ public let credentialsCount: Int
+ public let currentRevisionNumber: Int
+ public let emailAddressList: [String]
+ public let privateEmailDomainList: [String]
+ public let publicEmailDomainList: [String]
+ public let encryptionPublicKey: String
+ public let updatedAt: String
+ public let username: String
+ public let version: String
+ public let client: String
+}
+
+/// Vault POST response from API
+public struct VaultPostResponse: Codable {
+ public let status: Int
+ public let newRevisionNumber: Int
+}
+
+/// Extension for the VaultStore class to handle vault mutation operations
+extension VaultStore {
+ // MARK: - Vault Preparation
+
+ /// Prepare the vault for upload by assembling all metadata
+ /// Returns a VaultUpload object ready to be sent to the server
+ public func prepareVault() throws -> VaultUpload {
+ // Get the current vault revision number
+ let currentRevision = getCurrentVaultRevisionNumber()
+
+ // Get the encrypted database
+ guard let encryptedDb = getEncryptedDatabase() else {
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to get encrypted database"]
+ )
+ }
+
+ // Get username
+ guard let username = getUsername() else {
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Username not found"]
+ )
+ }
+
+ // Ensure vault is unlocked to query database
+ guard isVaultUnlocked else {
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Vault must be unlocked to prepare for upload"]
+ )
+ }
+
+ // Get all credentials to count them and extract private email addresses
+ let credentials = try getAllCredentials()
+
+ // Get private email domains from metadata
+ let metadata = getVaultMetadataObject()
+ let privateEmailDomains = metadata?.privateEmailDomains ?? []
+
+ // Extract private email addresses from credentials
+ let privateEmailAddresses = credentials
+ .compactMap { $0.alias?.email }
+ .filter { email in
+ // Check if email belongs to any private domain
+ privateEmailDomains.contains { domain in
+ email.lowercased().hasSuffix("@\(domain.lowercased())")
+ }
+ }
+ // Remove duplicates
+ .reduce(into: [String]()) { result, email in
+ if !result.contains(email) {
+ result.append(email)
+ }
+ }
+
+ // Get database version
+ let dbVersion = try getDatabaseVersion()
+
+ // Get client version
+ let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0.0"
+ let baseVersion = version.split(separator: "-").first.map(String.init) ?? "0.0.0"
+ let client = "ios-\(baseVersion)"
+
+ // Format dates in ISO 8601 format
+ let dateFormatter = ISO8601DateFormatter()
+ dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ let now = dateFormatter.string(from: Date())
+
+ return VaultUpload(
+ blob: encryptedDb,
+ createdAt: now,
+ credentialsCount: credentials.count,
+ currentRevisionNumber: currentRevision,
+ emailAddressList: privateEmailAddresses,
+ privateEmailDomainList: [], // Empty on purpose, API will not use this for vault updates
+ publicEmailDomainList: [], // Empty on purpose, API will not use this for vault updates
+ encryptionPublicKey: "", // Empty on purpose, only required if new public/private key pair is generated
+ updatedAt: now,
+ username: username,
+ version: dbVersion,
+ client: client
+ )
+ }
+
+ // MARK: - Vault Mutation
+
+ /// Execute a vault mutation operation
+ /// This method:
+ /// 1. Executes the provided SQL operation (already wrapped in a transaction by caller)
+ /// 2. Prepares the vault for upload
+ /// 3. Uploads the vault to the server
+ /// 4. Updates the local revision number
+ ///
+ /// Note: The caller must wrap their database operations in beginTransaction()/commitTransaction()
+ /// which will trigger the encryption and local storage of the database.
+ public func mutateVault(using webApiService: WebApiService) async throws {
+ print("VaultStore: Starting vault mutation")
+
+ // Prepare vault for upload
+ print("VaultStore: Preparing vault for upload")
+ let vault = try prepareVault()
+ print("VaultStore: Vault prepared successfully, credentials count: \(vault.credentialsCount)")
+
+ // Convert to JSON (use default key encoding which is camelCase)
+ let encoder = JSONEncoder()
+ let jsonData = try encoder.encode(vault)
+ guard let jsonString = String(data: jsonData, encoding: .utf8) else {
+ print("VaultStore: Failed to encode vault to JSON")
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to encode vault to JSON"]
+ )
+ }
+
+ print("VaultStore: Uploading vault to server (size: \(jsonString.count) bytes)")
+
+ // Upload to server
+ let response = try await webApiService.executeRequest(
+ method: "POST",
+ endpoint: "Vault",
+ body: jsonString,
+ headers: ["Content-Type": "application/json"],
+ requiresAuth: true
+ )
+
+ print("VaultStore: Server response status code: \(response.statusCode)")
+
+ // Check response status
+ guard response.statusCode == 200 else {
+ print("VaultStore: Server rejected vault upload with status \(response.statusCode)")
+ print("VaultStore: Response body: \(response.body)")
+
+ // If we get here, the server rejected the vault update
+ if response.statusCode >= 400 {
+ throw NSError(
+ domain: "VaultStore",
+ code: response.statusCode,
+ userInfo: [NSLocalizedDescriptionKey: "Server returned error: \(response.statusCode)"]
+ )
+ }
+
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Unexpected server response: \(response.statusCode)"]
+ )
+ }
+
+ // Parse response
+ guard let responseData = response.body.data(using: .utf8) else {
+ print("VaultStore: Failed to convert response body to data")
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to convert response body to data"]
+ )
+ }
+
+ let vaultResponse: VaultPostResponse
+ do {
+ vaultResponse = try JSONDecoder().decode(VaultPostResponse.self, from: responseData)
+ print("VaultStore: Parsed upload response - status: \(vaultResponse.status), newRevision: \(vaultResponse.newRevisionNumber)")
+ } catch {
+ print("VaultStore: Failed to parse vault upload response: \(error)")
+ print("VaultStore: Response body: \(response.body)")
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to parse vault upload response: \(error.localizedDescription)"]
+ )
+ }
+
+ // Check vault response status
+ if vaultResponse.status == 0 {
+ // Success - update local revision number
+ setCurrentVaultRevisionNumber(vaultResponse.newRevisionNumber)
+
+ // Clear offline mode on successful upload
+ setOfflineMode(false)
+ } else if vaultResponse.status == 1 {
+ // Merge required (should not happen with API >= 0.20.0)
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Vault merge required"]
+ )
+ } else if vaultResponse.status == 2 {
+ // Vault outdated
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Vault is outdated, please sync first"]
+ )
+ } else {
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to upload vault"]
+ )
+ }
+ }
+
+ // MARK: - Helper Methods
+
+ /// Get the database version from the DatabaseVersion table
+ private func getDatabaseVersion() throws -> String {
+ let query = "SELECT version FROM DatabaseVersion LIMIT 1"
+ let results = try executeQuery(query, params: [])
+
+ if let firstRow = results.first,
+ let version = firstRow["version"] as? String {
+ return version
+ }
+
+ return "0.0.0"
+ }
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
new file mode 100644
index 000000000..b1a8305c1
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
@@ -0,0 +1,213 @@
+import Foundation
+import VaultModels
+
+/// Status response from Auth/status endpoint
+public struct StatusResponse: Codable {
+ public let clientVersionSupported: Bool
+ public let serverVersion: String
+ public let vaultRevision: Int
+ public let srpSalt: String
+}
+
+/// Vault data from API
+public struct VaultData: Codable {
+ public let username: String
+ public let blob: String
+ public let version: String
+ public let currentRevisionNumber: Int
+ public let encryptionPublicKey: String
+ public let credentialsCount: Int
+ public let emailAddressList: [String]
+ public let privateEmailDomainList: [String]
+ public let publicEmailDomainList: [String]
+ public let createdAt: String
+ public let updatedAt: String
+}
+
+/// Vault response from Vault GET endpoint
+public struct VaultResponse: Codable {
+ public let status: Int
+ public let vault: VaultData
+}
+
+/// Extension for the VaultStore class to handle vault sync operations
+extension VaultStore {
+ // MARK: - Vault Sync
+
+ /// Sync the vault with the server
+ /// Returns true if a new vault was downloaded, false if vault is already up to date
+ public func syncVault(using webApiService: WebApiService) async throws -> Bool {
+ let status = try await fetchAndValidateStatus(using: webApiService)
+ setOfflineMode(false)
+
+ let currentRevision = getCurrentVaultRevisionNumber()
+ if status.vaultRevision > currentRevision {
+ try await downloadAndStoreVault(using: webApiService, newRevision: status.vaultRevision)
+ return true
+ }
+
+ return false
+ }
+
+ // MARK: - Private Helpers
+
+ /// Fetch and validate server status
+ private func fetchAndValidateStatus(using webApiService: WebApiService) async throws -> StatusResponse {
+ let statusResponse = try await webApiService.executeRequest(
+ method: "GET",
+ endpoint: "Auth/status",
+ body: nil,
+ headers: [:],
+ requiresAuth: true
+ )
+
+ // Check if we got a successful response (token refresh may have occurred)
+ guard statusResponse.statusCode == 200 else {
+ // If still unauthorized after token refresh attempt
+ if statusResponse.statusCode == 401 {
+ print("VaultStore: Authentication failed (401), tokens may be expired")
+ throw NSError(
+ domain: "VaultStore",
+ code: 401,
+ userInfo: [NSLocalizedDescriptionKey: "Authentication failed - please login again"]
+ )
+ }
+
+ setOfflineMode(true)
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Server not available"]
+ )
+ }
+
+ guard let statusData = statusResponse.body.data(using: .utf8) else {
+ print("VaultStore: Failed to convert status response to data")
+ print("VaultStore: Response body: '\(statusResponse.body)'")
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to convert status response to data"]
+ )
+ }
+
+ let decoder = JSONDecoder()
+ let status: StatusResponse
+ do {
+ status = try decoder.decode(StatusResponse.self, from: statusData)
+ } catch {
+ print("VaultStore: Failed to decode status response: \(error)")
+ print("VaultStore: Response body: '\(statusResponse.body)'")
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to parse status response: \(error.localizedDescription)"]
+ )
+ }
+
+ guard status.clientVersionSupported else {
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Client version not supported"]
+ )
+ }
+
+ try validateSrpSalt(status.srpSalt)
+ return status
+ }
+
+ /// Validate SRP salt hasn't changed (password change detection)
+ private func validateSrpSalt(_ srpSalt: String) throws {
+ guard let keyDerivationParams = self.keyDerivationParams,
+ let keyDerivationData = keyDerivationParams.data(using: .utf8),
+ let params = try? JSONDecoder().decode(EncryptionKeyDerivationParams.self, from: keyDerivationData) else {
+ return
+ }
+
+ if !srpSalt.isEmpty && srpSalt != params.salt {
+ throw NSError(
+ domain: "VaultStore",
+ code: -2,
+ userInfo: [NSLocalizedDescriptionKey: "Password has changed, please login again"]
+ )
+ }
+ }
+
+ /// Download vault from server and store it locally
+ private func downloadAndStoreVault(using webApiService: WebApiService, newRevision: Int) async throws {
+ let vaultResponse = try await webApiService.executeRequest(
+ method: "GET",
+ endpoint: "Vault",
+ body: nil,
+ headers: [:],
+ requiresAuth: true
+ )
+
+ guard vaultResponse.statusCode == 200 else {
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to download vault"]
+ )
+ }
+
+ let vault = try parseVaultResponse(vaultResponse.body)
+ try validateVaultStatus(vault.status)
+ try storeEncryptedDatabase(vault.vault.blob)
+ setCurrentVaultRevisionNumber(newRevision)
+
+ if isVaultUnlocked {
+ try unlockVault()
+ }
+ }
+
+ /// Parse vault response from JSON
+ private func parseVaultResponse(_ body: String) throws -> VaultResponse {
+ guard let vaultData = body.data(using: .utf8) else {
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to convert vault response to data"]
+ )
+ }
+
+ do {
+ return try JSONDecoder().decode(VaultResponse.self, from: vaultData)
+ } catch {
+ print("VaultStore: Failed to decode vault response: \(error)")
+ print("VaultStore: Response body: \(body)")
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to parse vault response: \(error.localizedDescription)"]
+ )
+ }
+ }
+
+ /// Validate vault response status
+ private func validateVaultStatus(_ status: Int) throws {
+ switch status {
+ case 0:
+ return
+ case 1:
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Vault merge required"]
+ )
+ case 2:
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Vault outdated"]
+ )
+ default:
+ throw NSError(
+ domain: "VaultStore",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Unknown vault status: \(status)"]
+ )
+ }
+ }
+}
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index e56044bef..78bf5a6e4 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -72,6 +72,19 @@ export interface Spec extends TurboModule {
headers: string,
requiresAuth: boolean
): Promise<string>;
+
+ // Username management
+ setUsername(username: string): Promise<void>;
+ getUsername(): Promise<string | null>;
+ clearUsername(): Promise<void>;
+
+ // Offline mode management
+ setOfflineMode(isOffline: boolean): Promise<void>;
+ getOfflineMode(): Promise<boolean>;
+
+ // Vault sync and mutate
+ syncVault(): Promise<boolean>;
+ mutateVault(): Promise<boolean>;
}
export default TurboModuleRegistry.getEnforcing<Spec>('NativeVaultManager');
diff --git a/apps/mobile-app/utils/WebApiService.ts b/apps/mobile-app/utils/WebApiService.ts
index 362ecfa26..892001c49 100644
--- a/apps/mobile-app/utils/WebApiService.ts
+++ b/apps/mobile-app/utils/WebApiService.ts
@@ -11,14 +11,6 @@ import NativeVaultManager from '@/specs/NativeVaultManager';
type RequestInit = globalThis.RequestInit;
-/**
- * Type for the token response from the API.
- */
-type TokenResponse = {
- token: string;
- refreshToken: string;
-}
-
/**
* Type for the native WebAPI response.
*/
@@ -380,22 +372,24 @@ export class WebApiService {
* TODO: This can be removed in a future version (e.g., after some time that 0.24.0 is released)
* and once most if not all active users have migrated.
*/
- private async syncLegacyConfigToNative(): Promise<void> {
- try {
- // Sync API URL from AsyncStorage to native (migration only)
- const apiUrl = await AsyncStorage.getItem('apiUrl');
- if (apiUrl) {
- await NativeVaultManager.setApiUrl(apiUrl);
- }
+ private async syncLegacyConfigToNative(): Promise<void> {
+ try {
+ // Migrate API URL from AsyncStorage to native on first launch, then remove to prevent repeated syncs
+ const apiUrl = await AsyncStorage.getItem('apiUrl');
+ if (apiUrl) {
+ await NativeVaultManager.setApiUrl(apiUrl);
+ await AsyncStorage.removeItem('apiUrl');
+ }
- // Sync tokens from AsyncStorage to native (migration only)
- const accessToken = await AsyncStorage.getItem('accessToken');
- const refreshToken = await AsyncStorage.getItem('refreshToken');
- if (accessToken && refreshToken) {
- await NativeVaultManager.setAuthTokens(accessToken, refreshToken);
- }
- } catch (error) {
- console.error('Failed to sync config to native layer:', error);
+ // Migrate tokens from AsyncStorage to native on first launch, then remove to prevent repeated syncs
+ const accessToken = await AsyncStorage.getItem('accessToken');
+ const refreshToken = await AsyncStorage.getItem('refreshToken');
+ if (accessToken && refreshToken) {
+ await NativeVaultManager.setAuthTokens(accessToken, refreshToken);
+ await AsyncStorage.multiRemove(['accessToken', 'refreshToken']);
}
+ } catch (error) {
+ console.error('Failed to sync config to native layer:', error);
}
+ }
}