Skip to content

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

Add browser extension new identity code and family sharing helpers (#2536)

Leendert de Borstc928a651233b
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index bc2c8edcc..7641e60ac 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -13,7 +13,7 @@ import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, han
import { handleOpenPopup, handlePopupWithItem, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';
import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePromptState, handleGetLastAutofilled, handleClearLastAutofilled } from '@/entrypoints/background/SavePromptStateHandler';
import { handleGetTwoFactorPrompt, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
-import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetEncryptionKey, handleGetUnlockKeyDerivationParams, handleGetPersistedFormValues, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreAccountKey, handleStoreUnlockKeyDerivationParams, handleStoreEncryptedVaultChunk, handleGetSyncState, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupUpdateVault, handleGroupRevokeAccess, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpCodes, handleGenerateTotpCode, handleGetAutofillCredential, handleRecordItemUsage, type AutofillSender } from '@/entrypoints/background/VaultMessageHandler';
+import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetEncryptionKey, handleGetUnlockKeyDerivationParams, handleGetPersistedFormValues, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreAccountKey, handleStoreUnlockKeyDerivationParams, handleStoreEncryptedVaultChunk, handleGetSyncState, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupUpdateVault, handleGroupLookupIdentityCode, handleGroupInviteMemberByCode, handleGroupAcceptManifestInvitation, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpCodes, handleGenerateTotpCode, handleGetAutofillCredential, handleRecordItemUsage, type AutofillSender } from '@/entrypoints/background/VaultMessageHandler';
import { getCurrentAutofillFrameUrl } from '@/entrypoints/contentScript/AutofillFrameUrl';
import { logFailure } from '@/utils/Diagnostics';
@@ -316,7 +316,9 @@ export default defineBackground({
onExtensionPageMessage('GROUP_CREATE_VAULT', ({ data }) => handleGroupCreateVault(data));
onExtensionPageMessage('GROUP_UPDATE_VAULT', ({ data }) => handleGroupUpdateVault(data));
onExtensionPageMessage('GROUP_INVITE_MEMBER', ({ data }) => handleGroupInviteMember(data));
- onExtensionPageMessage('GROUP_REVOKE_ACCESS', ({ data }) => handleGroupRevokeAccess(data));
+ onExtensionPageMessage('GROUP_LOOKUP_IDENTITY_CODE', ({ data }) => handleGroupLookupIdentityCode(data));
+ onExtensionPageMessage('GROUP_INVITE_MEMBER_BY_CODE', ({ data }) => handleGroupInviteMemberByCode(data));
+ onExtensionPageMessage('GROUP_ACCEPT_MANIFEST_INVITATION', ({ data }) => handleGroupAcceptManifestInvitation(data));
onExtensionPageMessage('LOCK_VAULT', () => handleLockVault());
onExtensionPageMessage('CLEAR_SESSION', () => handleClearSession());
onExtensionPageMessage('CLEAR_VAULT_DATA', () => handleClearVaultData());
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 0e8ea4516..92b7d37e6 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -1,6 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
-import { ApiRequestError } from '@aliasvault/client/api/errors/ApiRequestError';
import { AppErrorCode, formatErrorWithCode } from '@aliasvault/client/api/errors/AppErrorCodes';
import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
import { WebApiService } from '@aliasvault/client/api/WebApiService';
@@ -16,7 +15,6 @@ import { generateTotpCode } from '@aliasvault/client/items/TotpUtility';
import { getOrCreateDeviceId } from '@aliasvault/client/platform/DeviceId';
import { filterItems, AutofillMatchingMode, extractRootDomain, isUrlAlreadyLinked } from '@aliasvault/client/rust/RustCore';
import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
-import { SharingService } from '@aliasvault/client/sharing/SharingService';
import { clearDirtyScopes, getDirtyScopes } from '@aliasvault/client/sync/VaultDirtyState';
import { vaultRequiresManifestMigration, VaultMigrationKind } from '@aliasvault/client/sync/VaultManifestMigration';
import { type VaultMutationScope, DEFAULT_VAULT_MUTATION_SCOPE, hasUserVisibleScope } from '@aliasvault/client/sync/VaultMutationScope';
@@ -1455,16 +1453,16 @@ export async function handleGetAutofillCredential(
/**
* What a sharing action reports back to the page that asked for it.
*/
-type SharingActionResponse = { success: boolean; error?: string; apiErrorCode?: string };
+export type SharingActionResponse = { success: boolean; error?: string; apiErrorCode?: string; manifestId?: string; username?: string; alreadyMember?: boolean };
/**
- * Put the outcome of a sharing engine operation into the words the family sharing page shows.
+ * Put the outcome of a sharing engine operation into the words the shared folders page shows.
* @param result - what the sync engine reported.
* @param failureMessage - the message for a failure without a more specific reason.
*/
async function sharingActionResponse(result: SharingOperationResult, failureMessage: string): Promise<SharingActionResponse> {
if (result.success) {
- return { success: true };
+ return { success: true, manifestId: result.manifestId, username: result.username, alreadyMember: result.alreadyMember };
}
if (result.apiErrorCode) {
@@ -1489,61 +1487,69 @@ async function sharingActionResponse(result: SharingOperationResult, failureMess
}
/**
- * Create another shared manifest for a family, with this account as its first member. The sync engine does the work,
- * so every client creates one the same way.
+ * Create a shared folder with this account as its owner; the server creates its group. The sync that follows pushes it,
+ * which inviting to it needs.
*
- * @param message - the family to create the vault for and the name to give it.
+ * @param message - the folder name.
*/
-export async function handleGroupCreateVault(message: { groupId: string; name: string }): Promise<SharingActionResponse> {
- const result = await vaultSync.createSharedManifest(message.groupId, message.name);
+export async function handleGroupCreateVault(message: { name: string }): Promise<SharingActionResponse> {
+ const result = await vaultSync.createSharedManifest(message.name);
if (result.success) {
- // The engine left the new folder and keypair in a dirty vault; this pushes them.
- void handleFullVaultSync().catch(error => logFailure('Background sync after creating a shared manifest failed', error));
+ await handleFullVaultSync().catch(error => logFailure('Background sync after creating a shared manifest failed', error));
}
return sharingActionResponse(result, familySharingText.errors.createVaultFailed);
}
/**
- * Change the details of one of a family's shared manifests. The server only accepts it from an administrator of the
- * family.
+ * Change the details of a shared folder. The server only accepts it from an administrator of its group.
*
- * @param message - the family, the manifest, and the details to change.
+ * @param message - the group, the manifest, and the details to change.
*/
export async function handleGroupUpdateVault(message: { groupId: string; manifestId: string; details: SharedManifestDetails }): Promise<SharingActionResponse> {
return sharingActionResponse(await vaultSync.updateSharedManifest(message.groupId, message.manifestId, message.details), await t('common.errors.unknownErrorTryAgain'));
}
/**
- * Invite a member of a family to one of its shared manifests, handing them the manifest's key encrypted to their
- * account keypair. The sync engine does the work, so every client invites the same way.
+ * Invite somebody verified before to a shared folder, handing them its key encrypted to their account keypair.
*
- * @param message - the family, the manifest, and the member being invited.
+ * @param message - the group, the manifest, and the person being invited.
*/
export async function handleGroupInviteMember(message: { groupId: string; manifestId: string; userId: string }): Promise<SharingActionResponse> {
return sharingActionResponse(await vaultSync.inviteToSharedManifest(message.groupId, message.manifestId, message.userId), familySharingText.errors.inviteFailed);
}
/**
- * Take a member's access to one shared manifest away, or hand back one's own.
+ * Find the account behind an identity code and check the code against its key, without certifying or inviting it.
*
- * @param message - the family, the vault, and the member losing access.
+ * @param message - the folder's group (none while the folder is still personal) and the identity code.
*/
-export async function handleGroupRevokeAccess(message: { groupId: string; manifestId: string; userId: string }): Promise<SharingActionResponse> {
- try {
- const webApi = new WebApiService();
- await SharingService.revokeAccess(webApi, message.groupId, message.manifestId, message.userId);
-
- devLog(`[Sharing] Revoked ${message.userId}'s access to vault ${message.manifestId}; syncing to pick up whatever the server left for this client to finish.`);
- void handleFullVaultSync().catch(error => logFailure('Background sync after a vault access change failed', error));
+export async function handleGroupLookupIdentityCode(message: { groupId?: string; identityCode: string }): Promise<SharingActionResponse> {
+ return sharingActionResponse(await vaultSync.lookupIdentityCode(message.groupId, message.identityCode), familySharingText.errors.inviteFailed);
+}
- return { success: true };
- } catch (error) {
- if (error instanceof ApiRequestError && error.apiErrorCode) {
- return { success: false, apiErrorCode: error.apiErrorCode };
- }
+/**
+ * Invite the account behind an identity code to a shared folder. The sync engine checks the key the server returns
+ * against the code and certifies it first; accepting makes the account a member of the folder's group.
+ *
+ * @param message - the group, the manifest, and the identity code.
+ */
+export async function handleGroupInviteMemberByCode(message: { groupId: string; manifestId: string; identityCode: string }): Promise<SharingActionResponse> {
+ return sharingActionResponse(await vaultSync.inviteToSharedManifestByCode(message.groupId, message.manifestId, message.identityCode), familySharingText.errors.inviteFailed);
+}
- logFailure('Failed to revoke shared manifest access', error);
- return { success: false, error: familySharingText.errors.revokeAccessFailed };
+/**
+ * Accept an invitation to a shared manifest: the sync engine signs the grant as this account's own, and the sync that
+ * follows pulls the shared manifest.
+ *
+ * @param message - the invitation and the inviter's identity code, when they are not verified yet.
+ */
+export async function handleGroupAcceptManifestInvitation(message: { invitationId: string; identityCode?: string }): Promise<SharingActionResponse> {
+ const result = await vaultSync.acceptSharedManifestInvitation(message.invitationId, message.identityCode);
+ if (result.success) {
+ await handleFullVaultSync();
}
+
+ return sharingActionResponse(result, familySharingText.errors.invitationGone);
}
+
diff --git a/apps/browser-extension/src/entrypoints/popup/App.tsx b/apps/browser-extension/src/entrypoints/popup/App.tsx
index 29528a333..619b5b019 100644
--- a/apps/browser-extension/src/entrypoints/popup/App.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/App.tsx
@@ -1,4 +1,3 @@
-import { CapabilityKeys } from '@aliasvault/models/webapi';
import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { HashRouter as Router, Routes, Route, useLocation } from 'react-router-dom';
@@ -9,7 +8,6 @@ import OverlayScrollbar from '@/entrypoints/popup/components/Layout/OverlayScrol
import PasskeyLayout from '@/entrypoints/popup/components/Layout/PasskeyLayout';
import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';
import { useApp } from '@/entrypoints/popup/context/AppContext';
-import { RequireCapability } from '@/entrypoints/popup/context/CapabilityContext';
import { useHeaderButtons } from '@/entrypoints/popup/context/HeaderButtonsContext';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { NavigationProvider } from '@/entrypoints/popup/context/NavigationContext';
@@ -33,7 +31,6 @@ import AutofillSettings from '@/entrypoints/popup/pages/settings/AutofillSetting
import AutoLockSettings from '@/entrypoints/popup/pages/settings/AutoLockSettings';
import ClipboardSettings from '@/entrypoints/popup/pages/settings/ClipboardSettings';
import ContextMenuSettings from '@/entrypoints/popup/pages/settings/ContextMenuSettings';
-import FamilySharingSettings from '@/entrypoints/popup/pages/settings/FamilySharingSettings';
import IdentityGeneratorSettings from '@/entrypoints/popup/pages/settings/IdentityGeneratorSettings';
import ImportExportSettings from '@/entrypoints/popup/pages/settings/ImportExportSettings';
import LanguageSettings from '@/entrypoints/popup/pages/settings/LanguageSettings';
@@ -227,7 +224,6 @@ const App: React.FC = () => {
{ path: '/settings/password-generator', element: <PasswordGeneratorSettings />, showBackButton: true, title: t('common.settings') },
{ path: '/settings/appearance', element: <AppearanceSettings />, showBackButton: true, title: t('common.settings') },
{ path: '/settings/import-export', element: <ImportExportSettings />, showBackButton: true, title: t('common.settings') },
- { path: '/settings/family-sharing', element: <RequireCapability capability={CapabilityKeys.VaultSharing}><FamilySharingSettings /></RequireCapability>, showBackButton: true, title: t('common.settings') },
], [t]);
useEffect(() => {
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Folders/FolderModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Folders/FolderModal.tsx
index 1398b4be0..79a1d1cc4 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Folders/FolderModal.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Folders/FolderModal.tsx
@@ -9,9 +9,11 @@ import { logFailure } from '@/utils/Diagnostics';
type FolderModalProps = {
isOpen: boolean;
onClose: () => void;
+ /** Save the name; throws an error with the message to show. */
onSave: (folderName: string) => Promise<void>;
initialName?: string;
mode: 'create' | 'edit';
+ maxLength?: number;
};
/**
@@ -22,7 +24,8 @@ const FolderModal: React.FC<FolderModalProps> = ({
onClose,
onSave,
initialName = '',
- mode
+ mode,
+ maxLength
}) => {
const { t } = useTranslation();
const [folderName, setFolderName] = useState(initialName);
@@ -55,11 +58,8 @@ const FolderModal: React.FC<FolderModalProps> = ({
await onSave(trimmedName);
onClose();
} catch (err) {
- if (hasErrorCode(err)) {
- setError(getErrorMessage(err, t('common.errors.unknownErrorTryAgain')));
- } else {
- setError(t('common.errors.unknownErrorTryAgain'));
- }
+ const fallback = err instanceof Error && err.message.length > 0 ? err.message : t('common.errors.unknownErrorTryAgain');
+ setError(hasErrorCode(err) ? getErrorMessage(err, t('common.errors.unknownErrorTryAgain')) : fallback);
logFailure('Error saving folder', err);
} finally {
setIsSubmitting(false);
@@ -109,6 +109,7 @@ const FolderModal: React.FC<FolderModalProps> = ({
type="text"
value={folderName}
onChange={(e) => setFolderName(e.target.value)}
+ maxLength={maxLength}
autoFocus
className="w-full p-2 border dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
/>
diff --git a/apps/browser-extension/src/entrypoints/popup/components/InlineSpinner.tsx b/apps/browser-extension/src/entrypoints/popup/components/InlineSpinner.tsx
new file mode 100644
index 000000000..575c8ff66
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/components/InlineSpinner.tsx
@@ -0,0 +1,15 @@
+import React from 'react';
+
+import Icon from '@/entrypoints/popup/components/Icons/Icon';
+
+/**
+ * A spinner with a line of text, shown in place of a dialog's content while it works.
+ */
+const InlineSpinner: React.FC<{ text: string }> = ({ text }) => (
+ <div className="flex flex-col items-center justify-center gap-3 py-8" role="status">
+ <Icon name="spinner" className="w-8 h-8 animate-spin text-primary-500" />
+ <p className="text-sm text-center text-gray-600 dark:text-gray-300">{text}</p>
+ </div>
+);
+
+export default InlineSpinner;
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Sharing/FamilyCodeDisplay.tsx b/apps/browser-extension/src/entrypoints/popup/components/Sharing/FamilyCodeDisplay.tsx
new file mode 100644
index 000000000..6800de8af
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/components/Sharing/FamilyCodeDisplay.tsx
@@ -0,0 +1,55 @@
+import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
+import React, { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import Icon from '@/entrypoints/popup/components/Icons/Icon';
+
+type FamilyCodeDisplayProps = {
+ code: string;
+ id?: string;
+ className?: string;
+ /** A smaller pill, for showing the code inside other content. */
+ isSmall?: boolean;
+};
+
+/**
+ * The user's own code in a pill; clicking anywhere on it copies the code.
+ */
+const FamilyCodeDisplay: React.FC<FamilyCodeDisplayProps> = ({ code, id, className = '', isSmall = false }) => {
+ const { t } = useTranslation();
+ const [copied, setCopied] = useState(false);
+
+ useEffect(() => {
+ if (!copied) {
+ return;
+ }
+ const timer = setTimeout(() => setCopied(false), 2000);
+ return (): void => clearTimeout(timer);
+ }, [copied]);
+
+ /**
+ * Copy the code. It is not secret, so it stays on the clipboard instead of going through the auto-clearing copy.
+ */
+ const copy = async (): Promise<void> => {
+ try {
+ await navigator.clipboard.writeText(code);
+ setCopied(true);
+ } catch {
+ // Clipboard access denied; the code stays visible to copy by hand.
+ }
+ };
+
+ return (
+ <button type="button" onClick={() => void copy()} title={t('common.copyToClipboard')} className={`inline-flex flex-wrap items-center rounded-full text-left bg-primary-50 hover:bg-primary-100 dark:bg-primary-900/30 dark:hover:bg-primary-900/50 border border-primary-200 dark:border-primary-800 ${isSmall ? 'gap-x-1.5 gap-y-0.5 pl-2.5 pr-1 py-0.5' : 'gap-x-2 gap-y-1 px-3 py-1.5'} ${className}`}>
+ <Icon name="shield-check" className={`${isSmall ? 'w-3.5 h-3.5' : 'w-4 h-4'} shrink-0 text-primary-500`} />
+ <span className="text-xs text-gray-700 dark:text-gray-300">{familySharingText.yourCode}</span>
+ <span id={id} className={`font-mono ${isSmall ? 'text-xs' : 'text-sm'} font-semibold tracking-wider whitespace-nowrap text-gray-900 dark:text-white`}>{code}</span>
+ <span className="inline-flex items-center gap-1 p-1 text-primary-600 dark:text-primary-400">
+ <Icon name={copied ? 'check' : 'duplicate'} className={isSmall ? 'w-3.5 h-3.5' : 'w-4 h-4'} />
+ {copied && <span className="text-xs">{t('common.copiedShort')}</span>}
+ </span>
+ </button>
+ );
+};
+
+export default FamilyCodeDisplay;
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Sharing/InviteMemberWizard.tsx b/apps/browser-extension/src/entrypoints/popup/components/Sharing/InviteMemberWizard.tsx
new file mode 100644
index 000000000..89e9b9658
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/components/Sharing/InviteMemberWizard.tsx
@@ -0,0 +1,257 @@
+import { familySharingText, splitAround } from '@aliasvault/client/sharing/FamilySharingView';
+import React, { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';
+import Icon from '@/entrypoints/popup/components/Icons/Icon';
+import InlineSpinner from '@/entrypoints/popup/components/InlineSpinner';
+import FamilyCodeDisplay from '@/entrypoints/popup/components/Sharing/FamilyCodeDisplay';
+
+/**
+ * `text` with `value` in bold.
+ * @param text - the full text.
+ * @param value - the part to emphasize.
+ */
+const emphasized = (text: string, value: string): React.ReactNode => {
+ const [before, bold, after] = splitAround(text, value);
+ return <>{before}<strong className="font-semibold text-gray-900 dark:text-white">{bold}</strong>{after}</>;
+};
+
+/** 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;
+};
+
+type InviteMemberWizardProps = {
+ isOpen: boolean;
+ /** This 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;
+ /** The people verified before who are not in the folder yet, offered before the code field. */
+ people?: KnownPerson[];
+ /** 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>;
+ /** Invite somebody verified before; throws an error with the message to show. */
+ onInvitePerson?: (userId: string) => Promise<void>;
+ onClose: () => void;
+};
+
+const STEP_COUNT = 3;
+
+/** Seconds the close button of the last step stays disabled, so the instructions get read. */
+const CLOSE_DELAY_SECONDS = 3;
+
+const INPUT_CLASS = 'w-full p-2 border dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500';
+const PRIMARY_CLASS = 'px-4 py-2 text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 rounded focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50';
+const SECONDARY_CLASS = 'px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50';
+
+/**
+ * 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.
+ */
+const InviteMemberWizard: React.FC<InviteMemberWizardProps> = ({ isOpen, ownCode, folderName, sharesFolder = false, people = [], onLookup, onInvite, onInvitePerson, onClose }) => {
+ const { t } = useTranslation();
+ 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(0);
+
+ useEffect(() => {
+ if (isOpen) {
+ setStep(1);
+ setCode('');
+ setAccount(null);
+ setSelected(null);
+ setError(null);
+ }
+ }, [isOpen]);
+
+ useEffect(() => {
+ if (closeCountdown <= 0) {
+ return;
+ }
+ const timer = setTimeout(() => setCloseCountdown(previous => previous - 1), 1000);
+ return (): void => clearTimeout(timer);
+ }, [closeCountdown]);
+
+ const trimmedCode = code.trim();
+
+ /**
+ * Run one step's action, showing its error in the wizard.
+ * @param action - the action.
+ */
+ const runStep = async (action: () => Promise<void>): Promise<void> => {
+ setIsBusy(true);
+ setError(null);
+ try {
+ await action();
+ } catch (stepError) {
+ setError(stepError instanceof Error && stepError.message.length > 0 ? 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 = !isBusy && (step !== 3 || closeCountdown <= 0);
+
+ /**
+ * Close, unless a step is running or the last step still counts down.
+ */
+ const close = (): void => {
+ if (canClose) {
+ onClose();
+ }
+ };
+
+ const footer = (
+ <div className="flex justify-end gap-3">
+ {step === 1 && <button type="button" onClick={close} disabled={isBusy} className={SECONDARY_CLASS}>{t('common.cancel')}</button>}
+ {step === 1 && <button id="invite-wizard-next" type="submit" form="invite-member-form" disabled={isBusy || (selected === null && trimmedCode.length === 0)} className={PRIMARY_CLASS}>{t('common.next')}</button>}
+ {step === 2 && <button type="button" onClick={() => setStep(1)} disabled={isBusy} className={SECONDARY_CLASS}>{t('common.back')}</button>}
+ {step === 2 && <button id="invite-wizard-confirm" type="button" onClick={() => void invite()} disabled={isBusy} className={PRIMARY_CLASS}>{familySharingText.invite}</button>}
+ {step === 3 && <button id="invite-wizard-close" type="button" onClick={close} disabled={!canClose} className={PRIMARY_CLASS}>{closeCountdown > 0 ? familySharingText.closeCountdown(closeCountdown) : t('common.close')}</button>}
+ </div>
+ );
+
+ return (
+ <ModalWrapper isOpen={isOpen} onClose={close} title={familySharingText.invitePeople} showCloseButton={canClose} footer={footer}>
+ {/* Progress through the three steps. */}
+ <div className="mb-4">
+ <div className="flex gap-2" aria-hidden="true">
+ {Array.from({ length: STEP_COUNT }, (_, index) => (
+ <div key={index} className={`h-1.5 flex-1 rounded-full ${index < step ? 'bg-primary-500' : 'bg-gray-200 dark:bg-gray-700'}`} />
+ ))}
+ </div>
+ <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">{familySharingText.wizardStep(step, STEP_COUNT)}</p>
+ </div>
+
+ {/* While a step works (looking the code up, or sharing the folder and sending the invitation) its content makes way for a spinner. */}
+ {isBusy && <InlineSpinner text={step === 2 && sharesFolder ? familySharingText.wizardCreating : t('common.loading')} />}
+
+ {step === 1 && !isBusy && (
+ <form
+ id="invite-member-form"
+ className="space-y-4"
+ onSubmit={event => {
+ event.preventDefault();
+ if (!isBusy && (selected !== null || trimmedCode.length > 0)) {
+ void lookup();
+ }
+ }}
+ >
+ {/* Somebody verified before needs no code; picking them and entering a code exclude each other. */}
+ {people.length > 0 && (
+ <div className="space-y-2">
+ <h4 className="text-base font-medium text-gray-900 dark:text-white">{familySharingText.inviteWizardChooseTitle}</h4>
+ <ul className="space-y-2">
+ {people.map(person => {
+ const isSelected = selected?.userId === person.userId;
+ return (
+ <li key={person.userId}>
+ <button
+ type="button"
+ data-person-option={person.username}
+ disabled={person.problem !== null}
+ title={person.problem ?? undefined}
+ onClick={() => {
+ setSelected(isSelected ? null : person);
+ setCode('');
+ }}
+ className={`flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left text-sm transition-colors disabled:opacity-50 ${isSelected ? 'border-primary-500 bg-primary-50 text-gray-900 dark:bg-primary-500/10 dark:text-white' : 'border-gray-200 text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-200 dark:hover:bg-gray-700/50'}`}
+ >
+ <Icon name={isSelected ? 'check-circle' : 'users'} className={`h-5 w-5 shrink-0 ${isSelected ? 'text-primary-500' : 'text-gray-400'}`} />
+ <span className="truncate">{person.username}</span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ )}
+
+ <div className="space-y-3">
+ <h4 className="text-base font-medium text-gray-900 dark:text-white">{people.length > 0 ? familySharingText.inviteWizardNewCodeTitle : familySharingText.inviteWizardCodeTitle}</h4>
+ <p className="text-sm text-gray-500 dark:text-gray-400">{familySharingText.inviteWizardCodeHint}</p>
+ <input
+ id="invite-wizard-code"
+ type="text"
+ value={code}
+ onChange={event => {
+ setCode(event.target.value);
+ setSelected(null);
+ }}
+ placeholder={familySharingText.codePlaceholder}
+ autoFocus={people.length === 0}
+ className={INPUT_CLASS}
+ />
+ </div>
+ </form>
+ )}
+
+ {step === 2 && account && !isBusy && (
+ <div className="space-y-3">
+ <h4 className="text-base font-medium text-gray-900 dark:text-white">{familySharingText.inviteWizardConfirmTitle}</h4>
+ <p className="text-sm text-gray-600 dark:text-gray-300">{emphasized(sharesFolder ? familySharingText.inviteWizardConfirmShare(account.username, folderName) : familySharingText.inviteWizardConfirmFolder(account.username, folderName), account.username)}</p>
+ </div>
+ )}
+
+ {step === 3 && account && (
+ <div className="space-y-4">
+ <div className="flex items-center gap-2">
+ <Icon name="check-circle" className="w-6 h-6 shrink-0 text-green-600 dark:text-green-400" />
+ <h4 className="text-base font-medium text-gray-900 dark:text-white">{emphasized(familySharingText.inviteWizardInvited(account.username), account.username)}</h4>
+ </div>
+ {/* What is left to do: the invitee types this code to accept. */}
+ <div className="space-y-3 rounded-lg border border-gray-200 p-3 dark:border-gray-700">
+ <h5 className="text-sm font-semibold text-gray-900 dark:text-white">{familySharingText.inviteWizardNextStep}</h5>
+ <p className="text-sm text-gray-600 dark:text-gray-300">{emphasized(familySharingText.inviteWizardShareHint(account.username), account.username)}</p>
+ {ownCode && <FamilyCodeDisplay code={ownCode} />}
+ <p className="text-xs text-gray-500 dark:text-gray-400">{familySharingText.inviteWizardShareNotSecret}</p>
+ </div>
+ </div>
+ )}
+
+ {error && <p className="mt-3 text-sm text-red-600 dark:text-red-400">{error}</p>}
+ </ModalWrapper>
+ );
+};
+
+export default InviteMemberWizard;
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Sharing/SharedFolderAccessModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Sharing/SharedFolderAccessModal.tsx
new file mode 100644
index 000000000..013a2d38c
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/components/Sharing/SharedFolderAccessModal.tsx
@@ -0,0 +1,398 @@
+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 React, { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AlertMessage from '@/entrypoints/popup/components/AlertMessage';
+import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';
+import Icon from '@/entrypoints/popup/components/Icons/Icon';
+import InlineSpinner from '@/entrypoints/popup/components/InlineSpinner';
+import FamilyCodeDisplay from '@/entrypoints/popup/components/Sharing/FamilyCodeDisplay';
+import InviteMemberWizard, { type FamilyCodeAccount } from '@/entrypoints/popup/components/Sharing/InviteMemberWizard';
+import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
+import { usePasswordConfirmedAction } from '@/entrypoints/popup/hooks/usePasswordConfirmedAction';
+import { type SharedFolders } from '@/entrypoints/popup/hooks/useSharedFolders';
+import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
+import { SharingOperationError, sharingFailureMessage, unwrapSharingResult } from '@/entrypoints/popup/utils/SharingErrors';
+
+import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
+
+import type { Folder, FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';
+import type { GroupMemberInfo } from '@aliasvault/models/webapi';
+
+const PRIMARY_BUTTON_CLASS = 'px-3 py-1.5 text-sm rounded-md bg-primary-500 hover:bg-primary-600 disabled:opacity-50 text-white';
+const SMALL_DANGER_CLASS = 'shrink-0 px-2 py-1 text-xs rounded-md text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/30 disabled:opacity-50';
+const SMALL_NEUTRAL_CLASS = 'shrink-0 px-2 py-1 text-xs rounded-md text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50';
+
+type SharedFolderAccessModalProps = {
+ /** The top-level folder: a personal one (shared on the first invitation) or a shared one. */
+ folder: Pick<Folder, 'Id' | 'ManifestId' | 'Name'>;
+ /** Whether the folder is a shared one. */
+ isShared: boolean;
+ shared: SharedFolders;
+ /** Called once the folder became a shared one or a personal one again, with the folder it is shown as now. */
+ onMoved: (ref: FolderRef, isShared: boolean) => void;
+ /** Called once this account left the shared folder, which is gone from its vault. */
+ 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.
+ */
+const SharedFolderAccessModal: React.FC<SharedFolderAccessModalProps> = ({ folder, isShared, shared, onMoved, onLeft, onClose }) => {
+ const { t } = useTranslation();
+ const webApi = useWebApi();
+ const { loadStoredDatabase, getSqliteClient } = useDb();
+ const { executeVaultMutationLocally } = useVaultMutate();
+ const { askPassword, passwordModal } = 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);
+ /** 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 dialog 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);
+ // A personal folder can always be shared; a shared folder takes an admin holding its key (and its overview loaded).
+ const canInvite = isShared ? current !== null && canAdministerGroup(current.group) && holdsManifestKey(current.manifest, shared.myUserId) : true;
+
+ /**
+ * Sync with the server, throwing when the sync failed.
+ * @param failureMessage - the message to show when it failed.
+ */
+ const syncVault = async (failureMessage: string): Promise<void> => {
+ if (!(await sendMessage('FULL_VAULT_SYNC', {})).success) {
+ throw new SharingOperationError(failureMessage);
+ }
+ };
+
+ /**
+ * Run one action, showing its error in the dialog, 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);
+ };
+
+ /**
+ * Write one change into the open vault and push it, so the server has it before the next sharing call.
+ * @param operation - the change.
+ * @param failureMessage - the message to show when it could not be pushed.
+ */
+ const writeAndPush = async (operation: () => Promise<void>, failureMessage: string): Promise<void> => {
+ await executeVaultMutationLocally(operation);
+ await syncVault(failureMessage);
+ await loadStoredDatabase();
+ };
+
+ /**
+ * 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;
+ }
+ if (isShared) {
+ // A shared folder whose people have not loaded yet; never share it a second time.
+ throw new SharingOperationError(familySharingText.errors.inviteFailed);
+ }
+
+ // The background syncs the new shared folder to the server before it answers.
+ const result = unwrapSharingResult(await sendMessage('GROUP_CREATE_VAULT', { name: folder.Name }));
+ const manifestId = (result.manifestId ?? '').toLowerCase();
+
+ // The contents move into the reopened vault, which then holds the new shared folder.
+ await loadStoredDatabase();
+ await writeAndPush(async () => {
+ const client = getSqliteClient();
+ if (!client) {
+ throw new SharingOperationError(familySharingText.errors.createVaultFailed);
+ }
+ await client.folders.moveContentsToManifest({ Id: folder.Id, ManifestId: folder.ManifestId }, manifestId);
+ }, familySharingText.errors.createVaultFailed);
+
+ 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();
+ unwrapSharingResult(await sendMessage('GROUP_INVITE_MEMBER', { groupId: target.group.groupId, manifestId: target.manifest.manifestId, userId }));
+ await loadStoredDatabase();
+ 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 = unwrapSharingResult(await sendMessage('GROUP_LOOKUP_IDENTITY_CODE', { groupId: current?.group.groupId, identityCode: code }));
+ 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 = unwrapSharingResult(await sendMessage('GROUP_INVITE_MEMBER_BY_CODE', { groupId: target.group.groupId, manifestId: target.manifest.manifestId, identityCode: code }));
+ setInviteNotice(familySharingText.invitationSent(result.username ?? ''));
+ } catch (inviteError) {
+ throw new Error(sharingFailureMessage(inviteError, familySharingText.errors.inviteFailed));
+ } finally {
+ await shared.reload();
+ }
+ };
+
+ /**
+ * 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());
+ if (!latest || latest.group.role !== 'owner' || hasOtherPeople(latest, shared.myUserId) || !getSqliteClient()) {
+ return;
+ }
+
+ let personal: FolderRef | null = null;
+ await writeAndPush(async () => {
+ const client = getSqliteClient();
+ if (!client) {
+ throw new SharingOperationError(familySharingText.errors.revokeAccessFailed);
+ }
+ personal = await client.folders.moveManifestToNewFolder(manifestId, folder.Name);
+ }, familySharingText.errors.revokeAccessFailed);
+ await SharingService.unshareSharedManifest(webApi, latest.group.groupId, manifestId);
+ await syncVault(familySharingText.errors.revokeAccessFailed);
+ await loadStoredDatabase();
+ await shared.reload();
+ if (personal) {
+ onMoved(personal, false);
+ }
+ };
+
+ /**
+ * Show the spinner while a password confirmed action runs and syncs in; a refused password takes it away again.
+ * @param work - the action's work.
+ */
+ const withSpinner = async (work: () => Promise<void>): Promise<void> => {
+ setBusy(true);
+ try {
+ await work();
+ } catch (workError) {
+ setBusy(false);
+ throw workError;
+ }
+ };
+
+ /**
+ * Ask for confirmation, then for the master password, before taking a member's access away or handing back one's own.
+ * @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 => {
+ askPassword({
+ title: isSelf ? familySharingText.leaveVault : familySharingText.revoke,
+ confirmMessage: isSelf ? familySharingText.leaveVaultConfirm(folder.Name) : familySharingText.revokeAccessConfirm(member.username, folder.Name),
+ confirmText: isSelf ? familySharingText.leaveVault : familySharingText.revoke,
+ description: isSelf ? familySharingText.leaveVaultPasswordPrompt(folder.Name) : familySharingText.revokeAccessPasswordPrompt(member.username, folder.Name),
+ failureMessage: familySharingText.errors.revokeAccessFailed,
+ /**
+ * Run the action with the password proof.
+ * @param answerChallenge - answers the SRP challenge.
+ */
+ perform: answerChallenge => withSpinner(() => (isSelf
+ ? SharingService.leaveSharedManifest(webApi, target.group.groupId, target.manifest.manifestId, answerChallenge)
+ : SharingService.revokeAccess(webApi, target.group.groupId, target.manifest.manifestId, member.userId, answerChallenge))),
+ /**
+ * Sync the change in and leave the folder, which is gone for this account, when it was its own access.
+ */
+ onDone: async () => {
+ setError(null);
+ setNotice(null);
+ try {
+ await syncVault(familySharingText.errors.revokeAccessFailed);
+ await loadStoredDatabase();
+ if (!isSelf) {
+ // Taking the last other person out makes the folder personal again.
+ await revertIfEmpty(target.manifest.manifestId);
+ }
+ await shared.reload();
+ } catch (revertError) {
+ setError(sharingFailureMessage(revertError, familySharingText.errors.revokeAccessFailed));
+ } finally {
+ setBusy(false);
+ }
+ if (isSelf) {
+ onLeft();
+ }
+ },
+ });
+ };
+
+ /*
+ * 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 dialog shows it, never while the invite wizard runs.
+ */
+ const revertCheckedRef = useRef<string | null>(null);
+ const emptyOwnedManifestId = current && current.group.role === 'owner' && !hasOthers && !busy && !isInviteOpen ? 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]);
+
+ return (
+ <>
+ <ModalWrapper isOpen onClose={() => (isInviteOpen || busy ? undefined : onClose())} title={folder.Name} showCloseButton>
+ {/* While something runs (sharing, inviting, taking access away, making the folder personal) the content makes way for a spinner. */}
+ {busy && <InlineSpinner text={t('common.loading')} />}
+ <div className={`space-y-3 ${busy ? 'hidden' : ''}`}>
+ {error && <AlertMessage type="error" message={error} />}
+ {notice && <AlertMessage type="success" message={notice} />}
+
+ {!isShared && <p className="text-sm text-gray-600 dark:text-gray-400">{familySharingText.shareFolderHint}</p>}
+
+ {/* The people with access, with a + to invite more; only listed once anybody besides this account is in. */}
+ {current && hasOthers && (
+ <div>
+ <div className="mb-1 flex items-center justify-between gap-2">
+ <h4 className="text-sm font-medium text-gray-900 dark:text-white">{familySharingText.peopleTitle}</h4>
+ {canInvite && (
+ <button id="invite-someone-new" disabled={busy} onClick={() => setIsInviteOpen(true)} title={familySharingText.invitePeople} aria-label={familySharingText.invitePeople} className="p-1.5 rounded-md text-primary-600 hover:bg-primary-50 dark:text-primary-400 dark:hover:bg-primary-900/30 disabled:opacity-50">
+ <Icon name="plus" className="w-4 h-4" />
+ </button>
+ )}
+ </div>
+ <ul className="divide-y divide-gray-100 dark:divide-gray-700">
+ {current.group.members.map(member => {
+ const access = describeMemberAccess(current.group, current.manifest, member, shared.myUserId);
+ return (
+ <li key={member.userId} className="flex items-center justify-between gap-2 py-1.5" data-person={member.username}>
+ <div className="min-w-0">
+ <p className="text-sm text-gray-900 dark:text-white truncate">{member.username}{access.isSelf && ` (${familySharingText.you})`}</p>
+ <p className="text-xs text-gray-500 dark:text-gray-400">{roleLabel(member)}</p>
+ </div>
+ {access.canLeave && <button disabled={busy} onClick={() => removeAccess(current, member, true)} className={SMALL_DANGER_CLASS}>{familySharingText.leaveVault}</button>}
+ {access.canRevoke && <button disabled={busy} onClick={() => removeAccess(current, member, false)} className={SMALL_DANGER_CLASS}>{familySharingText.revoke}</button>}
+ </li>
+ );
+ })}
+ {canAdministerGroup(current.group) && pendingInvitees(current).map(invitation => (
+ <li key={invitation.id} className="flex items-center justify-between gap-2 py-1.5" data-person={invitation.inviteeUsername}>
+ <div className="min-w-0">
+ <p className="text-sm text-gray-900 dark:text-white truncate">{invitation.inviteeUsername}</p>
+ <p className="text-xs text-gray-500 dark:text-gray-400">{familySharingText.invited}</p>
+ </div>
+ <button
+ disabled={busy}
+ onClick={() => void run(async () => {
+ await SharingService.withdrawInvitation(webApi, invitation.id);
+ await revertIfEmpty(current.manifest.manifestId);
+ }, familySharingText.errors.invitationGone)}
+ className={SMALL_NEUTRAL_CLASS}
+ >
+ {familySharingText.withdraw}
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {/* 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 && (
+ <div className="space-y-1.5">
+ <p className="text-xs text-gray-500 dark:text-gray-400">{familySharingText.pendingCodeTip}</p>
+ <FamilyCodeDisplay code={shared.ownCode} isSmall />
+ </div>
+ )}
+
+ {/* Nobody else in yet (or still a personal folder): inviting is the one thing to do, so it is shown prominently. */}
+ {current && !hasOthers && <p className="text-sm text-gray-600 dark:text-gray-400">{familySharingText.notSharedYet}</p>}
+ {canInvite && !hasOthers && (
+ <button id="invite-someone-new" disabled={busy} onClick={() => setIsInviteOpen(true)} className={`${PRIMARY_BUTTON_CLASS} inline-flex items-center gap-1.5`}>
+ <Icon name="plus" className="w-4 h-4" />
+ {familySharingText.invitePeople}
+ </button>
+ )}
+ </div>
+ </ModalWrapper>
+
+ <InviteMemberWizard
+ isOpen={isInviteOpen}
+ sharesFolder={!isShared}
+ folderName={folder.Name}
+ ownCode={shared.ownCode}
+ people={invitable.map(person => ({ userId: person.userId, username: person.username, problem: memberKeyProblem(person) }))}
+ onLookup={lookup}
+ onInvite={inviteByCode}
+ onInvitePerson={inviteKnown}
+ onClose={() => {
+ setIsInviteOpen(false);
+ setNotice(inviteNotice);
+ setInviteNotice(null);
+ }}
+ />
+
+ {passwordModal}
+ </>
+ );
+};
+
+export default SharedFolderAccessModal;
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Sharing/SharedFolderInvitationModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Sharing/SharedFolderInvitationModal.tsx
new file mode 100644
index 000000000..402ddbfd9
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/components/Sharing/SharedFolderInvitationModal.tsx
@@ -0,0 +1,133 @@
+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 ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';
+import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
+import { sharingFailureMessage, unwrapSharingResult } from '@/entrypoints/popup/utils/SharingErrors';
+
+import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
+
+import type { ReceivedManifestInvitation } from '@aliasvault/models/webapi';
+
+const INPUT_CLASS = 'w-full p-2 text-sm border dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500';
+const PRIMARY_BUTTON_CLASS = 'px-3 py-1.5 text-sm rounded-md bg-primary-500 hover:bg-primary-600 disabled:opacity-50 text-white';
+const SECONDARY_BUTTON_CLASS = 'px-3 py-1.5 text-sm rounded-md bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 disabled:opacity-50 text-gray-700 dark:text-gray-300';
+
+type SharedFolderInvitationModalProps = {
+ invitation: ReceivedManifestInvitation | null;
+ folderName: string;
+ 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.
+ */
+const SharedFolderInvitationModal: React.FC<SharedFolderInvitationModalProps> = ({ invitation, folderName, onDone, onClose }) => {
+ const { t } = useTranslation();
+ 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(() => {
+ setAskCode(false);
+ setCode('');
+ setError(null);
+ }, [invitation?.id]);
+
+ 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 {
+ // The background syncs after accepting, which pulls the shared folder.
+ const result = await sendMessage('GROUP_ACCEPT_MANIFEST_INVITATION', { invitationId: invitation.id, identityCode: askCode ? code.trim() : undefined });
+ if (result.apiErrorCode === 'INVITER_NOT_VERIFIED') {
+ setAskCode(true);
+ }
+ unwrapSharingResult(result);
+ 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 footer = (
+ <div className="flex justify-end gap-2">
+ {!askCode && <button type="button" disabled={busy} onClick={() => void decline()} className={SECONDARY_BUTTON_CLASS}>{familySharingText.decline}</button>}
+ {askCode && <button type="button" disabled={busy} onClick={() => setAskCode(false)} className={SECONDARY_BUTTON_CLASS}>{t('common.back')}</button>}
+ <button id="accept-invitation" type="submit" form="shared-folder-invitation-form" disabled={busy || (askCode && code.trim().length === 0)} className={PRIMARY_BUTTON_CLASS}>{familySharingText.accept}</button>
+ </div>
+ );
+
+ return (
+ <ModalWrapper
+ isOpen
+ onClose={onClose}
+ title={askCode ? familySharingText.inviterCodeTitle(invitation.inviterUsername) : familySharingText.sharedWithYou(invitation.inviterUsername, folderName)}
+ footer={footer}
+ >
+ <form
+ id="shared-folder-invitation-form"
+ className="space-y-3"
+ onSubmit={event => {
+ event.preventDefault();
+ void accept();
+ }}
+ >
+ {!askCode && (
+ <>
+ <p className="text-sm text-gray-600 dark:text-gray-300">{familySharingText.sharedWithYouHint}</p>
+ <p className="text-sm text-gray-500 dark:text-gray-400">{isInviterVerified(invitation) ? familySharingText.invitedByVerified(invitation.inviterUsername) : familySharingText.invitedBy(invitation.inviterUsername)}</p>
+ </>
+ )}
+ {askCode && (
+ <>
+ <p className="text-sm text-gray-600 dark:text-gray-300">{familySharingText.inviterCodeExplanation(invitation.inviterUsername)}</p>
+ <input id="inviter-code" type="text" className={INPUT_CLASS} value={code} onChange={event => setCode(event.target.value)} placeholder={familySharingText.codePlaceholder} autoFocus />
+ </>
+ )}
+ {error && <p className="text-sm text-red-600 dark:text-red-400">{error}</p>}
+ </form>
+ </ModalWrapper>
+ );
+};
+
+export default SharedFolderInvitationModal;
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Sharing/SharedVaultModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Sharing/SharedVaultModal.tsx
deleted file mode 100644
index f1fa6a8d9..000000000
--- a/apps/browser-extension/src/entrypoints/popup/components/Sharing/SharedVaultModal.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-import { hasErrorCode, getErrorMessage } from '@aliasvault/client/api/errors/AppErrorCodes';
-import { familySharingText, MAX_SHARED_VAULT_NAME_LENGTH } from '@aliasvault/client/sharing/FamilySharingView';
-import React, { useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';
-
-import { logFailure } from '@/utils/Diagnostics';
-
-type SharedVaultModalProps = {
- isOpen: boolean;
- onClose: () => void;
- onSave: (name: string) => Promise<void>;
- initialName?: string;
- mode: 'create' | 'rename';
-};
-
-/**
- * Modal for creating or renaming a shared vault.
- */
-const SharedVaultModal: React.FC<SharedVaultModalProps> = ({ isOpen, onClose, onSave, initialName = '', mode }) => {
- const { t } = useTranslation();
- const [name, setName] = useState(initialName);
- const [isSubmitting, setIsSubmitting] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const trimmedName = name.trim();
-
- useEffect(() => {
- if (isOpen) {
- setName(initialName);
- setError(null);
- }
- }, [isOpen, initialName]);
-
- /**
- * Save the name and close.
- */
- const handleSubmit = async (e: React.FormEvent): Promise<void> => {
- e.preventDefault();
- if (!trimmedName || isSubmitting) {
- return;
- }
-
- setIsSubmitting(true);
- setError(null);
-
- try {
- await onSave(trimmedName);
- onClose();
- } catch (err) {
- setError(hasErrorCode(err) ? getErrorMessage(err, t('common.errors.unknownErrorTryAgain')) : t('common.errors.unknownErrorTryAgain'));
- logFailure('Error saving shared vault', err);
- } finally {
- setIsSubmitting(false);
- }
- };
-
- return (
- <ModalWrapper
- isOpen={isOpen}
- onClose={onClose}
- title={mode === 'create' ? familySharingText.createSharedVault : familySharingText.renameVault}
- footer={
- <div className="flex justify-end gap-3">
- <button
- type="button"
- onClick={onClose}
- disabled={isSubmitting}
- className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50"
- >
- {t('common.cancel')}
- </button>
- <button
- type="submit"
- form="shared-vault-form"
- disabled={isSubmitting || !trimmedName}
- className="px-4 py-2 text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 rounded focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50"
- >
- {isSubmitting ? t('common.saving') : mode === 'create' ? familySharingText.create : t('common.save')}
- </button>
- </div>
- }
- >
- <form id="shared-vault-form" onSubmit={handleSubmit}>
- <label htmlFor="sharedVaultName" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
- {familySharingText.vaultName}
- </label>
- <input
- id="sharedVaultName"
- type="text"
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder={familySharingText.vaultNamePlaceholder}
- maxLength={MAX_SHARED_VAULT_NAME_LENGTH}
- autoFocus
- className="w-full p-2 border dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
- />
- {error && <p className="mt-2 text-sm text-red-600 dark:text-red-400">{error}</p>}
- </form>
- </ModalWrapper>
- );
-};
-
-export default SharedVaultModal;
diff --git a/apps/browser-extension/src/entrypoints/popup/context/CapabilityContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/CapabilityContext.tsx
index 93300e0a6..33be90cf3 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/CapabilityContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/CapabilityContext.tsx
@@ -1,7 +1,6 @@
import { type Capabilities, CapabilityService } from '@aliasvault/client/api/CapabilityService';
import { type CapabilityKey, isCapabilityEnabled } from '@aliasvault/models/webapi';
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
-import { Navigate } from 'react-router-dom';
type CapabilityContextType = {
isEnabled: (key: CapabilityKey) => boolean;
@@ -44,26 +43,6 @@ export const useCapabilities = (): CapabilityContextType['isEnabled'] => {
return useCapabilityContext().isEnabled;
};
-/**
- * Renders a page only for accounts the capability is on for.
- * @param root0 - the capability to require and the page to render.
- * @param root0.capability - the capability the page needs.
- * @param root0.children - the page.
- */
-export const RequireCapability: React.FC<{ capability: CapabilityKey; children: React.ReactNode }> = ({ capability, children }) => {
- const { isEnabled, isLoaded } = useCapabilityContext();
-
- /*
- * Nothing is known before the stored capabilities are read, and redirecting on a guess would throw out a
- * legitimate deep link. The popup's loading state covers the moment this takes.
- */
- if (!isLoaded) {
- return null;
- }
-
- return isEnabled(capability) ? <>{children}</> : <Navigate to="/" replace />;
-};
-
/**
* The capabilities of this account.
*/
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index 532efa89b..330298711 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -51,6 +51,7 @@ type VaultMetadata = {
type DbContextType = {
sqliteClient: SqliteClient | null;
+ getSqliteClient: () => SqliteClient | null;
dbInitialized: boolean;
dbAvailable: boolean;
isOffline: boolean;
@@ -130,6 +131,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
* SQLite client.
*/
const [sqliteClient, setSqliteClient] = useState<SqliteClient | null>(null);
+ const sqliteClientRef = useRef<SqliteClient | null>(null);
/** Writes of this window still in progress; see runLocalVaultWrite. */
const localWritesInFlightRef = useRef(0);
@@ -258,6 +260,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
useEffect(() => {
return vaultStateEvents.onVaultLocked(() => {
clearEmailKeyCache();
+ sqliteClientRef.current = null;
setSqliteClient(null);
setDbAvailable(false);
});
@@ -303,6 +306,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
const client = new SqliteClient();
await client.initializeFromBytes(decryptedVault);
+ sqliteClientRef.current = client;
setSqliteClient(client);
setDbInitialized(true);
setDbAvailable(true);
@@ -432,6 +436,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
*/
const clearDatabase = useCallback(() : void => {
clearEmailKeyCache();
+ sqliteClientRef.current = null;
setSqliteClient(null);
setDbInitialized(false);
setDbAvailable(false);
@@ -441,9 +446,11 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
* Get offline state synchronously from ref.
*/
const getIsOffline = useCallback(() => isOfflineRef.current, []);
+ const getSqliteClient = useCallback(() => sqliteClientRef.current, []);
const contextValue = useMemo(() => ({
sqliteClient,
+ getSqliteClient,
dbInitialized,
dbAvailable,
isOffline,
@@ -466,7 +473,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
syncError,
clearSyncError,
runLocalVaultWrite,
- }), [sqliteClient, dbInitialized, dbAvailable, isOffline, getIsOffline, hasUnsyncedUserChanges, isSyncing, isUploading, setIsOffline, shouldSuppressEmailErrors, loadStoredDatabase, storeAccountKey, storeUnlockKeyDerivationParams, clearDatabase, getVaultMetadata, refreshSyncState, requiresLegacySqliteBlobMigration, requiresManifestMigration, syncError, clearSyncError, runLocalVaultWrite]);
+ }), [sqliteClient, getSqliteClient, dbInitialized, dbAvailable, isOffline, getIsOffline, hasUnsyncedUserChanges, isSyncing, isUploading, setIsOffline, shouldSuppressEmailErrors, loadStoredDatabase, storeAccountKey, storeUnlockKeyDerivationParams, clearDatabase, getVaultMetadata, refreshSyncState, requiresLegacySqliteBlobMigration, requiresManifestMigration, syncError, clearSyncError, runLocalVaultWrite]);
return (
<DbContext.Provider value={contextValue}>
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/usePasswordConfirmedAction.tsx b/apps/browser-extension/src/entrypoints/popup/hooks/usePasswordConfirmedAction.tsx
new file mode 100644
index 000000000..cbe7c16d2
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/usePasswordConfirmedAction.tsx
@@ -0,0 +1,91 @@
+import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
+import { MasterPasswordService } from '@aliasvault/client/auth/MasterPasswordService';
+import React, { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ConfirmDeleteModal from '@/entrypoints/popup/components/Dialogs/ConfirmDeleteModal';
+import ConfirmPasswordModal from '@/entrypoints/popup/components/Dialogs/ConfirmPasswordModal';
+import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
+import { sharingFailureMessage } from '@/entrypoints/popup/utils/SharingErrors';
+
+import type { SrpChallengeResponder } from '@aliasvault/client/sharing/SharingService';
+
+/**
+ * An action the user confirms first and the server then confirms with the master password.
+ */
+export type PasswordConfirmedAction = {
+ title: string;
+ /** The warning shown before the password is asked for. */
+ confirmMessage: string;
+ /** The text of both confirm buttons. */
+ confirmText: string;
+ /** The text next to the password field. */
+ description: string;
+ failureMessage: string;
+ /** Run the action, answering the server's SRP challenge with the entered password. */
+ perform: (answerChallenge: SrpChallengeResponder) => Promise<void>;
+ /** What follows once the action succeeded. */
+ onDone: () => Promise<void> | void;
+};
+
+/**
+ * A warning followed by a master password prompt for actions the server confirms with it. A wrong password keeps the prompt open.
+ * @returns `askPassword` to start the confirmation of an action, and the dialogs to render.
+ */
+export function usePasswordConfirmedAction(): { askPassword: (action: PasswordConfirmedAction) => void; passwordModal: React.ReactNode } {
+ const { t } = useTranslation();
+ const { showLoading, hideLoading } = useLoading();
+ const [pending, setPending] = useState<{ action: PasswordConfirmedAction; stage: 'confirm' | 'password' } | null>(null);
+
+ /**
+ * Start the confirmation of an action.
+ * @param action - the action to run once confirmed.
+ */
+ const askPassword = (action: PasswordConfirmedAction): void => setPending({ action, stage: 'confirm' });
+
+ /**
+ * Run the pending action with the entered master password; a thrown error keeps the prompt open with its message.
+ * @param password - the entered master password.
+ */
+ const run = async (password: string): Promise<void> => {
+ const action = pending?.action;
+ if (!action) {
+ return;
+ }
+
+ showLoading();
+ try {
+ await action.perform(async challenge => (await MasterPasswordService.answerSrpChallenge(challenge, password)).proof);
+ } catch (actionError) {
+ throw new Error(apiErrorCodeOf(actionError) === 'PASSWORD_MISMATCH' ? t('common.errors.wrongPassword') : sharingFailureMessage(actionError, action.failureMessage));
+ } finally {
+ hideLoading();
+ }
+
+ setPending(null);
+ await action.onDone();
+ };
+
+ const passwordModal = (
+ <>
+ <ConfirmDeleteModal
+ isOpen={pending?.stage === 'confirm'}
+ onClose={() => setPending(null)}
+ onConfirm={() => setPending(previous => (previous ? { ...previous, stage: 'password' } : previous))}
+ title={pending?.action.title ?? ''}
+ message={pending?.action.confirmMessage ?? ''}
+ confirmText={pending?.action.confirmText ?? ''}
+ />
+ <ConfirmPasswordModal
+ isOpen={pending?.stage === 'password'}
+ onClose={() => setPending(null)}
+ onConfirm={run}
+ title={pending?.action.title ?? ''}
+ message={pending?.action.description ?? ''}
+ confirmText={pending?.action.confirmText ?? ''}
+ />
+ </>
+ );
+
+ return { askPassword, passwordModal };
+}
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useSharedFolders.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useSharedFolders.ts
new file mode 100644
index 000000000..181c1e31b
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useSharedFolders.ts
@@ -0,0 +1,57 @@
+import { sharingView, type SharedFolder } from '@aliasvault/client/sharing/FamilySharingView';
+import { SharingService } from '@aliasvault/client/sharing/SharingService';
+import { CapabilityKeys } from '@aliasvault/models/webapi';
+import { useCallback, useEffect, useState } from 'react';
+
+import { useCapabilities } from '@/entrypoints/popup/context/CapabilityContext';
+import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
+
+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, again whenever a sync reports a different number of open
+ * invitations, 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));
+ setOwnCode(await SharingService.ownIdentityCode());
+ } catch {
+ // Offline or not reachable: the vault keeps showing what it already knew.
+ }
+ }, [isEnabled, webApi]);
+
+ useEffect(() => {
+ void reload();
+ return SharingService.watchPendingInvitationCount(() => void reload());
+ }, [reload]);
+
+ return { isEnabled, ...view, invitationNames, ownCode, reload };
+}
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
index 802baac8a..15b7282a2 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
@@ -42,6 +42,11 @@ export function useVaultMutate(): {
* @returns The scopes the operation wrote into
*/
const saveLocally = useCallback((operation: () => Promise<void>): Promise<VaultMutationScope[]> => dbContext.runLocalVaultWrite(async () => {
+ const sqliteClient = dbContext.getSqliteClient();
+ if (!sqliteClient) {
+ throw new Error('Vault is locked');
+ }
+
// Execute the provided operation (e.g. create/update/delete credential)
await operation();
@@ -50,12 +55,12 @@ export function useVaultMutate(): {
* only touched a bucket-scoped repository (e.g. 'Settings') lets the background sync push just that data
* bucket instead of the full vault manifest.
*/
- const scopes = dbContext.sqliteClient!.takeMutationScopes();
+ const scopes = sqliteClient.takeMutationScopes();
try {
// Export and encrypt the updated vault
const encryptionKey = await sendMessage('GET_ENCRYPTION_KEY') as string;
- const encryptedVaultBlob = await encryptVaultBlob(dbContext.sqliteClient!.exportToBytes(), encryptionKey);
+ const encryptedVaultBlob = await encryptVaultBlob(sqliteClient.exportToBytes(), encryptionKey);
// Store the updated vault locally, mark dirty, increment mutation sequence.
await storeEncryptedVault(encryptedVaultBlob, { markDirty: true, scopes });
@@ -65,7 +70,7 @@ export function useVaultMutate(): {
* reach storage carries it along. Put the scopes back, or that mutation could store the change under a
* bucket scope alone and a bucket-only push would leave it behind.
*/
- scopes.forEach(scope => dbContext.sqliteClient!.recordMutationScope(scope));
+ scopes.forEach(scope => sqliteClient.recordMutationScope(scope));
throw error;
}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
index 178b3b8e1..7d087b2a0 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
@@ -2,7 +2,9 @@ import { isSameItem, scopedKey } from '@aliasvault/client/database/ItemRef';
import { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
import { canHaveSubfolders, getDescendantFolderIds, getFolderPath, getRecursiveItemCount, isItemInFolder, 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 React, { useState, useEffect, useCallback, useDeferredValue, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
@@ -22,17 +24,24 @@ import ItemFilterDropdown from '@/entrypoints/popup/components/Items/ItemFilterD
import { ITEM_TYPE_OPTIONS } from '@/entrypoints/popup/components/Items/ItemTypeSelector';
import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';
import ReloadButton from '@/entrypoints/popup/components/ReloadButton';
+import SharedFolderAccessModal from '@/entrypoints/popup/components/Sharing/SharedFolderAccessModal';
+import SharedFolderInvitationModal from '@/entrypoints/popup/components/Sharing/SharedFolderInvitationModal';
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useHeaderButtons } from '@/entrypoints/popup/context/HeaderButtonsContext';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
+import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { useListKeyboardNav } from '@/entrypoints/popup/hooks/useListKeyboardNav';
+import { usePasswordConfirmedAction } from '@/entrypoints/popup/hooks/usePasswordConfirmedAction';
+import { useSharedFolders } from '@/entrypoints/popup/hooks/useSharedFolders';
import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
import { useVaultRefresh } from '@/entrypoints/popup/hooks/useVaultRefresh';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
+import { sharingFailureMessage, unwrapSharingResult } from '@/entrypoints/popup/utils/SharingErrors';
import { devLog } from '@/utils/devLogger/DevLogger';
import { itemRoute } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
+import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
@@ -148,6 +157,12 @@ const ItemsList: React.FC = () => {
const [showSortMenu, setShowSortMenu] = useState(false);
const [showFolders, setShowFolders] = useState(true);
const [visibleItemCount, setVisibleItemCount] = useState(ITEM_BATCH_SIZE);
+ /** The folder whose people dialog is open; kept while the folder turns into a shared one and the page moves to it. */
+ const [peopleFolder, setPeopleFolder] = useState<{ folder: Pick<Folder, 'Id' | 'ManifestId' | 'Name'>; isShared: boolean } | null>(null);
+ const [openInvitationId, setOpenInvitationId] = useState<string | null>(null);
+ const shared = useSharedFolders();
+ const webApi = useWebApi();
+ const { askPassword, passwordModal } = usePasswordConfirmedAction();
const { setIsInitialLoading } = useLoading();
const searchInputRef = useRef<HTMLInputElement | null>(null);
const sentinelRef = useRef<HTMLDivElement | null>(null);
@@ -191,8 +206,14 @@ const ItemsList: React.FC = () => {
return dbContext.sqliteClient.folders.getById(currentFolderRef);
}, [currentFolderRef, dbContext?.sqliteClient, folderRefreshKey]);
- // 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 currentFolderIsVirtual = currentFolder !== null && multiManifestRendering.isVirtualFolder(currentFolder);
+ const currentShared = currentFolder !== null && currentFolderIsVirtual ? shared.folders.find(folder => folder.manifest.manifestId.toLowerCase() === currentFolder.ManifestId.toLowerCase()) ?? null : null;
+ const canManageShared = currentShared !== null && canAdministerGroup(currentShared.group);
+ const canRenameCurrent = !currentFolderIsVirtual || (currentShared !== null && canManageShared && holdsManifestKey(currentShared.manifest, shared.myUserId));
+ const canDeleteCurrent = !currentFolderIsVirtual || canManageShared;
+ // A top-level personal folder can be shared; a subfolder cannot, as a shared folder is always a top-level one.
+ const canShareCurrent = shared.isEnabled && currentFolder !== null && (currentFolderIsVirtual || (currentFolder.ParentFolderId ?? null) === null);
// Get current folder's full path (for relative path computation in search results)
const currentFolderPath = useMemo(() => {
@@ -429,6 +450,80 @@ const ItemsList: React.FC = () => {
setShowEditFolderModal(false);
}, [dbContext, currentFolderRef, executeVaultMutationAsync]);
+ /**
+ * Sync, then reopen the stored vault so the folders show what changed on the server.
+ */
+ const syncAndReload = useCallback(async (): Promise<void> => {
+ await sendMessage('FULL_VAULT_SYNC', {});
+ await dbContext.loadStoredDatabase();
+ }, [dbContext]);
+
+ /**
+ * Rename the current shared folder: its name is encrypted with its key and kept on the server for every member.
+ * Throws so the rename modal shows the error.
+ */
+ const handleRenameSharedFolder = useCallback(async (name: string): Promise<void> => {
+ if (!currentShared) {
+ return;
+ }
+
+ try {
+ unwrapSharingResult(await sendMessage('GROUP_UPDATE_VAULT', { groupId: currentShared.group.groupId, manifestId: currentShared.manifest.manifestId, details: { name } }));
+ } catch (renameError) {
+ throw new Error(sharingFailureMessage(renameError, t('common.errors.unknownErrorTryAgain')));
+ }
+
+ await syncAndReload();
+ setFolderRefreshKey(prev => prev + 1);
+ await shared.reload();
+ }, [currentShared, syncAndReload, shared, t]);
+
+ /**
+ * Delete the current shared folder for everyone, after a confirmation and the master password.
+ */
+ const handleDeleteSharedFolder = (): void => {
+ if (!currentShared) {
+ return;
+ }
+
+ const name = currentFolderName ?? '';
+ askPassword({
+ title: familySharingText.deleteVault,
+ confirmMessage: familySharingText.deleteVaultConfirm(name),
+ confirmText: t('common.delete'),
+ description: familySharingText.deleteVaultPasswordPrompt(name),
+ failureMessage: familySharingText.errors.deleteVaultFailed,
+ /**
+ * Run the deletion with the password proof.
+ * @param answerChallenge - answers the SRP challenge.
+ */
+ perform: answerChallenge => SharingService.deleteSharedManifest(webApi, currentShared.group.groupId, currentShared.manifest.manifestId, answerChallenge),
+ /**
+ * Sync the deletion in and go to the vault's top level.
+ */
+ onDone: async () => {
+ await syncAndReload();
+ await shared.reload();
+ navigate('/items');
+ },
+ });
+ };
+
+ /**
+ * Finish an answered invitation: an accepted one is synced in (the background already synced) and opened.
+ * @param manifestId - the shared folder the invitation was for.
+ * @param accepted - whether it was accepted.
+ */
+ const finishInvitation = async (manifestId: string, accepted: boolean): Promise<void> => {
+ setOpenInvitationId(null);
+ if (accepted) {
+ await dbContext.loadStoredDatabase();
+ const id = manifestId.toLowerCase();
+ navigate(`/items/folder/${id}/${id}?filter=${encodeURIComponent(filterType)}`);
+ }
+ await shared.reload();
+ };
+
// Set header buttons on mount and clear on unmount
useEffect((): (() => void) => {
const headerButtonsJSX = (
@@ -814,6 +909,22 @@ const ItemsList: React.FC = () => {
}
}, [activeKind, activeIndex, visibleItems.length, hasMoreItems]);
+ /* Invitations to shared folders wait in the folder list at the top level until they are answered. */
+ const invitationPills = !currentFolderId && !searchTerm ? shared.invitations.map(invitation => (
+ <button
+ key={invitation.id}
+ data-invitation={invitation.id}
+ onClick={() => setOpenInvitationId(invitation.id)}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm border border-dashed border-primary-400 bg-primary-50/50 text-gray-500 hover:bg-primary-50 dark:border-primary-600 dark:bg-primary-900/10 dark:text-gray-400 dark:hover:bg-primary-900/20 transition-colors"
+ >
+ <Icon name="mail" className="w-3.5 h-3.5 text-primary-500" />
+ <span className="truncate max-w-[120px]">{shared.invitationNames[invitation.id] ?? familySharingText.sharedVault}</span>
+ <span className="text-xs text-primary-600 dark:text-primary-400">{familySharingText.invitationPending}</span>
+ </button>
+ )) : [];
+
+ const openInvitation = shared.invitations.find(candidate => candidate.id === openInvitationId) ?? null;
+
if (isLoading) {
return (
<div className="flex justify-center items-center p-8">
@@ -847,23 +958,37 @@ const ItemsList: React.FC = () => {
}}
onSelectRecentlyDeleted={() => navigate('/items/deleted')}
/>
- {/* Edit and Delete buttons, only for a folder the vault actually stores */}
- {currentFolderId && !currentFolderIsVirtual && (
+ {/* People, edit and delete buttons; a shared folder is managed through its shared manifest */}
+ {currentFolderId && currentFolder && (canShareCurrent || canRenameCurrent || canDeleteCurrent) && (
<div className="flex items-center gap-1 shrink-0">
- <button
- onClick={() => setShowEditFolderModal(true)}
- title={t('items.folders.editFolder')}
- className="p-1.5 text-gray-400 hover:text-primary-500 dark:text-gray-500 dark:hover:text-primary-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
- >
- <Icon name="pencil-alt" className="w-4 h-4" />
- </button>
- <button
- onClick={() => setShowDeleteFolderModal(true)}
- title={t('items.folders.deleteFolder')}
- className="p-1.5 text-gray-400 hover:text-red-500 dark:text-gray-500 dark:hover:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
- >
- <Icon name="trash" className="w-4 h-4" strokeWidth={1} />
- </button>
+ {canShareCurrent && (
+ <button
+ id="folder-people"
+ onClick={() => setPeopleFolder({ folder: currentFolder, isShared: currentFolderIsVirtual })}
+ title={familySharingText.peopleTitle}
+ className="p-1.5 text-gray-400 hover:text-primary-500 dark:text-gray-500 dark:hover:text-primary-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
+ >
+ <Icon name="users" className="w-4 h-4" />
+ </button>
+ )}
+ {canRenameCurrent && (
+ <button
+ onClick={() => setShowEditFolderModal(true)}
+ title={t('items.folders.editFolder')}
+ className="p-1.5 text-gray-400 hover:text-primary-500 dark:text-gray-500 dark:hover:text-primary-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
+ >
+ <Icon name="pencil-alt" className="w-4 h-4" />
+ </button>
+ )}
+ {canDeleteCurrent && (
+ <button
+ onClick={() => (currentFolderIsVirtual ? handleDeleteSharedFolder() : setShowDeleteFolderModal(true))}
+ title={t('items.folders.deleteFolder')}
+ className="p-1.5 text-gray-400 hover:text-red-500 dark:text-gray-500 dark:hover:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
+ >
+ <Icon name="trash" className="w-4 h-4" strokeWidth={1} />
+ </button>
+ )}
</div>
)}
</div>
@@ -945,6 +1070,7 @@ const ItemsList: React.FC = () => {
{items.length === 0 ? (
<>
+ {invitationPills.length > 0 && <div className="flex flex-wrap items-center gap-2 mb-4">{invitationPills}</div>}
<div className="text-gray-500 dark:text-gray-400 space-y-2 mb-10">
<p>
{t('items.welcomeTitle')}
@@ -1016,6 +1142,7 @@ const ItemsList: React.FC = () => {
isShared={folder.isShared}
/>
))}
+ {invitationPills}
{canCreateSubfolder && (
<button
onClick={handleAddFolder}
@@ -1049,6 +1176,7 @@ const ItemsList: React.FC = () => {
isShared={folder.isShared}
/>
))}
+ {invitationPills}
{canCreateSubfolder && (
<button
onClick={handleAddFolder}
@@ -1148,13 +1276,14 @@ const ItemsList: React.FC = () => {
mode="create"
/>
- {/* Edit Folder Modal */}
+ {/* Edit Folder Modal; 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={currentFolderIsVirtual ? handleRenameSharedFolder : handleEditFolder}
initialName={currentFolderName || ''}
mode="edit"
+ maxLength={currentFolderIsVirtual ? MAX_SHARED_VAULT_NAME_LENGTH : undefined}
/>
{/* Delete Folder Modal */}
@@ -1165,6 +1294,35 @@ const ItemsList: React.FC = () => {
onDeleteFolderAndContents={handleDeleteFolderAndContents}
itemCount={totalItemCountInFolderTree}
/>
+
+ {peopleFolder && (
+ <SharedFolderAccessModal
+ folder={peopleFolder.folder}
+ isShared={peopleFolder.isShared}
+ shared={shared}
+ onMoved={(ref, isShared) => {
+ setPeopleFolder(open => (open ? { folder: { ...open.folder, Id: ref.Id, ManifestId: ref.ManifestId }, isShared } : null));
+ // The contents moved inside the open vault, which does not reload the list by itself.
+ setItems(dbContext.getSqliteClient()?.items.getAll() ?? []);
+ setFolderRefreshKey(prev => prev + 1);
+ navigate(`/items/folder/${ref.ManifestId}/${ref.Id}?filter=${encodeURIComponent(filterType)}`);
+ }}
+ onLeft={() => {
+ setPeopleFolder(null);
+ navigate('/items');
+ }}
+ onClose={() => setPeopleFolder(null)}
+ />
+ )}
+
+ <SharedFolderInvitationModal
+ invitation={openInvitation}
+ folderName={openInvitation ? shared.invitationNames[openInvitation.id] ?? familySharingText.sharedVault : ''}
+ onDone={accepted => (openInvitation ? finishInvitation(openInvitation.manifestId, accepted) : Promise.resolve())}
+ onClose={() => setOpenInvitationId(null)}
+ />
+
+ {passwordModal}
</div>
);
};
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/FamilySharingSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/FamilySharingSettings.tsx
deleted file mode 100644
index 377544a84..000000000
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/FamilySharingSettings.tsx
+++ /dev/null
@@ -1,623 +0,0 @@
-import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
-import { MasterPasswordService } from '@aliasvault/client/auth/MasterPasswordService';
-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 React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
-
-import AlertMessage from '@/entrypoints/popup/components/AlertMessage';
-import ConfirmDeleteModal from '@/entrypoints/popup/components/Dialogs/ConfirmDeleteModal';
-import ConfirmPasswordModal from '@/entrypoints/popup/components/Dialogs/ConfirmPasswordModal';
-import FolderIcon from '@/entrypoints/popup/components/Folders/FolderIcon';
-import { HeaderIcon, HeaderIconType } from '@/entrypoints/popup/components/Icons/HeaderIcons';
-import Icon from '@/entrypoints/popup/components/Icons/Icon';
-import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';
-import PageTitle from '@/entrypoints/popup/components/PageTitle';
-import ReloadButton from '@/entrypoints/popup/components/ReloadButton';
-import SharedVaultModal from '@/entrypoints/popup/components/Sharing/SharedVaultModal';
-import { useApp } from '@/entrypoints/popup/context/AppContext';
-import { useDb } from '@/entrypoints/popup/context/DbContext';
-import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
-import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
-
-import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
-
-import type { GroupInfo, GroupMemberInfo, GroupOverviewResponse, SharedManifestInfo } from '@aliasvault/models/webapi';
-
-/**
- * The access removal the confirmation dialog is about.
- */
-type PendingRemoval = { group: GroupInfo; manifest: SharedManifestInfo; member: GroupMemberInfo; isSelf: boolean };
-
-/**
- * A shared manifest deletion in progress: first a plain warning, then the master password confirmation.
- */
-type PendingVaultDelete = { group: GroupInfo; manifest: SharedManifestInfo; stage: 'confirm' | 'password' };
-
-/** A failure the background script already put into words for the user. */
-class BackgroundActionError extends Error {}
-
-/** A failure the background script reported as a bare API error code. */
-class BackgroundApiError extends Error {}
-
-/**
- * Family sharing settings page: create a family's shared manifests, invite the members of that family to them, and
- * answer the invitations others sent.
- */
-const FamilySharingSettings: React.FC = () => {
- const { t } = useTranslation();
- const navigate = useNavigate();
- const app = useApp();
- const webApi = useWebApi();
- const { sqliteClient, loadStoredDatabase } = useDb();
- const { setIsInitialLoading, showLoading, hideLoading } = useLoading();
- const [isLoading, setIsLoading] = useState(true);
- const hasLoadedRef = useRef(false);
-
- const [overview, setOverview] = useState<GroupOverviewResponse | null>(null);
- const [error, setError] = useState<string | null>(null);
- const [notice, setNotice] = useState<string | null>(null);
- const [busy, setBusy] = useState(false);
- const [pendingVaultCreate, setPendingVaultCreate] = useState<GroupInfo | null>(null);
- const vaultNames = useMemo<Record<string, string>>(() => (sqliteClient ? multiManifestRendering.displayNames(sqliteClient) : {}), [sqliteClient]);
- const [pendingRemoval, setPendingRemoval] = useState<PendingRemoval | null>(null);
- const [pendingVaultDelete, setPendingVaultDelete] = useState<PendingVaultDelete | null>(null);
- const [expandedRosters, setExpandedRosters] = useState<Record<string, boolean>>({});
- const [openVaultMenuId, setOpenVaultMenuId] = useState<string | null>(null);
- const [pendingVaultRename, setPendingVaultRename] = useState<{ group: GroupInfo; manifest: SharedManifestInfo } | null>(null);
- const [invitationNames, setInvitationNames] = useState<Record<string, string>>({});
-
- const loadOverview = useCallback(async (): Promise<void> => {
- try {
- const loaded = await SharingService.getOverview(webApi);
- setOverview(loaded);
- setInvitationNames(await SharingService.openInvitationNames(loaded.receivedInvitations));
- setError(null);
- } catch {
- setError(familySharingText.errors.loadFailed);
- } finally {
- setIsInitialLoading(false);
- }
- }, [webApi, setIsInitialLoading]);
-
- useEffect(() => {
- loadOverview().then(() => {
- if (!hasLoadedRef.current) {
- hasLoadedRef.current = true;
- setIsLoading(false);
- }
- });
- }, [loadOverview, setIsLoading]);
-
- /**
- * Sync the vault and reload the overview, to pick up what other family members changed.
- */
- const refresh = useCallback(async (): Promise<void> => {
- setIsLoading(true);
- try {
- await sendMessage('FULL_VAULT_SYNC', {});
- await loadStoredDatabase();
- await loadOverview();
- } finally {
- setIsLoading(false);
- }
- }, [loadStoredDatabase, loadOverview, setIsLoading]);
-
- /**
- * Run one action.
- * @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);
- };
-
- /**
- * 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 BackgroundActionError) {
- // The background script says why in the user's own language; that reason beats anything this page could guess.
- return actionError.message.length > 0 ? actionError.message : fallback;
- }
-
- const code = actionError instanceof BackgroundApiError ? actionError.message : apiErrorCodeOf(actionError);
-
- const knownError = sharingErrorMessage(code);
- if (knownError) {
- return knownError;
- }
-
- return code !== null ? `${fallback} [${code}]` : fallback;
- };
-
- /**
- * Send one background message and turn a failure into the error the screen knows how to report.
- * @param result - what the background script answered.
- */
- const unwrap = (result: { success: boolean; error?: string; apiErrorCode?: string }): void => {
- if (result.success) {
- return;
- }
-
- throw result.apiErrorCode ? new BackgroundApiError(result.apiErrorCode) : new BackgroundActionError(result.error ?? '');
- };
-
- /**
- * Create another shared manifest for the family picked in the create modal.
- * @param name - the new vault's name.
- */
- const createSharedVault = (name: string): Promise<void> => {
- const group = pendingVaultCreate;
- if (!group) {
- return Promise.resolve();
- }
-
- return run(async () => {
- unwrap(await sendMessage('GROUP_CREATE_VAULT', { groupId: group.groupId, name }));
- await loadStoredDatabase();
- }, familySharingText.errors.createVaultFailed);
- };
-
- /**
- * Rename a shared manifest, which only an administrator of the family may do.
- * @param name - the new name.
- */
- const renameSharedVault = async (name: string): Promise<void> => {
- if (!pendingVaultRename) {
- return;
- }
-
- unwrap(await sendMessage('GROUP_UPDATE_VAULT', { groupId: pendingVaultRename.group.groupId, manifestId: pendingVaultRename.manifest.manifestId, details: { name } }));
- await loadStoredDatabase();
- };
-
- /**
- * Invite one member to one shared manifest.
- * @param group - the family the vault belongs to.
- * @param manifest - the vault.
- * @param member - the member being invited.
- */
- const inviteMember = (group: GroupInfo, manifest: SharedManifestInfo, member: GroupMemberInfo): Promise<void> => run(async () => {
- unwrap(await sendMessage('GROUP_INVITE_MEMBER', { groupId: group.groupId, manifestId: manifest.manifestId, userId: member.userId }));
- await loadStoredDatabase();
- setNotice(familySharingText.invitationSent(member.username));
- }, familySharingText.errors.inviteFailed);
-
- /**
- * Accept an invitation, opening the shared manifest it names.
- * @param invitationId - the invitation to accept.
- */
- const acceptInvitation = (invitationId: string): Promise<void> => run(async () => {
- await SharingService.acceptInvitation(webApi, invitationId);
- await sendMessage('FULL_VAULT_SYNC', {});
- // Same as creating one: the sync wrote the joined vault to storage, and this window has to pick it up to render it.
- await loadStoredDatabase();
- }, familySharingText.errors.invitationGone);
-
- /**
- * Carry out the access removal the confirmation dialog was about.
- */
- const confirmRemoval = (): Promise<void> => {
- const removal = pendingRemoval;
- setPendingRemoval(null);
- if (!removal) {
- return Promise.resolve();
- }
-
- return run(async () => {
- unwrap(await sendMessage('GROUP_REVOKE_ACCESS', { groupId: removal.group.groupId, manifestId: removal.manifest.manifestId, userId: removal.member.userId }));
- await loadStoredDatabase();
- }, familySharingText.errors.revokeAccessFailed);
- };
-
- /**
- * Delete a shared manifest with password confirmation.
- * @param password - the entered master password.
- */
- const deleteSharedVault = async (password: string): Promise<void> => {
- const target = pendingVaultDelete;
- if (!target) {
- return;
- }
-
- showLoading();
- try {
- await SharingService.deleteSharedManifest(webApi, target.group.groupId, target.manifest.manifestId, async challenge => (await MasterPasswordService.answerSrpChallenge(challenge, password)).proof);
- } catch (deleteError) {
- if (apiErrorCodeOf(deleteError) === 'PASSWORD_MISMATCH') {
- throw new Error(t('common.errors.wrongPassword'));
- }
-
- throw new Error(apiErrorMessage(deleteError, familySharingText.errors.deleteVaultFailed));
- } finally {
- hideLoading();
- }
-
- setPendingVaultDelete(null);
- await run(async () => {
- await sendMessage('FULL_VAULT_SYNC', {});
- await loadStoredDatabase();
- setNotice(familySharingText.vaultDeleted);
- }, familySharingText.errors.deleteVaultFailed);
- };
-
- /**
- * Whether a family's roster is expanded.
- * @param groupId - the family.
- */
- const isRosterExpanded = (groupId: string): boolean => expandedRosters[groupId] ?? false;
-
- /**
- * Toggle a family's roster open or shut.
- * @param groupId - the family.
- */
- const toggleRoster = (groupId: string): void => setExpandedRosters(previous => ({ ...previous, [groupId]: !isRosterExpanded(groupId) }));
-
- /**
- * What to call a shared manifest on screen.
- * @param manifest - the vault.
- */
- const vaultLabel = (manifest: SharedManifestInfo): string => vaultNames[manifest.manifestId.toLowerCase()] ?? familySharingText.sharedVault;
-
- /**
- * The title and message of the confirmation dialog.
- */
- const removalDialog = (): { title: string; message: string; confirmText: string; warning?: string } => {
- if (!pendingRemoval) {
- return { title: '', message: '', confirmText: familySharingText.revoke };
- }
-
- if (pendingRemoval.isSelf) {
- return {
- title: familySharingText.leaveVault,
- message: familySharingText.leaveVaultConfirm(vaultLabel(pendingRemoval.manifest)),
- confirmText: familySharingText.leaveVault,
- };
- }
-
- return {
- title: familySharingText.revoke,
- message: familySharingText.revokeAccessConfirm(pendingRemoval.member.username, vaultLabel(pendingRemoval.manifest)),
- confirmText: familySharingText.revoke,
- warning: familySharingText.revokeAccessWarning,
- };
- };
-
- const receivedInvitations = overview?.receivedInvitations ?? [];
- const groups = overview?.groups ?? [];
- const dialog = removalDialog();
-
- if (isLoading) {
- return (
- <div className="flex justify-center items-center p-8">
- <LoadingSpinner />
- </div>
- );
- }
-
- return (
- <div className="space-y-4">
- <ConfirmDeleteModal
- isOpen={pendingRemoval !== null}
- onClose={() => setPendingRemoval(null)}
- onConfirm={confirmRemoval}
- title={dialog.title}
- message={dialog.message}
- confirmText={dialog.confirmText}
- warning={dialog.warning}
- />
-
- <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"
- />
-
- <ConfirmDeleteModal
- isOpen={pendingVaultDelete?.stage === 'confirm'}
- onClose={() => setPendingVaultDelete(null)}
- onConfirm={() => setPendingVaultDelete(previous => (previous ? { ...previous, stage: 'password' } : previous))}
- title={familySharingText.deleteVault}
- message={familySharingText.deleteVaultConfirm(pendingVaultDelete ? vaultLabel(pendingVaultDelete.manifest) : '')}
- confirmText={t('common.delete')}
- />
-
- <ConfirmPasswordModal
- isOpen={pendingVaultDelete?.stage === 'password'}
- onClose={() => setPendingVaultDelete(null)}
- onConfirm={deleteSharedVault}
- title={familySharingText.deleteVault}
- message={familySharingText.deleteVaultPasswordPrompt(pendingVaultDelete ? vaultLabel(pendingVaultDelete.manifest) : '')}
- confirmText={t('common.delete')}
- />
-
- <div>
- <div className="flex justify-between items-center">
- <div className="flex items-center gap-2">
- <PageTitle>{familySharingText.title}</PageTitle>
- <span className="px-2 py-0.5 text-xs font-semibold rounded-full bg-primary-100 dark:bg-primary-900 text-primary-700 dark:text-primary-300 uppercase tracking-wide">
- {familySharingText.beta}
- </span>
- </div>
- <ReloadButton onClick={() => void refresh()} />
- </div>
- <p className="text-sm text-gray-600 dark:text-gray-400">{familySharingText.description}</p>
- </div>
-
- {error && <AlertMessage type="error" message={error} />}
- {notice && <AlertMessage type="success" message={notice} />}
-
- {receivedInvitations.length > 0 && (
- <section>
- <h3 className="text-md font-semibold text-gray-900 dark:text-white mb-2">{familySharingText.invitations}</h3>
- <div className="space-y-2">
- {receivedInvitations.map(invitation => (
- <div key={invitation.id} className="p-3 space-y-2 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-primary-400 dark:border-primary-500 ring-2 ring-primary-200 dark:ring-primary-900/60">
- <div className="flex items-center gap-2 min-w-0">
- <FolderIcon isShared className="w-4 h-4 text-primary-500 dark:text-primary-400" />
- <div className="min-w-0">
- <p className="font-medium text-gray-900 dark:text-white truncate">{invitationNames[invitation.id] ?? familySharingText.sharedVault}</p>
- <p className="text-sm text-gray-500 dark:text-gray-400">{familySharingText.invitedBy(invitation.inviterUsername)}</p>
- </div>
- </div>
- <div className="flex gap-2">
- <button
- disabled={busy}
- onClick={() => acceptInvitation(invitation.id)}
- className="px-3 py-1.5 text-sm rounded-md bg-primary-500 hover:bg-primary-600 disabled:opacity-50 text-white"
- >
- {familySharingText.accept}
- </button>
- <button
- disabled={busy}
- onClick={() => run(() => SharingService.declineInvitation(webApi, invitation.id), familySharingText.errors.invitationGone)}
- className="px-3 py-1.5 text-sm rounded-md bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 disabled:opacity-50 text-gray-700 dark:text-gray-300"
- >
- {familySharingText.decline}
- </button>
- </div>
- </div>
- ))}
- </div>
- </section>
- )}
-
- {groups.length === 0 && receivedInvitations.length === 0 && (
- <AlertMessage type="info" message={familySharingText.notAvailable} />
- )}
-
- {groups.map(group => {
- const canAdminister = canAdministerGroup(group);
- const myUserId = ownUserIdIn(group, app.username);
-
- return (
- <section key={group.groupId} className="space-y-3">
- {/* The family's members. */}
- <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-3">
- <button onClick={() => toggleRoster(group.groupId)} className="flex items-center justify-between w-full text-left">
- <span className="font-medium text-gray-900 dark:text-white">{familySharingText.members} ({group.members.length})</span>
- <Icon name="chevron-down" className={`w-5 h-5 text-gray-500 transition-transform ${isRosterExpanded(group.groupId) ? 'rotate-180' : ''}`} />
- </button>
-
- {isRosterExpanded(group.groupId) && (
- <div className="mt-2 space-y-2">
- <ul className="divide-y divide-gray-100 dark:divide-gray-700">
- {group.members.map(member => {
- const isSelf = member.userId === myUserId;
-
- return (
- <li key={member.userId} className="flex items-center justify-between gap-2 py-1.5 first:pt-0 last:pb-0">
- <div className="min-w-0">
- <p className="text-sm text-gray-900 dark:text-white truncate">
- {member.username}{isSelf && ` (${familySharingText.you})`}
- </p>
- <p className="text-xs text-gray-500 dark:text-gray-400">{roleLabel(member)}</p>
- </div>
- </li>
- );
- })}
- </ul>
- </div>
- )}
- </div>
-
- {/* One block per shared manifest, each with the members who can open it. */}
- {group.manifests.length > 0 && (
- <div className="space-y-2">
- <h3 className="text-md font-semibold text-gray-900 dark:text-white">{familySharingText.sharedVaults}</h3>
- {group.manifests.map(manifest => {
- const iHoldKey = holdsManifestKey(manifest, myUserId);
- // The shared manifest's folder exists in this vault once the manifest itself does.
- const folderId = manifest.manifestId.toLowerCase();
- const hasFolder = vaultNames[folderId] !== undefined;
-
- return (
- <div key={manifest.manifestId} className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-3 space-y-2">
- <div className="flex items-center justify-between gap-2 -mx-1.5 -mt-1.5">
- {hasFolder ? (
- <button onClick={() => navigate(`/items/folder/${folderId}/${folderId}`)} className="flex flex-1 items-center gap-2 min-w-0 px-1.5 py-1 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
- <FolderIcon isShared className="w-4 h-4 text-primary-500 dark:text-primary-400" />
- <span className="font-medium text-gray-900 dark:text-white truncate">{vaultLabel(manifest)}</span>
- <Icon name="chevron-right" className="w-4 h-4 ml-auto shrink-0 text-gray-400" />
- </button>
- ) : (
- <div className="flex flex-1 items-center gap-2 min-w-0 px-1.5 py-1">
- <FolderIcon isShared className="w-4 h-4 text-primary-500 dark:text-primary-400" />
- <span className="font-medium text-gray-900 dark:text-white truncate">{vaultLabel(manifest)}</span>
- </div>
- )}
- {/* Deleting a shared manifest is hidden behind a settings gear icon menu. */}
- {canAdminister && (
- <div className="relative shrink-0">
- <button
- disabled={busy}
- onClick={() => setOpenVaultMenuId(previous => (previous === manifest.manifestId ? null : manifest.manifestId))}
- title={t('common.settings')}
- aria-label={t('common.settings')}
- className="p-1 rounded-md text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
- >
- <HeaderIcon type={HeaderIconType.SETTINGS} className="w-4 h-4" />
- </button>
-
- {openVaultMenuId === manifest.manifestId && (
- <>
- <div className="fixed inset-0 z-10" onClick={() => setOpenVaultMenuId(null)} />
- <div className="absolute right-0 top-full mt-1 w-44 py-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-xl z-20">
- {/* Renaming encrypts the name with the vault's key, so it takes a member who holds it. */}
- {iHoldKey && (
- <button
- onClick={() => {
- setOpenVaultMenuId(null);
- setPendingVaultRename({ group, manifest });
- }}
- className="w-full px-3 py-2 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
- >
- {t('items.folders.editFolder')}
- </button>
- )}
- <button
- onClick={() => {
- setOpenVaultMenuId(null);
- setPendingVaultDelete({ group, manifest, stage: 'confirm' });
- }}
- className="w-full px-3 py-2 text-left text-sm text-red-600 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700"
- >
- {familySharingText.deleteVault}
- </button>
- </div>
- </>
- )}
- </div>
- )}
- </div>
-
- {/* Inviting somebody encrypts this vault's key for them, which an admin who holds no grant on it cannot do. */}
- {canAdminister && !iHoldKey && (
- <p className="text-xs text-gray-500 dark:text-gray-400">{familySharingText.cannotInviteWithoutAccess}</p>
- )}
-
- <ul className="divide-y divide-gray-100 dark:divide-gray-700">
- {group.members.map(member => {
- const access = describeMemberAccess(group, manifest, member, myUserId);
- const { isSelf, invitation } = access;
-
- return (
- <li key={member.userId} className="flex items-center justify-between gap-2 py-1.5 first:pt-0 last:pb-0">
- <div className="min-w-0">
- <p className="text-sm text-gray-900 dark:text-white truncate">
- {member.username}{isSelf && ` (${familySharingText.you})`}
- </p>
- <p className="text-xs text-gray-500 dark:text-gray-400">
- {access.statusText}
- </p>
- </div>
-
- {access.canLeave && (
- <button
- disabled={busy}
- onClick={() => setPendingRemoval({ group, manifest, member, isSelf })}
- className="shrink-0 px-2 py-1 text-xs rounded-md text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/30 disabled:opacity-50"
- >
- {familySharingText.leaveVault}
- </button>
- )}
-
- {access.canRevoke && (
- <button
- disabled={busy}
- onClick={() => setPendingRemoval({ group, manifest, member, isSelf })}
- className="shrink-0 px-2 py-1 text-xs rounded-md text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/30 disabled:opacity-50"
- >
- {familySharingText.revoke}
- </button>
- )}
-
- {access.canWithdraw && invitation && (
- <button
- disabled={busy}
- onClick={() => run(() => SharingService.withdrawInvitation(webApi, invitation.id), familySharingText.errors.invitationGone)}
- className="shrink-0 px-2 py-1 text-xs rounded-md text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
- >
- {familySharingText.withdraw}
- </button>
- )}
-
- {access.canInvite && (
- <button
- disabled={busy || !access.isReadyForInvite}
- title={access.isReadyForInvite ? undefined : familySharingText.errors.userNotReady}
- onClick={() => inviteMember(group, manifest, member)}
- className="shrink-0 px-2 py-1 text-xs rounded-md bg-primary-500 hover:bg-primary-600 disabled:opacity-50 text-white"
- >
- {familySharingText.invite}
- </button>
- )}
- </li>
- );
- })}
- </ul>
- </div>
- );
- })}
- </div>
- )}
-
- {group.manifests.length === 0 && (
- <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-3">
- <p className="text-sm text-gray-600 dark:text-gray-400">
- {canAdminister ? familySharingText.noSharedVaultAdmin : familySharingText.noSharedVaultMember}
- </p>
- </div>
- )}
-
- {/* Creating another shared manifest. */}
- {canAdminister && (
- <button
- type="button"
- disabled={busy}
- onClick={() => setPendingVaultCreate(group)}
- className="w-full px-4 py-2 border-2 border-dashed border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 rounded-md hover:border-primary-500 hover:text-primary-600 dark:hover:text-primary-400 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
- >
- <Icon name="plus-sm" className="w-5 h-5" />
- <span className="text-sm font-medium">{familySharingText.createSharedVault}</span>
- </button>
- )}
- </section>
- );
- })}
- </div>
- );
-};
-
-export default FamilySharingSettings;
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx
index 277d8f38f..20ba96961 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx
@@ -1,5 +1,6 @@
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
+import { SharingService } from '@aliasvault/client/sharing/SharingService';
import { CapabilityKeys } from '@aliasvault/models/webapi';
import React, { useEffect, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,6 +12,7 @@ import { HeaderIconType } from '@/entrypoints/popup/components/Icons/HeaderIcons
import Icon from '@/entrypoints/popup/components/Icons/Icon';
import PageTitle from '@/entrypoints/popup/components/PageTitle';
import { SettingsGroup, SettingsRow } from '@/entrypoints/popup/components/Settings/SettingsMenu';
+import FamilyCodeDisplay from '@/entrypoints/popup/components/Sharing/FamilyCodeDisplay';
import { useApp } from '@/entrypoints/popup/context/AppContext';
import { useAuth } from '@/entrypoints/popup/context/AuthContext';
import { useCapabilities } from '@/entrypoints/popup/context/CapabilityContext';
@@ -41,6 +43,11 @@ const Settings: React.FC = () => {
const navigate = useNavigate();
const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);
const [serverVersion, setServerVersion] = useState<string | null>(null);
+ const [ownSharingCode, setOwnSharingCode] = useState<string | null>(null);
+
+ useEffect(() => {
+ void SharingService.ownIdentityCode().then(setOwnSharingCode);
+ }, []);
/**
* Open the client tab.
@@ -222,13 +229,12 @@ const Settings: React.FC = () => {
</div>
</div>
</div>
- {hasCapability(CapabilityKeys.VaultSharing) && (
- <SettingsRow
- label={familySharingText.title}
- badge={familySharingText.beta}
- onClick={() => navigate('/settings/family-sharing')}
- icon="user-group"
- />
+ {/* The code someone who shares a folder with this account needs to invite it. */}
+ {hasCapability(CapabilityKeys.VaultSharing) && ownSharingCode && (
+ <div className="flex flex-col gap-2 p-4">
+ <FamilyCodeDisplay id="own-identity-code" code={ownSharingCode} className="self-start" />
+ <p className="text-xs text-gray-500 dark:text-gray-400">{familySharingText.yourCodeSettingsHint}</p>
+ </div>
)}
</div>
</section>
diff --git a/apps/browser-extension/src/entrypoints/popup/utils/SharingErrors.ts b/apps/browser-extension/src/entrypoints/popup/utils/SharingErrors.ts
new file mode 100644
index 000000000..2375f4894
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/utils/SharingErrors.ts
@@ -0,0 +1,39 @@
+import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
+import { sharingErrorMessage } from '@aliasvault/client/sharing/FamilySharingView';
+
+import type { SharingActionResponse } from '@/entrypoints/background/VaultMessageHandler';
+
+/**
+ * Error thrown by a failed sharing operation, carrying the message to show.
+ */
+export class SharingOperationError extends Error {}
+
+/** A failure the background script reported as a bare API error code. */
+class SharingApiError 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.length > 0 ? error.message : fallback;
+ }
+
+ const code = error instanceof SharingApiError ? error.message : apiErrorCodeOf(error);
+ return sharingErrorMessage(code) ?? (code !== null ? `${fallback} [${code}]` : fallback);
+}
+
+/**
+ * Throw the error a failed background sharing answer stands for; the background already put most failures into words.
+ * @param result - what the background script answered.
+ * @returns The successful answer.
+ */
+export function unwrapSharingResult(result: SharingActionResponse): SharingActionResponse {
+ if (result.success) {
+ return result;
+ }
+
+ throw result.apiErrorCode ? new SharingApiError(result.apiErrorCode) : new SharingOperationError(result.error ?? '');
+}
diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
index 74ff18531..770858a29 100644
--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
@@ -15,6 +15,7 @@ export type TotpCodePreview = {
};
import type { TwoFactorPrompt } from '@/entrypoints/background/TwoFactorStateHandler';
+import type { SharingActionResponse } from '@/entrypoints/background/VaultMessageHandler';
import type { SavePromptPersistedState, LastAutofilledCredential } from '@/utils/loginDetector';
import type { PendingPasskeyRequest, WebAuthnSettingsResponse, WebAuthnPublicKeyGetPayload, MatchingPasskeysResponse, WebAuthnAssertionResponse } from '@/utils/passkey/types';
@@ -97,10 +98,12 @@ export interface IExtensionMessageProtocol {
GET_TWO_FACTOR_STATE(): TwoFactorPrompt | null;
GET_VAULT_MIGRATION_STATUS(): VaultMigrationKind;
GET_WEBAUTHN_SETTINGS(data: any): WebAuthnSettingsResponse;
- GROUP_CREATE_VAULT(data: { groupId: string; name: string }): { success: boolean; error?: string; apiErrorCode?: string };
- GROUP_UPDATE_VAULT(data: { groupId: string; manifestId: string; details: SharedManifestDetails }): { success: boolean; error?: string; apiErrorCode?: string };
- GROUP_INVITE_MEMBER(data: { groupId: string; manifestId: string; userId: string }): { success: boolean; error?: string; apiErrorCode?: string };
- GROUP_REVOKE_ACCESS(data: { groupId: string; manifestId: string; userId: string }): { success: boolean; error?: string; apiErrorCode?: string };
+ GROUP_CREATE_VAULT(data: { name: string }): SharingActionResponse;
+ GROUP_UPDATE_VAULT(data: { groupId: string; manifestId: string; details: SharedManifestDetails }): SharingActionResponse;
+ GROUP_INVITE_MEMBER(data: { groupId: string; manifestId: string; userId: string }): SharingActionResponse;
+ GROUP_LOOKUP_IDENTITY_CODE(data: { groupId?: string; identityCode: string }): SharingActionResponse;
+ GROUP_INVITE_MEMBER_BY_CODE(data: { groupId: string; manifestId: string; identityCode: string }): SharingActionResponse;
+ GROUP_ACCEPT_MANIFEST_INVITATION(data: { invitationId: string; identityCode?: string }): SharingActionResponse;
IS_URL_LINKED_TO_CREDENTIAL(data: { itemId: string; manifestId: string; url: string }): { linked: boolean };
IS_LOGIN_SAVE_BLOCKED(data: { domain: string }): boolean;
LOCK_VAULT(): BoolResponse;
diff --git a/apps/web/src/components/sharing/SharedFolderAccessModal.tsx b/apps/web/src/components/sharing/SharedFolderAccessModal.tsx
index 5a1fef51d..334e6244c 100644
--- a/apps/web/src/components/sharing/SharedFolderAccessModal.tsx
+++ b/apps/web/src/components/sharing/SharedFolderAccessModal.tsx
@@ -32,6 +32,8 @@ type SharedFolderAccessModalProps = {
shared: SharedFolders;
/** Called once the folder became a shared one or a personal one again, with the folder it is shown as now. */
onMoved: (ref: FolderRef, isShared: boolean) => void;
+ /** Called once this account left the shared folder, which is gone from its vault. */
+ onLeft: () => void;
onClose: () => void;
};
@@ -39,7 +41,7 @@ type SharedFolderAccessModalProps = {
* 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.
*/
-const SharedFolderAccessModal: React.FC<SharedFolderAccessModalProps> = ({ isOpen, folder, isShared, shared, onMoved, onClose }) => {
+const SharedFolderAccessModal: React.FC<SharedFolderAccessModalProps> = ({ isOpen, folder, isShared, shared, onMoved, onLeft, onClose }) => {
const { t } = useTranslation();
const webApi = useWebApi();
const { loadStoredDatabase, getSqliteClient } = useDb();
@@ -214,26 +216,24 @@ const SharedFolderAccessModal: React.FC<SharedFolderAccessModalProps> = ({ isOpe
? SharingService.leaveSharedManifest(webApi, target.group.groupId, target.manifest.manifestId, answerChallenge)
: SharingService.revokeAccess(webApi, target.group.groupId, target.manifest.manifestId, member.userId, answerChallenge))),
/**
- * Sync the change in and close when the folder is gone for this account.
+ * Sync the change in and leave the folder, which is gone for this account, when it was its own access.
*/
onDone: async () => {
try {
await syncVault();
await loadStoredDatabase();
- if (isSelf) {
- await shared.reload();
- } else {
+ if (!isSelf) {
// Taking the last other person out makes the folder personal again.
await revertIfEmpty(target.manifest.manifestId);
- await shared.reload();
}
+ await shared.reload();
} catch (revertError) {
setError(sharingFailureMessage(revertError, familySharingText.errors.revokeAccessFailed));
} finally {
setBusy(false);
}
if (isSelf) {
- onClose();
+ onLeft();
}
},
});
diff --git a/apps/web/src/pages/items/Home.tsx b/apps/web/src/pages/items/Home.tsx
index ea4dd56c9..e2ff5bd20 100644
--- a/apps/web/src/pages/items/Home.tsx
+++ b/apps/web/src/pages/items/Home.tsx
@@ -719,6 +719,10 @@ const ItemsHome: React.FC = () => {
setPeopleFolder(open => (open ? { folder: { ...open.folder, Id: ref.Id, ManifestId: ref.ManifestId, ParentFolderId: null }, isShared } : null));
navigate(buildItemsUrl(ref, filterType));
}}
+ onLeft={() => {
+ setPeopleFolder(null);
+ navigate(buildItemsUrl(null, filterType));
+ }}
onClose={() => setPeopleFolder(null)}
/>
)}
diff --git a/core/client/src/database/repositories/ImportExportRepository.ts b/core/client/src/database/repositories/ImportExportRepository.ts
index 17ee3eefc..7239f302f 100644
--- a/core/client/src/database/repositories/ImportExportRepository.ts
+++ b/core/client/src/database/repositories/ImportExportRepository.ts
@@ -52,8 +52,7 @@ export class ImportExportRepository extends BaseRepository {
/**
* The manifest every vault export reads: always the personal manifest.
*
- * Note: shared manifests are not part of a regular vault export. Exporting a shared manifest is a separate,
- * admin-only flow in the family sharing UI.
+ * Note: shared manifests are not part of a regular vault export.
* @returns The personal manifest id
*/
private *exportManifestId(): DbOp<string> {
diff --git a/core/client/src/sharing/SharingService.ts b/core/client/src/sharing/SharingService.ts
index 396d163dd..1d5ed16a2 100644
--- a/core/client/src/sharing/SharingService.ts
+++ b/core/client/src/sharing/SharingService.ts
@@ -60,7 +60,7 @@ export class SharingService {
}
/**
- * The families this user belongs to, their shared manifests, and the invitations awaiting an answer.
+ * The shared folders this account is in (each with its group of people), the invitations awaiting an answer, and the people verified before.
* @param webApi - API client to reuse.
*/
public static async getOverview(webApi: SharingApi): Promise<GroupOverviewResponse> {
diff --git a/core/client/src/sync/VaultSync.ts b/core/client/src/sync/VaultSync.ts
index 6a43e4899..7d513f855 100644
--- a/core/client/src/sync/VaultSync.ts
+++ b/core/client/src/sync/VaultSync.ts
@@ -78,11 +78,11 @@ export type KeyRotationOperationResult = SyncErrorDetail & {
*/
export type SharingOperationResult = SyncErrorDetail & {
success: boolean;
- /** The shared manifest the operation created or invited to. */
+ /** The shared manifest the operation created, invited to or accepted. */
manifestId?: string;
/** The account an identity code belonged to. */
username?: string;
- /** The account was already a member of the family, so only its key was certified. */
+ /** The account is already in the folder's group, so only its key was certified. */
alreadyMember?: boolean;
/** The API error code the server refused with, which the sharing screen has words for. */
apiErrorCode?: string;