Skip to content

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

Fetch and store capabilities in mobile app (#2159)

Leendert de Borst6887f95dc967
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 e630164ed..dd53b3286 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
@@ -1332,6 +1332,20 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
}
+ /**
+ * Get the capabilities the server resolved for this account as a JSON object, or null if none were stored yet.
+ * @param promise The promise to resolve.
+ */
+ @ReactMethod
+ override fun getCapabilities(promise: Promise) {
+ try {
+ promise.resolve(vaultStore.metadata.getCapabilities())
+ } catch (e: Exception) {
+ Log.e(TAG, "Error getting capabilities", e)
+ promise.reject("ERR_GET_CAPABILITIES", "Failed to get capabilities: ${e.message}", e)
+ }
+ }
+
// MARK: - Offline Mode Management
/**
@@ -1545,6 +1559,36 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
}
+ /**
+ * Run a sharing operation of the sync engine (see VaultStore.runSharingOperation). Failures resolve with the error code.
+ * @param operation The operation: `createSharedManifest` or `inviteToSharedManifest`.
+ * @param paramsJson What the operation acts on, as a JSON object.
+ * @param promise The promise to resolve with the operation result.
+ */
+ @ReactMethod
+ override fun runSharingOperation(operation: String, paramsJson: String, promise: Promise) {
+ CoroutineScope(Dispatchers.IO).launch {
+ try {
+ val result = vaultStore.runSharingOperation(operation, JSONObject(paramsJson), webApiService)
+ val resultMap = Arguments.createMap().apply {
+ putBoolean("success", result.success)
+ putBoolean("vaultUpgradeRequired", result.vaultUpgradeRequired)
+ putString("apiErrorCode", result.apiErrorCode)
+ putString("error", result.error)
+ putString("errorMessage", result.errorMessage)
+ }
+ withContext(Dispatchers.Main) {
+ promise.resolve(resultMap)
+ }
+ } catch (e: Exception) {
+ withContext(Dispatchers.Main) {
+ Log.e(TAG, "Error running the sharing operation", e)
+ promise.reject("VAULT_SHARING_ERROR", "Failed to run the sharing operation: ${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 2a9c1b041..dc9b2f2ab 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
@@ -61,3 +61,20 @@ data class VaultMigrationResult(
val error: String? = null,
val errorMessage: String? = null,
)
+
+/**
+ * Result of a sharing operation of the sync engine (creating a shared manifest, inviting a member to one).
+ *
+ * @property success Whether the operation completed.
+ * @property apiErrorCode The API error code the server refused with, which the sharing screen has words for.
+ * @property vaultUpgradeRequired Whether the vault has to finish upgrading before it can be shared.
+ * @property error The error code, if any.
+ * @property errorMessage The error message, if any.
+ */
+data class VaultSharingResult(
+ val success: Boolean,
+ val apiErrorCode: String? = null,
+ val vaultUpgradeRequired: Boolean = false,
+ val error: String? = null,
+ val errorMessage: String? = null,
+)
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMetadataManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMetadataManager.kt
index 4dd41caa3..91552ea4c 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMetadataManager.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMetadataManager.kt
@@ -129,6 +129,20 @@ class VaultMetadataManager(
storageProvider.clearServerVersion()
}
+ /**
+ * Set the capabilities the server resolved for this account, as a JSON object.
+ */
+ fun setCapabilities(json: String) {
+ storageProvider.setCapabilities(json)
+ }
+
+ /**
+ * Get the capabilities the server resolved for this account, as a JSON object.
+ */
+ fun getCapabilities(): String? {
+ return storageProvider.getCapabilities()
+ }
+
/**
* Check if the stored server version is greater than or equal to the specified version.
* @param targetVersion The version to compare against (e.g., "0.25.0")
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 bab877808..7bf32bbf5 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
@@ -729,6 +729,17 @@ class VaultStore(
return sync.migrateVaultManifest(webApiService)
}
+ /**
+ * Run a sharing operation of the sync engine (see VaultSync.runSharingOperation).
+ */
+ suspend fun runSharingOperation(
+ operation: String,
+ params: org.json.JSONObject,
+ webApiService: net.aliasvault.app.webapi.WebApiService,
+ ): VaultSharingResult {
+ return sync.runSharingOperation(operation, params, 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 704d2f669..d5707e255 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
@@ -23,10 +23,13 @@ class VaultSync(
) {
companion object {
private const val TAG = "VaultSync"
+
+ /** The engine operations the sharing screen may ask for. */
+ private val SHARING_OPERATIONS = setOf("createSharedManifest", "inviteToSharedManifest")
}
/**
- * Full vault sync: status check, then pull (and merge) or push as the server and local revisions decide. Never throws.
+ * Full vault sync: status check, then pull (and merge) or push as the server and local revisions decide.
*/
suspend fun syncVaultWithServer(webApiService: WebApiService): VaultSyncResult {
val startNanos = System.nanoTime()
@@ -115,8 +118,7 @@ class VaultSync(
/**
* 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. Never throws.
+ * account-key upgrade of a legacy vault) and push it.
*/
suspend fun migrateVaultManifest(webApiService: WebApiService): VaultMigrationResult {
val result = try {
@@ -132,6 +134,29 @@ class VaultSync(
return VaultMigrationResult(true, pushed)
}
+ /**
+ * Run a sharing operation of the engine: `createSharedManifest` or `inviteToSharedManifest`.
+ */
+ suspend fun runSharingOperation(operation: String, params: JSONObject, webApiService: WebApiService): VaultSharingResult {
+ if (operation !in SHARING_OPERATIONS) {
+ return failedSharing(AppError.SyncEngineFailed("Unknown sharing operation $operation"))
+ }
+ val result = try {
+ run(operation, webApiService, sharing = params)
+ } catch (e: AppError) {
+ return failedSharing(e)
+ }
+ if (result.optBoolean("success", false)) {
+ return VaultSharingResult(true)
+ }
+ val apiErrorCode = result.optString("apiErrorCode").takeIf { it.isNotEmpty() }
+ val vaultUpgradeRequired = result.optBoolean("vaultUpgradeRequired", false)
+ if (apiErrorCode != null || vaultUpgradeRequired) {
+ return VaultSharingResult(false, apiErrorCode, vaultUpgradeRequired)
+ }
+ return failedSharing(syncError(result))
+ }
+
/**
* Push the pending local changes (after a native mutation such as an autofill link or a passkey creation).
*/
@@ -147,9 +172,9 @@ class VaultSync(
* Run one engine operation and adopt what it reported. A driver failure surfaces as the native error.
*/
@Suppress("TooGenericExceptionCaught")
- private suspend fun run(operation: String, webApiService: WebApiService, encryptionKey: String? = null): JSONObject {
+ private suspend fun run(operation: String, webApiService: WebApiService, encryptionKey: String? = null, sharing: JSONObject? = null): JSONObject {
val result = try {
- VaultSyncEngine(vaultStore, storageProvider, webApiService).run(operation, encryptionKey = encryptionKey)
+ VaultSyncEngine(vaultStore, storageProvider, webApiService).run(operation, encryptionKey = encryptionKey, sharing = sharing)
} catch (e: Exception) {
throw driverError(e)
}
@@ -158,11 +183,12 @@ class VaultSync(
}
/**
- * Persist what the engine reported: server version, offline mode, session values it changed, and the email
- * routing a pulled vault came with. Capabilities are not stored: the mobile app has no capability gate yet.
+ * Persist what the engine reported: server version and capabilities, offline mode, session values it changed,
+ * and the email routing a pulled vault came with.
*/
private fun adoptSyncResult(result: JSONObject) {
result.optString("serverVersion").takeIf { it.isNotEmpty() }?.let { vaultStore.metadata.setServerVersion(it) }
+ result.optJSONObject("capabilities")?.let { vaultStore.metadata.setCapabilities(it.toString()) }
if (result.has("isOfflineMode")) {
vaultStore.metadata.setOfflineMode(result.optBoolean("isOfflineMode", false))
}
@@ -200,6 +226,14 @@ class VaultSync(
return VaultMigrationResult(false, false, error.code, error.message)
}
+ /**
+ * A failed sharing operation return.
+ */
+ private fun failedSharing(error: AppError): VaultSharingResult {
+ Log.e(TAG, "Sharing operation failed (${error.code}): ${error.message}", error.cause)
+ return VaultSharingResult(false, error = error.code, errorMessage = error.message)
+ }
+
/**
* An error the driver itself threw (a request it could not build, a command it could not decode).
*/
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
index 67e51120f..233890161 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
@@ -44,15 +44,15 @@ class VaultSyncEngine(
private var runLog = VaultSyncRunLog("")
/**
- * Run one engine operation (`fullSync`, `statusCheck`, `migrationStatus`, `migrateManifest`, `resolveVaultKey`) and
- * return its result. [encryptionKey] overrides the store's key for the one operation that runs before it is known.
+ * Run one engine operation (`fullSync`, `statusCheck`, `migrationStatus`, `migrateManifest`, `resolveVaultKey`, or a
+ * sharing operation) and return its result.
*/
- suspend fun run(operation: String, forcePull: Boolean = false, encryptionKey: String? = null): JSONObject {
+ suspend fun run(operation: String, forcePull: Boolean = false, encryptionKey: String? = null, sharing: JSONObject? = null): JSONObject {
JnaInitializer.ensureInitialized()
val log = VaultSyncRunLog(operation)
runLog = log
var success: Boolean? = null
- val session = VaultSyncSession(buildRequest(operation, forcePull, encryptionKey))
+ val session = VaultSyncSession(buildRequest(operation, forcePull, encryptionKey, sharing))
try {
while (true) {
val commandJson = log.engine { session.nextCommand() }
@@ -78,7 +78,7 @@ class VaultSyncEngine(
// region Request
- private fun buildRequest(operation: String, forcePull: Boolean, encryptionKey: String?): String {
+ private fun buildRequest(operation: String, forcePull: Boolean, encryptionKey: String?, sharing: JSONObject?): String {
val metadata = vaultStore.metadata.getVaultMetadataObject()
val syncState = vaultStore.getSyncState()
val request = JSONObject().apply {
@@ -96,6 +96,7 @@ class VaultSyncEngine(
(encryptionKey ?: vaultStore.getEncryptionKeyBase64())?.let { request.put("encryptionKey", it) }
(state("accountPublicKey") as? String)?.let { request.put("accountPublicKey", it) }
vaultStore.accountPrivateKey?.let { request.put("accountPrivateKey", it) }
+ sharing?.let { request.put("sharing", it) }
return request.toString()
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt
index 3be5f1c91..b006acd43 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt
@@ -157,6 +157,18 @@ class AndroidStorageProvider(private val context: Context) : StorageProvider {
}
}
+ override fun setCapabilities(json: String) {
+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)
+ sharedPreferences.edit {
+ putString("capabilities", json)
+ }
+ }
+
+ override fun getCapabilities(): String? {
+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)
+ return sharedPreferences.getString("capabilities", null)
+ }
+
// region Sync State
override fun setIsDirty(isDirty: Boolean) {
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt
index 24b8ff82a..2e575852a 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt
@@ -130,6 +130,18 @@ interface StorageProvider {
*/
fun clearServerVersion()
+ /**
+ * Set the capabilities the server resolved for this account.
+ * @param json The capabilities as a JSON object, keyed by capability key
+ */
+ fun setCapabilities(json: String)
+
+ /**
+ * Get the capabilities the server resolved for this account.
+ * @return The capabilities as a JSON object, or null if none were stored yet
+ */
+ fun getCapabilities(): String?
+
// region Sync State
/**
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt
index 2f6e319c8..a70819649 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt
@@ -17,6 +17,7 @@ class TestStorageProvider : StorageProvider {
private var username: String? = null
private var offlineMode: Boolean = false
private var serverVersion: String? = null
+ private var capabilities: String? = null
private var isDirty: Boolean = false
private var mutationSequence: Int = 0
private var isSyncing: Boolean = false
@@ -108,6 +109,14 @@ class TestStorageProvider : StorageProvider {
serverVersion = null
}
+ override fun setCapabilities(json: String) {
+ capabilities = json
+ }
+
+ override fun getCapabilities(): String? {
+ return capabilities
+ }
+
// region Sync State
override fun setIsDirty(isDirty: Boolean) {
diff --git a/apps/mobile-app/app/_layout.tsx b/apps/mobile-app/app/_layout.tsx
index aa8418125..cadbd4354 100644
--- a/apps/mobile-app/app/_layout.tsx
+++ b/apps/mobile-app/app/_layout.tsx
@@ -17,6 +17,7 @@ import SpaceMono from '@/assets/fonts/SpaceMono-Regular.ttf';
import { AliasVaultToast } from '@/components/Toast';
import { AppProvider } from '@/context/AppContext';
import { AuthProvider } from '@/context/AuthContext';
+import { CapabilityProvider } from '@/context/CapabilityContext';
import { ClipboardCountdownProvider } from '@/context/ClipboardCountdownContext';
import { DbProvider } from '@/context/DbContext';
import { DialogProvider } from '@/context/DialogContext';
@@ -146,17 +147,19 @@ export default function RootLayout() : React.ReactNode {
<NavigationProvider>
<DbProvider>
<AuthProvider>
- <WebApiProvider>
- <AppProvider>
- <ClipboardCountdownProvider>
- <DialogProvider>
- <GestureHandlerRootView>
- <RootLayoutNav />
- </GestureHandlerRootView>
- </DialogProvider>
- </ClipboardCountdownProvider>
- </AppProvider>
- </WebApiProvider>
+ <CapabilityProvider>
+ <WebApiProvider>
+ <AppProvider>
+ <ClipboardCountdownProvider>
+ <DialogProvider>
+ <GestureHandlerRootView>
+ <RootLayoutNav />
+ </GestureHandlerRootView>
+ </DialogProvider>
+ </ClipboardCountdownProvider>
+ </AppProvider>
+ </WebApiProvider>
+ </CapabilityProvider>
</AuthProvider>
</DbProvider>
</NavigationProvider>
diff --git a/apps/mobile-app/components/folders/FolderSelectorModal.tsx b/apps/mobile-app/components/folders/FolderSelectorModal.tsx
index 4c964ead1..cd19a4f65 100644
--- a/apps/mobile-app/components/folders/FolderSelectorModal.tsx
+++ b/apps/mobile-app/components/folders/FolderSelectorModal.tsx
@@ -9,15 +9,12 @@ import {
ScrollView,
} from 'react-native';
+import { isSharedFolder } from '@aliasvault/client/items/FolderUtils';
import { useColors } from '@/hooks/useColorScheme';
import { ModalWrapper } from '@/components/common/ModalWrapper';
+import { FolderIcon } from '@/components/folders/FolderIcon';
-type Folder = {
- Id: string;
- Name: string;
- ParentFolderId: string | null;
- Weight: number;
-};
+import type { Folder } from '@aliasvault/client/database/repositories/FolderRepository';
type FolderTreeNode = Folder & {
children: FolderTreeNode[];
@@ -29,6 +26,7 @@ type FolderTreeNode = Folder & {
interface IFolderSelectorModalProps {
folders: Folder[];
selectedFolderId: string | null | undefined;
+ personalManifestId: string | null;
onFolderChange: (folderId: string | null) => void;
isOpen: boolean;
onClose: () => void;
@@ -43,6 +41,7 @@ interface IFolderSelectorModalProps {
export const FolderSelectorModal: React.FC<IFolderSelectorModalProps> = ({
folders,
selectedFolderId,
+ personalManifestId,
onFolderChange,
isOpen,
onClose,
@@ -277,8 +276,8 @@ export const FolderSelectorModal: React.FC<IFolderSelectorModalProps> = ({
</View>
{/* Folder icon */}
- <MaterialIcons
- name="folder"
+ <FolderIcon
+ isShared={isSharedFolder(node, personalManifestId)}
size={22}
color={isSelected ? colors.tint : colors.textMuted}
style={styles.folderIcon}
@@ -309,7 +308,7 @@ export const FolderSelectorModal: React.FC<IFolderSelectorModalProps> = ({
)}
</View>
);
- }, [expandedFolders, selectedFolderId, handleSelectFolder, toggleFolder, colors, styles]);
+ }, [expandedFolders, selectedFolderId, personalManifestId, handleSelectFolder, toggleFolder, colors, styles]);
const modalContent = (
<View style={styles.modalContainer}>
diff --git a/apps/mobile-app/context/CapabilityContext.tsx b/apps/mobile-app/context/CapabilityContext.tsx
new file mode 100644
index 000000000..d17a79218
--- /dev/null
+++ b/apps/mobile-app/context/CapabilityContext.tsx
@@ -0,0 +1,95 @@
+import { type CapabilityKey, isCapabilityEnabled } from '@aliasvault/models/webapi';
+import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
+
+import { useAuth } from '@/context/AuthContext';
+import NativeVaultManager from '@/specs/NativeVaultManager';
+import emitter from '@/utils/EventEmitter';
+
+/** The resolved capabilities, keyed by capability key. */
+type Capabilities = Record<string, string>;
+
+type CapabilityContextType = {
+ isEnabled: (key: CapabilityKey) => boolean;
+ isLoaded: boolean;
+}
+
+const CapabilityContext = createContext<CapabilityContextType | undefined>(undefined);
+
+/**
+ * Serves this account's capabilities to the UI. The native sync stores what the server resolved, so they are
+ * re-read after every sync, and when the login state changes because a logout clears them.
+ */
+export const CapabilityProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const { isLoggedIn } = useAuth();
+ const [capabilities, setCapabilities] = useState<Capabilities>({});
+ const [isLoaded, setIsLoaded] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ /**
+ * Read the stored capabilities. An unknown capability is off, so a failed read leaves every gated screen hidden.
+ */
+ const load = async (): Promise<void> => {
+ const stored = await NativeVaultManager.getCapabilities().then(parseCapabilities).catch(() => ({}));
+ if (!cancelled) {
+ setCapabilities(stored);
+ setIsLoaded(true);
+ }
+ };
+
+ load();
+ const subscription = emitter.addListener('vaultSynced', load);
+
+ return (): void => {
+ cancelled = true;
+ subscription.remove();
+ };
+ }, [isLoggedIn]);
+
+ const isEnabled = useCallback((key: CapabilityKey): boolean => isCapabilityEnabled(capabilities[key]), [capabilities]);
+
+ const value = useMemo(() => ({ isEnabled, isLoaded }), [isEnabled, isLoaded]);
+
+ return (
+ <CapabilityContext.Provider value={value}>
+ {children}
+ </CapabilityContext.Provider>
+ );
+};
+
+/**
+ * The capability check for this account.
+ */
+export const useCapabilities = (): CapabilityContextType['isEnabled'] => {
+ return useCapabilityContext().isEnabled;
+};
+
+/**
+ * The capabilities of this account, with whether they have been read yet.
+ */
+export const useCapabilityContext = (): CapabilityContextType => {
+ const context = useContext(CapabilityContext);
+ if (context === undefined) {
+ throw new Error('useCapabilities must be used within a CapabilityProvider');
+ }
+
+ return context;
+};
+
+/**
+ * Parse the stored capabilities, reading anything that is not a JSON object as none.
+ * @param json - the capabilities as stored natively, or null when no sync stored any yet.
+ */
+function parseCapabilities(json: string | null): Capabilities {
+ if (!json) {
+ return {};
+ }
+
+ try {
+ const parsed: unknown = JSON.parse(json);
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Capabilities : {};
+ } catch {
+ return {};
+ }
+}
diff --git a/apps/mobile-app/hooks/usePersonalManifestId.ts b/apps/mobile-app/hooks/usePersonalManifestId.ts
new file mode 100644
index 000000000..313abc6af
--- /dev/null
+++ b/apps/mobile-app/hooks/usePersonalManifestId.ts
@@ -0,0 +1,32 @@
+import { useEffect, useState } from 'react';
+
+import { useDb } from '@/context/DbContext';
+
+/**
+ * The id of the user's personal manifest, which is what tells a shared folder apart from the user's own.
+ */
+export function usePersonalManifestId(): string | null {
+ const { sqliteClient, dbAvailable, isSyncing } = useDb();
+ const [personalManifestId, setPersonalManifestId] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!sqliteClient || !dbAvailable || isSyncing) {
+ return;
+ }
+
+ let cancelled = false;
+ sqliteClient.getPersonalManifestId().then((id) => {
+ if (!cancelled) {
+ setPersonalManifestId(id);
+ }
+ }).catch(() => {
+ // Without the id no folder is marked as shared, which is the safe reading of an unknown.
+ });
+
+ return (): void => {
+ cancelled = true;
+ };
+ }, [sqliteClient, dbAvailable, isSyncing]);
+
+ return personalManifestId;
+}
diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.ts
index 178e3c9bc..f88dde9a7 100644
--- a/apps/mobile-app/hooks/useVaultSync.ts
+++ b/apps/mobile-app/hooks/useVaultSync.ts
@@ -6,6 +6,7 @@ import { useTranslation } from '@/hooks/useTranslation';
import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
+import emitter from '@/utils/EventEmitter';
import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
import {
AppErrorCode,
@@ -251,6 +252,7 @@ export const useVaultSync = (): {
} finally {
syncInProgressRef.current = false;
await dbContext.refreshSyncState();
+ emitter.emit('vaultSynced');
dbContext.setIsSyncing(false);
dbContext.setIsUploading(false);
}
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index 94975f988..fe2f624c4 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -269,6 +269,10 @@
[vaultManager getServerVersion:resolve rejecter:reject];
}
+- (void)getCapabilities:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager getCapabilities:resolve rejecter:reject];
+}
+
// MARK: - Offline Mode Management
- (void)setOfflineMode:(BOOL)isOffline resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
@@ -297,6 +301,10 @@
[vaultManager migrateVaultManifest:resolve rejecter:reject];
}
+- (void)runSharingOperation:(NSString *)operation paramsJson:(NSString *)paramsJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager runSharingOperation:operation paramsJson:paramsJson resolver:resolve rejecter:reject];
+}
+
- (void)getVaultSyncLogs:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
[vaultManager getVaultSyncLogs:resolve rejecter:reject];
}
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 7561b5e7e..db3b2b297 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -708,6 +708,12 @@ public class VaultManager: NSObject {
resolve(isGreaterOrEqual)
}
+ @objc
+ func getCapabilities(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ resolve(vaultStore.getCapabilities())
+ }
+
@objc
func getServerVersion(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
@@ -860,6 +866,31 @@ public class VaultManager: NSObject {
}
}
+ /// Run a sharing operation of the sync engine (see VaultStore.runSharingOperation). Failures resolve with the error code.
+ @objc
+ func runSharingOperation(_ operation: String,
+ paramsJson: String,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ guard let data = paramsJson.data(using: .utf8), let params = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else {
+ reject("VAULT_SHARING_ERROR", "The sharing operation parameters are not a JSON object", nil)
+ return
+ }
+ Task {
+ let result = await vaultStore.runSharingOperation(operation, params: params, using: webApiService)
+ await MainActor.run {
+ let response: [String: Any] = [
+ "success": result.success,
+ "vaultUpgradeRequired": result.vaultUpgradeRequired,
+ "apiErrorCode": result.apiErrorCode as Any,
+ "error": result.error as Any,
+ "errorMessage": result.errorMessage as Any
+ ]
+ resolve(response)
+ }
+ }
+ }
+
// MARK: - PIN Unlock Methods
@objc
diff --git a/apps/mobile-app/ios/VaultStoreKit/Models/SyncModels.swift b/apps/mobile-app/ios/VaultStoreKit/Models/SyncModels.swift
index 7db834a44..2a22593e2 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Models/SyncModels.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Models/SyncModels.swift
@@ -76,3 +76,20 @@ public struct VaultMigrationResult {
self.errorMessage = errorMessage
}
}
+
+/// Result of a sharing operation of the sync engine (creating a shared manifest, inviting a member to one).
+public struct VaultSharingResult {
+ public let success: Bool
+ public let apiErrorCode: String?
+ public let vaultUpgradeRequired: Bool
+ public let error: String?
+ public let errorMessage: String?
+
+ public init(success: Bool, apiErrorCode: String? = nil, vaultUpgradeRequired: Bool = false, error: String? = nil, errorMessage: String? = nil) {
+ self.success = success
+ self.apiErrorCode = apiErrorCode
+ self.vaultUpgradeRequired = vaultUpgradeRequired
+ self.error = error
+ self.errorMessage = errorMessage
+ }
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
index 9aee3f9fc..44ae3f2e5 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
@@ -110,6 +110,28 @@ internal final class VaultSync {
return VaultMigrationResult(success: true, pushed: pushed)
}
+ /// Run a sharing operation of the engine.
+ func runSharingOperation(_ operation: String, params: [String: Any], using webApiService: WebApiService) async -> VaultSharingResult {
+ guard Self.sharingOperations.contains(operation) else {
+ return failedSharing(.syncEngineFailed(message: "Unknown sharing operation \(operation)"))
+ }
+ let result: [String: Any]
+ do {
+ result = try await run(operation, using: webApiService, sharing: params)
+ } catch {
+ return failedSharing(Self.driverError(error))
+ }
+ if result["success"] as? Bool == true {
+ return VaultSharingResult(success: true)
+ }
+ let apiErrorCode = result["apiErrorCode"] as? String
+ let vaultUpgradeRequired = result["vaultUpgradeRequired"] as? Bool ?? false
+ if apiErrorCode != nil || vaultUpgradeRequired {
+ return VaultSharingResult(success: false, apiErrorCode: apiErrorCode, vaultUpgradeRequired: vaultUpgradeRequired)
+ }
+ return failedSharing(Self.syncError(from: result))
+ }
+
/// Push the pending local changes (after a native mutation such as an autofill link or a passkey creation).
func mutateVault(using webApiService: WebApiService) async throws {
let result = await syncVaultWithServer(using: webApiService)
@@ -119,10 +141,10 @@ internal final class VaultSync {
}
/// Run one engine operation and adopt what it reported. A driver failure surfaces as the native error.
- private func run(_ operation: String, using webApiService: WebApiService, encryptionKey: String? = nil) async throws -> [String: Any] {
+ private func run(_ operation: String, using webApiService: WebApiService, encryptionKey: String? = nil, sharing: [String: Any]? = nil) async throws -> [String: Any] {
let result: [String: Any]
do {
- result = try await VaultSyncEngine(vaultStore: vaultStore, webApiService: webApiService).run(operation: operation, encryptionKey: encryptionKey)
+ result = try await VaultSyncEngine(vaultStore: vaultStore, webApiService: webApiService).run(operation: operation, encryptionKey: encryptionKey, sharing: sharing)
} catch {
throw Self.driverError(error)
}
@@ -130,12 +152,15 @@ internal final class VaultSync {
return result
}
- /// Persist what the engine reported: server version, offline mode, session values it changed, and the email
- /// routing a pulled vault came with. Capabilities are not stored: the mobile app has no capability gate yet.
+ /// Persist what the engine reported: server version and capabilities, offline mode, session values it changed,
+ /// and the email routing a pulled vault came with.
private func adoptSyncResult(_ result: [String: Any]) {
if let serverVersion = result["serverVersion"] as? String, !serverVersion.isEmpty {
vaultStore.setServerVersion(serverVersion)
}
+ if let capabilities = result["capabilities"] as? [String: String], let data = try? JSONSerialization.data(withJSONObject: capabilities), let json = String(data: data, encoding: .utf8) {
+ vaultStore.setCapabilities(json)
+ }
if let offline = result["isOfflineMode"] as? Bool {
vaultStore.setOfflineMode(offline)
}
@@ -164,6 +189,12 @@ internal final class VaultSync {
return VaultMigrationResult(success: false, pushed: false, error: error.code, errorMessage: error.message)
}
+ /// A failed sharing operation return.
+ private func failedSharing(_ error: AppError) -> VaultSharingResult {
+ print("[VaultSync] Sharing operation failed (\(error.code)): \(error.message)")
+ return VaultSharingResult(success: false, error: error.code, errorMessage: error.message)
+ }
+
/// An error the driver itself threw (a request it could not build, a command it could not decode).
private static func driverError(_ error: Error) -> AppError {
if let appError = error as? AppError {
@@ -183,6 +214,9 @@ internal final class VaultSync {
return (codedErrors[code] ?? { .unknownError(message: $0) })(message)
}
+ /// The engine operations the sharing screen may ask for.
+ private static let sharingOperations: Set<String> = ["createSharedManifest", "inviteToSharedManifest"]
+
/// The forced logouts by the engine's reason.
private static let logoutErrors: [String: AppError] = [
"clientVersionNotSupported": .clientVersionNotSupported,
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
index e6d859441..834c4b532 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
@@ -38,13 +38,13 @@ public final class VaultSyncEngine {
closeStaging()
}
- /// Run one engine operation (`fullSync`, `statusCheck`, `migrationStatus`, `migrateManifest`, `resolveVaultKey`) and
- /// return its result. `encryptionKey` overrides the store's key for the one operation that runs before it is known.
- public func run(operation: String, forcePull: Bool = false, encryptionKey: String? = nil) async throws -> [String: Any] {
+ /// Run one engine operation (`fullSync`, `statusCheck`, `migrationStatus`, `migrateManifest`, `resolveVaultKey`, or a
+ /// sharing operation) and return its result.
+ public func run(operation: String, forcePull: Bool = false, encryptionKey: String? = nil, sharing: [String: Any]? = nil) async throws -> [String: Any] {
let log = VaultSyncRunLog(operation: operation)
runLog = log
var finalResult: [String: Any]?
- let session = try VaultSyncSession(requestJson: try buildRequest(operation: operation, forcePull: forcePull, encryptionKey: encryptionKey))
+ let session = try VaultSyncSession(requestJson: try buildRequest(operation: operation, forcePull: forcePull, encryptionKey: encryptionKey, sharing: sharing))
defer {
closeStaging()
log.finish(result: finalResult, userDefaults: vaultStore.userDefaults)
@@ -69,7 +69,7 @@ public final class VaultSyncEngine {
// MARK: - Request
- private func buildRequest(operation: String, forcePull: Bool, encryptionKey: String?) throws -> String {
+ private func buildRequest(operation: String, forcePull: Bool, encryptionKey: String?, sharing: [String: Any]?) throws -> String {
let metadata = vaultStore.getVaultMetadataObject()
let syncState = vaultStore.getSyncState()
var request: [String: Any] = [
@@ -93,6 +93,9 @@ public final class VaultSyncEngine {
if let privateKey = vaultStore.accountPrivateKey {
request["accountPrivateKey"] = privateKey
}
+ if let sharing = sharing {
+ request["sharing"] = sharing
+ }
return try Self.serializeJson(request)
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
index 38a64e3aa..5284c1708 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
@@ -63,6 +63,7 @@ extension VaultStore {
self.userDefaults.removeObject(forKey: VaultConstants.offlineModeKey)
self.userDefaults.removeObject(forKey: VaultConstants.pinEnabledKey)
self.userDefaults.removeObject(forKey: VaultConstants.serverVersionKey)
+ self.userDefaults.removeObject(forKey: VaultConstants.capabilitiesKey)
// Clear sync state
self.userDefaults.removeObject(forKey: VaultConstants.isDirtyKey)
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift
index c4dbb7d0c..bcdaccb94 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift
@@ -112,6 +112,18 @@ extension VaultStore {
userDefaults.synchronize()
}
+ // MARK: - Capabilities Storage
+
+ /// Set the capabilities the server resolved for this account, as a JSON object
+ public func setCapabilities(_ json: String) {
+ userDefaults.set(json, forKey: VaultConstants.capabilitiesKey)
+ }
+
+ /// Get the capabilities the server resolved for this account, as a JSON object
+ public func getCapabilities() -> String? {
+ return userDefaults.string(forKey: VaultConstants.capabilitiesKey)
+ }
+
/// Check if the stored server version is greater than or equal to the specified version
/// - Parameter targetVersion: The version to compare against (e.g., "0.25.0")
/// - Returns: true if stored server version >= targetVersion, false if server version not available or less than target
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
index 2d76370a7..4bf2bf44c 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
@@ -29,6 +29,11 @@ extension VaultStore {
return await sync.migrateVaultManifest(using: webApiService)
}
+ /// Run a sharing operation of the sync engine (see VaultSync.runSharingOperation).
+ public func runSharingOperation(_ operation: String, params: [String: Any], using webApiService: WebApiService) async -> VaultSharingResult {
+ return await sync.runSharingOperation(operation, params: params, using: webApiService)
+ }
+
/// Push the pending local changes (after a native mutation such as an autofill link or a passkey creation).
public func mutateVault(using webApiService: WebApiService) async throws {
try await sync.mutateVault(using: webApiService)
diff --git a/apps/mobile-app/ios/VaultUtils/VaultConstants.swift b/apps/mobile-app/ios/VaultUtils/VaultConstants.swift
index f547f29bf..818d5dca5 100644
--- a/apps/mobile-app/ios/VaultUtils/VaultConstants.swift
+++ b/apps/mobile-app/ios/VaultUtils/VaultConstants.swift
@@ -18,6 +18,7 @@ public struct VaultConstants {
public static let offlineModeKey = "aliasvault_offline_mode"
public static let pinEnabledKey = "aliasvault_pin_enabled"
public static let serverVersionKey = "aliasvault_server_version"
+ public static let capabilitiesKey = "aliasvault_capabilities"
public static let autofillCopyTotpOnFillKey = "aliasvault_autofill_copy_totp_on_fill"
public static let isDirtyKey = "aliasvault_is_dirty"
public static let mutationSequenceKey = "aliasvault_mutation_sequence"
diff --git a/apps/mobile-app/platform/MobilePlatform.ts b/apps/mobile-app/platform/MobilePlatform.ts
index 332721bcb..aacb9778c 100644
--- a/apps/mobile-app/platform/MobilePlatform.ts
+++ b/apps/mobile-app/platform/MobilePlatform.ts
@@ -11,9 +11,9 @@ import { MobileAppIdentity } from '@/utils/AppInfo';
* Which translation key backs each of the client core's own messages.
*/
const TRANSLATION_KEYS: Record<TranslatableMessage, string> = {
- [TranslatableMessage.UnnamedSharedVault]: 'items.sharedFolderName',
+ [TranslatableMessage.UnnamedSharedVault]: 'sharing.family.unnamedVault',
[TranslatableMessage.ClientOutdated]: 'vault.errors.appOutdated',
- [TranslatableMessage.SharedFolderDeleteRefused]: 'items.deleteSharedFolderHint',
+ [TranslatableMessage.SharedFolderDeleteRefused]: 'items.folders.deleteSharedFolderHint',
[TranslatableMessage.VaultUpgradeRequired]: 'vault.errors.vaultOutdated',
};
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index e2a1d6202..1e4705ec1 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -32,12 +32,15 @@ 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. A vault that still has to be upgraded is reported through the two *Required flags and not synced.
+ // Vault sync.
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 }>;
+ // A sharing operation of the sync engine.
+ runSharingOperation(operation: string, paramsJson: string): Promise<{ success: boolean; apiErrorCode: string | null; vaultUpgradeRequired: 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 }>;
@@ -113,6 +116,9 @@ export interface Spec extends TurboModule {
isServerVersionGreaterThanOrEqualTo(targetVersion: string): Promise<boolean>;
getServerVersion(): Promise<string | null>;
+ // The capabilities the server resolved for this account as a JSON object, or null when no sync stored any yet.
+ getCapabilities(): Promise<string | null>;
+
// PIN unlock methods
isPinEnabled(): Promise<boolean>;
isKeystoreAvailable(): Promise<boolean>;
diff --git a/apps/mobile-app/utils/SqliteClient.ts b/apps/mobile-app/utils/SqliteClient.ts
index ce6298809..9a94a07fe 100644
--- a/apps/mobile-app/utils/SqliteClient.ts
+++ b/apps/mobile-app/utils/SqliteClient.ts
@@ -26,7 +26,7 @@ class SqliteClient {
private readonly database = new NativeDatabaseClient();
/**
- * The logo repository itself, which the item and folder repositories call into.
+ * The logo repository itself, which the item repository calls into.
*/
private readonly logoRepository = new LogoRepository(this.database);
@@ -38,7 +38,7 @@ class SqliteClient {
/**
* Repository for Folder operations.
*/
- public readonly folders = asyncRepository(new FolderRepository(this.database, this.logoRepository), this.database);
+ public readonly folders = asyncRepository(new FolderRepository(this.database), this.database);
/**
* Repository for item logo operations.
@@ -65,6 +65,13 @@ class SqliteClient {
*/
public readonly itemStats = asyncRepository(new ItemStatsRepository(this.database), this.database);
+ /**
+ * The id of the user's personal manifest, or null when no pull has recorded one yet.
+ */
+ public getPersonalManifestId(): Promise<string | null> {
+ return this.database.getPersonalManifestId();
+ }
+
/**
* Store the vault metadata via the native code implementation.
*
diff --git a/apps/mobile-app/utils/WebApiService.ts b/apps/mobile-app/utils/WebApiService.ts
index b635f19f8..d8802df65 100644
--- a/apps/mobile-app/utils/WebApiService.ts
+++ b/apps/mobile-app/utils/WebApiService.ts
@@ -5,6 +5,7 @@ import type { StatusResponse, VaultResponse, AuthLogModel, RefreshToken } from '
import i18n from '@/i18n';
+import { ApiRequestError } from '@aliasvault/client/api/errors/ApiRequestError';
import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';
import { LocalAuthError } from './types/errors/LocalAuthError';
import { PayloadTooLargeError } from '@aliasvault/client/api/errors/PayloadTooLargeError';
@@ -101,7 +102,9 @@ export class WebApiService {
}
if (response.statusCode >= 400 && throwOnError) {
- throw new Error(i18n.t('auth.errors.httpError', { status: response.statusCode }));
+ const error = new ApiRequestError(response.statusCode, extractApiErrorCode(response.body));
+ error.message = i18n.t('auth.errors.httpError', { status: response.statusCode });
+ throw error;
}
// Parse response body if requested
@@ -372,3 +375,21 @@ export class WebApiService {
}
}
}
+
+/**
+ * Extract the structured API error code (e.g. "VAULT_NOT_UP_TO_DATE") from an error response body.
+ */
+function extractApiErrorCode(body: string | null | undefined): string | null {
+ try {
+ const parsed = JSON.parse(body ?? '') as { code?: unknown; title?: unknown };
+ for (const value of [parsed.code, parsed.title]) {
+ // Server error codes are uppercase enum names
+ if (typeof value === 'string' && /^[A-Z0-9_]{2,64}$/.test(value)) {
+ return value;
+ }
+ }
+ } catch {
+ // Body is empty or not JSON (e.g. proxy error page).
+ }
+ return null;
+}