Skip to content

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

Add web app contexts and hooks (#2413)

Leendert de Borstd7a8766d0041
diff --git a/apps/web/src/context/AppContext.tsx b/apps/web/src/context/AppContext.tsx
index ddf70d115..48460cc65 100644
--- a/apps/web/src/context/AppContext.tsx
+++ b/apps/web/src/context/AppContext.tsx
@@ -3,8 +3,10 @@ import React, { createContext, useContext, useMemo, useCallback, useEffect, useS
import { useTranslation } from 'react-i18next';
import { useAuth } from '@/context/AuthContext';
+import { useDb } from '@/context/DbContext';
import { useWebApi } from '@/context/WebApiContext';
import { vaultStateEvents } from '@/events/VaultStateEvents';
+import { vaultStore } from '@/vault/VaultStore';
type AppContextType = {
isLoggedIn: boolean;
@@ -25,6 +27,7 @@ const AppContext = createContext<AppContextType | undefined>(undefined);
export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const auth = useAuth();
const webApi = useWebApi();
+ const { clearDatabase } = useDb();
const [isLoggedIn, setIsLoggedIn] = useState(false);
const isLoggingOutRef = useRef(false);
const { t } = useTranslation();
@@ -83,12 +86,16 @@ export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children
initializeAuth();
}, [initializeAuth]);
- // Reflect logouts from other tabs.
+ /*
+ * Reflect a logout from this tab or another one.
+ */
useEffect(() => {
return vaultStateEvents.onLoggedOut(() => {
+ clearDatabase();
+ void vaultStore.lockVault();
setIsLoggedIn(false);
});
- }, []);
+ }, [clearDatabase]);
const contextValue = useMemo(() => ({
isInitialized: auth.isInitialized,
diff --git a/apps/web/src/context/CapabilityContext.tsx b/apps/web/src/context/CapabilityContext.tsx
new file mode 100644
index 000000000..c5fe192f5
--- /dev/null
+++ b/apps/web/src/context/CapabilityContext.tsx
@@ -0,0 +1,73 @@
+import { type Capabilities, CapabilityService } from '@aliasvault/client/api/CapabilityService';
+import { type CapabilityKey, isCapabilityEnabled } from '@aliasvault/models/webapi';
+import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
+import { Navigate } from 'react-router-dom';
+
+type CapabilityContextType = {
+ isEnabled: (key: CapabilityKey) => boolean;
+ isLoaded: boolean;
+}
+
+const CapabilityContext = createContext<CapabilityContextType | undefined>(undefined);
+
+/**
+ * Serves this account's capabilities to the UI.
+ */
+export const CapabilityProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const [capabilities, setCapabilities] = useState<Capabilities>({});
+ const [isLoaded, setIsLoaded] = useState(false);
+
+ useEffect(() => {
+ CapabilityService.getAll().then((stored) => {
+ setCapabilities(stored);
+ setIsLoaded(true);
+ });
+
+ return CapabilityService.watch(setCapabilities);
+ }, []);
+
+ const isEnabled = useCallback((key: CapabilityKey): boolean => isCapabilityEnabled(capabilities[key]), [capabilities]);
+
+ const value = useMemo(() => ({ isEnabled, isLoaded }), [isEnabled, isLoaded]);
+
+ return (
+ <CapabilityContext.Provider value={value}>
+ {children}
+ </CapabilityContext.Provider>
+ );
+};
+
+/**
+ * The capability check for this account.
+ */
+export const useCapabilities = (): CapabilityContextType['isEnabled'] => {
+ return useCapabilityContext().isEnabled;
+};
+
+/**
+ * Renders a page only for accounts the capability is on for.
+ * @param root0 - the capability to require and the page to render.
+ * @param root0.capability - the capability the page needs.
+ * @param root0.children - the page.
+ */
+export const RequireCapability: React.FC<{ capability: CapabilityKey; children: React.ReactNode }> = ({ capability, children }) => {
+ const { isEnabled, isLoaded } = useCapabilityContext();
+
+ if (!isLoaded) {
+ return null;
+ }
+
+ return isEnabled(capability) ? <>{children}</> : <Navigate to="/" replace />;
+};
+
+/**
+ * The capabilities of this account.
+ */
+const useCapabilityContext = (): CapabilityContextType => {
+ const context = useContext(CapabilityContext);
+ if (context === undefined) {
+ throw new Error('useCapabilities must be used within a CapabilityProvider');
+ }
+
+ return context;
+};
diff --git a/apps/web/src/context/NotificationContext.tsx b/apps/web/src/context/NotificationContext.tsx
new file mode 100644
index 000000000..6d3795228
--- /dev/null
+++ b/apps/web/src/context/NotificationContext.tsx
@@ -0,0 +1,83 @@
+import React, { createContext, useCallback, useContext, useMemo, useRef, useState } from 'react';
+
+/**
+ * A queued notification.
+ */
+export type Notification = {
+ type: 'success' | 'error';
+ message: string;
+};
+
+type NotificationContextType = {
+ addSuccessMessage: (message: string, notify?: boolean) => void;
+ addErrorMessage: (message: string, notify?: boolean) => void;
+ clearMessages: () => void;
+ takeMessages: () => Notification[];
+ version: number;
+}
+
+const NotificationContext = createContext<NotificationContextType | undefined>(undefined);
+
+/**
+ * Global notifications: messages are queued here and rendered inline at the top of the page.
+ */
+export const NotificationProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const queue = useRef<Notification[]>([]);
+ const [version, setVersion] = useState(0);
+
+ /**
+ * Queue a message.
+ */
+ const add = useCallback((notification: Notification, notify: boolean): void => {
+ queue.current = [...queue.current, notification];
+ if (notify) {
+ setVersion(v => v + 1);
+ }
+ }, []);
+
+ /**
+ * Queue a success message.
+ */
+ const addSuccessMessage = useCallback((message: string, notify: boolean = false): void => add({ type: 'success', message }, notify), [add]);
+
+ /**
+ * Queue an error message.
+ */
+ const addErrorMessage = useCallback((message: string, notify: boolean = false): void => add({ type: 'error', message }, notify), [add]);
+
+ /**
+ * Drop every queued message and clear what is shown.
+ */
+ const clearMessages = useCallback((): void => {
+ queue.current = [];
+ setVersion(v => v + 1);
+ }, []);
+
+ /**
+ * Take the queued messages off the queue.
+ */
+ const takeMessages = useCallback((): Notification[] => {
+ const messages = queue.current;
+ queue.current = [];
+ return messages;
+ }, []);
+
+ const value = useMemo(() => ({ addSuccessMessage, addErrorMessage, clearMessages, takeMessages, version }), [addSuccessMessage, addErrorMessage, clearMessages, takeMessages, version]);
+
+ return (
+ <NotificationContext.Provider value={value}>
+ {children}
+ </NotificationContext.Provider>
+ );
+};
+
+/**
+ * Hook to use the global notifications.
+ */
+export const useNotifications = (): NotificationContextType => {
+ const context = useContext(NotificationContext);
+ if (context === undefined) {
+ throw new Error('useNotifications must be used within a NotificationProvider');
+ }
+ return context;
+};
diff --git a/apps/web/src/context/WebApiContext.tsx b/apps/web/src/context/WebApiContext.tsx
new file mode 100644
index 000000000..aef42d3f5
--- /dev/null
+++ b/apps/web/src/context/WebApiContext.tsx
@@ -0,0 +1,28 @@
+import { WebApiService } from '@aliasvault/client/api/WebApiService';
+import React, { createContext, useContext, useState } from 'react';
+
+const WebApiContext = createContext<WebApiService | null>(null);
+
+/**
+ * WebApiProvider to provide the WebApiService to the app that components can use.
+ */
+export const WebApiProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const [webApiService] = useState<WebApiService>(() => new WebApiService());
+
+ return (
+ <WebApiContext.Provider value={webApiService}>
+ {children}
+ </WebApiContext.Provider>
+ );
+};
+
+/**
+ * Hook to use the WebApiService.
+ */
+export const useWebApi = (): WebApiService => {
+ const context = useContext(WebApiContext);
+ if (!context) {
+ throw new Error('useWebApi must be used within a WebApiProvider');
+ }
+ return context;
+};
diff --git a/apps/web/src/events/VaultStateEvents.ts b/apps/web/src/events/VaultStateEvents.ts
new file mode 100644
index 000000000..95d4e936d
--- /dev/null
+++ b/apps/web/src/events/VaultStateEvents.ts
@@ -0,0 +1,20 @@
+import { getPlatform } from '@aliasvault/client/platform';
+
+import { StorageKeys } from '@/utils/StorageKeys';
+
+type Unsubscribe = () => void;
+type Listener = () => void;
+
+/**
+ * Vault state events. The access token is stored for every tab, so a logout reaches all open tabs.
+ */
+export const vaultStateEvents = {
+ /** Fires when the user is logged out in any tab. */
+ onLoggedOut(listener: Listener): Unsubscribe {
+ return getPlatform().storage.watch<string | null>(StorageKeys.ACCESS_TOKEN, (newValue) => {
+ if (!newValue) {
+ listener();
+ }
+ });
+ },
+};
diff --git a/apps/web/src/hooks/useClickOutside.ts b/apps/web/src/hooks/useClickOutside.ts
new file mode 100644
index 000000000..9606f5975
--- /dev/null
+++ b/apps/web/src/hooks/useClickOutside.ts
@@ -0,0 +1,29 @@
+import { useEffect, type RefObject } from 'react';
+
+/**
+ * Call `onClose` when a mouse click lands outside every given element.
+ * @param refs - the elements that count as "inside"
+ * @param onClose - what to do on an outside click
+ * @param enabled - whether to listen at all
+ */
+export function useClickOutside(refs: RefObject<HTMLElement | null>[], onClose: () => void, enabled: boolean = true): void {
+ useEffect(() => {
+ if (!enabled) {
+ return;
+ }
+
+ /**
+ * Close when the click target is not inside any of the elements.
+ */
+ const handleClick = (event: MouseEvent): void => {
+ const target = event.target as Node;
+ if (refs.some(ref => ref.current?.contains(target))) {
+ return;
+ }
+ onClose();
+ };
+
+ document.addEventListener('mousedown', handleClick);
+ return (): void => document.removeEventListener('mousedown', handleClick);
+ }, [refs, onClose, enabled]);
+}
diff --git a/apps/web/src/hooks/useClipboardCopy.ts b/apps/web/src/hooks/useClipboardCopy.ts
new file mode 100644
index 000000000..59b404bd5
--- /dev/null
+++ b/apps/web/src/hooks/useClipboardCopy.ts
@@ -0,0 +1,25 @@
+import { useCallback, useEffect, useState } from 'react';
+
+import { useDb } from '@/context/DbContext';
+import { clipboardCopyService } from '@/utils/ClipboardCopyService';
+
+const DEFAULT_CLIPBOARD_CLEAR_SECONDS = 10;
+
+/**
+ * Copy a value to the clipboard and know whether this element is the one that was copied last.
+ * @param id - the id of the element the value belongs to
+ */
+export function useClipboardCopy(id: string): { copied: boolean; copyToClipboard: (value: string) => Promise<void> } {
+ const dbContext = useDb();
+ const [copied, setCopied] = useState(clipboardCopyService.getCopiedId() === id);
+
+ useEffect(() => clipboardCopyService.subscribe((copiedId) => setCopied(copiedId === id)), [id]);
+
+ const copyToClipboard = useCallback(async (value: string): Promise<void> => {
+ const stored = dbContext.sqliteClient?.settings.getSetting('ClipboardClearSeconds', String(DEFAULT_CLIPBOARD_CLEAR_SECONDS));
+ const clearAfterSeconds = Number.parseInt(stored ?? '', 10);
+ await clipboardCopyService.copy(id, value, Number.isNaN(clearAfterSeconds) ? DEFAULT_CLIPBOARD_CLEAR_SECONDS : clearAfterSeconds);
+ }, [dbContext.sqliteClient, id]);
+
+ return { copied, copyToClipboard };
+}
diff --git a/apps/web/src/hooks/useEmailDomains.ts b/apps/web/src/hooks/useEmailDomains.ts
new file mode 100644
index 000000000..e23f4e59c
--- /dev/null
+++ b/apps/web/src/hooks/useEmailDomains.ts
@@ -0,0 +1,53 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+
+import { useDb } from '@/context/DbContext';
+
+/**
+ * Domain checks: which addresses AliasVault or SpamOK can receive mail for.
+ */
+export type EmailDomainChecks = {
+ /** Whether the domains are known yet. */
+ isLoaded: boolean;
+ isSpamOkDomain: (email: string) => boolean;
+ isAliasVaultDomain: (email: string) => boolean;
+ isAliasVaultSupportedDomain: (email: string) => boolean;
+};
+
+/**
+ * Whether an address ends in one of the domains.
+ */
+const endsWithDomain = (email: string, domains: string[]): boolean => {
+ const lower = email.toLowerCase();
+ return domains.some(domain => lower.endsWith('@' + domain.toLowerCase()));
+};
+
+/**
+ * The email domains this instance serves, from the vault metadata the sync recorded.
+ */
+export function useEmailDomains(): EmailDomainChecks {
+ const dbContext = useDb();
+ const [publicDomains, setPublicDomains] = useState<string[]>([]);
+ const [privateDomains, setPrivateDomains] = useState<string[]>([]);
+ const [isLoaded, setIsLoaded] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ void dbContext.getVaultMetadata().then((metadata) => {
+ if (cancelled) {
+ return;
+ }
+ setPublicDomains(metadata?.publicEmailDomains ?? []);
+ setPrivateDomains(metadata?.privateEmailDomains ?? []);
+ setIsLoaded(true);
+ });
+ return (): void => {
+ cancelled = true;
+ };
+ }, [dbContext]);
+
+ const isSpamOkDomain = useCallback((email: string): boolean => endsWithDomain(email, publicDomains), [publicDomains]);
+ const isAliasVaultDomain = useCallback((email: string): boolean => endsWithDomain(email, privateDomains), [privateDomains]);
+ const isAliasVaultSupportedDomain = useCallback((email: string): boolean => isSpamOkDomain(email) || isAliasVaultDomain(email), [isAliasVaultDomain, isSpamOkDomain]);
+
+ return useMemo(() => ({ isLoaded, isSpamOkDomain, isAliasVaultDomain, isAliasVaultSupportedDomain }), [isAliasVaultDomain, isAliasVaultSupportedDomain, isLoaded, isSpamOkDomain]);
+}
diff --git a/apps/web/src/hooks/useKeyboardShortcut.ts b/apps/web/src/hooks/useKeyboardShortcut.ts
new file mode 100644
index 000000000..9d9bd96f6
--- /dev/null
+++ b/apps/web/src/hooks/useKeyboardShortcut.ts
@@ -0,0 +1,52 @@
+import { useEffect } from 'react';
+
+/** How long the first key of a two-key chord stays armed. */
+const CHORD_TIMEOUT_MS = 1000;
+
+/**
+ * Whether the keyboard focus is in a text field, where chords must not fire.
+ */
+const isTypingTarget = (): boolean => {
+ const element = document.activeElement;
+ if (!element) {
+ return false;
+ }
+ const tag = element.tagName;
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (element as HTMLElement).isContentEditable;
+};
+
+/**
+ * Register a two-key chord such as "gc" (the Blazor KeyboardShortcutService).
+ * @param chord - the two keys, e.g. 'gc'
+ * @param handler - what to run when the chord is pressed
+ */
+export function useKeyboardShortcut(chord: string, handler: () => void): void {
+ useEffect(() => {
+ let firstKeyAt: number | null = null;
+ const [first, second] = chord.split('');
+
+ /**
+ * Track the chord.
+ */
+ const onKeyDown = (event: KeyboardEvent): void => {
+ if (event.ctrlKey || event.metaKey || event.altKey || isTypingTarget()) {
+ return;
+ }
+ const key = event.key.toLowerCase();
+ if (key === first && (firstKeyAt === null || Date.now() - firstKeyAt > CHORD_TIMEOUT_MS)) {
+ firstKeyAt = Date.now();
+ return;
+ }
+ if (key === second && firstKeyAt !== null && Date.now() - firstKeyAt <= CHORD_TIMEOUT_MS) {
+ firstKeyAt = null;
+ event.preventDefault();
+ handler();
+ return;
+ }
+ firstKeyAt = null;
+ };
+
+ document.addEventListener('keydown', onKeyDown);
+ return (): void => document.removeEventListener('keydown', onKeyDown);
+ }, [chord, handler]);
+}
diff --git a/apps/web/src/hooks/useMinDurationLoading.ts b/apps/web/src/hooks/useMinDurationLoading.ts
new file mode 100644
index 000000000..82c99098f
--- /dev/null
+++ b/apps/web/src/hooks/useMinDurationLoading.ts
@@ -0,0 +1,52 @@
+import { useState, useEffect, useCallback, useRef } from 'react';
+
+/**
+ * Hook that keeps a loading state true for a minimum duration, so a fast load does not flicker.
+ * @param initialState - initial loading state
+ * @param minDuration - minimum duration in milliseconds
+ * @returns [isLoading, setIsLoading]
+ */
+export const useMinDurationLoading = (initialState: boolean = false, minDuration: number = 300): [boolean, (value: boolean) => void] => {
+ const [isLoading, setIsLoading] = useState(initialState);
+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const startTimeRef = useRef<number | null>(null);
+
+ const setLoadingState = useCallback((value: boolean) => {
+ if (value) {
+ setIsLoading(true);
+ startTimeRef.current = Date.now();
+ return;
+ }
+
+ const elapsedTime = startTimeRef.current ? Date.now() - startTimeRef.current : 0;
+ const remainingTime = Math.max(0, minDuration - elapsedTime);
+
+ if (remainingTime === 0) {
+ setIsLoading(false);
+ } else {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+ timeoutRef.current = setTimeout(() => {
+ setIsLoading(false);
+ }, remainingTime);
+ }
+ }, [minDuration]);
+
+ useEffect(() => {
+ if (initialState) {
+ setIsLoading(true);
+ startTimeRef.current = Date.now();
+ }
+ }, [initialState]);
+
+ useEffect(() => {
+ return (): void => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+ };
+ }, []);
+
+ return [isLoading, setLoadingState];
+};