Skip to content

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

Update web app new identity code and folder sharing structure (#2536)

Leendert de Borstc6f71f1b95f2
diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx
index 9886187b9..537abbdb2 100644
--- a/apps/web/src/App.tsx
+++ b/apps/web/src/App.tsx
@@ -1,8 +1,6 @@
-import { CapabilityKeys } from '@aliasvault/models/webapi';
import React from 'react';
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
-import { RequireCapability } from '@/context/CapabilityContext';
import AuthLayout from '@/layouts/AuthLayout';
import MainLayout from '@/layouts/MainLayout';
import ForgotPassword from '@/pages/auth/ForgotPassword';
@@ -19,7 +17,6 @@ import RecentlyDeleted from '@/pages/items/RecentlyDeleted';
import ItemView from '@/pages/items/View';
import NotFound from '@/pages/NotFound';
import AppsSettings from '@/pages/settings/Apps';
-import FamilySharing from '@/pages/settings/FamilySharing';
import GeneralSettings from '@/pages/settings/General';
import IdentityGeneratorSettings from '@/pages/settings/IdentityGenerator';
import ImportExport from '@/pages/settings/importexport/ImportExport';
@@ -81,7 +78,6 @@ const App: React.FC = () => (
<Route path="/settings/two-factor/enable" element={<TwoFactor key="enable" mode="enable" />} />
<Route path="/settings/two-factor/disable" element={<TwoFactor key="disable" mode="disable" />} />
<Route path="/settings/storage-insights" element={<StorageInsights />} />
- <Route path="/settings/family-sharing" element={<RequireCapability capability={CapabilityKeys.VaultSharing}><FamilySharing /></RequireCapability>} />
<Route path="/settings/import-export" element={<ImportExport />} />
<Route path="/settings/import-export/reset-vault" element={<ResetVault />} />
<Route path="/settings/apps" element={<AppsSettings />} />
diff --git a/apps/web/src/components/layout/TopMenu.tsx b/apps/web/src/components/layout/TopMenu.tsx
index 359995b23..647781279 100644
--- a/apps/web/src/components/layout/TopMenu.tsx
+++ b/apps/web/src/components/layout/TopMenu.tsx
@@ -1,6 +1,4 @@
-import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
import { ItemTypes } from '@aliasvault/models/vault';
-import { CapabilityKeys } from '@aliasvault/models/webapi';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
@@ -15,7 +13,6 @@ import Icon from '@/components/shared/Icon';
import MenuItem from '@/components/shared/MenuItem';
import { useAccountReminders } from '@/context/AccountReminderContext';
import { useAuth } from '@/context/AuthContext';
-import { useCapabilities } from '@/context/CapabilityContext';
import { useTheme } from '@/context/ThemeContext';
import { useClickOutside } from '@/hooks/useClickOutside';
import { useConfirmLogout } from '@/hooks/useConfirmLogout';
@@ -36,7 +33,6 @@ const TopMenu: React.FC = () => {
const location = useLocation();
const navigate = useNavigate();
const { username } = useAuth();
- const hasCapability = useCapabilities();
const { isDarkMode, toggleTheme } = useTheme();
const confirmLogout = useConfirmLogout();
const [isQuickCreateOpen, setIsQuickCreateOpen] = useState(false);
@@ -128,11 +124,6 @@ const TopMenu: React.FC = () => {
<AccountMenuLink onNavigate={closeUserMenu} to="/emails" icon="emails" label={t('emails.title')} />
</div>
<div className="border-t border-gray-100 dark:border-gray-600 py-1">
- {hasCapability(CapabilityKeys.VaultSharing) && (
- <AccountMenuLink onNavigate={closeUserMenu} to="/settings/family-sharing" icon="familySharing" label={familySharingText.title}>
- <span className="px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide rounded bg-primary-100 text-primary-800 dark:bg-primary-900 dark:text-primary-200">{familySharingText.beta}</span>
- </AccountMenuLink>
- )}
<AccountMenuLink onNavigate={closeUserMenu} to="/settings/two-factor" icon="twoFactor" label={t('common.twoFactorAuthentication')}>
{reminders.enableTwoFactor && (
<span title={t('settings.securitySettings.twoFactor.disabledMessage')} className="flex items-center justify-center w-7 h-7">
diff --git a/apps/web/src/components/settings/FamilyCode.tsx b/apps/web/src/components/settings/FamilyCode.tsx
new file mode 100644
index 000000000..26a042cba
--- /dev/null
+++ b/apps/web/src/components/settings/FamilyCode.tsx
@@ -0,0 +1,66 @@
+import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
+import React, { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import Icon from '@/components/shared/Icon';
+
+type FamilyCodeProps = {
+ code: string;
+ /** The id of the code text, for the one copy on the page that tests read. */
+ id?: string;
+ className?: string;
+ /** A smaller pill, for showing the code inside other content. */
+ isSmall?: boolean;
+};
+
+/** How long the copy button shows that the code was copied. */
+const COPIED_MS = 2000;
+
+/**
+ * The account's own family code; clicking anywhere on it copies the code. The code is not secret, so it is copied without the clipboard
+ * clear timer that vault values get.
+ */
+const FamilyCode: React.FC<FamilyCodeProps> = ({ code, id, className = '', isSmall = false }) => {
+ const { t } = useTranslation();
+ const [isCopied, setIsCopied] = useState(false);
+
+ useEffect(() => {
+ if (!isCopied) {
+ return undefined;
+ }
+
+ const timer = setTimeout(() => setIsCopied(false), COPIED_MS);
+ return (): void => clearTimeout(timer);
+ }, [isCopied]);
+
+ /**
+ * Copy the code to the clipboard.
+ */
+ const copy = async (): Promise<void> => {
+ try {
+ await navigator.clipboard.writeText(code);
+ setIsCopied(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-2 gap-y-0.5 pl-3 pr-1 py-1' : 'gap-x-3 gap-y-1 pl-4 pr-1.5 py-1.5'} ${className}`}
+ >
+ <Icon name="shield-check" className={`${isSmall ? 'w-4 h-4' : 'w-5 h-5'} shrink-0 text-primary-500`} />
+ <span className={`${isSmall ? 'text-xs' : 'text-sm'} text-gray-700 dark:text-gray-300`}>{familySharingText.yourCode}</span>
+ <span id={id} className={`font-mono ${isSmall ? 'text-sm' : 'text-base'} font-semibold tracking-wider whitespace-nowrap text-gray-900 dark:text-white`}>{code}</span>
+ <span className={`inline-flex items-center gap-1.5 ${isSmall ? 'px-2 py-0.5 text-xs' : 'px-3 py-1 text-sm'} font-medium text-primary-700 dark:text-primary-300`}>
+ <Icon name={isCopied ? 'check' : 'duplicate'} className={isSmall ? 'w-3.5 h-3.5' : 'w-4 h-4'} />
+ {isCopied && t('common.copiedShort')}
+ </span>
+ </button>
+ );
+};
+
+export default FamilyCode;
diff --git a/apps/web/src/components/settings/InviteMemberWizard.tsx b/apps/web/src/components/settings/InviteMemberWizard.tsx
new file mode 100644
index 000000000..6e9089cf7
--- /dev/null
+++ b/apps/web/src/components/settings/InviteMemberWizard.tsx
@@ -0,0 +1,266 @@
+import { familySharingText, splitAround } from '@aliasvault/client/sharing/FamilySharingView';
+import React, { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AlertMessageError from '@/components/alerts/AlertMessageError';
+import FamilyCode from '@/components/settings/FamilyCode';
+import Button from '@/components/shared/Button';
+import FormModal from '@/components/shared/FormModal';
+import Icon from '@/components/shared/Icon';
+import InlineSpinner from '@/components/shared/InlineSpinner';
+import InputTextField from '@/components/shared/InputTextField';
+
+/**
+ * `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. */
+ ownFamilyCode: string | null;
+ /** Find the account behind a code; throws an error with the message to show. */
+ onLookup: (code: string) => Promise<FamilyCodeAccount>;
+ /** Invite the account behind a code; throws an error with the message to show. */
+ onInvite: (code: string) => Promise<void>;
+ /** The people verified before who are not in the folder yet, offered before the code field. */
+ people?: KnownPerson[];
+ /** Invite somebody verified before; throws an error with the message to show. */
+ onInvitePerson?: (userId: string) => Promise<void>;
+ /** The folder the invitation is for. */
+ folderName: string;
+ /** Whether inviting turns a personal folder into a shared one. */
+ sharesFolder?: boolean;
+ 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;
+
+/**
+ * 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, ownFamilyCode, onLookup, onInvite, people = [], onInvitePerson, folderName, sharesFolder = false, 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 undefined;
+ }
+
+ const timer = setTimeout(() => setCloseCountdown(seconds => seconds - 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 to run.
+ */
+ const runStep = async (action: () => Promise<void>): Promise<void> => {
+ setIsBusy(true);
+ setError(null);
+ try {
+ await action();
+ } catch (stepError) {
+ setError(stepError instanceof Error ? stepError.message : t('common.errors.unknownErrorTryAgain'));
+ } finally {
+ setIsBusy(false);
+ }
+ };
+
+ /**
+ * Ask to confirm the person picked, or look the code up first and ask to confirm who it belongs to.
+ */
+ const lookup = (): Promise<void> => runStep(async () => {
+ setAccount(selected ? { username: selected.username } : await onLookup(trimmedCode));
+ setStep(2);
+ });
+
+ /**
+ * Invite the person picked or the account behind the code, then show this account's own code.
+ */
+ const invite = (): Promise<void> => runStep(async () => {
+ if (selected && onInvitePerson) {
+ await onInvitePerson(selected.userId);
+ } else {
+ await onInvite(trimmedCode);
+ }
+ setCloseCountdown(CLOSE_DELAY_SECONDS);
+ setStep(3);
+ });
+
+ const canClose = !isBusy && (step !== 3 || closeCountdown === 0);
+
+ /**
+ * The primary action of the current step, also run on Enter.
+ */
+ const confirm = (): void => {
+ if (isBusy) {
+ return;
+ }
+ if (step === 1 && (selected !== null || trimmedCode.length > 0)) {
+ void lookup();
+ } else if (step === 2) {
+ void invite();
+ } else if (step === 3 && canClose) {
+ onClose();
+ }
+ };
+
+ /**
+ * Close, unless a step is running or the last step still counts down.
+ */
+ const close = (): void => {
+ if (canClose) {
+ onClose();
+ }
+ };
+
+ const footer = (
+ <>
+ {step === 1 && <Button id="invite-wizard-next" isDisabled={isBusy || (selected === null && trimmedCode.length === 0)} onClick={confirm}>{t('common.next')}</Button>}
+ {step === 2 && <Button id="invite-wizard-confirm" isDisabled={isBusy} onClick={confirm}>{familySharingText.invite}</Button>}
+ {step === 3 && <Button id="invite-wizard-close" isDisabled={!canClose} onClick={close}>{closeCountdown > 0 ? familySharingText.closeCountdown(closeCountdown) : t('common.close')}</Button>}
+ {step === 1 && <Button color="secondary" isDisabled={isBusy} onClick={close}>{t('common.cancel')}</Button>}
+ {step === 2 && <Button color="secondary" isDisabled={isBusy} onClick={() => setStep(1)}>{t('common.back')}</Button>}
+ </>
+ );
+
+ return (
+ <FormModal isOpen={isOpen} title={familySharingText.invitePeople} maxWidth="xl" closeOnOverlayClick={false} closeOnEscape={canClose} footerContent={footer} onClose={close} onConfirm={confirm}>
+ {/* Progress through the three steps. */}
+ <div className="mb-5">
+ <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 && (
+ <div className="space-y-5">
+ {/* 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-4 py-2.5 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>
+ <InputTextField
+ id="invite-wizard-code"
+ value={code}
+ onValueChange={value => {
+ setCode(value);
+ setSelected(null);
+ }}
+ placeholder={familySharingText.codePlaceholder}
+ autoFocus={people.length === 0}
+ />
+ </div>
+ </div>
+ )}
+
+ {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-500" />
+ <h4 className="text-base font-medium text-gray-900 dark:text-white">{emphasized(familySharingText.inviteWizardInvited(account.username), account.username)}</h4>
+ </div>
+ {/* What the admin still has to do: the invitee types this code to accept. */}
+ <div className="space-y-3 rounded-lg border border-gray-200 p-4 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>
+ {ownFamilyCode && <FamilyCode code={ownFamilyCode} />}
+ <p className="text-xs text-gray-500 dark:text-gray-400">{familySharingText.inviteWizardShareNotSecret}</p>
+ </div>
+ </div>
+ )}
+
+ {error && <AlertMessageError message={error} />}
+ </FormModal>
+ );
+};
+
+export default InviteMemberWizard;
diff --git a/apps/web/src/components/shared/FormModal.tsx b/apps/web/src/components/shared/FormModal.tsx
index f989ba3a5..94fa257c4 100644
--- a/apps/web/src/components/shared/FormModal.tsx
+++ b/apps/web/src/components/shared/FormModal.tsx
@@ -21,6 +21,7 @@ type FormModalProps = {
closeOnOverlayClick?: boolean;
closeOnEscape?: boolean;
submitOnEnter?: boolean;
+ showCloseButton?: boolean;
onClose: () => void;
onConfirm?: () => void;
};
@@ -45,7 +46,7 @@ const getMaxWidthClass = (maxWidth: FormModalProps['maxWidth']): string => {
const FormModal: React.FC<FormModalProps> = ({
isOpen, title = '', icon, iconBackgroundClass = 'bg-primary-100 dark:bg-primary-900/30', children, footerContent, showDefaultFooter = true,
confirmText, cancelText, confirmDisabled = false, confirmButtonClass = 'bg-primary-600 hover:bg-primary-700', isLoading = false, maxWidth = 'lg',
- closeOnOverlayClick = true, closeOnEscape = true, submitOnEnter = true, onClose, onConfirm,
+ closeOnOverlayClick = true, closeOnEscape = true, submitOnEnter = true, showCloseButton = false, onClose, onConfirm,
}) => {
const { t } = useTranslation();
const panelRef = useRef<HTMLDivElement>(null);
@@ -82,10 +83,17 @@ const FormModal: React.FC<FormModalProps> = ({
</div>
)}
<div className={`${icon ? 'mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left' : ''} flex-1`}>
- {title && (
- <h3 className="text-lg font-semibold leading-6 text-gray-900 dark:text-white">
- {title}
- </h3>
+ {(title || showCloseButton) && (
+ <div className="flex items-start justify-between gap-4">
+ <h3 className="min-w-0 text-lg font-semibold leading-6 text-gray-900 dark:text-white break-words">
+ {title}
+ </h3>
+ {showCloseButton && (
+ <button type="button" onClick={onClose} aria-label={t('common.close')} className="-m-1 p-1 shrink-0 rounded-md text-gray-400 hover:text-gray-600 hover:bg-gray-100 dark:text-gray-500 dark:hover:text-gray-300 dark:hover:bg-gray-700">
+ <Icon name="x" className="w-5 h-5" />
+ </button>
+ )}
+ </div>
)}
<div className={title ? 'mt-4' : ''}>
{children}
diff --git a/apps/web/src/components/shared/InlineSpinner.tsx b/apps/web/src/components/shared/InlineSpinner.tsx
new file mode 100644
index 000000000..3faeb4957
--- /dev/null
+++ b/apps/web/src/components/shared/InlineSpinner.tsx
@@ -0,0 +1,15 @@
+import React from 'react';
+
+import Icon from '@/components/shared/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-10" 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/web/src/components/sharing/SharedFolderAccessModal.tsx b/apps/web/src/components/sharing/SharedFolderAccessModal.tsx
new file mode 100644
index 000000000..5a1fef51d
--- /dev/null
+++ b/apps/web/src/components/sharing/SharedFolderAccessModal.tsx
@@ -0,0 +1,382 @@
+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 AlertMessageError from '@/components/alerts/AlertMessageError';
+import AlertMessageSuccess from '@/components/alerts/AlertMessageSuccess';
+import FamilyCode from '@/components/settings/FamilyCode';
+import InviteMemberWizard, { type FamilyCodeAccount } from '@/components/settings/InviteMemberWizard';
+import Button from '@/components/shared/Button';
+import FormModal from '@/components/shared/FormModal';
+import Icon from '@/components/shared/Icon';
+import InlineSpinner from '@/components/shared/InlineSpinner';
+import SmallButton from '@/components/shared/SmallButton';
+import { useConfirmModal } from '@/context/ConfirmModalContext';
+import { useDb } from '@/context/DbContext';
+import { useWebApi } from '@/context/WebApiContext';
+import { usePasswordConfirmedAction } from '@/hooks/usePasswordConfirmedAction';
+import { type SharedFolders } from '@/hooks/useSharedFolders';
+import { useVaultMutate } from '@/hooks/useVaultMutate';
+import { useVaultSync } from '@/hooks/useVaultSync';
+import { SharingOperationError, sharingFailureMessage, unwrapSharingResult } from '@/utils/SharingErrors';
+import { vaultStore } from '@/vault/VaultStore';
+
+import type { Folder, FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';
+import type { GroupMemberInfo } from '@aliasvault/models/webapi';
+
+type SharedFolderAccessModalProps = {
+ isOpen: boolean;
+ folder: Folder;
+ 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;
+ 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> = ({ isOpen, folder, isShared, shared, onMoved, onClose }) => {
+ const { t } = useTranslation();
+ const webApi = useWebApi();
+ const { loadStoredDatabase, getSqliteClient } = useDb();
+ const { syncVault } = useVaultSync();
+ const { executeVaultMutationAsync } = useVaultMutate();
+ const { showConfirmation } = useConfirmModal();
+ 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(() => {
+ if (isOpen) {
+ void reload();
+ }
+ }, [isOpen, reload]);
+
+ const current = isShared ? shared.folders.find(candidate => candidate.manifest.manifestId.toLowerCase() === folder.ManifestId.toLowerCase()) ?? null : null;
+ const others = shared.verifiedPeople.filter(person => person.userId !== shared.myUserId);
+ const invitable = current ? invitablePeople(current, others) : others;
+ const hasOthers = current !== null && hasOtherPeople(current, shared.myUserId);
+ const canInvite = isShared ? current !== null && canAdministerGroup(current.group) && holdsManifestKey(current.manifest, shared.myUserId) : true;
+
+ /**
+ * Run one action, showing its error in the 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);
+ };
+
+ /**
+ * 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);
+ }
+
+ const result = await vaultStore.createSharedManifest(folder.Name);
+ unwrapSharingResult(result, familySharingText.errors.createVaultFailed, t);
+ const manifestId = (result.manifestId ?? '').toLowerCase();
+
+ // The sync pushes the new shared folder; the contents then move into it with a push of their own.
+ await syncVault();
+ const client = await loadStoredDatabase();
+ if (!client) {
+ throw new SharingOperationError(familySharingText.errors.createVaultFailed);
+ }
+ await executeVaultMutationAsync(async () => {
+ await client.folders.moveContentsToManifest({ Id: folder.Id, ManifestId: folder.ManifestId }, manifestId);
+ });
+
+ 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 vaultStore.inviteToSharedManifest(target.group.groupId, target.manifest.manifestId, userId), familySharingText.errors.inviteFailed, t);
+ 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 = await vaultStore.lookupIdentityCode(current?.group.groupId, code);
+ unwrapSharingResult(result, familySharingText.errors.inviteFailed, t);
+ 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, once the person is known and confirmed.
+ * The sync engine checks their key against the code and certifies it.
+ * @param code - the code entered.
+ */
+ const inviteByCode = async (code: string): Promise<void> => {
+ try {
+ const target = await ensureShared();
+ const result = await vaultStore.inviteToSharedManifestByCode(target.group.groupId, target.manifest.manifestId, code);
+ unwrapSharingResult(result, familySharingText.errors.inviteFailed, t);
+ setInviteNotice(familySharingText.invitationSent(result.username ?? ''));
+ } catch (inviteError) {
+ throw new Error(sharingFailureMessage(inviteError, familySharingText.errors.inviteFailed));
+ } finally {
+ await shared.reload();
+ }
+ };
+
+ /**
+ * 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 = async (target: SharedFolder, member: GroupMemberInfo, isSelf: boolean): Promise<void> => {
+ const confirmed = isSelf
+ ? await showConfirmation(familySharingText.leaveVault, familySharingText.leaveVaultConfirm(folder.Name), familySharingText.leaveVault, t('common.cancel'))
+ : await showConfirmation(familySharingText.revoke, familySharingText.revokeAccessConfirm(member.username, folder.Name), familySharingText.revoke, t('common.cancel'));
+ if (!confirmed) {
+ return;
+ }
+
+ askPassword({
+ title: 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 close when the folder is gone for this account.
+ */
+ onDone: async () => {
+ try {
+ await syncVault();
+ await loadStoredDatabase();
+ if (isSelf) {
+ await shared.reload();
+ } else {
+ // 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) {
+ onClose();
+ }
+ },
+ });
+ };
+
+ /**
+ * Turn a shared folder this account owns back into a personal one when nobody else is in it or invited anymore (as the
+ * server sees it now): its contents move into a new personal folder with its name, then the empty shared folder is
+ * deleted. Nothing is shared anymore, so this takes no master password.
+ * @param manifestId - the shared folder.
+ */
+ const revertIfEmpty = async (manifestId: string): Promise<void> => {
+ const latest = sharingView(await SharingService.getOverview(webApi)).folders.find(candidate => candidate.manifest.manifestId.toLowerCase() === manifestId.toLowerCase());
+ const client = getSqliteClient();
+ if (!latest || latest.group.role !== 'owner' || hasOtherPeople(latest, shared.myUserId) || !client) {
+ return;
+ }
+
+ let personal: FolderRef | null = null;
+ await executeVaultMutationAsync(async () => {
+ personal = await client.folders.moveManifestToNewFolder(manifestId, folder.Name);
+ });
+ await SharingService.unshareSharedManifest(webApi, latest.group.groupId, manifestId);
+ await syncVault();
+ await loadStoredDatabase();
+ await shared.reload();
+ if (personal) {
+ onMoved(personal, false);
+ }
+ };
+
+ /*
+ * 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 = isOpen && 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 (
+ <>
+ <FormModal
+ isOpen={isOpen}
+ title={folder.Name}
+ showCloseButton
+ showDefaultFooter={false}
+ onClose={onClose}
+ >
+ {/* 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-4 ${busy ? 'hidden' : ''}`}>
+ {error && <AlertMessageError message={error} hasTopMargin={false} />}
+ {notice && <AlertMessageSuccess 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-2 flex items-center justify-between gap-2">
+ <h4 className="text-sm font-medium text-gray-900 dark:text-white">{familySharingText.peopleTitle}</h4>
+ {canInvite && hasOthers && (
+ <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-5 h-5" />
+ </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-2" 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-sm text-gray-500 dark:text-gray-400">{roleLabel(member)}</p>
+ </div>
+ {access.canLeave && <SmallButton color="danger" isDisabled={busy} onClick={() => void removeAccess(current, member, true)}>{familySharingText.leaveVault}</SmallButton>}
+ {access.canRevoke && <SmallButton color="danger" isDisabled={busy} onClick={() => void removeAccess(current, member, false)}>{familySharingText.revoke}</SmallButton>}
+ </li>
+ );
+ })}
+ {canAdministerGroup(current.group) && pendingInvitees(current).map(invitation => (
+ <li key={invitation.id} className="flex items-center justify-between gap-2 py-2" 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-sm text-gray-500 dark:text-gray-400">{familySharingText.invited}</p>
+ </div>
+ <SmallButton isDisabled={busy} onClick={() => void run(async () => {
+ await SharingService.withdrawInvitation(webApi, invitation.id);
+ await revertIfEmpty(current.manifest.manifestId);
+ }, familySharingText.errors.invitationGone)}>{familySharingText.withdraw}</SmallButton>
+ </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>
+ <FamilyCode 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 && (
+ <div>
+ <Button id="invite-someone-new" isDisabled={busy} onClick={() => setIsInviteOpen(true)}>
+ <span className="inline-flex items-center gap-2"><Icon name="plus" className="w-4 h-4" />{familySharingText.invitePeople}</span>
+ </Button>
+ </div>
+ )}
+ </div>
+ </FormModal>
+
+ <InviteMemberWizard
+ isOpen={isInviteOpen}
+ sharesFolder={!isShared}
+ folderName={folder.Name}
+ ownFamilyCode={shared.ownCode}
+ onLookup={lookup}
+ onInvite={inviteByCode}
+ people={invitable.map(person => ({ userId: person.userId, username: person.username, problem: memberKeyProblem(person) }))}
+ onInvitePerson={inviteKnown}
+ onClose={() => {
+ setIsInviteOpen(false);
+ setNotice(inviteNotice);
+ setInviteNotice(null);
+ }}
+ />
+
+ {passwordModal}
+ </>
+ );
+};
+
+export default SharedFolderAccessModal;
diff --git a/apps/web/src/components/sharing/SharedFolderInvitationModal.tsx b/apps/web/src/components/sharing/SharedFolderInvitationModal.tsx
new file mode 100644
index 000000000..a160e0caf
--- /dev/null
+++ b/apps/web/src/components/sharing/SharedFolderInvitationModal.tsx
@@ -0,0 +1,124 @@
+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 AlertMessageError from '@/components/alerts/AlertMessageError';
+import Button from '@/components/shared/Button';
+import FormModal from '@/components/shared/FormModal';
+import InputTextField from '@/components/shared/InputTextField';
+import { useWebApi } from '@/context/WebApiContext';
+import { sharingFailureMessage, unwrapSharingResult } from '@/utils/SharingErrors';
+import { vaultStore } from '@/vault/VaultStore';
+
+import type { ReceivedManifestInvitation } from '@aliasvault/models/webapi';
+
+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 {
+ const result = await vaultStore.acceptSharedManifestInvitation(invitation.id, askCode ? code.trim() : undefined);
+ if (result.apiErrorCode === 'INVITER_NOT_VERIFIED') {
+ setAskCode(true);
+ }
+ unwrapSharingResult(result, familySharingText.errors.invitationGone, t);
+ 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 = (
+ <>
+ <Button id="accept-invitation" isDisabled={busy || (askCode && code.trim().length === 0)} onClick={() => void accept()}>{familySharingText.accept}</Button>
+ {!askCode && <Button color="secondary" isDisabled={busy} onClick={() => void decline()}>{familySharingText.decline}</Button>}
+ {askCode && <Button color="secondary" isDisabled={busy} onClick={() => setAskCode(false)}>{t('common.back')}</Button>}
+ </>
+ );
+
+ return (
+ <FormModal
+ isOpen
+ title={askCode ? familySharingText.inviterCodeTitle(invitation.inviterUsername) : familySharingText.sharedWithYou(invitation.inviterUsername, folderName)}
+ footerContent={footer}
+ onClose={onClose}
+ onConfirm={() => void accept()}
+ >
+ <div className="space-y-3">
+ {!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>
+ <InputTextField id="inviter-code" value={code} onValueChange={setCode} placeholder={familySharingText.codePlaceholder} autoFocus />
+ </>
+ )}
+ {error && <AlertMessageError message={error} hasTopMargin={false} />}
+ </div>
+ </FormModal>
+ );
+};
+
+export default SharedFolderInvitationModal;
diff --git a/apps/web/src/context/CapabilityContext.tsx b/apps/web/src/context/CapabilityContext.tsx
index c5fe192f5..ede2ed45a 100644
--- a/apps/web/src/context/CapabilityContext.tsx
+++ b/apps/web/src/context/CapabilityContext.tsx
@@ -57,7 +57,7 @@ export const RequireCapability: React.FC<{ capability: CapabilityKey; children:
return null;
}
- return isEnabled(capability) ? <>{children}</> : <Navigate to="/" replace />;
+ return isEnabled(capability) ? <>{children}</> : <Navigate to="/settings" replace />;
};
/**
diff --git a/apps/web/src/context/DbContext.tsx b/apps/web/src/context/DbContext.tsx
index 49abd0c8b..dfa0f42e4 100644
--- a/apps/web/src/context/DbContext.tsx
+++ b/apps/web/src/context/DbContext.tsx
@@ -13,6 +13,7 @@ import type { SyncErrorDetail } from '@aliasvault/client/sync/VaultSync';
type DbContextType = {
sqliteClient: SqliteClient | null;
+ getSqliteClient: () => SqliteClient | null;
dbInitialized: boolean;
dbAvailable: boolean;
isOffline: boolean;
@@ -40,6 +41,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
const [dbAvailable, setDbAvailable] = useState(false);
const [isOffline, setIsOfflineState] = useState(false);
const isOfflineRef = useRef(false);
+ const sqliteClientRef = useRef<SqliteClient | null>(null);
const [isSyncing, setIsSyncing] = useState(false);
const [isUploading, setIsUploading] = useState(false);
const [syncErrorDetail, setSyncErrorDetail] = useState<SyncErrorDetail | null>(null);
@@ -113,6 +115,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
if (response.vault) {
const client = new SqliteClient();
await client.initializeFromBytes(response.vault);
+ sqliteClientRef.current = client;
setSqliteClient(client);
setDbInitialized(true);
setDbAvailable(true);
@@ -147,6 +150,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
*/
const clearDatabase = useCallback((): void => {
clearEmailKeyCache();
+ sqliteClientRef.current = null;
setSqliteClient(null);
setDbInitialized(false);
setDbAvailable(false);
@@ -156,9 +160,11 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
* Get offline state.
*/
const getIsOffline = useCallback(() => isOfflineRef.current, []);
+ const getSqliteClient = useCallback(() => sqliteClientRef.current, []);
const contextValue = useMemo(() => ({
sqliteClient,
+ getSqliteClient,
dbInitialized,
dbAvailable,
isOffline,
@@ -170,7 +176,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
clearDatabase,
syncError,
clearSyncError,
- }), [sqliteClient, dbInitialized, dbAvailable, isOffline, getIsOffline, setIsOffline, isSyncing, isUploading, loadStoredDatabase, clearDatabase, syncError, clearSyncError]);
+ }), [sqliteClient, getSqliteClient, dbInitialized, dbAvailable, isOffline, getIsOffline, setIsOffline, isSyncing, isUploading, loadStoredDatabase, clearDatabase, syncError, clearSyncError]);
return (
<DbContext.Provider value={contextValue}>
diff --git a/apps/web/src/hooks/usePasswordConfirmedAction.tsx b/apps/web/src/hooks/usePasswordConfirmedAction.tsx
new file mode 100644
index 000000000..cb1acd44a
--- /dev/null
+++ b/apps/web/src/hooks/usePasswordConfirmedAction.tsx
@@ -0,0 +1,80 @@
+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 PasswordConfirmationModal from '@/components/shared/PasswordConfirmationModal';
+import { useLoading } from '@/context/LoadingContext';
+import { sharingFailureMessage } from '@/utils/SharingErrors';
+
+import type { SrpChallengeResponder } from '@aliasvault/client/sharing/SharingService';
+
+/**
+ * An action the server confirms with the master password.
+ */
+export type PasswordConfirmedAction = {
+ title: string;
+ 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 master password prompt for actions the server confirms with it. A wrong password keeps the prompt open.
+ * @returns `askPassword` to open the prompt for an action, and the prompt element to render.
+ */
+export function usePasswordConfirmedAction(): { askPassword: (action: PasswordConfirmedAction) => void; passwordModal: React.ReactNode } {
+ const { t } = useTranslation();
+ const { showLoading, hideLoading } = useLoading();
+ const [pending, setPending] = useState<PasswordConfirmedAction | null>(null);
+ const [error, setError] = useState('');
+
+ /**
+ * Open the prompt for an action.
+ * @param action - the action to run once the password is entered.
+ */
+ const askPassword = (action: PasswordConfirmedAction): void => {
+ setError('');
+ setPending(action);
+ };
+
+ /**
+ * Run the pending action with the entered master password.
+ * @param password - the entered master password.
+ */
+ const run = async (password: string): Promise<void> => {
+ const action = pending;
+ if (!action) {
+ return;
+ }
+
+ showLoading();
+ try {
+ await action.perform(async challenge => (await MasterPasswordService.answerSrpChallenge(challenge, password)).proof);
+ } catch (actionError) {
+ setError(apiErrorCodeOf(actionError) === 'PASSWORD_MISMATCH' ? t('common.errors.wrongPassword') : sharingFailureMessage(actionError, action.failureMessage));
+ return;
+ } finally {
+ hideLoading();
+ }
+
+ setPending(null);
+ await action.onDone();
+ };
+
+ const passwordModal = (
+ <PasswordConfirmationModal
+ isOpen={pending !== null}
+ title={pending?.title ?? ''}
+ description={pending?.description ?? ''}
+ errorMessage={error}
+ onPasswordSubmitted={password => void run(password)}
+ onClose={() => setPending(null)}
+ />
+ );
+
+ return { askPassword, passwordModal };
+}
diff --git a/apps/web/src/hooks/useSharedFolders.ts b/apps/web/src/hooks/useSharedFolders.ts
new file mode 100644
index 000000000..df154c00b
--- /dev/null
+++ b/apps/web/src/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 '@/context/CapabilityContext';
+import { useWebApi } from '@/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/web/src/hooks/useVaultMutate.ts b/apps/web/src/hooks/useVaultMutate.ts
index aae6fb47b..392822b14 100644
--- a/apps/web/src/hooks/useVaultMutate.ts
+++ b/apps/web/src/hooks/useVaultMutate.ts
@@ -58,7 +58,7 @@ export function useVaultMutate(): {
const saveLocally = useCallback(async (operation: () => Promise<void>): Promise<VaultMutationScope[]> => {
await operation();
- const sqliteClient = dbContext.sqliteClient;
+ const sqliteClient = dbContext.getSqliteClient();
if (!sqliteClient) {
throw new Error('Vault is locked');
}
diff --git a/apps/web/src/pages/items/Home.tsx b/apps/web/src/pages/items/Home.tsx
index b7a58e070..ea4dd56c9 100644
--- a/apps/web/src/pages/items/Home.tsx
+++ b/apps/web/src/pages/items/Home.tsx
@@ -2,7 +2,9 @@ import { scopedKey } from '@aliasvault/client/database/ItemRef';
import { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
import { canHaveSubfolders, getDescendantFolderIds, getFolderPath, isItemInFolder, isSharedFolder } from '@aliasvault/client/items/FolderUtils';
import { ItemFilter, applyTypeFilter, type ItemFilterType, parseItemFilterType } from '@aliasvault/client/items/ItemFilters';
+import { canAdministerGroup, familySharingText, holdsManifestKey } from '@aliasvault/client/sharing/FamilySharingView';
import { multiManifestRendering } from '@aliasvault/client/sharing/MultiManifestRendering';
+import { SharingService } from '@aliasvault/client/sharing/SharingService';
import { ItemTypes, type Item, type ItemType } from '@aliasvault/models/vault';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -26,16 +28,25 @@ import PageHeader from '@/components/shared/PageHeader';
import RefreshButton from '@/components/shared/RefreshButton';
import Select from '@/components/shared/Select';
import type { SortDirection } from '@/components/shared/SortableTable';
+import SharedFolderAccessModal from '@/components/sharing/SharedFolderAccessModal';
+import SharedFolderInvitationModal from '@/components/sharing/SharedFolderInvitationModal';
+import { useConfirmModal } from '@/context/ConfirmModalContext';
import { useDb } from '@/context/DbContext';
import { useNotifications } from '@/context/NotificationContext';
import { useQuickCreate } from '@/context/QuickCreateContext';
+import { useWebApi } from '@/context/WebApiContext';
import { useClickOutside } from '@/hooks/useClickOutside';
import { usePageTitle } from '@/hooks/usePageTitle';
+import { usePasswordConfirmedAction } from '@/hooks/usePasswordConfirmedAction';
+import { useSharedFolders } from '@/hooks/useSharedFolders';
import { useVaultMutate, VaultPushFailedError } from '@/hooks/useVaultMutate';
import { useVaultRefresh } from '@/hooks/useVaultRefresh';
+import { useVaultSync } from '@/hooks/useVaultSync';
import { folderRoute } from '@/utils/ItemRoute';
import { getLocalPreferenceJson, setLocalPreferenceJson } from '@/utils/LocalPreferences';
+import { unwrapSharingResult } from '@/utils/SharingErrors';
import { LocalPreferenceKeys } from '@/utils/StorageKeys';
+import { vaultStore } from '@/vault/VaultStore';
import type { Folder, FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';
@@ -95,6 +106,14 @@ const ItemsHome: React.FC = () => {
const [showFolderModal, setShowFolderModal] = useState(false);
const [showEditFolderModal, setShowEditFolderModal] = useState(false);
const [showDeleteFolderModal, setShowDeleteFolderModal] = useState(false);
+ /** 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: Folder; isShared: boolean } | null>(null);
+ const [openInvitationId, setOpenInvitationId] = useState<string | null>(null);
+ const shared = useSharedFolders();
+ const webApi = useWebApi();
+ const { syncVault } = useVaultSync();
+ const { showConfirmation } = useConfirmModal();
+ const { askPassword, passwordModal } = usePasswordConfirmedAction();
const [showFolders, setShowFolders] = useState<boolean>(() => getLocalPreferenceJson<boolean>(LocalPreferenceKeys.ITEMS_SHOW_FOLDERS) ?? true);
const [viewMode, setViewModeState] = useState<ViewMode>('grid');
const [sortOrder, setSortOrderState] = useState<CredentialSortOrder>(CredentialSortOrder.NewestFirst);
@@ -197,8 +216,12 @@ const ItemsHome: React.FC = () => {
const currentFolder = useMemo(() => folderRef ? allFolders.find(f => f.Id === folderRef.Id && f.ManifestId === folderRef.ManifestId) ?? null : null, [allFolders, folderRef]);
const currentFolderName = currentFolder?.Name ?? '';
- // A virtual folder (a 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 = currentFolderIsVirtual ? shared.folders.find(folder => folder.manifest.manifestId.toLowerCase() === currentFolder.ManifestId.toLowerCase()) ?? null : null;
+ const canManageShared = currentShared !== null && canAdministerGroup(currentShared.group);
+ // 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);
/**
* Items after the folder and type filters.
@@ -401,6 +424,13 @@ const ItemsHome: React.FC = () => {
return;
}
try {
+ if (currentShared) {
+ // A shared folder's name is encrypted with its key and kept on the server for every member.
+ unwrapSharingResult(await vaultStore.updateSharedManifest(currentShared.group.groupId, currentShared.manifest.manifestId, { name }), t('common.errorGeneric'), t);
+ await syncVault();
+ setAllFolders((await dbContext.loadStoredDatabase())?.folders.getAll() ?? client.folders.getAll());
+ return;
+ }
await executeVaultMutationAsync(async () => {
await client.folders.update(folderRef, name);
});
@@ -413,6 +443,55 @@ const ItemsHome: React.FC = () => {
}
};
+ /**
+ * Delete the current shared folder for everyone, after a confirmation and the master password.
+ */
+ const deleteSharedFolder = async (): Promise<void> => {
+ if (!currentShared || !await showConfirmation(familySharingText.deleteVault, familySharingText.deleteVaultConfirm(currentFolderName), t('common.delete'), t('common.cancel'))) {
+ return;
+ }
+
+ askPassword({
+ title: familySharingText.deleteVault,
+ description: familySharingText.deleteVaultPasswordPrompt(currentFolderName),
+ 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 syncVault();
+ await dbContext.loadStoredDatabase();
+ await shared.reload();
+ notifications.addSuccessMessage(familySharingText.vaultDeleted);
+ navigate(buildItemsUrl(null, filterType));
+ },
+ });
+ };
+
+ /**
+ * Finish an answered invitation: an accepted one is synced in and opened.
+ * @param invitationId - the invitation.
+ * @param manifestId - the shared folder it was for.
+ * @param accepted - whether it was accepted.
+ */
+ const finishInvitation = async (invitationId: string, manifestId: string, accepted: boolean): Promise<void> => {
+ setOpenInvitationId(null);
+ if (accepted) {
+ await syncVault();
+ const client = await dbContext.loadStoredDatabase();
+ if (client) {
+ setAllFolders(client.folders.getAll());
+ }
+ navigate(buildItemsUrl({ Id: manifestId.toLowerCase(), ManifestId: manifestId.toLowerCase() }, filterType));
+ }
+ await shared.reload();
+ };
+
/**
* Delete the current folder, keeping or trashing its contents, and go to its parent.
*/
@@ -481,14 +560,23 @@ const ItemsHome: React.FC = () => {
onSelectFilter={setFilter}
onSelectRecentlyDeleted={() => navigate('/items/recently-deleted')}
onToggleShowFolders={toggleShowFolders}
- titleActions={isInFolder && !currentFolderIsVirtual ? (
+ titleActions={isInFolder ? (
<>
- <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-5 h-5" />
- </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-5 h-5" 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-5 h-5" />
+ </button>
+ )}
+ {(!currentFolderIsVirtual || (canManageShared && holdsManifestKey(currentShared.manifest, shared.myUserId))) && (
+ <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-5 h-5" />
+ </button>
+ )}
+ {(!currentFolderIsVirtual || canManageShared) && (
+ <button onClick={() => (currentFolderIsVirtual ? void deleteSharedFolder() : 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-5 h-5" strokeWidth={1} />
+ </button>
+ )}
</>
) : undefined} />
)}
@@ -550,8 +638,21 @@ const ItemsHome: React.FC = () => {
setVisibleItemCount(BATCH_SIZE); navigate(buildItemsUrl({ Id: folder.id, ManifestId: folder.manifestId }, filterType));
}} />
))}
+ {/* Invitations to shared folders wait in the folder list until they are answered. */}
+ {!isInFolder && shared.invitations.map(invitation => (
+ <button
+ key={invitation.id}
+ data-invitation={invitation.id}
+ onClick={() => setOpenInvitationId(invitation.id)}
+ className="inline-flex items-center gap-2 px-5 py-2.5 text-sm rounded-lg 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-4 h-4 text-primary-500" />
+ <span className="truncate max-w-[150px]">{shared.invitationNames[invitation.id] ?? familySharingText.sharedVault}</span>
+ <span className="text-xs text-primary-600 dark:text-primary-400">{familySharingText.invitationPending}</span>
+ </button>
+ ))}
{canCreateSubfolder && (
- <button onClick={() => setShowFolderModal(true)} className={getAddFolderButtonClass()}>
+ <button id="new-folder-button" onClick={() => setShowFolderModal(true)} className={getAddFolderButtonClass()}>
<Icon name="folder" className="w-4 h-4" />
<Icon name="plus" className="w-3.5 h-3.5 -ml-0.5" strokeWidth={2.5} />
{currentLevelFolders.length === 0 && <span>{t('items.folders.newFolder')}</span>}
@@ -608,6 +709,31 @@ const ItemsHome: React.FC = () => {
onClose={() => setShowDeleteFolderModal(false)}
onDeleteFolderOnly={() => deleteFolder(false)}
onDeleteFolderAndContents={() => deleteFolder(true)} />
+ {peopleFolder && (
+ <SharedFolderAccessModal
+ isOpen
+ folder={peopleFolder.folder}
+ isShared={peopleFolder.isShared}
+ shared={shared}
+ onMoved={(ref, isShared) => {
+ setPeopleFolder(open => (open ? { folder: { ...open.folder, Id: ref.Id, ManifestId: ref.ManifestId, ParentFolderId: null }, isShared } : null));
+ navigate(buildItemsUrl(ref, filterType));
+ }}
+ onClose={() => setPeopleFolder(null)}
+ />
+ )}
+ {((): React.ReactNode => {
+ const invitation = shared.invitations.find(candidate => candidate.id === openInvitationId) ?? null;
+ return (
+ <SharedFolderInvitationModal
+ invitation={invitation}
+ folderName={invitation ? shared.invitationNames[invitation.id] ?? familySharingText.sharedVault : ''}
+ onDone={accepted => (invitation ? finishInvitation(invitation.id, invitation.manifestId, accepted) : Promise.resolve())}
+ onClose={() => setOpenInvitationId(null)}
+ />
+ );
+ })()}
+ {passwordModal}
</>
);
};
diff --git a/apps/web/src/pages/settings/FamilySharing.tsx b/apps/web/src/pages/settings/FamilySharing.tsx
deleted file mode 100644
index 478a1303f..000000000
--- a/apps/web/src/pages/settings/FamilySharing.tsx
+++ /dev/null
@@ -1,591 +0,0 @@
-import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
-import { AppErrorCode, formatErrorWithCode } from '@aliasvault/client/api/errors/AppErrorCodes';
-import { MasterPasswordService } from '@aliasvault/client/auth/MasterPasswordService';
-import { canAdministerGroup, describeMemberAccess, familySharingText, holdsManifestKey, MAX_SHARED_VAULT_NAME_LENGTH, 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, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
-
-import AlertMessageError from '@/components/alerts/AlertMessageError';
-import AlertMessageSuccess from '@/components/alerts/AlertMessageSuccess';
-import FolderIcon from '@/components/folders/FolderIcon';
-import FolderModal from '@/components/folders/FolderModal';
-import LoadingIndicator from '@/components/loading/LoadingIndicator';
-import SettingsPageHeader from '@/components/settings/SettingsPageHeader';
-import Button from '@/components/shared/Button';
-import Card from '@/components/shared/Card';
-import Icon from '@/components/shared/Icon';
-import InputTextField from '@/components/shared/InputTextField';
-import PageContent from '@/components/shared/PageContent';
-import PasswordConfirmationModal from '@/components/shared/PasswordConfirmationModal';
-import RefreshButton from '@/components/shared/RefreshButton';
-import SectionTitle from '@/components/shared/SectionTitle';
-import SmallButton from '@/components/shared/SmallButton';
-import { useAuth } from '@/context/AuthContext';
-import { useConfirmModal } from '@/context/ConfirmModalContext';
-import { useDb } from '@/context/DbContext';
-import { useLoading } from '@/context/LoadingContext';
-import { useWebApi } from '@/context/WebApiContext';
-import { usePageTitle } from '@/hooks/usePageTitle';
-import { useVaultSync } from '@/hooks/useVaultSync';
-import { folderRoute } from '@/utils/ItemRoute';
-import { vaultStore } from '@/vault/VaultStore';
-
-import type { SharingOperationResult } from '@aliasvault/client/sync/VaultSync';
-import type { GroupInfo, GroupMemberInfo, GroupOverviewResponse, ReceivedManifestInvitation, SharedManifestInfo } from '@aliasvault/models/webapi';
-type ManifestTarget = { group: GroupInfo; manifest: SharedManifestInfo };
-
-/**
- * Error thrown by a failed sharing operation.
- */
-class SharingOperationError extends Error {}
-
-/**
- * Props for the invitation card.
- */
-type InvitationCardProps = {
- vaultName: string;
- inviterUsername: string;
- isDisabled: boolean;
- onAccept: () => void;
- onDecline: () => void;
-};
-
-/**
- * An invitation to a shared manifest, highlighted as something that waits for the user to answer.
- */
-const InvitationCard: React.FC<InvitationCardProps> = ({ vaultName, inviterUsername, isDisabled, onAccept, onDecline }) => (
- <Card variant="tile" className="flex flex-col gap-4 border-primary-400 ring-2 ring-primary-200 dark:border-primary-500 dark:ring-primary-900/60">
- <div className="flex items-center gap-2 min-w-0">
- <FolderIcon isShared className="w-5 h-5 text-primary-500" />
- <div className="min-w-0">
- <p className="text-lg font-medium text-gray-900 dark:text-white truncate" title={vaultName}>{vaultName}</p>
- <p className="text-sm text-gray-500 dark:text-gray-400">{familySharingText.invitedBy(inviterUsername)}</p>
- </div>
- </div>
- <div className="flex justify-end gap-2">
- <Button color="secondary" isDisabled={isDisabled} onClick={onDecline}>{familySharingText.decline}</Button>
- <Button isDisabled={isDisabled} onClick={onAccept}>{familySharingText.accept}</Button>
- </div>
- </Card>
-);
-
-/**
- * Family sharing page: create a family's shared manifests, invite its members to them, and answer invitations.
- */
-const FamilySharing: React.FC = () => {
- const { t } = useTranslation();
- const webApi = useWebApi();
- const { showLoading, hideLoading } = useLoading();
- const { username } = useAuth();
- const { sqliteClient, loadStoredDatabase } = useDb();
- const { syncVault } = useVaultSync();
- const { showConfirmation } = useConfirmModal();
- usePageTitle(familySharingText.title);
-
- const [overview, setOverview] = useState<GroupOverviewResponse | null>(null);
- const [isLoading, setIsLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const [notice, setNotice] = useState<string | null>(null);
- const [busy, setBusy] = useState(false);
- const [newVaultNames, setNewVaultNames] = useState<Record<string, string>>({});
- const vaultNames = useMemo<Record<string, string>>(() => (sqliteClient ? multiManifestRendering.displayNames(sqliteClient) : {}), [sqliteClient]);
- const [invitationNames, setInvitationNames] = useState<Record<string, string>>({});
- const [openVaultMenuId, setOpenVaultMenuId] = useState<string | null>(null);
- const [pendingVaultRename, setPendingVaultRename] = useState<ManifestTarget | null>(null);
- const [pendingVaultDelete, setPendingVaultDelete] = useState<ManifestTarget | null>(null);
- const [deletePasswordError, setDeletePasswordError] = useState('');
-
- 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 {
- setIsLoading(false);
- }
- }, [webApi, setIsLoading]);
-
- useEffect(() => {
- void loadOverview();
- }, [loadOverview]);
-
- /**
- * The message to show for a failed action.
- * @param actionError - the error thrown by the call.
- * @param fallback - the message for everything else.
- */
- const apiErrorMessage = (actionError: unknown, fallback: string): string => {
- if (actionError instanceof SharingOperationError) {
- return actionError.message;
- }
-
- const code = apiErrorCodeOf(actionError);
- const knownError = sharingErrorMessage(code);
- if (knownError) {
- return knownError;
- }
-
- return code !== null ? `${fallback} [${code}]` : fallback;
- };
-
- /**
- * Run one action, then reload so the page shows what the server holds now.
- * @param action - the action to run.
- * @param failureMessage - what to show when it fails without a more specific reason.
- */
- const run = async (action: () => Promise<void>, failureMessage: string): Promise<void> => {
- setBusy(true);
- setError(null);
- setNotice(null);
-
- let failure: string | null = null;
- try {
- await action();
- } catch (actionError) {
- failure = apiErrorMessage(actionError, failureMessage);
- }
-
- await loadOverview();
-
- if (failure !== null) {
- setError(failure);
- }
-
- setBusy(false);
- };
-
- /**
- * Throw the error a failed sync engine sharing operation stands for.
- * @param result - what the operation returned.
- * @param fallback - the message for a failure without a more specific reason.
- */
- const unwrap = (result: SharingOperationResult, fallback: string): void => {
- if (result.success) {
- return;
- }
-
- if (result.vaultUpgradeRequired) {
- throw new SharingOperationError(familySharingText.errors.vaultUpgradeRequired);
- }
-
- if (result.errorCode === AppErrorCode.VAULT_LOCKED) {
- throw new SharingOperationError(formatErrorWithCode(t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED));
- }
-
- const knownError = sharingErrorMessage(result.apiErrorCode);
- const code = result.apiErrorCode ?? result.error;
- throw new SharingOperationError(knownError ?? (code ? `${fallback} [${code}]` : fallback));
- };
-
- /**
- * Sync, then reopen the stored vault so shared manifest folders and names show the change.
- */
- const syncAndReload = async (): Promise<void> => {
- await syncVault();
- await loadStoredDatabase();
- };
-
- /**
- * Sync the vault and reload the overview, to pick up what other family members changed.
- */
- const refresh = async (): Promise<void> => {
- setIsLoading(true);
- try {
- await syncAndReload();
- await loadOverview();
- } finally {
- setIsLoading(false);
- }
- };
-
- /**
- * Create another shared manifest for the family. The sync that follows pushes it to the server.
- * @param group - the family to create it for.
- */
- const createSharedVault = async (group: GroupInfo): Promise<void> => {
- const name = (newVaultNames[group.groupId] ?? '').trim();
- if (name.length === 0) {
- return;
- }
-
- showLoading();
- try {
- await run(async () => {
- unwrap(await vaultStore.createSharedManifest(group.groupId, name), familySharingText.errors.createVaultFailed);
- setNewVaultNames(previous => ({ ...previous, [group.groupId]: '' }));
- await syncAndReload();
- }, familySharingText.errors.createVaultFailed);
- } finally {
- hideLoading();
- }
- };
-
- /**
- * Rename a shared manifest, which only an administrator of the family may do. Throws so the modal shows the error.
- * @param name - the new name.
- */
- const renameSharedVault = async (name: string): Promise<void> => {
- const target = pendingVaultRename;
- if (!target) {
- return;
- }
-
- try {
- unwrap(await vaultStore.updateSharedManifest(target.group.groupId, target.manifest.manifestId, { name }), t('common.errors.unknownErrorTryAgain'));
- } catch (renameError) {
- throw new Error(apiErrorMessage(renameError, t('common.errors.unknownErrorTryAgain')));
- }
-
- await syncAndReload();
- await loadOverview();
- };
-
- /**
- * Invite one member to one shared manifest.
- * @param group - the family the shared manifest belongs to.
- * @param manifest - the shared manifest.
- * @param member - the member being invited.
- */
- const inviteMember = (group: GroupInfo, manifest: SharedManifestInfo, member: GroupMemberInfo): Promise<void> => run(async () => {
- unwrap(await vaultStore.inviteToSharedManifest(group.groupId, manifest.manifestId, member.userId), familySharingText.errors.inviteFailed);
- await loadStoredDatabase();
- setNotice(familySharingText.invitationSent(member.username));
- }, familySharingText.errors.inviteFailed);
-
- /**
- * Accept an invitation; the sync that follows pulls the joined shared manifest.
- * @param invitationId - the invitation to accept.
- */
- const acceptInvitation = (invitationId: string): Promise<void> => run(async () => {
- await SharingService.acceptInvitation(webApi, invitationId);
- await syncAndReload();
- }, familySharingText.errors.invitationGone);
-
- /**
- * Ask for confirmation, then take a member's access to a shared manifest away, or hand back one's own.
- * @param group - the family.
- * @param manifest - the shared manifest.
- * @param member - the member losing access.
- * @param isSelf - whether the member is the current user.
- */
- const removeAccess = async (group: GroupInfo, manifest: SharedManifestInfo, member: GroupMemberInfo, isSelf: boolean): Promise<void> => {
- const vault = vaultLabel(manifest);
- const confirmed = isSelf
- ? await showConfirmation(familySharingText.leaveVault, familySharingText.leaveVaultConfirm(vault), familySharingText.leaveVault, t('common.cancel'))
- : await showConfirmation(familySharingText.revoke, `${familySharingText.revokeAccessConfirm(member.username, vault)}\n\n${familySharingText.revokeAccessWarning}`, familySharingText.revoke, t('common.cancel'));
- if (!confirmed) {
- return;
- }
-
- await run(async () => {
- await SharingService.revokeAccess(webApi, group.groupId, manifest.manifestId, member.userId);
- await syncAndReload();
- }, familySharingText.errors.revokeAccessFailed);
- };
-
- /**
- * Ask for confirmation, then for the master password, before deleting a shared manifest.
- * @param target - the shared manifest to delete.
- */
- const startVaultDelete = async (target: ManifestTarget): Promise<void> => {
- const confirmed = await showConfirmation(familySharingText.deleteVault, familySharingText.deleteVaultConfirm(vaultLabel(target.manifest)), t('common.delete'), t('common.cancel'));
- if (confirmed) {
- setDeletePasswordError('');
- setPendingVaultDelete(target);
- }
- };
-
- /**
- * Delete a shared manifest with the entered master password.
- * @param password - the entered master password.
- */
- const deleteSharedVault = async (password: string): Promise<void> => {
- const target = pendingVaultDelete;
- if (!target) {
- return;
- }
-
- setBusy(true);
- showLoading();
- try {
- await SharingService.deleteSharedManifest(webApi, target.group.groupId, target.manifest.manifestId, async challenge => (await MasterPasswordService.answerSrpChallenge(challenge, password)).proof);
- } catch (deleteError) {
- setDeletePasswordError(apiErrorCodeOf(deleteError) === 'PASSWORD_MISMATCH' ? t('common.errors.wrongPassword') : apiErrorMessage(deleteError, familySharingText.errors.deleteVaultFailed));
- setBusy(false);
- return;
- } finally {
- hideLoading();
- }
-
- setPendingVaultDelete(null);
- await run(async () => {
- await syncAndReload();
- setNotice(familySharingText.vaultDeleted);
- }, familySharingText.errors.deleteVaultFailed);
- };
-
- /**
- * What to call a shared manifest on screen.
- * @param manifest - the shared manifest.
- */
- const vaultLabel = (manifest: SharedManifestInfo): string => vaultNames[manifest.manifestId.toLowerCase()] ?? familySharingText.sharedVault;
-
- const receivedInvitations = overview?.receivedInvitations ?? [];
- const groups = overview?.groups ?? [];
- // An invitation shows in its family's shared vaults; one for a family this overview does not list shows on its own.
- const orphanInvitations = receivedInvitations.filter(invitation => !groups.some(group => group.groupId.toLowerCase() === invitation.groupId.toLowerCase()));
-
- /**
- * The card of one received invitation.
- * @param invitation - the invitation.
- */
- const invitationCard = (invitation: ReceivedManifestInvitation): React.ReactNode => (
- <InvitationCard
- key={invitation.id}
- vaultName={invitationNames[invitation.id] ?? familySharingText.sharedVault}
- inviterUsername={invitation.inviterUsername}
- isDisabled={busy}
- onAccept={() => void acceptInvitation(invitation.id)}
- onDecline={() => void run(() => SharingService.declineInvitation(webApi, invitation.id), familySharingText.errors.invitationGone)}
- />
- );
-
- return (
- <>
- <SettingsPageHeader
- icon="familySharing"
- title={familySharingText.title}
- description={familySharingText.description}
- customActions={<RefreshButton onClick={refresh} buttonText={t('common.refresh')} />}
- titleSuffix={<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>}
- />
-
- <FolderModal
- isOpen={pendingVaultRename !== null}
- onClose={() => setPendingVaultRename(null)}
- onSave={renameSharedVault}
- initialName={pendingVaultRename ? vaultLabel(pendingVaultRename.manifest) : ''}
- maxLength={MAX_SHARED_VAULT_NAME_LENGTH}
- mode="edit"
- />
-
- <PasswordConfirmationModal
- isOpen={pendingVaultDelete !== null}
- title={familySharingText.deleteVault}
- description={familySharingText.deleteVaultPasswordPrompt(pendingVaultDelete ? vaultLabel(pendingVaultDelete.manifest) : '')}
- errorMessage={deletePasswordError}
- onPasswordSubmitted={password => void deleteSharedVault(password)}
- onClose={() => setPendingVaultDelete(null)}
- />
-
- <PageContent>
- <div className="mx-4">
- {error && <div className="mb-4"><AlertMessageError message={error} hasTopMargin={false} /></div>}
- {notice && <AlertMessageSuccess message={notice} />}
- </div>
-
- {isLoading && <LoadingIndicator />}
-
- {!isLoading && orphanInvitations.length > 0 && (
- <section className="mx-4 mb-6">
- <SectionTitle className="mb-4">{familySharingText.invitations}</SectionTitle>
- <div className="grid grid-cols-1 items-start gap-4 md:grid-cols-2 xl:grid-cols-3">
- {orphanInvitations.map(invitationCard)}
- </div>
- </section>
- )}
-
- {!isLoading && overview && groups.length === 0 && receivedInvitations.length === 0 && (
- <Card><p className="text-sm text-gray-600 dark:text-gray-400">{familySharingText.notAvailable}</p></Card>
- )}
-
- {!isLoading && groups.map(group => {
- const canAdminister = canAdministerGroup(group);
- const myUserId = ownUserIdIn(group, username);
- const groupInvitations = receivedInvitations.filter(invitation => invitation.groupId.toLowerCase() === group.groupId.toLowerCase());
- const invitedManifestIds = new Set(groupInvitations.map(invitation => invitation.manifestId.toLowerCase()));
-
- return (
- <section key={group.groupId} className="mx-4 mb-6 space-y-6">
- {/* The family's members. */}
- <Card variant="tile">
- <SectionTitle className="mb-3">{familySharingText.members} ({group.members.length})</SectionTitle>
- <ul className="flex flex-wrap gap-x-10 gap-y-3">
- {group.members.map(member => (
- <li key={member.userId} className="min-w-0">
- <p className="text-sm text-gray-900 dark:text-white truncate">{member.username}{member.userId === myUserId && ` (${familySharingText.you})`}</p>
- <p className="text-sm text-gray-500 dark:text-gray-400">{roleLabel(member)}</p>
- </li>
- ))}
- </ul>
- </Card>
-
- <div className="min-w-0">
- <SectionTitle className="mb-0">{familySharingText.sharedVaults}</SectionTitle>
- <p className="mt-1 mb-4 text-sm text-gray-500 dark:text-gray-400">{familySharingText.sharedVaultsHint}</p>
-
- {/* One card per shared manifest, each with the members who can open it. */}
- <div className="grid grid-cols-1 items-start gap-4 md:grid-cols-2 xl:grid-cols-3">
- {/* Invitations first: they wait for an answer, and stand in for the vault's own card until accepted. */}
- {groupInvitations.map(invitationCard)}
-
- {group.manifests.filter(manifest => !invitedManifestIds.has(manifest.manifestId.toLowerCase())).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 (
- <Card key={manifest.manifestId} variant="tile">
- <div className="flex items-center gap-1 -mx-2 -mt-2 mb-2">
- {hasFolder ? (
- <Link to={folderRoute({ Id: folderId, ManifestId: folderId })} className="flex flex-1 items-center gap-2 min-w-0 px-2 py-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
- <FolderIcon isShared className="w-5 h-5 text-primary-500" />
- <span className="text-lg font-medium text-gray-900 dark:text-white truncate" title={vaultLabel(manifest)}>{vaultLabel(manifest)}</span>
- <Icon name="chevron-right" className="w-4 h-4 ml-auto shrink-0 text-gray-400" />
- </Link>
- ) : (
- <div className="flex flex-1 items-center gap-2 min-w-0 px-2 py-1.5">
- <FolderIcon isShared className="w-5 h-5 text-primary-500" />
- <span className="text-lg font-medium text-gray-900 dark:text-white truncate" title={vaultLabel(manifest)}>{vaultLabel(manifest)}</span>
- </div>
- )}
- {canAdminister && (
- <div className="relative shrink-0">
- <button
- disabled={busy}
- onClick={() => setOpenVaultMenuId(previous => (previous === manifest.manifestId ? null : manifest.manifestId))}
- aria-label={t('common.edit')}
- className="p-1.5 rounded-md text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
- >
- <Icon name="cog" className="w-5 h-5" />
- </button>
-
- {openVaultMenuId === manifest.manifestId && (
- <>
- <div className="fixed inset-0 z-10" onClick={() => setOpenVaultMenuId(null)} />
- <div className="absolute right-0 top-full mt-1 w-48 py-1 bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg shadow-xl z-20">
- {/* Renaming encrypts the name with the shared manifest's key, so it takes a member who holds it. */}
- {iHoldKey && (
- <button
- onClick={() => {
- setOpenVaultMenuId(null);
- setPendingVaultRename({ group, manifest });
- }}
- className="w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600"
- >
- {t('items.folders.editFolder')}
- </button>
- )}
- <button
- onClick={() => {
- setOpenVaultMenuId(null);
- void startVaultDelete({ group, manifest });
- }}
- className="w-full px-4 py-2 text-left text-sm text-red-600 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-600"
- >
- {familySharingText.deleteVault}
- </button>
- </div>
- </>
- )}
- </div>
- )}
- </div>
-
- {/* Inviting somebody encrypts this shared manifest's key for them, which an admin without a grant on it cannot do. */}
- {canAdminister && !iHoldKey && (
- <p className="mb-3 text-sm 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-2 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-sm text-gray-500 dark:text-gray-400">{access.statusText}</p>
- </div>
-
- {access.canLeave && (
- <SmallButton color="danger" isDisabled={busy} onClick={() => void removeAccess(group, manifest, member, isSelf)}>{familySharingText.leaveVault}</SmallButton>
- )}
-
- {access.canRevoke && (
- <SmallButton color="danger" isDisabled={busy} onClick={() => void removeAccess(group, manifest, member, isSelf)}>{familySharingText.revoke}</SmallButton>
- )}
-
- {access.canWithdraw && invitation && (
- <SmallButton isDisabled={busy} onClick={() => void run(() => SharingService.withdrawInvitation(webApi, invitation.id), familySharingText.errors.invitationGone)}>{familySharingText.withdraw}</SmallButton>
- )}
-
- {access.canInvite && (
- <SmallButton
- color="primary"
- isDisabled={busy || !access.isReadyForInvite}
- title={access.isReadyForInvite ? undefined : familySharingText.errors.userNotReady}
- onClick={() => void inviteMember(group, manifest, member)}
- >
- {familySharingText.invite}
- </SmallButton>
- )}
- </li>
- );
- })}
- </ul>
- </Card>
- );
- })}
-
- {/* Creating another shared manifest. */}
- {(canAdminister || group.manifests.length === 0) && (
- <Card variant="tile" className="border-dashed">
- {group.manifests.length === 0 && (
- <p className="mb-3 text-sm text-gray-600 dark:text-gray-400">{canAdminister ? familySharingText.noSharedVaultAdmin : familySharingText.noSharedVaultMember}</p>
- )}
-
- {canAdminister && (
- <>
- <h4 className="mb-3 text-base font-medium text-gray-900 dark:text-white">{familySharingText.createSharedVault}</h4>
- <form
- className="flex gap-2"
- onSubmit={event => {
- event.preventDefault();
- void createSharedVault(group);
- }}
- >
- <div className="flex-1 min-w-0">
- <InputTextField
- id={`new-vault-name-${group.groupId}`}
- value={newVaultNames[group.groupId] ?? ''}
- onValueChange={value => setNewVaultNames(previous => ({ ...previous, [group.groupId]: value }))}
- placeholder={familySharingText.vaultNamePlaceholder}
- maxLength={MAX_SHARED_VAULT_NAME_LENGTH}
- />
- </div>
- <Button type="submit" isDisabled={busy}>{familySharingText.create}</Button>
- </form>
- </>
- )}
- </Card>
- )}
- </div>
- </div>
- </section>
- );
- })}
- </PageContent>
- </>
- );
-};
-
-export default FamilySharing;
diff --git a/apps/web/src/pages/settings/Settings.tsx b/apps/web/src/pages/settings/Settings.tsx
index 1f0912a10..4977fc1ee 100644
--- a/apps/web/src/pages/settings/Settings.tsx
+++ b/apps/web/src/pages/settings/Settings.tsx
@@ -1,9 +1,11 @@
import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
+import { SharingService } from '@aliasvault/client/sharing/SharingService';
import { CapabilityKeys } from '@aliasvault/models/webapi';
-import React from 'react';
+import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
+import FamilyCode from '@/components/settings/FamilyCode';
import SettingsIcon, { type SettingsIconName } from '@/components/settings/SettingsIcon';
import PageContent from '@/components/shared/PageContent';
import PageHeader from '@/components/shared/PageHeader';
@@ -73,6 +75,11 @@ const Settings: React.FC = () => {
const { t } = useTranslation();
const { username } = useAuth();
const hasCapability = useCapabilities();
+ const [ownSharingCode, setOwnSharingCode] = useState<string | null>(null);
+
+ useEffect(() => {
+ void SharingService.ownIdentityCode().then(setOwnSharingCode);
+ }, []);
const confirmLogout = useConfirmLogout();
const { reminders } = useAccountReminders();
@@ -134,19 +141,19 @@ const Settings: React.FC = () => {
</div>
</div>
<div className="flex flex-wrap gap-2">
- {hasCapability(CapabilityKeys.VaultSharing) && (
- <Link to="/settings/family-sharing" className="inline-flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-700 bg-gray-100 hover:bg-gray-200 dark:text-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600">
- <SettingsIcon name="familySharing" className="w-4 h-4 mr-2" />
- {familySharingText.title}
- <span className="ml-2 px-1.5 py-0.5 text-[10px] font-semibold uppercase rounded bg-primary-100 text-primary-800 dark:bg-primary-900 dark:text-primary-200">{familySharingText.beta}</span>
- </Link>
- )}
<button type="button" id="logoutButton" onClick={() => void confirmLogout()} className="inline-flex items-center px-3 py-2 text-sm font-medium rounded-lg text-red-600 bg-red-50 hover:bg-red-100 dark:text-red-400 dark:bg-red-900/30 dark:hover:bg-red-900/50">
<SettingsIcon name="logout" className="w-4 h-4 mr-2" />
{t('web.topMenu.logOut')}
</button>
</div>
</section>
+ {/* The code someone who shares a folder with this account needs to invite it. */}
+ {hasCapability(CapabilityKeys.VaultSharing) && ownSharingCode && (
+ <section className="flex flex-col gap-2 p-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 dark:bg-gray-800">
+ <FamilyCode id="own-identity-code" code={ownSharingCode} className="self-start" />
+ <p className="text-sm text-gray-500 dark:text-gray-400">{familySharingText.yourCodeSettingsHint}</p>
+ </section>
+ )}
<div className="grid grid-cols-1 md:grid-cols-2 md:grid-rows-[auto_1fr] gap-4 items-start">
<Group group={security} className="md:col-start-1 md:row-start-1" />
<div className="space-y-4 md:col-start-2 md:row-start-1 md:row-span-2">
diff --git a/apps/web/src/utils/SharingErrors.ts b/apps/web/src/utils/SharingErrors.ts
new file mode 100644
index 000000000..25f981b08
--- /dev/null
+++ b/apps/web/src/utils/SharingErrors.ts
@@ -0,0 +1,48 @@
+import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
+import { AppErrorCode, formatErrorWithCode } from '@aliasvault/client/api/errors/AppErrorCodes';
+import { familySharingText, sharingErrorMessage } from '@aliasvault/client/sharing/FamilySharingView';
+
+import type { SharingOperationResult } from '@aliasvault/client/sync/VaultSync';
+import type { TFunction } from 'i18next';
+
+/**
+ * Error thrown by a failed sharing operation, carrying the message to show.
+ */
+export class SharingOperationError extends Error {}
+
+/**
+ * The message to show for a failed sharing action.
+ * @param error - the error thrown by the call.
+ * @param fallback - the message for an error the sharing screens have no words for.
+ */
+export function sharingFailureMessage(error: unknown, fallback: string): string {
+ if (error instanceof SharingOperationError) {
+ return error.message;
+ }
+
+ const code = apiErrorCodeOf(error);
+ return sharingErrorMessage(code) ?? (code !== null ? `${fallback} [${code}]` : fallback);
+}
+
+/**
+ * Throw the error a failed sync engine sharing operation stands for.
+ * @param result - what the operation returned.
+ * @param fallback - the message for a failure without a more specific reason.
+ * @param t - the translation function.
+ */
+export function unwrapSharingResult(result: SharingOperationResult, fallback: string, t: TFunction): void {
+ if (result.success) {
+ return;
+ }
+
+ if (result.vaultUpgradeRequired) {
+ throw new SharingOperationError(familySharingText.errors.vaultUpgradeRequired);
+ }
+
+ if (result.errorCode === AppErrorCode.VAULT_LOCKED) {
+ throw new SharingOperationError(formatErrorWithCode(t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED));
+ }
+
+ const code = result.apiErrorCode ?? result.error;
+ throw new SharingOperationError(sharingErrorMessage(result.apiErrorCode) ?? (code ? `${fallback} [${code}]` : fallback));
+}
diff --git a/apps/web/src/vault/VaultStore.ts b/apps/web/src/vault/VaultStore.ts
index 7f8365bfe..1e8d191c7 100644
--- a/apps/web/src/vault/VaultStore.ts
+++ b/apps/web/src/vault/VaultStore.ts
@@ -499,12 +499,11 @@ export const vaultStore = {
},
/**
- * Create a group's shared manifest. Leaves the vault dirty, so the next sync pushes it.
- * @param groupId - the group
+ * Create a shared manifest with a group of its own. Leaves the vault dirty, so the next sync pushes it.
* @param name - the shared manifest's name
*/
- createSharedManifest(groupId: string, name: string): Promise<SharingOperationResult> {
- return vaultSync.createSharedManifest(groupId, name);
+ createSharedManifest(name: string): Promise<SharingOperationResult> {
+ return vaultSync.createSharedManifest(name);
},
/**
@@ -518,30 +517,22 @@ export const vaultStore = {
},
/**
- * Find the account behind an identity code and check the code against its key, without inviting it.
- * @param groupId - the family
+ * Invite the account behind an identity code to a shared manifest, certifying its key first.
+ * @param groupId - the group
+ * @param manifestId - the shared manifest
* @param identityCode - the identity code the other person gave outside AliasVault
*/
- lookupIdentityCode(groupId: string, identityCode: string): Promise<SharingOperationResult> {
- return vaultSync.lookupIdentityCode(groupId, identityCode);
+ inviteToSharedManifestByCode(groupId: string, manifestId: string, identityCode: string): Promise<SharingOperationResult> {
+ return vaultSync.inviteToSharedManifestByCode(groupId, manifestId, identityCode);
},
/**
- * Invite the account with the given identity code to a family, certifying its key first.
- * @param groupId - the family
+ * Find the account behind an identity code and check the code against its key, without inviting it.
+ * @param groupId - the group of the shared folder the person is invited to, if it is shared already
* @param identityCode - the identity code the other person gave outside AliasVault
*/
- inviteToGroup(groupId: string, identityCode: string): Promise<SharingOperationResult> {
- return vaultSync.inviteToGroup(groupId, identityCode);
- },
-
- /**
- * Accept an invitation to join a family, certifying the inviter's key with their identity code when not done before.
- * @param invitationId - the invitation
- * @param identityCode - the inviter's identity code
- */
- acceptGroupInvitation(invitationId: string, identityCode?: string): Promise<SharingOperationResult> {
- return vaultSync.acceptGroupInvitation(invitationId, identityCode);
+ lookupIdentityCode(groupId: string | undefined, identityCode: string): Promise<SharingOperationResult> {
+ return vaultSync.lookupIdentityCode(groupId, identityCode);
},
/**
diff --git a/apps/web/tests/fixtures/WebApp.ts b/apps/web/tests/fixtures/WebApp.ts
index 86287c2c5..92f9f2d0a 100644
--- a/apps/web/tests/fixtures/WebApp.ts
+++ b/apps/web/tests/fixtures/WebApp.ts
@@ -121,12 +121,21 @@ export class WebApp {
}
/**
- * Open the Family Sharing page via the account popover.
+ * Open the settings overview via the account popover.
*/
- public async openFamilySharing(): Promise<void> {
+ public async openSettings(): Promise<void> {
await this.page.locator('#userMenuButton').click();
- await this.page.locator('#userMenu').getByRole('link', { name: 'Family Sharing' }).click();
- await expect(this.page).toHaveURL(/\/settings\/family-sharing$/);
+ await this.page.locator('#userMenu').getByRole('link', { name: 'Settings', exact: true }).click();
+ await expect(this.page).toHaveURL(/\/settings$/);
+ }
+
+ /**
+ * Open a folder of the vault's top level by its name.
+ */
+ public async openFolder(name: string): Promise<void> {
+ await this.openVault();
+ await this.page.getByRole('button', { name }).first().click();
+ await expect(this.page).toHaveURL(/\/items\/folder\//);
}
/**
diff --git a/apps/web/tests/helpers/test-api.ts b/apps/web/tests/helpers/test-api.ts
index 5d1613ff5..61b789f95 100644
--- a/apps/web/tests/helpers/test-api.ts
+++ b/apps/web/tests/helpers/test-api.ts
@@ -188,19 +188,6 @@ export async function postTwoFactorAuth(apiUrl: string, token: string, action: '
});
}
-/**
- * Create a shared group with the given owner and members via the DEBUG-only test controller.
- * @returns The group id
- */
-export async function createSharedGroup(apiUrl: string, name: string, ownerUsername: string, memberUsernames: string[]): Promise<string> {
- const url = `${apiUrl}/v2/Test/shared-groups`;
- const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, ownerUsername, memberUsernames }) });
- if (!response.ok) {
- throw new Error(`Creating a shared group via ${url} failed with status ${response.status}: ${await response.text()}`);
- }
- return ((await response.json()) as { groupId: string }).groupId;
-}
-
/**
* Turn a capability on for one account via the DEBUG-only test controller; the API drops its capability cache so it applies on the next request.
*/
diff --git a/core/client/src/constants/StorageKeys.ts b/core/client/src/constants/StorageKeys.ts
index 2da2b4d60..e1187edef 100644
--- a/core/client/src/constants/StorageKeys.ts
+++ b/core/client/src/constants/StorageKeys.ts
@@ -30,6 +30,8 @@ export const StorageKeys = {
SERVER_VERSION: 'local:serverVersion',
/** The capabilities that are enabled for this account passed from the server. */
CAPABILITIES: 'local:capabilities',
+ /** The number of open invitations to shared folders addressed to this account, from the last status call. */
+ PENDING_SHARING_INVITATIONS: 'local:pendingSharingInvitations',
/*
* -- Vault data (local cache) --
@@ -118,6 +120,7 @@ export const AUTH_STORAGE_KEYS: readonly StorageKey[] = [
StorageKeys.REFRESH_TOKEN,
StorageKeys.LAST_SYNC_ERROR,
StorageKeys.CAPABILITIES,
+ StorageKeys.PENDING_SHARING_INVITATIONS,
];
/** Keys that must not survive a vault lock: the Account Key. Hosts add anything they derive from decrypted data. */
diff --git a/core/client/src/database/queries/FolderQueries.ts b/core/client/src/database/queries/FolderQueries.ts
index 4d9714966..28acc8125 100644
--- a/core/client/src/database/queries/FolderQueries.ts
+++ b/core/client/src/database/queries/FolderQueries.ts
@@ -85,6 +85,49 @@ export class FolderQueries {
FROM Folders
WHERE ParentFolderId = ? AND ManifestId = ? AND IsDeleted = 0`;
+ /**
+ * The direct child folders of a folder, with their names, within the parent's own manifest.
+ */
+ public static readonly GET_CHILD_FOLDERS = `
+ SELECT Id, Name
+ FROM Folders
+ WHERE ParentFolderId = ? AND ManifestId = ? AND IsDeleted = 0`;
+
+ /**
+ * The top-level folders of a manifest, with their names.
+ */
+ public static readonly GET_TOP_LEVEL_FOLDERS = `
+ SELECT Id, Name
+ FROM Folders
+ WHERE ParentFolderId IS NULL AND ManifestId = ? AND IsDeleted = 0`;
+
+ /**
+ * The live items at the top level of a manifest, outside any folder.
+ */
+ public static readonly GET_TOP_LEVEL_ITEM_IDS = `
+ SELECT Id
+ FROM Items
+ WHERE FolderId IS NULL AND ManifestId = ? AND IsDeleted = 0`;
+
+ /**
+ * The live items directly inside a folder.
+ */
+ public static readonly GET_ITEM_IDS_IN_FOLDER = `
+ SELECT Id
+ FROM Items
+ WHERE FolderId = ? AND ManifestId = ? AND IsDeleted = 0`;
+
+ /**
+ * Move one item into a folder of another manifest; a trigger carries its child rows along and leaves a tombstone.
+ * Params: folder id (or NULL), target manifest id, timestamp, item id, source manifest id.
+ */
+ public static readonly MOVE_ITEM_TO_MANIFEST = `
+ UPDATE Items
+ SET FolderId = ?,
+ ManifestId = ?,
+ UpdatedAt = ?
+ WHERE Id = ? AND ManifestId = ?`;
+
/**
* Update parent folder for child folders.
*/
diff --git a/core/client/src/database/repositories/FolderRepository.ts b/core/client/src/database/repositories/FolderRepository.ts
index 49f5d9243..a0d1f52e3 100644
--- a/core/client/src/database/repositories/FolderRepository.ts
+++ b/core/client/src/database/repositories/FolderRepository.ts
@@ -192,6 +192,82 @@ export class FolderRepository extends BaseRepository {
return totalItemsDeleted;
}
+ /**
+ * Move a folder's contents into a shared manifest, whose top level its own items and subfolders land in. A folder row
+ * cannot change manifest, so the subfolders are created there anew; items move with their own rows. The folder and its
+ * subfolders are then deleted here.
+ * @param ref - The folder whose contents move
+ * @param targetManifestId - The shared manifest they move into
+ * @returns The number of items moved
+ */
+ public async moveContentsToManifest(ref: FolderRef, targetManifestId: string): Promise<number> {
+ this.assertNotVirtual(ref);
+ return this.withTransaction(() => this.run(this.moveTree({ manifestId: ref.ManifestId, folderId: ref.Id }, { manifestId: targetManifestId, folderId: null })));
+ }
+
+ /**
+ * Move everything a shared manifest holds into a new top-level personal folder with the given name, so the shared
+ * manifest is left empty. Its folders are created there anew; items move with their own rows.
+ * @param sourceManifestId - The shared manifest whose contents move
+ * @param name - The name of the personal folder they move into
+ * @returns The new personal folder
+ */
+ public async moveManifestToNewFolder(sourceManifestId: string, name: string): Promise<FolderRef> {
+ return this.withTransaction(async () => {
+ const manifestId = await this.run(this.writeManifestId());
+ const folderId = crypto.randomUUID();
+ const now = this.now();
+ await this.run(this.execute(FolderQueries.INSERT, [folderId, name, null, manifestId, now, now]));
+ await this.run(this.moveTree({ manifestId: sourceManifestId, folderId: null }, { manifestId, folderId }));
+ return { Id: folderId, ManifestId: manifestId };
+ });
+ }
+
+ /**
+ * Recreate the folders under a source (a folder, or a manifest's top level) under a target in another manifest, move the
+ * items along, and delete the source folders (the source folder itself included).
+ * @param source - Where the contents are now: a folder, or the top level of a manifest when `folderId` is null
+ * @param target - Where they land: a folder, or the top level of a manifest when `folderId` is null
+ * @returns The number of items moved
+ */
+ private *moveTree(source: { manifestId: string; folderId: string | null }, target: { manifestId: string; folderId: string | null }): DbOp<number> {
+ const now = this.now();
+ // Source folder id (null for the source's top level) to the folder its contents land in.
+ const landing = new Map<string | null, string | null>([[source.folderId, target.folderId]]);
+ const pending: (string | null)[] = [source.folderId];
+ const moved: string[] = [];
+
+ while (pending.length > 0) {
+ const parentId = pending.shift()!;
+ const children = parentId === null
+ ? yield* this.query<{ Id: string; Name: string }>(FolderQueries.GET_TOP_LEVEL_FOLDERS, [source.manifestId])
+ : yield* this.query<{ Id: string; Name: string }>(FolderQueries.GET_CHILD_FOLDERS, [parentId, source.manifestId]);
+ for (const child of children) {
+ const newId = crypto.randomUUID();
+ yield* this.execute(FolderQueries.INSERT, [newId, child.Name, landing.get(parentId) ?? null, target.manifestId, now, now]);
+ landing.set(child.Id, newId);
+ pending.push(child.Id);
+ moved.push(child.Id);
+ }
+ }
+
+ let itemsMoved = 0;
+ for (const [folderId, newFolderId] of landing) {
+ const items = folderId === null
+ ? yield* this.query<{ Id: string }>(FolderQueries.GET_TOP_LEVEL_ITEM_IDS, [source.manifestId])
+ : yield* this.query<{ Id: string }>(FolderQueries.GET_ITEM_IDS_IN_FOLDER, [folderId, source.manifestId]);
+ for (const item of items) {
+ itemsMoved += yield* this.execute(FolderQueries.MOVE_ITEM_TO_MANIFEST, [newFolderId, target.manifestId, now, item.Id, source.manifestId]);
+ }
+ }
+
+ for (const id of [...moved.reverse(), ...(source.folderId ? [source.folderId] : [])]) {
+ yield* this.execute(FolderQueries.SOFT_DELETE, [now, id, source.manifestId]);
+ }
+
+ return itemsMoved;
+ }
+
/**
* Refuse to change or delete a virtual folder (see {@link multiManifestRendering}): the vault stores no row for
* one, settings are managed elsewhere (e.g. shared manifest settings).
diff --git a/core/client/src/sharing/MultiManifestRendering.ts b/core/client/src/sharing/MultiManifestRendering.ts
index 5fe6c11bd..e01f50836 100644
--- a/core/client/src/sharing/MultiManifestRendering.ts
+++ b/core/client/src/sharing/MultiManifestRendering.ts
@@ -1,3 +1,5 @@
+import { familySharingText } from './FamilySharingView';
+
import type { Folder } from '../database/repositories/FolderRepository';
import type { SqliteClient } from '../database/SqliteClient';
@@ -105,7 +107,7 @@ const subfolderRendering: MultiManifestRenderer = {
const roots = sharedManifests
.filter(manifest => !storedRoots.has(manifest.ManifestId.toLowerCase()))
- .map(manifest => ({ Id: manifest.ManifestId.toLowerCase(), Name: manifest.Name ?? '', ParentFolderId: null, Weight: 0, ManifestId: manifest.ManifestId }));
+ .map(manifest => ({ Id: manifest.ManifestId.toLowerCase(), Name: manifest.Name || familySharingText.sharedVault, ParentFolderId: null, Weight: 0, ManifestId: manifest.ManifestId }));
const nested = stored.map(folder => (folder.ParentFolderId === null && shared.has(String(folder.ManifestId).toLowerCase()) && !subfolderRendering.isVirtualFolder(folder)
? { ...folder, ParentFolderId: String(folder.ManifestId).toLowerCase() }
@@ -146,8 +148,9 @@ const subfolderRendering: MultiManifestRenderer = {
return {};
}
- const rows = sqliteClient.executeQuery<{ Id: string; Name: string }>('SELECT Id, Name FROM Manifests WHERE Name IS NOT NULL');
- return Object.fromEntries(rows.map(row => [row.Id.toLowerCase(), row.Name]));
+ // A manifest whose name is not known (yet) shows under a generic name.
+ const rows = sqliteClient.executeQuery<{ Id: string; Name: string | null }>('SELECT Id, Name FROM Manifests');
+ return Object.fromEntries(rows.map(row => [row.Id.toLowerCase(), row.Name || familySharingText.sharedVault]));
},
};
diff --git a/core/client/src/sharing/SharingService.ts b/core/client/src/sharing/SharingService.ts
index 4604d91b8..396d163dd 100644
--- a/core/client/src/sharing/SharingService.ts
+++ b/core/client/src/sharing/SharingService.ts
@@ -1,7 +1,9 @@
-import { VaultKeyAlgorithm, type CreateGroupResponse, type GroupOverviewResponse, type PasswordConfirmationChallenge, type PasswordConfirmationRequest, type ReceivedManifestInvitation } from '@aliasvault/models/webapi';
+import { VaultKeyAlgorithm, type GroupOverviewResponse, type PasswordConfirmationChallenge, type PasswordConfirmationRequest, type ReceivedManifestInvitation } from '@aliasvault/models/webapi';
import { VaultKeyService } from '../auth/VaultKeyService';
+import { StorageKeys } from '../constants/StorageKeys';
import { EncryptionUtility } from '../crypto/EncryptionUtility';
+import { getPlatform } from '../platform/ClientPlatform';
import { devWarn } from '../platform/Logger';
import { rustCore } from '../rust/RustCore';
@@ -31,6 +33,15 @@ export type InvitationNameDecryptor = (encryptedName: string, recipientPublicKey
* Service with static helpers implementing the vault sharing flows.
*/
export class SharingService {
+ /**
+ * Watch the number of open invitations to shared folders, which every sync updates.
+ * @param callback - called with the new number whenever it changes.
+ * @returns Unwatch function.
+ */
+ public static watchPendingInvitationCount(callback: (count: number) => void): () => void {
+ return getPlatform().storage.watch<number>(StorageKeys.PENDING_SHARING_INVITATIONS, count => callback(count ?? 0));
+ }
+
/**
* This account's own identity code, derived from its signing private key; null while the vault is locked or the account has no signing key yet.
*/
@@ -48,36 +59,6 @@ export class SharingService {
}
}
- /**
- * Create a family (shared group) owned by this user. The server allows one per user.
- * @param webApi - API client to reuse.
- * @returns The new group's id.
- */
- public static async createGroup(webApi: SharingApi): Promise<string> {
- return (await webApi.post<object, CreateGroupResponse>('Groups', {})).groupId;
- }
-
- /**
- * Leave a family, giving up access to all of its shared manifests. The server requires proof of the caller's master
- * password and refuses this for the family's owner.
- * @param webApi - API client to reuse.
- * @param groupId - the family to leave.
- * @param answerChallenge - proves the master password, which each host derives its own way.
- */
- public static async leaveGroup(webApi: SharingApi, groupId: string, answerChallenge: SrpChallengeResponder): Promise<void> {
- const challenge = await webApi.post<object, PasswordConfirmationChallenge>(`Groups/${groupId}/leave/initiate`, {});
- await webApi.post<PasswordConfirmationRequest, void>(`Groups/${groupId}/leave/confirm`, await answerChallenge(challenge), false);
- }
-
- /**
- * Delete a family this user owns. The server refuses this while it still has shared manifests or other members.
- * @param webApi - API client to reuse.
- * @param groupId - the family to delete.
- */
- public static async deleteGroup(webApi: SharingApi, groupId: string): Promise<void> {
- await webApi.delete<void>(`Groups/${groupId}`);
- }
-
/**
* The families this user belongs to, their shared manifests, and the invitations awaiting an answer.
* @param webApi - API client to reuse.
@@ -121,19 +102,6 @@ export class SharingService {
return names;
}
- /**
- * Take a member out of the family, and with it their access to every shared manifest of the family. The server
- * requires proof of the caller's master password.
- * @param webApi - API client to reuse.
- * @param groupId - the family.
- * @param userId - the member to remove.
- * @param answerChallenge - proves the master password, which each host derives its own way.
- */
- public static async removeMember(webApi: SharingApi, groupId: string, userId: string, answerChallenge: SrpChallengeResponder): Promise<void> {
- const challenge = await webApi.post<object, PasswordConfirmationChallenge>(`Groups/${groupId}/members/${userId}/remove/initiate`, {});
- await webApi.post<PasswordConfirmationRequest, void>(`Groups/${groupId}/members/${userId}/remove/confirm`, await answerChallenge(challenge), false);
- }
-
/**
* Take another member's access to one shared manifest away. The server requires proof of the caller's master password.
* @param webApi - API client to reuse.
@@ -147,6 +115,17 @@ export class SharingService {
await webApi.post<PasswordConfirmationRequest, void>(`Groups/${groupId}/manifests/${manifestId}/access/${userId}/revoke/confirm`, await answerChallenge(challenge), false);
}
+ /**
+ * Delete a shared manifest nobody else is in, after its owner moved its contents out, so the folder is personal again.
+ * The server refuses while anybody else is in it or invited; it asks for no master password, as nothing is shared anymore.
+ * @param webApi - API client to reuse.
+ * @param groupId - the group of the shared manifest.
+ * @param manifestId - the shared manifest.
+ */
+ public static async unshareSharedManifest(webApi: SharingApi, groupId: string, manifestId: string): Promise<void> {
+ await webApi.post<object, void>(`Groups/${groupId}/manifests/${manifestId}/unshare`, {}, false);
+ }
+
/**
* Hand back one's own access to a shared manifest. The server requires proof of the caller's master password and
* refuses this for group admins.
diff --git a/core/client/src/sync/VaultSync.ts b/core/client/src/sync/VaultSync.ts
index 8103587fe..6a43e4899 100644
--- a/core/client/src/sync/VaultSync.ts
+++ b/core/client/src/sync/VaultSync.ts
@@ -94,6 +94,7 @@ export type SharingOperationResult = SyncErrorDetail & {
type PersistableSyncResult = VaultSyncEngineResultBase & {
serverVersion?: string;
capabilities?: Record<string, string>;
+ pendingSharingInvitations?: number;
isOfflineMode?: boolean;
emailDomains?: VaultSyncEmailDomains;
};
@@ -185,13 +186,12 @@ export class VaultSync {
}
/**
- * Create a group's shared manifest with this account as its first member. The vault is left dirty, so the caller's
+ * Create a shared manifest with a group of its own, owned by this account. The vault is left dirty, so the caller's
* next sync pushes the new manifest. Never throws.
- * @param groupId - the group to create the shared manifest for
* @param name - name of the shared manifest / shared vault
*/
- public async createSharedManifest(groupId: string, name: string): Promise<SharingOperationResult> {
- return this.runSharingOperation('createSharedManifest', { groupId, name });
+ public async createSharedManifest(name: string): Promise<SharingOperationResult> {
+ return this.runSharingOperation('createSharedManifest', { name });
}
/**
@@ -205,6 +205,17 @@ export class VaultSync {
return this.runSharingOperation('inviteToSharedManifest', { groupId, manifestId, userId });
}
+ /**
+ * Invite the account behind an identity code to a shared manifest. The engine checks the key the server returns
+ * against the code and certifies it; accepting also makes the account a member of the group. Never throws.
+ * @param groupId - the group the shared manifest belongs to
+ * @param manifestId - the shared manifest to invite them to
+ * @param identityCode - the identity code the other person gave outside AliasVault
+ */
+ public async inviteToSharedManifestByCode(groupId: string, manifestId: string, identityCode: string): Promise<SharingOperationResult> {
+ return this.runSharingOperation('inviteToSharedManifest', { groupId, manifestId, identityCode });
+ }
+
/**
* Change the details of a shared manifest (only allowed for administrators of the group).
* @param groupId - the group the shared manifest belongs to
@@ -216,35 +227,15 @@ export class VaultSync {
}
/**
- * Find the account behind an identity code and check the code against its key, so the admin can confirm who they invite.
- * Certifies and invites nothing. Never throws.
- * @param groupId - the family
+ * Find the account behind an identity code and check the code against its key, so the user can confirm who they invite,
+ * also before the folder is shared. Certifies and invites nothing. Never throws.
+ * @param groupId - the group of the shared folder the person is invited to, if it is shared already
* @param identityCode - the identity code the other person gave outside AliasVault
*/
- public async lookupIdentityCode(groupId: string, identityCode: string): Promise<SharingOperationResult> {
+ public async lookupIdentityCode(groupId: string | undefined, identityCode: string): Promise<SharingOperationResult> {
return this.runSharingOperation('lookupIdentityCode', { groupId, identityCode });
}
- /**
- * Invite the account with the given identity code to a family. The engine checks the key the server returns against
- * the code, certifies it, and invites; an account already in the family is only certified. Never throws.
- * @param groupId - the family
- * @param identityCode - the identity code the other person gave outside AliasVault
- */
- public async inviteToGroup(groupId: string, identityCode: string): Promise<SharingOperationResult> {
- return this.runSharingOperation('inviteToGroup', { groupId, identityCode });
- }
-
- /**
- * Accept an invitation to join a family. The inviter's key has to be certified: with their identity code now, or from
- * an earlier certification. Never throws.
- * @param invitationId - the invitation
- * @param identityCode - the inviter's identity code, when they are not certified yet
- */
- public async acceptGroupInvitation(invitationId: string, identityCode?: string): Promise<SharingOperationResult> {
- return this.runSharingOperation('acceptGroupInvitation', { invitationId, identityCode });
- }
-
/**
* Accept an invitation to a shared manifest: the engine checks the certified inviter signed it and signs the grant as
* this account's own. Never throws.
@@ -356,6 +347,9 @@ export class VaultSync {
if (result.capabilities) {
await CapabilityService.storeCapabilities(result.capabilities);
}
+ if (result.pendingSharingInvitations !== undefined && result.pendingSharingInvitations !== await storage.get<number>(StorageKeys.PENDING_SHARING_INVITATIONS)) {
+ await storage.set(StorageKeys.PENDING_SHARING_INVITATIONS, result.pendingSharingInvitations);
+ }
if (result.isOfflineMode !== undefined) {
await storage.set(StorageKeys.IS_OFFLINE_MODE, result.isOfflineMode);
}
diff --git a/core/client/src/sync/VaultSyncEngine.ts b/core/client/src/sync/VaultSyncEngine.ts
index 236dbe56b..5a811097f 100644
--- a/core/client/src/sync/VaultSyncEngine.ts
+++ b/core/client/src/sync/VaultSyncEngine.ts
@@ -21,7 +21,7 @@ import type { ISqliteDatabase, SqliteValue } from '../platform/SqliteEngine';
/** The operations the engine runs. */
/** The sharing operations, which take `VaultSyncSharingParams`. */
-export type VaultSyncSharingOperation = 'createSharedManifest' | 'inviteToSharedManifest' | 'updateSharedManifest' | 'lookupIdentityCode' | 'inviteToGroup' | 'acceptGroupInvitation' | 'acceptSharedManifestInvitation';
+export type VaultSyncSharingOperation = 'createSharedManifest' | 'inviteToSharedManifest' | 'updateSharedManifest' | 'lookupIdentityCode' | 'acceptSharedManifestInvitation';
export type VaultSyncOperation = 'fullSync' | 'migrationStatus' | 'migrateManifest' | 'statusCheck' | 'resolveVaultKey' | VaultSyncSharingOperation | 'rotateAccountKeys';
@@ -99,6 +99,7 @@ export type VaultSyncEngineResult = VaultSyncEngineResultBase & {
requiresLogout: boolean;
serverVersion?: string;
capabilities?: Record<string, string>;
+ pendingSharingInvitations?: number;
isOfflineMode: boolean;
pulledRevision?: number;
emailDomains?: VaultSyncEmailDomains;
diff --git a/core/rust/src/vault_sync/sharing.rs b/core/rust/src/vault_sync/sharing.rs
index 057c347fa..05bc58f93 100644
--- a/core/rust/src/vault_sync/sharing.rs
+++ b/core/rust/src/vault_sync/sharing.rs
@@ -395,11 +395,8 @@ const NEW_MANIFEST_KEY_VERSION: i64 = 0;
async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {
let key = ctx.encryption_key()?;
let target = params(ctx)?;
- // Without a name, every client shows the shared manifest under its own translated default name.
- let name = target.name.as_deref().map(str::trim).filter(|name| !name.is_empty()).map(str::to_string);
- if let Some(name) = &name {
- check_name_length(name)?;
- }
+ let name = target.name.as_deref().map(str::trim).filter(|name| !name.is_empty()).ok_or_else(|| SyncError::Other("A shared manifest needs a name".to_string()))?.to_string();
+ check_name_length(&name)?;
let overview = fetch_overview(ctx).await?;
@@ -418,11 +415,11 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {
let requested_id = db::new_id();
let self_encrypted_vek = keys::encrypt_manifest_vek(&manifest_vek, &requested_id, &self_public_key)?;
let self_grant_signature = me.sign(&crypto::signing::grant_message(&requested_id, NEW_MANIFEST_KEY_VERSION, &me.user_id, &self_public_key, ALGORITHM_RSA_OAEP_SHA256, &self_encrypted_vek))?;
- let encrypted_name = name.as_deref().map(|name| pull::encrypt_manifest_name(name, &requested_id, &manifest_vek)).transpose()?;
+ let encrypted_name = pull::encrypt_manifest_name(&name, &requested_id, &manifest_vek)?;
let response: CreateSharedManifestResponse = http::post(
&ctx.host,
"Groups/manifests",
- &CreateSharedManifestRequest { manifest_id: &requested_id, self_encrypted_vek: &self_encrypted_vek, self_account_public_key: &self_public_key, algorithm: ALGORITHM_RSA_OAEP_SHA256, self_grant_signature: &self_grant_signature, encrypted_name: encrypted_name.as_deref() },
+ &CreateSharedManifestRequest { manifest_id: &requested_id, self_encrypted_vek: &self_encrypted_vek, self_account_public_key: &self_public_key, algorithm: ALGORITHM_RSA_OAEP_SHA256, self_grant_signature: &self_grant_signature, encrypted_name: Some(&encrypted_name) },
false,
)
.await?;
@@ -440,7 +437,7 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {
account_public_key: self_public_key,
algorithm: ALGORITHM_RSA_OAEP_SHA256.to_string(),
salt: vault_codec::generate_manifest_salt(),
- encrypted_name,
+ encrypted_name: Some(encrypted_name),
can_administer: true,
key_version: NEW_MANIFEST_KEY_VERSION,
},
@@ -451,7 +448,7 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {
revisions.insert(manifest_id.clone(), response.revision_number);
state::set(&ctx.host, state::SERVER_MANIFEST_REVISIONS, &revisions).await?;
- db::set_manifest_name(&ctx.host, &manifest_id, name.as_deref()).await?;
+ db::set_manifest_name(&ctx.host, &manifest_id, Some(&name)).await?;
// Mail to an alias in this manifest is encrypted with the manifest's own keypair.
let delivery_keys = crypto::generate_rsa_key_pair()?;