Skip to content

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

Add TOTP code and attachment as optional fields (#1404)

Leendert de Borst8e9572c89e52
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/AttachmentBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/AttachmentBlock.tsx
index f438a9710..44658a10b 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/AttachmentBlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/AttachmentBlock.tsx
@@ -6,13 +6,14 @@ import { useDb } from '@/entrypoints/popup/context/DbContext';
import type { Attachment } from '@/utils/dist/shared/models/vault';
type AttachmentBlockProps = {
- credentialId: string;
+ credentialId?: string;
+ itemId?: string;
}
/**
- * This component shows attachments for a credential.
+ * This component shows attachments for a credential or item.
*/
-const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ credentialId }) => {
+const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ credentialId, itemId }) => {
const { t } = useTranslation();
const [attachments, setAttachments] = useState<Attachment[]>([]);
const [loading, setLoading] = useState(true);
@@ -49,7 +50,7 @@ const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ credentialId }) => {
useEffect(() => {
/**
- * Loads the attachments for the credential.
+ * Loads the attachments for the credential or item.
*/
const loadAttachments = async (): Promise<void> => {
if (!dbContext?.sqliteClient) {
@@ -57,7 +58,12 @@ const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ credentialId }) => {
}
try {
- const attachmentList = dbContext.sqliteClient.getAttachmentsForCredential(credentialId);
+ let attachmentList: Attachment[] = [];
+ if (itemId) {
+ attachmentList = dbContext.sqliteClient.getAttachmentsForItem(itemId);
+ } else if (credentialId) {
+ attachmentList = dbContext.sqliteClient.getAttachmentsForCredential(credentialId);
+ }
setAttachments(attachmentList);
} catch (error) {
console.error('Error loading attachments:', error);
@@ -67,7 +73,7 @@ const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ credentialId }) => {
};
loadAttachments();
- }, [credentialId, dbContext?.sqliteClient]);
+ }, [credentialId, itemId, dbContext?.sqliteClient]);
if (loading) {
return (
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/TotpBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/TotpBlock.tsx
index 6705ddb71..4a84122c7 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/TotpBlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Credentials/Details/TotpBlock.tsx
@@ -8,13 +8,14 @@ import { useDb } from '@/entrypoints/popup/context/DbContext';
import type { TotpCode } from '@/utils/dist/shared/models/vault';
type TotpBlockProps = {
- credentialId: string;
+ credentialId?: string;
+ itemId?: string;
}
/**
- * This component shows TOTP codes for a credential.
+ * This component shows TOTP codes for a credential or item.
*/
-const TotpBlock: React.FC<TotpBlockProps> = ({ credentialId }) => {
+const TotpBlock: React.FC<TotpBlockProps> = ({ credentialId, itemId }) => {
const { t } = useTranslation();
const [totpCodes, setTotpCodes] = useState<TotpCode[]>([]);
const [loading, setLoading] = useState(true);
@@ -84,7 +85,7 @@ const TotpBlock: React.FC<TotpBlockProps> = ({ credentialId }) => {
useEffect(() => {
/**
- * Loads the TOTP codes for the credential.
+ * Loads the TOTP codes for the credential or item.
*/
const loadTotpCodes = async (): Promise<void> => {
if (!dbContext?.sqliteClient) {
@@ -92,7 +93,12 @@ const TotpBlock: React.FC<TotpBlockProps> = ({ credentialId }) => {
}
try {
- const codes = dbContext.sqliteClient.getTotpCodesForCredential(credentialId);
+ let codes: TotpCode[] = [];
+ if (itemId) {
+ codes = dbContext.sqliteClient.getTotpCodesForItem(itemId);
+ } else if (credentialId) {
+ codes = dbContext.sqliteClient.getTotpCodesForCredential(credentialId);
+ }
setTotpCodes(codes);
} catch (error) {
console.error('Error loading TOTP codes:', error);
@@ -102,7 +108,7 @@ const TotpBlock: React.FC<TotpBlockProps> = ({ credentialId }) => {
};
loadTotpCodes();
- }, [credentialId, dbContext?.sqliteClient]);
+ }, [credentialId, itemId, dbContext?.sqliteClient]);
useEffect(() => {
/**
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemAddEdit.tsx
index ed985c5bd..dc03dfdef 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemAddEdit.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemAddEdit.tsx
@@ -2,6 +2,8 @@ import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
+import AttachmentUploader from '@/entrypoints/popup/components/Credentials/Details/AttachmentUploader';
+import TotpEditor from '@/entrypoints/popup/components/Credentials/Details/TotpEditor';
import Modal from '@/entrypoints/popup/components/Dialogs/Modal';
import EditableFieldLabel from '@/entrypoints/popup/components/Forms/EditableFieldLabel';
import { FormInput } from '@/entrypoints/popup/components/Forms/FormInput';
@@ -16,7 +18,7 @@ import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
import { IdentityHelperUtils, CreateIdentityGenerator, convertAgeRangeToBirthdateOptions } from '@/utils/dist/shared/identity-generator';
-import type { Item, ItemField, ItemType, FieldType } from '@/utils/dist/shared/models/vault';
+import type { Item, ItemField, ItemType, FieldType, Attachment, TotpCode } from '@/utils/dist/shared/models/vault';
import { getSystemFieldsForItemType, isFieldShownByDefault } from '@/utils/dist/shared/models/vault';
import { CreatePasswordGenerator } from '@/utils/dist/shared/password-generator';
@@ -160,6 +162,23 @@ const ItemAddEdit: React.FC = () => {
// Track password field visibility (for showing generated passwords)
const [showPassword, setShowPassword] = useState(false);
+ // TOTP codes state
+ const [totpCodes, setTotpCodes] = useState<TotpCode[]>([]);
+ const [originalTotpCodeIds, setOriginalTotpCodeIds] = useState<string[]>([]);
+ const [totpEditorState, setTotpEditorState] = useState<{
+ isAddFormVisible: boolean;
+ formData: { name: string; secretKey: string };
+ }>({
+ isAddFormVisible: false,
+ formData: { name: '', secretKey: '' }
+ });
+ const [show2FA, setShow2FA] = useState(false);
+
+ // Attachments state
+ const [attachments, setAttachments] = useState<Attachment[]>([]);
+ const [originalAttachmentIds, setOriginalAttachmentIds] = useState<string[]>([]);
+ const [showAttachments, setShowAttachments] = useState(false);
+
/**
* Get all applicable system fields for the current item type.
* These are sorted by DefaultDisplayOrder.
@@ -303,6 +322,22 @@ const ItemAddEdit: React.FC = () => {
setFieldValues(initialValues);
setCustomFields(existingCustomFields);
+ // Load TOTP codes for this item
+ const itemTotpCodes = dbContext.sqliteClient.getTotpCodesForItem(id);
+ setTotpCodes(itemTotpCodes);
+ setOriginalTotpCodeIds(itemTotpCodes.map(tc => tc.Id));
+ if (itemTotpCodes.length > 0) {
+ setShow2FA(true);
+ }
+
+ // Load attachments for this item
+ const itemAttachments = dbContext.sqliteClient.getAttachmentsForItem(id);
+ setAttachments(itemAttachments);
+ setOriginalAttachmentIds(itemAttachments.map(a => a.Id));
+ if (itemAttachments.length > 0) {
+ setShowAttachments(true);
+ }
+
setLocalLoading(false);
setIsInitialLoading(false);
} else {
@@ -405,9 +440,15 @@ const ItemAddEdit: React.FC = () => {
await executeVaultMutation(async () => {
if (isEditMode) {
- await dbContext.sqliteClient!.updateItem(updatedItem);
+ await dbContext.sqliteClient!.updateItem(
+ updatedItem,
+ originalAttachmentIds,
+ attachments,
+ originalTotpCodeIds,
+ totpCodes
+ );
} else {
- await dbContext.sqliteClient!.createItem(updatedItem);
+ await dbContext.sqliteClient!.createItem(updatedItem, attachments, totpCodes);
}
});
@@ -416,7 +457,7 @@ const ItemAddEdit: React.FC = () => {
} catch (err) {
console.error('Error saving item:', err);
}
- }, [item, fieldValues, applicableSystemFields, customFields, dbContext, isEditMode, executeVaultMutation, navigate]);
+ }, [item, fieldValues, applicableSystemFields, customFields, dbContext, isEditMode, executeVaultMutation, navigate, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes]);
/**
* Handle delete action.
@@ -674,7 +715,23 @@ const ItemAddEdit: React.FC = () => {
}, []);
/**
- * Add menu options - shows available optional sections (Notes and Custom Fields only).
+ * Handle adding 2FA section from menu.
+ */
+ const handleAdd2FAFromMenu = useCallback((): void => {
+ setShow2FA(true);
+ setShowAddMenu(false);
+ }, []);
+
+ /**
+ * Handle adding attachments section from menu.
+ */
+ const handleAddAttachmentsFromMenu = useCallback((): void => {
+ setShowAttachments(true);
+ setShowAddMenu(false);
+ }, []);
+
+ /**
+ * Add menu options - shows available optional sections (Notes, 2FA, Attachments, and Custom Fields).
* Alias has its own dedicated button since it's a core feature.
*/
const addMenuOptions = useMemo(() => {
@@ -700,6 +757,35 @@ const ItemAddEdit: React.FC = () => {
});
}
+ // 2FA TOTP option - only for Login and Alias types, and when not already shown
+ const supports2FA = item?.ItemType === 'Login' || item?.ItemType === 'Alias';
+ if (supports2FA && !show2FA) {
+ options.push({
+ key: '2fa',
+ label: t('common.twoFactorAuthentication'),
+ icon: (
+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
+ </svg>
+ ),
+ action: handleAdd2FAFromMenu
+ });
+ }
+
+ // Attachments option - available for all types, when not already shown
+ if (!showAttachments) {
+ options.push({
+ key: 'attachments',
+ label: t('common.attachments'),
+ icon: (
+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
+ </svg>
+ ),
+ action: handleAddAttachmentsFromMenu
+ });
+ }
+
// Custom field option (always available)
options.push({
key: 'custom',
@@ -713,7 +799,7 @@ const ItemAddEdit: React.FC = () => {
});
return options;
- }, [showNotes, notesField, fieldValues, isEditMode, t, handleAddNotesFromMenu, handleAddCustomFieldFromMenu, shouldShowFieldByDefault]);
+ }, [showNotes, notesField, fieldValues, isEditMode, t, handleAddNotesFromMenu, handleAddCustomFieldFromMenu, handleAdd2FAFromMenu, handleAddAttachmentsFromMenu, shouldShowFieldByDefault, item?.ItemType, show2FA, showAttachments]);
// Set header buttons
useEffect(() => {
@@ -1133,6 +1219,26 @@ const ItemAddEdit: React.FC = () => {
</div>
)}
+ {/* 2FA TOTP Section - only for Login and Alias types */}
+ {show2FA && (item?.ItemType === 'Login' || item?.ItemType === 'Alias') && (
+ <TotpEditor
+ totpCodes={totpCodes}
+ onTotpCodesChange={setTotpCodes}
+ originalTotpCodeIds={originalTotpCodeIds}
+ isAddFormVisible={totpEditorState.isAddFormVisible}
+ formData={totpEditorState.formData}
+ onStateChange={setTotpEditorState}
+ />
+ )}
+
+ {/* Attachments Section */}
+ {showAttachments && (
+ <AttachmentUploader
+ attachments={attachments}
+ onAttachmentsChange={setAttachments}
+ />
+ )}
+
{/* Generic + button with dropdown menu for Notes and Custom Fields */}
<div className="relative">
<button
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 0123deae7..7d5ae4dfe 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/credentials/ItemDetails.tsx
@@ -3,7 +3,6 @@ import { useTranslation } from 'react-i18next';
import { useNavigate, useParams } from 'react-router-dom';
import {
- HeaderBlock,
TotpBlock,
AttachmentBlock,
FieldBlock
@@ -168,12 +167,10 @@ const ItemDetails: React.FC = (): React.ReactElement => {
</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>
+ {/* TOTP codes - only for Login and Alias types, shown at top */}
+ {(item.ItemType === 'Login' || item.ItemType === 'Alias') && (
+ <TotpBlock itemId={item.Id} />
+ )}
{/* Render fields dynamically by category */}
{Object.keys(groupedFields).length > 0 && (
@@ -235,11 +232,8 @@ const ItemDetails: React.FC = (): React.ReactElement => {
</>
)}
- {/* TOTP codes */}
- {item.HasTotp && <TotpBlock credentialId={item.Id} />}
-
- {/* Attachments */}
- {item.HasAttachment && <AttachmentBlock credentialId={item.Id} />}
+ {/* Attachments - shown at bottom */}
+ <AttachmentBlock itemId={item.Id} />
{/* Tags */}
{item.Tags && item.Tags.length > 0 && (
diff --git a/apps/browser-extension/src/utils/SqliteClient.ts b/apps/browser-extension/src/utils/SqliteClient.ts
index d39e6d64c..226ca0b6a 100644
--- a/apps/browser-extension/src/utils/SqliteClient.ts
+++ b/apps/browser-extension/src/utils/SqliteClient.ts
@@ -1174,6 +1174,70 @@ export class SqliteClient {
}
}
+ /**
+ * Get TOTP codes for an item
+ * @param itemId - The ID of the item to get TOTP codes for
+ * @returns Array of TotpCode objects
+ */
+ public getTotpCodesForItem(itemId: string): TotpCode[] {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
+
+ try {
+ if (!this.tableExists('TotpCodes')) {
+ return [];
+ }
+
+ const query = `
+ SELECT
+ Id,
+ Name,
+ SecretKey,
+ ItemId
+ FROM TotpCodes
+ WHERE ItemId = ? AND IsDeleted = 0`;
+
+ return this.executeQuery<TotpCode>(query, [itemId]);
+ } catch (error) {
+ console.error('Error getting TOTP codes for item:', error);
+ return [];
+ }
+ }
+
+ /**
+ * Get attachments for an item
+ * @param itemId - The ID of the item
+ * @returns Array of attachments for the item
+ */
+ public getAttachmentsForItem(itemId: string): Attachment[] {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
+
+ try {
+ if (!this.tableExists('Attachments')) {
+ return [];
+ }
+
+ const query = `
+ SELECT
+ Id,
+ Filename,
+ Blob,
+ ItemId,
+ CreatedAt,
+ UpdatedAt,
+ IsDeleted
+ FROM Attachments
+ WHERE ItemId = ? AND IsDeleted = 0`;
+ return this.executeQuery<Attachment>(query, [itemId]);
+ } catch (error) {
+ console.error('Error getting attachments for item:', error);
+ return [];
+ }
+ }
+
/**
* Delete a credential by ID
* @param credentialId - The ID of the credential to delete
@@ -1973,9 +2037,11 @@ export class SqliteClient {
/**
* Create a new item with field-based structure
* @param item The item object to insert
+ * @param attachments Optional attachments to associate with the item
+ * @param totpCodes Optional TOTP codes to associate with the item
* @returns The ID of the created item
*/
- public async createItem(item: Item): Promise<string> {
+ public async createItem(item: Item, attachments: Attachment[] = [], totpCodes: TotpCode[] = []): Promise<string> {
if (!this.db) {
throw new Error('Database not initialized');
}
@@ -2077,6 +2143,45 @@ export class SqliteClient {
}
}
+ // 3. Insert TOTP codes
+ for (const totpCode of totpCodes) {
+ const totpQuery = `
+ INSERT INTO TotpCodes (Id, Name, SecretKey, ItemId, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`;
+
+ this.executeUpdate(totpQuery, [
+ totpCode.Id || crypto.randomUUID().toUpperCase(),
+ totpCode.Name,
+ totpCode.SecretKey,
+ itemId,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
+ }
+
+ // 4. Insert attachments
+ for (const attachment of attachments) {
+ const attachmentQuery = `
+ INSERT INTO Attachments (Id, Filename, Blob, ItemId, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`;
+
+ // Convert number[] to Uint8Array if needed
+ const blobData = attachment.Blob instanceof Uint8Array
+ ? attachment.Blob
+ : new Uint8Array(attachment.Blob);
+
+ this.executeUpdate(attachmentQuery, [
+ attachment.Id || crypto.randomUUID().toUpperCase(),
+ attachment.Filename,
+ blobData,
+ itemId,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
+ }
+
await this.commitTransaction();
return itemId;
} catch (error) {
@@ -2089,9 +2194,19 @@ export class SqliteClient {
/**
* Update an existing item with field-based structure
* @param item The item object to update
+ * @param originalAttachmentIds Original attachment IDs for tracking changes
+ * @param attachments Current attachments list
+ * @param originalTotpCodeIds Original TOTP code IDs for tracking changes
+ * @param totpCodes Current TOTP codes list
* @returns The number of rows modified
*/
- public async updateItem(item: Item): Promise<number> {
+ public async updateItem(
+ item: Item,
+ originalAttachmentIds: string[] = [],
+ attachments: Attachment[] = [],
+ originalTotpCodeIds: string[] = [],
+ totpCodes: TotpCode[] = []
+ ): Promise<number> {
if (!this.db) {
throw new Error('Database not initialized');
}
@@ -2285,6 +2400,87 @@ export class SqliteClient {
}
}
+ // 6. Handle TOTP codes
+ for (const totpCode of totpCodes) {
+ const wasOriginal = originalTotpCodeIds.includes(totpCode.Id);
+
+ if (totpCode.IsDeleted) {
+ // Soft-delete existing TOTP codes
+ if (wasOriginal) {
+ const deleteTotpQuery = `
+ UPDATE TotpCodes
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE Id = ?`;
+ this.executeUpdate(deleteTotpQuery, [currentDateTime, totpCode.Id]);
+ }
+ } else if (wasOriginal) {
+ // Update existing TOTP code
+ const updateTotpQuery = `
+ UPDATE TotpCodes
+ SET Name = ?,
+ SecretKey = ?,
+ UpdatedAt = ?
+ WHERE Id = ?`;
+ this.executeUpdate(updateTotpQuery, [
+ totpCode.Name,
+ totpCode.SecretKey,
+ currentDateTime,
+ totpCode.Id
+ ]);
+ } else {
+ // Insert new TOTP code
+ const insertTotpQuery = `
+ INSERT INTO TotpCodes (Id, Name, SecretKey, ItemId, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`;
+ this.executeUpdate(insertTotpQuery, [
+ totpCode.Id || crypto.randomUUID().toUpperCase(),
+ totpCode.Name,
+ totpCode.SecretKey,
+ item.Id,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
+ }
+ }
+
+ // 7. Handle attachments
+ for (const attachment of attachments) {
+ const wasOriginal = originalAttachmentIds.includes(attachment.Id);
+
+ if (attachment.IsDeleted) {
+ // Soft-delete existing attachments
+ if (wasOriginal) {
+ const deleteAttachmentQuery = `
+ UPDATE Attachments
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE Id = ?`;
+ this.executeUpdate(deleteAttachmentQuery, [currentDateTime, attachment.Id]);
+ }
+ } else if (!wasOriginal) {
+ // Insert new attachment
+ const blobData = attachment.Blob instanceof Uint8Array
+ ? attachment.Blob
+ : new Uint8Array(attachment.Blob);
+
+ const insertAttachmentQuery = `
+ INSERT INTO Attachments (Id, Filename, Blob, ItemId, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`;
+ this.executeUpdate(insertAttachmentQuery, [
+ attachment.Id || crypto.randomUUID().toUpperCase(),
+ attachment.Filename,
+ blobData,
+ item.Id,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
+ }
+ // Note: Existing attachments are not updated (blob data doesn't change)
+ }
+
await this.commitTransaction();
return 1;
} catch (error) {