Skip to content

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

Add mobile app new identity code and family sharing helpers (#2536)

Leendert de Borst27613dcf2ead
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 e1e9afd2c..cbabdf4e9 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
@@ -350,6 +350,15 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
promise.resolve(vaultStore.decryptWithAccountPrivateKey(encryptedName))
}
+ /**
+ * The identity code of the account's own signing key; null while locked or when the account has no signing key yet.
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun getSigningKeyFingerprint(promise: Promise) {
+ promise.resolve(vaultStore.signingKeyFingerprint())
+ }
+
/**
* Resolve and store the vault key right after login from the unlock key (see VaultStore.resolveVaultKey).
* Resolves with no value; rejects with the native error code when the chain does not open or the session is gone.
@@ -1539,7 +1548,7 @@ 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 operation The operation, one of VaultSync.SHARING_OPERATIONS.
* @param paramsJson What the operation acts on, as a JSON object.
* @param promise The promise to resolve with the operation result.
*/
@@ -1554,6 +1563,9 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
putString("apiErrorCode", result.apiErrorCode)
putString("error", result.error)
putString("errorMessage", result.errorMessage)
+ putString("manifestId", result.manifestId)
+ putString("username", result.username)
+ putBoolean("alreadyMember", result.alreadyMember)
}
withContext(Dispatchers.Main) {
promise.resolve(resultMap)
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 dc9b2f2ab..78a944416 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
@@ -63,13 +63,16 @@ data class VaultMigrationResult(
)
/**
- * Result of a sharing operation of the sync engine (creating a shared manifest, inviting a member to one).
+ * Result of a sharing operation of the sync engine (creating a shared manifest, inviting to one, accepting an invitation).
*
* @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.
+ * @property manifestId The shared manifest the operation created, invited to or accepted.
+ * @property username The account an identity code belonged to.
+ * @property alreadyMember The account is already in the folder's group, so only its key was certified.
*/
data class VaultSharingResult(
val success: Boolean,
@@ -77,4 +80,7 @@ data class VaultSharingResult(
val vaultUpgradeRequired: Boolean = false,
val error: String? = null,
val errorMessage: String? = null,
+ val manifestId: String? = null,
+ val username: String? = null,
+ val alreadyMember: Boolean = false,
)
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 bbb5cd8e7..0555857bd 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
@@ -1,6 +1,7 @@
package net.aliasvault.app.vaultstore
import android.os.SystemClock
+import android.util.Base64
import android.util.Log
import kotlinx.coroutines.suspendCancellableCoroutine
import net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallback
@@ -19,6 +20,7 @@ import org.json.JSONObject
import uniffi.aliasvault_core.ItemUsageAction
import uniffi.aliasvault_core.VaultException
import uniffi.aliasvault_core.VaultItem
+import uniffi.aliasvault_core.accountSigningKeyFingerprint
import uniffi.aliasvault_core.rsaDecrypt
import java.util.Date
import java.util.UUID
@@ -260,6 +262,22 @@ class VaultStore(
internal val accountKeyBase64: String?
get() = crypto.accountKeyBase64
+ /**
+ * The identity code of the account's own signing key, derived from the private key the sync engine cached, or null
+ * while the vault is locked or the account has no signing key yet.
+ * Other platform implementations: SharingService.ownIdentityCode (core/client), VaultStore.signingKeyFingerprint (iOS).
+ */
+ fun signingKeyFingerprint(): String? {
+ val accountKey = accountKeyBase64?.let { Base64.decode(it, Base64.NO_WRAP) } ?: return null
+ val encryptedSigningPrivateKey = VaultSyncEngine.persistedState(storageProvider, VaultSyncEngine.ENCRYPTED_SIGNING_PRIVATE_KEY_STATE_KEY) as? String ?: return null
+ return try {
+ accountSigningKeyFingerprint(encryptedSigningPrivateKey, accountKey)
+ } catch (e: VaultException) {
+ Log.w(TAG, "The signing private key did not open", e)
+ null
+ }
+ }
+
/**
* Decrypt base64 RSA-OAEP ciphertext with the session's account private key as UTF-8 text, or null when the session
* holds no private key or it does not open the ciphertext.
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 151894c91..d1fdda5c1 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
@@ -31,7 +31,7 @@ class VaultSync(
private const val SYNC_HOLD_POLL_MS = 100L
/** The engine operations the sharing screen may ask for. */
- private val SHARING_OPERATIONS = setOf("createSharedManifest", "inviteToSharedManifest", "updateSharedManifest")
+ private val SHARING_OPERATIONS = setOf("createSharedManifest", "inviteToSharedManifest", "updateSharedManifest", "lookupIdentityCode", "acceptSharedManifestInvitation")
}
/** One engine run at a time: two runs against the same vault overwrite each other's stores and dirty flag. */
@@ -144,7 +144,7 @@ class VaultSync(
}
/**
- * Run a sharing operation of the engine: `createSharedManifest`, `inviteToSharedManifest` or `updateSharedManifest`.
+ * Run a sharing operation of the engine, one of SHARING_OPERATIONS.
*/
suspend fun runSharingOperation(operation: String, params: JSONObject, webApiService: WebApiService): VaultSharingResult {
if (operation !in SHARING_OPERATIONS) {
@@ -156,7 +156,7 @@ class VaultSync(
return failedSharing(e)
}
if (result.optBoolean("success", false)) {
- return VaultSharingResult(true)
+ return VaultSharingResult(true, manifestId = result.optString("manifestId").takeIf { it.isNotEmpty() }, username = result.optString("username").takeIf { it.isNotEmpty() }, alreadyMember = result.optBoolean("alreadyMember", false))
}
val apiErrorCode = result.optString("apiErrorCode").takeIf { it.isNotEmpty() }
val vaultUpgradeRequired = result.optBoolean("vaultUpgradeRequired", false)
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 eb8fda01d..a2efec381 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
@@ -33,6 +33,19 @@ class VaultSyncEngine(
private const val ENCRYPTED_VEK_STATE_KEY = "encryptedVek"
private const val ENCRYPTED_ACCOUNT_PRIVATE_KEY_STATE_KEY = "encryptedAccountPrivateKey"
+ /** Engine state key holding the account signing private key encrypted with the Account Key, which the own identity code derives from. */
+ internal const val ENCRYPTED_SIGNING_PRIVATE_KEY_STATE_KEY = "encryptedSigningPrivateKey"
+
+ /**
+ * One persisted engine value, decoded from the `{"v": value}` JSON text it is stored as.
+ * @param storageProvider The storage the engine state lives in
+ * @param key The engine state key
+ */
+ internal fun persistedState(storageProvider: StorageProvider, key: String): Any? {
+ val json = storageProvider.getSyncEngineState(key) ?: return null
+ return JSONObject(json).opt("v")?.takeIf { it != JSONObject.NULL }
+ }
+
/** Engine state key that lives in the native store instead (the login writes it there), routed on read and write. */
private const val DERIVATION_PARAMS_STATE_KEY = "encryptionKeyDerivationParams"
}
@@ -215,8 +228,7 @@ class VaultSyncEngine(
if (key == DERIVATION_PARAMS_STATE_KEY) {
return storageProvider.getKeyDerivationParams().takeIf { it.isNotBlank() }?.let { JSONObject(it) }
}
- val json = storageProvider.getSyncEngineState(key) ?: return null
- return JSONObject(json).opt("v")?.takeIf { it != JSONObject.NULL }
+ return persistedState(storageProvider, key)
}
private fun setState(key: String, value: Any?) {
diff --git a/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsx b/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsx
index 0ad2aa8e9..d25ea02d0 100644
--- a/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsx
@@ -1,7 +1,9 @@
import { scopedKey, type ItemRef } from '@aliasvault/client/database/ItemRef';
import { canHaveSubfolders, getRecursiveItemCount, isSharedFolder } from '@aliasvault/client/items/FolderUtils';
import { ItemFilter, applySearchFilter, applyTypeFilter, isItemTypeFilter, parseItemFilterType, type ItemFilterType } from '@aliasvault/client/items/ItemFilters';
+import { canAdministerGroup, familySharingText, holdsManifestKey, MAX_SHARED_VAULT_NAME_LENGTH } from '@aliasvault/client/sharing/FamilySharingView';
import { multiManifestRendering } from '@aliasvault/client/sharing/MultiManifestRendering';
+import { SharingService } from '@aliasvault/client/sharing/SharingService';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useNavigation, useRouter, useLocalSearchParams } from 'expo-router';
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
@@ -14,13 +16,17 @@ import type { DisplayItem } from '@/utils/DisplayItem';
import emitter from '@/utils/EventEmitter';
import { folderRoute } from '@/utils/FolderRoute';
import { HapticsUtility } from '@/utils/HapticsUtility';
+import { runSharingOperation, sharingFailureMessage } from '@/utils/SharingErrors';
import { useColors } from '@/hooks/useColorScheme';
import { useItemSort, useSortedItems } from '@/hooks/useItemSort';
import { useNavigationDebounce } from '@/hooks/useNavigationDebounce';
+import { usePasswordConfirmedAction } from '@/hooks/usePasswordConfirmedAction';
import { usePersonalManifestId } from '@/hooks/usePersonalManifestId';
+import { useSharedFolders } from '@/hooks/useSharedFolders';
import { useVaultMutate } from '@/hooks/useVaultMutate';
import { useVaultRefresh } from '@/hooks/useVaultRefresh';
+import { useVaultSync } from '@/hooks/useVaultSync';
import { DeleteFolderModal } from '@/components/folders/DeleteFolderModal';
import { FolderBreadcrumb } from '@/components/folders/FolderBreadcrumb';
@@ -30,6 +36,7 @@ import { FolderPill } from '@/components/folders/FolderPill';
import { AddItemFab } from '@/components/items/AddItemFab';
import { ItemCard } from '@/components/items/ItemCard';
import { SortMenu } from '@/components/items/SortMenu';
+import { SharedFolderAccessModal } from '@/components/sharing/SharedFolderAccessModal';
import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
@@ -37,6 +44,8 @@ import { RobustPressable } from '@/components/ui/RobustPressable';
import { SkeletonLoader } from '@/components/ui/SkeletonLoader';
import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
+import { useDialog } from '@/context/DialogContext';
+import { useWebApi } from '@/context/WebApiContext';
import type { FolderWithCount } from '@/components/folders/FolderPill';
import type { ItemSummary } from '@aliasvault/client/database/mappers/ItemMapper';
@@ -94,6 +103,14 @@ export default function FolderViewScreen(): React.ReactNode {
const [showEditFolderModal, setShowEditFolderModal] = useState(false);
const [showDeleteFolderModal, setShowDeleteFolderModal] = useState(false);
const [showCreateSubfolderModal, setShowCreateSubfolderModal] = useState(false);
+ /** The folder whose people sheet is open; kept while the folder turns into a shared one or a personal one and the screen moves to it. */
+ const [peopleFolder, setPeopleFolder] = useState<{ folder: Folder; isShared: boolean } | null>(null);
+ const shared = useSharedFolders();
+ const reloadShared = shared.reload;
+ const webApi = useWebApi();
+ const { syncVault } = useVaultSync();
+ const { showConfirm } = useDialog();
+ const runWithPassword = usePasswordConfirmedAction();
const authContext = useApp();
const dbContext = useDb();
@@ -233,9 +250,41 @@ export default function FolderViewScreen(): React.ReactNode {
loadItems();
}, [isAuthenticated, isDatabaseAvailable, loadItems, setIsLoadingItems]);
- // A virtual folder (e.g. shared manifest) is not editable or deletable here.
+ // A virtual folder (a shared manifest) is renamed and deleted through its shared folder, not as a stored folder.
const isVirtualFolder = multiManifestRendering.isVirtualFolder(folderRef);
const isShared = isSharedFolder(folderRef, personalManifestId);
+ const currentShared = isVirtualFolder ? shared.folders.find(candidate => candidate.manifest.manifestId.toLowerCase() === folderRef.ManifestId.toLowerCase()) ?? null : null;
+ const canManageShared = currentShared !== null && canAdministerGroup(currentShared.group);
+ const canEditFolder = !isVirtualFolder || (canManageShared && holdsManifestKey(currentShared.manifest, shared.myUserId));
+ const canDeleteFolder = !isVirtualFolder || canManageShared;
+ const canShareFolder = shared.isEnabled && folder !== null && (isVirtualFolder || !folder.ParentFolderId);
+
+ /**
+ * Delete the shared folder for everyone, after a confirmation and the master password, then go to the vault root.
+ */
+ const deleteSharedFolder = useCallback((): void => {
+ if (!currentShared) {
+ return;
+ }
+ const name = folder?.Name ?? '';
+ showConfirm(familySharingText.deleteVault, familySharingText.deleteVaultConfirm(name), t('common.delete'), async () => {
+ try {
+ const done = await runWithPassword(familySharingText.deleteVault, familySharingText.deleteVaultPasswordPrompt(name), t('common.delete'), answerChallenge => (
+ SharingService.deleteSharedManifest(webApi, currentShared.group.groupId, currentShared.manifest.manifestId, answerChallenge)
+ ));
+ if (!done) {
+ return;
+ }
+ await syncVault();
+ emitter.emit('itemChanged');
+ await reloadShared();
+ Toast.show({ type: 'success', text1: familySharingText.vaultDeleted });
+ router.dismissTo('/(tabs)/items');
+ } catch (deleteError) {
+ Toast.show({ type: 'error', text1: sharingFailureMessage(deleteError, familySharingText.errors.deleteVaultFailed) });
+ }
+ }, { confirmStyle: 'destructive' });
+ }, [currentShared, folder?.Name, showConfirm, runWithPassword, webApi, syncVault, reloadShared, router, t]);
/**
* Set up header with folder name and edit/delete buttons.
@@ -250,32 +299,41 @@ export default function FolderViewScreen(): React.ReactNode {
/**
* Header right buttons for edit and delete.
*/
- headerRight: (): React.ReactNode => (isVirtualFolder ? null : (
+ headerRight: (): React.ReactNode => (
<View style={{ flexDirection: 'row', gap: 4 }}>
- <RobustPressable
- onPress={() => setShowEditFolderModal(true)}
- style={{ padding: 8 }}
- >
- <MaterialIcons
- name="edit"
- size={Platform.OS === 'android' ? 24 : 22}
- color={colors.primary}
- />
- </RobustPressable>
- <RobustPressable
- onPress={() => setShowDeleteFolderModal(true)}
- style={{ padding: 8 }}
- >
- <MaterialIcons
- name="delete"
- size={Platform.OS === 'android' ? 24 : 22}
- color={colors.destructive}
- />
- </RobustPressable>
+ {canShareFolder && folder && (
+ <RobustPressable onPress={() => setPeopleFolder({ folder, isShared: isVirtualFolder })} style={{ padding: 8 }}>
+ <MaterialIcons name="people" size={Platform.OS === 'android' ? 24 : 22} color={colors.primary} />
+ </RobustPressable>
+ )}
+ {canEditFolder && (
+ <RobustPressable
+ onPress={() => setShowEditFolderModal(true)}
+ style={{ padding: 8 }}
+ >
+ <MaterialIcons
+ name="edit"
+ size={Platform.OS === 'android' ? 24 : 22}
+ color={colors.primary}
+ />
+ </RobustPressable>
+ )}
+ {canDeleteFolder && (
+ <RobustPressable
+ onPress={() => (isVirtualFolder ? deleteSharedFolder() : setShowDeleteFolderModal(true))}
+ style={{ padding: 8 }}
+ >
+ <MaterialIcons
+ name="delete"
+ size={Platform.OS === 'android' ? 24 : 22}
+ color={colors.destructive}
+ />
+ </RobustPressable>
+ )}
</View>
- )),
+ ),
});
- }, [navigation, folder?.Name, isVirtualFolder, isShared, colors.primary, colors.destructive, t]);
+ }, [navigation, folder, isVirtualFolder, isShared, canShareFolder, canEditFolder, canDeleteFolder, deleteSharedFolder, colors.primary, colors.destructive, t]);
/**
* Delete an item (move to trash).
@@ -336,6 +394,19 @@ export default function FolderViewScreen(): React.ReactNode {
setShowEditFolderModal(false);
}, [dbContext.sqliteClient, folderRef, executeVaultMutation, loadItems]);
+ /**
+ * Rename the shared folder: its name is encrypted with its key and kept on the server for every member.
+ */
+ const handleEditSharedFolder = useCallback(async (newName: string) => {
+ if (!currentShared) {
+ return;
+ }
+ await runSharingOperation('updateSharedManifest', { groupId: currentShared.group.groupId, manifestId: currentShared.manifest.manifestId, name: newName }, t('common.errors.unknownErrorTryAgain'));
+ await syncVault();
+ await loadItems();
+ emitter.emit('itemChanged');
+ }, [currentShared, syncVault, loadItems, t]);
+
/**
* Delete the folder (keep items - move them to root).
*/
@@ -862,13 +933,14 @@ export default function FolderViewScreen(): React.ReactNode {
topOffset={Platform.OS === 'ios' ? paddingTop + 104 : paddingTop + 44}
/>
- {/* Folder modals */}
+ {/* Folder modals; a shared folder is renamed through its shared manifest, whose name an invitation has to fit */}
<FolderModal
isOpen={showEditFolderModal}
onClose={() => setShowEditFolderModal(false)}
- onSave={handleEditFolder}
+ onSave={isVirtualFolder ? handleEditSharedFolder : handleEditFolder}
initialName={folder?.Name || ''}
mode="edit"
+ maxLength={isVirtualFolder ? MAX_SHARED_VAULT_NAME_LENGTH : undefined}
/>
<FolderModal
isOpen={showCreateSubfolderModal}
@@ -884,6 +956,22 @@ export default function FolderViewScreen(): React.ReactNode {
onDeleteFolderAndContents={handleDeleteFolderAndContents}
itemCount={totalItemCountInFolderTree}
/>
+ {peopleFolder && (
+ <SharedFolderAccessModal
+ folder={peopleFolder.folder}
+ isShared={peopleFolder.isShared}
+ shared={shared}
+ onMoved={(ref, movedIsShared) => {
+ setPeopleFolder(open => (open ? { folder: { ...open.folder, Id: ref.Id, ManifestId: ref.ManifestId, ParentFolderId: null }, isShared: movedIsShared } : null));
+ router.setParams({ manifestId: ref.ManifestId, id: ref.Id });
+ }}
+ onLeft={() => {
+ setPeopleFolder(null);
+ router.dismissTo('/(tabs)/items');
+ }}
+ onClose={() => setPeopleFolder(null)}
+ />
+ )}
</ThemedContainer>
);
}
diff --git a/apps/mobile-app/app/(tabs)/items/index.tsx b/apps/mobile-app/app/(tabs)/items/index.tsx
index f96fd332c..b8b3cfc3c 100644
--- a/apps/mobile-app/app/(tabs)/items/index.tsx
+++ b/apps/mobile-app/app/(tabs)/items/index.tsx
@@ -2,6 +2,7 @@ import { scopedKey, type ItemRef } from '@aliasvault/client/database/ItemRef';
import { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
import { getRecursiveItemCount, isSharedFolder } from '@aliasvault/client/items/FolderUtils';
import { ItemFilter, applySearchFilter, applyTypeFilter, isItemTypeFilter, type ItemFilterType } from '@aliasvault/client/items/ItemFilters';
+import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useNavigation, useRouter, useLocalSearchParams } from 'expo-router';
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
@@ -19,8 +20,10 @@ import { useColors } from '@/hooks/useColorScheme';
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
import { useNavigationDebounce } from '@/hooks/useNavigationDebounce';
import { usePersonalManifestId } from '@/hooks/usePersonalManifestId';
+import { useSharedFolders } from '@/hooks/useSharedFolders';
import { useVaultMutate } from '@/hooks/useVaultMutate';
import { useVaultRefresh } from '@/hooks/useVaultRefresh';
+import { useVaultSync } from '@/hooks/useVaultSync';
import Logo from '@/assets/images/logo.svg';
import { FolderModal } from '@/components/folders/FolderModal';
@@ -29,6 +32,7 @@ import { AddItemFab } from '@/components/items/AddItemFab';
import { ItemCard } from '@/components/items/ItemCard';
import { ItemFilterMenu } from '@/components/items/ItemFilterMenu';
import { SortMenu } from '@/components/items/SortMenu';
+import { SharedFolderInvitationModal } from '@/components/sharing/SharedFolderInvitationModal';
import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
@@ -82,6 +86,9 @@ export default function ItemsScreen(): React.ReactNode {
const [hasLoadedItems, setHasLoadedItems] = useState(false);
const { executeVaultMutation } = useVaultMutate();
const [showFolderModal, setShowFolderModal] = useState(false);
+ const shared = useSharedFolders();
+ const { syncVault } = useVaultSync();
+ const [openInvitationId, setOpenInvitationId] = useState<string | null>(null);
// Search and filter state
const [searchQuery, setSearchQuery] = useState('');
@@ -444,6 +451,22 @@ export default function ItemsScreen(): React.ReactNode {
});
}, [router, navigate, filterType]);
+ /**
+ * Finish an answered invitation: an accepted one is synced in and opened.
+ * @param manifestId - the shared folder it was for.
+ * @param accepted - whether it was accepted.
+ */
+ const finishInvitation = useCallback(async (manifestId: string, accepted: boolean): Promise<void> => {
+ setOpenInvitationId(null);
+ if (accepted) {
+ await syncVault();
+ await loadItems();
+ const folderId = manifestId.toLowerCase();
+ handleFolderClick({ Id: folderId, ManifestId: folderId });
+ }
+ await shared.reload();
+ }, [syncVault, loadItems, handleFolderClick, shared]);
+
/**
* Create a new folder.
*/
@@ -536,6 +559,27 @@ export default function ItemsScreen(): React.ReactNode {
color: colors.textMuted,
fontSize: 14,
},
+ invitationPill: {
+ alignItems: 'center',
+ backgroundColor: colors.primary + '10',
+ borderColor: colors.primary,
+ borderRadius: 20,
+ borderStyle: 'dashed',
+ borderWidth: 1,
+ flexDirection: 'row',
+ gap: 6,
+ paddingHorizontal: 12,
+ paddingVertical: 8,
+ },
+ invitationPillLabel: {
+ color: colors.primary,
+ fontSize: 12,
+ },
+ invitationPillName: {
+ color: colors.textMuted,
+ fontSize: 14,
+ maxWidth: 120,
+ },
// Search styles
searchContainer: {
position: 'relative',
@@ -706,6 +750,14 @@ export default function ItemsScreen(): React.ReactNode {
onPress={() => handleFolderClick({ Id: folder.id, ManifestId: folder.manifestId })}
/>
))}
+ {/* Invitations to shared folders wait in the folder list until they are answered. */}
+ {shared.invitations.map(invitation => (
+ <TouchableOpacity key={invitation.id} style={styles.invitationPill} onPress={() => setOpenInvitationId(invitation.id)} activeOpacity={0.7}>
+ <MaterialIcons name="mail-outline" size={16} color={colors.primary} />
+ <Text style={styles.invitationPillName} numberOfLines={1} ellipsizeMode="tail">{shared.invitationNames[invitation.id] ?? familySharingText.sharedVault}</Text>
+ <Text style={styles.invitationPillLabel}>{familySharingText.invitationPending}</Text>
+ </TouchableOpacity>
+ ))}
<TouchableOpacity
style={styles.newFolderButton}
onPress={() => setShowFolderModal(true)}
@@ -910,6 +962,17 @@ export default function ItemsScreen(): React.ReactNode {
mode="create"
/>
+ {((): React.ReactNode => {
+ const invitation = shared.invitations.find(candidate => candidate.id === openInvitationId) ?? null;
+ return (
+ <SharedFolderInvitationModal
+ invitation={invitation}
+ folderName={invitation ? shared.invitationNames[invitation.id] ?? familySharingText.sharedVault : ''}
+ onDone={accepted => (invitation ? finishInvitation(invitation.manifestId, accepted) : Promise.resolve())}
+ onClose={() => setOpenInvitationId(null)}
+ />
+ );
+ })()}
</ThemedContainer>
);
}
diff --git a/apps/mobile-app/app/(tabs)/settings/_layout.tsx b/apps/mobile-app/app/(tabs)/settings/_layout.tsx
index 1c9dbbb03..633c37fe1 100644
--- a/apps/mobile-app/app/(tabs)/settings/_layout.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/_layout.tsx
@@ -1,4 +1,3 @@
-import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
import { Stack } from 'expo-router';
import { useTranslation } from 'react-i18next';
import { Platform, Text } from 'react-native';
@@ -100,14 +99,6 @@ export default function SettingsLayout(): React.ReactNode {
...defaultHeaderOptions,
}}
/>
- <Stack.Screen
- name="family-sharing"
- options={{
- title: familySharingText.title,
- headerBackTitle: t('common.settings'),
- ...defaultHeaderOptions,
- }}
- />
<Stack.Screen
name="security/index"
options={{
diff --git a/apps/mobile-app/app/(tabs)/settings/family-sharing.tsx b/apps/mobile-app/app/(tabs)/settings/family-sharing.tsx
deleted file mode 100644
index 6536571f2..000000000
--- a/apps/mobile-app/app/(tabs)/settings/family-sharing.tsx
+++ /dev/null
@@ -1,659 +0,0 @@
-import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
-import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
-import { canAdministerGroup, describeMemberAccess, familySharingText, holdsManifestKey, ownUserIdIn, roleLabel, sharingErrorMessage } from '@aliasvault/client/sharing/FamilySharingView';
-import { multiManifestRendering } from '@aliasvault/client/sharing/MultiManifestRendering';
-import { SharingService } from '@aliasvault/client/sharing/SharingService';
-import { CapabilityKeys } from '@aliasvault/models/webapi';
-import { Ionicons } from '@expo/vector-icons';
-import MaterialIcons from '@expo/vector-icons/MaterialIcons';
-import { Redirect, useRouter } from 'expo-router';
-import { useCallback, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Platform, RefreshControl, StyleSheet, TouchableOpacity, View } from 'react-native';
-import ContextMenu from 'react-native-context-menu-view';
-
-import { folderRoute } from '@/utils/FolderRoute';
-import { HapticsUtility } from '@/utils/HapticsUtility';
-
-import { useColors } from '@/hooks/useColorScheme';
-import { useLogout } from '@/hooks/useLogout';
-import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
-import { useVaultSync } from '@/hooks/useVaultSync';
-
-import { FolderIcon } from '@/components/folders/FolderIcon';
-import { SharedVaultModal } from '@/components/sharing/SharedVaultModal';
-import { ThemedContainer } from '@/components/themed/ThemedContainer';
-import { ThemedScrollView } from '@/components/themed/ThemedScrollView';
-import { ThemedText } from '@/components/themed/ThemedText';
-import { SkeletonLoader } from '@/components/ui/SkeletonLoader';
-import { useApp } from '@/context/AppContext';
-import { useCapabilityContext } from '@/context/CapabilityContext';
-import { useDb } from '@/context/DbContext';
-import { useDialog } from '@/context/DialogContext';
-import { useWebApi } from '@/context/WebApiContext';
-import NativeVaultManager from '@/specs/NativeVaultManager';
-
-import type { GroupInfo, GroupMemberInfo, GroupOverviewResponse, SharedManifestInfo } from '@aliasvault/models/webapi';
-
-/** A sharing operation that failed with a reason already put into words for the user. */
-class SharingOperationError extends Error {}
-
-/**
- * Family sharing screen: create a family's shared manifests, invite the members of that family to them, and answer the
- * invitations others sent.
- */
-export default function FamilySharingScreen(): React.ReactNode {
- const colors = useColors();
- const webApi = useWebApi();
- const { t } = useTranslation();
- const router = useRouter();
- const { username } = useApp();
- const { logoutForced } = useLogout();
- const { sqliteClient } = useDb();
- const { isEnabled, isLoaded } = useCapabilityContext();
- const { showConfirm } = useDialog();
- const { syncVault } = useVaultSync();
-
- const [overview, setOverview] = useState<GroupOverviewResponse | null>(null);
- const [vaultNames, setVaultNames] = useState<Record<string, string>>({});
- const [error, setError] = useState<string | null>(null);
- const [notice, setNotice] = useState<string | null>(null);
- const [busy, setBusy] = useState(false);
- const [isLoading, setIsLoading] = useMinDurationLoading(true, 200);
- const [isRefreshing, setIsRefreshing] = useMinDurationLoading(false, 200);
- const [expandedRosters, setExpandedRosters] = useState<Record<string, boolean>>({});
- const [pendingVaultCreate, setPendingVaultCreate] = useState<GroupInfo | null>(null);
- const [pendingVaultRename, setPendingVaultRename] = useState<{ group: GroupInfo; manifest: SharedManifestInfo } | null>(null);
- const [invitationNames, setInvitationNames] = useState<Record<string, string>>({});
-
- /**
- * Load the families, their shared manifests and the open invitations, plus the names this vault has for them.
- */
- const loadOverview = useCallback(async (): Promise<void> => {
- try {
- const loaded = await SharingService.getOverview(webApi);
- setOverview(loaded);
- setInvitationNames(await SharingService.openInvitationNames(loaded.receivedInvitations, encryptedName => NativeVaultManager.decryptInvitationName(encryptedName)));
-
- if (sqliteClient) {
- // A shared vault is shown as a top-level folder.
- const folders = await sqliteClient.folders.getAll();
- setVaultNames(Object.fromEntries(folders.filter(folder => multiManifestRendering.isVirtualFolder(folder)).map(folder => [folder.Id.toLowerCase(), folder.Name])));
- }
-
- setError(null);
- } catch {
- setError(familySharingText.errors.loadFailed);
- } finally {
- setIsLoading(false);
- }
- }, [webApi, sqliteClient, setIsLoading]);
-
- useEffect(() => {
- // eslint-disable-next-line react-hooks/set-state-in-effect
- loadOverview();
- }, [loadOverview]);
-
- /**
- * The message to show for a failed action.
- * @param actionError - the error thrown by the call.
- * @param fallback - the message for everything else.
- */
- const apiErrorMessage = (actionError: unknown, fallback: string): string => {
- if (actionError instanceof SharingOperationError) {
- return actionError.message;
- }
-
- const code = apiErrorCodeOf(actionError);
- const knownError = sharingErrorMessage(code);
- if (knownError) {
- return knownError;
- }
-
- return code !== null ? `${fallback} [${code}]` : fallback;
- };
-
- /**
- * Run one action, then reload so the screen shows what the server holds now.
- * @param action - the action to run.
- * @param failureMessage - what to show when it fails without a more specific reason.
- */
- const run = async (action: () => Promise<void>, failureMessage: string): Promise<void> => {
- setBusy(true);
- setError(null);
- setNotice(null);
-
- let failure: string | null = null;
- try {
- await action();
- } catch (actionError) {
- failure = apiErrorMessage(actionError, failureMessage);
- }
-
- await loadOverview();
-
- if (failure !== null) {
- setError(failure);
- }
-
- setBusy(false);
- };
-
- /**
- * Run one of the sync engine's sharing operations, which hold the vault keys this screen never sees.
- * @param operation - the engine operation.
- * @param params - what it acts on.
- * @param fallback - the message for a failure without a more specific reason.
- */
- const runSharingOperation = async (operation: 'createSharedManifest' | 'inviteToSharedManifest' | 'updateSharedManifest', params: Record<string, string>, fallback: string): Promise<void> => {
- const result = await NativeVaultManager.runSharingOperation(operation, JSON.stringify(params));
- if (result.success) {
- return;
- }
-
- if (result.vaultUpgradeRequired) {
- throw new SharingOperationError(familySharingText.errors.vaultUpgradeRequired);
- }
-
- const knownError = sharingErrorMessage(result.apiErrorCode);
- const code = result.apiErrorCode ?? result.error;
- throw new SharingOperationError(knownError ?? (code ? `${fallback} [${code}]` : fallback));
- };
-
- /**
- * Create another shared manifest for the family picked in the create modal. The sync that follows pushes it to the server.
- * @param name - the new vault's name.
- */
- const createSharedVault = (name: string): Promise<void> => {
- const group = pendingVaultCreate;
- if (!group) {
- return Promise.resolve();
- }
-
- return run(async () => {
- await runSharingOperation('createSharedManifest', { groupId: group.groupId, name }, familySharingText.errors.createVaultFailed);
- await syncVault();
- }, familySharingText.errors.createVaultFailed);
- };
-
- /**
- * Rename a shared manifest, which only an administrator of the family may do. Every member fetches the name on their next sync.
- * @param name - the new name.
- */
- const renameSharedVault = async (name: string): Promise<void> => {
- const target = pendingVaultRename;
- if (!target) {
- return;
- }
-
- await run(async () => {
- await runSharingOperation('updateSharedManifest', { groupId: target.group.groupId, manifestId: target.manifest.manifestId, name }, t('common.errors.unknownErrorTryAgain'));
- await syncVault();
- }, t('common.errors.unknownErrorTryAgain'));
- };
-
- /**
- * Invite one member to one shared manifest.
- * @param group - the family the shared manifest belongs to.
- * @param manifest - the shared manifest.
- * @param member - the member being invited.
- */
- const inviteMember = (group: GroupInfo, manifest: SharedManifestInfo, member: GroupMemberInfo): Promise<void> => run(async () => {
- await runSharingOperation('inviteToSharedManifest', { groupId: group.groupId, manifestId: manifest.manifestId, userId: member.userId }, familySharingText.errors.inviteFailed);
- setNotice(familySharingText.invitationSent(member.username));
- }, familySharingText.errors.inviteFailed);
-
- /**
- * Accept an invitation. The sync that follows is what brings the shared manifest into this vault.
- * @param invitationId - the invitation to accept.
- */
- const acceptInvitation = (invitationId: string): Promise<void> => run(async () => {
- await SharingService.acceptInvitation(webApi, invitationId);
- await syncVault();
- }, familySharingText.errors.invitationGone);
-
- /**
- * What to call a shared manifest on screen.
- * @param manifest - the shared manifest.
- */
- const vaultLabel = (manifest: SharedManifestInfo): string => vaultNames[manifest.manifestId.toLowerCase()] ?? familySharingText.sharedVault;
-
- /**
- * Open the shared manifest's folder in the items tab.
- */
- const openVault = (manifest: SharedManifestInfo): void => {
- const folderId = manifest.manifestId.toLowerCase();
- router.push(folderRoute({ Id: folderId, ManifestId: folderId }));
- };
-
- /**
- * Ask before taking a member's access away, or before giving up one's own.
- */
- const confirmRemoval = (group: GroupInfo, manifest: SharedManifestInfo, member: GroupMemberInfo, isSelf: boolean): void => {
- const title = isSelf ? familySharingText.leaveVault : familySharingText.revoke;
- const message = isSelf
- ? familySharingText.leaveVaultConfirm(vaultLabel(manifest))
- : `${familySharingText.revokeAccessConfirm(member.username, vaultLabel(manifest))}\n\n${familySharingText.revokeAccessWarning}`;
-
- showConfirm(title, message, title, () => run(async () => {
- await SharingService.revokeAccess(webApi, group.groupId, manifest.manifestId, member.userId);
- await syncVault();
- }, familySharingText.errors.revokeAccessFailed), { confirmStyle: 'destructive' });
- };
-
- /**
- * Delete a shared manifest behind the native password prompt, whose unlock key answers the server's SRP challenge.
- * @param group - the group the shared manifest belongs to.
- * @param manifest - the shared manifest to delete.
- */
- const deleteSharedVault = async (group: GroupInfo, manifest: SharedManifestInfo): Promise<void> => {
- let unlockKey: string | null;
- try {
- unlockKey = await NativeVaultManager.showPasswordUnlockForKey(familySharingText.deleteVault, familySharingText.deleteVaultPasswordPrompt(vaultLabel(manifest)), t('common.delete'));
- } catch (err) {
- // Too many wrong passwords: the native layer cleared the vault, so log out.
- if (err && typeof err === 'object' && 'code' in err && err.code === 'MAX_ATTEMPTS_REACHED') {
- await logoutForced();
- }
- return;
- }
-
- if (!unlockKey) {
- return;
- }
-
- await run(async () => {
- try {
- await SharingService.deleteSharedManifest(webApi, group.groupId, manifest.manifestId, async challenge => {
- const passwordHash = await SrpAuthService.srpPasswordHash(unlockKey, challenge.encryptionType);
- return SrpAuthService.deriveClientProof(challenge.salt, challenge.srpIdentity, passwordHash, challenge.serverEphemeral);
- });
- } catch (deleteError) {
- // Local unlock key could mismatch what is actually stored on server (recent password change on other device), if so we show a incorrect password error.
- if (apiErrorCodeOf(deleteError) === 'PASSWORD_MISMATCH') {
- throw new SharingOperationError(t('common.errors.wrongPassword'));
- }
-
- throw deleteError;
- }
-
- await syncVault();
- setNotice(familySharingText.vaultDeleted);
- }, familySharingText.errors.deleteVaultFailed);
- };
-
- /**
- * Ask before deleting a shared manifest, then move on to the native master password prompt.
- */
- const confirmVaultDelete = (group: GroupInfo, manifest: SharedManifestInfo): void => {
- showConfirm(
- familySharingText.deleteVault,
- familySharingText.deleteVaultConfirm(vaultLabel(manifest)),
- t('common.delete'),
- () => deleteSharedVault(group, manifest),
- { confirmStyle: 'destructive' }
- );
- };
-
- /**
- * Refresh on pull to refresh.
- */
- const onRefresh = async (): Promise<void> => {
- HapticsUtility.impact();
- setIsRefreshing(true);
- try {
- await syncVault();
- await loadOverview();
- } finally {
- setIsRefreshing(false);
- }
- };
-
- const styles = StyleSheet.create({
- addButton: {
- alignItems: 'center',
- borderColor: colors.accentBorder,
- borderRadius: 8,
- borderStyle: 'dashed',
- borderWidth: 2,
- flexDirection: 'row',
- gap: 8,
- justifyContent: 'center',
- paddingVertical: 12,
- },
- addButtonText: {
- color: colors.textMuted,
- fontSize: 14,
- fontWeight: '600',
- },
- actionText: {
- color: colors.primary,
- fontSize: 14,
- fontWeight: '600',
- },
- actionTextDestructive: {
- color: colors.destructive,
- },
- banner: {
- borderRadius: 10,
- marginTop: 16,
- padding: 12,
- },
- bannerError: {
- backgroundColor: colors.errorBackground,
- },
- bannerErrorText: {
- color: colors.errorText,
- fontSize: 14,
- },
- bannerSuccess: {
- backgroundColor: colors.successBackground,
- },
- bannerSuccessText: {
- color: colors.success,
- fontSize: 14,
- },
- betaBadge: {
- backgroundColor: colors.primary,
- borderRadius: 10,
- paddingHorizontal: 8,
- paddingVertical: 2,
- },
- betaBadgeText: {
- color: colors.primarySurfaceText,
- fontSize: 11,
- fontWeight: '600',
- textTransform: 'uppercase',
- },
- buttonRow: {
- flexDirection: 'row',
- gap: 16,
- marginTop: 10,
- },
- card: {
- backgroundColor: colors.accentBackground,
- borderRadius: 10,
- marginBottom: 12,
- padding: 16,
- },
- cardHeader: {
- alignItems: 'center',
- flexDirection: 'row',
- justifyContent: 'space-between',
- },
- cardTitle: {
- color: colors.text,
- flex: 1,
- fontSize: 16,
- fontWeight: '600',
- },
- disabled: {
- opacity: 0.5,
- },
- headerRow: {
- alignItems: 'center',
- flexDirection: 'row',
- gap: 8,
- },
- headerText: {
- color: colors.textMuted,
- flex: 1,
- fontSize: 13,
- },
- invitationCard: {
- borderColor: colors.primary,
- borderWidth: 1.5,
- },
- invitationTitleRow: {
- alignItems: 'center',
- flexDirection: 'row',
- gap: 8,
- },
- memberName: {
- color: colors.text,
- fontSize: 14,
- },
- memberRow: {
- alignItems: 'center',
- borderTopColor: colors.accentBorder,
- borderTopWidth: StyleSheet.hairlineWidth,
- flexDirection: 'row',
- gap: 8,
- justifyContent: 'space-between',
- marginTop: 10,
- paddingTop: 10,
- },
- memberText: {
- flex: 1,
- },
- moreButton: {
- alignItems: 'center',
- height: 44,
- justifyContent: 'center',
- marginRight: -10,
- marginVertical: -10,
- width: 44,
- },
- mutedText: {
- color: colors.textMuted,
- fontSize: 13,
- },
- section: {
- marginTop: 20,
- },
- sectionTitle: {
- color: colors.text,
- fontSize: 15,
- fontWeight: '600',
- marginBottom: 8,
- },
- vaultTitleRow: {
- alignItems: 'center',
- flex: 1,
- flexDirection: 'row',
- gap: 8,
- },
- });
-
- // Nothing is known before the stored capabilities are read, and redirecting on a guess would throw out a deep link.
- if (!isLoaded) {
- return null;
- }
-
- if (!isEnabled(CapabilityKeys.VaultSharing)) {
- return <Redirect href="/(tabs)/settings" />;
- }
-
- const receivedInvitations = overview?.receivedInvitations ?? [];
- const groups = overview?.groups ?? [];
-
- /**
- * One member of a family or of a shared manifest, with whatever can be done about them on the right.
- */
- const renderMemberRow = (member: GroupMemberInfo, isSelf: boolean, detail: string, action?: React.ReactNode): React.ReactNode => (
- <View key={member.userId} style={styles.memberRow}>
- <View style={styles.memberText}>
- <ThemedText style={styles.memberName} numberOfLines={1}>
- {member.username}{isSelf && ` (${familySharingText.you})`}
- </ThemedText>
- <ThemedText style={styles.mutedText}>{detail}</ThemedText>
- </View>
- {action}
- </View>
- );
-
- /**
- * A text button on the right of a row.
- */
- const renderAction = (label: string, onPress: () => void, destructive: boolean = false, enabled: boolean = true): React.ReactNode => (
- <TouchableOpacity onPress={onPress} disabled={busy || !enabled} style={(busy || !enabled) && styles.disabled}>
- <ThemedText style={[styles.actionText, destructive && styles.actionTextDestructive]}>{label}</ThemedText>
- </TouchableOpacity>
- );
-
- /**
- * The vault's admin actions, behind a "more" button so the title row itself stays tappable.
- */
- const renderVaultMenu = (group: GroupInfo, manifest: SharedManifestInfo, canRename: boolean): React.ReactNode => {
- const renameAction = { title: t('items.folders.editFolder'), systemIcon: Platform.select({ ios: 'pencil', default: 'baseline_edit' }) };
- const deleteAction = { title: familySharingText.deleteVault, systemIcon: Platform.select({ ios: 'trash', default: 'baseline_delete' }), destructive: true };
- const actions = canRename ? [renameAction, deleteAction] : [deleteAction];
-
- return (
- <ContextMenu
- dropdownMenuMode
- disabled={busy}
- actions={actions}
- onPress={(event) => (actions[event.nativeEvent.index] === renameAction ? setPendingVaultRename({ group, manifest }) : confirmVaultDelete(group, manifest))}
- >
- <View style={[styles.moreButton, busy && styles.disabled]} accessible accessibilityRole="button" accessibilityLabel={t('common.settings')}>
- <Ionicons name={Platform.OS === 'ios' ? 'ellipsis-horizontal-circle' : 'ellipsis-vertical'} size={22} color={colors.textMuted} />
- </View>
- </ContextMenu>
- );
- };
-
- return (
- <ThemedContainer>
- <ThemedScrollView refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={onRefresh} colors={[colors.primary]} tintColor={colors.primary} />}>
- <View style={styles.headerRow}>
- <ThemedText style={styles.headerText}>{familySharingText.description}</ThemedText>
- <View style={styles.betaBadge}>
- <ThemedText style={styles.betaBadgeText}>{familySharingText.beta}</ThemedText>
- </View>
- </View>
-
- {error && (
- <View style={[styles.banner, styles.bannerError]}>
- <ThemedText style={styles.bannerErrorText}>{error}</ThemedText>
- </View>
- )}
- {notice && (
- <View style={[styles.banner, styles.bannerSuccess]}>
- <ThemedText style={styles.bannerSuccessText}>{notice}</ThemedText>
- </View>
- )}
-
- {isLoading ? (
- <View style={styles.section}>
- <SkeletonLoader count={2} height={100} parts={3} />
- </View>
- ) : (
- <>
- {receivedInvitations.length > 0 && (
- <View style={styles.section}>
- <ThemedText style={styles.sectionTitle}>{familySharingText.invitations}</ThemedText>
- {receivedInvitations.map(invitation => (
- <View key={invitation.id} style={[styles.card, styles.invitationCard]}>
- <View style={styles.invitationTitleRow}>
- <FolderIcon isShared size={20} color={colors.tint} />
- <ThemedText style={styles.cardTitle} numberOfLines={1}>{invitationNames[invitation.id] ?? familySharingText.sharedVault}</ThemedText>
- </View>
- <ThemedText style={styles.mutedText}>{familySharingText.invitedBy(invitation.inviterUsername)}</ThemedText>
- <View style={styles.buttonRow}>
- {renderAction(familySharingText.accept, () => acceptInvitation(invitation.id))}
- {renderAction(familySharingText.decline, () => run(() => SharingService.declineInvitation(webApi, invitation.id), familySharingText.errors.invitationGone), true)}
- </View>
- </View>
- ))}
- </View>
- )}
-
- {groups.length === 0 && receivedInvitations.length === 0 && !error && (
- <View style={styles.section}>
- <ThemedText style={styles.mutedText}>{familySharingText.notAvailable}</ThemedText>
- </View>
- )}
-
- {groups.map((group) => {
- const canAdminister = canAdministerGroup(group);
- const myUserId = ownUserIdIn(group, username);
- const isRosterExpanded = expandedRosters[group.groupId] ?? false;
-
- return (
- <View key={group.groupId} style={styles.section}>
- {/* The family's members. */}
- <View style={styles.card}>
- <TouchableOpacity style={styles.cardHeader} onPress={() => setExpandedRosters(previous => ({ ...previous, [group.groupId]: !isRosterExpanded }))} activeOpacity={0.7}>
- <ThemedText style={styles.cardTitle}>{familySharingText.members} ({group.members.length})</ThemedText>
- <Ionicons name={isRosterExpanded ? 'chevron-up' : 'chevron-down'} size={20} color={colors.textMuted} />
- </TouchableOpacity>
- {isRosterExpanded && group.members.map(member => renderMemberRow(member, member.userId === myUserId, roleLabel(member)))}
- </View>
-
- {/* One card per shared manifest, each with the members who can open it. */}
- <ThemedText style={styles.sectionTitle}>{familySharingText.sharedVaults}</ThemedText>
- {group.manifests.length === 0 && (
- <ThemedText style={styles.mutedText}>{canAdminister ? familySharingText.noSharedVaultAdmin : familySharingText.noSharedVaultMember}</ThemedText>
- )}
- {group.manifests.map(manifest => (
- <View key={manifest.manifestId} style={styles.card}>
- <View style={styles.cardHeader}>
- {/* The shared manifest's folder exists in this vault once the manifest itself does. */}
- {vaultNames[manifest.manifestId.toLowerCase()] !== undefined ? (
- <TouchableOpacity style={styles.vaultTitleRow} onPress={() => openVault(manifest)} activeOpacity={0.6} hitSlop={{ top: 10, bottom: 10 }} accessibilityRole="link">
- <FolderIcon isShared size={20} color={colors.tint} />
- <ThemedText style={styles.cardTitle} numberOfLines={1}>{vaultLabel(manifest)}</ThemedText>
- <Ionicons name="chevron-forward" size={18} color={colors.textMuted} />
- </TouchableOpacity>
- ) : (
- <View style={styles.vaultTitleRow}>
- <FolderIcon isShared size={20} color={colors.tint} />
- <ThemedText style={styles.cardTitle} numberOfLines={1}>{vaultLabel(manifest)}</ThemedText>
- </View>
- )}
- {/* Renaming encrypts the name with the folder's key, so it takes a member who holds it. */}
- {canAdminister && renderVaultMenu(group, manifest, holdsManifestKey(manifest, myUserId))}
- </View>
-
- {/* Inviting somebody encrypts this folder's key for them, which an admin who holds no grant on it cannot do. */}
- {canAdminister && !holdsManifestKey(manifest, myUserId) && (
- <ThemedText style={styles.mutedText}>{familySharingText.cannotInviteWithoutAccess}</ThemedText>
- )}
-
- {group.members.map((member) => {
- const access = describeMemberAccess(group, manifest, member, myUserId);
- const invitation = access.invitation;
-
- return renderMemberRow(member, access.isSelf, access.statusText, (
- <>
- {access.canLeave && renderAction(familySharingText.leaveVault, () => confirmRemoval(group, manifest, member, true), true)}
- {access.canRevoke && renderAction(familySharingText.revoke, () => confirmRemoval(group, manifest, member, false), true)}
- {access.canWithdraw && invitation && renderAction(familySharingText.withdraw, () => run(() => SharingService.withdrawInvitation(webApi, invitation.id), familySharingText.errors.invitationGone))}
- {access.canInvite && renderAction(familySharingText.invite, () => inviteMember(group, manifest, member), false, access.isReadyForInvite)}
- </>
- ));
- })}
- </View>
- ))}
-
- {/* Creating another shared manifest. */}
- {canAdminister && (
- <TouchableOpacity style={[styles.addButton, busy && styles.disabled]} onPress={() => setPendingVaultCreate(group)} disabled={busy} activeOpacity={0.7}>
- <MaterialIcons name="add" size={24} color={colors.textMuted} />
- <ThemedText style={styles.addButtonText}>{familySharingText.createSharedVault}</ThemedText>
- </TouchableOpacity>
- )}
- </View>
- );
- })}
- </>
- )}
- </ThemedScrollView>
-
- <SharedVaultModal
- isOpen={pendingVaultCreate !== null}
- onClose={() => setPendingVaultCreate(null)}
- onSave={createSharedVault}
- mode="create"
- />
- <SharedVaultModal
- isOpen={pendingVaultRename !== null}
- onClose={() => setPendingVaultRename(null)}
- onSave={renameSharedVault}
- initialName={pendingVaultRename ? vaultLabel(pendingVaultRename.manifest) : ''}
- mode="rename"
- />
- </ThemedContainer>
- );
-}
diff --git a/apps/mobile-app/app/(tabs)/settings/index.tsx b/apps/mobile-app/app/(tabs)/settings/index.tsx
index ed06a9ae1..d8ca0c0b0 100644
--- a/apps/mobile-app/app/(tabs)/settings/index.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/index.tsx
@@ -16,6 +16,7 @@ import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
import { useNavigationDebounce } from '@/hooks/useNavigationDebounce';
import { useTranslation } from '@/hooks/useTranslation';
+import { FamilyCode } from '@/components/sharing/FamilyCode';
import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedText } from '@/components/themed/ThemedText';
import { AndroidHeader } from '@/components/ui/AndroidHeader';
@@ -49,6 +50,16 @@ export default function SettingsScreen() : React.ReactNode {
const [clipboardClearDisplay, setClipboardClearDisplay] = useState<string>('');
const [authMethodDisplay, setAuthMethodDisplay] = useState<string>('');
const [serverVersion, setServerVersion] = useState<string | null>(null);
+ const [ownSharingCode, setOwnSharingCode] = useState<string | null>(null);
+ const isSharingEnabled = hasCapability(CapabilityKeys.VaultSharing);
+
+ // The own code is derived natively from the signing private key, which only the native layer can open.
+ useFocusEffect(useCallback(() => {
+ if (!isSharingEnabled) {
+ return;
+ }
+ NativeVaultManager.getSigningKeyFingerprint().then(setOwnSharingCode).catch(() => setOwnSharingCode(null));
+ }, [isSharingEnabled]));
const [isFirstLoad, setIsFirstLoad] = useMinDurationLoading(true, 100);
const { isEnabled: isDeveloperToolsEnabled, registerTap, refresh: refreshDeveloperTools } = useDeveloperToolsUnlock();
@@ -254,25 +265,20 @@ export default function SettingsScreen() : React.ReactNode {
borderRadius: 10,
overflow: 'hidden',
},
- betaBadge: {
- backgroundColor: colors.primary,
- borderRadius: 10,
- paddingHorizontal: 6,
- paddingVertical: 1,
- },
- betaBadgeText: {
- color: colors.primarySurfaceText,
- fontSize: 10,
- fontWeight: '600',
- lineHeight: 14,
- textTransform: 'uppercase',
- },
groupSection: {
backgroundColor: colors.accentBackground,
borderRadius: 10,
marginTop: 8,
overflow: 'hidden',
},
+ ownCodeHint: {
+ color: colors.textMuted,
+ fontSize: 13,
+ marginTop: 8,
+ },
+ ownCodeSection: {
+ padding: 16,
+ },
groupTitle: {
color: colors.textMuted,
fontSize: 13,
@@ -335,16 +341,6 @@ export default function SettingsScreen() : React.ReactNode {
marginRight: 12,
width: 24,
},
- settingItemLabel: {
- alignItems: 'center',
- flex: 1,
- flexDirection: 'row',
- gap: 8,
- },
- settingItemLabelText: {
- color: colors.text,
- fontSize: 16,
- },
settingItemText: {
color: colors.text,
flex: 1,
@@ -421,30 +417,16 @@ export default function SettingsScreen() : React.ReactNode {
<Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
</View>
</TouchableOpacity>
- {hasCapability(CapabilityKeys.VaultSharing) && (
- <>
- <View style={styles.separator} />
- <TouchableOpacity
- style={styles.settingItem}
- onPress={() => navigate(() => router.push('/(tabs)/settings/family-sharing'))}
- >
- <View style={styles.settingItemIcon}>
- <Ionicons name="people-outline" size={20} color={colors.text} />
- </View>
- <View style={styles.settingItemContent}>
- <View style={styles.settingItemLabel}>
- <ThemedText style={styles.settingItemLabelText}>{familySharingText.title}</ThemedText>
- <View style={styles.betaBadge}>
- <ThemedText style={styles.betaBadgeText}>{familySharingText.beta}</ThemedText>
- </View>
- </View>
- <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
- </View>
- </TouchableOpacity>
- </>
- )}
</View>
+ {/* The code people need to invite this account to a shared folder. */}
+ {isSharingEnabled && ownSharingCode && (
+ <View style={[styles.groupSection, styles.ownCodeSection]}>
+ <FamilyCode code={ownSharingCode} />
+ <ThemedText style={styles.ownCodeHint}>{familySharingText.yourCodeSettingsHint}</ThemedText>
+ </View>
+ )}
+
<ThemedText style={styles.groupTitle}>{t('settings.groups.autofill')}</ThemedText>
<View style={styles.groupSection}>
{Platform.OS === 'ios' && (
diff --git a/apps/mobile-app/components/common/ModalWrapper.tsx b/apps/mobile-app/components/common/ModalWrapper.tsx
index f43217ac4..e8aed3dd2 100644
--- a/apps/mobile-app/components/common/ModalWrapper.tsx
+++ b/apps/mobile-app/components/common/ModalWrapper.tsx
@@ -1,4 +1,6 @@
+import { Ionicons } from '@expo/vector-icons';
import React from 'react';
+import { useTranslation } from 'react-i18next';
import {
Modal,
StyleSheet,
@@ -6,15 +8,17 @@ import {
View,
KeyboardAvoidingView,
Platform,
+ TouchableOpacity,
TouchableWithoutFeedback,
Keyboard,
ScrollView,
StatusBar,
} from 'react-native';
-import { ModalBackdrop } from '@/components/common/ModalBackdrop';
import { useColors } from '@/hooks/useColorScheme';
+import { ModalBackdrop } from '@/components/common/ModalBackdrop';
+
interface IModalWrapperProps {
isOpen: boolean;
onClose: () => void;
@@ -31,6 +35,8 @@ interface IModalWrapperProps {
showHeaderBorder?: boolean;
showFooterBorder?: boolean;
closeOnBackdropPress?: boolean;
+ /** Show a close (X) button next to the title. */
+ showCloseButton?: boolean;
}
/**
@@ -57,8 +63,10 @@ export const ModalWrapper: React.FC<IModalWrapperProps> = ({
showHeaderBorder = true,
showFooterBorder = true,
closeOnBackdropPress = false,
+ showCloseButton = false,
}) => {
const colors = useColors();
+ const { t } = useTranslation();
/**
* Handle close - only allow if not submitting.
@@ -90,14 +98,25 @@ export const ModalWrapper: React.FC<IModalWrapperProps> = ({
shadowRadius: 8,
width: width as never,
},
+ closeButton: {
+ marginRight: -4,
+ padding: 4,
+ },
+ closeButtonDisabled: {
+ opacity: 0.4,
+ },
header: {
+ alignItems: 'center',
borderBottomColor: showHeaderBorder ? colors.accentBorder : 'transparent',
borderBottomWidth: showHeaderBorder ? 1 : 0,
+ flexDirection: 'row',
+ gap: 12,
padding: 20,
paddingBottom: 16,
},
title: {
color: colors.text,
+ flex: 1,
fontSize: 18,
fontWeight: '600',
},
@@ -116,11 +135,19 @@ export const ModalWrapper: React.FC<IModalWrapperProps> = ({
},
});
+ /**
+ * The modal card: title, body and footer.
+ */
const renderContent = (): React.ReactNode => (
<View style={styles.container}>
{title && (
<View style={styles.header}>
- <Text style={styles.title}>{title}</Text>
+ <Text style={styles.title} numberOfLines={showCloseButton ? 2 : undefined}>{title}</Text>
+ {showCloseButton && (
+ <TouchableOpacity style={[styles.closeButton, isSubmitting && styles.closeButtonDisabled]} onPress={handleClose} disabled={isSubmitting} accessibilityRole="button" accessibilityLabel={t('common.close')} hitSlop={8}>
+ <Ionicons name="close" size={22} color={colors.textMuted} />
+ </TouchableOpacity>
+ )}
</View>
)}
@@ -142,6 +169,9 @@ export const ModalWrapper: React.FC<IModalWrapperProps> = ({
</View>
);
+ /**
+ * The backdrop around the card, with keyboard avoiding or close on press when asked for.
+ */
const renderBackdrop = (): React.ReactNode => {
if (keyboardAvoiding) {
return (
diff --git a/apps/mobile-app/components/folders/FolderModal.tsx b/apps/mobile-app/components/folders/FolderModal.tsx
index 33fc6ea21..3785ec121 100644
--- a/apps/mobile-app/components/folders/FolderModal.tsx
+++ b/apps/mobile-app/components/folders/FolderModal.tsx
@@ -21,6 +21,7 @@ interface IFolderModalProps {
onSave: (folderName: string) => Promise<void>;
initialName?: string;
mode: 'create' | 'edit';
+ maxLength?: number;
}
/**
@@ -32,6 +33,7 @@ export const FolderModal: React.FC<IFolderModalProps> = ({
onSave,
initialName = '',
mode,
+ maxLength,
}) => {
const { t } = useTranslation();
const colors = useColors();
@@ -67,7 +69,7 @@ export const FolderModal: React.FC<IFolderModalProps> = ({
onClose();
} catch (err) {
- setError(t('common.errors.unknownErrorTryAgain'));
+ setError(err instanceof Error && err.message.length > 0 ? err.message : t('common.errors.unknownErrorTryAgain'));
console.error('Error saving folder:', err);
} finally {
setIsSubmitting(false);
@@ -148,6 +150,7 @@ export const FolderModal: React.FC<IFolderModalProps> = ({
onChangeText={setFolderName}
placeholder={t('items.folders.folderNamePlaceholder')}
placeholderTextColor={colors.textMuted}
+ maxLength={maxLength}
autoFocus
autoCapitalize="sentences"
editable={!isSubmitting}
diff --git a/apps/mobile-app/components/sharing/FamilyCode.tsx b/apps/mobile-app/components/sharing/FamilyCode.tsx
new file mode 100644
index 000000000..e1f3b0fa1
--- /dev/null
+++ b/apps/mobile-app/components/sharing/FamilyCode.tsx
@@ -0,0 +1,144 @@
+import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
+import { Ionicons } from '@expo/vector-icons';
+import React, { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Platform, Share, StyleSheet, TouchableOpacity, View } from 'react-native';
+
+import { copyToClipboard } from '@/utils/ClipboardUtility';
+
+import { useColors } from '@/hooks/useColorScheme';
+
+import { ThemedText } from '@/components/themed/ThemedText';
+
+const COPIED_FEEDBACK_MS = 2000;
+
+interface IFamilyCodeProps {
+ /** The account's own code. */
+ code: string;
+ /** A smaller pill without the copy and share buttons, for showing the code inside other content. */
+ isSmall?: boolean;
+}
+
+/**
+ * The account's own code, with buttons to copy and share it; tapping the code itself copies it too. The code is not secret, so it is never cleared from the clipboard.
+ */
+export const FamilyCode: React.FC<IFamilyCodeProps> = ({ code, isSmall = false }) => {
+ const { t } = useTranslation();
+ const colors = useColors();
+ const [copied, setCopied] = useState(false);
+
+ useEffect(() => {
+ if (!copied) {
+ return undefined;
+ }
+ const timer = setTimeout(() => setCopied(false), COPIED_FEEDBACK_MS);
+ return (): void => clearTimeout(timer);
+ }, [copied]);
+
+ /**
+ * Copy the code to the clipboard.
+ */
+ const copy = async (): Promise<void> => {
+ try {
+ await copyToClipboard(code);
+ setCopied(true);
+ } catch (error) {
+ console.error('Failed to copy the code:', error);
+ }
+ };
+
+ /**
+ * Open the share sheet with the code.
+ */
+ const share = async (): Promise<void> => {
+ try {
+ await Share.share({ message: code });
+ } catch (error) {
+ console.error('Failed to share the code:', error);
+ }
+ };
+
+ const styles = StyleSheet.create({
+ actionButton: {
+ alignItems: 'center',
+ borderColor: colors.accentBorder,
+ borderRadius: 8,
+ borderWidth: 1,
+ flexDirection: 'row',
+ gap: 6,
+ paddingHorizontal: 12,
+ paddingVertical: 8,
+ },
+ actionRow: {
+ flexDirection: 'row',
+ flexWrap: 'wrap',
+ gap: 8,
+ marginTop: 8,
+ },
+ actionText: {
+ color: colors.primary,
+ fontSize: 14,
+ fontWeight: '500',
+ },
+ pill: {
+ alignItems: 'center',
+ alignSelf: 'flex-start',
+ backgroundColor: colors.accentBackground,
+ borderColor: colors.primary,
+ borderRadius: 999,
+ borderWidth: 1,
+ flexDirection: 'row',
+ flexWrap: 'wrap',
+ gap: 8,
+ paddingHorizontal: 14,
+ paddingVertical: 8,
+ },
+ pillCode: {
+ color: colors.text,
+ fontFamily: Platform.OS === 'ios' ? 'Courier' : 'monospace',
+ fontSize: 16,
+ fontWeight: '700',
+ letterSpacing: 1,
+ },
+ pillLabel: {
+ color: colors.textMuted,
+ fontSize: 13,
+ },
+ smallCode: {
+ fontSize: 14,
+ },
+ smallLabel: {
+ fontSize: 12,
+ },
+ smallPill: {
+ gap: 6,
+ paddingHorizontal: 10,
+ paddingVertical: 5,
+ },
+ });
+
+ return (
+ <View>
+ <TouchableOpacity style={[styles.pill, isSmall && styles.smallPill]} onPress={() => void copy()} activeOpacity={0.7} accessibilityRole="button" accessibilityHint={t('common.copyToClipboard')}>
+ <Ionicons name="shield-checkmark-outline" size={isSmall ? 15 : 18} color={colors.primary} />
+ <ThemedText style={[styles.pillLabel, isSmall && styles.smallLabel]}>{familySharingText.yourCode}</ThemedText>
+ <ThemedText style={[styles.pillCode, isSmall && styles.smallCode]}>{code}</ThemedText>
+ {isSmall && <Ionicons name={copied ? 'checkmark' : 'copy-outline'} size={14} color={colors.primary} />}
+ </TouchableOpacity>
+ {!isSmall && (
+ <View style={styles.actionRow}>
+ <TouchableOpacity style={styles.actionButton} onPress={() => void copy()} activeOpacity={0.7} accessibilityRole="button">
+ <Ionicons name={copied ? 'checkmark' : 'copy-outline'} size={16} color={colors.primary} />
+ <ThemedText style={styles.actionText}>{copied ? t('common.copiedShort') : t('common.copyToClipboard')}</ThemedText>
+ </TouchableOpacity>
+ <TouchableOpacity style={styles.actionButton} onPress={() => void share()} activeOpacity={0.7} accessibilityRole="button">
+ <Ionicons name="share-outline" size={16} color={colors.primary} />
+ <ThemedText style={styles.actionText}>{t('common.share')}</ThemedText>
+ </TouchableOpacity>
+ </View>
+ )}
+ </View>
+ );
+};
+
+export default FamilyCode;
diff --git a/apps/mobile-app/components/sharing/InviteMemberWizard.tsx b/apps/mobile-app/components/sharing/InviteMemberWizard.tsx
new file mode 100644
index 000000000..806ae4c7b
--- /dev/null
+++ b/apps/mobile-app/components/sharing/InviteMemberWizard.tsx
@@ -0,0 +1,402 @@
+import { familySharingText, splitAround } from '@aliasvault/client/sharing/FamilySharingView';
+import { Ionicons } from '@expo/vector-icons';
+import React, { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { ActivityIndicator, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
+
+import { useColors } from '@/hooks/useColorScheme';
+
+import { ModalWrapper } from '@/components/common/ModalWrapper';
+import { FamilyCode } from '@/components/sharing/FamilyCode';
+
+/** The account a code belongs to. */
+export type FamilyCodeAccount = { username: string };
+
+/** Somebody verified before, who can be invited without their code. */
+export type KnownPerson = {
+ userId: string;
+ username: string;
+ /** Why they cannot be invited yet, or null when they can. */
+ problem: string | null;
+};
+
+interface IInviteMemberWizardProps {
+ isOpen: boolean;
+ /** The account's own code, which the invitee needs to accept. */
+ ownCode: string | null;
+ /** The folder the invitation is for. */
+ folderName: string;
+ /** Whether inviting turns a personal folder into a shared one. */
+ sharesFolder?: boolean;
+ /** Find the account behind a code; throws an error with the message to show. */
+ onLookup: (code: string) => Promise<FamilyCodeAccount>;
+ /** Invite the account behind a code; throws an error with the message to show. */
+ onInvite: (code: string) => Promise<void>;
+ /** The people verified before who are not in the folder yet, offered before the code field. */
+ people?: KnownPerson[];
+ /** Invite somebody verified before; throws an error with the message to show. */
+ onInvitePerson?: (userId: string) => Promise<void>;
+ onClose: () => void;
+}
+
+const STEP_COUNT = 3;
+const CLOSE_DELAY_SECONDS = 3;
+
+/**
+ * Three step wizard that picks somebody verified before or takes a new person's code, confirms who gets invited, and hands
+ * out this account's own code for them to accept with.
+ */
+export const InviteMemberWizard: React.FC<IInviteMemberWizardProps> = ({ isOpen, ownCode, folderName, sharesFolder = false, onLookup, onInvite, people = [], onInvitePerson, onClose }) => {
+ const { t } = useTranslation();
+ const colors = useColors();
+ const [step, setStep] = useState(1);
+ const [code, setCode] = useState('');
+ const [account, setAccount] = useState<FamilyCodeAccount | null>(null);
+ /** The person verified before who was picked instead of entering a code. */
+ const [selected, setSelected] = useState<KnownPerson | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [isBusy, setIsBusy] = useState(false);
+ const [closeCountdown, setCloseCountdown] = useState(CLOSE_DELAY_SECONDS);
+
+ useEffect(() => {
+ if (isOpen) {
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- reset the wizard each time it opens
+ setStep(1);
+ setCode('');
+ setAccount(null);
+ setSelected(null);
+ setError(null);
+ setCloseCountdown(CLOSE_DELAY_SECONDS);
+ }
+ }, [isOpen]);
+
+ // The last step holds the close button back for a moment, so the instructions get read.
+ useEffect(() => {
+ if (step !== 3 || closeCountdown <= 0) {
+ return undefined;
+ }
+ const timer = setTimeout(() => setCloseCountdown(previous => previous - 1), 1000);
+ return (): void => clearTimeout(timer);
+ }, [step, closeCountdown]);
+
+ const trimmedCode = code.trim();
+ const username = account?.username ?? '';
+ const [invitedBefore, invitedName, invitedAfter] = splitAround(familySharingText.inviteWizardInvited(username), username);
+ const [shareBefore, shareName, shareAfter] = splitAround(familySharingText.inviteWizardShareHint(username), username);
+ const [confirmBefore, confirmName, confirmAfter] = splitAround(sharesFolder ? familySharingText.inviteWizardConfirmShare(username, folderName) : familySharingText.inviteWizardConfirmFolder(username, folderName), username);
+ const canContinue = selected !== null || trimmedCode.length > 0;
+
+ /**
+ * Run one step's action, showing its error in the wizard.
+ * @param action - the action to run.
+ */
+ const runStep = async (action: () => Promise<void>): Promise<void> => {
+ setIsBusy(true);
+ setError(null);
+ try {
+ await action();
+ } catch (stepError) {
+ setError(stepError instanceof Error ? stepError.message : t('common.errors.unknownErrorTryAgain'));
+ } finally {
+ setIsBusy(false);
+ }
+ };
+
+ /**
+ * Ask to confirm the person picked, or look the code up first and ask to confirm who it belongs to.
+ */
+ const lookup = (): Promise<void> => runStep(async () => {
+ setAccount(selected ? { username: selected.username } : await onLookup(trimmedCode));
+ setStep(2);
+ });
+
+ /**
+ * Invite the person picked or the account behind the code, then show this account's own code.
+ */
+ const invite = (): Promise<void> => runStep(async () => {
+ if (selected && onInvitePerson) {
+ await onInvitePerson(selected.userId);
+ } else {
+ await onInvite(trimmedCode);
+ }
+ setCloseCountdown(CLOSE_DELAY_SECONDS);
+ setStep(3);
+ });
+
+ const canClose = step !== 3 || closeCountdown <= 0;
+
+ /**
+ * Close, unless a step is running or the last step still counts down.
+ */
+ const close = (): void => {
+ if (!isBusy && canClose) {
+ onClose();
+ }
+ };
+
+ const styles = StyleSheet.create({
+ bodyText: {
+ color: colors.text,
+ fontSize: 15,
+ marginTop: 8,
+ },
+ emphasis: {
+ fontWeight: '600',
+ },
+ buttonRow: {
+ flexDirection: 'row',
+ gap: 12,
+ marginTop: 20,
+ },
+ disabled: {
+ opacity: 0.6,
+ },
+ errorText: {
+ color: colors.destructive,
+ fontSize: 14,
+ marginTop: 8,
+ },
+ hintText: {
+ color: colors.textMuted,
+ fontSize: 14,
+ marginTop: 8,
+ },
+ input: {
+ backgroundColor: colors.modalSurfaceRaised,
+ borderColor: colors.accentBorder,
+ borderRadius: 8,
+ borderWidth: 1,
+ color: colors.text,
+ fontSize: 16,
+ marginTop: 12,
+ paddingHorizontal: 12,
+ paddingVertical: 10,
+ },
+ personName: {
+ color: colors.text,
+ flex: 1,
+ fontSize: 15,
+ },
+ personOption: {
+ alignItems: 'center',
+ borderColor: colors.accentBorder,
+ borderRadius: 8,
+ borderWidth: 1,
+ flexDirection: 'row',
+ gap: 10,
+ marginTop: 8,
+ paddingHorizontal: 12,
+ paddingVertical: 10,
+ },
+ personOptionSelected: {
+ backgroundColor: colors.accentBackground,
+ borderColor: colors.primary,
+ },
+ personProblem: {
+ color: colors.warning,
+ fontSize: 12,
+ marginTop: 2,
+ },
+ personText: {
+ flex: 1,
+ },
+ primaryButton: {
+ alignItems: 'center',
+ backgroundColor: colors.tint,
+ borderRadius: 8,
+ flex: 1,
+ paddingVertical: 12,
+ },
+ primaryButtonText: {
+ color: colors.white,
+ fontSize: 16,
+ fontWeight: '600',
+ },
+ progressBar: {
+ borderRadius: 999,
+ flex: 1,
+ height: 6,
+ },
+ progressRow: {
+ flexDirection: 'row',
+ gap: 8,
+ },
+ progressText: {
+ color: colors.textMuted,
+ fontSize: 12,
+ marginBottom: 16,
+ marginTop: 8,
+ },
+ secondaryButton: {
+ alignItems: 'center',
+ borderColor: colors.accentBorder,
+ borderRadius: 8,
+ borderWidth: 1,
+ flex: 1,
+ paddingVertical: 12,
+ },
+ secondaryButtonText: {
+ color: colors.text,
+ fontSize: 16,
+ fontWeight: '500',
+ },
+ busyBox: {
+ alignItems: 'center',
+ gap: 12,
+ paddingVertical: 24,
+ },
+ busyText: {
+ color: colors.textMuted,
+ fontSize: 14,
+ textAlign: 'center',
+ },
+ codeSection: {
+ marginTop: 20,
+ },
+ nextStepBox: {
+ borderColor: colors.accentBorder,
+ borderRadius: 8,
+ borderWidth: 1,
+ marginTop: 16,
+ padding: 12,
+ },
+ nextStepTitle: {
+ color: colors.text,
+ fontSize: 15,
+ fontWeight: '600',
+ },
+ shareBlock: {
+ marginTop: 12,
+ },
+ stepTitle: {
+ color: colors.text,
+ fontSize: 17,
+ fontWeight: '600',
+ },
+ titleRow: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ gap: 8,
+ },
+ });
+
+ /**
+ * One of the two buttons at the bottom of a step.
+ */
+ const renderButton = (label: string, onPress: () => void, isPrimary: boolean, enabled: boolean = true): React.ReactNode => (
+ <TouchableOpacity style={[isPrimary ? styles.primaryButton : styles.secondaryButton, !enabled && styles.disabled]} onPress={onPress} disabled={!enabled}>
+ <Text style={isPrimary ? styles.primaryButtonText : styles.secondaryButtonText}>{label}</Text>
+ </TouchableOpacity>
+ );
+
+ return (
+ <ModalWrapper isOpen={isOpen} onClose={close} isSubmitting={isBusy || !canClose} title={familySharingText.invitePeople} keyboardAvoiding showHeaderBorder={false} showFooterBorder={false}>
+ {/* Progress through the three steps. */}
+ <View style={styles.progressRow} accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
+ {Array.from({ length: STEP_COUNT }, (_, index) => (
+ <View key={index} style={[styles.progressBar, { backgroundColor: index < step ? colors.primary : colors.accentBorder }]} />
+ ))}
+ </View>
+ <Text style={styles.progressText}>{familySharingText.wizardStep(step, STEP_COUNT)}</Text>
+
+ {/* While a step works (looking the code up, or sharing the folder and sending the invitation) its content makes way for a spinner. */}
+ {isBusy && (
+ <View style={styles.busyBox}>
+ <ActivityIndicator color={colors.primary} />
+ <Text style={styles.busyText}>{step === 2 && sharesFolder ? familySharingText.wizardCreating : t('common.loading')}</Text>
+ </View>
+ )}
+
+ {step === 1 && !isBusy && (
+ <View>
+ {/* Somebody verified before needs no code; picking them and entering a code exclude each other. */}
+ {people.length > 0 && (
+ <View>
+ <Text style={styles.stepTitle}>{familySharingText.inviteWizardChooseTitle}</Text>
+ {people.map(person => {
+ const isSelected = selected?.userId === person.userId;
+ return (
+ <TouchableOpacity
+ key={person.userId}
+ style={[styles.personOption, isSelected && styles.personOptionSelected, person.problem !== null && styles.disabled]}
+ disabled={person.problem !== null}
+ activeOpacity={0.7}
+ accessibilityState={{ selected: isSelected, disabled: person.problem !== null }}
+ onPress={() => {
+ setSelected(isSelected ? null : person);
+ setCode('');
+ }}
+ >
+ <Ionicons name={isSelected ? 'checkmark-circle' : 'people-outline'} size={20} color={isSelected ? colors.primary : colors.textMuted} />
+ <View style={styles.personText}>
+ <Text style={styles.personName} numberOfLines={1}>{person.username}</Text>
+ {person.problem && <Text style={styles.personProblem}>{person.problem}</Text>}
+ </View>
+ </TouchableOpacity>
+ );
+ })}
+ </View>
+ )}
+
+ <View style={people.length > 0 ? styles.codeSection : undefined}>
+ <Text style={styles.stepTitle}>{people.length > 0 ? familySharingText.inviteWizardNewCodeTitle : familySharingText.inviteWizardCodeTitle}</Text>
+ <Text style={styles.hintText}>{familySharingText.inviteWizardCodeHint}</Text>
+ <TextInput
+ style={styles.input}
+ value={code}
+ onChangeText={value => {
+ setCode(value);
+ setSelected(null);
+ }}
+ placeholder={familySharingText.codePlaceholder}
+ placeholderTextColor={colors.textMuted}
+ keyboardType="number-pad"
+ autoCorrect={false}
+ autoFocus={people.length === 0}
+ returnKeyType="next"
+ onSubmitEditing={() => canContinue && void lookup()}
+ />
+ </View>
+ {error && <Text style={styles.errorText}>{error}</Text>}
+ <View style={styles.buttonRow}>
+ {renderButton(t('common.cancel'), close, false)}
+ {renderButton(t('common.next'), () => void lookup(), true, canContinue)}
+ </View>
+ </View>
+ )}
+
+ {step === 2 && !isBusy && (
+ <View>
+ <Text style={styles.stepTitle}>{familySharingText.inviteWizardConfirmTitle}</Text>
+ <Text style={styles.bodyText}>{confirmBefore}<Text style={styles.emphasis}>{confirmName}</Text>{confirmAfter}</Text>
+ {error && <Text style={styles.errorText}>{error}</Text>}
+ <View style={styles.buttonRow}>
+ {renderButton(t('common.back'), () => setStep(1), false)}
+ {renderButton(familySharingText.invite, () => void invite(), true)}
+ </View>
+ </View>
+ )}
+
+ {step === 3 && (
+ <View>
+ <View style={styles.titleRow}>
+ <Ionicons name="checkmark-circle" size={22} color={colors.success} />
+ <Text style={styles.stepTitle}>{invitedBefore}<Text style={styles.emphasis}>{invitedName}</Text>{invitedAfter}</Text>
+ </View>
+ {/* What the inviter still has to do: the invitee types this code to accept. */}
+ <View style={styles.nextStepBox}>
+ <Text style={styles.nextStepTitle}>{familySharingText.inviteWizardNextStep}</Text>
+ <Text style={styles.bodyText}>{shareBefore}<Text style={styles.emphasis}>{shareName}</Text>{shareAfter}</Text>
+ {ownCode && <View style={styles.shareBlock}><FamilyCode code={ownCode} /></View>}
+ <Text style={styles.hintText}>{familySharingText.inviteWizardShareNotSecret}</Text>
+ </View>
+ <View style={styles.buttonRow}>
+ {renderButton(canClose ? t('common.close') : familySharingText.closeCountdown(closeCountdown), close, false, canClose)}
+ </View>
+ </View>
+ )}
+ </ModalWrapper>
+ );
+};
+
+export default InviteMemberWizard;
diff --git a/apps/mobile-app/components/sharing/SharedFolderAccessModal.tsx b/apps/mobile-app/components/sharing/SharedFolderAccessModal.tsx
new file mode 100644
index 000000000..e7238abcb
--- /dev/null
+++ b/apps/mobile-app/components/sharing/SharedFolderAccessModal.tsx
@@ -0,0 +1,496 @@
+import { canAdministerGroup, describeMemberAccess, familySharingText, hasOtherPeople, holdsManifestKey, invitablePeople, memberKeyProblem, pendingInvitees, roleLabel, sharingView, type SharedFolder } from '@aliasvault/client/sharing/FamilySharingView';
+import { SharingService } from '@aliasvault/client/sharing/SharingService';
+import { Ionicons } from '@expo/vector-icons';
+import React, { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { ActivityIndicator, StyleSheet, TouchableOpacity, View } from 'react-native';
+
+import emitter from '@/utils/EventEmitter';
+import { runSharingOperation, sharingFailureMessage, SharingOperationError } from '@/utils/SharingErrors';
+
+import { useColors } from '@/hooks/useColorScheme';
+import { usePasswordConfirmedAction } from '@/hooks/usePasswordConfirmedAction';
+import { type SharedFolders } from '@/hooks/useSharedFolders';
+import { useVaultSync } from '@/hooks/useVaultSync';
+
+import { ModalWrapper } from '@/components/common/ModalWrapper';
+import { FamilyCode } from '@/components/sharing/FamilyCode';
+import { InviteMemberWizard, type FamilyCodeAccount } from '@/components/sharing/InviteMemberWizard';
+import { ThemedText } from '@/components/themed/ThemedText';
+import { useDb } from '@/context/DbContext';
+import { useDialog } from '@/context/DialogContext';
+import { useWebApi } from '@/context/WebApiContext';
+
+import type { Folder, FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';
+import type { GroupMemberInfo } from '@aliasvault/models/webapi';
+
+interface ISharedFolderAccessModalProps {
+ folder: Folder;
+ isShared: boolean;
+ shared: SharedFolders;
+ onMoved: (ref: FolderRef, isShared: boolean) => void;
+ onLeft: () => void;
+ onClose: () => void;
+}
+
+/**
+ * The people of a folder: who has access, inviting someone new by their code or somebody verified before, and taking
+ * access away. A personal folder becomes a shared folder on its first invitation, and turns personal again once nobody
+ * else is in it. Mounted while the sheet is open.
+ */
+export const SharedFolderAccessModal: React.FC<ISharedFolderAccessModalProps> = ({ folder, isShared, shared, onMoved, onLeft, onClose }) => {
+ const { t } = useTranslation();
+ const colors = useColors();
+ const webApi = useWebApi();
+ const dbContext = useDb();
+ const { syncVault } = useVaultSync();
+ const { showDialog } = useDialog();
+ const runWithPassword = usePasswordConfirmedAction();
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
+ const [isInviteOpen, setIsInviteOpen] = useState(false);
+ /** Whether the sheet makes way for a confirmation or the password prompt, which show on top of the screen. */
+ const [isHidden, setIsHidden] = useState(false);
+ /** The notice of the invite wizard, shown once it closes rather than behind it. */
+ const [inviteNotice, setInviteNotice] = useState<string | null>(null);
+
+ // Who is in the folder changes on other devices too, so the sheet shows the server's current view when it opens.
+ const { reload } = shared;
+ useEffect(() => {
+ void reload();
+ }, [reload]);
+
+ const current = isShared ? shared.folders.find(candidate => candidate.manifest.manifestId.toLowerCase() === folder.ManifestId.toLowerCase()) ?? null : null;
+ const others = shared.verifiedPeople.filter(person => person.userId !== shared.myUserId);
+ const invitable = current ? invitablePeople(current, others) : others;
+ const hasOthers = current !== null && hasOtherPeople(current, shared.myUserId);
+ const canInvite = isShared ? current !== null && canAdministerGroup(current.group) && holdsManifestKey(current.manifest, shared.myUserId) : true;
+
+ /**
+ * Run one action, showing its error in the sheet, then reload what is shown.
+ * @param action - the action to run.
+ * @param failureMessage - the message for a failure without a more specific reason.
+ */
+ const run = async (action: () => Promise<void>, failureMessage: string): Promise<void> => {
+ setBusy(true);
+ setError(null);
+ setNotice(null);
+ try {
+ await action();
+ } catch (actionError) {
+ setError(sharingFailureMessage(actionError, failureMessage));
+ }
+ await shared.reload();
+ setBusy(false);
+ };
+
+ /**
+ * The shared folder this folder is, turning a personal folder into one first (the wizard had the user confirm who it is
+ * shared with): the shared folder is created with the folder's name, the folder's contents move into it, and the
+ * personal folder is deleted.
+ * @returns The shared folder.
+ */
+ const ensureShared = async (): Promise<SharedFolder> => {
+ if (current) {
+ return current;
+ }
+ const client = dbContext.sqliteClient;
+ if (isShared || !client) {
+ // A shared folder whose people have not loaded yet; never share it a second time.
+ throw new SharingOperationError(isShared ? familySharingText.errors.inviteFailed : familySharingText.errors.createVaultFailed);
+ }
+
+ const result = await runSharingOperation('createSharedManifest', { name: folder.Name }, familySharingText.errors.createVaultFailed);
+ const manifestId = (result.manifestId ?? '').toLowerCase();
+
+ // The sync pushes the new shared folder; the contents then move into it with a push of their own.
+ await syncVault();
+ // The native store commits the move into the vault the sync just reopened, and marks it dirty for the push below.
+ await client.folders.moveContentsToManifest({ Id: folder.Id, ManifestId: folder.ManifestId }, manifestId);
+ await dbContext.refreshSyncState();
+ await syncVault();
+ emitter.emit('itemChanged');
+
+ const created = sharingView(await SharingService.getOverview(webApi)).folders.find(candidate => candidate.manifest.manifestId.toLowerCase() === manifestId) ?? null;
+ if (!created) {
+ throw new SharingOperationError(familySharingText.errors.createVaultFailed);
+ }
+ onMoved({ Id: manifestId, ManifestId: manifestId }, true);
+ return created;
+ };
+
+ /**
+ * Invite somebody verified before (picked in the wizard), sharing a personal folder at this point.
+ * @param userId - the person to invite.
+ */
+ const inviteKnown = async (userId: string): Promise<void> => {
+ try {
+ const target = await ensureShared();
+ await runSharingOperation('inviteToSharedManifest', { groupId: target.group.groupId, manifestId: target.manifest.manifestId, userId }, familySharingText.errors.inviteFailed);
+ setInviteNotice(familySharingText.invitationSent(shared.verifiedPeople.find(person => person.userId === userId)?.username ?? ''));
+ } catch (inviteError) {
+ throw new Error(sharingFailureMessage(inviteError, familySharingText.errors.inviteFailed));
+ } finally {
+ await shared.reload();
+ }
+ };
+
+ /**
+ * Find the account behind a code for the invite wizard, also before the folder is shared. Throws an error with the message to show.
+ * @param code - the code entered.
+ */
+ const lookup = async (code: string): Promise<FamilyCodeAccount> => {
+ try {
+ const result = await runSharingOperation('lookupIdentityCode', { groupId: current?.group.groupId, identityCode: code }, familySharingText.errors.inviteFailed);
+ if (result.alreadyMember) {
+ throw new SharingOperationError(familySharingText.errors.alreadyHasAccess);
+ }
+ return { username: result.username ?? '' };
+ } catch (lookupError) {
+ throw new Error(sharingFailureMessage(lookupError, familySharingText.errors.inviteFailed));
+ }
+ };
+
+ /**
+ * Invite the account behind a code, sharing a personal folder at this point; the sync engine checks its key against the code and certifies it.
+ * @param code - the code entered.
+ */
+ const inviteByCode = async (code: string): Promise<void> => {
+ try {
+ const target = await ensureShared();
+ const result = await runSharingOperation('inviteToSharedManifest', { groupId: target.group.groupId, manifestId: target.manifest.manifestId, identityCode: code }, familySharingText.errors.inviteFailed);
+ setInviteNotice(familySharingText.invitationSent(result.username ?? ''));
+ } catch (inviteError) {
+ throw new Error(sharingFailureMessage(inviteError, familySharingText.errors.inviteFailed));
+ } finally {
+ await shared.reload();
+ }
+ };
+
+ /**
+ * Open the invite wizard, which shows instead of the sheet.
+ */
+ const openInviteWizard = (): void => {
+ setError(null);
+ setNotice(null);
+ setIsInviteOpen(true);
+ };
+
+ /**
+ * Close the invite wizard and show the sheet again, with the wizard's notice.
+ */
+ const closeInviteWizard = (): void => {
+ setIsInviteOpen(false);
+ setNotice(inviteNotice);
+ setInviteNotice(null);
+ };
+
+ /**
+ * Turn a shared folder this account owns back into a personal one when nobody else is in it or invited anymore (as the
+ * server sees it now): its contents move into a new personal folder with its name, then the empty shared folder is
+ * deleted. Nothing is shared anymore, so this takes no master password.
+ * @param manifestId - the shared folder.
+ */
+ const revertIfEmpty = async (manifestId: string): Promise<void> => {
+ const latest = sharingView(await SharingService.getOverview(webApi)).folders.find(candidate => candidate.manifest.manifestId.toLowerCase() === manifestId.toLowerCase());
+ const client = dbContext.sqliteClient;
+ if (!latest || latest.group.role !== 'owner' || hasOtherPeople(latest, shared.myUserId) || !client) {
+ return;
+ }
+
+ // The native store commits the move and marks the vault dirty; the sync pushes it before the shared folder goes.
+ const personal = await client.folders.moveManifestToNewFolder(manifestId, folder.Name);
+ await dbContext.refreshSyncState();
+ await syncVault();
+ await SharingService.unshareSharedManifest(webApi, latest.group.groupId, manifestId);
+ await syncVault();
+ emitter.emit('itemChanged');
+ await shared.reload();
+ onMoved(personal, false);
+ };
+
+ /**
+ * Ask for confirmation, then for the master password, before taking a member's access away or handing back one's own.
+ * The sheet hides first, so the confirmation and the password prompt show on top of the screen.
+ * @param target - the shared folder.
+ * @param member - the member losing access.
+ * @param isSelf - whether the member is the current user.
+ */
+ const removeAccess = (target: SharedFolder, member: GroupMemberInfo, isSelf: boolean): void => {
+ const title = isSelf ? familySharingText.leaveVault : familySharingText.revoke;
+ const message = isSelf ? familySharingText.leaveVaultConfirm(folder.Name) : familySharingText.revokeAccessConfirm(member.username, folder.Name);
+ const passwordPrompt = isSelf ? familySharingText.leaveVaultPasswordPrompt(folder.Name) : familySharingText.revokeAccessPasswordPrompt(member.username, folder.Name);
+
+ /**
+ * Confirmed: ask for the password, then show the sheet with a spinner while the change runs and syncs in.
+ */
+ const confirmed = async (): Promise<void> => {
+ try {
+ const done = await runWithPassword(title, passwordPrompt, title, async answerChallenge => {
+ setBusy(true);
+ setIsHidden(false);
+ await (isSelf
+ ? SharingService.leaveSharedManifest(webApi, target.group.groupId, target.manifest.manifestId, answerChallenge)
+ : SharingService.revokeAccess(webApi, target.group.groupId, target.manifest.manifestId, member.userId, answerChallenge));
+ });
+ if (!done) {
+ return;
+ }
+ await syncVault();
+ emitter.emit('itemChanged');
+ if (isSelf) {
+ await shared.reload();
+ onLeft();
+ return;
+ }
+ // Taking the last other person out makes the folder personal again.
+ await revertIfEmpty(target.manifest.manifestId);
+ await shared.reload();
+ } catch (removeError) {
+ setError(sharingFailureMessage(removeError, familySharingText.errors.revokeAccessFailed));
+ } finally {
+ setBusy(false);
+ setIsHidden(false);
+ }
+ };
+
+ setError(null);
+ setNotice(null);
+ setIsHidden(true);
+ /**
+ * Cancelled: show the sheet again.
+ */
+ const cancelled = (): void => setIsHidden(false);
+
+ showDialog(title, message, [
+ { text: t('common.cancel'), style: 'cancel', onPress: cancelled },
+ { text: title, style: 'destructive', onPress: confirmed },
+ ]);
+ };
+
+ /*
+ * A shared folder this account owns that nobody else is in anymore (they left, or an invitation was declined or expired
+ * elsewhere) is personal again: turned back once when the sheet shows it, never while the invite wizard runs.
+ */
+ const revertCheckedRef = useRef<string | null>(null);
+ const emptyOwnedManifestId = current && current.group.role === 'owner' && !hasOthers && !busy && !isInviteOpen && !isHidden ? current.manifest.manifestId : null;
+ useEffect(() => {
+ if (!emptyOwnedManifestId || revertCheckedRef.current === emptyOwnedManifestId) {
+ return;
+ }
+ revertCheckedRef.current = emptyOwnedManifestId;
+ void run(() => revertIfEmpty(emptyOwnedManifestId), familySharingText.errors.revokeAccessFailed);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [emptyOwnedManifestId]);
+
+ const styles = StyleSheet.create({
+ actionText: {
+ color: colors.primary,
+ fontSize: 14,
+ fontWeight: '600',
+ },
+ actionTextDestructive: {
+ color: colors.destructive,
+ },
+ addButton: {
+ padding: 4,
+ },
+ banner: {
+ borderRadius: 10,
+ marginBottom: 12,
+ padding: 12,
+ },
+ bannerError: {
+ backgroundColor: colors.errorBackground,
+ },
+ bannerErrorText: {
+ color: colors.errorText,
+ fontSize: 14,
+ },
+ bannerSuccess: {
+ backgroundColor: colors.successBackground,
+ },
+ bannerSuccessText: {
+ color: colors.success,
+ fontSize: 14,
+ },
+ busyBox: {
+ alignItems: 'center',
+ gap: 12,
+ paddingVertical: 24,
+ },
+ busyText: {
+ color: colors.textMuted,
+ fontSize: 14,
+ },
+ codeTip: {
+ gap: 6,
+ marginTop: 16,
+ },
+ disabled: {
+ opacity: 0.5,
+ },
+ hintText: {
+ color: colors.textMuted,
+ fontSize: 14,
+ },
+ memberName: {
+ color: colors.text,
+ fontSize: 14,
+ },
+ memberRow: {
+ alignItems: 'center',
+ borderTopColor: colors.accentBorder,
+ borderTopWidth: StyleSheet.hairlineWidth,
+ flexDirection: 'row',
+ gap: 8,
+ justifyContent: 'space-between',
+ paddingVertical: 10,
+ },
+ memberText: {
+ flex: 1,
+ },
+ mutedText: {
+ color: colors.textMuted,
+ fontSize: 13,
+ },
+ peopleHeader: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ justifyContent: 'space-between',
+ marginBottom: 4,
+ },
+ peopleTitle: {
+ color: colors.text,
+ fontSize: 15,
+ fontWeight: '600',
+ },
+ primaryButton: {
+ alignItems: 'center',
+ alignSelf: 'flex-start',
+ backgroundColor: colors.primary,
+ borderRadius: 8,
+ flexDirection: 'row',
+ gap: 6,
+ marginTop: 12,
+ paddingHorizontal: 16,
+ paddingVertical: 10,
+ },
+ primaryButtonText: {
+ color: colors.primarySurfaceText,
+ fontSize: 14,
+ fontWeight: '600',
+ },
+ tipText: {
+ color: colors.textMuted,
+ fontSize: 12,
+ },
+ });
+
+ /**
+ * One row of the people list, with whatever can be done about it on the right.
+ */
+ const renderRow = (key: string, name: string, detail: string, action?: React.ReactNode): React.ReactNode => (
+ <View key={key} style={styles.memberRow}>
+ <View style={styles.memberText}>
+ <ThemedText style={styles.memberName} numberOfLines={1}>{name}</ThemedText>
+ <ThemedText style={styles.mutedText}>{detail}</ThemedText>
+ </View>
+ {action}
+ </View>
+ );
+
+ /**
+ * A text button on the right of a row.
+ */
+ const renderAction = (label: string, onPress: () => void, destructive: boolean = false): React.ReactNode => (
+ <TouchableOpacity onPress={onPress} disabled={busy} style={busy && styles.disabled}>
+ <ThemedText style={[styles.actionText, destructive && styles.actionTextDestructive]}>{label}</ThemedText>
+ </TouchableOpacity>
+ );
+
+ /**
+ * The people with access and the pending invitees, with a + to invite more.
+ */
+ const renderPeople = (target: SharedFolder): React.ReactNode => (
+ <View>
+ <View style={styles.peopleHeader}>
+ <ThemedText style={styles.peopleTitle}>{familySharingText.peopleTitle}</ThemedText>
+ {canInvite && (
+ <TouchableOpacity style={styles.addButton} onPress={openInviteWizard} disabled={busy} accessibilityRole="button" accessibilityLabel={familySharingText.invitePeople} hitSlop={8}>
+ <Ionicons name="add" size={24} color={colors.primary} />
+ </TouchableOpacity>
+ )}
+ </View>
+ {target.group.members.map(member => {
+ const access = describeMemberAccess(target.group, target.manifest, member, shared.myUserId);
+ return renderRow(member.userId, access.isSelf ? `${member.username} (${familySharingText.you})` : member.username, roleLabel(member), (
+ <>
+ {access.canLeave && renderAction(familySharingText.leaveVault, () => removeAccess(target, member, true), true)}
+ {access.canRevoke && renderAction(familySharingText.revoke, () => removeAccess(target, member, false), true)}
+ </>
+ ));
+ })}
+ {canAdministerGroup(target.group) && pendingInvitees(target).map(invitation => renderRow(invitation.id, invitation.inviteeUsername, familySharingText.invited, renderAction(familySharingText.withdraw, () => void run(async () => {
+ await SharingService.withdrawInvitation(webApi, invitation.id);
+ await revertIfEmpty(target.manifest.manifestId);
+ }, familySharingText.errors.invitationGone))))}
+ </View>
+ );
+
+ return (
+ <>
+ <ModalWrapper isOpen={!isInviteOpen && !isHidden} onClose={onClose} isSubmitting={busy} title={folder.Name} showCloseButton scrollable maxScrollHeight={480}>
+ {/* While something runs (sharing, inviting, taking access away, making the folder personal) the content makes way for a spinner. */}
+ {busy ? (
+ <View style={styles.busyBox}>
+ <ActivityIndicator color={colors.primary} />
+ <ThemedText style={styles.busyText}>{t('common.loading')}</ThemedText>
+ </View>
+ ) : (
+ <View>
+ {error && <View style={[styles.banner, styles.bannerError]}><ThemedText style={styles.bannerErrorText}>{error}</ThemedText></View>}
+ {notice && <View style={[styles.banner, styles.bannerSuccess]}><ThemedText style={styles.bannerSuccessText}>{notice}</ThemedText></View>}
+
+ {!isShared && <ThemedText style={styles.hintText}>{familySharingText.shareFolderHint}</ThemedText>}
+
+ {/* The people with access; only listed once anybody besides this account is in. */}
+ {current && hasOthers && renderPeople(current)}
+
+ {/* While an invitation waits, the code the invitee types to accept it is at hand here too. */}
+ {current && canAdministerGroup(current.group) && pendingInvitees(current).length > 0 && shared.ownCode && (
+ <View style={styles.codeTip}>
+ <ThemedText style={styles.tipText}>{familySharingText.pendingCodeTip}</ThemedText>
+ <FamilyCode code={shared.ownCode} isSmall />
+ </View>
+ )}
+
+ {/* Nobody else in yet (or still a personal folder): inviting is the one thing to do, so it is shown prominently. */}
+ {current && !hasOthers && <ThemedText style={styles.hintText}>{familySharingText.notSharedYet}</ThemedText>}
+ {canInvite && !hasOthers && (
+ <TouchableOpacity style={styles.primaryButton} activeOpacity={0.7} onPress={openInviteWizard}>
+ <Ionicons name="add" size={18} color={colors.primarySurfaceText} />
+ <ThemedText style={styles.primaryButtonText}>{familySharingText.invitePeople}</ThemedText>
+ </TouchableOpacity>
+ )}
+ </View>
+ )}
+ </ModalWrapper>
+
+ <InviteMemberWizard
+ isOpen={isInviteOpen}
+ ownCode={shared.ownCode}
+ folderName={folder.Name}
+ sharesFolder={!isShared}
+ onLookup={lookup}
+ onInvite={inviteByCode}
+ people={invitable.map(person => ({ userId: person.userId, username: person.username, problem: memberKeyProblem(person) }))}
+ onInvitePerson={inviteKnown}
+ onClose={closeInviteWizard}
+ />
+ </>
+ );
+};
+
+export default SharedFolderAccessModal;
diff --git a/apps/mobile-app/components/sharing/SharedFolderInvitationModal.tsx b/apps/mobile-app/components/sharing/SharedFolderInvitationModal.tsx
new file mode 100644
index 000000000..3030b2fbe
--- /dev/null
+++ b/apps/mobile-app/components/sharing/SharedFolderInvitationModal.tsx
@@ -0,0 +1,200 @@
+import { familySharingText, isInviterVerified } from '@aliasvault/client/sharing/FamilySharingView';
+import { SharingService } from '@aliasvault/client/sharing/SharingService';
+import React, { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { ActivityIndicator, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
+
+import { sharingFailureMessage, unwrapSharingResult } from '@/utils/SharingErrors';
+
+import { useColors } from '@/hooks/useColorScheme';
+
+import { ModalWrapper } from '@/components/common/ModalWrapper';
+import { useWebApi } from '@/context/WebApiContext';
+import NativeVaultManager from '@/specs/NativeVaultManager';
+
+import type { ReceivedManifestInvitation } from '@aliasvault/models/webapi';
+
+interface ISharedFolderInvitationModalProps {
+ invitation: ReceivedManifestInvitation | null;
+ /** The name of the shared folder, as the invitation carries it. */
+ folderName: string;
+ /** Called once the invitation was accepted or declined. */
+ onDone: (accepted: boolean) => Promise<void>;
+ onClose: () => void;
+}
+
+/**
+ * An invitation to a shared folder: accept or decline it. Accepting from an inviter this account has not verified yet
+ * first asks for their code.
+ */
+export const SharedFolderInvitationModal: React.FC<ISharedFolderInvitationModalProps> = ({ invitation, folderName, onDone, onClose }) => {
+ const { t } = useTranslation();
+ const colors = useColors();
+ const webApi = useWebApi();
+ const [askCode, setAskCode] = useState(false);
+ const [code, setCode] = useState('');
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- reset the dialog for each invitation
+ setAskCode(false);
+ setCode('');
+ setError(null);
+ }, [invitation?.id]);
+
+ const styles = StyleSheet.create({
+ bodyText: {
+ color: colors.text,
+ fontSize: 15,
+ },
+ buttonRow: {
+ flexDirection: 'row',
+ gap: 12,
+ marginTop: 20,
+ },
+ codeInput: {
+ backgroundColor: colors.modalSurfaceRaised,
+ borderColor: colors.accentBorder,
+ borderRadius: 8,
+ borderWidth: 1,
+ color: colors.text,
+ fontSize: 16,
+ marginTop: 12,
+ paddingHorizontal: 12,
+ paddingVertical: 10,
+ },
+ disabled: {
+ opacity: 0.5,
+ },
+ errorText: {
+ color: colors.destructive,
+ fontSize: 14,
+ marginTop: 8,
+ },
+ modalButton: {
+ alignItems: 'center',
+ borderColor: colors.accentBorder,
+ borderRadius: 8,
+ borderWidth: 1,
+ flex: 1,
+ paddingVertical: 12,
+ },
+ modalButtonPrimary: {
+ backgroundColor: colors.tint,
+ borderWidth: 0,
+ },
+ modalButtonPrimaryText: {
+ color: colors.white,
+ fontSize: 16,
+ fontWeight: '600',
+ },
+ modalButtonText: {
+ color: colors.text,
+ fontSize: 16,
+ fontWeight: '500',
+ },
+ mutedText: {
+ color: colors.textMuted,
+ fontSize: 14,
+ marginTop: 8,
+ },
+ });
+
+ if (!invitation) {
+ return null;
+ }
+
+ /**
+ * Accept, with the inviter's code when it was asked for; an engine that holds no certification of the inviter asks for it.
+ */
+ const accept = async (): Promise<void> => {
+ if (!askCode && !isInviterVerified(invitation)) {
+ setAskCode(true);
+ return;
+ }
+ if (askCode && code.trim().length === 0) {
+ return;
+ }
+
+ setBusy(true);
+ setError(null);
+ try {
+ const result = await NativeVaultManager.runSharingOperation('acceptSharedManifestInvitation', JSON.stringify({ invitationId: invitation.id, identityCode: askCode ? code.trim() : undefined }));
+ if (result.apiErrorCode === 'INVITER_NOT_VERIFIED') {
+ setAskCode(true);
+ }
+ unwrapSharingResult(result, familySharingText.errors.invitationGone);
+ await onDone(true);
+ } catch (acceptError) {
+ setError(sharingFailureMessage(acceptError, familySharingText.errors.invitationGone));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ /**
+ * Decline the invitation.
+ */
+ const decline = async (): Promise<void> => {
+ setBusy(true);
+ setError(null);
+ try {
+ await SharingService.declineInvitation(webApi, invitation.id);
+ await onDone(false);
+ } catch (declineError) {
+ setError(sharingFailureMessage(declineError, familySharingText.errors.invitationGone));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const canAccept = !busy && !(askCode && code.trim().length === 0);
+
+ return (
+ <ModalWrapper
+ isOpen
+ onClose={onClose}
+ isSubmitting={busy}
+ title={askCode ? familySharingText.inviterCodeTitle(invitation.inviterUsername) : familySharingText.sharedWithYou(invitation.inviterUsername, folderName)}
+ keyboardAvoiding
+ showHeaderBorder={false}
+ showFooterBorder={false}
+ >
+ {!askCode && (
+ <>
+ <Text style={styles.bodyText}>{familySharingText.sharedWithYouHint}</Text>
+ <Text style={styles.mutedText}>{isInviterVerified(invitation) ? familySharingText.invitedByVerified(invitation.inviterUsername) : familySharingText.invitedBy(invitation.inviterUsername)}</Text>
+ </>
+ )}
+ {askCode && (
+ <>
+ <Text style={styles.bodyText}>{familySharingText.inviterCodeExplanation(invitation.inviterUsername)}</Text>
+ <TextInput
+ style={styles.codeInput}
+ value={code}
+ onChangeText={setCode}
+ placeholder={familySharingText.codePlaceholder}
+ placeholderTextColor={colors.textMuted}
+ keyboardType="number-pad"
+ autoCorrect={false}
+ autoFocus
+ editable={!busy}
+ onSubmitEditing={() => void accept()}
+ />
+ </>
+ )}
+ {error && <Text style={styles.errorText}>{error}</Text>}
+ <View style={styles.buttonRow}>
+ <TouchableOpacity style={[styles.modalButton, busy && styles.disabled]} disabled={busy} onPress={() => (askCode ? setAskCode(false) : void decline())}>
+ <Text style={styles.modalButtonText}>{askCode ? t('common.back') : familySharingText.decline}</Text>
+ </TouchableOpacity>
+ <TouchableOpacity style={[styles.modalButton, styles.modalButtonPrimary, !canAccept && styles.disabled]} disabled={!canAccept} onPress={() => void accept()}>
+ {busy ? <ActivityIndicator color={colors.white} size="small" /> : <Text style={styles.modalButtonPrimaryText}>{familySharingText.accept}</Text>}
+ </TouchableOpacity>
+ </View>
+ </ModalWrapper>
+ );
+};
+
+export default SharedFolderInvitationModal;
diff --git a/apps/mobile-app/components/sharing/SharedVaultModal.tsx b/apps/mobile-app/components/sharing/SharedVaultModal.tsx
deleted file mode 100644
index 811f43aa7..000000000
--- a/apps/mobile-app/components/sharing/SharedVaultModal.tsx
+++ /dev/null
@@ -1,165 +0,0 @@
-import { familySharingText, MAX_SHARED_VAULT_NAME_LENGTH } from '@aliasvault/client/sharing/FamilySharingView';
-import * as Haptics from 'expo-haptics';
-import React, { useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { ActivityIndicator, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
-
-import { HapticsUtility } from '@/utils/HapticsUtility';
-
-import { useColors } from '@/hooks/useColorScheme';
-
-import { ModalWrapper } from '@/components/common/ModalWrapper';
-
-interface ISharedVaultModalProps {
- isOpen: boolean;
- onClose: () => void;
- onSave: (name: string) => Promise<void>;
- initialName?: string;
- mode: 'create' | 'rename';
-}
-
-/**
- * Modal for creating or renaming a shared vault.
- */
-export const SharedVaultModal: React.FC<ISharedVaultModalProps> = ({ isOpen, onClose, onSave, initialName = '', mode }) => {
- const { t } = useTranslation();
- const colors = useColors();
- const [name, setName] = useState(initialName);
- const [isSubmitting, setIsSubmitting] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const trimmedName = name.trim();
-
- useEffect(() => {
- if (isOpen) {
- // eslint-disable-next-line react-hooks/set-state-in-effect -- reset the form each time the modal opens
- setName(initialName);
- setError(null);
- }
- }, [isOpen, initialName]);
-
- /**
- * Save the name and close.
- */
- const handleSubmit = async (): Promise<void> => {
- if (!trimmedName || isSubmitting) {
- return;
- }
-
- setIsSubmitting(true);
- setError(null);
-
- try {
- await onSave(trimmedName);
- HapticsUtility.notification(Haptics.NotificationFeedbackType.Success);
- onClose();
- } catch (err) {
- setError(t('common.errors.unknownErrorTryAgain'));
- console.error('Error saving shared vault:', err);
- } finally {
- setIsSubmitting(false);
- }
- };
-
- const canSubmit = trimmedName.length > 0 && !isSubmitting;
-
- const styles = StyleSheet.create({
- buttonRow: {
- flexDirection: 'row',
- gap: 12,
- marginTop: 20,
- },
- cancelButton: {
- alignItems: 'center',
- borderColor: colors.accentBorder,
- borderRadius: 8,
- borderWidth: 1,
- flex: 1,
- paddingVertical: 12,
- },
- cancelButtonText: {
- color: colors.text,
- fontSize: 16,
- fontWeight: '500',
- },
- errorText: {
- color: colors.destructive,
- fontSize: 14,
- marginTop: 8,
- },
- input: {
- backgroundColor: colors.modalSurfaceRaised,
- borderColor: colors.accentBorder,
- borderRadius: 8,
- borderWidth: 1,
- color: colors.text,
- fontSize: 16,
- marginTop: 8,
- paddingHorizontal: 12,
- paddingVertical: 10,
- },
- label: {
- color: colors.textMuted,
- fontSize: 14,
- fontWeight: '500',
- },
- saveButton: {
- alignItems: 'center',
- backgroundColor: colors.tint,
- borderRadius: 8,
- flex: 1,
- paddingVertical: 12,
- },
- saveButtonDisabled: {
- opacity: 0.6,
- },
- saveButtonText: {
- color: colors.white,
- fontSize: 16,
- fontWeight: '600',
- },
- });
-
- return (
- <ModalWrapper
- isOpen={isOpen}
- onClose={onClose}
- isSubmitting={isSubmitting}
- title={mode === 'create' ? familySharingText.createSharedVault : familySharingText.renameVault}
- keyboardAvoiding
- showHeaderBorder={false}
- showFooterBorder={false}
- >
- <Text style={styles.label}>{familySharingText.vaultName}</Text>
- <TextInput
- style={styles.input}
- value={name}
- onChangeText={setName}
- placeholder={familySharingText.vaultNamePlaceholder}
- placeholderTextColor={colors.textMuted}
- maxLength={MAX_SHARED_VAULT_NAME_LENGTH}
- autoFocus
- autoCapitalize="sentences"
- returnKeyType="done"
- onSubmitEditing={handleSubmit}
- editable={!isSubmitting}
- />
-
- {error && <Text style={styles.errorText}>{error}</Text>}
-
- <View style={styles.buttonRow}>
- <TouchableOpacity style={styles.cancelButton} onPress={onClose} disabled={isSubmitting}>
- <Text style={styles.cancelButtonText}>{t('common.cancel')}</Text>
- </TouchableOpacity>
- <TouchableOpacity style={[styles.saveButton, !canSubmit && styles.saveButtonDisabled]} onPress={handleSubmit} disabled={!canSubmit}>
- {isSubmitting ? (
- <ActivityIndicator color={colors.white} size="small" />
- ) : (
- <Text style={styles.saveButtonText}>{mode === 'create' ? familySharingText.create : t('common.save')}</Text>
- )}
- </TouchableOpacity>
- </View>
- </ModalWrapper>
- );
-};
-
-export default SharedVaultModal;
diff --git a/apps/mobile-app/hooks/usePasswordConfirmedAction.ts b/apps/mobile-app/hooks/usePasswordConfirmedAction.ts
new file mode 100644
index 000000000..31c2aae0b
--- /dev/null
+++ b/apps/mobile-app/hooks/usePasswordConfirmedAction.ts
@@ -0,0 +1,54 @@
+import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
+import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { SharingOperationError } from '@/utils/SharingErrors';
+
+import { useLogout } from '@/hooks/useLogout';
+
+import NativeVaultManager from '@/specs/NativeVaultManager';
+
+import type { SrpChallengeResponder } from '@aliasvault/client/sharing/SharingService';
+
+/** Runs an action the server confirms with the master password; resolves false when the prompt was cancelled. */
+export type RunWithPassword = (title: string, description: string, confirmText: string, perform: (answerChallenge: SrpChallengeResponder) => Promise<void>) => Promise<boolean>;
+
+/**
+ * Run actions the server confirms with the master password, behind the native password prompt whose unlock key answers the SRP challenge.
+ */
+export function usePasswordConfirmedAction(): RunWithPassword {
+ const { t } = useTranslation();
+ const { logoutForced } = useLogout();
+
+ return useCallback(async (title, description, confirmText, perform) => {
+ let unlockKey: string | null;
+ try {
+ unlockKey = await NativeVaultManager.showPasswordUnlockForKey(title, description, confirmText);
+ } catch (err) {
+ // Too many wrong passwords: the native layer cleared the vault, so log out.
+ if (err && typeof err === 'object' && 'code' in err && err.code === 'MAX_ATTEMPTS_REACHED') {
+ await logoutForced();
+ }
+ return false;
+ }
+
+ if (!unlockKey) {
+ return false;
+ }
+
+ try {
+ await perform(async challenge => {
+ const passwordHash = await SrpAuthService.srpPasswordHash(unlockKey, challenge.encryptionType);
+ return SrpAuthService.deriveClientProof(challenge.salt, challenge.srpIdentity, passwordHash, challenge.serverEphemeral);
+ });
+ } catch (actionError) {
+ // The local unlock key can differ from the server's after a password change on another device.
+ if (apiErrorCodeOf(actionError) === 'PASSWORD_MISMATCH') {
+ throw new SharingOperationError(t('common.errors.wrongPassword'));
+ }
+ throw actionError;
+ }
+ return true;
+ }, [logoutForced, t]);
+}
diff --git a/apps/mobile-app/hooks/useSharedFolders.ts b/apps/mobile-app/hooks/useSharedFolders.ts
new file mode 100644
index 000000000..dd2dd3b50
--- /dev/null
+++ b/apps/mobile-app/hooks/useSharedFolders.ts
@@ -0,0 +1,65 @@
+import { sharingView, type SharedFolder } from '@aliasvault/client/sharing/FamilySharingView';
+import { SharingService } from '@aliasvault/client/sharing/SharingService';
+import { CapabilityKeys } from '@aliasvault/models/webapi';
+import { useFocusEffect } from 'expo-router';
+import { useCallback, useEffect, useState } from 'react';
+
+import emitter from '@/utils/EventEmitter';
+
+import { useCapabilities } from '@/context/CapabilityContext';
+import { useWebApi } from '@/context/WebApiContext';
+import NativeVaultManager from '@/specs/NativeVaultManager';
+
+import type { GroupMemberInfo, ReceivedManifestInvitation } from '@aliasvault/models/webapi';
+
+/**
+ * What the vault shows of sharing: the shared folders with their people, the invitations waiting for an answer, the
+ * people verified before and this account's own code.
+ */
+export type SharedFolders = {
+ isEnabled: boolean;
+ myUserId: string;
+ folders: SharedFolder[];
+ invitations: ReceivedManifestInvitation[];
+ invitationNames: Record<string, string>;
+ verifiedPeople: GroupMemberInfo[];
+ ownCode: string | null;
+ reload: () => Promise<void>;
+};
+
+/**
+ * Load the sharing overview while vault sharing is enabled: when the screen gains focus, after every sync, and on request.
+ */
+export function useSharedFolders(): SharedFolders {
+ const webApi = useWebApi();
+ const isEnabled = useCapabilities()(CapabilityKeys.VaultSharing);
+ const [view, setView] = useState<ReturnType<typeof sharingView>>(sharingView(null));
+ const [invitationNames, setInvitationNames] = useState<Record<string, string>>({});
+ const [ownCode, setOwnCode] = useState<string | null>(null);
+
+ const reload = useCallback(async (): Promise<void> => {
+ if (!isEnabled) {
+ return;
+ }
+ try {
+ const overview = await SharingService.getOverview(webApi);
+ setView(sharingView(overview));
+ setInvitationNames(await SharingService.openInvitationNames(overview.receivedInvitations, encryptedName => NativeVaultManager.decryptInvitationName(encryptedName)));
+ // The own code is derived natively from the signing private key, which only the native layer can open.
+ setOwnCode(await NativeVaultManager.getSigningKeyFingerprint());
+ } catch {
+ // Offline or not reachable: the vault keeps showing what it already knew.
+ }
+ }, [isEnabled, webApi]);
+
+ useFocusEffect(useCallback(() => {
+ void reload();
+ }, [reload]));
+
+ useEffect(() => {
+ const subscription = emitter.addListener('vaultSynced', () => void reload());
+ return (): void => subscription.remove();
+ }, [reload]);
+
+ return { isEnabled, ...view, invitationNames, ownCode, reload };
+}
diff --git a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift
index 50f2a2487..77f59c71c 100644
--- a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift
@@ -142,6 +142,13 @@ public class NativeVaultManager: NSObject {
resolve(vaultStore.decryptWithAccountPrivateKey(encryptedName))
}
+ /// The identity code of the account's own signing key; nil while locked or when the account has no signing key yet.
+ @objc
+ func getSigningKeyFingerprint(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ resolve(vaultStore.signingKeyFingerprint())
+ }
+
/// Resolve and store the vault key right after login from the password-derived key (see VaultStore.resolveVaultKey).
@objc
func resolveVaultKey(_ base64DerivedKey: String,
@@ -884,7 +891,10 @@ public class NativeVaultManager: NSObject {
"vaultUpgradeRequired": result.vaultUpgradeRequired,
"apiErrorCode": result.apiErrorCode as Any,
"error": result.error as Any,
- "errorMessage": result.errorMessage as Any
+ "errorMessage": result.errorMessage as Any,
+ "manifestId": result.manifestId as Any,
+ "username": result.username as Any,
+ "alreadyMember": result.alreadyMember
]
resolve(response)
}
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index 12dca8212..e140215e9 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -133,6 +133,10 @@
[vaultManager decryptInvitationName:encryptedName resolver:resolve rejecter:reject];
}
+- (void)getSigningKeyFingerprint:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager getSigningKeyFingerprint:resolve rejecter:reject];
+}
+
- (void)unlockVault:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
[vaultManager unlockVault:resolve rejecter:reject];
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Models/SyncModels.swift b/apps/mobile-app/ios/VaultStoreKit/Models/SyncModels.swift
index 9ce03d56b..1ddf1c9f8 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Models/SyncModels.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Models/SyncModels.swift
@@ -79,19 +79,25 @@ public struct VaultMigrationResult {
}
}
-/// Result of a sharing operation of the sync engine (creating a shared manifest, inviting a member to one).
+/// Result of a sharing operation of the sync engine (creating a shared manifest, inviting to one, accepting an invitation).
public struct VaultSharingResult {
public let success: Bool
public let apiErrorCode: String?
public let vaultUpgradeRequired: Bool
public let error: String?
public let errorMessage: String?
+ public let manifestId: String?
+ public let username: String?
+ public let alreadyMember: Bool
- public init(success: Bool, apiErrorCode: String? = nil, vaultUpgradeRequired: Bool = false, error: String? = nil, errorMessage: String? = nil) {
+ public init(success: Bool, apiErrorCode: String? = nil, vaultUpgradeRequired: Bool = false, error: String? = nil, errorMessage: String? = nil, manifestId: String? = nil, username: String? = nil, alreadyMember: Bool = false) {
self.success = success
self.apiErrorCode = apiErrorCode
self.vaultUpgradeRequired = vaultUpgradeRequired
self.error = error
self.errorMessage = errorMessage
+ self.manifestId = manifestId
+ self.username = username
+ self.alreadyMember = alreadyMember
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
index 643f5ff11..3f41c4c8e 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
@@ -120,7 +120,7 @@ internal final class VaultSync {
return failedSharing(Self.driverError(error))
}
if result["success"] as? Bool == true {
- return VaultSharingResult(success: true)
+ return VaultSharingResult(success: true, manifestId: result["manifestId"] as? String, username: result["username"] as? String, alreadyMember: result["alreadyMember"] as? Bool ?? false)
}
let apiErrorCode = result["apiErrorCode"] as? String
let vaultUpgradeRequired = result["vaultUpgradeRequired"] as? Bool ?? false
@@ -237,7 +237,7 @@ internal final class VaultSync {
}
/// The engine operations the sharing screen may ask for.
- private static let sharingOperations: Set<String> = ["createSharedManifest", "inviteToSharedManifest", "updateSharedManifest"]
+ private static let sharingOperations: Set<String> = ["createSharedManifest", "inviteToSharedManifest", "updateSharedManifest", "lookupIdentityCode", "acceptSharedManifestInvitation"]
/// The forced logouts by the engine's reason.
private static let logoutErrors: [String: AppError] = [
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
index 46ec105cb..49422a831 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
@@ -18,6 +18,9 @@ public final class VaultSyncEngine {
private static let encryptedVekStateKey = "encryptedVek"
private static let encryptedAccountPrivateKeyStateKey = "encryptedAccountPrivateKey"
+ /// Engine state key holding the account signing private key encrypted with the Account Key, which the own identity code derives from.
+ static let encryptedSigningPrivateKeyStateKey = "encryptedSigningPrivateKey"
+
/// Engine state key that lives in the native store instead (the login writes it there), routed on read and write.
private static let derivationParamsStateKey = "encryptionKeyDerivationParams"
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
index d6f388e25..21e482247 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
@@ -148,6 +148,17 @@ extension VaultStore {
return String(data: plaintext, encoding: .utf8)
}
+ /// The identity code of the account's own signing key, derived from the private key the sync engine cached, or nil
+ /// while the vault is locked or the account has no signing key yet.
+ /// Other platform implementations: SharingService.ownIdentityCode (core/client), VaultStore.signingKeyFingerprint (Android).
+ public func signingKeyFingerprint() -> String? {
+ guard let accountKeyBase64 = accountKeyBase64, let accountKey = Data(base64Encoded: accountKeyBase64),
+ let encryptedSigningPrivateKey = VaultSyncEngine.persistedState(forKey: VaultSyncEngine.encryptedSigningPrivateKeyStateKey, in: userDefaults) as? String else {
+ return nil
+ }
+ return try? RustCoreFramework.accountSigningKeyFingerprint(encryptedSigningPrivateKey: encryptedSigningPrivateKey, accountKey: accountKey)
+ }
+
/// Verify the password and return its unlock key (base64) if correct. Callers derive the SRP input from it for the
/// account's encryption type; `storeAccountKey` turns it into the Account Key.
public func verifyPassword(_ password: String) -> String? {
diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.ts
index 5efe33982..1fb08a657 100644
--- a/apps/mobile-app/platform/NativeRustCore.ts
+++ b/apps/mobile-app/platform/NativeRustCore.ts
@@ -71,6 +71,7 @@ export const nativeRustCore: IRustCore = {
symmetricDecryptBytes: (encrypted, keyBase64) => callForBytes('symmetricDecryptBytes', base64(encrypted), keyBase64),
symmetricEncryptBytes: (plaintext, keyBase64) => callForBytes('symmetricEncryptBytes', base64(plaintext), keyBase64),
rsaDecrypt: (base64Ciphertext, privateKeyJwk) => callForBytes('rsaDecrypt', base64Ciphertext, privateKeyJwk),
+ accountSigningKeyFingerprint: () => notImplementedOnMobile('accountSigningKeyFingerprint', 'the Account Key stays in the native VaultStore, use NativeVaultManager.getSigningKeyFingerprint'),
pinGenerateSalt: () => notImplementedOnMobile('pinGenerateSalt', PIN_IS_NATIVE),
pinEncrypt: () => notImplementedOnMobile('pinEncrypt', PIN_IS_NATIVE),
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index 903f1628c..975a33be7 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -36,7 +36,7 @@ export interface Spec extends TurboModule {
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 }>;
+ runSharingOperation(operation: string, paramsJson: string): Promise<{ success: boolean; apiErrorCode: string | null; vaultUpgradeRequired: boolean; error: string | null; errorMessage: string | null; manifestId: string | null; username: string | null; alreadyMember: boolean }>;
// Quick check if sync is needed
checkSyncStatus(): Promise<{ success: boolean; hasNewerVault: boolean; hasDirtyChanges: boolean; isOffline: boolean; requiresLogout: boolean; errorCode: string | null }>;
@@ -72,6 +72,7 @@ export interface Spec extends TurboModule {
resolveVaultKey(base64DerivedKey: string): Promise<void>;
getPersonalManifestId(): Promise<string | null>;
decryptInvitationName(encryptedName: string): Promise<string | null>;
+ getSigningKeyFingerprint(): Promise<string | null>;
hasEncryptedDatabase(): Promise<boolean>;
// Auto-lock settings
diff --git a/apps/mobile-app/utils/SharingErrors.ts b/apps/mobile-app/utils/SharingErrors.ts
new file mode 100644
index 000000000..db687e83e
--- /dev/null
+++ b/apps/mobile-app/utils/SharingErrors.ts
@@ -0,0 +1,56 @@
+import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
+import { familySharingText, sharingErrorMessage } from '@aliasvault/client/sharing/FamilySharingView';
+
+import NativeVaultManager from '@/specs/NativeVaultManager';
+
+import type { VaultSyncSharingOperation } from '@aliasvault/client/sync/VaultSyncEngine';
+
+/** What a native sharing operation answers. */
+export type NativeSharingResult = Awaited<ReturnType<typeof NativeVaultManager.runSharingOperation>>;
+
+/**
+ * Error thrown by a failed sharing operation, carrying the message to show.
+ */
+export class SharingOperationError extends Error {}
+
+/**
+ * The message to show for a failed sharing action.
+ * @param error - the error thrown by the call.
+ * @param fallback - the message for an error the sharing screens have no words for.
+ */
+export function sharingFailureMessage(error: unknown, fallback: string): string {
+ if (error instanceof SharingOperationError) {
+ return error.message;
+ }
+
+ const code = apiErrorCodeOf(error);
+ return sharingErrorMessage(code) ?? (code !== null ? `${fallback} [${code}]` : fallback);
+}
+
+/**
+ * Throw the error a failed native sharing operation stands for.
+ * @param result - what the operation returned.
+ * @param fallback - the message for a failure without a more specific reason.
+ */
+export function unwrapSharingResult(result: NativeSharingResult, fallback: string): NativeSharingResult {
+ if (result.success) {
+ return result;
+ }
+
+ if (result.vaultUpgradeRequired) {
+ throw new SharingOperationError(familySharingText.errors.vaultUpgradeRequired);
+ }
+
+ const code = result.apiErrorCode ?? result.error;
+ throw new SharingOperationError(sharingErrorMessage(result.apiErrorCode) ?? (code ? `${fallback} [${code}]` : fallback));
+}
+
+/**
+ * Run one of the native sync engine's sharing operations, which hold the keys the JS side never sees.
+ * @param operation - the engine operation.
+ * @param params - what it acts on.
+ * @param fallback - the message for a failure without a more specific reason.
+ */
+export async function runSharingOperation(operation: VaultSyncSharingOperation, params: Record<string, string | undefined>, fallback: string): Promise<NativeSharingResult> {
+ return unwrapSharingResult(await NativeVaultManager.runSharingOperation(operation, JSON.stringify(params)), fallback);
+}