Skip to content

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

Linting fixes (#541)

Leendert de Borst1d59548df0b8
diff --git a/browser-extensions/chrome/background.ts b/browser-extensions/chrome/background.ts
index 56b13d958..2e1cf09b6 100644
--- a/browser-extensions/chrome/background.ts
+++ b/browser-extensions/chrome/background.ts
@@ -1,6 +1,6 @@
import { VaultState, initialVaultState } from './src/background/VaultState';
import { setupContextMenus, handleContextMenuClick } from './src/background/ContextMenu';
-import { handleClearVault, handleCreateIdentity, handleGetCredentials, handleGetVault, handleStoreVault } from './src/background/VaultMessageHandler';
+import { handleClearVault, handleCreateIdentity, handleGetCredentials, handleGetDefaultEmailDomain, handleGetDerivedKey, handleGetVault, handleStoreVault } from './src/background/VaultMessageHandler';
import { handleOpenPopup, handlePopupWithCredential } from './src/background/PopupMessageHandler';
let vaultState: VaultState = { ...initialVaultState };
@@ -33,6 +33,14 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
handleCreateIdentity(message, vaultState, sendResponse);
break;
+ case 'GET_DEFAULT_EMAIL_DOMAIN':
+ handleGetDefaultEmailDomain(vaultState, sendResponse);
+ break;
+
+ case 'GET_DERIVED_KEY':
+ handleGetDerivedKey(vaultState, sendResponse);
+ break;
+
// Popup-related messages
case 'OPEN_POPUP': {
handleOpenPopup(message, vaultState, sendResponse);
diff --git a/browser-extensions/chrome/src/App.tsx b/browser-extensions/chrome/src/App.tsx
index 8db048295..07bd3f93b 100644
--- a/browser-extensions/chrome/src/App.tsx
+++ b/browser-extensions/chrome/src/App.tsx
@@ -1,5 +1,5 @@
-import React, { useState, useEffect, useRef } from 'react';
-import { HashRouter as Router, Routes, Route, Navigate, useNavigate } from 'react-router-dom';
+import React, { useState, useEffect } from 'react';
+import { HashRouter as Router, Routes, Route } from 'react-router-dom';
import { useAuth } from './context/AuthContext';
import { useDb } from './context/DbContext';
import { useMinDurationLoading } from './hooks/useMinDurationLoading';
@@ -21,11 +21,13 @@ type RouteConfig = {
title?: string;
};
+/**
+ * App component.
+ */
const App: React.FC = () => {
const authContext = useAuth();
const dbContext = useDb();
const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
- const [clientUrl, setClientUrl] = useState('https://app.aliasvault.net');
const [currentTab, setCurrentTab] = useState<'credentials' | 'emails'>('credentials');
const [isLoading, setIsLoading] = useMinDurationLoading(true, 150);
@@ -48,10 +50,6 @@ const App: React.FC = () => {
}
}, [authContext.isInitialized, dbContext.dbInitialized, setIsLoading]);
- console.log('authContext.isLoggedIn', authContext.isInitialized);
- console.log('dbContext.dbInitialized', dbContext.dbInitialized);
- console.log('isLoading', isLoading);
-
if (isLoading) {
return (
<div className="min-h-screen min-w-[350px] bg-white dark:bg-gray-900 flex flex-col">
@@ -69,8 +67,6 @@ const App: React.FC = () => {
<div className="min-h-screen min-w-[350px] bg-white dark:bg-gray-900 flex flex-col">
<Header
authContext={authContext}
- clientUrl={clientUrl}
- handleRefresh={async () => {}}
toggleUserMenu={() => setIsUserMenuOpen(!isUserMenuOpen)}
isUserMenuOpen={isUserMenuOpen}
routes={routes}
diff --git a/browser-extensions/chrome/src/background/VaultMessageHandler.ts b/browser-extensions/chrome/src/background/VaultMessageHandler.ts
index 995b77855..2310687c1 100644
--- a/browser-extensions/chrome/src/background/VaultMessageHandler.ts
+++ b/browser-extensions/chrome/src/background/VaultMessageHandler.ts
@@ -233,4 +233,73 @@ export function getEmailAddressesForVault(
const domain = email.split('@')[1];
return vaultState.privateEmailDomains.includes(domain);
});
-}
\ No newline at end of file
+}
+
+/**
+ * Get default email domain for a vault.
+ */
+export function handleGetDefaultEmailDomain(
+ vaultState: VaultState,
+ sendResponse: (response: any) => void
+) : void {
+ if (!vaultState.derivedKey) {
+ sendResponse({ domain: null });
+ return;
+ }
+
+ /*
+ * TODO: usage between chrome storage session and vaultState is
+ * now mixed. Determine where to store the domain lists and avoid
+ * storing it in multiple places when it's not needed.
+ */
+ chrome.storage.session.get(['publicEmailDomains', 'privateEmailDomains'], (result) => {
+ const privateEmailDomains = result.privateEmailDomains || [];
+ const publicEmailDomains = result.publicEmailDomains || [];
+
+ /*
+ * TODO: add vault preference settings to determine which domain to use
+ * taking into account vault settings.
+ */
+
+ // Function to check if a domain is valid
+ /**
+ *
+ */
+ const isValidDomain = (domain: string) : boolean => {
+ return domain &&
+ domain !== 'DISABLED.TLD' &&
+ (privateEmailDomains.includes(domain) || publicEmailDomains.includes(domain));
+ };
+
+ // Get first valid private domain
+ const firstPrivate = privateEmailDomains.find(isValidDomain);
+
+ if (firstPrivate) {
+ sendResponse({ domain: firstPrivate });
+ return;
+ }
+
+ // Return first valid public domain
+ const firstPublic = publicEmailDomains.find(isValidDomain);
+
+ if (firstPublic) {
+ sendResponse({ domain: firstPublic });
+ return;
+ }
+
+ // Return null if no valid domains are found
+ sendResponse({ domain: null });
+
+ return;
+ });
+}
+
+/**
+ * Get the derived key for a vault which is stored in local memory only.
+ */
+export function handleGetDerivedKey(
+ vaultState: VaultState,
+ sendResponse: (response: any) => void
+) : void {
+ sendResponse(vaultState.derivedKey ? vaultState.derivedKey : null);
+}
diff --git a/browser-extensions/chrome/src/components/FormInputCopyToClipboard.tsx b/browser-extensions/chrome/src/components/FormInputCopyToClipboard.tsx
index 69b01ad9d..f584f8ee5 100644
--- a/browser-extensions/chrome/src/components/FormInputCopyToClipboard.tsx
+++ b/browser-extensions/chrome/src/components/FormInputCopyToClipboard.tsx
@@ -1,7 +1,10 @@
import React, { useState, useEffect } from 'react';
import { ClipboardCopyService } from '../utils/ClipboardCopyService';
-interface FormInputCopyToClipboardProps {
+/**
+ * Form input copy to clipboard props.
+ */
+type FormInputCopyToClipboardProps = {
id: string;
label: string;
value: string;
@@ -10,6 +13,9 @@ interface FormInputCopyToClipboardProps {
const clipboardService = new ClipboardCopyService();
+/**
+ * Form input copy to clipboard component.
+ */
export const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> = ({
id,
label,
@@ -20,13 +26,18 @@ export const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> =
const [copied, setCopied] = useState(false);
useEffect(() => {
- const unsubscribe = clipboardService.subscribe((copiedId) => {
+ const unsubscribe = clipboardService.subscribe((copiedId) : void => {
setCopied(copiedId === id);
});
- return () => unsubscribe();
+ return () : void => {
+ unsubscribe();
+ };
}, [id]);
- const copyToClipboard = async () => {
+ /**
+ * Copy to clipboard.
+ */
+ const copyToClipboard = async () : Promise<void> => {
try {
await navigator.clipboard.writeText(value);
clipboardService.setCopied(id);
diff --git a/browser-extensions/chrome/src/components/Layout/BottomNav.tsx b/browser-extensions/chrome/src/components/Layout/BottomNav.tsx
index f29f91168..15f22471d 100644
--- a/browser-extensions/chrome/src/components/Layout/BottomNav.tsx
+++ b/browser-extensions/chrome/src/components/Layout/BottomNav.tsx
@@ -2,17 +2,27 @@ import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import { useDb } from '../../context/DbContext';
-interface BottomNavProps {
+
+/**
+ * Bottom nav props.
+ */
+type BottomNavProps = {
currentTab: 'credentials' | 'emails';
setCurrentTab: (tab: 'credentials' | 'emails') => void;
}
+/**
+ * Bottom nav component.
+ */
const BottomNav: React.FC<BottomNavProps> = ({ currentTab, setCurrentTab }) => {
const authContext = useAuth();
const dbContext = useDb();
const navigate = useNavigate();
- const handleTabChange = (tab: 'credentials' | 'emails') => {
+ /**
+ * Handle tab change.
+ */
+ const handleTabChange = (tab: 'credentials' | 'emails') : void => {
setCurrentTab(tab);
navigate(`/${tab}`);
};
diff --git a/browser-extensions/chrome/src/components/Layout/Header.tsx b/browser-extensions/chrome/src/components/Layout/Header.tsx
index 869bb4280..f8b301ca5 100644
--- a/browser-extensions/chrome/src/components/Layout/Header.tsx
+++ b/browser-extensions/chrome/src/components/Layout/Header.tsx
@@ -1,11 +1,12 @@
-import React, { useRef, useState, useEffect } from 'react';
+import React from 'react';
import { UserMenu } from './UserMenu';
import { useNavigate, useLocation } from 'react-router-dom';
-import { useAuth } from '../../context/AuthContext';
-interface HeaderProps {
+/**
+ * Header props.
+ */
+type HeaderProps = {
authContext: any;
- handleRefresh: () => Promise<void>;
toggleUserMenu: () => void;
isUserMenuOpen: boolean;
routes?: {
@@ -15,15 +16,20 @@ interface HeaderProps {
}[];
}
+/**
+ * Header component.
+ */
const Header: React.FC<HeaderProps> = ({
authContext,
- handleRefresh,
routes = []
}) => {
const navigate = useNavigate();
const location = useLocation();
- const openClientTab = async () => {
+ /**
+ * Open the client tab.
+ */
+ const openClientTab = async () : Promise<void> => {
const setting = await chrome.storage.local.get(['clientUrl']);
window.open(setting.clientUrl, '_blank');
};
@@ -36,9 +42,10 @@ const Header: React.FC<HeaderProps> = ({
return regex.test(location.pathname);
});
- console.log('currentRoute', currentRoute);
-
- const handleSettings = () => {
+ /**
+ * Handle settings.
+ */
+ const handleSettings = () : void => {
navigate('/settings');
};
@@ -46,44 +53,44 @@ const Header: React.FC<HeaderProps> = ({
<header className="fixed z-30 w-full bg-white border-b border-gray-200 dark:bg-gray-800 dark:border-gray-700">
<div className="flex items-center h-16 px-4">
{currentRoute?.showBackButton ? (
- <button
- id="back"
- onClick={() => navigate(-1)}
- className="flex items-center gap-2 hover:bg-gray-100 dark:hover:bg-gray-700 pr-2 pt-1.5 pb-1.5 rounded-lg group"
- >
- <div className="flex items-center">
+ <button
+ id="back"
+ onClick={() => navigate(-1)}
+ className="flex items-center gap-2 hover:bg-gray-100 dark:hover:bg-gray-700 pr-2 pt-1.5 pb-1.5 rounded-lg group"
+ >
+ <div className="flex items-center">
<svg className="w-5 h-5 text-gray-500 group-hover:text-gray-900 dark:text-gray-400 dark:group-hover:text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
- {currentRoute.title && (
- <h1 className="text-lg font-medium text-gray-900 dark:text-white ml-2">
- {currentRoute.title}
- </h1>
- )}
- </div>
+ {currentRoute.title && (
+ <h1 className="text-lg font-medium text-gray-900 dark:text-white ml-2">
+ {currentRoute.title}
+ </h1>
+ )}
+ </div>
</button>
) : (
<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>
- <span className="text-primary-500 text-[10px] ml-1 font-normal">BETA</span>
+ <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>
+ <span className="text-primary-500 text-[10px] ml-1 font-normal">BETA</span>
</div>
)}
<div className="flex-grow" />
<div className="flex items-center">
- {!currentRoute?.showBackButton ? (
- <button
- onClick={openClientTab}
- className="p-2"
- >
- <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-gray-400" viewBox="0 0 20 20" fill="currentColor">
- <path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z" />
- <path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z" />
- </svg>
- </button>
- ) : (<></>)}
+ {!currentRoute?.showBackButton ? (
+ <button
+ onClick={openClientTab}
+ className="p-2"
+ >
+ <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-gray-400" viewBox="0 0 20 20" fill="currentColor">
+ <path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z" />
+ <path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z" />
+ </svg>
+ </button>
+ ) : (<></>)}
</div>
{!authContext.isLoggedIn ? (
<button
@@ -98,7 +105,6 @@ const Header: React.FC<HeaderProps> = ({
</button>
) : (
<UserMenu
- onRefresh={handleRefresh}
username={authContext.username}
/>
)}
diff --git a/browser-extensions/chrome/src/components/Layout/UserMenu.tsx b/browser-extensions/chrome/src/components/Layout/UserMenu.tsx
index 50d774ad0..f3a27d315 100644
--- a/browser-extensions/chrome/src/components/Layout/UserMenu.tsx
+++ b/browser-extensions/chrome/src/components/Layout/UserMenu.tsx
@@ -3,14 +3,18 @@ import { useAuth } from '../../context/AuthContext';
import { useNavigate } from 'react-router-dom';
import { useLoading } from '../../context/LoadingContext';
-interface UserMenuProps {
+/**
+ * User menu props.
+ */
+type UserMenuProps = {
username: string;
- onRefresh?: () => void;
}
+/**
+ * User menu component.
+ */
export const UserMenu: React.FC<UserMenuProps> = ({
- username,
- onRefresh,
+ username
}) => {
const authContext = useAuth();
const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
@@ -20,7 +24,10 @@ export const UserMenu: React.FC<UserMenuProps> = ({
const { showLoading, hideLoading } = useLoading();
useEffect(() => {
- const handleClickOutside = (event: MouseEvent) => {
+ /**
+ * Handle clicking outside the user menu.
+ */
+ const handleClickOutside = (event: MouseEvent) : void => {
if (
menuRef.current &&
buttonRef.current &&
@@ -32,18 +39,24 @@ export const UserMenu: React.FC<UserMenuProps> = ({
};
document.addEventListener('mousedown', handleClickOutside);
- return () => document.removeEventListener('mousedown', handleClickOutside);
+ return () : void => {
+ document.removeEventListener('mousedown', handleClickOutside);
+ };
}, []);
- const toggleUserMenu = () => {
+ /**
+ * Toggle the user menu.
+ */
+ const toggleUserMenu = () : void => {
setIsUserMenuOpen(!isUserMenuOpen);
};
- const onLogout = async () => {
+ /**
+ * Handle logging out.
+ */
+ const onLogout = async () : Promise<void> => {
showLoading();
- console.log('logging out');
await authContext.logout();
- console.log('redirecting to home');
navigate('/', { replace: true });
// Delay for 100ms for improved UX
await new Promise(resolve => setTimeout(resolve, 100));
diff --git a/browser-extensions/chrome/src/components/LoadingSpinner.tsx b/browser-extensions/chrome/src/components/LoadingSpinner.tsx
index 8ea0fec0d..1ae18c186 100644
--- a/browser-extensions/chrome/src/components/LoadingSpinner.tsx
+++ b/browser-extensions/chrome/src/components/LoadingSpinner.tsx
@@ -14,19 +14,19 @@ const LoadingSpinner: React.FC = () => {
const spinner = (
<>
- <style>
- {`
+ <style>
+ {`
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`}
- </style>
- <div
- className="border-[4px] border-solid border-current/10 dark:border-white/10 border-t-current dark:border-t-white"
- style={spinnerStyle}
- />
- </>
+ </style>
+ <div
+ className="border-[4px] border-solid border-current/10 dark:border-white/10 border-t-current dark:border-t-white"
+ style={spinnerStyle}
+ />
+ </>
);
return (
diff --git a/browser-extensions/chrome/src/components/LoadingSpinnerFullScreen.tsx b/browser-extensions/chrome/src/components/LoadingSpinnerFullScreen.tsx
index c8b987125..d7630e9a6 100644
--- a/browser-extensions/chrome/src/components/LoadingSpinnerFullScreen.tsx
+++ b/browser-extensions/chrome/src/components/LoadingSpinnerFullScreen.tsx
@@ -19,19 +19,19 @@ const LoadingSpinnerFullScreen: React.FC = () => {
const spinner = (
<>
- <style>
- {`
+ <style>
+ {`
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`}
- </style>
- <div
- className="border-[4px] border-solid border-current/10 dark:border-white/10 border-t-current dark:border-t-white"
- style={spinnerStyle}
- />
- </>
+ </style>
+ <div
+ className="border-[4px] border-solid border-current/10 dark:border-white/10 border-t-current dark:border-t-white"
+ style={spinnerStyle}
+ />
+ </>
);
return (
diff --git a/browser-extensions/chrome/src/components/ReloadButton.tsx b/browser-extensions/chrome/src/components/ReloadButton.tsx
index 5d4dae194..f9db7cb54 100644
--- a/browser-extensions/chrome/src/components/ReloadButton.tsx
+++ b/browser-extensions/chrome/src/components/ReloadButton.tsx
@@ -1,9 +1,15 @@
import React from 'react';
-interface ReloadButtonProps {
+/**
+ * Reload button props.
+ */
+type ReloadButtonProps = {
onClick: () => void;
-}
+};
+/**
+ * Reload button component.
+ */
const ReloadButton: React.FC<ReloadButtonProps> = ({ onClick }) => {
return (
<div
diff --git a/browser-extensions/chrome/src/context/AuthContext.tsx b/browser-extensions/chrome/src/context/AuthContext.tsx
index 5d7fc65f9..0707fb18b 100644
--- a/browser-extensions/chrome/src/context/AuthContext.tsx
+++ b/browser-extensions/chrome/src/context/AuthContext.tsx
@@ -1,4 +1,4 @@
-import React, { createContext, useContext, useState, useEffect, useRef } from 'react';
+import React, { createContext, useContext, useState, useEffect } from 'react';
type AuthContextType = {
isLoggedIn: boolean;
@@ -25,7 +25,10 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
* Check for tokens in chrome storage on initial load
*/
useEffect(() => {
- const initializeAuth = async () => {
+ /**
+ * Initialize the authentication state.
+ */
+ const initializeAuth = async () : Promise<void> => {
const stored = await chrome.storage.local.get(['accessToken', 'refreshToken', 'username']);
if (stored.accessToken && stored.refreshToken && stored.username) {
setUsername(stored.username);
@@ -40,7 +43,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
/**
* Login
*/
- const login = async (username: string, accessToken: string, refreshToken: string) => {
+ const login = async (username: string, accessToken: string, refreshToken: string) : Promise<void> => {
await chrome.storage.local.set({
username,
accessToken,
@@ -54,7 +57,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
/**
* Logout
*/
- const logout = async () => {
+ const logout = async () : Promise<void> => {
await chrome.runtime.sendMessage({ type: 'CLEAR_VAULT' });
await chrome.storage.local.remove(['username', 'accessToken', 'refreshToken']);
setUsername(null);
diff --git a/browser-extensions/chrome/src/context/DbContext.tsx b/browser-extensions/chrome/src/context/DbContext.tsx
index 429360257..75fe096ad 100644
--- a/browser-extensions/chrome/src/context/DbContext.tsx
+++ b/browser-extensions/chrome/src/context/DbContext.tsx
@@ -49,9 +49,11 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
setPublicEmailDomains(publicEmailDomains);
setPrivateEmailDomains(privateEmailDomains);
- // Store in background worker.
- // TODO: perhaps we can simply pass the full vaultresponse object instead of the individual fields
- // in case we need to access more fields in the future.
+ /*
+ * Store in background worker.
+ * TODO: perhaps we can simply pass the full vaultresponse object instead of the individual fields
+ * in case we need to access more fields in the future.
+ */
chrome.runtime.sendMessage({
type: 'STORE_VAULT',
derivedKey: derivedKey,
diff --git a/browser-extensions/chrome/src/generators/Identity/UsernameEmailGenerator.ts b/browser-extensions/chrome/src/generators/Identity/UsernameEmailGenerator.ts
index 075b3e548..96371df56 100644
--- a/browser-extensions/chrome/src/generators/Identity/UsernameEmailGenerator.ts
+++ b/browser-extensions/chrome/src/generators/Identity/UsernameEmailGenerator.ts
@@ -1,102 +1,120 @@
import { Identity } from "./types/Identity";
+/**
+ *
+ */
export class UsernameEmailGenerator {
- private static readonly MIN_LENGTH = 6;
- private static readonly MAX_LENGTH = 20;
- private readonly symbols: string[] = ['.', '-'];
-
- public generateUsername(identity: Identity): string {
- // Generate username based on email prefix but strip all non-alphanumeric characters
- let username = this.generateEmailPrefix(identity);
- username = username.replace(/[^a-zA-Z0-9]/g, '');
-
- // Adjust length
- if (username.length < UsernameEmailGenerator.MIN_LENGTH) {
- username += this.generateRandomString(UsernameEmailGenerator.MIN_LENGTH - username.length);
- } else if (username.length > UsernameEmailGenerator.MAX_LENGTH) {
- username = username.substring(0, UsernameEmailGenerator.MAX_LENGTH);
- }
-
- return username;
+ private static readonly MIN_LENGTH = 6;
+ private static readonly MAX_LENGTH = 20;
+ private readonly symbols: string[] = ['.', '-'];
+
+ /**
+ *
+ */
+ public generateUsername(identity: Identity): string {
+ // Generate username based on email prefix but strip all non-alphanumeric characters
+ let username = this.generateEmailPrefix(identity);
+ username = username.replace(/[^a-zA-Z0-9]/g, '');
+
+ // Adjust length
+ if (username.length < UsernameEmailGenerator.MIN_LENGTH) {
+ username += this.generateRandomString(UsernameEmailGenerator.MIN_LENGTH - username.length);
+ } else if (username.length > UsernameEmailGenerator.MAX_LENGTH) {
+ username = username.substring(0, UsernameEmailGenerator.MAX_LENGTH);
}
- public generateEmailPrefix(identity: Identity): string {
- const parts: string[] = [];
-
- switch (Math.floor(Math.random() * 4)) {
- case 0:
- // First initial + last name
- parts.push(identity.firstName.substring(0, 1).toLowerCase() + identity.lastName.toLowerCase());
- break;
- case 1:
- // Full name
- parts.push((identity.firstName + identity.lastName).toLowerCase());
- break;
- case 2:
- // First name + last initial
- parts.push(identity.firstName.toLowerCase() + identity.lastName.substring(0, 1).toLowerCase());
- break;
- case 3:
- // First 3 chars of first name + last name
- parts.push(identity.firstName.substring(0, Math.min(3, identity.firstName.length)).toLowerCase() + identity.lastName.toLowerCase());
- break;
- }
-
- // Add birth year variations
- if (Math.floor(Math.random() * 3) !== 0) {
- switch (Math.floor(Math.random() * 2)) {
- case 0:
- parts.push(identity.birthDate.getFullYear().toString().substring(2));
- break;
- case 1:
- parts.push(identity.birthDate.getFullYear().toString());
- break;
- }
- } else if (Math.floor(Math.random() * 2) === 0) {
- // Add random numbers for more uniqueness
- parts.push((Math.floor(Math.random() * 990) + 10).toString());
- }
-
- // Join parts with random symbols, possibly multiple
- let emailPrefix = parts.join(this.getRandomSymbol());
-
- // Add extra random symbol at random position
- if (Math.floor(Math.random() * 2) === 0) {
- const position = Math.floor(Math.random() * emailPrefix.length);
- emailPrefix = emailPrefix.slice(0, position) + this.getRandomSymbol() + emailPrefix.slice(position);
- }
-
- emailPrefix = this.sanitizeEmailPrefix(emailPrefix);
-
- // Adjust length
- if (emailPrefix.length < UsernameEmailGenerator.MIN_LENGTH) {
- emailPrefix += this.generateRandomString(UsernameEmailGenerator.MIN_LENGTH - emailPrefix.length);
- } else if (emailPrefix.length > UsernameEmailGenerator.MAX_LENGTH) {
- emailPrefix = emailPrefix.substring(0, UsernameEmailGenerator.MAX_LENGTH);
- }
-
- return emailPrefix;
+ return username;
+ }
+
+ /**
+ *
+ */
+ public generateEmailPrefix(identity: Identity): string {
+ const parts: string[] = [];
+
+ switch (Math.floor(Math.random() * 4)) {
+ case 0:
+ // First initial + last name
+ parts.push(identity.firstName.substring(0, 1).toLowerCase() + identity.lastName.toLowerCase());
+ break;
+ case 1:
+ // Full name
+ parts.push((identity.firstName + identity.lastName).toLowerCase());
+ break;
+ case 2:
+ // First name + last initial
+ parts.push(identity.firstName.toLowerCase() + identity.lastName.substring(0, 1).toLowerCase());
+ break;
+ case 3:
+ // First 3 chars of first name + last name
+ parts.push(identity.firstName.substring(0, Math.min(3, identity.firstName.length)).toLowerCase() + identity.lastName.toLowerCase());
+ break;
}
- private sanitizeEmailPrefix(input: string): string {
- // Remove any character that's not a letter, number, dot, underscore, or hyphen including special characters
- let sanitized = input.replace(/[^a-zA-Z0-9._-]/g, '');
-
- // Remove consecutive dots, underscores, or hyphens
- sanitized = sanitized.replace(/[-_.]{2,}/g, (match) => match[0]);
+ // Add birth year variations
+ if (Math.floor(Math.random() * 3) !== 0) {
+ switch (Math.floor(Math.random() * 2)) {
+ case 0:
+ parts.push(identity.birthDate.getFullYear().toString().substring(2));
+ break;
+ case 1:
+ parts.push(identity.birthDate.getFullYear().toString());
+ break;
+ }
+ } else if (Math.floor(Math.random() * 2) === 0) {
+ // Add random numbers for more uniqueness
+ parts.push((Math.floor(Math.random() * 990) + 10).toString());
+ }
- // Ensure it doesn't start or end with a dot, underscore, or hyphen
- sanitized = sanitized.replace(/^[-._]+|[-._]+$/g, '');
+ // Join parts with random symbols, possibly multiple
+ let emailPrefix = parts.join(this.getRandomSymbol());
- return sanitized;
+ // Add extra random symbol at random position
+ if (Math.floor(Math.random() * 2) === 0) {
+ const position = Math.floor(Math.random() * emailPrefix.length);
+ emailPrefix = emailPrefix.slice(0, position) + this.getRandomSymbol() + emailPrefix.slice(position);
}
- private getRandomSymbol(): string {
- return Math.floor(Math.random() * 3) === 0 ? this.symbols[Math.floor(Math.random() * this.symbols.length)] : '';
- }
+ emailPrefix = this.sanitizeEmailPrefix(emailPrefix);
- private generateRandomString(length: number): string {
- const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
- return Array.from({ length }, () => chars.charAt(Math.floor(Math.random() * chars.length))).join('');
+ // Adjust length
+ if (emailPrefix.length < UsernameEmailGenerator.MIN_LENGTH) {
+ emailPrefix += this.generateRandomString(UsernameEmailGenerator.MIN_LENGTH - emailPrefix.length);
+ } else if (emailPrefix.length > UsernameEmailGenerator.MAX_LENGTH) {
+ emailPrefix = emailPrefix.substring(0, UsernameEmailGenerator.MAX_LENGTH);
}
+
+ return emailPrefix;
+ }
+
+ /**
+ *
+ */
+ private sanitizeEmailPrefix(input: string): string {
+ // Remove any character that's not a letter, number, dot, underscore, or hyphen including special characters
+ let sanitized = input.replace(/[^a-zA-Z0-9._-]/g, '');
+
+ // Remove consecutive dots, underscores, or hyphens
+ sanitized = sanitized.replace(/[-_.]{2,}/g, (match) => match[0]);
+
+ // Ensure it doesn't start or end with a dot, underscore, or hyphen
+ sanitized = sanitized.replace(/^[-._]+|[-._]+$/g, '');
+
+ return sanitized;
+ }
+
+ /**
+ *
+ */
+ private getRandomSymbol(): string {
+ return Math.floor(Math.random() * 3) === 0 ? this.symbols[Math.floor(Math.random() * this.symbols.length)] : '';
+ }
+
+ /**
+ *
+ */
+ private generateRandomString(length: number): string {
+ const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
+ return Array.from({ length }, () => chars.charAt(Math.floor(Math.random() * chars.length))).join('');
+ }
}
diff --git a/browser-extensions/chrome/src/generators/Identity/__tests__/IdentityGenerator.test.ts b/browser-extensions/chrome/src/generators/Identity/__tests__/IdentityGenerator.test.ts
index bcac62586..71bc37bc8 100644
--- a/browser-extensions/chrome/src/generators/Identity/__tests__/IdentityGenerator.test.ts
+++ b/browser-extensions/chrome/src/generators/Identity/__tests__/IdentityGenerator.test.ts
@@ -3,11 +3,13 @@ import { IdentityGeneratorNl } from '../implementations/IdentityGeneratorNl';
import { describe, it, expect } from 'vitest';
import { IIdentityGenerator } from '../interfaces/IIdentityGenerator';
-// Test factory function to run tests for each language implementation
+/**
+ * Test the identity generator.
+ */
const testIdentityGenerator = (
language: string,
generator: IIdentityGenerator
-) => {
+) : void => {
describe(`IdentityGenerator${language}`, () => {
describe('generateRandomIdentity', () => {
it('should generate a random gender identity when no gender is specified', async () => {
@@ -29,7 +31,7 @@ const testIdentityGenerator = (
it('should generate an identity with all non-empty fields', async () => {
const identity = await generator.generateRandomIdentity();
- Object.entries(identity).forEach(([key, value]) => {
+ Object.entries(identity).forEach(([, value]) => {
expect(value).toBeTruthy();
expect(value).not.toBe('');
expect(value).not.toBeNull();
diff --git a/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorEn.ts b/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorEn.ts
index 401984714..b53014f1b 100644
--- a/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorEn.ts
+++ b/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorEn.ts
@@ -1,21 +1,39 @@
import { BaseIdentityGenerator } from "./base/BaseIdentityGenerator";
+/**
+ *
+ */
export class IdentityGeneratorEn extends BaseIdentityGenerator {
+ /**
+ *
+ */
protected getFirstNamesMaleJson(): string[] {
- // This is a placeholder for the dictionary-loader to replace with the actual data.
- // See vite-plugins/dictionary-loader.ts for more information.
+ /*
+ * This is a placeholder for the dictionary-loader to replace with the actual data.
+ * See vite-plugins/dictionary-loader.ts for more information.
+ */
return '__FIRSTNAMES_MALE_EN__';
}
+ /**
+ *
+ */
protected getFirstNamesFemaleJson(): string[] {
- // This is a placeholder for the dictionary-loader to replace with the actual data.
- // See vite-plugins/dictionary-loader.ts for more information.
+ /*
+ * This is a placeholder for the dictionary-loader to replace with the actual data.
+ * See vite-plugins/dictionary-loader.ts for more information.
+ */
return '__FIRSTNAMES_FEMALE_EN__';
}
+ /**
+ *
+ */
protected getLastNamesJson(): string[] {
- // This is a placeholder for the dictionary-loader to replace with the actual data.
- // See vite-plugins/dictionary-loader.ts for more information.
+ /*
+ * This is a placeholder for the dictionary-loader to replace with the actual data.
+ * See vite-plugins/dictionary-loader.ts for more information.
+ */
return '__LASTNAMES_EN__';
}
}
diff --git a/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorNl.ts b/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorNl.ts
index 3ac0c78f1..c49aa3f7a 100644
--- a/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorNl.ts
+++ b/browser-extensions/chrome/src/generators/Identity/implementations/IdentityGeneratorNl.ts
@@ -1,21 +1,39 @@
import { BaseIdentityGenerator } from "./base/BaseIdentityGenerator";
+/**
+ *
+ */
export class IdentityGeneratorNl extends BaseIdentityGenerator {
+ /**
+ *
+ */
protected getFirstNamesMaleJson(): string[] {
- // This is a placeholder for the dictionary-loader to replace with the actual data.
- // See vite-plugins/dictionary-loader.ts for more information.
+ /*
+ * This is a placeholder for the dictionary-loader to replace with the actual data.
+ * See vite-plugins/dictionary-loader.ts for more information.
+ */
return '__FIRSTNAMES_MALE_NL__';
}
+ /**
+ *
+ */
protected getFirstNamesFemaleJson(): string[] {
- // This is a placeholder for the dictionary-loader to replace with the actual data.
- // See vite-plugins/dictionary-loader.ts for more information.
+ /*
+ * This is a placeholder for the dictionary-loader to replace with the actual data.
+ * See vite-plugins/dictionary-loader.ts for more information.
+ */
return '__FIRSTNAMES_FEMALE_NL__';
}
+ /**
+ *
+ */
protected getLastNamesJson(): string[] {
- // This is a placeholder for the dictionary-loader to replace with the actual data.
- // See vite-plugins/dictionary-loader.ts for more information.
+ /*
+ * This is a placeholder for the dictionary-loader to replace with the actual data.
+ * See vite-plugins/dictionary-loader.ts for more information.
+ */
return '__LASTNAMES_NL__';
}
}
diff --git a/browser-extensions/chrome/src/generators/Identity/implementations/base/BaseIdentityGenerator.ts b/browser-extensions/chrome/src/generators/Identity/implementations/base/BaseIdentityGenerator.ts
index a070a291b..da33b35a9 100644
--- a/browser-extensions/chrome/src/generators/Identity/implementations/base/BaseIdentityGenerator.ts
+++ b/browser-extensions/chrome/src/generators/Identity/implementations/base/BaseIdentityGenerator.ts
@@ -3,13 +3,19 @@ import { Gender } from '../../types/Gender';
import { IIdentityGenerator } from '../../interfaces/IIdentityGenerator';
import { Identity } from '../../types/Identity';
+/**
+ * Base identity generator.
+ */
export abstract class BaseIdentityGenerator implements IIdentityGenerator {
protected firstNamesMale: string[] = [];
protected firstNamesFemale: string[] = [];
protected lastNames: string[] = [];
private random = Math.random;
- constructor() {
+ /**
+ * Constructor.
+ */
+ public constructor() {
// Each implementing class should provide these as static JSON strings
this.firstNamesMale = this.getFirstNamesMaleJson();
this.firstNamesFemale = this.getFirstNamesFemaleJson();
@@ -20,6 +26,9 @@ export abstract class BaseIdentityGenerator implements IIdentityGenerator {
protected abstract getFirstNamesFemaleJson(): string[];
protected abstract getLastNamesJson(): string[];
+ /**
+ * Generate a random date of birth.
+ */
protected generateRandomDateOfBirth(): Date {
const today = new Date();
const minAge = 21;
@@ -32,7 +41,10 @@ export abstract class BaseIdentityGenerator implements IIdentityGenerator {
return new Date(timestamp);
}
- async generateRandomIdentity(): Promise<Identity> {
+ /**
+ * Generate a random identity.
+ */
+ public async generateRandomIdentity(): Promise<Identity> {
const identity: Identity = {
firstName: '',
lastName: '',
diff --git a/browser-extensions/chrome/src/generators/Identity/types/Identity.ts b/browser-extensions/chrome/src/generators/Identity/types/Identity.ts
index 054a0d568..738b8ee83 100644
--- a/browser-extensions/chrome/src/generators/Identity/types/Identity.ts
+++ b/browser-extensions/chrome/src/generators/Identity/types/Identity.ts
@@ -1,4 +1,9 @@
-export interface Identity {
+import { Gender } from './Gender';
+
+/**
+ * Identity.
+ */
+export type Identity = {
firstName: string;
lastName: string;
gender: Gender;
diff --git a/browser-extensions/chrome/src/generators/Password/PasswordGenerator.ts b/browser-extensions/chrome/src/generators/Password/PasswordGenerator.ts
index 6e416a471..0d223b136 100644
--- a/browser-extensions/chrome/src/generators/Password/PasswordGenerator.ts
+++ b/browser-extensions/chrome/src/generators/Password/PasswordGenerator.ts
@@ -1,102 +1,126 @@
+/**
+ *
+ */
export class PasswordGenerator {
- private readonly lowercaseChars = 'abcdefghijklmnopqrstuvwxyz';
- private readonly uppercaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
- private readonly numberChars = '0123456789';
- private readonly specialChars = '!@#$%^&*()_+-=[]{}|;:,.<>?';
+ private readonly lowercaseChars = 'abcdefghijklmnopqrstuvwxyz';
+ private readonly uppercaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
+ private readonly numberChars = '0123456789';
+ private readonly specialChars = '!@#$%^&*()_+-=[]{}|;:,.<>?';
- private length: number = 18;
- private useLowercase: boolean = true;
- private useUppercase: boolean = true;
- private useNumbers: boolean = true;
- private useSpecial: boolean = true;
+ private length: number = 18;
+ private useLowercase: boolean = true;
+ private useUppercase: boolean = true;
+ private useNumbers: boolean = true;
+ private useSpecial: boolean = true;
- public setLength(length: number): PasswordGenerator {
- this.length = length;
- return this;
- }
+ /**
+ *
+ */
+ public setLength(length: number): PasswordGenerator {
+ this.length = length;
+ return this;
+ }
- public useLowercaseLetters(use: boolean): PasswordGenerator {
- this.useLowercase = use;
- return this;
- }
+ /**
+ *
+ */
+ public useLowercaseLetters(use: boolean): PasswordGenerator {
+ this.useLowercase = use;
+ return this;
+ }
- public useUppercaseLetters(use: boolean): PasswordGenerator {
- this.useUppercase = use;
- return this;
- }
+ /**
+ *
+ */
+ public useUppercaseLetters(use: boolean): PasswordGenerator {
+ this.useUppercase = use;
+ return this;
+ }
- public useNumericCharacters(use: boolean): PasswordGenerator {
- this.useNumbers = use;
- return this;
- }
+ /**
+ *
+ */
+ public useNumericCharacters(use: boolean): PasswordGenerator {
+ this.useNumbers = use;
+ return this;
+ }
- public useSpecialCharacters(use: boolean): PasswordGenerator {
- this.useSpecial = use;
- return this;
- }
+ /**
+ *
+ */
+ public useSpecialCharacters(use: boolean): PasswordGenerator {
+ this.useSpecial = use;
+ return this;
+ }
- private getUnbiasedRandomIndex(max: number): number {
- // Calculate the largest multiple of max that fits within Uint32
- const limit = Math.floor((2 ** 32) / max) * max;
+ /**
+ *
+ */
+ private getUnbiasedRandomIndex(max: number): number {
+ // Calculate the largest multiple of max that fits within Uint32
+ const limit = Math.floor((2 ** 32) / max) * max;
- while (true) {
- const array = new Uint32Array(1);
- crypto.getRandomValues(array);
- const value = array[0];
+ while (true) {
+ const array = new Uint32Array(1);
+ crypto.getRandomValues(array);
+ const value = array[0];
- // Reject values that would introduce bias
- if (value < limit) {
- return value % max;
- }
- }
+ // Reject values that would introduce bias
+ if (value < limit) {
+ return value % max;
+ }
}
+ }
- public generateRandomPassword(): string {
- let chars = '';
- let password = '';
+ /**
+ *
+ */
+ public generateRandomPassword(): string {
+ let chars = '';
+ let password = '';
- // Build character set based on options
- if (this.useLowercase) chars += this.lowercaseChars;
- if (this.useUppercase) chars += this.uppercaseChars;
- if (this.useNumbers) chars += this.numberChars;
- if (this.useSpecial) chars += this.specialChars;
+ // Build character set based on options
+ if (this.useLowercase) chars += this.lowercaseChars;
+ if (this.useUppercase) chars += this.uppercaseChars;
+ if (this.useNumbers) chars += this.numberChars;
+ if (this.useSpecial) chars += this.specialChars;
- // Ensure at least one character set is selected
- if (chars.length === 0) {
- chars = this.lowercaseChars;
- }
+ // Ensure at least one character set is selected
+ if (chars.length === 0) {
+ chars = this.lowercaseChars;
+ }
- // Generate password
- for (let i = 0; i < this.length; i++) {
- password += chars[this.getUnbiasedRandomIndex(chars.length)];
- }
+ // Generate password
+ for (let i = 0; i < this.length; i++) {
+ password += chars[this.getUnbiasedRandomIndex(chars.length)];
+ }
- // Ensure password contains at least one character from each selected set
- if (this.useLowercase && !password.match(/[a-z]/)) {
- const pos = this.getUnbiasedRandomIndex(this.length);
- password = password.substring(0, pos) +
+ // Ensure password contains at least one character from each selected set
+ if (this.useLowercase && !password.match(/[a-z]/)) {
+ const pos = this.getUnbiasedRandomIndex(this.length);
+ password = password.substring(0, pos) +
this.lowercaseChars[this.getUnbiasedRandomIndex(this.lowercaseChars.length)] +
password.substring(pos + 1);
- }
- if (this.useUppercase && !password.match(/[A-Z]/)) {
- const pos = this.getUnbiasedRandomIndex(this.length);
- password = password.substring(0, pos) +
+ }
+ if (this.useUppercase && !password.match(/[A-Z]/)) {
+ const pos = this.getUnbiasedRandomIndex(this.length);
+ password = password.substring(0, pos) +
this.uppercaseChars[this.getUnbiasedRandomIndex(this.uppercaseChars.length)] +
password.substring(pos + 1);
- }
- if (this.useNumbers && !password.match(/[0-9]/)) {
- const pos = this.getUnbiasedRandomIndex(this.length);
- password = password.substring(0, pos) +
+ }
+ if (this.useNumbers && !password.match(/[0-9]/)) {
+ const pos = this.getUnbiasedRandomIndex(this.length);
+ password = password.substring(0, pos) +
this.numberChars[this.getUnbiasedRandomIndex(this.numberChars.length)] +
password.substring(pos + 1);
- }
- if (this.useSpecial && !password.match(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/)) {
- const pos = this.getUnbiasedRandomIndex(this.length);
- password = password.substring(0, pos) +
+ }
+ if (this.useSpecial && !password.match(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/)) {
+ const pos = this.getUnbiasedRandomIndex(this.length);
+ password = password.substring(0, pos) +
this.specialChars[this.getUnbiasedRandomIndex(this.specialChars.length)] +
password.substring(pos + 1);
- }
-
- return password;
}
+
+ return password;
+ }
}
diff --git a/browser-extensions/chrome/src/generators/Password/__tests__/PasswordGenerator.test.ts b/browser-extensions/chrome/src/generators/Password/__tests__/PasswordGenerator.test.ts
index 9845a229a..3aab96a45 100644
--- a/browser-extensions/chrome/src/generators/Password/__tests__/PasswordGenerator.test.ts
+++ b/browser-extensions/chrome/src/generators/Password/__tests__/PasswordGenerator.test.ts
@@ -2,90 +2,90 @@ import { PasswordGenerator } from '../PasswordGenerator';
import { describe, it, expect, beforeEach } from 'vitest';
describe('PasswordGenerator', () => {
- let generator: PasswordGenerator;
-
- beforeEach(() => {
- generator = new PasswordGenerator();
- });
-
- it('generates password with default settings', () => {
- const password = generator.generateRandomPassword();
-
- // Default length is 18
- expect(password.length).toBe(18);
-
- // Should contain at least one of each character type by default
- expect(password).toMatch(/[a-z]/); // lowercase
- expect(password).toMatch(/[A-Z]/); // uppercase
- expect(password).toMatch(/[0-9]/); // numbers
- expect(password).toMatch(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/); // special
- });
-
- it('respects custom length setting', () => {
- const customLength = 24;
- const password = generator.setLength(customLength).generateRandomPassword();
- expect(password.length).toBe(customLength);
- });
-
- it('respects lowercase setting', () => {
- const password = generator.useLowercaseLetters(false).generateRandomPassword();
- expect(password).not.toMatch(/[a-z]/);
- });
-
- it('respects uppercase setting', () => {
- const password = generator.useUppercaseLetters(false).generateRandomPassword();
- expect(password).not.toMatch(/[A-Z]/);
- });
-
- it('respects numbers setting', () => {
- const password = generator.useNumericCharacters(false).generateRandomPassword();
- expect(password).not.toMatch(/[0-9]/);
- });
-
- it('respects special characters setting', () => {
- const password = generator.useSpecialCharacters(false).generateRandomPassword();
- expect(password).not.toMatch(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/);
- });
-
- it('generates different passwords on subsequent calls', () => {
- const password1 = generator.generateRandomPassword();
- const password2 = generator.generateRandomPassword();
- expect(password1).not.toBe(password2);
- });
-
- it('handles minimum character requirements', () => {
- // Generate multiple passwords to ensure consistency
- for (let i = 0; i < 100; i++) {
- const password = generator.generateRandomPassword();
-
- // Each password should contain at least one character from each enabled set
- expect(password).toMatch(/[a-z]/);
- expect(password).toMatch(/[A-Z]/);
- expect(password).toMatch(/[0-9]/);
- expect(password).toMatch(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/);
- }
- });
-
- it('falls back to lowercase when all options disabled', () => {
- const password = generator
- .useLowercaseLetters(false)
- .useUppercaseLetters(false)
- .useNumericCharacters(false)
- .useSpecialCharacters(false)
- .generateRandomPassword();
-
- // Should fall back to lowercase
- expect(password).toMatch(/^[a-z]+$/);
- });
-
- it('maintains method chaining', () => {
- const result = generator
- .setLength(20)
- .useLowercaseLetters(true)
- .useUppercaseLetters(true)
- .useNumericCharacters(true)
- .useSpecialCharacters(true);
-
- expect(result).toBe(generator);
- });
+ let generator: PasswordGenerator;
+
+ beforeEach(() => {
+ generator = new PasswordGenerator();
+ });
+
+ it('generates password with default settings', () => {
+ const password = generator.generateRandomPassword();
+
+ // Default length is 18
+ expect(password.length).toBe(18);
+
+ // Should contain at least one of each character type by default
+ expect(password).toMatch(/[a-z]/); // lowercase
+ expect(password).toMatch(/[A-Z]/); // uppercase
+ expect(password).toMatch(/[0-9]/); // numbers
+ expect(password).toMatch(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/); // special
+ });
+
+ it('respects custom length setting', () => {
+ const customLength = 24;
+ const password = generator.setLength(customLength).generateRandomPassword();
+ expect(password.length).toBe(customLength);
+ });
+
+ it('respects lowercase setting', () => {
+ const password = generator.useLowercaseLetters(false).generateRandomPassword();
+ expect(password).not.toMatch(/[a-z]/);
+ });
+
+ it('respects uppercase setting', () => {
+ const password = generator.useUppercaseLetters(false).generateRandomPassword();
+ expect(password).not.toMatch(/[A-Z]/);
+ });
+
+ it('respects numbers setting', () => {
+ const password = generator.useNumericCharacters(false).generateRandomPassword();
+ expect(password).not.toMatch(/[0-9]/);
+ });
+
+ it('respects special characters setting', () => {
+ const password = generator.useSpecialCharacters(false).generateRandomPassword();
+ expect(password).not.toMatch(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/);
+ });
+
+ it('generates different passwords on subsequent calls', () => {
+ const password1 = generator.generateRandomPassword();
+ const password2 = generator.generateRandomPassword();
+ expect(password1).not.toBe(password2);
+ });
+
+ it('handles minimum character requirements', () => {
+ // Generate multiple passwords to ensure consistency
+ for (let i = 0; i < 100; i++) {
+ const password = generator.generateRandomPassword();
+
+ // Each password should contain at least one character from each enabled set
+ expect(password).toMatch(/[a-z]/);
+ expect(password).toMatch(/[A-Z]/);
+ expect(password).toMatch(/[0-9]/);
+ expect(password).toMatch(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/);
+ }
+ });
+
+ it('falls back to lowercase when all options disabled', () => {
+ const password = generator
+ .useLowercaseLetters(false)
+ .useUppercaseLetters(false)
+ .useNumericCharacters(false)
+ .useSpecialCharacters(false)
+ .generateRandomPassword();
+
+ // Should fall back to lowercase
+ expect(password).toMatch(/^[a-z]+$/);
+ });
+
+ it('maintains method chaining', () => {
+ const result = generator
+ .setLength(20)
+ .useLowercaseLetters(true)
+ .useUppercaseLetters(true)
+ .useNumericCharacters(true)
+ .useSpecialCharacters(true);
+
+ expect(result).toBe(generator);
+ });
});
\ No newline at end of file
diff --git a/browser-extensions/chrome/src/pages/CredentialDetails.tsx b/browser-extensions/chrome/src/pages/CredentialDetails.tsx
index 8f62ac500..e1fefafef 100644
--- a/browser-extensions/chrome/src/pages/CredentialDetails.tsx
+++ b/browser-extensions/chrome/src/pages/CredentialDetails.tsx
@@ -5,18 +5,27 @@ import { Credential } from '../types/Credential';
import { Buffer } from 'buffer';
import { FormInputCopyToClipboard } from '../components/FormInputCopyToClipboard';
+/**
+ * Credential details page.
+ */
const CredentialDetails: React.FC = () => {
const { id } = useParams();
const navigate = useNavigate();
const dbContext = useDb();
const [credential, setCredential] = useState<Credential | null>(null);
- const isPopup = () => {
+ /**
+ * Check if the current page is a popup.
+ */
+ const isPopup = () : boolean => {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get('popup') === 'true';
};
- const openInNewPopup = () => {
+ /**
+ * Open the credential details in a new popup.
+ */
+ const openInNewPopup = () : void => {
const width = 380;
const height = 600;
const left = window.screen.width / 2 - width / 2;
@@ -36,7 +45,6 @@ const CredentialDetails: React.FC = () => {
// For popup windows, ensure we have proper history state for navigation
if (isPopup()) {
// Clear existing history and create fresh entries
- console.log(window.location.href);
window.history.replaceState({}, '', `index.html#/credentials`);
window.history.pushState({}, '', `index.html#/credentials/${id}`);
}
@@ -55,7 +63,7 @@ const CredentialDetails: React.FC = () => {
} catch (err) {
console.error('Error loading credential:', err);
}
- }, [dbContext.sqliteClient, id]);
+ }, [dbContext.sqliteClient, id, navigate]);
if (!credential) {
return <div>Loading...</div>;
diff --git a/browser-extensions/chrome/src/pages/CredentialsList.tsx b/browser-extensions/chrome/src/pages/CredentialsList.tsx
index 8b6b76295..262914801 100644
--- a/browser-extensions/chrome/src/pages/CredentialsList.tsx
+++ b/browser-extensions/chrome/src/pages/CredentialsList.tsx
@@ -32,7 +32,7 @@ const CredentialsList: React.FC = () => {
/**
* Retrieve latest vault and refresh the page.
*/
- const onRefresh = async () => {
+ const onRefresh = async () : Promise<void> => {
showLoading();
try {
// Make API call to get latest vault
@@ -68,8 +68,8 @@ const CredentialsList: React.FC = () => {
<ul className="space-y-2">
{credentials.map(cred => (
<li key={cred.Id}
- onClick={() => navigate(`/credentials/${cred.Id}`)}
- className="p-2 border dark:border-gray-600 rounded flex items-center bg-gray-50 dark:bg-gray-800 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700">
+ onClick={() => navigate(`/credentials/${cred.Id}`)}
+ className="p-2 border dark:border-gray-600 rounded flex items-center bg-gray-50 dark:bg-gray-800 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700">
<img
src={cred.Logo ? `data:image/x-icon;base64,${Buffer.from(cred.Logo).toString('base64')}` : '/assets/images/service-placeholder.webp'}
alt={cred.ServiceName}
diff --git a/browser-extensions/chrome/src/pages/EmailDetails.tsx b/browser-extensions/chrome/src/pages/EmailDetails.tsx
index 9251299b9..98af18068 100644
--- a/browser-extensions/chrome/src/pages/EmailDetails.tsx
+++ b/browser-extensions/chrome/src/pages/EmailDetails.tsx
@@ -8,6 +8,9 @@ import { useMinDurationLoading } from '../hooks/useMinDurationLoading';
import EncryptionUtility from '../utils/EncryptionUtility';
import { Buffer } from 'buffer';
+/**
+ * Email details page.
+ */
const EmailDetails: React.FC = () => {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
@@ -18,7 +21,10 @@ const EmailDetails: React.FC = () => {
const [isLoading, setIsLoading] = useMinDurationLoading(true, 150);
useEffect(() => {
- const loadEmail = async () => {
+ /**
+ * Load the email.
+ */
+ const loadEmail = async () : Promise<void> => {
try {
setIsLoading(true);
setError(null);
@@ -66,9 +72,12 @@ const EmailDetails: React.FC = () => {
};
loadEmail();
- }, [id, dbContext?.sqliteClient, webApi]);
+ }, [id, dbContext?.sqliteClient, webApi, setIsLoading]);
- const handleDelete = async () => {
+ /**
+ * Handle deleting an email.
+ */
+ const handleDelete = async () : Promise<void> => {
try {
await webApi.delete(`Email/${id}`);
navigate('/emails');
diff --git a/browser-extensions/chrome/src/pages/Home.tsx b/browser-extensions/chrome/src/pages/Home.tsx
index 41fb2b8ca..6916b4ed0 100644
--- a/browser-extensions/chrome/src/pages/Home.tsx
+++ b/browser-extensions/chrome/src/pages/Home.tsx
@@ -6,6 +6,9 @@ import UnlockSuccess from './UnlockSuccess';
import { useNavigate } from 'react-router-dom';
import { useDb } from '../context/DbContext';
+/**
+ * Home page that shows the correct page based on the user's authentication state.
+ */
const Home: React.FC = () => {
const { isLoggedIn } = useAuth();
const authContext = useAuth();
@@ -16,12 +19,10 @@ const Home: React.FC = () => {
useEffect(() => {
if (isLoggedIn && !needsUnlock && !isInlineUnlockMode) {
- console.log('navigating to credentials');
navigate('/credentials', { replace: true });
}
}, [isLoggedIn, needsUnlock, isInlineUnlockMode, navigate]);
-
if (!isLoggedIn) {
return <Login />;
}
@@ -31,7 +32,6 @@ const Home: React.FC = () => {
}
if (isInlineUnlockMode) {
- console.log('isInlineUnlockMode');
return <UnlockSuccess onClose={() => setIsInlineUnlockMode(false)} />;
}
diff --git a/browser-extensions/chrome/src/pages/Login.tsx b/browser-extensions/chrome/src/pages/Login.tsx
index c359e050f..8e6618c1c 100644
--- a/browser-extensions/chrome/src/pages/Login.tsx
+++ b/browser-extensions/chrome/src/pages/Login.tsx
@@ -64,15 +64,15 @@ const Login: React.FC = () => {
throw new Error('Login failed -- no token returned');
}
- // Make another API call trying to get latest vault
- const vaultResponseJson = await webApi.get('Vault') as VaultResponse;
+ // Make another API call trying to get latest vault
+ const vaultResponseJson = await webApi.get('Vault') as VaultResponse;
- // Attempt to decrypt the blob
- const passwordHashBase64 = Buffer.from(passwordHash).toString('base64');
- const decryptedBlob = await EncryptionUtility.symmetricDecrypt(vaultResponseJson.vault.blob, passwordHashBase64);
+ // Attempt to decrypt the blob
+ const passwordHashBase64 = Buffer.from(passwordHash).toString('base64');
+ const decryptedBlob = await EncryptionUtility.symmetricDecrypt(vaultResponseJson.vault.blob, passwordHashBase64);
- // Initialize the SQLite context with decrypted data
- await dbContext.initializeDatabase(passwordHashBase64, decryptedBlob, vaultResponseJson.vault.publicEmailDomainList, vaultResponseJson.vault.privateEmailDomainList, vaultResponseJson.vault.currentRevisionNumber);
+ // Initialize the SQLite context with decrypted data
+ await dbContext.initializeDatabase(passwordHashBase64, decryptedBlob, vaultResponseJson.vault.publicEmailDomainList, vaultResponseJson.vault.privateEmailDomainList, vaultResponseJson.vault.currentRevisionNumber);
// 3. Handle 2FA if required
/*
diff --git a/browser-extensions/chrome/src/pages/Unlock.tsx b/browser-extensions/chrome/src/pages/Unlock.tsx
index 05ff36775..1b8b0a41b 100644
--- a/browser-extensions/chrome/src/pages/Unlock.tsx
+++ b/browser-extensions/chrome/src/pages/Unlock.tsx
@@ -82,7 +82,6 @@ const Unlock: React.FC = () => {
hideLoading();
}
-
};
return (
diff --git a/browser-extensions/chrome/src/pages/UnlockSuccess.tsx b/browser-extensions/chrome/src/pages/UnlockSuccess.tsx
index 2153ab49d..5f72eaf3a 100644
--- a/browser-extensions/chrome/src/pages/UnlockSuccess.tsx
+++ b/browser-extensions/chrome/src/pages/UnlockSuccess.tsx
@@ -1,13 +1,16 @@
import React from 'react';
+/**
+ *
+ */
const UnlockSuccess: React.FC<{
onClose: () => void;
}> = ({ onClose }) => (
- <div className="flex flex-col items-center justify-center p-6 text-center">
+ <div className="flex flex-col items-center justify-center p-6 text-center">
<div className="mb-4 text-green-600 dark:text-green-400">
- <svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
- </svg>
+ </svg>
</div>
<h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-white">
Your vault is successfully unlocked
@@ -16,20 +19,20 @@ const UnlockSuccess: React.FC<{
You can now use autofill in login forms in your browser.
</p>
<div className="space-y-3 w-full">
- <button
+ <button
onClick={() => window.close()}
className="w-full px-4 py-2 text-white bg-primary-600 rounded hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2"
- >
+ >
Close this popup
- </button>
- <button
+ </button>
+ <button
onClick={() => onClose()}
className="w-full px-4 py-2 text-gray-700 bg-gray-100 rounded hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600"
- >
+ >
Browse vault contents
- </button>
- </div>
- </div>
- );
+ </button>
+ </div>
+ </div>
+);
export default UnlockSuccess;
diff --git a/browser-extensions/chrome/src/utils/ClipboardCopyService.tsx b/browser-extensions/chrome/src/utils/ClipboardCopyService.tsx
index f6c109cf1..322dd05be 100644
--- a/browser-extensions/chrome/src/utils/ClipboardCopyService.tsx
+++ b/browser-extensions/chrome/src/utils/ClipboardCopyService.tsx
@@ -1,24 +1,39 @@
+/**
+ * Clipboard copy service that keeps track of the last copied ID so it can be shown in the UI.
+ */
export class ClipboardCopyService {
- private currentCopiedId: string = '';
- private onCopyCallbacks: ((id: string) => void)[] = [];
+ private currentCopiedId: string = '';
+ private onCopyCallbacks: ((id: string) => void)[] = [];
- public setCopied(id: string) {
- this.currentCopiedId = id;
- this.notifySubscribers();
- }
+ /**
+ * Set the copied ID.
+ */
+ public setCopied(id: string) : void {
+ this.currentCopiedId = id;
+ this.notifySubscribers();
+ }
- public getCopiedId(): string {
- return this.currentCopiedId;
- }
+ /**
+ * Get the copied ID.
+ */
+ public getCopiedId(): string {
+ return this.currentCopiedId;
+ }
- public subscribe(callback: (id: string) => void) {
- this.onCopyCallbacks.push(callback);
- return () => {
- this.onCopyCallbacks = this.onCopyCallbacks.filter(cb => cb !== callback);
- };
- }
+ /**
+ * Subscribe to clipboard copy events.
+ */
+ public subscribe(callback: (id: string) => void) {
+ this.onCopyCallbacks.push(callback);
+ return () : void => {
+ this.onCopyCallbacks = this.onCopyCallbacks.filter(cb => cb !== callback);
+ };
+ }
- private notifySubscribers() {
- this.onCopyCallbacks.forEach(callback => callback(this.currentCopiedId));
- }
- }
\ No newline at end of file
+ /**
+ * Notify subscribers.
+ */
+ private notifySubscribers() : void {
+ this.onCopyCallbacks.forEach(callback => callback(this.currentCopiedId));
+ }
+}
\ No newline at end of file
diff --git a/browser-extensions/chrome/src/utils/EncryptionUtility.tsx b/browser-extensions/chrome/src/utils/EncryptionUtility.tsx
index 72ce06165..d914abe91 100644
--- a/browser-extensions/chrome/src/utils/EncryptionUtility.tsx
+++ b/browser-extensions/chrome/src/utils/EncryptionUtility.tsx
@@ -7,192 +7,192 @@ import argon2 from 'argon2-browser/dist/argon2-bundled.min.js';
* - RSA-OAEP asymmetric encryption/decryption
*/
class EncryptionUtility {
- /**
- * Derives a key from a password using Argon2id
- */
- public static async deriveKeyFromPassword(
- password: string,
- salt: string,
- encryptionType: string = 'Argon2id',
- encryptionSettings: string = '{"Iterations":1,"MemorySize":1024,"DegreeOfParallelism":4}'
- ): Promise<string> {
- const settings = JSON.parse(encryptionSettings);
-
- try {
- if (encryptionType !== 'Argon2Id') {
- throw new Error('Unsupported encryption type');
- }
-
- const hash = await argon2.hash({
- pass: password,
- salt: salt,
- time: settings.Iterations,
- mem: settings.MemorySize,
- parallelism: settings.DegreeOfParallelism,
- hashLen: 32,
- type: 2, // 0 = Argon2d, 1 = Argon2i, 2 = Argon2id
- });
-
- // Return bytes
- return hash.hash;
- } catch (error) {
- console.error('Argon2 hashing failed:', error);
- throw error;
- }
+ /**
+ * Derives a key from a password using Argon2id
+ */
+ public static async deriveKeyFromPassword(
+ password: string,
+ salt: string,
+ encryptionType: string = 'Argon2id',
+ encryptionSettings: string = '{"Iterations":1,"MemorySize":1024,"DegreeOfParallelism":4}'
+ ): Promise<string> {
+ const settings = JSON.parse(encryptionSettings);
+
+ try {
+ if (encryptionType !== 'Argon2Id') {
+ throw new Error('Unsupported encryption type');
+ }
+
+ const hash = await argon2.hash({
+ pass: password,
+ salt: salt,
+ time: settings.Iterations,
+ mem: settings.MemorySize,
+ parallelism: settings.DegreeOfParallelism,
+ hashLen: 32,
+ type: 2, // 0 = Argon2d, 1 = Argon2i, 2 = Argon2id
+ });
+
+ // Return bytes
+ return hash.hash;
+ } catch (error) {
+ console.error('Argon2 hashing failed:', error);
+ throw error;
}
-
- /**
- * Encrypts data using AES-GCM symmetric encryption
- */
- public static async symmetricEncrypt(plaintext: string, base64Key: string): Promise<string> {
- if (!plaintext) return plaintext;
-
- const key = await crypto.subtle.importKey(
- "raw",
- Uint8Array.from(atob(base64Key), c => c.charCodeAt(0)),
- {
- name: "AES-GCM",
- length: 256,
- },
- false,
- ["encrypt"]
- );
-
- const iv = crypto.getRandomValues(new Uint8Array(12));
- const encoder = new TextEncoder();
- const encoded = encoder.encode(plaintext);
-
- const ciphertext = await crypto.subtle.encrypt(
- { name: "AES-GCM", iv: iv },
- key,
- encoded
- );
-
- const combined = new Uint8Array(iv.length + ciphertext.byteLength);
- combined.set(iv, 0);
- combined.set(new Uint8Array(ciphertext), iv.length);
-
- return btoa(
- Array.from(combined)
- .map(byte => String.fromCharCode(byte))
- .join('')
- );
- }
-
- /**
- * Decrypts data using AES-GCM symmetric encryption
- */
- public static async symmetricDecrypt(base64Ciphertext: string, base64Key: string): Promise<string> {
- if (!base64Ciphertext) return base64Ciphertext;
-
- const key = await crypto.subtle.importKey(
- "raw",
- Uint8Array.from(atob(base64Key), c => c.charCodeAt(0)),
- {
- name: "AES-GCM",
- length: 256,
- },
- false,
- ["decrypt"]
- );
-
- const ivAndCiphertext = Uint8Array.from(atob(base64Ciphertext), c => c.charCodeAt(0));
- const iv = ivAndCiphertext.slice(0, 12);
- const ciphertext = ivAndCiphertext.slice(12);
-
- const decrypted = await crypto.subtle.decrypt(
- { name: "AES-GCM", iv: iv },
- key,
- ciphertext
- );
-
- const decoder = new TextDecoder();
- return decoder.decode(decrypted);
- }
-
- /**
- * Generates a new RSA key pair for asymmetric encryption
- */
- public static async generateRsaKeyPair(): Promise<{ publicKey: string, privateKey: string }> {
- const keyPair = await crypto.subtle.generateKey(
- {
- name: "RSA-OAEP",
- modulusLength: 2048,
- publicExponent: new Uint8Array([1, 0, 1]),
- hash: "SHA-256",
- },
- true,
- ["encrypt", "decrypt"]
- );
-
- const publicKey = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
- const privateKey = await crypto.subtle.exportKey("jwk", keyPair.privateKey);
-
- return {
- publicKey: JSON.stringify(publicKey),
- privateKey: JSON.stringify(privateKey)
- };
- }
-
- /**
- * Encrypts data using RSA-OAEP asymmetric encryption with a public key
- */
- public static async encryptWithPublicKey(plaintext: string, publicKey: string): Promise<string> {
- const publicKeyObj = await crypto.subtle.importKey(
- "jwk",
- JSON.parse(publicKey),
- {
- name: "RSA-OAEP",
- hash: "SHA-256",
- },
- false,
- ["encrypt"]
- );
-
- const encodedPlaintext = new TextEncoder().encode(plaintext);
- const cipherBuffer = await crypto.subtle.encrypt(
- {
- name: "RSA-OAEP"
- },
- publicKeyObj,
- encodedPlaintext
- );
-
- return btoa(String.fromCharCode.apply(null, new Uint8Array(cipherBuffer)));
- }
-
- /**
- * Decrypts data using RSA-OAEP asymmetric encryption with a private key
- */
- public static async decryptWithPrivateKey(ciphertext: string, privateKey: string): Promise<Uint8Array> {
- try {
- const privateKeyObj = await crypto.subtle.importKey(
- "jwk",
- JSON.parse(privateKey),
- {
- name: "RSA-OAEP",
- hash: "SHA-256",
- },
- true,
- ["decrypt"]
- );
-
- const cipherBuffer = Uint8Array.from(atob(ciphertext), c => c.charCodeAt(0));
- const plaintextBuffer = await crypto.subtle.decrypt(
- {
- name: "RSA-OAEP",
- hash: "SHA-256",
- },
- privateKeyObj,
- cipherBuffer
- );
-
- return new Uint8Array(plaintextBuffer);
- } catch (error) {
- console.error('RSA decryption failed:', error);
- throw new Error(`Failed to decrypt: ${error.message}`);
- }
+ }
+
+ /**
+ * Encrypts data using AES-GCM symmetric encryption
+ */
+ public static async symmetricEncrypt(plaintext: string, base64Key: string): Promise<string> {
+ if (!plaintext) return plaintext;
+
+ const key = await crypto.subtle.importKey(
+ "raw",
+ Uint8Array.from(atob(base64Key), c => c.charCodeAt(0)),
+ {
+ name: "AES-GCM",
+ length: 256,
+ },
+ false,
+ ["encrypt"]
+ );
+
+ const iv = crypto.getRandomValues(new Uint8Array(12));
+ const encoder = new TextEncoder();
+ const encoded = encoder.encode(plaintext);
+
+ const ciphertext = await crypto.subtle.encrypt(
+ { name: "AES-GCM", iv: iv },
+ key,
+ encoded
+ );
+
+ const combined = new Uint8Array(iv.length + ciphertext.byteLength);
+ combined.set(iv, 0);
+ combined.set(new Uint8Array(ciphertext), iv.length);
+
+ return btoa(
+ Array.from(combined)
+ .map(byte => String.fromCharCode(byte))
+ .join('')
+ );
+ }
+
+ /**
+ * Decrypts data using AES-GCM symmetric encryption
+ */
+ public static async symmetricDecrypt(base64Ciphertext: string, base64Key: string): Promise<string> {
+ if (!base64Ciphertext) return base64Ciphertext;
+
+ const key = await crypto.subtle.importKey(
+ "raw",
+ Uint8Array.from(atob(base64Key), c => c.charCodeAt(0)),
+ {
+ name: "AES-GCM",
+ length: 256,
+ },
+ false,
+ ["decrypt"]
+ );
+
+ const ivAndCiphertext = Uint8Array.from(atob(base64Ciphertext), c => c.charCodeAt(0));
+ const iv = ivAndCiphertext.slice(0, 12);
+ const ciphertext = ivAndCiphertext.slice(12);
+
+ const decrypted = await crypto.subtle.decrypt(
+ { name: "AES-GCM", iv: iv },
+ key,
+ ciphertext
+ );
+
+ const decoder = new TextDecoder();
+ return decoder.decode(decrypted);
+ }
+
+ /**
+ * Generates a new RSA key pair for asymmetric encryption
+ */
+ public static async generateRsaKeyPair(): Promise<{ publicKey: string, privateKey: string }> {
+ const keyPair = await crypto.subtle.generateKey(
+ {
+ name: "RSA-OAEP",
+ modulusLength: 2048,
+ publicExponent: new Uint8Array([1, 0, 1]),
+ hash: "SHA-256",
+ },
+ true,
+ ["encrypt", "decrypt"]
+ );
+
+ const publicKey = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
+ const privateKey = await crypto.subtle.exportKey("jwk", keyPair.privateKey);
+
+ return {
+ publicKey: JSON.stringify(publicKey),
+ privateKey: JSON.stringify(privateKey)
+ };
+ }
+
+ /**
+ * Encrypts data using RSA-OAEP asymmetric encryption with a public key
+ */
+ public static async encryptWithPublicKey(plaintext: string, publicKey: string): Promise<string> {
+ const publicKeyObj = await crypto.subtle.importKey(
+ "jwk",
+ JSON.parse(publicKey),
+ {
+ name: "RSA-OAEP",
+ hash: "SHA-256",
+ },
+ false,
+ ["encrypt"]
+ );
+
+ const encodedPlaintext = new TextEncoder().encode(plaintext);
+ const cipherBuffer = await crypto.subtle.encrypt(
+ {
+ name: "RSA-OAEP"
+ },
+ publicKeyObj,
+ encodedPlaintext
+ );
+
+ return btoa(String.fromCharCode.apply(null, new Uint8Array(cipherBuffer)));
+ }
+
+ /**
+ * Decrypts data using RSA-OAEP asymmetric encryption with a private key
+ */
+ public static async decryptWithPrivateKey(ciphertext: string, privateKey: string): Promise<Uint8Array> {
+ try {
+ const privateKeyObj = await crypto.subtle.importKey(
+ "jwk",
+ JSON.parse(privateKey),
+ {
+ name: "RSA-OAEP",
+ hash: "SHA-256",
+ },
+ true,
+ ["decrypt"]
+ );
+
+ const cipherBuffer = Uint8Array.from(atob(ciphertext), c => c.charCodeAt(0));
+ const plaintextBuffer = await crypto.subtle.decrypt(
+ {
+ name: "RSA-OAEP",
+ hash: "SHA-256",
+ },
+ privateKeyObj,
+ cipherBuffer
+ );
+
+ return new Uint8Array(plaintextBuffer);
+ } catch (error) {
+ console.error('RSA decryption failed:', error);
+ throw new Error(`Failed to decrypt: ${error.message}`);
}
+ }
}
export default EncryptionUtility;
diff --git a/browser-extensions/chrome/src/utils/SqliteClient.tsx b/browser-extensions/chrome/src/utils/SqliteClient.tsx
index 001aec74b..1c903fc22 100644
--- a/browser-extensions/chrome/src/utils/SqliteClient.tsx
+++ b/browser-extensions/chrome/src/utils/SqliteClient.tsx
@@ -6,125 +6,125 @@ import { EncryptionKey } from '../types/EncryptionKey';
* Client for interacting with the SQLite database.
*/
class SqliteClient {
- private db: Database | null = null;
+ private db: Database | null = null;
- /**
- * Initialize the SQLite database from a base64 string
- */
- public async initializeFromBase64(base64String: string): Promise<void> {
- try {
- // Convert base64 to Uint8Array
- const binaryString = atob(base64String);
- const bytes = new Uint8Array(binaryString.length);
- for (let i = 0; i < binaryString.length; i++) {
- bytes[i] = binaryString.charCodeAt(i);
- }
+ /**
+ * Initialize the SQLite database from a base64 string
+ */
+ public async initializeFromBase64(base64String: string): Promise<void> {
+ try {
+ // Convert base64 to Uint8Array
+ const binaryString = atob(base64String);
+ const bytes = new Uint8Array(binaryString.length);
+ for (let i = 0; i < binaryString.length; i++) {
+ bytes[i] = binaryString.charCodeAt(i);
+ }
- // Initialize SQL.js with the WASM file from the local file system.
- const SQL = await initSqlJs({
- /**
- * Locates SQL.js files from the local file system.
- * @param file - The name of the file to locate
- * @returns The complete URL path to the file
- */
- locateFile: (file: string) => `src/${file}`
- });
+ // Initialize SQL.js with the WASM file from the local file system.
+ const SQL = await initSqlJs({
+ /**
+ * Locates SQL.js files from the local file system.
+ * @param file - The name of the file to locate
+ * @returns The complete URL path to the file
+ */
+ locateFile: (file: string) => `src/${file}`
+ });
- // Create database from the binary data
- this.db = new SQL.Database(bytes);
- } catch (error) {
- console.error('Error initializing SQLite database:', error);
- throw error;
- }
+ // Create database from the binary data
+ this.db = new SQL.Database(bytes);
+ } catch (error) {
+ console.error('Error initializing SQLite database:', error);
+ throw error;
}
+ }
- /**
- * Export the SQLite database to a base64 string
- * @returns Base64 encoded string of the database
- */
- public exportToBase64(): string {
- if (!this.db) {
- throw new Error('Database not initialized');
- }
+ /**
+ * Export the SQLite database to a base64 string
+ * @returns Base64 encoded string of the database
+ */
+ public exportToBase64(): string {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
- try {
- // Export database to Uint8Array
- const binaryArray = this.db.export();
+ try {
+ // Export database to Uint8Array
+ const binaryArray = this.db.export();
- // Convert Uint8Array to base64 string
- let binaryString = '';
- for (let i = 0; i < binaryArray.length; i++) {
- binaryString += String.fromCharCode(binaryArray[i]);
- }
- return btoa(binaryString);
- } catch (error) {
- console.error('Error exporting SQLite database:', error);
- throw error;
- }
+ // Convert Uint8Array to base64 string
+ let binaryString = '';
+ for (let i = 0; i < binaryArray.length; i++) {
+ binaryString += String.fromCharCode(binaryArray[i]);
+ }
+ return btoa(binaryString);
+ } catch (error) {
+ console.error('Error exporting SQLite database:', error);
+ throw error;
}
+ }
- /**
- * Execute a SELECT query
- */
- public executeQuery<T>(query: string, params: (string | number | null | Uint8Array)[] = []): T[] {
- if (!this.db) {
- throw new Error('Database not initialized');
- }
+ /**
+ * Execute a SELECT query
+ */
+ public executeQuery<T>(query: string, params: (string | number | null | Uint8Array)[] = []): T[] {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
- try {
- const stmt = this.db.prepare(query);
- stmt.bind(params);
+ try {
+ const stmt = this.db.prepare(query);
+ stmt.bind(params);
- const results: T[] = [];
- while (stmt.step()) {
- results.push(stmt.getAsObject());
- }
- stmt.free();
+ const results: T[] = [];
+ while (stmt.step()) {
+ results.push(stmt.getAsObject());
+ }
+ stmt.free();
- return results;
- } catch (error) {
- console.error('Error executing query:', error);
- throw error;
- }
+ return results;
+ } catch (error) {
+ console.error('Error executing query:', error);
+ throw error;
}
+ }
- /**
- * Execute an INSERT, UPDATE, or DELETE query
- */
- public executeUpdate(query: string, params: (string | number | null | Uint8Array)[] = []): number {
- if (!this.db) {
- throw new Error('Database not initialized');
- }
+ /**
+ * Execute an INSERT, UPDATE, or DELETE query
+ */
+ public executeUpdate(query: string, params: (string | number | null | Uint8Array)[] = []): number {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
- try {
- const stmt = this.db.prepare(query);
- stmt.bind(params);
- stmt.step();
- const changes = this.db.getRowsModified();
- stmt.free();
- return changes;
- } catch (error) {
- console.error('Error executing update:', error);
- throw error;
- }
+ try {
+ const stmt = this.db.prepare(query);
+ stmt.bind(params);
+ stmt.step();
+ const changes = this.db.getRowsModified();
+ stmt.free();
+ return changes;
+ } catch (error) {
+ console.error('Error executing update:', error);
+ throw error;
}
+ }
- /**
- * Close the database connection and free resources
- */
- public close(): void {
- if (this.db) {
- this.db.close();
- this.db = null;
- }
+ /**
+ * Close the database connection and free resources
+ */
+ public close(): void {
+ if (this.db) {
+ this.db.close();
+ this.db = null;
}
+ }
- /**
- * Fetch all credentials with their associated service information
- * @returns Array of Credential objects with service details
- */
- public getAllCredentials(): Credential[] {
- const query = `
+ /**
+ * Fetch all credentials with their associated service information
+ * @returns Array of Credential objects with service details
+ */
+ public getAllCredentials(): Credential[] {
+ const query = `
SELECT DISTINCT
c.Id,
c.Username,
@@ -147,144 +147,144 @@ class SqliteClient {
WHERE c.IsDeleted = 0
ORDER BY c.CreatedAt DESC`;
- const results = this.executeQuery(query);
+ const results = this.executeQuery(query);
- return results.map((row: any) => ({
- Id: row.Id,
- Username: row.Username,
- Password: row.Password,
- Email: row.Email,
- ServiceName: row.ServiceName,
- ServiceUrl: row.ServiceUrl,
- Logo: row.Logo,
- Notes: row.Notes,
- Alias: {
- FirstName: row.FirstName,
- LastName: row.LastName,
- NickName: row.NickName,
- BirthDate: row.BirthDate,
- Gender: row.Gender,
- Email: row.Email
- }
- }));
- }
+ return results.map((row: any) => ({
+ Id: row.Id,
+ Username: row.Username,
+ Password: row.Password,
+ Email: row.Email,
+ ServiceName: row.ServiceName,
+ ServiceUrl: row.ServiceUrl,
+ Logo: row.Logo,
+ Notes: row.Notes,
+ Alias: {
+ FirstName: row.FirstName,
+ LastName: row.LastName,
+ NickName: row.NickName,
+ BirthDate: row.BirthDate,
+ Gender: row.Gender,
+ Email: row.Email
+ }
+ }));
+ }
- /**
- * Fetch all encryption keys.
- */
- public getAllEncryptionKeys(): EncryptionKey[] {
- return this.executeQuery<EncryptionKey>(`SELECT
+ /**
+ * Fetch all encryption keys.
+ */
+ public getAllEncryptionKeys(): EncryptionKey[] {
+ return this.executeQuery<EncryptionKey>(`SELECT
x.PublicKey,
x.PrivateKey,
x.IsPrimary
FROM EncryptionKeys x`);
- }
+ }
- /**
- * Create a new credential with associated entities
- * @param credential The credential object to insert
- * @returns The number of rows modified
- */
- public createCredential(credential: Credential): number {
- if (!this.db) {
- throw new Error('Database not initialized');
- }
+ /**
+ * Create a new credential with associated entities
+ * @param credential The credential object to insert
+ * @returns The number of rows modified
+ */
+ public createCredential(credential: Credential): number {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
- try {
- this.db.run('BEGIN TRANSACTION');
+ try {
+ this.db.run('BEGIN TRANSACTION');
- // 1. Insert Service
- let logoData = null;
- try {
- if (credential.Logo) {
- // Handle object-like array conversion
- if (typeof credential.Logo === 'object' && !ArrayBuffer.isView(credential.Logo)) {
- const values = Object.values(credential.Logo);
- logoData = new Uint8Array(values);
- }
- // Handle existing array types
- else if (Array.isArray(credential.Logo) || credential.Logo instanceof ArrayBuffer || credential.Logo instanceof Uint8Array) {
- logoData = new Uint8Array(credential.Logo);
- }
- }
- } catch (error) {
- console.warn('Failed to convert logo to Uint8Array:', error);
- logoData = null;
- }
+ // 1. Insert Service
+ let logoData = null;
+ try {
+ if (credential.Logo) {
+ // Handle object-like array conversion
+ if (typeof credential.Logo === 'object' && !ArrayBuffer.isView(credential.Logo)) {
+ const values = Object.values(credential.Logo);
+ logoData = new Uint8Array(values);
+ }
+ // Handle existing array types
+ else if (Array.isArray(credential.Logo) || credential.Logo instanceof ArrayBuffer || credential.Logo instanceof Uint8Array) {
+ logoData = new Uint8Array(credential.Logo);
+ }
+ }
+ } catch (error) {
+ console.warn('Failed to convert logo to Uint8Array:', error);
+ logoData = null;
+ }
- const serviceQuery = `
+ const serviceQuery = `
INSERT INTO Services (Id, Name, Url, Logo, CreatedAt, UpdatedAt)
VALUES (?, ?, ?, ?, ?, ?)`;
- const serviceId = crypto.randomUUID().toUpperCase();
- const currentDateTime = new Date().toISOString()
- .replace('T', ' ')
- .replace('Z', '')
- .substring(0, 23);
- const serviceResult = this.executeUpdate(serviceQuery, [
- serviceId,
- credential.ServiceName,
- credential.ServiceUrl ?? null,
- logoData,
- currentDateTime,
- currentDateTime
- ]);
+ const serviceId = crypto.randomUUID().toUpperCase();
+ const currentDateTime = new Date().toISOString()
+ .replace('T', ' ')
+ .replace('Z', '')
+ .substring(0, 23);
+ this.executeUpdate(serviceQuery, [
+ serviceId,
+ credential.ServiceName,
+ credential.ServiceUrl ?? null,
+ logoData,
+ currentDateTime,
+ currentDateTime
+ ]);
- // 2. Insert Alias
- const aliasQuery = `
+ // 2. Insert Alias
+ const aliasQuery = `
INSERT INTO Aliases (Id, FirstName, LastName, NickName, BirthDate, Gender, Email, CreatedAt, UpdatedAt)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
- const aliasId = crypto.randomUUID().toUpperCase();
- const aliasResult = this.executeUpdate(aliasQuery, [
- aliasId,
- credential.Alias.FirstName ?? null,
- credential.Alias.LastName ?? null,
- credential.Alias.NickName ?? null,
- credential.Alias.BirthDate ?? null,
- credential.Alias.Gender ?? null,
- credential.Alias.Email ?? null,
- currentDateTime,
- currentDateTime
- ]);
+ const aliasId = crypto.randomUUID().toUpperCase();
+ this.executeUpdate(aliasQuery, [
+ aliasId,
+ credential.Alias.FirstName ?? null,
+ credential.Alias.LastName ?? null,
+ credential.Alias.NickName ?? null,
+ credential.Alias.BirthDate ?? null,
+ credential.Alias.Gender ?? null,
+ credential.Alias.Email ?? null,
+ currentDateTime,
+ currentDateTime
+ ]);
- // 3. Insert Credential
- const credentialQuery = `
+ // 3. Insert Credential
+ const credentialQuery = `
INSERT INTO Credentials (Id, Username, Notes, ServiceId, AliasId, CreatedAt, UpdatedAt)
VALUES (?, ?, ?, ?, ?, ?, ?)`;
- const credentialId = crypto.randomUUID().toUpperCase();
- const credentialResult = this.executeUpdate(credentialQuery, [
- credentialId,
- credential.Username,
- credential.Notes ?? null,
- serviceId,
- aliasId,
- currentDateTime,
- currentDateTime
- ]);
+ const credentialId = crypto.randomUUID().toUpperCase();
+ this.executeUpdate(credentialQuery, [
+ credentialId,
+ credential.Username,
+ credential.Notes ?? null,
+ serviceId,
+ aliasId,
+ currentDateTime,
+ currentDateTime
+ ]);
- // 4. Insert Password
- if (credential.Password) {
- const passwordQuery = `
+ // 4. Insert Password
+ if (credential.Password) {
+ const passwordQuery = `
INSERT INTO Passwords (Id, Value, CredentialId, CreatedAt, UpdatedAt)
VALUES (?, ?, ?, ?, ?)`;
- const passwordId = crypto.randomUUID().toUpperCase();
- this.executeUpdate(passwordQuery, [
- passwordId,
- credential.Password,
- credentialId,
- currentDateTime,
- currentDateTime
- ]);
- }
+ const passwordId = crypto.randomUUID().toUpperCase();
+ this.executeUpdate(passwordQuery, [
+ passwordId,
+ credential.Password,
+ credentialId,
+ currentDateTime,
+ currentDateTime
+ ]);
+ }
- this.db.run('COMMIT');
- return 1;
+ this.db.run('COMMIT');
+ return 1;
- } catch (error) {
- this.db.run('ROLLBACK');
- console.error('Error creating credential:', error);
- throw error;
- }
+ } catch (error) {
+ this.db.run('ROLLBACK');
+ console.error('Error creating credential:', error);
+ throw error;
}
+ }
}
export default SqliteClient;
\ No newline at end of file
diff --git a/browser-extensions/chrome/src/utils/WebApiService.ts b/browser-extensions/chrome/src/utils/WebApiService.ts
index dc55b27b1..d78fe20f1 100644
--- a/browser-extensions/chrome/src/utils/WebApiService.ts
+++ b/browser-extensions/chrome/src/utils/WebApiService.ts
@@ -190,7 +190,6 @@ export class WebApiService {
*/
private async getAccessToken(): Promise<string | null> {
const token = await chrome.storage.local.get('accessToken');
- console.log('accessToken get', token);
return token.accessToken || null;
}
@@ -199,7 +198,6 @@ export class WebApiService {
*/
private async getRefreshToken(): Promise<string | null> {
const token = await chrome.storage.local.get('refreshToken');
- console.log('refreshToken get', token);
return token.refreshToken || null;
}
diff --git a/browser-extensions/chrome/src/utils/form-detector/FormDetector.ts b/browser-extensions/chrome/src/utils/form-detector/FormDetector.ts
index de5809006..f5eeea3c4 100644
--- a/browser-extensions/chrome/src/utils/form-detector/FormDetector.ts
+++ b/browser-extensions/chrome/src/utils/form-detector/FormDetector.ts
@@ -1,40 +1,15 @@
-type LoginForm = {
- form: HTMLFormElement | null;
- emailField: HTMLInputElement | null;
- emailConfirmField: HTMLInputElement | null;
- usernameField: HTMLInputElement | null;
- passwordField: HTMLInputElement | null;
- passwordConfirmField: HTMLInputElement | null;
-
- // Identity fields
- firstNameField: HTMLInputElement | null;
- lastNameField: HTMLInputElement | null;
-
- // Birthdate fields can be either a single field or multiple fields
- birthdateField: {
- single: HTMLInputElement | null;
- format: string; // 'yyyy-mm-dd' | 'dd-mm-yyyy' | 'mm-dd-yyyy'
- day: HTMLInputElement | null;
- month: HTMLInputElement | null;
- year: HTMLInputElement | null;
- };
-
- // Gender field can be either select, radio or text input
- genderField: {
- type: 'select' | 'radio' | 'text';
- field: HTMLInputElement | HTMLSelectElement | null;
- radioButtons?: {
- male: HTMLInputElement | null;
- female: HTMLInputElement | null;
- other: HTMLInputElement | null;
- };
- };
-}
+import { LoginForm } from "./types/LoginForm";
+/**
+ * Form detector.
+ */
export class FormDetector {
private document: Document;
- constructor(document: Document) {
+ /**
+ * Constructor.
+ */
+ public constructor(document: Document) {
this.document = document;
}
@@ -52,13 +27,14 @@ export class FormDetector {
// Create a Set to track processed forms to avoid duplicates
const processedForms = new Set<HTMLFormElement | null>();
- // Helper to create a form entry
+ /**
+ * Helper to create a form entry
+ */
const createFormEntry = (
form: HTMLFormElement | null,
- emailField: HTMLInputElement | null,
usernameField: HTMLInputElement | null,
passwordField: HTMLInputElement | null
- ) => {
+ ) : void => {
// Skip if we've already processed this form
if (form && processedForms.has(form)) return;
processedForms.add(form);
@@ -90,9 +66,8 @@ export class FormDetector {
// Process password fields first
passwordFields.forEach(passwordField => {
const form = passwordField.closest('form');
- const emailField = this.findEmailField(passwordField).primary;
const usernameField = this.findUsernameField(passwordField);
- createFormEntry(form, emailField, usernameField, passwordField);
+ createFormEntry(form, usernameField, passwordField);
});
// Process email fields that aren't already part of a processed form
@@ -104,7 +79,7 @@ export class FormDetector {
const passwordField = form ?
form.querySelector<HTMLInputElement>('input[type="password"]') : null;
const usernameField = this.findUsernameField(field);
- createFormEntry(form, field, usernameField, passwordField);
+ createFormEntry(form, usernameField, passwordField);
}
});
@@ -116,8 +91,7 @@ export class FormDetector {
if (this.isLikelyUsernameField(field)) {
const passwordField = form ?
form.querySelector<HTMLInputElement>('input[type="password"]') : null;
- const emailField = this.findEmailField(field).primary;
- createFormEntry(form, emailField, field, passwordField);
+ createFormEntry(form, field, passwordField);
}
});
@@ -231,6 +205,9 @@ export class FormDetector {
let confirmEmail: HTMLInputElement | null = null;
// Helper function to check if an input is an email field
+ /**
+ *
+ */
const isEmailField = (input: HTMLInputElement, confirmPatterns: string[] = []): boolean => {
const type = input.type.toLowerCase();
if (type === 'text' || type === 'email') {
@@ -286,6 +263,9 @@ export class FormDetector {
};
}
+ /**
+ *
+ */
private findBirthdateFields(form: HTMLFormElement | null): LoginForm['birthdateField'] {
// First try to find a single date input
const singleDateField = this.findInputField(form, ['birthdate', 'birth-date', 'dob', 'geboortedatum'], ['date', 'text']);
@@ -355,6 +335,9 @@ export class FormDetector {
};
}
+ /**
+ *
+ */
private findGenderField(form: HTMLFormElement | null): LoginForm['genderField'] {
// Try to find select element first
const selectField = form
@@ -379,7 +362,10 @@ export class FormDetector {
const femalePatterns = ['female', 'woman', 'f', 'vrouw', 'gender2'];
const otherPatterns = ['other', 'diverse', 'custom', 'prefer not', 'anders', 'iets', 'unknown', 'gender3'];
- const findRadioByPatterns = (patterns: string[], isOther: boolean = false) => {
+ /**
+ *
+ */
+ const findRadioByPatterns = (patterns: string[], isOther: boolean = false) : HTMLInputElement | null => {
return Array.from(radioButtons).find(radio => {
const attributes = [
radio.value,
diff --git a/browser-extensions/chrome/src/utils/form-detector/__tests__/FormDetector.test.ts b/browser-extensions/chrome/src/utils/form-detector/__tests__/FormDetector.test.ts
index cb7ef070f..7c0e4ccbb 100644
--- a/browser-extensions/chrome/src/utils/form-detector/__tests__/FormDetector.test.ts
+++ b/browser-extensions/chrome/src/utils/form-detector/__tests__/FormDetector.test.ts
@@ -1,16 +1,23 @@
import { FormDetector } from '../FormDetector';
import { readFileSync } from 'fs';
import { join } from 'path';
-import { describe, it, expect, beforeEach } from 'vitest';
+import { describe, it, expect } from 'vitest';
import { JSDOM } from 'jsdom';
+import { LoginForm } from '../types/LoginForm';
// Helper function to load HTML test files
+/**
+ *
+ */
const loadTestHtml = (filename: string): string => {
return readFileSync(join(__dirname, 'test-forms', filename), 'utf-8');
};
// Helper function to setup form detection test
-const setupFormTest = (htmlFile: string) => {
+/**
+ *
+ */
+const setupFormTest = (htmlFile: string) : { document: Document, result: LoginForm } => {
const html = loadTestHtml(htmlFile);
const dom = new JSDOM(html, {
url: 'http://localhost',
@@ -42,8 +49,10 @@ enum FormField {
GenderOther = 'genderOther'
}
-// Helper function to test field detection
-const testField = (fieldName: FormField, elementId: string, htmlFile: string) => {
+/**
+ * Helper function to test field detection
+ */
+const testField = (fieldName: FormField, elementId: string, htmlFile: string) : void => {
it(`should detect ${fieldName} field`, () => {
const { document, result } = setupFormTest(htmlFile);
@@ -83,7 +92,10 @@ const testField = (fieldName: FormField, elementId: string, htmlFile: string) =>
};
// New helper function to test birthdate format property
-const testBirthdateFormat = (expectedFormat: string, htmlFile: string) => {
+/**
+ *
+ */
+const testBirthdateFormat = (expectedFormat: string, htmlFile: string) : void => {
it('should detect correct birthdate format', () => {
const { result } = setupFormTest(htmlFile);
expect(result.birthdateField.format).toBe(expectedFormat);
diff --git a/browser-extensions/chrome/src/utils/form-detector/types/LoginForm.ts b/browser-extensions/chrome/src/utils/form-detector/types/LoginForm.ts
new file mode 100644
index 000000000..50b74c557
--- /dev/null
+++ b/browser-extensions/chrome/src/utils/form-detector/types/LoginForm.ts
@@ -0,0 +1,32 @@
+export type LoginForm = {
+ form: HTMLFormElement | null;
+ emailField: HTMLInputElement | null;
+ emailConfirmField: HTMLInputElement | null;
+ usernameField: HTMLInputElement | null;
+ passwordField: HTMLInputElement | null;
+ passwordConfirmField: HTMLInputElement | null;
+
+ // Identity fields
+ firstNameField: HTMLInputElement | null;
+ lastNameField: HTMLInputElement | null;
+
+ // Birthdate fields can be either a single field or multiple fields
+ birthdateField: {
+ single: HTMLInputElement | null;
+ format: string; // 'yyyy-mm-dd' | 'dd-mm-yyyy' | 'mm-dd-yyyy'
+ day: HTMLInputElement | null;
+ month: HTMLInputElement | null;
+ year: HTMLInputElement | null;
+ };
+
+ // Gender field can be either select, radio or text input
+ genderField: {
+ type: 'select' | 'radio' | 'text';
+ field: HTMLInputElement | HTMLSelectElement | null;
+ radioButtons?: {
+ male: HTMLInputElement | null;
+ female: HTMLInputElement | null;
+ other: HTMLInputElement | null;
+ };
+ };
+ }