Skip to content

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

Tweak favicon logic and misc UI (#1404)

Leendert de Borst02c62962405a
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Forms/AddFieldMenu.tsx b/apps/browser-extension/src/entrypoints/popup/components/Forms/AddFieldMenu.tsx
index 527fa8d10..ce0ab58a6 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Forms/AddFieldMenu.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Forms/AddFieldMenu.tsx
@@ -196,7 +196,7 @@ const AddFieldMenu: React.FC<AddFieldMenuProps> = ({
<button
type="button"
onClick={() => setIsOpen(!isOpen)}
- className="w-full px-4 py-3 border-2 border-dashed border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 rounded-md hover:border-primary-500 hover:text-primary-600 dark:hover:text-primary-400 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 transition-colors flex items-center justify-center gap-2"
+ className="w-full px-4 py-2 border-2 border-dashed border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 rounded-md hover:border-primary-500 hover:text-primary-600 dark:hover:text-primary-400 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 transition-colors flex items-center justify-center gap-2"
>
<PlusIcon />
</button>
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Forms/EmailDomainField.tsx b/apps/browser-extension/src/entrypoints/popup/components/Forms/EmailDomainField.tsx
index 2096b2348..9c1f6200c 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Forms/EmailDomainField.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Forms/EmailDomainField.tsx
@@ -10,6 +10,20 @@ type EmailDomainFieldProps = {
onChange: (value: string) => void;
error?: string;
required?: boolean;
+ /**
+ * When true, defaults to free text mode (custom domain) instead of domain chooser.
+ * Also changes the toggle button labels to "Generate alias email" / "Enter normal email".
+ */
+ defaultToFreeText?: boolean;
+ /**
+ * Callback to remove this field. When provided, shows an X button in the label.
+ */
+ onRemove?: () => void;
+ /**
+ * Callback to generate an alias email. When provided and defaultToFreeText is true,
+ * clicking "Generate alias email" will call this instead of just toggling mode.
+ */
+ onGenerateAlias?: () => void;
}
// Hardcoded public email domains (same as in AliasVault.Client)
@@ -36,11 +50,14 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
value,
onChange,
error,
- required = false
+ required = false,
+ defaultToFreeText = false,
+ onRemove,
+ onGenerateAlias
}) => {
const { t } = useTranslation();
const dbContext = useDb();
- const [isCustomDomain, setIsCustomDomain] = useState(false);
+ const [isCustomDomain, setIsCustomDomain] = useState(defaultToFreeText);
const [localPart, setLocalPart] = useState('');
const [selectedDomain, setSelectedDomain] = useState('');
const [isPopupVisible, setIsPopupVisible] = useState(false);
@@ -153,10 +170,15 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
if (newIsCustom) {
/*
- * Switching to custom domain mode
- * If we have a domain-based value, extract just the local part
+ * Switching to custom domain mode (free text / normal email)
+ * If defaultToFreeText is true (Login type), clear the field so user can enter their own email
+ * Otherwise, extract just the local part from the domain-based value
*/
- if (value && value.includes('@')) {
+ if (defaultToFreeText) {
+ // Clear the field for Login type - user wants to enter their own email
+ onChange('');
+ setLocalPart('');
+ } else if (value && value.includes('@')) {
const [local] = value.split('@');
onChange(local);
setLocalPart(local);
@@ -176,7 +198,7 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
onChange(`${value}@${defaultDomain}`);
}
}
- }, [isCustomDomain, value, localPart, showPrivateDomains, privateEmailDomains, onChange]);
+ }, [isCustomDomain, value, localPart, showPrivateDomains, privateEmailDomains, onChange, defaultToFreeText]);
// Handle clicks outside the popup
useEffect(() => {
@@ -197,12 +219,39 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
}
}, [isPopupVisible]);
+ /**
+ * Handle the "Generate alias email" button click.
+ * Calls onGenerateAlias if provided, and switches to domain chooser mode.
+ */
+ const handleGenerateAliasClick = useCallback(() => {
+ if (onGenerateAlias) {
+ onGenerateAlias();
+ }
+ // Always switch to domain chooser mode
+ setIsCustomDomain(false);
+ }, [onGenerateAlias]);
+
return (
<div className="space-y-2">
- <label htmlFor={id} className="block font-medium text-gray-700 dark:text-gray-300">
- {label}
- {required && <span className="text-red-500 ml-1">*</span>}
- </label>
+ <div className="flex items-center justify-between">
+ <label htmlFor={id} className="block font-medium text-gray-700 dark:text-gray-300">
+ {label}
+ {required && <span className="text-red-500 ml-1">*</span>}
+ </label>
+ {onRemove && (
+ <button
+ type="button"
+ onClick={onRemove}
+ className="w-5 h-5 flex items-center justify-center text-gray-300 hover:text-red-400 dark:text-gray-500 dark:hover:text-red-400 transition-colors"
+ title={t('common.delete')}
+ >
+ <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
+ <line x1="18" y1="6" x2="6" y2="18"/>
+ <line x1="6" y1="6" x2="18" y2="18"/>
+ </svg>
+ </button>
+ )}
+ </div>
<div className="relative w-full">
<div className="flex w-full">
@@ -216,7 +265,7 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
} focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-white`}
value={isCustomDomain ? value : localPart}
onChange={handleLocalPartChange}
- placeholder={isCustomDomain ? t('credentials.enterFullEmail') : t('credentials.enterEmailPrefix')}
+ placeholder={isCustomDomain ? t('credentials.enterRealEmail') : t('credentials.enterEmailPrefix')}
/>
{!isCustomDomain && (
@@ -300,12 +349,12 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
<div>
<button
type="button"
- onClick={toggleCustomDomain}
+ onClick={isCustomDomain && defaultToFreeText ? handleGenerateAliasClick : toggleCustomDomain}
className="text-sm text-primary-600 dark:text-primary-400 hover:text-primary-700 dark:hover:text-primary-300"
>
{isCustomDomain
- ? t('credentials.useDomainChooser')
- : t('credentials.enterCustomDomain')}
+ ? (defaultToFreeText ? t('credentials.generateAliasEmail') : t('credentials.useDomainChooser'))
+ : (defaultToFreeText ? t('credentials.enterNormalEmail') : t('credentials.enterCustomDomain'))}
</button>
</div>
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemAddEdit.tsx
index 7ba677927..e3af86129 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemAddEdit.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemAddEdit.tsx
@@ -1,6 +1,9 @@
+import { Buffer } from 'buffer';
+
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
+import { sendMessage } from 'webext-bridge/popup';
import AttachmentUploader from '@/entrypoints/popup/components/Credentials/Details/AttachmentUploader';
import PasskeyEditor from '@/entrypoints/popup/components/Credentials/Details/PasskeyEditor';
@@ -8,6 +11,7 @@ import TotpEditor from '@/entrypoints/popup/components/Credentials/Details/TotpE
import Modal from '@/entrypoints/popup/components/Dialogs/Modal';
import AddFieldMenu from '@/entrypoints/popup/components/Forms/AddFieldMenu';
import EditableFieldLabel from '@/entrypoints/popup/components/Forms/EditableFieldLabel';
+import EmailDomainField from '@/entrypoints/popup/components/Forms/EmailDomainField';
import { FormInput } from '@/entrypoints/popup/components/Forms/FormInput';
import FormSection from '@/entrypoints/popup/components/Forms/FormSection';
import HiddenField from '@/entrypoints/popup/components/Forms/HiddenField';
@@ -20,11 +24,17 @@ import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useHeaderButtons } from '@/entrypoints/popup/context/HeaderButtonsContext';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
+import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import useAliasGenerator from '@/entrypoints/popup/hooks/useAliasGenerator';
import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
+import { SKIP_FORM_RESTORE_KEY } from '@/utils/Constants';
import type { Item, ItemField, ItemType, FieldType, Attachment, TotpCode } from '@/utils/dist/core/models/vault';
import { FieldCategories, FieldTypes, ItemTypes, getSystemFieldsForItemType, isFieldShownByDefault } from '@/utils/dist/core/models/vault';
+import { ServiceDetectionUtility } from '@/utils/serviceDetection/ServiceDetectionUtility';
+import { SqliteClient } from '@/utils/SqliteClient';
+
+import { browser } from '#imports';
// Valid item types from the shared model
const VALID_ITEM_TYPES: ItemType[] = [ItemTypes.Login, ItemTypes.Alias, ItemTypes.CreditCard, ItemTypes.Note];
@@ -43,6 +53,27 @@ type CustomFieldDefinition = {
displayOrder: number;
};
+/**
+ * Persisted form data type used for JSON serialization.
+ */
+type PersistedFormData = {
+ itemId: string | null;
+ item: Item | null;
+ fieldValues: Record<string, string | string[]>;
+ customFields: CustomFieldDefinition[];
+ totpEditorState?: {
+ isAddFormVisible: boolean;
+ formData: {
+ name: string;
+ secretKey: string;
+ };
+ };
+ showNotes: boolean;
+ show2FA: boolean;
+ showAttachments: boolean;
+ manuallyAddedFields: string[];
+};
+
/**
* Add or edit item page with dynamic field support.
* Shows all applicable system fields for the item type, not just fields with values.
@@ -63,6 +94,7 @@ const ItemAddEdit: React.FC = () => {
const { setHeaderButtons } = useHeaderButtons();
const { setIsInitialLoading } = useLoading();
const { generateAlias, lastGeneratedValues } = useAliasGenerator();
+ const webApi = useWebApi();
// Component state
const [localLoading, setLocalLoading] = useState(true);
@@ -188,7 +220,116 @@ const ItemAddEdit: React.FC = () => {
}, [applicableSystemFields]);
/**
- * Load item data if in edit mode.
+ * Persists the current form values to storage.
+ * @returns Promise that resolves when the form values are persisted
+ */
+ const persistFormValues = useCallback(async (): Promise<void> => {
+ if (localLoading) {
+ // Do not persist values if the page is still loading.
+ return;
+ }
+
+ const persistedData: PersistedFormData = {
+ itemId: id || null,
+ item,
+ fieldValues,
+ customFields,
+ totpEditorState,
+ showNotes,
+ show2FA,
+ showAttachments,
+ manuallyAddedFields: Array.from(manuallyAddedFields)
+ };
+ await sendMessage('PERSIST_FORM_VALUES', JSON.stringify(persistedData), 'background');
+ }, [id, item, fieldValues, customFields, totpEditorState, showNotes, show2FA, showAttachments, manuallyAddedFields, localLoading]);
+
+ /**
+ * Loads persisted form values from storage.
+ * @returns Promise that resolves when the form values are loaded
+ */
+ const loadPersistedValues = useCallback(async (): Promise<void> => {
+ const persistedData = await sendMessage('GET_PERSISTED_FORM_VALUES', null, 'background') as string | null;
+
+ try {
+ let persistedDataObject: PersistedFormData | null = null;
+ try {
+ if (persistedData) {
+ persistedDataObject = JSON.parse(persistedData) as PersistedFormData;
+ }
+ } catch (error) {
+ console.error('Error parsing persisted data:', error);
+ }
+
+ if (!persistedDataObject) {
+ return;
+ }
+
+ const isCurrentPage = persistedDataObject.itemId === (id || null);
+ if (persistedDataObject && isCurrentPage) {
+ // Restore item state
+ if (persistedDataObject.item) {
+ setItem(persistedDataObject.item);
+ }
+ // Restore field values
+ if (persistedDataObject.fieldValues) {
+ setFieldValues(persistedDataObject.fieldValues);
+ }
+ // Restore custom fields
+ if (persistedDataObject.customFields) {
+ setCustomFields(persistedDataObject.customFields);
+ }
+ // Restore TOTP editor state
+ if (persistedDataObject.totpEditorState) {
+ setTotpEditorState(persistedDataObject.totpEditorState);
+ }
+ // Restore visibility states
+ if (persistedDataObject.showNotes !== undefined) {
+ setShowNotes(persistedDataObject.showNotes);
+ }
+ if (persistedDataObject.show2FA !== undefined) {
+ setShow2FA(persistedDataObject.show2FA);
+ }
+ if (persistedDataObject.showAttachments !== undefined) {
+ setShowAttachments(persistedDataObject.showAttachments);
+ }
+ // Restore manually added fields
+ if (persistedDataObject.manuallyAddedFields) {
+ setManuallyAddedFields(new Set(persistedDataObject.manuallyAddedFields));
+ }
+ }
+ } catch (error) {
+ console.error('Error loading persisted data:', error);
+ }
+ }, [id]);
+
+ /**
+ * Clears persisted form values from storage.
+ * @returns Promise that resolves when the form values are cleared
+ */
+ const clearPersistedValues = useCallback(async (): Promise<void> => {
+ await sendMessage('CLEAR_PERSISTED_FORM_VALUES', null, 'background');
+ }, []);
+
+ /**
+ * Watch for form changes and persist them.
+ */
+ useEffect(() => {
+ if (!localLoading) {
+ void persistFormValues();
+ }
+ }, [item, fieldValues, customFields, totpEditorState, showNotes, show2FA, showAttachments, manuallyAddedFields, persistFormValues, localLoading]);
+
+ /**
+ * Clear persisted values when the page is unmounted.
+ */
+ useEffect(() => {
+ return (): void => {
+ void clearPersistedValues();
+ };
+ }, [clearPersistedValues]);
+
+ /**
+ * Load item data if in edit mode, or initialize for create mode with service detection.
*/
useEffect(() => {
if (!dbContext?.sqliteClient || !id || !isEditMode) {
@@ -197,31 +338,113 @@ const ItemAddEdit: React.FC = () => {
? itemTypeParam
: DEFAULT_ITEM_TYPE;
- setItem({
- Id: crypto.randomUUID().toUpperCase(),
- Name: itemNameParam || '',
- ItemType: effectiveType,
- FolderId: null,
- Fields: [],
- CreatedAt: new Date().toISOString(),
- UpdatedAt: new Date().toISOString()
- });
+ // Get URL parameters for service detection (e.g., from content script popout)
+ // Use searchParams from react-router which handles hash-based routing correctly
+ const serviceNameFromUrl = searchParams.get('serviceName');
+ const serviceUrlFromUrl = searchParams.get('serviceUrl');
+ const currentUrl = searchParams.get('currentUrl');
- // Check if notes should be shown by default for this type
- const typeFields = getSystemFieldsForItemType(effectiveType);
- const notesFieldDef = typeFields.find(f => f.FieldKey === 'metadata.notes');
- if (notesFieldDef && isFieldShownByDefault(notesFieldDef, effectiveType)) {
- setShowNotes(true);
- }
+ /**
+ * Initialize service detection from URL parameters or current tab.
+ */
+ const initializeWithServiceDetection = async (): Promise<void> => {
+ let detectedName = itemNameParam || '';
+ let detectedUrl = '';
+
+ try {
+ // If URL parameters are present (e.g., from content script popout), use them
+ if (serviceNameFromUrl || serviceUrlFromUrl || currentUrl) {
+ if (serviceNameFromUrl) {
+ detectedName = decodeURIComponent(serviceNameFromUrl);
+ }
+ if (serviceUrlFromUrl) {
+ detectedUrl = decodeURIComponent(serviceUrlFromUrl);
+ }
- // Load folders
- if (dbContext?.sqliteClient) {
- const allFolders = dbContext.sqliteClient.getAllFolders();
- setFolders(allFolders);
- }
+ // If we have currentUrl but missing serviceName or serviceUrl, derive them
+ if (currentUrl && (!serviceNameFromUrl || !serviceUrlFromUrl)) {
+ const decodedCurrentUrl = decodeURIComponent(currentUrl);
+ const serviceInfo = ServiceDetectionUtility.getServiceInfoFromTab(decodedCurrentUrl);
+
+ if (!serviceNameFromUrl && serviceInfo.suggestedNames.length > 0) {
+ detectedName = serviceInfo.suggestedNames[0];
+ }
+ if (!serviceUrlFromUrl && serviceInfo.serviceUrl) {
+ detectedUrl = serviceInfo.serviceUrl;
+ }
+ }
+ } else {
+ // Otherwise, detect from current active tab (for dashboard case)
+ const [activeTab] = await browser.tabs.query({ active: true, currentWindow: true });
+
+ if (activeTab?.url) {
+ const serviceInfo = ServiceDetectionUtility.getServiceInfoFromTab(
+ activeTab.url,
+ activeTab.title
+ );
- setLocalLoading(false);
- setIsInitialLoading(false);
+ if (serviceInfo.suggestedNames.length > 0 && !detectedName) {
+ detectedName = serviceInfo.suggestedNames[0];
+ }
+ if (serviceInfo.serviceUrl) {
+ detectedUrl = serviceInfo.serviceUrl;
+ }
+ }
+ }
+ } catch (error) {
+ console.error('Error detecting service information:', error);
+ }
+
+ // Create the new item with detected values
+ const newItem: Item = {
+ Id: crypto.randomUUID().toUpperCase(),
+ Name: detectedName,
+ ItemType: effectiveType,
+ FolderId: null,
+ Fields: [],
+ CreatedAt: new Date().toISOString(),
+ UpdatedAt: new Date().toISOString()
+ };
+
+ setItem(newItem);
+
+ // Set the detected URL in field values if we have one
+ if (detectedUrl) {
+ setFieldValues(prev => ({
+ ...prev,
+ 'login.url': detectedUrl
+ }));
+ }
+
+ // Check if notes should be shown by default for this type
+ const typeFields = getSystemFieldsForItemType(effectiveType);
+ const notesFieldDef = typeFields.find(f => f.FieldKey === 'metadata.notes');
+ if (notesFieldDef && isFieldShownByDefault(notesFieldDef, effectiveType)) {
+ setShowNotes(true);
+ }
+
+ // Load folders
+ if (dbContext?.sqliteClient) {
+ const allFolders = dbContext.sqliteClient.getAllFolders();
+ setFolders(allFolders);
+ }
+
+ // Check if we should skip form restoration (e.g., when opened from popout button)
+ const result = await browser.storage.local.get([SKIP_FORM_RESTORE_KEY]);
+ if (result[SKIP_FORM_RESTORE_KEY]) {
+ // Clear the flag after using it
+ await browser.storage.local.remove([SKIP_FORM_RESTORE_KEY]);
+ // Don't load persisted values
+ } else {
+ // Load persisted form values normally
+ await loadPersistedValues();
+ }
+
+ setLocalLoading(false);
+ setIsInitialLoading(false);
+ };
+
+ void initializeWithServiceDetection();
return;
}
@@ -283,7 +506,8 @@ const ItemAddEdit: React.FC = () => {
setLocalLoading(false);
setIsInitialLoading(false);
}
- }, [dbContext?.sqliteClient, id, isEditMode, itemTypeParam, itemNameParam, navigate, setIsInitialLoading]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dbContext?.sqliteClient, id, isEditMode, itemTypeParam, itemNameParam, navigate, setIsInitialLoading, searchParams]);
/**
* Handle generating alias and populating fields.
@@ -330,6 +554,23 @@ const ItemAddEdit: React.FC = () => {
setShowPassword(true);
}, [generateAlias, lastGeneratedValues]);
+ /**
+ * Generate only the alias email (for Login type email field).
+ * Generates a random identity and uses it to create an email address.
+ */
+ const handleGenerateAliasEmail = useCallback(async () => {
+ const generatedData = await generateAlias();
+ if (!generatedData) {
+ return;
+ }
+
+ // Only update the email field
+ setFieldValues(prev => ({
+ ...prev,
+ 'login.email': generatedData.email
+ }));
+ }, [generateAlias]);
+
/**
* Check if alias fields are shown by default for the current item type.
* Uses alias.first_name as the indicator since email is now a login field.
@@ -430,6 +671,49 @@ const ItemAddEdit: React.FC = () => {
UpdatedAt: new Date().toISOString()
};
+ // Extract favicon from URL if the item has one and no logo exists for this source
+ const urlValue = fieldValues['login.url'];
+ const urlList = Array.isArray(urlValue) ? urlValue : urlValue ? [urlValue] : [];
+ // Find the first valid URL (starts with http://, https://, or www.)
+ const validUrl = urlList.find(url => {
+ const trimmed = url?.trim();
+ return trimmed && (trimmed.startsWith('http://') || trimmed.startsWith('https://') || trimmed.startsWith('www.'));
+ });
+ // Normalize URL: prepend https:// if it starts with www.
+ const urlString = validUrl?.startsWith('www.') ? `https://${validUrl}` : validUrl;
+
+ if (urlString && dbContext?.sqliteClient) {
+ // Extract and normalize the source domain from the URL
+ const source = SqliteClient.extractSourceFromUrl(urlString);
+
+ // Check if a logo already exists for this source
+ if (dbContext.sqliteClient.hasLogoForSource(source)) {
+ console.debug(`[Favicon] Logo already exists for source "${source}", skipping fetch`);
+ } else {
+ console.debug(`[Favicon] No logo found for source "${source}", fetching...`);
+ setLocalLoading(true);
+ try {
+ const timeoutPromise = new Promise((_, reject) =>
+ setTimeout(() => reject(new Error('Favicon extraction timed out')), 5000)
+ );
+
+ const faviconPromise = webApi.get<{ image: string }>('Favicon/Extract?url=' + urlString);
+ const faviconResponse = await Promise.race([faviconPromise, timeoutPromise]) as { image: string };
+
+ console.debug('[Favicon] Response received:', faviconResponse?.image ? 'has image' : 'no image');
+
+ if (faviconResponse?.image) {
+ const decodedImage = Uint8Array.from(Buffer.from(faviconResponse.image, 'base64'));
+ updatedItem.Logo = decodedImage;
+ console.debug('[Favicon] Logo decoded and attached to item');
+ }
+ } catch (err) {
+ // Favicon extraction failed or timed out, this is not a critical error so we can ignore it.
+ console.error('[Favicon] Error extracting favicon:', err);
+ }
+ }
+ }
+
// Save to database and sync vault
if (!dbContext?.sqliteClient) {
throw new Error('Database not initialized');
@@ -440,6 +724,8 @@ const ItemAddEdit: React.FC = () => {
* Sync happens in background, status shown via header indicator.
*/
await executeVaultMutationAsync(async () => {
+ setLocalLoading(false);
+
if (isEditMode) {
await dbContext.sqliteClient!.updateItem(
updatedItem,
@@ -460,6 +746,9 @@ const ItemAddEdit: React.FC = () => {
}
});
+ // Clear persisted form values after successful save
+ void clearPersistedValues();
+
/*
* Navigate to details page, replacing the add/edit page in history.
* This way pressing back goes to items list, not back to the edit form.
@@ -468,7 +757,7 @@ const ItemAddEdit: React.FC = () => {
} catch (err) {
console.error('Error saving item:', err);
}
- }, [item, fieldValues, applicableSystemFields, customFields, dbContext, isEditMode, executeVaultMutationAsync, navigate, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyIdsMarkedForDeletion]);
+ }, [item, fieldValues, applicableSystemFields, customFields, dbContext, isEditMode, executeVaultMutationAsync, navigate, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyIdsMarkedForDeletion, webApi, clearPersistedValues]);
/**
* Handle delete action.
@@ -775,6 +1064,23 @@ const ItemAddEdit: React.FC = () => {
);
case FieldTypes.Email:
+ /*
+ * Use EmailDomainField for email fields to provide domain chooser functionality.
+ * For login.email (Login type), default to free text mode instead of domain chooser.
+ * EmailDomainField handles its own remove button in the label, so don't wrap it.
+ */
+ return (
+ <EmailDomainField
+ id={fieldKey}
+ label={label}
+ value={stringValue}
+ onChange={(value) => handleFieldChange(fieldKey, value)}
+ defaultToFreeText={fieldKey === 'login.email'}
+ onRemove={onRemove}
+ onGenerateAlias={fieldKey === 'login.email' ? handleGenerateAliasEmail : undefined}
+ />
+ );
+
case FieldTypes.URL:
case FieldTypes.Phone:
case FieldTypes.Number:
@@ -793,7 +1099,7 @@ const ItemAddEdit: React.FC = () => {
);
}
- }, [fieldValues, handleFieldChange, showPassword, t]);
+ }, [fieldValues, handleFieldChange, showPassword, t, handleGenerateAliasEmail]);
/**
* Handle form submission via Enter key.
@@ -846,7 +1152,11 @@ const ItemAddEdit: React.FC = () => {
}, [aliasFieldsShownByDefault, handleGenerateAlias, t]);
if (localLoading || !item) {
- return <LoadingSpinner />;
+ return (
+ <div className="flex justify-center items-center p-8">
+ <LoadingSpinner />
+ </div>
+ );
}
return (
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemDetails.tsx
index 6584f02e7..a0d31802d 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemDetails.tsx
@@ -6,7 +6,8 @@ import {
TotpBlock,
AttachmentBlock,
FieldBlock,
- PasskeyBlock
+ PasskeyBlock,
+ EmailBlock
} from '@/entrypoints/popup/components/Credentials/Details';
import HeaderButton from '@/entrypoints/popup/components/HeaderButton';
import { HeaderIconType } from '@/entrypoints/popup/components/Icons/HeaderIcons';
@@ -159,6 +160,14 @@ const ItemDetails: React.FC = (): React.ReactElement => {
</div>
</div>
+ {/* Email block with recent emails - only for Login and Alias types with email field */}
+ {(item.ItemType === ItemTypes.Login || item.ItemType === ItemTypes.Alias) && ((): React.ReactNode => {
+ const emailField = item.Fields.find(f => f.FieldKey === 'login.email');
+ const emailValue = emailField?.Value;
+ const email = Array.isArray(emailValue) ? emailValue[0] : emailValue;
+ return email ? <EmailBlock email={email} /> : null;
+ })()}
+
{/* TOTP codes - only for Login and Alias types, shown at top */}
{(item.ItemType === ItemTypes.Login || item.ItemType === ItemTypes.Alias) && (
<TotpBlock itemId={item.Id} />
diff --git a/apps/browser-extension/src/i18n/locales/en.json b/apps/browser-extension/src/i18n/locales/en.json
index 0d42e782a..687b76922 100644
--- a/apps/browser-extension/src/i18n/locales/en.json
+++ b/apps/browser-extension/src/i18n/locales/en.json
@@ -259,7 +259,9 @@
"publicEmailDescription": "Anonymous but limited privacy. Email content is readable by anyone that knows the address.",
"useDomainChooser": "Use domain chooser",
"enterCustomDomain": "Enter custom domain",
- "enterFullEmail": "Enter full email address",
+ "generateAliasEmail": "Generate alias email",
+ "enterNormalEmail": "Enter normal email",
+ "enterRealEmail": "Enter real email address",
"enterEmailPrefix": "Enter email prefix",
"viewHistory": "View history",
"history": "History",
diff --git a/apps/browser-extension/src/utils/SqliteClient.ts b/apps/browser-extension/src/utils/SqliteClient.ts
index 113e88ef5..d6fce42de 100644
--- a/apps/browser-extension/src/utils/SqliteClient.ts
+++ b/apps/browser-extension/src/utils/SqliteClient.ts
@@ -886,36 +886,13 @@ export class SqliteClient {
const currentDateTime = dateFormatter.now();
const itemId = crypto.randomUUID().toUpperCase();
- // 1. Handle Logo - insert into Logos table if provided
+ // 1. Handle Logo - get or create logo entry
let logoId: string | null = null;
if (credential.Logo) {
- let logoData = null;
- try {
- // 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 logoData = SqliteClient.convertLogoToUint8Array(credential.Logo);
if (logoData) {
- logoId = crypto.randomUUID().toUpperCase();
- const logoQuery = `
- INSERT INTO Logos (Id, FileData, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?)`;
- this.executeUpdate(logoQuery, [
- logoId,
- logoData,
- currentDateTime,
- currentDateTime,
- 0
- ]);
+ const source = SqliteClient.extractSourceFromUrl(credential.ServiceUrl);
+ logoId = this.getOrCreateLogoId(source, logoData, currentDateTime);
}
}
@@ -1600,6 +1577,119 @@ export class SqliteClient {
}
}
+ /**
+ * Check if a logo exists for the given source domain.
+ * @param source The normalized source domain (e.g., 'github.com')
+ * @returns True if a logo exists for this source, false otherwise
+ */
+ public hasLogoForSource(source: string): boolean {
+ const existingLogoQuery = `
+ SELECT Id FROM Logos
+ WHERE Source = ? AND IsDeleted = 0
+ LIMIT 1`;
+ const existingLogos = this.executeQuery<{ Id: string }>(existingLogoQuery, [source]);
+ return existingLogos.length > 0;
+ }
+
+ /**
+ * Get the logo ID for a given source domain if it exists.
+ * @param source The normalized source domain (e.g., 'github.com')
+ * @returns The logo ID if found, null otherwise
+ */
+ public getLogoIdForSource(source: string): string | null {
+ const existingLogoQuery = `
+ SELECT Id FROM Logos
+ WHERE Source = ? AND IsDeleted = 0
+ LIMIT 1`;
+ const existingLogos = this.executeQuery<{ Id: string }>(existingLogoQuery, [source]);
+ return existingLogos.length > 0 ? existingLogos[0].Id : null;
+ }
+
+ /**
+ * Get or create a logo ID for the given source domain.
+ * If a logo for this source already exists, returns its ID.
+ * Otherwise, creates a new logo entry and returns its ID.
+ * @param source The normalized source domain (e.g., 'github.com')
+ * @param logoData The logo image data as Uint8Array
+ * @param currentDateTime The current date/time string for timestamps
+ * @returns The logo ID (existing or newly created)
+ */
+ private getOrCreateLogoId(source: string, logoData: Uint8Array, currentDateTime: string): string {
+ // Check if a logo for this source already exists
+ const existingLogoQuery = `
+ SELECT Id FROM Logos
+ WHERE Source = ? AND IsDeleted = 0
+ LIMIT 1`;
+ const existingLogos = this.executeQuery<{ Id: string }>(existingLogoQuery, [source]);
+
+ if (existingLogos.length > 0) {
+ // Reuse existing logo
+ return existingLogos[0].Id;
+ }
+
+ // Create new logo entry
+ const logoId = crypto.randomUUID().toUpperCase();
+ const logoQuery = `
+ INSERT INTO Logos (Id, Source, FileData, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?)`;
+ this.executeUpdate(logoQuery, [
+ logoId,
+ source,
+ logoData,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
+
+ return logoId;
+ }
+
+ /**
+ * Extract and normalize source domain from a URL string.
+ * @param urlString The URL to extract the domain from
+ * @returns The normalized source domain (e.g., 'github.com'), or 'unknown' if extraction fails
+ */
+ public static extractSourceFromUrl(urlString: string | undefined | null): string {
+ if (!urlString) {
+ return 'unknown';
+ }
+
+ try {
+ const url = new URL(urlString.startsWith('http') ? urlString : `https://${urlString}`);
+ // Normalize hostname by removing www. prefix
+ return url.hostname.replace(/^www\./i, '');
+ } catch {
+ return 'unknown';
+ }
+ }
+
+ /**
+ * Convert logo data from various formats to Uint8Array.
+ * @param logo The logo data in various possible formats
+ * @returns Uint8Array of logo data, or null if conversion fails
+ */
+ private static convertLogoToUint8Array(logo: unknown): Uint8Array | null {
+ if (!logo) {
+ return null;
+ }
+
+ try {
+ // Handle object-like array conversion (from JSON deserialization)
+ if (typeof logo === 'object' && !ArrayBuffer.isView(logo) && !Array.isArray(logo)) {
+ const values = Object.values(logo as Record<string, number>);
+ return new Uint8Array(values);
+ }
+ // Handle existing array types
+ if (Array.isArray(logo) || logo instanceof ArrayBuffer || logo instanceof Uint8Array) {
+ return new Uint8Array(logo as ArrayLike<number>);
+ }
+ } catch (error) {
+ console.warn('Failed to convert logo to Uint8Array:', error);
+ }
+
+ return null;
+ }
+
/**
* Detect MIME type from file signature (magic numbers)
*/
@@ -2063,7 +2153,21 @@ export class SqliteClient {
const currentDateTime = dateFormatter.now();
const itemId = item.Id || crypto.randomUUID().toUpperCase();
- // 1. Insert Item
+ // 1. Handle Logo - get or create logo entry
+ let logoId: string | null = null;
+ if (item.Logo) {
+ const logoData = SqliteClient.convertLogoToUint8Array(item.Logo);
+ if (logoData) {
+ // Extract source from URL field
+ const urlField = item.Fields?.find(f => f.FieldKey === 'login.url');
+ const urlValue = urlField?.Value;
+ const urlString = Array.isArray(urlValue) ? urlValue[0] : urlValue;
+ const source = SqliteClient.extractSourceFromUrl(urlString);
+ logoId = this.getOrCreateLogoId(source, logoData, currentDateTime);
+ }
+ }
+
+ // 2. Insert Item
const itemQuery = `
INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;
@@ -2072,14 +2176,14 @@ export class SqliteClient {
itemId,
item.Name ?? null,
item.ItemType,
- null, // LogoId - handle logo separately if needed
+ logoId,
item.FolderId ?? null,
currentDateTime,
currentDateTime,
0
]);
- // 2. Insert FieldValues for all fields
+ // 3. Insert FieldValues for all fields
if (item.Fields && item.Fields.length > 0) {
for (const field of item.Fields) {
// Skip empty fields
@@ -2227,12 +2331,27 @@ export class SqliteClient {
const currentDateTime = dateFormatter.now();
- // 1. Update Item
+ // 1. Handle Logo - get or create logo entry
+ let logoId: string | null = null;
+ if (item.Logo) {
+ const logoData = SqliteClient.convertLogoToUint8Array(item.Logo);
+ if (logoData) {
+ // Extract source from URL field
+ const urlField = item.Fields?.find(f => f.FieldKey === 'login.url');
+ const urlValue = urlField?.Value;
+ const urlString = Array.isArray(urlValue) ? urlValue[0] : urlValue;
+ const source = SqliteClient.extractSourceFromUrl(urlString);
+ logoId = this.getOrCreateLogoId(source, logoData, currentDateTime);
+ }
+ }
+
+ // 2. Update Item (including LogoId if a new logo was provided)
const itemQuery = `
UPDATE Items
SET Name = ?,
ItemType = ?,
FolderId = ?,
+ LogoId = COALESCE(?, LogoId),
UpdatedAt = ?
WHERE Id = ?`;
@@ -2240,11 +2359,12 @@ export class SqliteClient {
item.Name ?? null,
item.ItemType,
item.FolderId ?? null,
+ logoId,
currentDateTime,
item.Id
]);
- // 2. Track history for fields that have EnableHistory=true before updating
+ // 3. Track history for fields that have EnableHistory=true before updating
await this.trackFieldHistory(item.Id, item.Fields, currentDateTime);
// 3. Get existing FieldValues for this item (to update in place, preserving IDs for merge)