Skip to content

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

Add chrome background service worker and vault persist (#541)

Leendert de Borst51fb01aaf901
diff --git a/browser-extensions/chrome/manifest.json b/browser-extensions/chrome/manifest.json
index 5df6ad22a..f0319dbc1 100644
--- a/browser-extensions/chrome/manifest.json
+++ b/browser-extensions/chrome/manifest.json
@@ -13,5 +13,12 @@
"128": "images/icon-128.png",
"192": "images/icon-192.png",
"512": "images/icon-512.png"
- }
+ },
+ "background": {
+ "service_worker": "src/background.ts",
+ "type": "module"
+ },
+ "permissions": [
+ "storage"
+ ]
}
\ No newline at end of file
diff --git a/browser-extensions/chrome/src/background.ts b/browser-extensions/chrome/src/background.ts
new file mode 100644
index 000000000..4267649ad
--- /dev/null
+++ b/browser-extensions/chrome/src/background.ts
@@ -0,0 +1,95 @@
+import { Buffer } from 'buffer';
+import EncryptionUtility from './utilities/EncryptionUtility';
+
+console.log('Background script initialized');
+
+let vaultState: {
+ decryptedVault: any | null;
+ sessionKey: string | null;
+} = {
+ decryptedVault: null,
+ sessionKey: null
+};
+
+// Listen for messages from popup
+chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
+ console.log('Received message:', message.type);
+ switch (message.type) {
+ case 'STORE_VAULT':
+ // Generate random session key
+ const sessionKey = crypto.getRandomValues(new Uint8Array(32));
+ vaultState.sessionKey = Buffer.from(sessionKey).toString('base64');
+
+ console.log('Session key for encryption:', vaultState.sessionKey);
+ console.log('Vault data being encrypted:', message.vault);
+
+ // Re-encrypt vault with session key
+ (async () => {
+ try {
+ const encryptedVault = await EncryptionUtility.symmetricEncrypt(
+ JSON.stringify(message.vault),
+ vaultState.sessionKey
+ );
+
+ console.log('Encrypted vault (after encryption):', encryptedVault);
+
+ // Store in chrome.storage.session and wait for completion
+ chrome.storage.session.set({ encryptedVault }, () => {
+ if (chrome.runtime.lastError) {
+ console.error('Failed to store vault:', chrome.runtime.lastError);
+ sendResponse({ success: false, error: 'Failed to store vault' });
+ } else {
+ sendResponse({ success: true });
+ }
+ });
+ } catch (error) {
+ console.error('Encryption failed:', error);
+ sendResponse({ success: false, error: 'Encryption failed' });
+ }
+ })();
+ break;
+
+ case 'GET_VAULT':
+ if (!vaultState.sessionKey) {
+ console.log('No session key available');
+ sendResponse({ vault: null });
+ return;
+ }
+
+ chrome.storage.session.get(['encryptedVault'], async (result) => {
+ try {
+ if (!result.encryptedVault) {
+ console.log('No encrypted vault found in storage');
+ sendResponse({ vault: null });
+ return;
+ }
+
+ // Decrypt vault with session key
+ const decryptedVault = await EncryptionUtility.symmetricDecrypt(
+ result.encryptedVault,
+ vaultState.sessionKey!
+ );
+
+ // Parse the decrypted vault and send response
+ try {
+ const parsedVault = JSON.parse(decryptedVault);
+ sendResponse({ vault: parsedVault });
+ } catch (parseError) {
+ console.error('Failed to parse decrypted vault:', parseError);
+ sendResponse({ vault: null, error: 'Failed to parse decrypted vault' });
+ }
+ } catch (decryptError) {
+ console.error('Failed to decrypt vault:', decryptError);
+ sendResponse({ vault: null, error: 'Failed to decrypt vault' });
+ }
+ });
+ break;
+
+ case 'CLEAR_VAULT':
+ vaultState.sessionKey = null;
+ chrome.storage.session.remove(['encryptedVault']);
+ sendResponse({ success: true });
+ break;
+ }
+ return true;
+});
\ No newline at end of file
diff --git a/browser-extensions/chrome/src/components/AppContent.tsx b/browser-extensions/chrome/src/components/AppContent.tsx
index b38657d6c..0d041a629 100644
--- a/browser-extensions/chrome/src/components/AppContent.tsx
+++ b/browser-extensions/chrome/src/components/AppContent.tsx
@@ -16,14 +16,21 @@ const AppContent: React.FC = () => {
const { isLoggedIn, username, logout } = useAuth();
const dbContext = useDb();
const [credentials, setCredentials] = useState<Credential[]>([]);
- const [needsUnlock, setNeedsUnlock] = useState(true);
+ const [needsUnlock, setNeedsUnlock] = useState(false);
useEffect(() => {
- if (isLoggedIn && dbContext?.isInitialized) {
- setNeedsUnlock(false);
- loadCredentials();
+ if (isLoggedIn) {
+ console.log('isLoggedIn is true');
+ if (!dbContext.isInitialized) {
+ console.log('Database is not initialized, setting needsUnlock to true');
+ setNeedsUnlock(true);
+ } else {
+ console.log('Database is initialized, setting needsUnlock to false');
+ setNeedsUnlock(false);
+ loadCredentials();
+ }
}
- }, [isLoggedIn, dbContext?.isInitialized]);
+ }, [isLoggedIn, dbContext.isInitialized]);
const loadCredentials = () => {
if (!dbContext?.sqliteClient) return;
@@ -54,31 +61,31 @@ const AppContent: React.FC = () => {
};
return (
- <div className="min-h-screen bg-blue-500 items-center justify-center p-4">
- <h1 className="text-white text-2xl mb-8">AliasVault</h1>
+ <div className="min-h-screen min-w-[350px] bg-white dark:bg-gray-800 items-center justify-center p-4">
+ <h1 className="text-gray-900 dark:text-white text-2xl mb-8">AliasVault</h1>
{isLoggedIn ? (
<div className="mt-4">
- <p className="text-white text-lg mb-4">Logged in as {username}</p>
+ <p className="text-gray-700 dark:text-gray-200 text-lg mb-4">Logged in as {username}</p>
{needsUnlock ? (
<Unlock />
) : (
<div>
- <div className="bg-white rounded-lg p-4 mb-4">
- <h2 className="text-xl mb-4">Your Credentials</h2>
+ <div className="bg-white dark:bg-gray-700 rounded-lg p-4 mb-4 shadow-lg">
+ <h2 className="text-gray-900 dark:text-white text-xl mb-4">Your Credentials</h2>
{credentials.length === 0 ? (
- <p className="text-gray-500">No credentials found</p>
+ <p className="text-gray-500 dark:text-gray-400">No credentials found</p>
) : (
<ul className="space-y-2">
{credentials.map(cred => (
- <li key={cred.Id} className="p-2 border rounded flex items-center">
+ <li key={cred.Id} className="p-2 border dark:border-gray-600 rounded flex items-center bg-gray-50 dark:bg-gray-800">
<img
src={cred.Logo ? `data:image/png;base64,${cred.Logo}` : '/images/service-placeholder.webp'}
alt={cred.ServiceName}
className="w-8 h-8 mr-2 flex-shrink-0"
/>
<div>
- <p className="font-medium">{cred.ServiceName}</p>
- <p className="text-sm text-gray-600">{cred.Username}</p>
+ <p className="font-medium text-gray-900 dark:text-white">{cred.ServiceName}</p>
+ <p className="text-sm text-gray-600 dark:text-gray-400">{cred.Username}</p>
</div>
</li>
))}
diff --git a/browser-extensions/chrome/src/components/Button.tsx b/browser-extensions/chrome/src/components/Button.tsx
index c36c4659f..8b6a6c6b0 100644
--- a/browser-extensions/chrome/src/components/Button.tsx
+++ b/browser-extensions/chrome/src/components/Button.tsx
@@ -8,7 +8,7 @@ interface ButtonProps {
const Button: React.FC<ButtonProps> = ({ onClick, children }) => {
return (
<button
- className="bg-white text-blue-500 px-4 py-2 rounded hover:bg-blue-100 transition-colors"
+ className="bg-primary-500 hover:bg-primary-600 text-white font-medium rounded-lg px-4 py-2 text-sm"
onClick={onClick}
>
{children}
diff --git a/browser-extensions/chrome/src/components/Login.tsx b/browser-extensions/chrome/src/components/Login.tsx
index 12b53313d..e4caef557 100644
--- a/browser-extensions/chrome/src/components/Login.tsx
+++ b/browser-extensions/chrome/src/components/Login.tsx
@@ -105,18 +105,18 @@ const Login: React.FC = () => {
return (
<div className="max-w-md">
- <form onSubmit={handleSubmit} className="bg-white w-full shadow-md rounded px-8 pt-6 pb-8 mb-4">
+ <form onSubmit={handleSubmit} className="bg-white dark:bg-gray-700 w-full shadow-md rounded px-8 pt-6 pb-8 mb-4">
{error && (
- <div className="mb-4 text-red-500 text-sm">
+ <div className="mb-4 text-red-500 dark:text-red-400 text-sm">
{error}
</div>
)}
<div className="mb-4">
- <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="username">
+ <label className="block text-gray-700 dark:text-gray-200 text-sm font-bold mb-2" htmlFor="username">
Username
</label>
<input
- className="shadow appearance-none border rounded py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
+ className="shadow appearance-none border rounded py-2 px-3 text-gray-700 dark:text-gray-200 dark:bg-gray-800 dark:border-gray-600 leading-tight focus:outline-none focus:shadow-outline"
id="username"
type="text"
name="username"
@@ -127,11 +127,11 @@ const Login: React.FC = () => {
/>
</div>
<div className="mb-6">
- <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="password">
+ <label className="block text-gray-700 dark:text-gray-200 text-sm font-bold mb-2" htmlFor="password">
Password
</label>
<input
- className="shadow appearance-none border rounded py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
+ className="shadow appearance-none border rounded py-2 px-3 text-gray-700 dark:text-gray-200 dark:bg-gray-800 dark:border-gray-600 mb-3 leading-tight focus:outline-none focus:shadow-outline"
id="password"
type="password"
name="password"
@@ -149,7 +149,7 @@ const Login: React.FC = () => {
onChange={(e) => setRememberMe(e.target.checked)}
className="mr-2"
/>
- <span className="text-sm">Remember me</span>
+ <span className="text-sm text-gray-700 dark:text-gray-200">Remember me</span>
</label>
<Button type="submit">
Login
diff --git a/browser-extensions/chrome/src/components/Unlock.tsx b/browser-extensions/chrome/src/components/Unlock.tsx
index 7d7116f2c..85217e8e8 100644
--- a/browser-extensions/chrome/src/components/Unlock.tsx
+++ b/browser-extensions/chrome/src/components/Unlock.tsx
@@ -60,28 +60,28 @@ const Unlock: React.FC = () => {
return (
<div className="max-w-md">
- <form onSubmit={handleSubmit} className="bg-white w-full shadow-md rounded px-8 pt-6 pb-8 mb-4">
+ <form onSubmit={handleSubmit} className="bg-white dark:bg-gray-700 w-full shadow-md rounded px-8 pt-6 pb-8 mb-4">
<div className="flex space-x-4 mb-6">
<img className="w-8 h-8 rounded-full" src="/images/avatar.webp" alt="User avatar" />
- <h2 className="text-2xl font-bold text-gray-900">{username}</h2>
+ <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{username}</h2>
</div>
- <p className="text-base text-gray-500 mb-6">
+ <p className="text-base text-gray-500 dark:text-gray-200 mb-6">
Enter your master password to unlock your database.
</p>
{error && (
- <div className="mb-4 text-red-500 text-sm">
+ <div className="mb-4 text-red-500 dark:text-red-400 text-sm">
{error}
</div>
)}
<div className="mb-6">
- <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="password">
+ <label className="block text-gray-700 dark:text-gray-200 text-sm font-bold mb-2" htmlFor="password">
Password
</label>
<input
- className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
+ className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 dark:text-gray-200 dark:bg-gray-800 dark:border-gray-600 mb-3 leading-tight focus:outline-none focus:shadow-outline"
id="password"
type="password"
value={password}
@@ -95,8 +95,8 @@ const Unlock: React.FC = () => {
Unlock
</Button>
- <div className="text-sm font-medium text-gray-500 mt-6">
- Switch accounts? <a href="#" onClick={handleLogout} className="text-primary-700 hover:underline">Log out</a>
+ <div className="text-sm font-medium text-gray-500 dark:text-gray-200 mt-6">
+ Switch accounts? <a href="#" onClick={handleLogout} className="text-primary-700 hover:underline dark:text-primary-500">Log out</a>
</div>
</form>
</div>
diff --git a/browser-extensions/chrome/src/context/DbContext.tsx b/browser-extensions/chrome/src/context/DbContext.tsx
index 911ad3412..448802eb8 100644
--- a/browser-extensions/chrome/src/context/DbContext.tsx
+++ b/browser-extensions/chrome/src/context/DbContext.tsx
@@ -1,11 +1,11 @@
-import React, { createContext, useContext, useState } from 'react';
+import React, { createContext, useContext, useState, useEffect } from 'react';
import SqliteClient from '../utilities/SqliteClient';
interface DbContextType {
sqliteClient: SqliteClient | null;
- initializeDatabase: (base64Data: string) => Promise<void>;
- clearDatabase: () => void;
isInitialized: boolean;
+ initializeDatabase: (blob: string) => Promise<void>;
+ clearDatabase: () => void;
}
const DbContext = createContext<DbContextType | undefined>(undefined);
@@ -14,34 +14,63 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
const [sqliteClient, setSqliteClient] = useState<SqliteClient | null>(null);
const [isInitialized, setIsInitialized] = useState(false);
- const initializeDatabase = async (base64Data: string) => {
+ const checkStoredVault = async () => {
+ console.log('Checking for stored vault');
try {
- const client = new SqliteClient();
- await client.initializeFromBase64(base64Data);
- setSqliteClient(client);
- setIsInitialized(true);
+ const response = await chrome.runtime.sendMessage({ type: 'GET_VAULT' });
+ if (response && response.vault) {
+ console.log('Found stored vault');
+ await initializeDatabase(response.vault);
+ }
} catch (error) {
- console.error('Failed to initialize SQLite database:', error);
- clearDatabase();
- throw error;
+ console.log('No stored vault found');
+ console.error('Error retrieving vault from background:', error);
}
};
- const clearDatabase = () => {
- if (sqliteClient) {
- sqliteClient.close();
+ useEffect(() => {
+ // Check if database is initialized and try to retrieve vault from background
+ console.log('Checking if database is initialized');
+ if (!isInitialized) {
+ checkStoredVault();
}
+ }, [isInitialized]);
+
+ // Add a listener for when the popup becomes visible
+ useEffect(() => {
+ const handleVisibilityChange = () => {
+ if (document.visibilityState === 'visible' && !isInitialized) {
+ checkStoredVault();
+ }
+ };
+
+ document.addEventListener('visibilitychange', handleVisibilityChange);
+ return () => {
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
+ };
+ }, [isInitialized]);
+
+ const initializeDatabase = async (blob: string) => {
+ const client = new SqliteClient();
+ await client.initializeFromBase64(blob);
+ setSqliteClient(client);
+ setIsInitialized(true);
+
+ // Store in background worker
+ chrome.runtime.sendMessage({
+ type: 'STORE_VAULT',
+ vault: blob
+ });
+ };
+
+ const clearDatabase = () => {
setSqliteClient(null);
setIsInitialized(false);
+ chrome.runtime.sendMessage({ type: 'CLEAR_VAULT' });
};
return (
- <DbContext.Provider value={{
- sqliteClient,
- initializeDatabase,
- clearDatabase,
- isInitialized
- }}>
+ <DbContext.Provider value={{ sqliteClient, isInitialized, initializeDatabase, clearDatabase }}>
{children}
</DbContext.Provider>
);
diff --git a/browser-extensions/chrome/src/manifest.json b/browser-extensions/chrome/src/manifest.json
index 079a5c348..4d2148821 100644
--- a/browser-extensions/chrome/src/manifest.json
+++ b/browser-extensions/chrome/src/manifest.json
@@ -1,6 +1,6 @@
{
"name": "AliasVault",
- "description": "AliasVault Chrome Extension which allows you to generate and manage aliases directly in your browser on signup and login forms.",
+ "description": "AliasVault Chrome Extension",
"version": "1.0",
"manifest_version": 3,
"content_security_policy": {
@@ -16,5 +16,12 @@
"128": "images/icon-128.png",
"192": "images/icon-192.png",
"512": "images/icon-512.png"
- }
+ },
+ "background": {
+ "service_worker": "background.js",
+ "type": "module"
+ },
+ "permissions": [
+ "storage"
+ ]
}
\ No newline at end of file
diff --git a/browser-extensions/chrome/vite.config.js b/browser-extensions/chrome/vite.config.js
index c9281bc66..67f615828 100644
--- a/browser-extensions/chrome/vite.config.js
+++ b/browser-extensions/chrome/vite.config.js
@@ -19,7 +19,7 @@ export default defineConfig({
},
{
src: 'node_modules/argon2-browser/dist/argon2.wasm',
- dest: 'src' // Copy to the root of the dist folder
+ dest: 'src'
}
]
}),
@@ -41,7 +41,12 @@ export default defineConfig({
rollupOptions: {
input: {
popup: './src/popup.html',
+ background: './src/background.ts'
},
+ output: {
+ entryFileNames: '[name].js',
+ format: 'es'
+ }
},
outDir: 'dist',
},