Skip to content

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

Refactor browser extension content script to use item structure (#1404)

Leendert de Borste58fb729719d
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index 81d67551c..51abbdfcc 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -8,8 +8,8 @@ import { handleResetAutoLockTimer, handlePopupHeartbeat, handleSetAutoLockTimeou
import { handleClipboardCopied, handleCancelClipboardClear, handleGetClipboardClearTimeout, handleSetClipboardClearTimeout, handleGetClipboardCountdownState } from '@/entrypoints/background/ClipboardClearHandler';
import { setupContextMenus } from '@/entrypoints/background/ContextMenu';
import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, handlePasskeyPopupResponse, handleGetRequestData } from '@/entrypoints/background/PasskeyHandler';
-import { handleOpenPopup, handlePopupWithCredential, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';
-import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearVault, handleLockVault, handleCreateIdentity, handleGetCredentials, handleGetFilteredCredentials, handleGetSearchCredentials, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVaultMetadata, handleSyncVault, handleUploadVault, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleGetServerRevision } from '@/entrypoints/background/VaultMessageHandler';
+import { handleOpenPopup, handlePopupWithItem, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';
+import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearVault, handleLockVault, handleCreateItem, handleGetFilteredItems, handleGetSearchItems, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVaultMetadata, handleSyncVault, handleUploadVault, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleGetServerRevision } from '@/entrypoints/background/VaultMessageHandler';
import { GLOBAL_CONTEXT_MENU_ENABLED_KEY } from '@/utils/Constants';
import { EncryptionKeyDerivationParams } from "@/utils/dist/core/models/metadata";
@@ -27,9 +27,8 @@ export default defineBackground({
onMessage('GET_ENCRYPTION_KEY', () => handleGetEncryptionKey());
onMessage('GET_ENCRYPTION_KEY_DERIVATION_PARAMS', () => handleGetEncryptionKeyDerivationParams());
onMessage('GET_VAULT', () => handleGetVault());
- onMessage('GET_CREDENTIALS', () => handleGetCredentials());
- onMessage('GET_FILTERED_CREDENTIALS', ({ data }) => handleGetFilteredCredentials(data as { currentUrl: string, pageTitle: string, matchingMode?: string }));
- onMessage('GET_SEARCH_CREDENTIALS', ({ data }) => handleGetSearchCredentials(data as { searchTerm: string }));
+ onMessage('GET_FILTERED_ITEMS', ({ data }) => handleGetFilteredItems(data as { currentUrl: string, pageTitle: string, matchingMode?: string }));
+ onMessage('GET_SEARCH_ITEMS', ({ data }) => handleGetSearchItems(data as { searchTerm: string }));
onMessage('GET_DEFAULT_EMAIL_DOMAIN', () => handleGetDefaultEmailDomain());
onMessage('GET_DEFAULT_IDENTITY_SETTINGS', () => handleGetDefaultIdentitySettings());
@@ -45,14 +44,14 @@ export default defineBackground({
onMessage('MARK_VAULT_CLEAN', ({ data }) => handleMarkVaultClean(data as { mutationSeqAtStart: number; newServerRevision: number }));
onMessage('GET_SERVER_REVISION', () => handleGetServerRevision());
- onMessage('CREATE_IDENTITY', ({ data }) => handleCreateIdentity(data));
+ onMessage('CREATE_ITEM', ({ data }) => handleCreateItem(data));
onMessage('UPLOAD_VAULT', () => handleUploadVault());
onMessage('SYNC_VAULT', () => handleSyncVault());
onMessage('LOCK_VAULT', () => handleLockVault());
onMessage('CLEAR_VAULT', () => handleClearVault());
onMessage('OPEN_POPUP', () => handleOpenPopup());
- onMessage('OPEN_POPUP_WITH_CREDENTIAL', ({ data }) => handlePopupWithCredential(data));
+ onMessage('OPEN_POPUP_WITH_ITEM', ({ data }) => handlePopupWithItem(data));
onMessage('OPEN_POPUP_CREATE_CREDENTIAL', ({ data }) => handleOpenPopupCreateCredential(data));
onMessage('TOGGLE_CONTEXT_MENU', ({ data }) => handleToggleContextMenu(data));
diff --git a/apps/browser-extension/src/entrypoints/background/PopupMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/PopupMessageHandler.ts
index 055177c3e..14e59c965 100644
--- a/apps/browser-extension/src/entrypoints/background/PopupMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/PopupMessageHandler.ts
@@ -23,12 +23,12 @@ export function handleOpenPopup() : Promise<BoolResponse> {
}
/**
- * Handle opening the popup with a credential.
+ * Handle opening the popup with an item.
*/
-export function handlePopupWithCredential(message: any) : Promise<BoolResponse> {
+export function handlePopupWithItem(message: any) : Promise<BoolResponse> {
return (async () : Promise<BoolResponse> => {
browser.windows.create({
- url: browser.runtime.getURL(`/popup.html?expanded=true#/credentials/${message.credentialId}`),
+ url: browser.runtime.getURL(`/popup.html?expanded=true#/credentials/${message.itemId}`),
type: 'popup',
width: 400,
height: 600,
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 649e325d6..1b8b71221 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -8,8 +8,8 @@ import { SqliteClient } from '@/utils/SqliteClient';
import { getItemWithFallback } from '@/utils/StorageUtility';
import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
import { BoolResponse as messageBoolResponse } from '@/utils/types/messaging/BoolResponse';
-import { CredentialsResponse as messageCredentialsResponse } from '@/utils/types/messaging/CredentialsResponse';
import { IdentitySettingsResponse } from '@/utils/types/messaging/IdentitySettingsResponse';
+import { ItemsResponse as messageItemsResponse } from '@/utils/types/messaging/ItemsResponse';
import { PasswordSettingsResponse as messagePasswordSettingsResponse } from '@/utils/types/messaging/PasswordSettingsResponse';
import { StringResponse as stringResponse } from '@/utils/types/messaging/StringResponse';
import { VaultResponse as messageVaultResponse } from '@/utils/types/messaging/VaultResponse';
@@ -283,10 +283,12 @@ export function handleClearVault(): messageBoolResponse {
}
/**
- * Get all credentials.
+ * Create a new item in the vault.
+ * Uses the native Item type with field-based structure.
*/
-export async function handleGetCredentials(
-) : Promise<messageCredentialsResponse> {
+export async function handleCreateItem(
+ message: any,
+) : Promise<messageBoolResponse> {
const encryptionKey = await handleGetEncryptionKey();
if (!encryptionKey) {
@@ -295,24 +297,29 @@ export async function handleGetCredentials(
try {
const sqliteClient = await createVaultSqliteClient();
- const credentials = sqliteClient.getAllCredentials();
- return { success: true, credentials: credentials };
+
+ // Add the new item to the vault/database.
+ await sqliteClient.createItem(message.item, message.attachments || [], message.totpCodes || []);
+
+ // Upload the new vault to the server.
+ await uploadNewVaultToServer(sqliteClient);
+
+ return { success: true };
} catch (error) {
- console.error('Error getting credentials:', error);
+ console.error('Failed to create item:', error);
return { success: false, error: await t('common.errors.unknownError') };
}
}
/**
- * Get credentials filtered by URL and page title for autofill performance optimization.
- * Filters credentials in the background script before sending to reduce message payload size.
- * Critical for large vaults (1000+ credentials) to avoid multi-second delays.
+ * Get items filtered by URL matching (for autofill).
+ * Filters items in the background script before sending to reduce message payload size.
*
* @param message - Filtering parameters: currentUrl, pageTitle, matchingMode
*/
-export async function handleGetFilteredCredentials(
+export async function handleGetFilteredItems(
message: { currentUrl: string, pageTitle: string, matchingMode?: string }
-) : Promise<messageCredentialsResponse> {
+) : Promise<messageItemsResponse> {
const encryptionKey = await handleGetEncryptionKey();
if (!encryptionKey) {
@@ -321,9 +328,9 @@ export async function handleGetFilteredCredentials(
try {
const sqliteClient = await createVaultSqliteClient();
- const allCredentials = sqliteClient.getAllCredentials();
+ const allItems = sqliteClient.getAllItems();
- const { filterCredentials, AutofillMatchingMode } = await import('@/utils/credentialMatcher/CredentialMatcher');
+ const { filterItems, AutofillMatchingMode } = await import('@/utils/credentialMatcher/CredentialMatcher');
// Parse matching mode from string
let matchingMode = AutofillMatchingMode.DEFAULT;
@@ -331,30 +338,30 @@ export async function handleGetFilteredCredentials(
matchingMode = message.matchingMode as typeof AutofillMatchingMode[keyof typeof AutofillMatchingMode];
}
- // Filter credentials in background to reduce payload size (~95% reduction)
- const filteredCredentials = await filterCredentials(
- allCredentials,
+ // Filter items in background to reduce payload size (~95% reduction)
+ const filteredItems = await filterItems(
+ allItems,
message.currentUrl,
message.pageTitle,
matchingMode
);
- return { success: true, credentials: filteredCredentials };
+ return { success: true, items: filteredItems };
} catch (error) {
- console.error('Error getting filtered credentials:', error);
+ console.error('Error getting filtered items:', error);
return { success: false, error: await t('common.errors.unknownError') };
}
}
/**
- * Get credentials filtered by text search query.
- * Searches across entire vault (service name, username, email, URL) and returns matches.
+ * Get items filtered by text search query.
+ * Searches across entire vault (name, fields) and returns matches.
*
* @param message - Search parameters: searchTerm
*/
-export async function handleGetSearchCredentials(
+export async function handleGetSearchItems(
message: { searchTerm: string }
-) : Promise<messageCredentialsResponse> {
+) : Promise<messageItemsResponse> {
const encryptionKey = await handleGetEncryptionKey();
if (!encryptionKey) {
@@ -363,64 +370,47 @@ export async function handleGetSearchCredentials(
try {
const sqliteClient = await createVaultSqliteClient();
- const allCredentials = sqliteClient.getAllCredentials();
+ const allItems = sqliteClient.getAllItems();
// If search term is empty, return empty array
if (!message.searchTerm || message.searchTerm.trim() === '') {
- return { success: true, credentials: [] };
+ return { success: true, items: [] };
}
const searchTerm = message.searchTerm.toLowerCase().trim();
+ const { FieldKey } = await import('@/utils/dist/core/models/vault');
- // Filter credentials by search term across multiple fields
- const searchResults = allCredentials.filter(cred => {
- const searchableFields = [
- cred.ServiceName?.toLowerCase(),
- cred.Username?.toLowerCase(),
- cred.Alias?.Email?.toLowerCase(),
- cred.ServiceUrl?.toLowerCase()
- ];
- return searchableFields.some(field => field?.includes(searchTerm));
- }).sort((a, b) => {
- // Sort by service name, then username
- const serviceNameComparison = (a.ServiceName ?? '').localeCompare(b.ServiceName ?? '');
- if (serviceNameComparison !== 0) {
- return serviceNameComparison;
+ // Filter items by search term across multiple fields
+ const searchResults = allItems.filter(item => {
+ // Search in item name
+ if (item.Name?.toLowerCase().includes(searchTerm)) {
+ return true;
}
- return (a.Username ?? '').localeCompare(b.Username ?? '');
- });
- return { success: true, credentials: searchResults };
- } catch (error) {
- console.error('Error searching credentials:', error);
- return { success: false, error: await t('common.errors.unknownError') };
- }
-}
-
-/**
- * Create an identity.
- */
-export async function handleCreateIdentity(
- message: any,
-) : Promise<messageBoolResponse> {
- const encryptionKey = await handleGetEncryptionKey();
-
- if (!encryptionKey) {
- return { success: false, error: await t('common.errors.vaultIsLocked') };
- }
-
- try {
- const sqliteClient = await createVaultSqliteClient();
-
- // Add the new credential to the vault/database.
- await sqliteClient.createCredential(message.credential, message.attachments || []);
+ // Search in field values
+ const searchableFieldKeys = [
+ FieldKey.LoginUsername,
+ FieldKey.LoginEmail,
+ FieldKey.LoginUrl,
+ FieldKey.AliasFirstName,
+ FieldKey.AliasLastName
+ ];
- // Upload the new vault to the server.
- await uploadNewVaultToServer(sqliteClient);
+ return item.Fields?.some(field => {
+ if (searchableFieldKeys.includes(field.FieldKey as any)) {
+ const value = Array.isArray(field.Value) ? field.Value.join(' ') : field.Value;
+ return value?.toLowerCase().includes(searchTerm);
+ }
+ return false;
+ });
+ }).sort((a, b) => {
+ // Sort by name
+ return (a.Name ?? '').localeCompare(b.Name ?? '');
+ });
- return { success: true };
+ return { success: true, items: searchResults };
} catch (error) {
- console.error('Failed to create identity:', error);
+ console.error('Error searching items:', error);
return { success: false, error: await t('common.errors.unknownError') };
}
}
diff --git a/apps/browser-extension/src/entrypoints/contentScript/Form.ts b/apps/browser-extension/src/entrypoints/contentScript/Form.ts
index 1c3b10736..836a85397 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/Form.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/Form.ts
@@ -2,7 +2,8 @@ import { sendMessage } from 'webext-bridge/content-script';
import { openAutofillPopup } from '@/entrypoints/contentScript/Popup';
-import type { Credential } from '@/utils/dist/core/models/vault';
+import type { Item } from '@/utils/dist/core/models/vault';
+import { itemToCredential } from '@/utils/dist/core/models/vault';
import { FormDetector } from '@/utils/formDetector/FormDetector';
import { FormFiller } from '@/utils/formDetector/FormFiller';
import { ClickValidator } from '@/utils/security/ClickValidator';
@@ -85,12 +86,13 @@ export function validateInputField(element: Element | null): { isValid: boolean;
}
/**
- * Fill credential into current form.
+ * Fill item into current form.
+ * Converts the Item to Credential format for FormFiller compatibility.
*
- * @param credential - The credential to fill.
- * @param input - The input element that triggered the popup. Required when filling credentials to know which form to fill.
+ * @param item - The item to fill.
+ * @param input - The input element that triggered the popup. Required when filling items to know which form to fill.
*/
-export async function fillCredential(credential: Credential, input: HTMLInputElement): Promise<void> {
+export async function fillItem(item: Item, input: HTMLInputElement): Promise<void> {
// Set debounce time to 300ms to prevent the popup from being shown again within 300ms because of autofill events.
hidePopupFor(300);
@@ -107,6 +109,8 @@ export async function fillCredential(credential: Credential, input: HTMLInputEle
return;
}
+ // Convert Item to Credential for FormFiller compatibility
+ const credential = itemToCredential(item);
const formFiller = new FormFiller(form, triggerInputEvents);
await formFiller.fillFields(credential);
}
diff --git a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts b/apps/browser-extension/src/entrypoints/contentScript/Popup.ts
index d8aee7149..ce85cae33 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/Popup.ts
@@ -1,17 +1,18 @@
import { sendMessage } from 'webext-bridge/content-script';
-import { fillCredential } from '@/entrypoints/contentScript/Form';
+import { fillItem } from '@/entrypoints/contentScript/Form';
import { DISABLED_SITES_KEY, TEMPORARY_DISABLED_SITES_KEY, GLOBAL_AUTOFILL_POPUP_ENABLED_KEY, VAULT_LOCKED_DISMISS_UNTIL_KEY, AUTOFILL_MATCHING_MODE_KEY, CUSTOM_EMAIL_HISTORY_KEY, CUSTOM_USERNAME_HISTORY_KEY } from '@/utils/Constants';
import { AutofillMatchingMode } from '@/utils/credentialMatcher/CredentialMatcher';
-import { CreateIdentityGenerator } from '@/utils/dist/core/identity-generator';
-import type { Credential } from '@/utils/dist/core/models/vault';
+import { CreateIdentityGenerator, IdentityHelperUtils } from '@/utils/dist/core/identity-generator';
+import type { Item, ItemField } from '@/utils/dist/core/models/vault';
+import { ItemTypes, FieldTypes, FieldKey } from '@/utils/dist/core/models/vault';
import { CreatePasswordGenerator, PasswordGenerator, PasswordSettings } from '@/utils/dist/core/password-generator';
import { ClickValidator } from '@/utils/security/ClickValidator';
import { ServiceDetectionUtility } from '@/utils/serviceDetection/ServiceDetectionUtility';
import { SqliteClient } from '@/utils/SqliteClient';
-import { CredentialsResponse } from '@/utils/types/messaging/CredentialsResponse';
import { IdentitySettingsResponse } from '@/utils/types/messaging/IdentitySettingsResponse';
+import { ItemsResponse } from '@/utils/types/messaging/ItemsResponse';
import { PasswordSettingsResponse } from '@/utils/types/messaging/PasswordSettingsResponse';
import { StringResponse } from '@/utils/types/messaging/StringResponse';
@@ -52,14 +53,14 @@ export function openAutofillPopup(input: HTMLInputElement, container: HTMLElemen
// Load autofill matching mode setting to send to background for filtering
const matchingMode = await storage.getItem(AUTOFILL_MATCHING_MODE_KEY) as AutofillMatchingMode ?? AutofillMatchingMode.DEFAULT;
- const response = await sendMessage('GET_FILTERED_CREDENTIALS', {
+ const response = await sendMessage('GET_FILTERED_ITEMS', {
currentUrl: window.location.href,
pageTitle: document.title,
matchingMode: matchingMode
- }, 'background') as CredentialsResponse;
+ }, 'background') as ItemsResponse;
if (response.success) {
- await createAutofillPopup(input, response.credentials, container);
+ await createAutofillPopup(input, response.items, container);
} else {
await createVaultLockedPopup(input, container);
}
@@ -123,27 +124,27 @@ export function createLoadingPopup(input: HTMLInputElement, message: string, roo
}
/**
- * Update the credential list content in the popup.
+ * Update the item list content in the popup.
*
- * @param credentials - The credentials to display.
- * @param credentialList - The credential list element.
- * @param input - The input element that triggered the popup. Required when filling credentials to know which form to fill.
+ * @param items - The items to display.
+ * @param itemList - The item list element.
+ * @param input - The input element that triggered the popup. Required when filling items to know which form to fill.
*/
-export function updatePopupContent(credentials: Credential[], credentialList: HTMLElement | null, input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string) : void {
- if (!credentialList) {
- credentialList = document.getElementById('aliasvault-credential-list') as HTMLElement;
+export function updatePopupContent(items: Item[], itemList: HTMLElement | null, input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string) : void {
+ if (!itemList) {
+ itemList = document.getElementById('aliasvault-credential-list') as HTMLElement;
}
- if (!credentialList) {
+ if (!itemList) {
return;
}
// Clear existing content
- credentialList.innerHTML = '';
+ itemList.innerHTML = '';
- // Add credentials using the shared function
- const credentialElements = createCredentialList(credentials, input, rootContainer, noMatchesText);
- credentialElements.forEach(element => credentialList.appendChild(element));
+ // Add items using the shared function
+ const itemElements = createItemList(items, input, rootContainer, noMatchesText);
+ itemElements.forEach(element => itemList.appendChild(element));
}
/**
@@ -169,7 +170,7 @@ export function removeExistingPopup(container: HTMLElement) : void {
/**
* Create auto-fill popup
*/
-export async function createAutofillPopup(input: HTMLInputElement, credentials: Credential[] | undefined, rootContainer: HTMLElement) : Promise<void> {
+export async function createAutofillPopup(input: HTMLInputElement, items: Item[] | undefined, rootContainer: HTMLElement) : Promise<void> {
// Get all translations first
const newText = await t('content.new');
const searchPlaceholder = await t('content.searchVault');
@@ -189,12 +190,12 @@ export async function createAutofillPopup(input: HTMLInputElement, credentials:
credentialList.className = 'av-credential-list';
popup.appendChild(credentialList);
- // Add initial credentials (already filtered by background script for performance)
- if (!credentials) {
- credentials = [];
+ // Add initial items (already filtered by background script for performance)
+ if (!items) {
+ items = [];
}
- updatePopupContent(credentials, credentialList, input, rootContainer, noMatchesText);
+ updatePopupContent(items, credentialList, input, rootContainer, noMatchesText);
// Add divider
const divider = document.createElement('div');
@@ -242,22 +243,72 @@ export async function createAutofillPopup(input: HTMLInputElement, credentials:
const response = await sendMessage('GET_DEFAULT_EMAIL_DOMAIN', {}, 'background') as StringResponse;
const domain = response.value;
- let credential: Credential;
+ let newItem: Item;
+ const currentDateTime = new Date().toISOString();
if (result.isCustomCredential) {
- // Create custom credential with information provided by user in popup.
+ // Create custom item with information provided by user in popup.
const faviconBytes = await getFaviconBytes(document);
- credential = {
+ const fields: ItemField[] = [];
+ let displayOrder = 0;
+
+ // Add URL field
+ const serviceUrl = getValidServiceUrl();
+ if (serviceUrl) {
+ fields.push({
+ FieldKey: FieldKey.LoginUrl,
+ Label: 'URL',
+ FieldType: FieldTypes.URL,
+ Value: serviceUrl,
+ IsHidden: false,
+ DisplayOrder: displayOrder++
+ });
+ }
+
+ // Add username if provided
+ if (result.customUsername) {
+ fields.push({
+ FieldKey: FieldKey.LoginUsername,
+ Label: 'Username',
+ FieldType: FieldTypes.Text,
+ Value: result.customUsername,
+ IsHidden: false,
+ DisplayOrder: displayOrder++
+ });
+ }
+
+ // Add email if provided
+ if (result.customEmail) {
+ fields.push({
+ FieldKey: FieldKey.LoginEmail,
+ Label: 'Email',
+ FieldType: FieldTypes.Email,
+ Value: result.customEmail,
+ IsHidden: false,
+ DisplayOrder: displayOrder++
+ });
+ }
+
+ // Add password if provided
+ if (result.customPassword) {
+ fields.push({
+ FieldKey: FieldKey.LoginPassword,
+ Label: 'Password',
+ FieldType: FieldTypes.Password,
+ Value: result.customPassword,
+ IsHidden: true,
+ DisplayOrder: displayOrder++
+ });
+ }
+
+ newItem = {
Id: '',
- ServiceName: result.serviceName ?? '',
- ServiceUrl: getValidServiceUrl(),
+ Name: result.serviceName ?? '',
+ ItemType: ItemTypes.Login,
Logo: faviconBytes ?? undefined,
- Username: result.customUsername,
- Password: result.customPassword ?? '',
- Alias: {
- BirthDate: '',
- Email: result.customEmail ?? ''
- }
+ Fields: fields,
+ CreatedAt: currentDateTime,
+ UpdatedAt: currentDateTime
};
} else {
// Generate new random identity using identity generator.
@@ -282,35 +333,113 @@ export async function createAutofillPopup(input: HTMLInputElement, credentials:
// Extract favicon from page and get the bytes
const faviconBytes = await getFaviconBytes(document);
- credential = {
+ // Build fields array for the Alias item type
+ const fields: ItemField[] = [];
+ let displayOrder = 0;
+
+ // Add URL field
+ const serviceUrl = getValidServiceUrl();
+ if (serviceUrl) {
+ fields.push({
+ FieldKey: FieldKey.LoginUrl,
+ Label: 'URL',
+ FieldType: FieldTypes.URL,
+ Value: serviceUrl,
+ IsHidden: false,
+ DisplayOrder: displayOrder++
+ });
+ }
+
+ // Add username
+ fields.push({
+ FieldKey: FieldKey.LoginUsername,
+ Label: 'Username',
+ FieldType: FieldTypes.Text,
+ Value: identity.nickName,
+ IsHidden: false,
+ DisplayOrder: displayOrder++
+ });
+
+ // Add email
+ fields.push({
+ FieldKey: FieldKey.LoginEmail,
+ Label: 'Email',
+ FieldType: FieldTypes.Email,
+ Value: `${identity.emailPrefix}@${domain}`,
+ IsHidden: false,
+ DisplayOrder: displayOrder++
+ });
+
+ // Add password
+ fields.push({
+ FieldKey: FieldKey.LoginPassword,
+ Label: 'Password',
+ FieldType: FieldTypes.Password,
+ Value: password,
+ IsHidden: true,
+ DisplayOrder: displayOrder++
+ });
+
+ // Add alias fields
+ fields.push({
+ FieldKey: FieldKey.AliasFirstName,
+ Label: 'First Name',
+ FieldType: FieldTypes.Text,
+ Value: identity.firstName,
+ IsHidden: false,
+ DisplayOrder: displayOrder++
+ });
+
+ fields.push({
+ FieldKey: FieldKey.AliasLastName,
+ Label: 'Last Name',
+ FieldType: FieldTypes.Text,
+ Value: identity.lastName,
+ IsHidden: false,
+ DisplayOrder: displayOrder++
+ });
+
+ fields.push({
+ FieldKey: FieldKey.AliasBirthdate,
+ Label: 'Birth Date',
+ FieldType: FieldTypes.Date,
+ Value: IdentityHelperUtils.normalizeBirthDate(identity.birthDate.toISOString()),
+ IsHidden: false,
+ DisplayOrder: displayOrder++
+ });
+
+ fields.push({
+ FieldKey: FieldKey.AliasGender,
+ Label: 'Gender',
+ FieldType: FieldTypes.Text,
+ Value: identity.gender,
+ IsHidden: false,
+ DisplayOrder: displayOrder++
+ });
+
+ newItem = {
Id: '',
- ServiceName: result.serviceName ?? '',
- ServiceUrl: getValidServiceUrl(),
+ Name: result.serviceName ?? '',
+ ItemType: ItemTypes.Alias,
Logo: faviconBytes ?? undefined,
- Username: identity.nickName,
- Password: password,
- Alias: {
- FirstName: identity.firstName,
- LastName: identity.lastName,
- BirthDate: identity.birthDate.toISOString(),
- Gender: identity.gender,
- Email: `${identity.emailPrefix}@${domain}`
- }
+ Fields: fields,
+ CreatedAt: currentDateTime,
+ UpdatedAt: currentDateTime
};
}
- // Create identity in background.
- await sendMessage('CREATE_IDENTITY', {
- credential: JSON.parse(JSON.stringify(credential))
+ // Create item in background.
+ await sendMessage('CREATE_ITEM', {
+ item: JSON.parse(JSON.stringify(newItem))
}, 'background');
// Close popup.
removeExistingPopup(rootContainer);
- // Fill the form with the new identity immediately.
- fillCredential(credential, input);
+ // Fill the form with the new item immediately.
+ fillItem(newItem, input);
} catch (error) {
- console.error('Error creating identity:', error);
+ console.error('Error creating item:', error);
loadingPopup.innerHTML = `
<div style="padding: 16px; color: #ef4444;">
${failedText}
@@ -336,7 +465,7 @@ export async function createAutofillPopup(input: HTMLInputElement, credentials:
// Handle search input.
let searchTimeout: NodeJS.Timeout | null = null;
searchInput.addEventListener('input', async () => {
- await handleSearchInput(searchInput, credentials, rootContainer, searchTimeout, credentialList, input, noMatchesText);
+ await handleSearchInput(searchInput, items, rootContainer, searchTimeout, credentialList, input, noMatchesText);
});
// Close button
@@ -544,18 +673,18 @@ export async function createVaultLockedPopup(input: HTMLInputElement, rootContai
/**
* Handle popup search input - searches entire vault when user types.
- * When empty, shows the initially URL-filtered credentials.
- * When user types, searches ALL credentials in vault (not just the pre-filtered set).
+ * When empty, shows the initially URL-filtered items.
+ * When user types, searches ALL items in vault (not just the pre-filtered set).
*
* @param searchInput - The search input element
- * @param initialCredentials - The initially URL-filtered credentials to show when search is empty
+ * @param initialItems - The initially URL-filtered items to show when search is empty
* @param rootContainer - The root container element
* @param searchTimeout - Timeout for debouncing search
- * @param credentialList - The credential list element to update
+ * @param itemList - The item list element to update
* @param input - The input field that triggered the popup
* @param noMatchesText - Text to show when no matches found
*/
-async function handleSearchInput(searchInput: HTMLInputElement, initialCredentials: Credential[], rootContainer: HTMLElement, searchTimeout: NodeJS.Timeout | null, credentialList: HTMLElement | null, input: HTMLInputElement, noMatchesText?: string) : Promise<void> {
+async function handleSearchInput(searchInput: HTMLInputElement, initialItems: Item[], rootContainer: HTMLElement, searchTimeout: NodeJS.Timeout | null, itemList: HTMLElement | null, input: HTMLInputElement, noMatchesText?: string) : Promise<void> {
if (searchTimeout) {
clearTimeout(searchTimeout);
}
@@ -563,48 +692,48 @@ async function handleSearchInput(searchInput: HTMLInputElement, initialCredentia
const searchTerm = searchInput.value.trim();
if (searchTerm === '') {
- // If search is empty, show the initially URL-filtered credentials
- updatePopupContent(initialCredentials, credentialList, input, rootContainer, noMatchesText);
+ // If search is empty, show the initially URL-filtered items
+ updatePopupContent(initialItems, itemList, input, rootContainer, noMatchesText);
} else {
// Search in full vault with search term
- const response = await sendMessage('GET_SEARCH_CREDENTIALS', {
+ const response = await sendMessage('GET_SEARCH_ITEMS', {
searchTerm: searchTerm
- }, 'background') as CredentialsResponse;
+ }, 'background') as ItemsResponse;
- if (response.success && response.credentials) {
- updatePopupContent(response.credentials, credentialList, input, rootContainer, noMatchesText);
+ if (response.success && response.items) {
+ updatePopupContent(response.items, itemList, input, rootContainer, noMatchesText);
} else {
- // On error, fallback to showing initial filtered credentials
- updatePopupContent(initialCredentials, credentialList, input, rootContainer, noMatchesText);
+ // On error, fallback to showing initial filtered items
+ updatePopupContent(initialItems, itemList, input, rootContainer, noMatchesText);
}
}
}
/**
- * Create credential list content for popup
+ * Create item list content for popup
*
- * @param credentials - The credentials to display.
- * @param input - The input element that triggered the popup. Required when filling credentials to know which form to fill.
+ * @param items - The items to display.
+ * @param input - The input element that triggered the popup. Required when filling items to know which form to fill.
*/
-function createCredentialList(credentials: Credential[], input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string): HTMLElement[] {
+function createItemList(items: Item[], input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string): HTMLElement[] {
const elements: HTMLElement[] = [];
- if (credentials.length > 0) {
- credentials.forEach(cred => {
- const item = document.createElement('div');
- item.className = 'av-credential-item';
+ if (items.length > 0) {
+ items.forEach(item => {
+ const itemElement = document.createElement('div');
+ itemElement.className = 'av-credential-item';
- // Create container for credential info (logo + username)
- const credentialInfo = document.createElement('div');
- credentialInfo.className = 'av-credential-info';
+ // Create container for item info (logo + username)
+ const itemInfo = document.createElement('div');
+ itemInfo.className = 'av-credential-info';
const imgElement = document.createElement('img');
imgElement.className = 'av-credential-logo';
- imgElement.src = SqliteClient.imgSrcFromBytes(cred.Logo);
+ imgElement.src = SqliteClient.imgSrcFromBytes(item.Logo);
- credentialInfo.appendChild(imgElement);
- const credTextContainer = document.createElement('div');
- credTextContainer.className = 'av-credential-text';
+ itemInfo.appendChild(imgElement);
+ const itemTextContainer = document.createElement('div');
+ itemTextContainer.className = 'av-credential-text';
// Service name (primary text) with passkey indicator
const serviceName = document.createElement('div');
@@ -617,11 +746,11 @@ function createCredentialList(credentials: Credential[], input: HTMLInputElement
serviceNameContainer.style.gap = '4px';
const serviceNameText = document.createElement('span');
- serviceNameText.textContent = cred.ServiceName;
+ serviceNameText.textContent = item.Name || '';
serviceNameContainer.appendChild(serviceNameText);
- // Add passkey indicator if credential has a passkey
- if (cred.HasPasskey) {
+ // Add passkey indicator if item has a passkey
+ if (item.HasPasskey) {
const passkeyIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
passkeyIcon.setAttribute('class', 'av-passkey-icon');
passkeyIcon.setAttribute('viewBox', '0 0 24 24');
@@ -645,25 +774,36 @@ function createCredentialList(credentials: Credential[], input: HTMLInputElement
serviceName.appendChild(serviceNameContainer);
- // Details container (secondary text)
+ // Details container (secondary text) - extract from fields
const detailsContainer = document.createElement('div');
detailsContainer.className = 'av-service-details';
+ // Get field values using helper function
+ const firstName = item.Fields.find(f => f.FieldKey === FieldKey.AliasFirstName)?.Value;
+ const lastName = item.Fields.find(f => f.FieldKey === FieldKey.AliasLastName)?.Value;
+ const username = item.Fields.find(f => f.FieldKey === FieldKey.LoginUsername)?.Value;
+ const email = item.Fields.find(f => f.FieldKey === FieldKey.LoginEmail)?.Value;
+
// Combine full name (if available) and username or email
- const details = [];
- if (cred.Alias?.FirstName && cred.Alias?.LastName) {
- details.push(`${cred.Alias.FirstName} ${cred.Alias.LastName}`);
+ const details: string[] = [];
+ const firstNameStr = Array.isArray(firstName) ? firstName[0] : firstName;
+ const lastNameStr = Array.isArray(lastName) ? lastName[0] : lastName;
+ const usernameStr = Array.isArray(username) ? username[0] : username;
+ const emailStr = Array.isArray(email) ? email[0] : email;
+
+ if (firstNameStr && lastNameStr) {
+ details.push(`${firstNameStr} ${lastNameStr}`);
}
- if (cred.Username) {
- details.push(cred.Username);
- } else if (cred.Alias?.Email) {
- details.push(cred.Alias.Email);
+ if (usernameStr) {
+ details.push(usernameStr);
+ } else if (emailStr) {
+ details.push(emailStr);
}
detailsContainer.textContent = details.join(' · ');
- credTextContainer.appendChild(serviceName);
- credTextContainer.appendChild(detailsContainer);
- credentialInfo.appendChild(credTextContainer);
+ itemTextContainer.appendChild(serviceName);
+ itemTextContainer.appendChild(detailsContainer);
+ itemInfo.appendChild(itemTextContainer);
// Add popout icon
const popoutIcon = document.createElement('div');
@@ -678,21 +818,21 @@ function createCredentialList(credentials: Credential[], input: HTMLInputElement
// Handle popout click with security validation
addReliableClickHandler(popoutIcon, (e) => {
- e.stopPropagation(); // Prevent credential fill
- sendMessage('OPEN_POPUP_WITH_CREDENTIAL', { credentialId: cred.Id }, 'background');
+ e.stopPropagation(); // Prevent item fill
+ sendMessage('OPEN_POPUP_WITH_ITEM', { itemId: item.Id }, 'background');
removeExistingPopup(rootContainer);
});
- item.appendChild(credentialInfo);
- item.appendChild(popoutIcon);
+ itemElement.appendChild(itemInfo);
+ itemElement.appendChild(popoutIcon);
- // Update click handler to only trigger on credentialInfo with security validation
- addReliableClickHandler(credentialInfo, () => {
- fillCredential(cred, input);
+ // Update click handler to only trigger on itemInfo with security validation
+ addReliableClickHandler(itemInfo, () => {
+ fillItem(item, input);
removeExistingPopup(rootContainer);
});
- elements.push(item);
+ elements.push(itemElement);
});
} else {
const noMatches = document.createElement('div');
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/AliasBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/AliasBlock.tsx
index aed1043b9..c32525ce7 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/AliasBlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/AliasBlock.tsx
@@ -51,7 +51,7 @@ const AliasBlock: React.FC<AliasBlockProps> = ({ credential }) => {
<FormInputCopyToClipboard
id="birthDate"
label={t('common.birthDate')}
- value={IdentityHelperUtils.normalizeBirthDateForDisplay(credential.Alias?.BirthDate)}
+ value={IdentityHelperUtils.normalizeBirthDate(credential.Alias?.BirthDate)}
/>
)}
</div>
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/HelpModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/HelpModal.tsx
index 8cc512a57..a4fb86071 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/HelpModal.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/HelpModal.tsx
@@ -1,5 +1,4 @@
import React, { useState } from 'react';
-import { useTranslation } from 'react-i18next';
import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';
@@ -14,7 +13,6 @@ type HelpModalProps = {
* Shows a modal popup with help information when clicked.
*/
const HelpModal: React.FC<HelpModalProps> = ({ title, content, className = '' }) => {
- const { t } = useTranslation();
const [showModal, setShowModal] = useState(false);
return (
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useAliasGenerator.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useAliasGenerator.ts
index 372532ee5..24f5ddccf 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useAliasGenerator.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useAliasGenerator.ts
@@ -96,7 +96,7 @@ const useAliasGenerator = (): {
firstName: identity.firstName,
lastName: identity.lastName,
gender: identity.gender,
- birthdate: IdentityHelperUtils.normalizeBirthDateForDisplay(identity.birthDate.toISOString()),
+ birthdate: IdentityHelperUtils.normalizeBirthDate(identity.birthDate.toISOString()),
username: identity.nickName,
password
};
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/credentials/CredentialAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/credentials/CredentialAddEdit.tsx
index 8e81ae315..b7fd46b5e 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/credentials/CredentialAddEdit.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/credentials/CredentialAddEdit.tsx
@@ -339,7 +339,7 @@ const CredentialAddEdit: React.FC = () => {
const result = dbContext.sqliteClient.getCredentialById(id);
if (result) {
- result.Alias.BirthDate = IdentityHelperUtils.normalizeBirthDateForDisplay(result.Alias.BirthDate);
+ result.Alias.BirthDate = IdentityHelperUtils.normalizeBirthDate(result.Alias.BirthDate);
// Set form values
Object.entries(result).forEach(([key, value]) => {
@@ -436,7 +436,7 @@ const CredentialAddEdit: React.FC = () => {
setValue('Alias.FirstName', identity.firstName);
setValue('Alias.LastName', identity.lastName);
setValue('Alias.Gender', identity.gender);
- setValue('Alias.BirthDate', IdentityHelperUtils.normalizeBirthDateForDisplay(identity.birthDate.toISOString()));
+ setValue('Alias.BirthDate', IdentityHelperUtils.normalizeBirthDate(identity.birthDate.toISOString()));
// Only overwrite username if it's empty or matches the last generated value
if (!currentUsername || currentUsername === lastGeneratedValues.username) {
@@ -540,7 +540,7 @@ const CredentialAddEdit: React.FC = () => {
// Normalize the birth date for database entry.
let birthdate = data.Alias.BirthDate;
if (birthdate) {
- birthdate = IdentityHelperUtils.normalizeBirthDateForDb(birthdate);
+ birthdate = IdentityHelperUtils.normalizeBirthDate(birthdate);
}
// Clean up empty protocol-only URLs
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 6d1e9aa28..63cc907bc 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemDetails.tsx
@@ -19,6 +19,7 @@ import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
import type { Item } from '@/utils/dist/core/models/vault';
import { FieldCategories, FieldTypes, ItemTypes } from '@/utils/dist/core/models/vault';
import { groupFieldsByCategory } from '@/utils/dist/core/models/vault';
+
import { EmailPreview } from '../../components/EmailPreview';
/**
diff --git a/apps/browser-extension/src/utils/credentialMatcher/CredentialMatcher.ts b/apps/browser-extension/src/utils/credentialMatcher/CredentialMatcher.ts
index b76c6291a..951697288 100644
--- a/apps/browser-extension/src/utils/credentialMatcher/CredentialMatcher.ts
+++ b/apps/browser-extension/src/utils/credentialMatcher/CredentialMatcher.ts
@@ -1,9 +1,10 @@
/**
- * Credential filtering via Rust WASM. See core/rust/src/credential_matcher for algorithm.
+ * Item filtering via Rust WASM. See core/rust/src/credential_matcher for algorithm.
*/
import { browser } from 'wxt/browser';
-import type { Credential } from '@/utils/dist/core/models/vault';
+import type { Credential, Item } from '@/utils/dist/core/models/vault';
+import { FieldKey } from '@/utils/dist/core/models/vault';
import init, {
filterCredentials as wasmFilterCredentials,
extractDomain as wasmExtractDomain,
@@ -33,26 +34,43 @@ async function ensureInit(): Promise<void> {
}
/**
- * Filter credentials by URL/title. Returns max 3 matches.
+ * Helper to get field value from an item's fields array.
*/
-export async function filterCredentials(
- credentials: Credential[],
+function getFieldValue(item: Item, fieldKey: string): string | undefined {
+ const field = item.Fields?.find(f => f.FieldKey === fieldKey);
+ if (!field) {
+ return undefined;
+ }
+ return Array.isArray(field.Value) ? field.Value[0] : field.Value;
+}
+
+/**
+ * Filter items by URL/title. Returns max 3 matches.
+ * Uses the same Rust WASM filtering logic but maps Item fields to the expected structure.
+ */
+export async function filterItems(
+ items: Item[],
currentUrl: string,
pageTitle: string,
matchingMode: AutofillMatchingMode = AutofillMatchingMode.DEFAULT
-): Promise<Credential[]> {
+): Promise<Item[]> {
await ensureInit();
+ // Map Items to the format expected by the WASM filter
const result = wasmFilterCredentials({
- credentials: credentials.map(c => ({ Id: c.Id, ServiceName: c.ServiceName, ServiceUrl: c.ServiceUrl })),
+ credentials: items.map(item => ({
+ Id: item.Id,
+ ServiceName: item.Name ?? '',
+ ServiceUrl: getFieldValue(item, FieldKey.LoginUrl)
+ })),
current_url: currentUrl,
page_title: pageTitle,
matching_mode: matchingMode
}) as { matched_ids: string[] };
return result.matched_ids
- .map(id => credentials.find(c => c.Id === id))
- .filter((c): c is Credential => c !== undefined);
+ .map(id => items.find(item => item.Id === id))
+ .filter((item): item is Item => item !== undefined);
}
/**
@@ -70,3 +88,31 @@ export async function extractRootDomain(domain: string): Promise<string> {
await ensureInit();
return wasmExtractRootDomain(domain);
}
+
+/**
+ * Filter credentials by URL/title. Returns max 3 matches.
+ * Uses the same Rust WASM filtering logic with the Credential type.
+ */
+export async function filterCredentials(
+ credentials: Credential[],
+ currentUrl: string,
+ pageTitle: string,
+ matchingMode: AutofillMatchingMode = AutofillMatchingMode.DEFAULT
+): Promise<Credential[]> {
+ await ensureInit();
+
+ const result = wasmFilterCredentials({
+ credentials: credentials.map(cred => ({
+ Id: cred.Id,
+ ServiceName: cred.ServiceName ?? '',
+ ServiceUrl: cred.ServiceUrl
+ })),
+ current_url: currentUrl,
+ page_title: pageTitle,
+ matching_mode: matchingMode
+ }) as { matched_ids: string[] };
+
+ return result.matched_ids
+ .map(id => credentials.find(cred => cred.Id === id))
+ .filter((cred): cred is Credential => cred !== undefined);
+}
diff --git a/apps/browser-extension/src/utils/dist/core/identity-generator/index.d.ts b/apps/browser-extension/src/utils/dist/core/identity-generator/index.d.ts
index 3b56246f0..a62a2ab83 100644
--- a/apps/browser-extension/src/utils/dist/core/identity-generator/index.d.ts
+++ b/apps/browser-extension/src/utils/dist/core/identity-generator/index.d.ts
@@ -153,15 +153,11 @@ declare class IdentityGeneratorDe extends IdentityGenerator {
*/
declare class IdentityHelperUtils {
/**
- * Normalize a birth date for display.
+ * Normalize a birth date to the standard format: "yyyy-MM-dd".
+ * Handles various input formats including ISO strings with time components.
+ * Returns empty string for invalid/empty dates.
*/
- static normalizeBirthDateForDisplay(birthDate: string | undefined): string;
- /**
- * Normalize a birth date for database storage.
- * Converts any date format to the standard format: "yyyy-MM-dd 00:00:00" (19 characters).
- * BirthDate fields do not include time or milliseconds, just date with 00:00:00.
- */
- static normalizeBirthDateForDb(input: string | undefined): string;
+ static normalizeBirthDate(input: string | undefined): string;
/**
* Check if a birth date is valid.
*/
diff --git a/apps/browser-extension/src/utils/dist/core/identity-generator/index.js b/apps/browser-extension/src/utils/dist/core/identity-generator/index.js
index 0207d241c..c4f396a89 100644
--- a/apps/browser-extension/src/utils/dist/core/identity-generator/index.js
+++ b/apps/browser-extension/src/utils/dist/core/identity-generator/index.js
@@ -5838,37 +5838,28 @@ var IdentityGeneratorDe = class extends IdentityGenerator {
// src/utils/IdentityHelperUtils.ts
var IdentityHelperUtils = class {
/**
- * Normalize a birth date for display.
+ * Normalize a birth date to the standard format: "yyyy-MM-dd".
+ * Handles various input formats including ISO strings with time components.
+ * Returns empty string for invalid/empty dates.
*/
- static normalizeBirthDateForDisplay(birthDate) {
- if (!birthDate || birthDate.startsWith("0001-01-01")) {
+ static normalizeBirthDate(input) {
+ if (!input || input.trim() === "" || input.startsWith("0001-01-01")) {
return "";
}
- return birthDate.split(/[T ]/)[0];
- }
- /**
- * Normalize a birth date for database storage.
- * Converts any date format to the standard format: "yyyy-MM-dd 00:00:00" (19 characters).
- * BirthDate fields do not include time or milliseconds, just date with 00:00:00.
- */
- static normalizeBirthDateForDb(input) {
- if (!input || input.trim() === "") {
- return "0001-01-01 00:00:00";
- }
const trimmed = input.trim();
const match = trimmed.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (match) {
- const [_, y, m, d] = match;
- return `${y}-${m}-${d} 00:00:00`;
+ const [, y, m, d] = match;
+ return `${y}-${m}-${d}`;
}
const parsedDate = new Date(trimmed);
if (!isNaN(parsedDate.getTime())) {
const year = parsedDate.getFullYear().toString().padStart(4, "0");
const month = (parsedDate.getMonth() + 1).toString().padStart(2, "0");
const day = parsedDate.getDate().toString().padStart(2, "0");
- return `${year}-${month}-${day} 00:00:00`;
+ return `${year}-${month}-${day}`;
}
- return "0001-01-01 00:00:00";
+ return "";
}
/**
* Check if a birth date is valid.
diff --git a/apps/browser-extension/src/utils/dist/core/identity-generator/index.mjs b/apps/browser-extension/src/utils/dist/core/identity-generator/index.mjs
index db4e8cef8..2bec72907 100644
--- a/apps/browser-extension/src/utils/dist/core/identity-generator/index.mjs
+++ b/apps/browser-extension/src/utils/dist/core/identity-generator/index.mjs
@@ -5801,37 +5801,28 @@ var IdentityGeneratorDe = class extends IdentityGenerator {
// src/utils/IdentityHelperUtils.ts
var IdentityHelperUtils = class {
/**
- * Normalize a birth date for display.
+ * Normalize a birth date to the standard format: "yyyy-MM-dd".
+ * Handles various input formats including ISO strings with time components.
+ * Returns empty string for invalid/empty dates.
*/
- static normalizeBirthDateForDisplay(birthDate) {
- if (!birthDate || birthDate.startsWith("0001-01-01")) {
+ static normalizeBirthDate(input) {
+ if (!input || input.trim() === "" || input.startsWith("0001-01-01")) {
return "";
}
- return birthDate.split(/[T ]/)[0];
- }
- /**
- * Normalize a birth date for database storage.
- * Converts any date format to the standard format: "yyyy-MM-dd 00:00:00" (19 characters).
- * BirthDate fields do not include time or milliseconds, just date with 00:00:00.
- */
- static normalizeBirthDateForDb(input) {
- if (!input || input.trim() === "") {
- return "0001-01-01 00:00:00";
- }
const trimmed = input.trim();
const match = trimmed.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (match) {
- const [_, y, m, d] = match;
- return `${y}-${m}-${d} 00:00:00`;
+ const [, y, m, d] = match;
+ return `${y}-${m}-${d}`;
}
const parsedDate = new Date(trimmed);
if (!isNaN(parsedDate.getTime())) {
const year = parsedDate.getFullYear().toString().padStart(4, "0");
const month = (parsedDate.getMonth() + 1).toString().padStart(2, "0");
const day = parsedDate.getDate().toString().padStart(2, "0");
- return `${year}-${month}-${day} 00:00:00`;
+ return `${year}-${month}-${day}`;
}
- return "0001-01-01 00:00:00";
+ return "";
}
/**
* Check if a birth date is valid.
diff --git a/apps/browser-extension/src/utils/types/messaging/CredentialsResponse.ts b/apps/browser-extension/src/utils/types/messaging/CredentialsResponse.ts
deleted file mode 100644
index bf6fd4693..000000000
--- a/apps/browser-extension/src/utils/types/messaging/CredentialsResponse.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import type { Credential } from "@/utils/dist/core/models/vault";
-
-export type CredentialsResponse = {
- success: boolean,
- error?: string,
- credentials?: Credential[]
-};
diff --git a/apps/browser-extension/src/utils/types/messaging/ItemsResponse.ts b/apps/browser-extension/src/utils/types/messaging/ItemsResponse.ts
new file mode 100644
index 000000000..8a20d9dad
--- /dev/null
+++ b/apps/browser-extension/src/utils/types/messaging/ItemsResponse.ts
@@ -0,0 +1,7 @@
+import type { Item } from "@/utils/dist/core/models/vault";
+
+export type ItemsResponse = {
+ success: boolean,
+ error?: string,
+ items?: Item[]
+};
diff --git a/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx b/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx
index 548d17ec6..006f76648 100644
--- a/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx
+++ b/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx
@@ -156,7 +156,7 @@ export default function AddEditCredentialScreen() : React.ReactNode {
try {
const existingCredential = await dbContext.sqliteClient!.getCredentialById(id);
if (existingCredential) {
- existingCredential.Alias.BirthDate = IdentityHelperUtils.normalizeBirthDateForDisplay(existingCredential.Alias.BirthDate);
+ existingCredential.Alias.BirthDate = IdentityHelperUtils.normalizeBirthDate(existingCredential.Alias.BirthDate);
Object.entries(existingCredential).forEach(([key, value]) => {
setValue(key as keyof Credential, value);
});
@@ -264,7 +264,7 @@ export default function AddEditCredentialScreen() : React.ReactNode {
setValue('Alias.LastName', identity.lastName);
setValue('Alias.NickName', identity.nickName);
setValue('Alias.Gender', identity.gender);
- setValue('Alias.BirthDate', IdentityHelperUtils.normalizeBirthDateForDisplay(identity.birthDate.toISOString()));
+ setValue('Alias.BirthDate', IdentityHelperUtils.normalizeBirthDate(identity.birthDate.toISOString()));
// Only overwrite username if it's empty or matches the last generated value
if (!currentUsername || currentUsername === lastGeneratedValues.username) {
@@ -374,7 +374,7 @@ export default function AddEditCredentialScreen() : React.ReactNode {
}
// Convert user birthdate entry format (yyyy-mm-dd) into valid ISO 8601 format for database storage
- credentialToSave.Alias.BirthDate = IdentityHelperUtils.normalizeBirthDateForDb(credentialToSave.Alias.BirthDate);
+ credentialToSave.Alias.BirthDate = IdentityHelperUtils.normalizeBirthDate(credentialToSave.Alias.BirthDate);
// Extract favicon from service URL if the credential has one
if (credentialToSave.ServiceUrl) {
diff --git a/apps/mobile-app/components/credentials/details/AliasDetails.tsx b/apps/mobile-app/components/credentials/details/AliasDetails.tsx
index 320ceab84..bf31ca6b9 100644
--- a/apps/mobile-app/components/credentials/details/AliasDetails.tsx
+++ b/apps/mobile-app/components/credentials/details/AliasDetails.tsx
@@ -53,7 +53,7 @@ export const AliasDetails: React.FC<AliasDetailsProps> = ({ credential }) : Reac
{IdentityHelperUtils.isValidBirthDate(credential.Alias?.BirthDate) && (
<FormInputCopyToClipboard
label={t('credentials.birthDate')}
- value={IdentityHelperUtils.normalizeBirthDateForDisplay(credential.Alias.BirthDate)}
+ value={IdentityHelperUtils.normalizeBirthDate(credential.Alias.BirthDate)}
/>
)}
</ThemedView>
diff --git a/apps/mobile-app/utils/dist/core/identity-generator/index.d.ts b/apps/mobile-app/utils/dist/core/identity-generator/index.d.ts
index 3b56246f0..a62a2ab83 100644
--- a/apps/mobile-app/utils/dist/core/identity-generator/index.d.ts
+++ b/apps/mobile-app/utils/dist/core/identity-generator/index.d.ts
@@ -153,15 +153,11 @@ declare class IdentityGeneratorDe extends IdentityGenerator {
*/
declare class IdentityHelperUtils {
/**
- * Normalize a birth date for display.
+ * Normalize a birth date to the standard format: "yyyy-MM-dd".
+ * Handles various input formats including ISO strings with time components.
+ * Returns empty string for invalid/empty dates.
*/
- static normalizeBirthDateForDisplay(birthDate: string | undefined): string;
- /**
- * Normalize a birth date for database storage.
- * Converts any date format to the standard format: "yyyy-MM-dd 00:00:00" (19 characters).
- * BirthDate fields do not include time or milliseconds, just date with 00:00:00.
- */
- static normalizeBirthDateForDb(input: string | undefined): string;
+ static normalizeBirthDate(input: string | undefined): string;
/**
* Check if a birth date is valid.
*/
diff --git a/apps/mobile-app/utils/dist/core/identity-generator/index.js b/apps/mobile-app/utils/dist/core/identity-generator/index.js
index 0207d241c..c4f396a89 100644
--- a/apps/mobile-app/utils/dist/core/identity-generator/index.js
+++ b/apps/mobile-app/utils/dist/core/identity-generator/index.js
@@ -5838,37 +5838,28 @@ var IdentityGeneratorDe = class extends IdentityGenerator {
// src/utils/IdentityHelperUtils.ts
var IdentityHelperUtils = class {
/**
- * Normalize a birth date for display.
+ * Normalize a birth date to the standard format: "yyyy-MM-dd".
+ * Handles various input formats including ISO strings with time components.
+ * Returns empty string for invalid/empty dates.
*/
- static normalizeBirthDateForDisplay(birthDate) {
- if (!birthDate || birthDate.startsWith("0001-01-01")) {
+ static normalizeBirthDate(input) {
+ if (!input || input.trim() === "" || input.startsWith("0001-01-01")) {
return "";
}
- return birthDate.split(/[T ]/)[0];
- }
- /**
- * Normalize a birth date for database storage.
- * Converts any date format to the standard format: "yyyy-MM-dd 00:00:00" (19 characters).
- * BirthDate fields do not include time or milliseconds, just date with 00:00:00.
- */
- static normalizeBirthDateForDb(input) {
- if (!input || input.trim() === "") {
- return "0001-01-01 00:00:00";
- }
const trimmed = input.trim();
const match = trimmed.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (match) {
- const [_, y, m, d] = match;
- return `${y}-${m}-${d} 00:00:00`;
+ const [, y, m, d] = match;
+ return `${y}-${m}-${d}`;
}
const parsedDate = new Date(trimmed);
if (!isNaN(parsedDate.getTime())) {
const year = parsedDate.getFullYear().toString().padStart(4, "0");
const month = (parsedDate.getMonth() + 1).toString().padStart(2, "0");
const day = parsedDate.getDate().toString().padStart(2, "0");
- return `${year}-${month}-${day} 00:00:00`;
+ return `${year}-${month}-${day}`;
}
- return "0001-01-01 00:00:00";
+ return "";
}
/**
* Check if a birth date is valid.
diff --git a/apps/mobile-app/utils/dist/core/identity-generator/index.mjs b/apps/mobile-app/utils/dist/core/identity-generator/index.mjs
index db4e8cef8..2bec72907 100644
--- a/apps/mobile-app/utils/dist/core/identity-generator/index.mjs
+++ b/apps/mobile-app/utils/dist/core/identity-generator/index.mjs
@@ -5801,37 +5801,28 @@ var IdentityGeneratorDe = class extends IdentityGenerator {
// src/utils/IdentityHelperUtils.ts
var IdentityHelperUtils = class {
/**
- * Normalize a birth date for display.
+ * Normalize a birth date to the standard format: "yyyy-MM-dd".
+ * Handles various input formats including ISO strings with time components.
+ * Returns empty string for invalid/empty dates.
*/
- static normalizeBirthDateForDisplay(birthDate) {
- if (!birthDate || birthDate.startsWith("0001-01-01")) {
+ static normalizeBirthDate(input) {
+ if (!input || input.trim() === "" || input.startsWith("0001-01-01")) {
return "";
}
- return birthDate.split(/[T ]/)[0];
- }
- /**
- * Normalize a birth date for database storage.
- * Converts any date format to the standard format: "yyyy-MM-dd 00:00:00" (19 characters).
- * BirthDate fields do not include time or milliseconds, just date with 00:00:00.
- */
- static normalizeBirthDateForDb(input) {
- if (!input || input.trim() === "") {
- return "0001-01-01 00:00:00";
- }
const trimmed = input.trim();
const match = trimmed.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (match) {
- const [_, y, m, d] = match;
- return `${y}-${m}-${d} 00:00:00`;
+ const [, y, m, d] = match;
+ return `${y}-${m}-${d}`;
}
const parsedDate = new Date(trimmed);
if (!isNaN(parsedDate.getTime())) {
const year = parsedDate.getFullYear().toString().padStart(4, "0");
const month = (parsedDate.getMonth() + 1).toString().padStart(2, "0");
const day = parsedDate.getDate().toString().padStart(2, "0");
- return `${year}-${month}-${day} 00:00:00`;
+ return `${year}-${month}-${day}`;
}
- return "0001-01-01 00:00:00";
+ return "";
}
/**
* Check if a birth date is valid.
diff --git a/apps/server/AliasVault.Client/wwwroot/js/dist/core/identity-generator/index.d.ts b/apps/server/AliasVault.Client/wwwroot/js/dist/core/identity-generator/index.d.ts
index 3b56246f0..a62a2ab83 100644
--- a/apps/server/AliasVault.Client/wwwroot/js/dist/core/identity-generator/index.d.ts
+++ b/apps/server/AliasVault.Client/wwwroot/js/dist/core/identity-generator/index.d.ts
@@ -153,15 +153,11 @@ declare class IdentityGeneratorDe extends IdentityGenerator {
*/
declare class IdentityHelperUtils {
/**
- * Normalize a birth date for display.
+ * Normalize a birth date to the standard format: "yyyy-MM-dd".
+ * Handles various input formats including ISO strings with time components.
+ * Returns empty string for invalid/empty dates.
*/
- static normalizeBirthDateForDisplay(birthDate: string | undefined): string;
- /**
- * Normalize a birth date for database storage.
- * Converts any date format to the standard format: "yyyy-MM-dd 00:00:00" (19 characters).
- * BirthDate fields do not include time or milliseconds, just date with 00:00:00.
- */
- static normalizeBirthDateForDb(input: string | undefined): string;
+ static normalizeBirthDate(input: string | undefined): string;
/**
* Check if a birth date is valid.
*/
diff --git a/apps/server/AliasVault.Client/wwwroot/js/dist/core/identity-generator/index.js b/apps/server/AliasVault.Client/wwwroot/js/dist/core/identity-generator/index.js
index 0207d241c..c4f396a89 100644
--- a/apps/server/AliasVault.Client/wwwroot/js/dist/core/identity-generator/index.js
+++ b/apps/server/AliasVault.Client/wwwroot/js/dist/core/identity-generator/index.js
@@ -5838,37 +5838,28 @@ var IdentityGeneratorDe = class extends IdentityGenerator {
// src/utils/IdentityHelperUtils.ts
var IdentityHelperUtils = class {
/**
- * Normalize a birth date for display.
+ * Normalize a birth date to the standard format: "yyyy-MM-dd".
+ * Handles various input formats including ISO strings with time components.
+ * Returns empty string for invalid/empty dates.
*/
- static normalizeBirthDateForDisplay(birthDate) {
- if (!birthDate || birthDate.startsWith("0001-01-01")) {
+ static normalizeBirthDate(input) {
+ if (!input || input.trim() === "" || input.startsWith("0001-01-01")) {
return "";
}
- return birthDate.split(/[T ]/)[0];
- }
- /**
- * Normalize a birth date for database storage.
- * Converts any date format to the standard format: "yyyy-MM-dd 00:00:00" (19 characters).
- * BirthDate fields do not include time or milliseconds, just date with 00:00:00.
- */
- static normalizeBirthDateForDb(input) {
- if (!input || input.trim() === "") {
- return "0001-01-01 00:00:00";
- }
const trimmed = input.trim();
const match = trimmed.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (match) {
- const [_, y, m, d] = match;
- return `${y}-${m}-${d} 00:00:00`;
+ const [, y, m, d] = match;
+ return `${y}-${m}-${d}`;
}
const parsedDate = new Date(trimmed);
if (!isNaN(parsedDate.getTime())) {
const year = parsedDate.getFullYear().toString().padStart(4, "0");
const month = (parsedDate.getMonth() + 1).toString().padStart(2, "0");
const day = parsedDate.getDate().toString().padStart(2, "0");
- return `${year}-${month}-${day} 00:00:00`;
+ return `${year}-${month}-${day}`;
}
- return "0001-01-01 00:00:00";
+ return "";
}
/**
* Check if a birth date is valid.
diff --git a/apps/server/AliasVault.Client/wwwroot/js/dist/core/identity-generator/index.mjs b/apps/server/AliasVault.Client/wwwroot/js/dist/core/identity-generator/index.mjs
index db4e8cef8..2bec72907 100644
--- a/apps/server/AliasVault.Client/wwwroot/js/dist/core/identity-generator/index.mjs
+++ b/apps/server/AliasVault.Client/wwwroot/js/dist/core/identity-generator/index.mjs
@@ -5801,37 +5801,28 @@ var IdentityGeneratorDe = class extends IdentityGenerator {
// src/utils/IdentityHelperUtils.ts
var IdentityHelperUtils = class {
/**
- * Normalize a birth date for display.
+ * Normalize a birth date to the standard format: "yyyy-MM-dd".
+ * Handles various input formats including ISO strings with time components.
+ * Returns empty string for invalid/empty dates.
*/
- static normalizeBirthDateForDisplay(birthDate) {
- if (!birthDate || birthDate.startsWith("0001-01-01")) {
+ static normalizeBirthDate(input) {
+ if (!input || input.trim() === "" || input.startsWith("0001-01-01")) {
return "";
}
- return birthDate.split(/[T ]/)[0];
- }
- /**
- * Normalize a birth date for database storage.
- * Converts any date format to the standard format: "yyyy-MM-dd 00:00:00" (19 characters).
- * BirthDate fields do not include time or milliseconds, just date with 00:00:00.
- */
- static normalizeBirthDateForDb(input) {
- if (!input || input.trim() === "") {
- return "0001-01-01 00:00:00";
- }
const trimmed = input.trim();
const match = trimmed.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (match) {
- const [_, y, m, d] = match;
- return `${y}-${m}-${d} 00:00:00`;
+ const [, y, m, d] = match;
+ return `${y}-${m}-${d}`;
}
const parsedDate = new Date(trimmed);
if (!isNaN(parsedDate.getTime())) {
const year = parsedDate.getFullYear().toString().padStart(4, "0");
const month = (parsedDate.getMonth() + 1).toString().padStart(2, "0");
const day = parsedDate.getDate().toString().padStart(2, "0");
- return `${year}-${month}-${day} 00:00:00`;
+ return `${year}-${month}-${day}`;
}
- return "0001-01-01 00:00:00";
+ return "";
}
/**
* Check if a birth date is valid.
diff --git a/apps/server/Databases/AliasClientDb/Migrations/20251213111207_1.7.0-FieldBasedDataModelUpdate.cs b/apps/server/Databases/AliasClientDb/Migrations/20251213111207_1.7.0-FieldBasedDataModelUpdate.cs
index 66a950bee..4894fe5a1 100644
--- a/apps/server/Databases/AliasClientDb/Migrations/20251213111207_1.7.0-FieldBasedDataModelUpdate.cs
+++ b/apps/server/Databases/AliasClientDb/Migrations/20251213111207_1.7.0-FieldBasedDataModelUpdate.cs
@@ -668,6 +668,7 @@ namespace AliasClientDb.Migrations
// Migrate alias.birthdate field (system field using FieldKey)
// Exclude DateTime.MinValue (year 0001) which represents empty/unset dates
+ // Strip time portion from old format (yyyy-MM-dd HH:mm:ss or yyyy-MM-ddTHH:mm:ss) to new format (yyyy-MM-dd)
migrationBuilder.Sql(@"
INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
SELECT
@@ -675,7 +676,7 @@ namespace AliasClientDb.Migrations
c.Id AS ItemId,
NULL AS FieldDefinitionId,
'alias.birthdate' AS FieldKey,
- a.BirthDate AS Value,
+ SUBSTR(a.BirthDate, 1, 10) AS Value,
0 AS Weight,
a.UpdatedAt AS CreatedAt,
a.UpdatedAt AS UpdatedAt,
diff --git a/core/typescript/identity-generator/src/__tests__/IdentityHelperUtils.test.ts b/core/typescript/identity-generator/src/__tests__/IdentityHelperUtils.test.ts
index 1560b0725..feecdef14 100644
--- a/core/typescript/identity-generator/src/__tests__/IdentityHelperUtils.test.ts
+++ b/core/typescript/identity-generator/src/__tests__/IdentityHelperUtils.test.ts
@@ -2,51 +2,59 @@ import { describe, it, expect } from 'vitest';
import { IdentityHelperUtils } from '../utils/IdentityHelperUtils';
describe('IdentityHelperUtils', () => {
- describe('normalizeBirthDateForDisplay', () => {
+ describe('normalizeBirthDate', () => {
it('should return empty string for undefined input', () => {
- expect(IdentityHelperUtils.normalizeBirthDateForDisplay(undefined)).toBe('');
+ expect(IdentityHelperUtils.normalizeBirthDate(undefined)).toBe('');
});
- it('should return empty string for default date', () => {
- expect(IdentityHelperUtils.normalizeBirthDateForDisplay('0001-01-01')).toBe('');
+ it('should return empty string for empty string input', () => {
+ expect(IdentityHelperUtils.normalizeBirthDate('')).toBe('');
});
- it('should strip time from ISO format date', () => {
- expect(IdentityHelperUtils.normalizeBirthDateForDisplay('1976-05-18T08:24:15.000Z')).toBe('1976-05-18');
+ it('should return empty string for default date (0001-01-01)', () => {
+ expect(IdentityHelperUtils.normalizeBirthDate('0001-01-01')).toBe('');
});
- it('should handle date with space separator', () => {
- expect(IdentityHelperUtils.normalizeBirthDateForDisplay('1976-05-18 08:24:15')).toBe('1976-05-18');
+ it('should return empty string for invalid date', () => {
+ expect(IdentityHelperUtils.normalizeBirthDate('invalid-date')).toBe('');
});
- it('should handle date without time', () => {
- expect(IdentityHelperUtils.normalizeBirthDateForDisplay('1976-05-18')).toBe('1976-05-18');
+ it('should strip time from ISO format date with T separator', () => {
+ expect(IdentityHelperUtils.normalizeBirthDate('1976-05-18T08:24:15.000Z')).toBe('1976-05-18');
+ });
+
+ it('should strip time from date with space separator', () => {
+ expect(IdentityHelperUtils.normalizeBirthDate('1976-05-18 08:24:15')).toBe('1976-05-18');
});
- });
- describe('normalizeBirthDateForDb', () => {
- it('should return default date for undefined input', () => {
- expect(IdentityHelperUtils.normalizeBirthDateForDb(undefined)).toBe('0001-01-01 00:00:00');
+ it('should return date as-is when already in correct format', () => {
+ expect(IdentityHelperUtils.normalizeBirthDate('1976-05-18')).toBe('1976-05-18');
});
- it('should return default date for empty string', () => {
- expect(IdentityHelperUtils.normalizeBirthDateForDb('')).toBe('0001-01-01 00:00:00');
+ it('should handle pre-1970 dates correctly', () => {
+ expect(IdentityHelperUtils.normalizeBirthDate('1955-03-24T00:00:00')).toBe('1955-03-24');
+ });
+ });
+
+ describe('isValidBirthDate', () => {
+ it('should return false for undefined input', () => {
+ expect(IdentityHelperUtils.isValidBirthDate(undefined)).toBe(false);
});
- it('should return default date for invalid date', () => {
- expect(IdentityHelperUtils.normalizeBirthDateForDb('invalid-date')).toBe('0001-01-01 00:00:00');
+ it('should return false for empty string', () => {
+ expect(IdentityHelperUtils.isValidBirthDate('')).toBe(false);
});
- it('should normalize ISO format date with time to space-separated format', () => {
- expect(IdentityHelperUtils.normalizeBirthDateForDb('1976-05-18T08:24:15.000Z')).toBe('1976-05-18 00:00:00');
+ it('should return false for default date (0001-01-01)', () => {
+ expect(IdentityHelperUtils.isValidBirthDate('0001-01-01')).toBe(false);
});
- it('should preserve date with space separator and time', () => {
- expect(IdentityHelperUtils.normalizeBirthDateForDb('1976-05-18 08:24:15')).toBe('1976-05-18 00:00:00');
+ it('should return true for valid date', () => {
+ expect(IdentityHelperUtils.isValidBirthDate('1976-05-18')).toBe(true);
});
- it('should add default time to date without time', () => {
- expect(IdentityHelperUtils.normalizeBirthDateForDb('1976-05-18')).toBe('1976-05-18 00:00:00');
+ it('should return true for valid ISO date', () => {
+ expect(IdentityHelperUtils.isValidBirthDate('1976-05-18T08:24:15.000Z')).toBe(true);
});
});
-});
\ No newline at end of file
+});
diff --git a/core/typescript/identity-generator/src/utils/IdentityHelperUtils.ts b/core/typescript/identity-generator/src/utils/IdentityHelperUtils.ts
index 0dde05a68..fed235583 100644
--- a/core/typescript/identity-generator/src/utils/IdentityHelperUtils.ts
+++ b/core/typescript/identity-generator/src/utils/IdentityHelperUtils.ts
@@ -3,27 +3,15 @@
*/
export class IdentityHelperUtils {
/**
- * Normalize a birth date for display.
+ * Normalize a birth date to the standard format: "yyyy-MM-dd".
+ * Handles various input formats including ISO strings with time components.
+ * Returns empty string for invalid/empty dates.
*/
- public static normalizeBirthDateForDisplay(birthDate: string | undefined): string {
- if (!birthDate || birthDate.startsWith('0001-01-01')) {
+ public static normalizeBirthDate(input: string | undefined): string {
+ if (!input || input.trim() === '' || input.startsWith('0001-01-01')) {
return '';
}
- // Handle both space and T separators
- return birthDate.split(/[T ]/)[0]; // Strip time
- }
-
- /**
- * Normalize a birth date for database storage.
- * Converts any date format to the standard format: "yyyy-MM-dd 00:00:00" (19 characters).
- * BirthDate fields do not include time or milliseconds, just date with 00:00:00.
- */
- public static normalizeBirthDateForDb(input: string | undefined): string {
- if (!input || input.trim() === '') {
- return '0001-01-01 00:00:00';
- }
-
const trimmed = input.trim();
/*
@@ -32,8 +20,8 @@ export class IdentityHelperUtils {
*/
const match = trimmed.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (match) {
- const [_, y, m, d] = match;
- return `${y}-${m}-${d} 00:00:00`;
+ const [, y, m, d] = match;
+ return `${y}-${m}-${d}`;
}
// Fall back to native Date parsing only if regex match fails
@@ -42,10 +30,10 @@ export class IdentityHelperUtils {
const year = parsedDate.getFullYear().toString().padStart(4, '0');
const month = (parsedDate.getMonth() + 1).toString().padStart(2, '0');
const day = parsedDate.getDate().toString().padStart(2, '0');
- return `${year}-${month}-${day} 00:00:00`;
+ return `${year}-${month}-${day}`;
}
- return '0001-01-01 00:00:00';
+ return '';
}
/**