Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor (#541)
Leendert de Borstaa1df77400e1
diff --git a/browser-extensions/chrome/eslint.config.js b/browser-extensions/chrome/eslint.config.jsindex 8aaa5c6d1..4ed5be7f4 100644--- a/browser-extensions/chrome/eslint.config.js+++ b/browser-extensions/chrome/eslint.config.js@@ -76,6 +76,7 @@ export default [{languageOptions: {globals: {+ NodeJS: true,...globals.node,...globals.browser,chrome: 'readonly',diff --git a/browser-extensions/chrome/src/App.tsx b/browser-extensions/chrome/src/App.tsxindex 3872f15f6..60d21fd9a 100644--- a/browser-extensions/chrome/src/App.tsx+++ b/browser-extensions/chrome/src/App.tsx@@ -13,28 +13,35 @@ import './styles/app.css';* Main application component*/const App: React.FC = () => {- const { isLoggedIn, isInitialized, username, logout } = useAuth();+ const authContext = useAuth();const dbContext = useDb();const [needsUnlock, setNeedsUnlock] = useState(false);const [showSettings, setShowSettings] = useState(false);++ /**+ * Loading state with minimum duration, shown when opening the extension popup.+ */const [isLoading, setIsLoading] = useMinDurationLoading(true, 200);/**- * Check if the user needs to unlock the vault+ * Check if the user needs to unlock the vault.*/useEffect(() => {- if (isLoggedIn && isInitialized && dbContext.dbAvailable && dbContext.dbInitialized) {+ if (authContext.isLoggedIn && authContext.isInitialized && dbContext.dbAvailable && dbContext.dbInitialized) {setNeedsUnlock(false);} else {setNeedsUnlock(true);}- }, [isLoggedIn, dbContext.dbInitialized, dbContext.dbAvailable, isInitialized]);+ }, [authContext.isLoggedIn, dbContext.dbInitialized, dbContext.dbAvailable, authContext.isInitialized]);+ /**+ * Set loading state to false when auth and db are initialized.+ */useEffect(() => {- if (isInitialized && dbContext.dbInitialized) {+ if (authContext.isInitialized && dbContext.dbInitialized) {setIsLoading(false);}- }, [isInitialized, dbContext.dbInitialized, setIsLoading]);+ }, [authContext.isInitialized, dbContext.dbInitialized, setIsLoading]);/*** Handle logout@@ -42,7 +49,7 @@ const App: React.FC = () => {const handleLogout = async (): Promise<void> => {setIsLoading(true);try {- await logout();+ await authContext.logout();} finally {setIsLoading(false);}@@ -95,14 +102,14 @@ const App: React.FC = () => {}return (- <div className="min-h-screen min-w-[350px] bg-white dark:bg-gray-800">- <div className="border-b border-gray-200 dark:border-gray-700">+ <div className="min-h-screen min-w-[350px] bg-white dark:bg-gray-900">+ <div className="border-b border-gray-200 dark:border-gray-700 dark:bg-gray-800"><div className="flex justify-between items-center px-4 py-3"><div className="flex items-center"><img src="/assets/images/logo.svg" alt="AliasVault" className="h-8 w-8 mr-2" /><h1 className="text-gray-900 dark:text-white text-xl font-bold">AliasVault</h1></div>- {!isLoggedIn ? (+ {!authContext.isLoggedIn ? (<buttonid="settings"onClick={toggleSettings}@@ -122,10 +129,10 @@ const App: React.FC = () => {</div></div>- <div className="p-4">- {isLoggedIn ? (+ <div className="p-4 dark:bg-gray-900">+ {authContext.isLoggedIn ? (<div className="mt-4">- <p className="text-gray-700 dark:text-gray-200 text-lg mb-4">Logged in as {username}</p>+ <p className="text-gray-700 dark:text-gray-200 text-lg mb-4">Logged in as {authContext.username}</p>{needsUnlock ? (<Unlock />) : (diff --git a/browser-extensions/chrome/src/contentScript.ts b/browser-extensions/chrome/src/contentScript.tsindex a2f3328eb..8c212208f 100644--- a/browser-extensions/chrome/src/contentScript.ts+++ b/browser-extensions/chrome/src/contentScript.ts@@ -69,10 +69,10 @@ function createPopup(input: HTMLInputElement, credentials: Credential[]) : void// Handle base64 image dataif (cred.Logo) {try {- const base64Logo = Buffer.from(cred.Logo).toString('base64');+ const base64Logo = base64Encode(cred.Logo);imgElement.src = `data:image/x-icon;base64,${base64Logo}`;} catch (error) {- console.error('Error encoding logo:', error);+ console.error('Error setting logo:', error);imgElement.src = `data:image/x-icon;base64,${placeholderBase64}`;}} else {@@ -136,3 +136,26 @@ function triggerInputEvents(element: HTMLInputElement) : void {element.dispatchEvent(new Event('input', { bubbles: true }));element.dispatchEvent(new Event('change', { bubbles: true }));}++/**+ * Base64 encode binary data.+ */+function base64Encode(buffer: Uint8Array): string | null {+ if (!buffer || typeof buffer !== 'object') {+ return null;+ }++ try {+ // Convert object to array of numbers+ const byteArray = Object.values(buffer);++ // Convert to binary string+ const binary = String.fromCharCode.apply(null, byteArray as number[]);++ // Use btoa to encode binary string to base64+ return btoa(binary);+ } catch (error) {+ console.error('Error encoding to base64:', error);+ return null;+ }+}\ No newline at end of filediff --git a/browser-extensions/chrome/src/context/AuthContext.tsx b/browser-extensions/chrome/src/context/AuthContext.tsxindex 0d6e47140..c6e2bb2a1 100644--- a/browser-extensions/chrome/src/context/AuthContext.tsx+++ b/browser-extensions/chrome/src/context/AuthContext.tsx@@ -11,10 +11,13 @@ type AuthContextType = {getRefreshToken: () => string | null;}+/**+ * Auth context.+ */const AuthContext = createContext<AuthContextType | undefined>(undefined);/**- * AuthProvider+ * AuthProvider to provide the authentication state to the app that components can use.*/export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {const [isLoggedIn, setIsLoggedIn] = useState(false);@@ -24,8 +27,11 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst [, setRefreshToken] = useState<string | null>(null);const accessTokenRef = useRef<string | null>(null);const refreshTokenRef = useRef<string | null>(null);++ /**+ * Check for tokens in localStorage on initial load+ */useEffect(() : void => {- // Check for tokens in localStorage on initial loadconst storedAccessToken = localStorage.getItem('accessToken');const storedRefreshToken = localStorage.getItem('refreshToken');const storedUsername = localStorage.getItem('username');diff --git a/browser-extensions/chrome/src/context/DbContext.tsx b/browser-extensions/chrome/src/context/DbContext.tsxindex 18dfd1b20..87da5f06c 100644--- a/browser-extensions/chrome/src/context/DbContext.tsx+++ b/browser-extensions/chrome/src/context/DbContext.tsx@@ -12,15 +12,19 @@ type DbContextType = {const DbContext = createContext<DbContextType | undefined>(undefined);/**- * DbProvider+ * DbProvider to provide the SQLite client to the app that components can use to make database queries.*/export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ /**+ * SQLite client.+ */const [sqliteClient, setSqliteClient] = useState<SqliteClient | null>(null);/*** Database initialization state. If true, the database has been initialized and the dbAvailable state is correct.*/const [dbInitialized, setDbInitialized] = useState(false);+/*** Database availability state. If true, the database is available. If false, the database is not available and needs to be unlocked or retrieved again from the API.*/@@ -67,14 +71,18 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }}}, []);+ /**+ * Check if database is initialized and try to retrieve vault from background+ */useEffect(() : void => {- // Check if database is initialized and try to retrieve vault from backgroundif (!dbInitialized) {checkStoredVault();}}, [dbInitialized, checkStoredVault]);- // Add a listener for when the popup becomes visible+ /**+ * Add a listener for when the popup becomes visible+ */useEffect(() : void => {/*** Handles visibility state changes of the document.@@ -93,7 +101,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }}, [dbInitialized, checkStoredVault]);/**- * Clear database+ * Clear database and remove from background worker, called when logging out.*/const clearDatabase = () : void => {setSqliteClient(null);diff --git a/browser-extensions/chrome/src/context/LoadingContext.tsx b/browser-extensions/chrome/src/context/LoadingContext.tsxindex 8db97d76f..a1acbe504 100644--- a/browser-extensions/chrome/src/context/LoadingContext.tsx+++ b/browser-extensions/chrome/src/context/LoadingContext.tsx@@ -7,6 +7,9 @@ type LoadingContextType = {hideLoading: () => void;}+/**+ * Loading context.+ */const LoadingContext = createContext<LoadingContextType | undefined>(undefined);/**@@ -15,8 +18,15 @@ const LoadingContext = createContext<LoadingContextType | undefined>(undefined);export const LoadingProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {const [isLoading, setIsLoading] = useState(false);- const showLoading = () => setIsLoading(true);- const hideLoading = () => setIsLoading(false);+ /**+ * Show loading spinner+ */+ const showLoading = (): void => setIsLoading(true);++ /**+ * Hide loading spinner+ */+ const hideLoading = (): void => setIsLoading(false);return (<LoadingContext.Provider value={{ isLoading, showLoading, hideLoading }}>@@ -26,7 +36,10 @@ export const LoadingProvider: React.FC<{ children: React.ReactNode }> = ({ child);};-export const useLoading = () => {+/**+ * Hook to use loading state+ */+export const useLoading = (): LoadingContextType => {const context = useContext(LoadingContext);if (context === undefined) {throw new Error('useLoading must be used within a LoadingProvider');diff --git a/browser-extensions/chrome/src/context/WebApiContext.tsx b/browser-extensions/chrome/src/context/WebApiContext.tsxindex 210bd801a..a8d5aa592 100644--- a/browser-extensions/chrome/src/context/WebApiContext.tsx+++ b/browser-extensions/chrome/src/context/WebApiContext.tsx@@ -5,12 +5,15 @@ import { useAuth } from './AuthContext';const WebApiContext = createContext<WebApiService | null>(null);/**- * WebApiProvider+ * WebApiProvider to provide the WebApiService to the app that components can use.*/export const WebApiProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {const { getAccessToken, getRefreshToken, updateTokens, logout } = useAuth();const [webApiService, setWebApiService] = useState<WebApiService | null>(null);+ /**+ * Initialize WebApiService+ */useEffect(() : void => {const service = new WebApiService(() => getAccessToken(),diff --git a/browser-extensions/chrome/src/hooks/useMinDurationLoading.ts b/browser-extensions/chrome/src/hooks/useMinDurationLoading.tsindex f58919a95..6f6ee9f41 100644--- a/browser-extensions/chrome/src/hooks/useMinDurationLoading.ts+++ b/browser-extensions/chrome/src/hooks/useMinDurationLoading.ts@@ -13,8 +13,8 @@ export const useMinDurationLoading = (minDuration: number = 300): [boolean, (value: boolean) => void] => {const [isLoading, setIsLoading] = useState(initialState);- const timeoutRef = useRef<NodeJS.Timeout>();- const startTimeRef = useRef<number>();+ const timeoutRef = useRef<NodeJS.Timeout | null>(null);+ const startTimeRef = useRef<number | null>(null);const setLoadingState = useCallback((value: boolean) => {if (value) {@@ -45,10 +45,10 @@ export const useMinDurationLoading = (setIsLoading(true);startTimeRef.current = Date.now();}- }, []); // Empty dependency array ensures this only runs once+ }, [initialState, setIsLoading]);useEffect(() => {- return () => {+ return (): void => {if (timeoutRef.current) {clearTimeout(timeoutRef.current);}diff --git a/browser-extensions/chrome/src/pages/CredentialsList.tsx b/browser-extensions/chrome/src/pages/CredentialsList.tsxindex 2c7d3c039..b4fed214b 100644--- a/browser-extensions/chrome/src/pages/CredentialsList.tsx+++ b/browser-extensions/chrome/src/pages/CredentialsList.tsx@@ -3,14 +3,10 @@ import { useDb } from '../context/DbContext';import { Credential } from '../types/Credential';import { Buffer } from 'buffer';-type CredentialsListProps = {- base64Encode: (buffer: Uint8Array) => string | null;-}-/*** Credentials list page*/-const CredentialsList: React.FC<CredentialsListProps> = () => {+const CredentialsList: React.FC = () => {const dbContext = useDb();const [credentials, setCredentials] = useState<Credential[]>([]);@@ -26,8 +22,8 @@ const CredentialsList: React.FC<CredentialsListProps> = () => {}, [dbContext.sqliteClient]);return (- <div className="bg-white dark:bg-gray-700 rounded-lg p-4 mb-4 shadow-lg">- <h2 className="text-gray-900 dark:text-white text-xl mb-4">Your Credentials</h2>+ <div>+ <h2 className="text-gray-900 dark:text-white text-xl mb-4">Credentials</h2>{credentials.length === 0 ? (<p className="text-gray-500 dark:text-gray-400">No credentials found</p>) : (diff --git a/browser-extensions/chrome/src/pages/Login.tsx b/browser-extensions/chrome/src/pages/Login.tsxindex 11a89e9a3..7730fbcba 100644--- a/browser-extensions/chrome/src/pages/Login.tsx+++ b/browser-extensions/chrome/src/pages/Login.tsx@@ -13,7 +13,8 @@ import { useLoading } from '../context/LoadingContext';* Login page*/const Login: React.FC = () => {- const { login } = useAuth();+ const authContext = useAuth();+ const dbContext = useDb();const [credentials, setCredentials] = useState({username: '',password: '',@@ -21,9 +22,7 @@ const Login: React.FC = () => {const { showLoading, hideLoading } = useLoading();const [rememberMe, setRememberMe] = useState(false);const [error, setError] = useState<string | null>(null);- const dbContext = useDb();const webApi = useWebApi();- // Create SrpUtility instance with webApiconst srpUtil = new SrpUtility(webApi);/**@@ -60,7 +59,7 @@ const Login: React.FC = () => {// Store access and refresh token using the contextif (validationResponse.token) {// Store auth info- await login(credentials.username, validationResponse.token.token, validationResponse.token.refreshToken);+ await authContext.login(credentials.username, validationResponse.token.token, validationResponse.token.refreshToken);} else {throw new Error('Login failed -- no token returned');}diff --git a/browser-extensions/chrome/src/pages/Unlock.tsx b/browser-extensions/chrome/src/pages/Unlock.tsxindex 3088f987c..0d77d35f0 100644--- a/browser-extensions/chrome/src/pages/Unlock.tsx+++ b/browser-extensions/chrome/src/pages/Unlock.tsx@@ -7,30 +7,31 @@ import Button from '../components/Button';import EncryptionUtility from '../utils/EncryptionUtility';import SrpUtility from '../utils/SrpUtility';import { VaultResponse } from '../types/webapi/VaultResponse';+import { useLoading } from '../context/LoadingContext';/*** Unlock page*/const Unlock: React.FC = () => {- const { username, logout } = useAuth();+ const authContext = useAuth();+ const dbContext = useDb();+const webApi = useWebApi();- // Create SrpUtility instance with webApiconst srpUtil = new SrpUtility(webApi);const [password, setPassword] = useState('');const [error, setError] = useState<string | null>(null);- const dbContext = useDb();-+ const { showLoading, hideLoading } = useLoading();/*** Handle submit*/const handleSubmit = async (e: React.FormEvent) : Promise<void> => {e.preventDefault();setError(null);-+ showLoading();try {// 1. Initiate login to get salt and server ephemeral- const loginResponse = await srpUtil.initiateLogin(username!);+ const loginResponse = await srpUtil.initiateLogin(authContext.username!);// Derive key from password using user's encryption settingsconst passwordHash = await EncryptionUtility.deriveKeyFromPassword(@@ -55,6 +56,8 @@ const Unlock: React.FC = () => {} catch (err) {setError('Failed to unlock vault. Please check your password and try again.');console.error('Unlock error:', err);+ } finally {+ hideLoading();}};@@ -62,7 +65,12 @@ const Unlock: React.FC = () => {* Handle logout*/const handleLogout = async () : Promise<void> => {- logout();+ showLoading();+ try {+ await authContext.logout();+ } finally {+ hideLoading();+ }};return (@@ -70,7 +78,7 @@ const Unlock: React.FC = () => {<form onSubmit={handleSubmit} className="bg-white dark:bg-gray-700 w-full shadow-md rounded px-8 pt-6 pb-8 mb-4"><div className="flex space-x-4 mb-6"><img className="w-8 h-8 rounded-full" src="/assets/images/avatar.webp" alt="User avatar" />- <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{username}</h2>+ <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{authContext.username}</h2></div><p className="text-base text-gray-500 dark:text-gray-200 mb-6">diff --git a/src/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.csindex 96de53e55..97d4ed731 100644--- a/src/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.cs+++ b/src/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.cs@@ -130,7 +130,7 @@ public class ChromeExtensionTests : ClientPlaywrightTest}serviceWorkers = serviceWorkersEnumerable.ToList();- if (!serviceWorkers.Any())+ if (serviceWorkers.Count == 0){throw new InvalidOperationException("No extension service workers found");}