Skip to content

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

Browser extension item structure GUI scaffolding (#1404)

Leendert de Borst1edddb2b4b9b
diff --git a/apps/browser-extension/src/entrypoints/popup/App.tsx b/apps/browser-extension/src/entrypoints/popup/App.tsx
index 1cdd55547..2decda76e 100644
--- a/apps/browser-extension/src/entrypoints/popup/App.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/App.tsx
@@ -19,6 +19,8 @@ import Upgrade from '@/entrypoints/popup/pages/auth/Upgrade';
import CredentialAddEdit from '@/entrypoints/popup/pages/credentials/CredentialAddEdit';
import CredentialDetails from '@/entrypoints/popup/pages/credentials/CredentialDetails';
import CredentialsList from '@/entrypoints/popup/pages/credentials/CredentialsList';
+import ItemAddEdit from '@/entrypoints/popup/pages/credentials/ItemAddEdit';
+import ItemDetails from '@/entrypoints/popup/pages/credentials/ItemDetails';
import EmailDetails from '@/entrypoints/popup/pages/emails/EmailDetails';
import EmailsList from '@/entrypoints/popup/pages/emails/EmailsList';
import Index from '@/entrypoints/popup/pages/Index';
@@ -186,6 +188,9 @@ const App: React.FC = () => {
{ path: '/credentials/add', element: <CredentialAddEdit />, showBackButton: true, title: t('credentials.addCredential') },
{ path: '/credentials/:id', element: <CredentialDetails />, showBackButton: true, title: t('credentials.credentialDetails') },
{ path: '/credentials/:id/edit', element: <CredentialAddEdit />, showBackButton: true, title: t('credentials.editCredential') },
+ { path: '/items/:id', element: <ItemDetails />, showBackButton: true, title: 'Item Details' },
+ { path: '/items/:id/edit', element: <ItemAddEdit />, showBackButton: true, title: 'Edit Item' },
+ { path: '/items/add', element: <ItemAddEdit />, showBackButton: true, title: 'Add Item' },
{ path: '/passkeys/create', element: <PasskeyCreate />, layout: LayoutType.PASSKEY },
{ path: '/passkeys/authenticate', element: <PasskeyAuthenticate />, layout: LayoutType.PASSKEY },
{ path: '/emails', element: <EmailsList />, showBackButton: false },
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Credentials/CredentialCard.tsx b/apps/browser-extension/src/entrypoints/popup/components/Credentials/CredentialCard.tsx
index 76a2545ef..67b40d714 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Credentials/CredentialCard.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Credentials/CredentialCard.tsx
@@ -57,7 +57,7 @@ const CredentialCard: React.FC<CredentialCardProps> = ({ credential }) => {
return (
<li>
<button
- onClick={() => navigate(`/credentials/${credential.Id}`)}
+ onClick={() => navigate(`/items/${credential.Id}`)}
className="w-full p-2 border dark:border-gray-600 rounded flex items-center bg-white dark:bg-gray-800 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<img
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/FieldBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/FieldBlock.tsx
new file mode 100644
index 000000000..56923d98e
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/FieldBlock.tsx
@@ -0,0 +1,101 @@
+import React from 'react';
+
+import { FormInputCopyToClipboard } from '@/entrypoints/popup/components/Forms/FormInputCopyToClipboard';
+
+import type { ItemField } from '@/utils/dist/shared/models/vault';
+
+interface FieldBlockProps {
+ field: ItemField;
+}
+
+/**
+ * Convert URLs in text to clickable links (same as NotesBlock).
+ */
+const convertUrlsToLinks = (text: string): string => {
+ const urlPattern = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/g;
+
+ return text.replace(urlPattern, (url) => {
+ const href = url.startsWith('http') ? url : `http://${url}`;
+ return `<a href="${href}" target="_blank" rel="noopener noreferrer" class="text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300">${url}</a>`;
+ });
+};
+
+/**
+ * Dynamic field block component that renders based on field type.
+ * Uses the same FormInputCopyToClipboard component as existing credential blocks.
+ */
+const FieldBlock: React.FC<FieldBlockProps> = ({ field }) => {
+ // Skip rendering if no value
+ if (!field.Value || (typeof field.Value === 'string' && field.Value.trim() === '')) {
+ return null;
+ }
+
+ const values = Array.isArray(field.Value) ? field.Value : [field.Value];
+
+ // Handle multi-value fields (like multiple URLs)
+ if (values.length > 1) {
+ return (
+ <div className="space-y-2">
+ {values.map((value, idx) => (
+ <FormInputCopyToClipboard
+ key={`${field.FieldKey}-${idx}`}
+ id={`${field.FieldKey}-${idx}`}
+ label={idx === 0 ? field.Label : `${field.Label} ${idx + 1}`}
+ value={value}
+ type={field.FieldType === 'Password' ? 'password' : 'text'}
+ />
+ ))}
+ </div>
+ );
+ }
+
+ const value = values[0];
+
+ // Render based on field type
+ switch (field.FieldType) {
+ case 'Password':
+ return (
+ <FormInputCopyToClipboard
+ id={field.FieldKey}
+ label={field.Label}
+ value={value}
+ type="password"
+ />
+ );
+
+ case 'TextArea':
+ // Use NotesBlock-style rendering for multi-line text
+ const formattedText = convertUrlsToLinks(value);
+ return (
+ <div>
+ <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
+ {field.Label}
+ </label>
+ <div className="p-4 bg-gray-50 rounded-lg dark:bg-gray-700">
+ <p
+ className="text-gray-900 dark:text-gray-100 whitespace-pre-wrap"
+ dangerouslySetInnerHTML={{ __html: formattedText }}
+ />
+ </div>
+ </div>
+ );
+
+ case 'Email':
+ case 'URL':
+ case 'Phone':
+ case 'Date':
+ case 'Number':
+ case 'Text':
+ default:
+ return (
+ <FormInputCopyToClipboard
+ id={field.FieldKey}
+ label={field.Label}
+ value={value}
+ type="text"
+ />
+ );
+ }
+};
+
+export default FieldBlock;
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/index.tsx b/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/index.tsx
index 45926b2b2..64fe860b8 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/index.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/index.tsx
@@ -1,6 +1,7 @@
import AliasBlock from './AliasBlock';
import AttachmentBlock from './AttachmentBlock';
import EmailBlock from './EmailBlock';
+import FieldBlock from './FieldBlock';
import HeaderBlock from './HeaderBlock';
import LoginCredentialsBlock from './LoginCredentialsBlock';
import NotesBlock from './NotesBlock';
@@ -13,5 +14,6 @@ export {
LoginCredentialsBlock,
AliasBlock,
NotesBlock,
- AttachmentBlock
+ AttachmentBlock,
+ FieldBlock
};
\ No newline at end of file
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemAddEdit.tsx
new file mode 100644
index 000000000..9e28bf6df
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemAddEdit.tsx
@@ -0,0 +1,417 @@
+import React, { useState, useEffect, useCallback, useMemo } from 'react';
+import { useForm } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+import { useNavigate, useParams } from 'react-router-dom';
+import { sendMessage } from 'webext-bridge/popup';
+
+import Modal from '@/entrypoints/popup/components/Dialogs/Modal';
+import { FormInput } from '@/entrypoints/popup/components/Forms/FormInput';
+import PasswordField from '@/entrypoints/popup/components/Forms/PasswordField';
+import HeaderButton from '@/entrypoints/popup/components/HeaderButton';
+import { HeaderIconType } from '@/entrypoints/popup/components/Icons/HeaderIcons';
+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 { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
+
+import type { Item, ItemField, ItemType, FieldType } from '@/utils/dist/shared/models/vault';
+import { getSystemFieldsForItemType } from '@/utils/dist/shared/models/vault';
+
+/**
+ * Form data structure matching the Item model
+ */
+type ItemFormData = {
+ Id: string;
+ Name: string;
+ ItemType: ItemType;
+ Fields: Record<string, string | string[]>; // FieldKey -> Value mapping
+};
+
+/**
+ * Add or edit item page with dynamic field support.
+ * Shows all applicable system fields for the item type, not just fields with values.
+ */
+const ItemAddEdit: React.FC = () => {
+ const { t } = useTranslation();
+ const { id } = useParams();
+ const navigate = useNavigate();
+ const dbContext = useDb();
+ const isEditMode = id !== undefined && id.length > 0;
+
+ const { executeVaultMutation, isLoading, syncStatus } = useVaultMutate();
+ const { setHeaderButtons } = useHeaderButtons();
+ const { setIsInitialLoading } = useLoading();
+ const [localLoading, setLocalLoading] = useState(true);
+ const [showDeleteModal, setShowDeleteModal] = useState(false);
+ const [item, setItem] = useState<Item | null>(null);
+
+ // Form state for dynamic fields
+ const [fieldValues, setFieldValues] = useState<Record<string, string | string[]>>({});
+
+ /**
+ * Get all applicable system fields for the current item type.
+ * These are sorted by DefaultDisplayOrder.
+ */
+ const applicableSystemFields = useMemo(() => {
+ if (!item) return [];
+ return getSystemFieldsForItemType(item.ItemType);
+ }, [item?.ItemType]);
+
+ /**
+ * Group system fields by category for organized rendering.
+ */
+ const groupedSystemFields = useMemo(() => {
+ const groups: Record<string, typeof applicableSystemFields> = {};
+
+ applicableSystemFields.forEach(field => {
+ const category = field.Category || 'Other';
+ if (!groups[category]) {
+ groups[category] = [];
+ }
+ groups[category].push(field);
+ });
+
+ return groups;
+ }, [applicableSystemFields]);
+
+ /**
+ * Load item data if in edit mode.
+ */
+ useEffect(() => {
+ if (!dbContext?.sqliteClient || !id || !isEditMode) {
+ // Create mode - initialize with defaults
+ setItem({
+ Id: crypto.randomUUID().toUpperCase(),
+ Name: '',
+ ItemType: 'Login',
+ Fields: [],
+ CreatedAt: new Date().toISOString(),
+ UpdatedAt: new Date().toISOString()
+ });
+ setLocalLoading(false);
+ setIsInitialLoading(false);
+ return;
+ }
+
+ try {
+ const result = dbContext.sqliteClient.getItemById(id);
+ if (result) {
+ setItem(result);
+
+ // Initialize field values from existing fields
+ const initialValues: Record<string, string | string[]> = {};
+ result.Fields.forEach(field => {
+ initialValues[field.FieldKey] = field.Value;
+ });
+ setFieldValues(initialValues);
+
+ setLocalLoading(false);
+ setIsInitialLoading(false);
+ } else {
+ console.error('Item not found');
+ navigate('/credentials');
+ }
+ } catch (err) {
+ console.error('Error loading item:', err);
+ setLocalLoading(false);
+ setIsInitialLoading(false);
+ }
+ }, [dbContext?.sqliteClient, id, isEditMode, navigate, setIsInitialLoading]);
+
+ /**
+ * Handle field value change.
+ */
+ const handleFieldChange = useCallback((fieldKey: string, value: string | string[]) => {
+ setFieldValues(prev => ({
+ ...prev,
+ [fieldKey]: value
+ }));
+ }, []);
+
+ /**
+ * Handle form submission.
+ */
+ const handleSave = useCallback(async () => {
+ if (!item) return;
+
+ try {
+ // Build the fields array from fieldValues
+ const fields: ItemField[] = [];
+
+ applicableSystemFields.forEach(systemField => {
+ const value = fieldValues[systemField.FieldKey];
+
+ // Only include fields with non-empty values
+ if (value && (Array.isArray(value) ? value.length > 0 : value.trim() !== '')) {
+ fields.push({
+ FieldKey: systemField.FieldKey,
+ Label: systemField.Label,
+ FieldType: systemField.FieldType,
+ Value: value,
+ IsHidden: systemField.IsHidden,
+ DisplayOrder: systemField.DefaultDisplayOrder
+ });
+ }
+ });
+
+ const updatedItem: Item = {
+ ...item,
+ Fields: fields,
+ UpdatedAt: new Date().toISOString()
+ };
+
+ // Save to database and sync vault
+ if (!dbContext?.sqliteClient) {
+ throw new Error('Database not initialized');
+ }
+
+ await executeVaultMutation(async () => {
+ if (isEditMode) {
+ await dbContext.sqliteClient!.updateItem(updatedItem);
+ console.log('Item updated:', updatedItem);
+ } else {
+ await dbContext.sqliteClient!.createItem(updatedItem);
+ console.log('Item created:', updatedItem);
+ }
+ });
+
+ // Navigate back to details page
+ navigate(`/items/${updatedItem.Id}`);
+ } catch (err) {
+ console.error('Error saving item:', err);
+ }
+ }, [item, fieldValues, applicableSystemFields, dbContext, isEditMode, executeVaultMutation, navigate]);
+
+ /**
+ * Handle delete action.
+ */
+ const handleDelete = useCallback(async () => {
+ if (!item || !isEditMode || !dbContext?.sqliteClient) return;
+
+ try {
+ // Delete from database and sync vault
+ await executeVaultMutation(async () => {
+ await dbContext.sqliteClient!.deleteItemById(item.Id);
+ console.log('Item deleted:', item.Id);
+ });
+
+ // Navigate back to credentials list
+ navigate('/credentials');
+ } catch (err) {
+ console.error('Error deleting item:', err);
+ } finally {
+ setShowDeleteModal(false);
+ }
+ }, [item, isEditMode, dbContext, executeVaultMutation, navigate]);
+
+ /**
+ * Handle cancel action.
+ */
+ const handleCancel = useCallback(() => {
+ if (isEditMode) {
+ navigate(`/items/${id}`);
+ } else {
+ navigate('/credentials');
+ }
+ }, [isEditMode, id, navigate]);
+
+ // Set header buttons
+ useEffect(() => {
+ const headerButtonsJSX = isEditMode ? (
+ <HeaderButton
+ onClick={() => setShowDeleteModal(true)}
+ title={t('credentials.deleteCredential')}
+ iconType={HeaderIconType.DELETE}
+ />
+ ) : null;
+
+ setHeaderButtons(headerButtonsJSX);
+
+ return () => setHeaderButtons(null);
+ }, [setHeaderButtons, isEditMode, t]);
+
+ /**
+ * Render a field input based on field type.
+ */
+ const renderFieldInput = useCallback((fieldKey: string, label: string, fieldType: FieldType, isHidden: boolean, isMultiValue: boolean) => {
+ const value = fieldValues[fieldKey] || '';
+
+ // Handle multi-value fields
+ if (isMultiValue) {
+ const values = Array.isArray(value) ? value : value ? [value] : [''];
+
+ return (
+ <div className="space-y-2">
+ <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
+ {label}
+ </label>
+ {values.map((val, idx) => (
+ <div key={`${fieldKey}-${idx}`} className="flex gap-2">
+ <FormInput
+ id={`${fieldKey}-${idx}`}
+ label=""
+ value={val}
+ onChange={(value) => {
+ const newValues = [...values];
+ newValues[idx] = value;
+ handleFieldChange(fieldKey, newValues.filter(v => v.trim() !== ''));
+ }}
+ type="text"
+ placeholder={`${label} ${idx + 1}`}
+ />
+ {idx === values.length - 1 && (
+ <button
+ type="button"
+ onClick={() => handleFieldChange(fieldKey, [...values, ''])}
+ className="px-3 py-2 text-sm text-primary-600 dark:text-primary-400 hover:text-primary-700 dark:hover:text-primary-300"
+ >
+ +
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+ );
+ }
+
+ // Single-value fields
+ const stringValue = Array.isArray(value) ? value[0] || '' : value;
+
+ switch (fieldType) {
+ case 'Password':
+ return (
+ <PasswordField
+ id={fieldKey}
+ label={label}
+ value={stringValue}
+ onChange={(val) => handleFieldChange(fieldKey, val)}
+ />
+ );
+
+ case 'TextArea':
+ return (
+ <div>
+ <label htmlFor={fieldKey} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
+ {label}
+ </label>
+ <textarea
+ id={fieldKey}
+ value={stringValue}
+ onChange={(e) => handleFieldChange(fieldKey, e.target.value)}
+ rows={4}
+ className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-white"
+ placeholder={label}
+ />
+ </div>
+ );
+
+ case 'Email':
+ case 'URL':
+ case 'Phone':
+ case 'Number':
+ case 'Date':
+ case 'Text':
+ default:
+ return (
+ <FormInput
+ id={fieldKey}
+ label={label}
+ value={stringValue}
+ onChange={(value) => handleFieldChange(fieldKey, value)}
+ type="text"
+ placeholder={label}
+ />
+ );
+ }
+ }, [fieldValues, handleFieldChange]);
+
+ if (localLoading || !item) {
+ return <LoadingSpinner />;
+ }
+
+ return (
+ <div className="space-y-6">
+ {/* Item Name */}
+ <div>
+ <FormInput
+ id="itemName"
+ label={t('credentials.serviceName')}
+ value={item.Name || ''}
+ onChange={(value) => setItem({ ...item, Name: value })}
+ type="text"
+ placeholder={t('credentials.serviceName')}
+ required
+ />
+ </div>
+
+ {/* Render fields grouped by category */}
+ {Object.keys(groupedSystemFields).map(category => (
+ <div key={category} className="space-y-4">
+ <h2 className="text-lg font-semibold text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700 pb-2">
+ {category === 'Login' && t('credentials.loginCredentials')}
+ {category === 'Alias' && t('credentials.aliasInformation')}
+ {category === 'Card' && t('credentials.cardInformation')}
+ {category === 'Identity' && t('credentials.identityInformation')}
+ {category !== 'Login' && category !== 'Alias' && category !== 'Card' && category !== 'Identity' && category}
+ </h2>
+
+ {groupedSystemFields[category].map(field => (
+ <div key={field.FieldKey}>
+ {renderFieldInput(
+ field.FieldKey,
+ field.Label,
+ field.FieldType,
+ field.IsHidden,
+ field.IsMultiValue
+ )}
+ </div>
+ ))}
+ </div>
+ ))}
+
+ {/* Action Buttons */}
+ <div className="flex gap-3 pt-6 border-t border-gray-200 dark:border-gray-700">
+ <button
+ type="button"
+ onClick={handleSave}
+ disabled={isLoading}
+ className="flex-1 px-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {isLoading ? t('common.saving') : t('common.save')}
+ </button>
+ <button
+ type="button"
+ onClick={handleCancel}
+ disabled={isLoading}
+ className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {t('common.cancel')}
+ </button>
+ </div>
+
+ {/* Delete Confirmation Modal */}
+ {isEditMode && (
+ <Modal
+ isOpen={showDeleteModal}
+ onClose={() => setShowDeleteModal(false)}
+ title={t('credentials.deleteCredentialTitle')}
+ message={t('credentials.deleteCredentialConfirmation')}
+ confirmText={t('common.delete')}
+ cancelText={t('common.cancel')}
+ onConfirm={handleDelete}
+ variant="danger"
+ />
+ )}
+
+ {/* Sync Status */}
+ {syncStatus && (
+ <div className="fixed bottom-4 right-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg p-4 border border-gray-200 dark:border-gray-700">
+ <p className="text-sm text-gray-700 dark:text-gray-300">{syncStatus}</p>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default ItemAddEdit;
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemDetails.tsx
new file mode 100644
index 000000000..8646dd207
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemDetails.tsx
@@ -0,0 +1,235 @@
+import React, { useState, useEffect, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate, useParams } from 'react-router-dom';
+
+import {
+ HeaderBlock,
+ TotpBlock,
+ AttachmentBlock,
+ FieldBlock
+} from '@/entrypoints/popup/components/Credentials/Details';
+import HeaderButton from '@/entrypoints/popup/components/HeaderButton';
+import { HeaderIconType } from '@/entrypoints/popup/components/Icons/HeaderIcons';
+import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { useHeaderButtons } from '@/entrypoints/popup/context/HeaderButtonsContext';
+import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
+import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
+
+import type { Item } from '@/utils/dist/shared/models/vault';
+import { groupFieldsByCategory } from '@/utils/dist/shared/models/vault';
+
+/**
+ * Item details page with dynamic field rendering.
+ */
+const ItemDetails: React.FC = (): React.ReactElement => {
+ const { t } = useTranslation();
+ const { id } = useParams();
+ const navigate = useNavigate();
+ const dbContext = useDb();
+ const [item, setItem] = useState<Item | null>(null);
+ const { setIsInitialLoading } = useLoading();
+ const { setHeaderButtons } = useHeaderButtons();
+
+ /**
+ * Open the item details in a new expanded popup.
+ */
+ const openInNewPopup = useCallback((): void => {
+ PopoutUtility.openInNewPopup(`/items/${id}`);
+ }, [id]);
+
+ /**
+ * Navigate to the edit page for this item.
+ */
+ const handleEdit = useCallback((): void => {
+ navigate(`/items/${id}/edit`);
+ }, [id, navigate]);
+
+ useEffect(() => {
+ if (PopoutUtility.isPopup()) {
+ window.history.replaceState({}, '', `popup.html#/credentials`);
+ window.history.pushState({}, '', `popup.html#/items/${id}`);
+ }
+
+ if (!dbContext?.sqliteClient || !id) {
+ return;
+ }
+
+ try {
+ const result = dbContext.sqliteClient.getItemById(id);
+ if (result) {
+ console.log('Item loaded:', result);
+ console.log('Fields:', result.Fields);
+ console.log('Tags:', result.Tags);
+ setItem(result);
+ setIsInitialLoading(false);
+ } else {
+ console.error('Item not found');
+ navigate('/credentials');
+ }
+ } catch (err) {
+ console.error('Error loading item:', err);
+ }
+ }, [dbContext.sqliteClient, id, navigate, setIsInitialLoading]);
+
+ // Set header buttons on mount and clear on unmount
+ useEffect((): (() => void) => {
+ const headerButtonsJSX = (
+ <div className="flex items-center gap-2">
+ {!PopoutUtility.isPopup() && (
+ <HeaderButton
+ onClick={openInNewPopup}
+ title={t('common.openInNewWindow')}
+ iconType={HeaderIconType.EXPAND}
+ />
+ )}
+ <HeaderButton
+ onClick={handleEdit}
+ title={t('credentials.editCredential')}
+ iconType={HeaderIconType.EDIT}
+ />
+ </div>
+ );
+ setHeaderButtons(headerButtonsJSX);
+ return () => {};
+ }, [setHeaderButtons, handleEdit, openInNewPopup, t]);
+
+ // Clear header buttons on unmount
+ useEffect((): (() => void) => {
+ return () => setHeaderButtons(null);
+ }, [setHeaderButtons]);
+
+ if (!item) {
+ return <div>{t('common.loading')}</div>;
+ }
+
+ // Group fields by category for organized display
+ const groupedFields = groupFieldsByCategory(item);
+
+ console.log('Grouped fields:', groupedFields);
+ console.log('Item:', item);
+
+ return (
+ <div className="space-y-4">
+ {/* Header with name and logo */}
+ <div className="flex justify-between items-center">
+ <div className="flex items-center gap-3">
+ {item.Logo && (
+ <img
+ src={`data:image/png;base64,${btoa(String.fromCharCode(...Array.from(item.Logo as Uint8Array)))}`}
+ alt={item.Name || 'Item'}
+ className="w-10 h-10 rounded"
+ />
+ )}
+ <h1 className="text-xl font-semibold text-gray-900 dark:text-white">
+ {item.Name || 'Untitled Item'}
+ </h1>
+ </div>
+ </div>
+
+ {/* Debug info */}
+ <div className="bg-yellow-100 dark:bg-yellow-900 p-2 rounded text-xs">
+ <strong>Debug:</strong> Fields count: {item.Fields.length},
+ Tags count: {item.Tags?.length || 0},
+ Grouped keys: {Object.keys(groupedFields).join(', ')}
+ </div>
+
+ {/* Render fields dynamically by category */}
+ {Object.keys(groupedFields).length > 0 && (
+ <>
+ {groupedFields.Login && groupedFields.Login.length > 0 && (
+ <div className="space-y-2">
+ <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
+ {t('credentials.loginCredentials')}
+ </h2>
+ {groupedFields.Login.map((field) => (
+ <FieldBlock key={field.FieldKey} field={field} />
+ ))}
+ </div>
+ )}
+
+ {groupedFields.Alias && groupedFields.Alias.length > 0 && (
+ <div className="space-y-2">
+ <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
+ {t('credentials.aliasInformation')}
+ </h2>
+ {groupedFields.Alias.map((field) => (
+ <FieldBlock key={field.FieldKey} field={field} />
+ ))}
+ </div>
+ )}
+
+ {groupedFields.Card && groupedFields.Card.length > 0 && (
+ <div className="space-y-2">
+ <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
+ {t('credentials.cardInformation')}
+ </h2>
+ {groupedFields.Card.map((field) => (
+ <FieldBlock key={field.FieldKey} field={field} />
+ ))}
+ </div>
+ )}
+
+ {groupedFields.Identity && groupedFields.Identity.length > 0 && (
+ <div className="space-y-2">
+ <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
+ {t('credentials.identityInformation')}
+ </h2>
+ {groupedFields.Identity.map((field) => (
+ <FieldBlock key={field.FieldKey} field={field} />
+ ))}
+ </div>
+ )}
+
+ {groupedFields.API && groupedFields.API.length > 0 && (
+ <div className="space-y-2">
+ <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
+ {t('credentials.apiInformation')}
+ </h2>
+ {groupedFields.API.map((field) => (
+ <FieldBlock key={field.FieldKey} field={field} />
+ ))}
+ </div>
+ )}
+
+ {groupedFields.Custom && groupedFields.Custom.length > 0 && (
+ <div className="space-y-2">
+ <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
+ {t('credentials.customFields')}
+ </h2>
+ {groupedFields.Custom.map((field) => (
+ <FieldBlock key={field.FieldKey} field={field} />
+ ))}
+ </div>
+ )}
+ </>
+ )}
+
+ {/* TOTP codes */}
+ {item.HasTotp && <TotpBlock credentialId={item.Id} />}
+
+ {/* Attachments */}
+ {item.HasAttachment && <AttachmentBlock credentialId={item.Id} />}
+
+ {/* Tags */}
+ {item.Tags && item.Tags.length > 0 && (
+ <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
+ <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
+ {t('credentials.tags')}
+ </label>
+ <div className="flex flex-wrap gap-2">
+ {item.Tags.map((tag) => (
+ <span
+ key={tag.Id}
+ className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"
+ >
+ {tag.Name}
+ </span>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default ItemDetails;
diff --git a/apps/browser-extension/src/utils/SqliteClient.ts b/apps/browser-extension/src/utils/SqliteClient.ts
index 6c14da8cb..ac7209706 100644
--- a/apps/browser-extension/src/utils/SqliteClient.ts
+++ b/apps/browser-extension/src/utils/SqliteClient.ts
@@ -1,8 +1,9 @@
import initSqlJs, { Database } from 'sql.js';
import * as dateFormatter from '@/utils/dateFormatter';
-import type { Credential, EncryptionKey, PasswordSettings, TotpCode, Passkey } from '@/utils/dist/shared/models/vault';
+import type { Credential, EncryptionKey, PasswordSettings, TotpCode, Passkey, Item, ItemField, ItemTagRef, FieldType } from '@/utils/dist/shared/models/vault';
import type { Attachment } from '@/utils/dist/shared/models/vault';
+import { FieldKey, SystemFieldRegistry, getSystemField } from '@/utils/dist/shared/models/vault';
import type { VaultVersion } from '@/utils/dist/shared/vault-sql';
import { VaultSqlGenerator, checkVersionCompatibility, extractVersionFromMigrationId } from '@/utils/dist/shared/vault-sql';
import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
@@ -207,37 +208,25 @@ export class SqliteClient {
* @returns Credential object with service details or null if not found.
*/
public getCredentialById(credentialId: string): Credential | null {
+ // WIP: Quick V5 schema refactor - field-based queries
const query = `
SELECT DISTINCT
- c.Id,
- c.Username,
- c.Notes,
- c.ServiceId,
- s.Name as ServiceName,
- s.Url as ServiceUrl,
- s.Logo as Logo,
- a.FirstName,
- a.LastName,
- a.NickName,
- a.BirthDate,
- a.Gender,
- a.Email,
- p.Value as Password,
+ i.Id,
+ i.Name as ServiceName,
+ l.FileData as Logo,
CASE
WHEN EXISTS (
SELECT 1 FROM Passkeys pk
- WHERE pk.CredentialId = c.Id AND pk.IsDeleted = 0
+ WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0
) THEN 1
ELSE 0
END as HasPasskey,
- (SELECT pk.RpId FROM Passkeys pk WHERE pk.CredentialId = c.Id AND pk.IsDeleted = 0 LIMIT 1) as PasskeyRpId,
- (SELECT pk.DisplayName FROM Passkeys pk WHERE pk.CredentialId = c.Id AND pk.IsDeleted = 0 LIMIT 1) as PasskeyDisplayName
- FROM Credentials c
- LEFT JOIN Services s ON c.ServiceId = s.Id
- LEFT JOIN Aliases a ON c.AliasId = a.Id
- LEFT JOIN Passwords p ON p.CredentialId = c.Id
- WHERE c.IsDeleted = 0
- AND c.Id = ?`;
+ (SELECT pk.RpId FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0 LIMIT 1) as PasskeyRpId,
+ (SELECT pk.DisplayName FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0 LIMIT 1) as PasskeyDisplayName
+ FROM Items i
+ LEFT JOIN Logos l ON i.LogoId = l.Id
+ WHERE i.IsDeleted = 0
+ AND i.Id = ?`;
const results = this.executeQuery(query, [credentialId]);
@@ -245,27 +234,44 @@ export class SqliteClient {
return null;
}
- // Convert the first row to a Credential object
+ // Get field values for this item (only system fields, which have FieldKey)
+ const fieldQuery = `
+ SELECT
+ fv.FieldKey,
+ fv.Value
+ FROM FieldValues fv
+ WHERE fv.ItemId = ? AND fv.IsDeleted = 0 AND fv.FieldKey IS NOT NULL`;
+
+ const fieldResults = this.executeQuery<{FieldKey: string, Value: string}>(fieldQuery, [credentialId]);
+
+ // Map field values by FieldKey
+ const fields: {[key: string]: string} = {};
+ fieldResults.forEach(f => {
+ if (f.FieldKey) {
+ fields[f.FieldKey] = f.Value;
+ }
+ });
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const row = results[0] as any;
return {
Id: row.Id,
- Username: row.Username,
- Password: row.Password,
+ Username: fields[FieldKey.LoginUsername] || undefined,
+ Password: fields[FieldKey.LoginPassword] || '',
ServiceName: row.ServiceName,
- ServiceUrl: row.ServiceUrl,
+ ServiceUrl: fields[FieldKey.LoginUrl] || undefined,
Logo: row.Logo,
- Notes: row.Notes,
+ Notes: fields[FieldKey.LoginNotes] || undefined,
HasPasskey: row.HasPasskey === 1,
PasskeyRpId: row.PasskeyRpId,
PasskeyDisplayName: row.PasskeyDisplayName,
Alias: {
- FirstName: row.FirstName,
- LastName: row.LastName,
- NickName: row.NickName,
- BirthDate: row.BirthDate,
- Gender: row.Gender,
- Email: row.Email
+ FirstName: fields[FieldKey.AliasFirstName] || undefined,
+ LastName: fields[FieldKey.AliasLastName] || undefined,
+ NickName: fields[FieldKey.AliasNickname] || undefined,
+ BirthDate: fields[FieldKey.AliasBirthdate] || '',
+ Gender: fields[FieldKey.AliasGender] || undefined,
+ Email: fields[FieldKey.AliasEmail] || undefined
},
};
}
@@ -275,81 +281,380 @@ export class SqliteClient {
* @returns Array of Credential objects with service details.
*/
public getAllCredentials(): Credential[] {
+ // WIP: Quick V5 schema refactor - field-based queries
const query = `
SELECT DISTINCT
- c.Id,
- c.Username,
- c.Notes,
- c.ServiceId,
- s.Name as ServiceName,
- s.Url as ServiceUrl,
- s.Logo as Logo,
- a.FirstName,
- a.LastName,
- a.NickName,
- a.BirthDate,
- a.Gender,
- a.Email,
- p.Value as Password,
+ i.Id,
+ i.Name as ServiceName,
+ l.FileData as Logo,
CASE
WHEN EXISTS (
SELECT 1 FROM Passkeys pk
- WHERE pk.CredentialId = c.Id AND pk.IsDeleted = 0
+ WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0
) THEN 1
ELSE 0
END as HasPasskey,
CASE
WHEN EXISTS (
SELECT 1 FROM Attachments att
- WHERE att.CredentialId = c.Id AND att.IsDeleted = 0
+ WHERE att.ItemId = i.Id AND att.IsDeleted = 0
) THEN 1
ELSE 0
END as HasAttachment
- FROM Credentials c
- LEFT JOIN Services s ON c.ServiceId = s.Id
- LEFT JOIN Aliases a ON c.AliasId = a.Id
- LEFT JOIN Passwords p ON p.CredentialId = c.Id
- WHERE c.IsDeleted = 0
- ORDER BY c.CreatedAt DESC`;
+ FROM Items i
+ LEFT JOIN Logos l ON i.LogoId = l.Id
+ WHERE i.IsDeleted = 0
+ ORDER BY i.CreatedAt DESC`;
const results = this.executeQuery(query);
+ // Get all field values in one query for performance
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- return results.map((row: any) => ({
+ const itemIds = results.map((r: any) => r.Id);
+ if (itemIds.length === 0) {
+ return [];
+ }
+
+ const fieldQuery = `
+ SELECT fv.ItemId, fv.FieldKey, fv.Value
+ FROM FieldValues fv
+ WHERE fv.ItemId IN (${itemIds.map(() => '?').join(',')})
+ AND fv.IsDeleted = 0
+ AND fv.FieldKey IS NOT NULL`;
+
+ const fieldResults = this.executeQuery<{ItemId: string, FieldKey: string, Value: string}>(fieldQuery, itemIds);
+
+ // Group fields by item ID
+ const fieldsByItem: {[itemId: string]: {[fieldKey: string]: string}} = {};
+ fieldResults.forEach(f => {
+ if (!fieldsByItem[f.ItemId]) {
+ fieldsByItem[f.ItemId] = {};
+ }
+ if (f.FieldKey) {
+ fieldsByItem[f.ItemId][f.FieldKey] = f.Value;
+ }
+ });
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return results.map((row: any) => {
+ const fields = fieldsByItem[row.Id] || {};
+ return {
+ Id: row.Id,
+ Username: fields[FieldKey.LoginUsername] || undefined,
+ Password: fields[FieldKey.LoginPassword] || '',
+ ServiceName: row.ServiceName,
+ ServiceUrl: fields[FieldKey.LoginUrl] || undefined,
+ Logo: row.Logo,
+ Notes: fields[FieldKey.LoginNotes] || undefined,
+ HasPasskey: row.HasPasskey === 1,
+ HasAttachment: row.HasAttachment === 1,
+ Alias: {
+ FirstName: fields[FieldKey.AliasFirstName] || undefined,
+ LastName: fields[FieldKey.AliasLastName] || undefined,
+ NickName: fields[FieldKey.AliasNickname] || undefined,
+ BirthDate: fields[FieldKey.AliasBirthdate] || '',
+ Gender: fields[FieldKey.AliasGender] || undefined,
+ Email: fields[FieldKey.AliasEmail] || undefined
+ }
+ };
+ });
+ }
+
+ /**
+ * Fetch all items with their dynamic fields and tags.
+ * @returns Array of Item objects with field-based data.
+ */
+ public getAllItems(): Item[] {
+ const query = `
+ SELECT DISTINCT
+ i.Id,
+ i.Name,
+ i.ItemType,
+ i.FolderId,
+ l.FileData as Logo,
+ CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
+ CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
+ CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
+ i.CreatedAt,
+ i.UpdatedAt
+ FROM Items i
+ LEFT JOIN Logos l ON i.LogoId = l.Id
+ WHERE i.IsDeleted = 0
+ ORDER BY i.CreatedAt DESC`;
+
+ const items = this.executeQuery(query);
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const itemIds = items.map((i: any) => i.Id);
+ if (itemIds.length === 0) {
+ return [];
+ }
+
+ // Get all field values (both system fields and custom fields)
+ const fieldsQuery = `
+ SELECT
+ fv.ItemId,
+ fv.FieldKey,
+ fv.FieldDefinitionId,
+ fd.Label as CustomLabel,
+ fd.FieldType as CustomFieldType,
+ fd.IsHidden as CustomIsHidden,
+ fv.Value,
+ fv.Weight as DisplayOrder
+ FROM FieldValues fv
+ LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id
+ WHERE fv.ItemId IN (${itemIds.map(() => '?').join(',')})
+ AND fv.IsDeleted = 0
+ ORDER BY fv.ItemId, fv.Weight`;
+
+ const fieldRows = this.executeQuery<{
+ ItemId: string;
+ FieldKey: string | null;
+ FieldDefinitionId: string | null;
+ CustomLabel: string | null;
+ CustomFieldType: string | null;
+ CustomIsHidden: number | null;
+ Value: string;
+ DisplayOrder: number;
+ }>(fieldsQuery, itemIds);
+
+ // Process fields - handle system fields vs custom fields
+ const fields = fieldRows.map(row => {
+ // System field: has FieldKey, get metadata from SystemFieldRegistry
+ if (row.FieldKey) {
+ const systemField = getSystemField(row.FieldKey);
+ return {
+ ItemId: row.ItemId,
+ FieldKey: row.FieldKey,
+ Label: systemField?.Label || row.FieldKey,
+ FieldType: systemField?.FieldType || 'Text',
+ IsHidden: systemField?.IsHidden ? 1 : 0,
+ Value: row.Value,
+ DisplayOrder: row.DisplayOrder
+ };
+ } else {
+ // Custom field: has FieldDefinitionId, get metadata from FieldDefinitions
+ return {
+ ItemId: row.ItemId,
+ FieldKey: `custom_${row.FieldDefinitionId}`, // Generate a key for custom fields
+ Label: row.CustomLabel || '',
+ FieldType: row.CustomFieldType || 'Text',
+ IsHidden: row.CustomIsHidden || 0,
+ Value: row.Value,
+ DisplayOrder: row.DisplayOrder
+ };
+ }
+ });
+
+ // Get all tags
+ const tagsQuery = `
+ SELECT
+ it.ItemId,
+ t.Id,
+ t.Name,
+ t.Color
+ FROM ItemTags it
+ INNER JOIN Tags t ON it.TagId = t.Id
+ WHERE it.ItemId IN (${itemIds.map(() => '?').join(',')})
+ AND it.IsDeleted = 0
+ AND t.IsDeleted = 0
+ ORDER BY t.DisplayOrder, t.Name`;
+
+ const tags = this.executeQuery<{
+ ItemId: string;
+ Id: string;
+ Name: string;
+ Color: string | null;
+ }>(tagsQuery, itemIds);
+
+ // Group by ItemId
+ const fieldsByItem: {[itemId: string]: ItemField[]} = {};
+ fields.forEach(f => {
+ if (!fieldsByItem[f.ItemId]) {
+ fieldsByItem[f.ItemId] = [];
+ }
+ fieldsByItem[f.ItemId].push({
+ FieldKey: f.FieldKey,
+ Label: f.Label,
+ FieldType: f.FieldType as FieldType,
+ Value: f.Value,
+ IsHidden: f.IsHidden === 1,
+ DisplayOrder: f.DisplayOrder
+ });
+ });
+
+ const tagsByItem: {[itemId: string]: ItemTagRef[]} = {};
+ tags.forEach(t => {
+ if (!tagsByItem[t.ItemId]) {
+ tagsByItem[t.ItemId] = [];
+ }
+ tagsByItem[t.ItemId].push({
+ Id: t.Id,
+ Name: t.Name,
+ Color: t.Color || undefined
+ });
+ });
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return items.map((row: any) => ({
Id: row.Id,
- Username: row.Username,
- Password: row.Password,
- ServiceName: row.ServiceName,
- ServiceUrl: row.ServiceUrl,
+ Name: row.Name,
+ ItemType: row.ItemType,
Logo: row.Logo,
- Notes: row.Notes,
+ FolderId: row.FolderId,
+ FolderPath: null,
+ Tags: tagsByItem[row.Id] || [],
+ Fields: fieldsByItem[row.Id] || [],
HasPasskey: row.HasPasskey === 1,
HasAttachment: row.HasAttachment === 1,
- Alias: {
- FirstName: row.FirstName,
- LastName: row.LastName,
- NickName: row.NickName,
- BirthDate: row.BirthDate,
- Gender: row.Gender,
- Email: row.Email
- }
+ HasTotp: row.HasTotp === 1,
+ CreatedAt: row.CreatedAt,
+ UpdatedAt: row.UpdatedAt
}));
}
+ /**
+ * Fetch a single item by ID with its dynamic fields and tags.
+ * @param itemId - The ID of the item to fetch.
+ * @returns Item object or null if not found.
+ */
+ public getItemById(itemId: string): Item | null {
+ const query = `
+ SELECT
+ i.Id,
+ i.Name,
+ i.ItemType,
+ i.FolderId,
+ l.FileData as Logo,
+ CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
+ CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
+ CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
+ i.CreatedAt,
+ i.UpdatedAt
+ FROM Items i
+ LEFT JOIN Logos l ON i.LogoId = l.Id
+ WHERE i.Id = ? AND i.IsDeleted = 0`;
+
+ const results = this.executeQuery(query, [itemId]);
+ if (results.length === 0) {
+ return null;
+ }
+
+ // Get field values (both system fields and custom fields)
+ const fieldsQuery = `
+ SELECT
+ fv.FieldKey,
+ fv.FieldDefinitionId,
+ fd.Label as CustomLabel,
+ fd.FieldType as CustomFieldType,
+ fd.IsHidden as CustomIsHidden,
+ fv.Value,
+ fv.Weight as DisplayOrder
+ FROM FieldValues fv
+ LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id
+ WHERE fv.ItemId = ? AND fv.IsDeleted = 0
+ ORDER BY fv.Weight`;
+
+ const fieldRows = this.executeQuery<{
+ FieldKey: string | null;
+ FieldDefinitionId: string | null;
+ CustomLabel: string | null;
+ CustomFieldType: string | null;
+ CustomIsHidden: number | null;
+ Value: string;
+ DisplayOrder: number;
+ }>(fieldsQuery, [itemId]);
+
+ // Process fields - handle system fields vs custom fields
+ const fields = fieldRows.map(row => {
+ // System field: has FieldKey, get metadata from SystemFieldRegistry
+ if (row.FieldKey) {
+ const systemField = getSystemField(row.FieldKey);
+ return {
+ FieldKey: row.FieldKey,
+ Label: systemField?.Label || row.FieldKey,
+ FieldType: systemField?.FieldType || 'Text',
+ IsHidden: systemField?.IsHidden ? 1 : 0,
+ Value: row.Value,
+ DisplayOrder: row.DisplayOrder
+ };
+ } else {
+ // Custom field: has FieldDefinitionId, get metadata from FieldDefinitions
+ return {
+ FieldKey: `custom_${row.FieldDefinitionId}`, // Generate a key for custom fields
+ Label: row.CustomLabel || '',
+ FieldType: row.CustomFieldType || 'Text',
+ IsHidden: row.CustomIsHidden || 0,
+ Value: row.Value,
+ DisplayOrder: row.DisplayOrder
+ };
+ }
+ });
+
+ // Get tags
+ const tagsQuery = `
+ SELECT
+ t.Id,
+ t.Name,
+ t.Color
+ FROM ItemTags it
+ INNER JOIN Tags t ON it.TagId = t.Id
+ WHERE it.ItemId = ? AND it.IsDeleted = 0 AND t.IsDeleted = 0
+ ORDER BY t.DisplayOrder, t.Name`;
+
+ const tags = this.executeQuery<{
+ Id: string;
+ Name: string;
+ Color: string | null;
+ }>(tagsQuery, [itemId]);
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const row = results[0] as any;
+ return {
+ Id: row.Id,
+ Name: row.Name,
+ ItemType: row.ItemType,
+ Logo: row.Logo,
+ FolderId: row.FolderId,
+ FolderPath: null,
+ Tags: tags.map(t => ({
+ Id: t.Id,
+ Name: t.Name,
+ Color: t.Color || undefined
+ })),
+ Fields: fields.map(f => ({
+ FieldKey: f.FieldKey,
+ Label: f.Label,
+ FieldType: f.FieldType as FieldType,
+ Value: f.Value,
+ IsHidden: f.IsHidden === 1,
+ DisplayOrder: f.DisplayOrder
+ })),
+ HasPasskey: row.HasPasskey === 1,
+ HasAttachment: row.HasAttachment === 1,
+ HasTotp: row.HasTotp === 1,
+ CreatedAt: row.CreatedAt,
+ UpdatedAt: row.UpdatedAt
+ };
+ }
+
/**
* Fetch all unique email addresses from all credentials.
* @returns Array of email addresses.
*/
public getAllEmailAddresses(): string[] {
const query = `
- SELECT DISTINCT
- a.Email
- FROM Credentials c
- LEFT JOIN Aliases a ON c.AliasId = a.Id
- WHERE a.Email IS NOT NULL AND a.Email != '' AND c.IsDeleted = 0
+ SELECT DISTINCT fv.Value as Email
+ FROM FieldValues fv
+ INNER JOIN Items i ON fv.ItemId = i.Id
+ WHERE fv.FieldKey = ?
+ AND fv.Value IS NOT NULL
+ AND fv.Value != ''
+ AND fv.IsDeleted = 0
+ AND i.IsDeleted = 0
`;
- const results = this.executeQuery(query);
+ const results = this.executeQuery(query, [FieldKey.AliasEmail]);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return results.map((row: any) => row.Email);
@@ -1607,6 +1912,228 @@ export class SqliteClient {
throw error;
}
}
+
+ /**
+ * Create a new item with field-based structure
+ * @param item The item object to insert
+ * @returns The ID of the created item
+ */
+ public async createItem(item: Item): Promise<string> {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
+
+ try {
+ this.beginTransaction();
+
+ const currentDateTime = dateFormatter.now();
+ const itemId = item.Id || crypto.randomUUID().toUpperCase();
+
+ // 1. Insert Item
+ const itemQuery = `
+ INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;
+
+ this.executeUpdate(itemQuery, [
+ itemId,
+ item.Name ?? null,
+ item.ItemType,
+ null, // LogoId - handle logo separately if needed
+ item.FolderId ?? null,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
+
+ // 2. Insert FieldValues for all fields
+ if (item.Fields && item.Fields.length > 0) {
+ for (const field of item.Fields) {
+ // Skip empty fields
+ if (!field.Value || (typeof field.Value === 'string' && field.Value.trim() === '')) {
+ continue;
+ }
+
+ const fieldValueId = crypto.randomUUID().toUpperCase();
+ const fieldQuery = `
+ INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
+
+ /*
+ * For system fields: FieldKey is set, FieldDefinitionId is NULL
+ * For custom fields: FieldDefinitionId is set, FieldKey is NULL (future implementation)
+ */
+ const valueString = Array.isArray(field.Value) ? JSON.stringify(field.Value) : field.Value;
+
+ this.executeUpdate(fieldQuery, [
+ fieldValueId,
+ itemId,
+ null, // FieldDefinitionId (NULL for system fields)
+ field.FieldKey, // FieldKey (set for system fields)
+ valueString,
+ field.DisplayOrder ?? 0,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
+ }
+ }
+
+ await this.commitTransaction();
+ return itemId;
+ } catch (error) {
+ this.rollbackTransaction();
+ console.error('Error creating item:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * Update an existing item with field-based structure
+ * @param item The item object to update
+ * @returns The number of rows modified
+ */
+ public async updateItem(item: Item): Promise<number> {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
+
+ try {
+ this.beginTransaction();
+
+ const currentDateTime = dateFormatter.now();
+
+ // 1. Update Item
+ const itemQuery = `
+ UPDATE Items
+ SET Name = ?,
+ ItemType = ?,
+ FolderId = ?,
+ UpdatedAt = ?
+ WHERE Id = ?`;
+
+ this.executeUpdate(itemQuery, [
+ item.Name ?? null,
+ item.ItemType,
+ item.FolderId ?? null,
+ currentDateTime,
+ item.Id
+ ]);
+
+ // 2. Delete all existing FieldValues for this item
+ const deleteFieldsQuery = `
+ UPDATE FieldValues
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE ItemId = ?`;
+
+ this.executeUpdate(deleteFieldsQuery, [currentDateTime, item.Id]);
+
+ // 3. Insert new FieldValues
+ if (item.Fields && item.Fields.length > 0) {
+ for (const field of item.Fields) {
+ // Skip empty fields
+ if (!field.Value || (typeof field.Value === 'string' && field.Value.trim() === '')) {
+ continue;
+ }
+
+ const fieldValueId = crypto.randomUUID().toUpperCase();
+ const fieldQuery = `
+ INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
+
+ const valueString = Array.isArray(field.Value) ? JSON.stringify(field.Value) : field.Value;
+
+ this.executeUpdate(fieldQuery, [
+ fieldValueId,
+ item.Id,
+ null, // FieldDefinitionId (NULL for system fields)
+ field.FieldKey, // FieldKey (set for system fields)
+ valueString,
+ field.DisplayOrder ?? 0,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
+ }
+ }
+
+ await this.commitTransaction();
+ return 1;
+ } catch (error) {
+ this.rollbackTransaction();
+ console.error('Error updating item:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * Delete an item by ID (soft delete)
+ * @param itemId - The ID of the item to delete
+ * @returns The number of rows updated
+ */
+ public async deleteItemById(itemId: string): Promise<number> {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
+
+ try {
+ this.beginTransaction();
+
+ const currentDateTime = dateFormatter.now();
+
+ // 1. Soft delete the item
+ const itemQuery = `
+ UPDATE Items
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE Id = ?`;
+
+ const result = this.executeUpdate(itemQuery, [currentDateTime, itemId]);
+
+ // 2. Soft delete all associated FieldValues
+ const fieldsQuery = `
+ UPDATE FieldValues
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE ItemId = ?`;
+
+ this.executeUpdate(fieldsQuery, [currentDateTime, itemId]);
+
+ // 3. Soft delete associated Passkeys
+ const passkeysQuery = `
+ UPDATE Passkeys
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE ItemId = ?`;
+
+ this.executeUpdate(passkeysQuery, [currentDateTime, itemId]);
+
+ // 4. Soft delete associated TotpCodes
+ const totpQuery = `
+ UPDATE TotpCodes
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE ItemId = ?`;
+
+ this.executeUpdate(totpQuery, [currentDateTime, itemId]);
+
+ // 5. Soft delete associated Attachments
+ const attachmentsQuery = `
+ UPDATE Attachments
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE ItemId = ?`;
+
+ this.executeUpdate(attachmentsQuery, [currentDateTime, itemId]);
+
+ await this.commitTransaction();
+ return result;
+ } catch (error) {
+ this.rollbackTransaction();
+ console.error('Error deleting item:', error);
+ throw error;
+ }
+ }
}
export default SqliteClient;
\ No newline at end of file