Skip to content

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

Add edit page scaffolding (#900)

Leendert de Borst19499f02d68d
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 1f0490d15..8470f65f3 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -11,6 +11,7 @@ import { StringResponse as stringResponse } from '@/utils/types/messaging/String
import { VaultResponse as messageVaultResponse } from '@/utils/types/messaging/VaultResponse';
import { VaultUploadResponse as messageVaultUploadResponse } from '@/utils/types/messaging/VaultUploadResponse';
import { WebApiService } from '@/utils/WebApiService';
+import { StoreVaultRequest } from '@/utils/types/messaging/StoreVaultRequest';
/**
* Check if the user is logged in and if the vault is locked.
@@ -33,20 +34,33 @@ export async function handleCheckAuthStatus() : Promise<{ isLoggedIn: boolean, i
* Store the vault in browser storage.
*/
export async function handleStoreVault(
- message: any,
+ message: StoreVaultRequest,
) : Promise<messageBoolResponse> {
try {
- const vaultResponse = message.vaultResponse as VaultResponse;
- const encryptedVaultBlob = vaultResponse.vault.blob;
+ // Store new encrypted vault in session storage.
+ await storage.setItem('session:encryptedVault', message.vaultBlob);
- // Store encrypted vault and derived key in session storage.
- await storage.setItems([
- { key: 'session:encryptedVault', value: encryptedVaultBlob },
- { key: 'session:derivedKey', value: message.derivedKey },
- { key: 'session:publicEmailDomains', value: vaultResponse.vault.publicEmailDomainList },
- { key: 'session:privateEmailDomains', value: vaultResponse.vault.privateEmailDomainList },
- { key: 'session:vaultRevisionNumber', value: vaultResponse.vault.currentRevisionNumber }
- ]);
+ /*
+ * For all other values, check if they have a value and store them in session storage if they do.
+ * Some updates, e.g. when mutating local database, these values will not be set.
+ */
+
+ // Store derived key in session storage (if it has a value)
+ if (message.derivedKey) {
+ await storage.setItem('session:derivedKey', message.derivedKey);
+ }
+
+ if (message.publicEmailDomainList) {
+ await storage.setItem('session:publicEmailDomains', message.publicEmailDomainList);
+ }
+
+ if (message.privateEmailDomainList) {
+ await storage.setItem('session:privateEmailDomains', message.privateEmailDomainList);
+ }
+
+ if (message.vaultRevisionNumber) {
+ await storage.setItem('session:vaultRevisionNumber', message.vaultRevisionNumber);
+ }
return { success: true };
} catch (error) {
diff --git a/apps/browser-extension/src/entrypoints/popup/App.tsx b/apps/browser-extension/src/entrypoints/popup/App.tsx
index a9b011afa..1962e3312 100644
--- a/apps/browser-extension/src/entrypoints/popup/App.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/App.tsx
@@ -9,6 +9,7 @@ import { useAuth } from '@/entrypoints/popup/context/AuthContext';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import AuthSettings from '@/entrypoints/popup/pages/AuthSettings';
import CredentialDetails from '@/entrypoints/popup/pages/CredentialDetails';
+import CredentialEdit from '@/entrypoints/popup/pages/CredentialEdit';
import CredentialsList from '@/entrypoints/popup/pages/CredentialsList';
import EmailDetails from '@/entrypoints/popup/pages/EmailDetails';
import EmailsList from '@/entrypoints/popup/pages/EmailsList';
@@ -44,6 +45,7 @@ const App: React.FC = () => {
{ path: '/auth-settings', element: <AuthSettings />, showBackButton: true, title: 'Settings' },
{ path: '/credentials', element: <CredentialsList />, showBackButton: false },
{ path: '/credentials/:id', element: <CredentialDetails />, showBackButton: true, title: 'Credential details' },
+ { path: '/credentials/:id/edit', element: <CredentialEdit />, showBackButton: true, title: 'Edit credential' },
{ path: '/emails', element: <EmailsList />, showBackButton: false },
{ path: '/emails/:id', element: <EmailDetails />, showBackButton: true, title: 'Email details' },
{ path: '/settings', element: <Settings />, showBackButton: false },
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index 765c730a0..0d40963f9 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -6,6 +6,7 @@ import type { VaultMetadata } from '@/utils/shared/models/metadata';
import type { VaultResponse } from '@/utils/shared/models/webapi';
import SqliteClient from '@/utils/SqliteClient';
import type { VaultResponse as messageVaultResponse } from '@/utils/types/messaging/VaultResponse';
+import { StoreVaultRequest } from '@/utils/types/messaging/StoreVaultRequest';
type DbContextType = {
sqliteClient: SqliteClient | null;
@@ -63,13 +64,18 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
vaultRevisionNumber: vaultResponse.vault.currentRevisionNumber,
});
- /*
+ /**
* Store encrypted vault in background worker.
*/
- sendMessage('STORE_VAULT', {
+ const request: StoreVaultRequest = {
+ vaultBlob: vaultResponse.vault.blob,
derivedKey: derivedKey,
- vaultResponse: vaultResponse,
- }, 'background');
+ publicEmailDomainList: vaultResponse.vault.publicEmailDomainList,
+ privateEmailDomainList: vaultResponse.vault.privateEmailDomainList,
+ vaultRevisionNumber: vaultResponse.vault.currentRevisionNumber,
+ };
+
+ await sendMessage('STORE_VAULT', request, 'background');
}, []);
const checkStoredVault = useCallback(async () => {
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
index 54f9b2800..b21059238 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
@@ -41,6 +41,7 @@ export function useVaultMutate() : {
try {
// Trigger the background worker to upload the current vault to the server
const response = await sendMessage('UPLOAD_VAULT', {}, 'background') as messageVaultUploadResponse;
+ console.log('Vault upload response:', response);
/*
* If we get here, it means we have a valid connection to the server.
@@ -49,6 +50,7 @@ export function useVaultMutate() : {
*/
if (response.status === 0 && response.newRevisionNumber) {
+ console.log('Vault upload successful, setting revision number:', response.newRevisionNumber);
await dbContext.setCurrentVaultRevisionNumber(response.newRevisionNumber);
options.onSuccess?.();
} else if (response.status === 1) {
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/CredentialDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/CredentialDetails.tsx
index 25cf32b31..4fd22bdcd 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/CredentialDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/CredentialDetails.tsx
@@ -50,6 +50,13 @@ const CredentialDetails: React.FC = () => {
window.close();
};
+ /**
+ * Navigate to the edit page for this credential.
+ */
+ const handleEdit = (): void => {
+ navigate(`/credentials/${id}/edit`);
+ };
+
useEffect(() => {
if (isPopup()) {
window.history.replaceState({}, '', `popup.html#/credentials`);
@@ -80,7 +87,15 @@ const CredentialDetails: React.FC = () => {
return (
<div className="space-y-4">
- <HeaderBlock credential={credential} onOpenNewPopup={openInNewPopup} />
+ <div className="flex justify-between items-center px-4">
+ <HeaderBlock credential={credential} onOpenNewPopup={openInNewPopup} />
+ <button
+ onClick={handleEdit}
+ className="text-blue-500 hover:text-blue-700"
+ >
+ Edit
+ </button>
+ </div>
{credential.Alias?.Email && (
<EmailBlock
email={credential.Alias.Email}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/CredentialEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/CredentialEdit.tsx
new file mode 100644
index 000000000..bd01bc267
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/pages/CredentialEdit.tsx
@@ -0,0 +1,153 @@
+import React, { useState, useEffect } from 'react';
+import { useNavigate, useParams } from 'react-router-dom';
+
+import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
+import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
+
+import type { Credential } from '@/utils/shared/models/vault';
+
+/**
+ * Credential edit page.
+ */
+const CredentialEdit: React.FC = () => {
+ const { id } = useParams();
+ const navigate = useNavigate();
+ const dbContext = useDb();
+ const [credential, setCredential] = useState<Credential | null>(null);
+ const { setIsInitialLoading } = useLoading();
+ const { executeVaultMutation, isLoading, syncStatus } = useVaultMutate();
+
+ useEffect(() => {
+ if (!dbContext?.sqliteClient || !id) {
+ return;
+ }
+
+ try {
+ const result = dbContext.sqliteClient.getCredentialById(id);
+ if (result) {
+ setCredential(result);
+ setIsInitialLoading(false);
+ } else {
+ console.error('Credential not found');
+ navigate('/credentials');
+ }
+ } catch (err) {
+ console.error('Error loading credential:', err);
+ }
+ }, [dbContext.sqliteClient, id, navigate, setIsInitialLoading]);
+
+ /**
+ * Handle the delete button click.
+ * @returns {Promise<void>}
+ */
+ const handleDelete = async (): Promise<void> => {
+ if (!id || !window.confirm('Are you sure you want to delete this credential? This action cannot be undone.')) {
+ return;
+ }
+
+ /**
+ * Execute the vault mutation to delete the credential.
+ */
+ executeVaultMutation(async () => {
+ /**
+ * Delete the credential from the database.
+ */
+ dbContext.sqliteClient!.deleteCredentialById(id);
+ }, {
+ /**
+ * Navigate back to the credentials list on success.
+ */
+ onSuccess: () => {
+ navigate('/credentials');
+ }
+ });
+ };
+
+ if (!credential) {
+ return <div>Loading...</div>;
+ }
+
+ return (
+ <div className="space-y-4 p-4">
+ <div className="flex justify-between items-center">
+ <h1 className="text-xl font-bold">Edit Credential</h1>
+ <button
+ onClick={() => navigate(`/credentials/${id}`)}
+ className="text-blue-500 hover:text-blue-700"
+ >
+ Cancel
+ </button>
+ </div>
+
+ {isLoading && (
+ <div className="text-sm text-gray-500">
+ {syncStatus}
+ </div>
+ )}
+
+ <div className="space-y-4">
+ <div>
+ <label className="block text-sm font-medium text-gray-700">Service Name</label>
+ <input
+ type="text"
+ value={credential.ServiceName}
+ onChange={(e) => setCredential({ ...credential, ServiceName: e.target.value })}
+ className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm font-medium text-gray-700">Service URL</label>
+ <input
+ type="text"
+ value={credential.ServiceUrl}
+ onChange={(e) => setCredential({ ...credential, ServiceUrl: e.target.value })}
+ className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm font-medium text-gray-700">Username</label>
+ <input
+ type="text"
+ value={credential.Username}
+ onChange={(e) => setCredential({ ...credential, Username: e.target.value })}
+ className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm font-medium text-gray-700">Password</label>
+ <input
+ type="password"
+ value={credential.Password}
+ onChange={(e) => setCredential({ ...credential, Password: e.target.value })}
+ className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm font-medium text-gray-700">Notes</label>
+ <textarea
+ value={credential.Notes}
+ onChange={(e) => setCredential({ ...credential, Notes: e.target.value })}
+ rows={4}
+ className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
+ />
+ </div>
+
+ <div className="pt-4">
+ <button
+ onClick={handleDelete}
+ className="w-full bg-red-500 text-white py-2 px-4 rounded hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
+ >
+ Delete Credential
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default CredentialEdit;
\ No newline at end of file
diff --git a/apps/browser-extension/src/utils/SqliteClient.ts b/apps/browser-extension/src/utils/SqliteClient.ts
index 03b702a39..b0d5253a8 100644
--- a/apps/browser-extension/src/utils/SqliteClient.ts
+++ b/apps/browser-extension/src/utils/SqliteClient.ts
@@ -1,6 +1,8 @@
import initSqlJs, { Database } from 'sql.js';
+import { sendMessage } from 'webext-bridge/popup';
import type { Credential, EncryptionKey, PasswordSettings, TotpCode } from '@/utils/shared/models/vault';
+import { StoreVaultRequest } from './types/messaging/StoreVaultRequest';
/**
* Placeholder base64 image for credentials without a logo.
@@ -12,6 +14,7 @@ const placeholderBase64 = 'UklGRjoEAABXRUJQVlA4IC4EAAAwFwCdASqAAIAAPpFCm0olo6Ihp
*/
export class SqliteClient {
private db: Database | null = null;
+ private isInTransaction: boolean = false;
/**
* Initialize the SQLite database from a base64 string
@@ -43,6 +46,81 @@ export class SqliteClient {
}
}
+ /**
+ * Begin a new transaction
+ */
+ public beginTransaction(): void {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
+
+ if (this.isInTransaction) {
+ throw new Error('Transaction already in progress');
+ }
+
+ try {
+ this.db.run('BEGIN TRANSACTION');
+ this.isInTransaction = true;
+ } catch (error) {
+ console.error('Error beginning transaction:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * Commit the current transaction and persist changes to the vault
+ */
+ public async commitTransaction(): Promise<void> {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
+
+ if (!this.isInTransaction) {
+ throw new Error('No transaction in progress');
+ }
+
+ try {
+ this.db.run('COMMIT');
+ this.isInTransaction = false;
+
+ // Export the current database state and store it in the background worker
+ const updatedVaultBlob = this.exportToBase64();
+
+ /**
+ * Store encrypted vault in background worker.
+ */
+ const request: StoreVaultRequest = {
+ vaultBlob: updatedVaultBlob,
+ };
+
+ await sendMessage('STORE_VAULT', request, 'background');
+ } catch (error) {
+ console.error('Error committing transaction:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * Rollback the current transaction
+ */
+ public rollbackTransaction(): void {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
+
+ if (!this.isInTransaction) {
+ throw new Error('No transaction in progress');
+ }
+
+ try {
+ this.db.run('ROLLBACK');
+ this.isInTransaction = false;
+ } catch (error) {
+ console.error('Error rolling back transaction:', error);
+ throw error;
+ }
+ }
+
/**
* Export the SQLite database to a base64 string
* @returns Base64 encoded string of the database
@@ -321,13 +399,13 @@ export class SqliteClient {
* @param credential The credential object to insert
* @returns The number of rows modified
*/
- public createCredential(credential: Credential): number {
+ public async createCredential(credential: Credential): Promise<number> {
if (!this.db) {
throw new Error('Database not initialized');
}
try {
- this.db.run('BEGIN TRANSACTION');
+ this.beginTransaction();
// 1. Insert Service
let logoData = null;
@@ -415,11 +493,11 @@ export class SqliteClient {
]);
}
- this.db.run('COMMIT');
+ await this.commitTransaction();
return 1;
} catch (error) {
- this.db.run('ROLLBACK');
+ this.rollbackTransaction();
console.error('Error creating credential:', error);
throw error;
}
@@ -500,6 +578,64 @@ export class SqliteClient {
}
}
+ /**
+ * Delete a credential by ID
+ * @param credentialId - The ID of the credential to delete
+ * @returns The number of rows deleted
+ */
+ public async deleteCredentialById(credentialId: string): Promise<number> {
+ if (!this.db) {
+ throw new Error('Database not initialized');
+ }
+
+ try {
+ this.beginTransaction();
+
+ const currentDateTime = new Date().toISOString()
+ .replace('T', ' ')
+ .replace('Z', '')
+ .substring(0, 23);
+
+ // Update the credential, alias, and service to be deleted
+ const query = `
+ UPDATE Credentials
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE Id = ?`;
+
+ const aliasQuery = `
+ UPDATE Aliases
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE Id = (
+ SELECT AliasId
+ FROM Credentials
+ WHERE Id = ?
+ )`;
+
+ const serviceQuery = `
+ UPDATE Services
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE Id = (
+ SELECT ServiceId
+ FROM Credentials
+ WHERE Id = ?
+ )`;
+
+ const results = this.executeUpdate(query, [currentDateTime, credentialId]);
+ this.executeUpdate(aliasQuery, [currentDateTime, credentialId]);
+ this.executeUpdate(serviceQuery, [currentDateTime, credentialId]);
+
+ await this.commitTransaction();
+ return results;
+ } catch (error) {
+ this.rollbackTransaction();
+ console.error('Error deleting credential:', error);
+ throw error;
+ }
+ }
+
/**
* Convert binary data to a base64 encoded image source.
*/
diff --git a/apps/browser-extension/src/utils/types/messaging/StoreVaultRequest.ts b/apps/browser-extension/src/utils/types/messaging/StoreVaultRequest.ts
new file mode 100644
index 000000000..c3225b6e9
--- /dev/null
+++ b/apps/browser-extension/src/utils/types/messaging/StoreVaultRequest.ts
@@ -0,0 +1,7 @@
+export type StoreVaultRequest = {
+ vaultBlob: string;
+ derivedKey?: string;
+ publicEmailDomainList?: string[];
+ privateEmailDomainList?: string[];
+ vaultRevisionNumber?: number;
+}