Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add security settings components (#2413)
Leendert de Borstbadfb170d1a3
diff --git a/apps/web/src/components/settings/security/ActiveSessionsSection.tsx b/apps/web/src/components/settings/security/ActiveSessionsSection.tsxnew file mode 100644index 000000000..6184a9d21--- /dev/null+++ b/apps/web/src/components/settings/security/ActiveSessionsSection.tsx@@ -0,0 +1,80 @@+import React, { useCallback, useImperativeHandle, useState, forwardRef } from 'react';+import { useTranslation } from 'react-i18next';++import LoadingIndicator from '@/components/loading/LoadingIndicator';+import SecuritySection, { formatDateTime, type SectionHandle } from '@/components/settings/security/SecuritySection';+import Button from '@/components/shared/Button';+import { useNotifications } from '@/context/NotificationContext';+import { useWebApi } from '@/context/WebApiContext';++import type { RefreshToken } from '@aliasvault/models/webapi';++/**+ * The devices with an active session, each revocable.+ */+const ActiveSessionsSection = forwardRef<SectionHandle, { onSessionsChanged: () => Promise<void> }>(({ onSessionsChanged }, ref) => {+ const { t } = useTranslation();+ const webApi = useWebApi();+ const notifications = useNotifications();+ const [isLoading, setIsLoading] = useState(true);+ const [sessions, setSessions] = useState<RefreshToken[]>([]);+ const tk = 'components.main.settings.security.activeSessionsSection';++ const loadData = useCallback(async (): Promise<void> => {+ setIsLoading(true);+ try {+ setSessions(await webApi.getActiveSessions());+ } finally {+ setIsLoading(false);+ }+ }, [webApi]);+ useImperativeHandle(ref, () => ({ loadData }), [loadData]);++ /**+ * Revoke a session.+ */+ const revokeSession = async (id: string): Promise<void> => {+ try {+ await webApi.revokeSession(id);+ notifications.addSuccessMessage(t(`${tk}.RevokeSuccessMessage`), true);+ await onSessionsChanged();+ } catch (error) {+ notifications.addErrorMessage(t(`${tk}.RevokeExceptionMessage`, { 0: error instanceof Error ? error.message : String(error) }), true);+ }+ };++ return (+ <SecuritySection title={t(`${tk}.Title`)}>+ <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">{t(`${tk}.Description`)}</p>+ {isLoading ? <LoadingIndicator /> : sessions.length === 0 ? (+ <p className="text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.NoSessionsMessage`)}</p>+ ) : (+ <div className="overflow-x-auto">+ <table className="w-full text-sm text-left text-gray-500 dark:text-gray-400">+ <thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">+ <tr>+ <th scope="col" className="px-6 py-3">{t(`${tk}.DeviceColumn`)}</th>+ <th scope="col" className="px-6 py-3">{t(`${tk}.LastActiveColumn`)}</th>+ <th scope="col" className="px-6 py-3">{t(`${tk}.ExpiresColumn`)}</th>+ <th scope="col" className="px-6 py-3">{t(`${tk}.ActionColumn`)}</th>+ </tr>+ </thead>+ <tbody>+ {sessions.map(session => (+ <tr key={session.id} className="bg-white border-b dark:bg-gray-800 dark:border-gray-700">+ <td className="px-6 py-4">{session.deviceIdentifier}</td>+ <td className="px-6 py-4">{formatDateTime(session.createdAt)}</td>+ <td className="px-6 py-4">{formatDateTime(session.expireDate)}</td>+ <td className="px-6 py-4"><Button color="danger" onClick={() => void revokeSession(session.id)}>{t(`${tk}.RevokeButton`)}</Button></td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </SecuritySection>+ );+});+ActiveSessionsSection.displayName = 'ActiveSessionsSection';++export default ActiveSessionsSection;diff --git a/apps/web/src/components/settings/security/DeleteAccountSection.tsx b/apps/web/src/components/settings/security/DeleteAccountSection.tsxnew file mode 100644index 000000000..b8f82612a--- /dev/null+++ b/apps/web/src/components/settings/security/DeleteAccountSection.tsx@@ -0,0 +1,23 @@+import React from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';++import SecuritySection from '@/components/settings/security/SecuritySection';+import Button from '@/components/shared/Button';++/**+ * Link to the delete account page.+ */+const DeleteAccountSection: React.FC = () => {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const tk = 'components.main.settings.security.deleteAccountSection';+ return (+ <SecuritySection title={t(`${tk}.Title`)}>+ <div className="mb-3 text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.Description`)}</div>+ <Button color="danger" onClick={() => navigate('/settings/security/delete-account')}>{t(`${tk}.DeleteButton`)}</Button>+ </SecuritySection>+ );+};++export default DeleteAccountSection;diff --git a/apps/web/src/components/settings/security/PasswordChangeSection.tsx b/apps/web/src/components/settings/security/PasswordChangeSection.tsxnew file mode 100644index 000000000..211d999d0--- /dev/null+++ b/apps/web/src/components/settings/security/PasswordChangeSection.tsx@@ -0,0 +1,23 @@+import React from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';++import SecuritySection from '@/components/settings/security/SecuritySection';+import Button from '@/components/shared/Button';++/**+ * Link to the change password page.+ */+const PasswordChangeSection: React.FC = () => {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const tk = 'components.main.settings.security.passwordChangeSection';+ return (+ <SecuritySection title={t(`${tk}.Title`)}>+ <div className="mb-3 text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.Description`)}</div>+ <Button onClick={() => navigate('/settings/security/change-password')}>{t(`${tk}.ChangePasswordButton`)}</Button>+ </SecuritySection>+ );+};++export default PasswordChangeSection;diff --git a/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx b/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsxnew file mode 100644index 000000000..7399afd58--- /dev/null+++ b/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx@@ -0,0 +1,78 @@+import React, { useCallback, useEffect, useImperativeHandle, useState, forwardRef } from 'react';+import { useTranslation } from 'react-i18next';++import LoadingIndicator from '@/components/loading/LoadingIndicator';+import SecuritySection, { type SectionHandle } from '@/components/settings/security/SecuritySection';+import Button from '@/components/shared/Button';+import { useApp } from '@/context/AppContext';+import { useNotifications } from '@/context/NotificationContext';+import { WebAuthnNotSupportedError, WebAuthnService } from '@/utils/WebAuthnService';++/**+ * Passkey quick unlock for this local browser session only.+ * TODO: this will be replaced by a fully integrated passkey PRF unlock feature, which is technically possible once 0.31.0+ is released.+ */+const QuickVaultUnlockSection = forwardRef<SectionHandle>((_, ref) => {+ const { t } = useTranslation();+ const app = useApp();+ const notifications = useNotifications();+ const [isLoading, setIsLoading] = useState(true);+ const [enabled, setEnabled] = useState(false);+ const tk = 'components.main.settings.security.quickVaultUnlockSection';++ const loadData = useCallback(async (): Promise<void> => {+ setIsLoading(true);+ setEnabled(WebAuthnService.isEnabled());+ setIsLoading(false);+ }, []);+ useImperativeHandle(ref, () => ({ loadData }), [loadData]);+ useEffect(() => void loadData(), [loadData]);++ /**+ * Create a passkey and encrypt the session keys with it.+ */+ const enable = async (): Promise<void> => {+ try {+ await WebAuthnService.enable(app.username ?? '');+ notifications.addSuccessMessage(t(`${tk}.SuccessEnabledMessage`), true);+ } catch (error) {+ if (error instanceof WebAuthnNotSupportedError) {+ notifications.addErrorMessage(t(`${tk}.WebAuthnNotSupportedError`), true);+ } else {+ console.info('An error occurred while trying to enable WebAuthn.', error);+ notifications.addErrorMessage(t(`${tk}.EnableErrorMessage`), true);+ }+ return;+ }+ await loadData();+ };++ /**+ * Forget the passkey.+ */+ const disable = async (): Promise<void> => {+ WebAuthnService.disable();+ notifications.addSuccessMessage(t(`${tk}.SuccessDisabledMessage`), true);+ await loadData();+ };++ return (+ <SecuritySection title={t(`${tk}.Title`)}>+ {isLoading ? <LoadingIndicator /> : enabled ? (+ <>+ <div className="mb-3 text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.EnabledDescription`)}</div>+ <Button color="danger" onClick={() => void disable()}>{t(`${tk}.DisableButton`)}</Button>+ </>+ ) : (+ <>+ <div className="mb-3 text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.DisabledDescription`)}</div>+ <div className="mb-3 text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.ExperimentalWarning`)}</div>+ <Button color="success" onClick={() => void enable()}>{t(`${tk}.EnableButton`)}</Button>+ </>+ )}+ </SecuritySection>+ );+});+QuickVaultUnlockSection.displayName = 'QuickVaultUnlockSection';++export default QuickVaultUnlockSection;diff --git a/apps/web/src/components/settings/security/RecentAuthLogsSection.tsx b/apps/web/src/components/settings/security/RecentAuthLogsSection.tsxnew file mode 100644index 000000000..65556278f--- /dev/null+++ b/apps/web/src/components/settings/security/RecentAuthLogsSection.tsx@@ -0,0 +1,72 @@+import { AuthEventType } from '@aliasvault/models/webapi';+import React, { useCallback, useImperativeHandle, useState, forwardRef } from 'react';+import { useTranslation } from 'react-i18next';++import LoadingIndicator from '@/components/loading/LoadingIndicator';+import SecuritySection, { formatDateTime, type SectionHandle } from '@/components/settings/security/SecuritySection';+import StatusPill from '@/components/shared/StatusPill';+import { useWebApi } from '@/context/WebApiContext';++import type { AuthLogModel } from '@aliasvault/models/webapi';++/** Auth logs shown, newest first. */+const MAX_AUTH_LOGS = 20;++/**+ * The latest login attempts.+ */+const RecentAuthLogsSection = forwardRef<SectionHandle>((_, ref) => {+ const { t } = useTranslation();+ const webApi = useWebApi();+ const [isLoading, setIsLoading] = useState(true);+ const [logs, setLogs] = useState<AuthLogModel[]>([]);+ const tk = 'components.main.settings.security.recentAuthLogsSection';++ const loadData = useCallback(async (): Promise<void> => {+ setIsLoading(true);+ try {+ const all = await webApi.getAuthLogs();+ setLogs([...all].sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()).slice(0, MAX_AUTH_LOGS));+ } finally {+ setIsLoading(false);+ }+ }, [webApi]);+ useImperativeHandle(ref, () => ({ loadData }), [loadData]);++ return (+ <SecuritySection title={t(`${tk}.Title`)}>+ <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">{t(`${tk}.Description`)}</p>+ {isLoading ? <LoadingIndicator /> : logs.length === 0 ? (+ <p className="text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.NoLogsMessage`)}</p>+ ) : (+ <div className="overflow-x-auto">+ <table className="w-full text-sm text-left text-gray-500 dark:text-gray-400">+ <thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">+ <tr>+ <th scope="col" className="px-6 py-3">{t(`${tk}.TimestampColumn`)}</th>+ <th scope="col" className="px-6 py-3">{t(`${tk}.EventTypeColumn`)}</th>+ <th scope="col" className="px-6 py-3">{t(`${tk}.ClientColumn`)}</th>+ <th scope="col" className="px-6 py-3">{t(`${tk}.IpAddressColumn`)}</th>+ <th scope="col" className="px-6 py-3">{t(`${tk}.SuccessColumn`)}</th>+ </tr>+ </thead>+ <tbody>+ {logs.map(log => (+ <tr key={log.id} className="bg-white border-b dark:bg-gray-800 dark:border-gray-700">+ <td className="px-6 py-4">{formatDateTime(log.timestamp)}</td>+ <td className="px-6 py-4">{AuthEventType[log.eventType] ?? log.eventType}</td>+ <td className="px-6 py-4">{log.client}</td>+ <td className="px-6 py-4">{log.ipAddress}</td>+ <td className="px-4 py-4"><StatusPill enabled={log.isSuccess} textTrue={t(`${tk}.SuccessStatus`)} textFalse={t(`${tk}.FailedStatus`)} /></td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </SecuritySection>+ );+});+RecentAuthLogsSection.displayName = 'RecentAuthLogsSection';++export default RecentAuthLogsSection;diff --git a/apps/web/src/components/settings/security/SecuritySection.tsx b/apps/web/src/components/settings/security/SecuritySection.tsxnew file mode 100644index 000000000..ddeac83d7--- /dev/null+++ b/apps/web/src/components/settings/security/SecuritySection.tsx@@ -0,0 +1,26 @@+import React from 'react';++/**+ * What the security page can ask a section to do.+ */+export type SectionHandle = {+ /** Reload the section's data. */+ loadData: () => Promise<void>;+};++/**+ * "g" date format: short date and time in the user's locale.+ */+export const formatDateTime = (value: string): string => new Date(value).toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' });++/**+ * Card holding one section of the security settings page.+ */+const SecuritySection: React.FC<{ title: string; children: React.ReactNode }> = ({ title, children }) => (+ <div className="p-4 mb-4 mx-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">+ <h3 className="mb-2 text-lg font-medium text-gray-900 dark:text-white">{title}</h3>+ {children}+ </div>+);++export default SecuritySection;diff --git a/apps/web/src/components/settings/security/TwoFactorAuthenticationSection.tsx b/apps/web/src/components/settings/security/TwoFactorAuthenticationSection.tsxnew file mode 100644index 000000000..3ed113b3a--- /dev/null+++ b/apps/web/src/components/settings/security/TwoFactorAuthenticationSection.tsx@@ -0,0 +1,50 @@+import React, { useCallback, useImperativeHandle, useState, forwardRef } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';++import LoadingIndicator from '@/components/loading/LoadingIndicator';+import SecuritySection, { type SectionHandle } from '@/components/settings/security/SecuritySection';+import Button from '@/components/shared/Button';+import { useWebApi } from '@/context/WebApiContext';++/**+ * Two-factor status with links to enable or disable it.+ */+const TwoFactorAuthenticationSection = forwardRef<SectionHandle>((_, ref) => {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const webApi = useWebApi();+ const [isLoading, setIsLoading] = useState(true);+ const [enabled, setEnabled] = useState(false);+ const tk = 'components.main.settings.security.twoFactorAuthenticationSection';++ const loadData = useCallback(async (): Promise<void> => {+ setIsLoading(true);+ try {+ const status = await webApi.get<{ twoFactorEnabled: boolean }>('TwoFactorAuth/status');+ setEnabled(status.twoFactorEnabled);+ } finally {+ setIsLoading(false);+ }+ }, [webApi]);+ useImperativeHandle(ref, () => ({ loadData }), [loadData]);++ return (+ <SecuritySection title={t(`${tk}.Title`)}>+ {isLoading ? <LoadingIndicator /> : enabled ? (+ <>+ <div className="mb-3 text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.EnabledMessage`)}</div>+ <Button color="danger" onClick={() => navigate('/settings/security/disable-2fa')}>{t(`${tk}.DisableButton`)}</Button>+ </>+ ) : (+ <>+ <div className="mb-3 text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.DisabledMessage`)}</div>+ <Button color="success" onClick={() => navigate('/settings/security/enable-2fa')}>{t(`${tk}.EnableButton`)}</Button>+ </>+ )}+ </SecuritySection>+ );+});+TwoFactorAuthenticationSection.displayName = 'TwoFactorAuthenticationSection';++export default TwoFactorAuthenticationSection;