Skip to content

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

Add contentscript for autofill popup (#541)

Leendert de Borst4c5517ae94ee
diff --git a/browser-extensions/chrome/manifest.json b/browser-extensions/chrome/manifest.json
index f0319dbc1..c521cf91d 100644
--- a/browser-extensions/chrome/manifest.json
+++ b/browser-extensions/chrome/manifest.json
@@ -19,6 +19,22 @@
"type": "module"
},
"permissions": [
- "storage"
+ "storage",
+ "activeTab"
+ ],
+ "content_scripts": [
+ {
+ "matches": ["<all_urls>"],
+ "js": ["src/contentScript.ts"],
+ "css": ["src/contentScript.css"]
+ }
+ ],
+ "web_accessible_resources": [{
+ "resources": ["images/*"],
+ "matches": ["<all_urls>"],
+ "use_dynamic_url": true
+ }],
+ "host_permissions": [
+ "<all_urls>"
]
}
\ No newline at end of file
diff --git a/browser-extensions/chrome/package.json b/browser-extensions/chrome/package.json
index 8c5b281df..69e75d09e 100644
--- a/browser-extensions/chrome/package.json
+++ b/browser-extensions/chrome/package.json
@@ -4,9 +4,10 @@
"main": "index.tsx",
"scripts": {
"dev": "vite",
- "build": "vite build",
+ "build": "vite build && npm run build:content-css",
"preview": "vite preview",
- "watch": "vite build --watch"
+ "watch": "vite build --watch",
+ "build:content-css": "tailwindcss -i ./src/styles/contentScript.css -o ./dist/contentScript.css --config tailwind.content.config.js"
},
"keywords": [],
"author": "",
diff --git a/browser-extensions/chrome/src/background.ts b/browser-extensions/chrome/src/background.ts
index 4267649ad..b125ba473 100644
--- a/browser-extensions/chrome/src/background.ts
+++ b/browser-extensions/chrome/src/background.ts
@@ -1,5 +1,6 @@
import { Buffer } from 'buffer';
import EncryptionUtility from './utilities/EncryptionUtility';
+import SqliteClient from './utilities/SqliteClient';
console.log('Background script initialized');
@@ -27,8 +28,8 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
(async () => {
try {
const encryptedVault = await EncryptionUtility.symmetricEncrypt(
- JSON.stringify(message.vault),
- vaultState.sessionKey
+ message.vault,
+ vaultState.sessionKey!
);
console.log('Encrypted vault (after encryption):', encryptedVault);
@@ -90,6 +91,74 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
chrome.storage.session.remove(['encryptedVault']);
sendResponse({ success: true });
break;
+
+ case 'GET_CREDENTIALS_FOR_URL':
+ console.log('GET_CREDENTIALS_FOR_URL called');
+ if (!vaultState.sessionKey) {
+ sendResponse({ credentials: [] });
+ return;
+ }
+ console.log('sessionKey:', vaultState.sessionKey);
+
+ chrome.storage.session.get(['encryptedVault'], async (result) => {
+ try {
+ if (!result.encryptedVault) {
+ sendResponse({ credentials: [] });
+ return;
+ }
+ console.log('encryptedVault:', result.encryptedVault);
+
+ const decryptedVault = await EncryptionUtility.symmetricDecrypt(
+ result.encryptedVault,
+ vaultState.sessionKey!
+ );
+ console.log('decryptedVault:', decryptedVault);
+ const url = new URL(message.url);
+
+ // Initialize SQLite client
+ const sqliteClient = new SqliteClient();
+ await sqliteClient.initializeFromBase64(decryptedVault);
+
+ // Query credentials with their related service information
+ const credentials = sqliteClient.executeQuery(`
+ SELECT
+ c.Id,
+ c.Username,
+ c.ServiceId,
+ s.Name as ServiceName,
+ s.Url as ServiceUrl,
+ s.Logo as Logo,
+ MAX(p.Value) as Password
+ FROM Credentials c
+ JOIN Services s ON s.Id = c.ServiceId
+ LEFT JOIN Passwords p ON p.CredentialId = c.Id
+ WHERE c.IsDeleted = 0
+ GROUP BY c.Id, c.Username, c.ServiceId, s.Name, s.Url, s.Logo
+ `);
+
+ console.log('credentials:', credentials);
+
+ // Filter credentials that match the current domain
+ const matchingCredentials = credentials.filter(cred => {
+ // TODO: Implement proper URL matching
+ return true;
+ /*try {
+ const credentialUrl = new URL(cred.ServiceUrl);
+ return credentialUrl.hostname === url.hostname;
+ } catch {
+ return false;
+ }*/
+ });
+
+ console.log('matchingCredentials:', matchingCredentials);
+
+ sendResponse({ credentials: matchingCredentials });
+ } catch (error) {
+ console.error('Error getting credentials:', error);
+ sendResponse({ credentials: [] });
+ }
+ });
+ break;
}
return true;
});
\ No newline at end of file
diff --git a/browser-extensions/chrome/src/contentScript.ts b/browser-extensions/chrome/src/contentScript.ts
new file mode 100644
index 000000000..f8b9070fa
--- /dev/null
+++ b/browser-extensions/chrome/src/contentScript.ts
@@ -0,0 +1,123 @@
+import { detectForms } from './utilities/FormDetector';
+
+console.log('Content script loaded!'); // This will help verify the script is running
+
+// Track active input field
+let activeInput: HTMLInputElement | null = null;
+
+// Listen for input field focus
+document.addEventListener('focusin', (e) => {
+ const target = e.target as HTMLInputElement;
+ if (target.tagName === 'INPUT') {
+ activeInput = target;
+ showCredentialPopup(target);
+ }
+});
+
+// Listen for input field blur
+document.addEventListener('focusout', (e) => {
+ activeInput = null;
+});
+
+// Create and manage credential popup
+function showCredentialPopup(input: HTMLInputElement) {
+ console.log('showCredentialPopup called');
+ const forms = detectForms();
+ if (!forms.length) return;
+
+ // Request credentials from background script
+ chrome.runtime.sendMessage({ type: 'GET_CREDENTIALS_FOR_URL', url: window.location.href }, (response) => {
+ console.log('response received:', response);
+ if (!response.credentials?.length) return;
+
+ console.log('credentials received, creating popup:');
+ createPopup(input, response.credentials);
+ });
+}
+
+function createPopup(input: HTMLInputElement, credentials: any[]) {
+ // Remove existing popup if any
+ removeExistingPopup();
+
+ const popup = document.createElement('div');
+ popup.id = 'aliasvault-credential-popup';
+ popup.style.cssText = `
+ position: absolute;
+ z-index: 999999;
+ background: white;
+ border: 1px solid #ccc;
+ border-radius: 4px;
+ box-shadow: 0 2px 4px rgba(0,0,0,0.2);
+ max-width: 300px;
+ padding: 8px 0;
+ `;
+
+ // Position popup below input
+ const rect = input.getBoundingClientRect();
+ popup.style.top = `${rect.bottom + window.scrollY + 2}px`;
+ popup.style.left = `${rect.left + window.scrollX}px`;
+
+ // Add credentials to popup
+ credentials.forEach(cred => {
+ const item = document.createElement('div');
+ item.style.cssText = `
+ padding: 8px 16px;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ `;
+
+ // Use chrome.runtime.getURL for the fallback image
+ const placeholderImage = chrome.runtime.getURL('images/service-placeholder.webp');
+ console.log('placeholderImage:', placeholderImage);
+ item.innerHTML = `
+ <img src="${cred.Logo || placeholderImage}" style="width: 16px; height: 16px;">
+ <span>${cred.Username}</span>
+ `;
+
+ item.addEventListener('click', () => {
+ fillCredential(cred);
+ removeExistingPopup();
+ });
+
+ item.addEventListener('mouseenter', () => {
+ item.style.backgroundColor = '#f0f0f0';
+ });
+
+ item.addEventListener('mouseleave', () => {
+ item.style.backgroundColor = 'transparent';
+ });
+
+ popup.appendChild(item);
+ });
+
+ document.body.appendChild(popup);
+}
+
+function removeExistingPopup() {
+ const existing = document.getElementById('aliasvault-credential-popup');
+ if (existing) {
+ existing.remove();
+ }
+}
+
+function fillCredential(credential: any) {
+ const forms = detectForms();
+ if (!forms.length) return;
+
+ const form = forms[0];
+ if (form.usernameField) {
+ form.usernameField.value = credential.username;
+ triggerInputEvents(form.usernameField);
+ }
+ if (form.passwordField) {
+ form.passwordField.value = credential.password;
+ triggerInputEvents(form.passwordField);
+ }
+}
+
+function triggerInputEvents(element: HTMLInputElement) {
+ element.dispatchEvent(new Event('input', { bubbles: true }));
+ element.dispatchEvent(new Event('change', { bubbles: true }));
+}
\ No newline at end of file
diff --git a/browser-extensions/chrome/src/manifest.json b/browser-extensions/chrome/src/manifest.json
index 4d2148821..20bd363da 100644
--- a/browser-extensions/chrome/src/manifest.json
+++ b/browser-extensions/chrome/src/manifest.json
@@ -22,6 +22,17 @@
"type": "module"
},
"permissions": [
- "storage"
+ "storage",
+ "activeTab"
+ ],
+ "content_scripts": [
+ {
+ "matches": ["<all_urls>"],
+ "js": ["contentScript.js"],
+ "css": ["contentScript.css"]
+ }
+ ],
+ "host_permissions": [
+ "<all_urls>"
]
}
\ No newline at end of file
diff --git a/browser-extensions/chrome/src/styles/contentScript.css b/browser-extensions/chrome/src/styles/contentScript.css
new file mode 100644
index 000000000..bd6213e1d
--- /dev/null
+++ b/browser-extensions/chrome/src/styles/contentScript.css
@@ -0,0 +1,3 @@
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
\ No newline at end of file
diff --git a/browser-extensions/chrome/src/utilities/FormDetector.ts b/browser-extensions/chrome/src/utilities/FormDetector.ts
new file mode 100644
index 000000000..9a26c884d
--- /dev/null
+++ b/browser-extensions/chrome/src/utilities/FormDetector.ts
@@ -0,0 +1,54 @@
+interface LoginForm {
+ form: HTMLFormElement | null;
+ usernameField: HTMLInputElement | null;
+ passwordField: HTMLInputElement | null;
+}
+
+export function detectForms(): LoginForm[] {
+ const forms: LoginForm[] = [];
+
+ // Find all password fields
+ const passwordFields = document.querySelectorAll<HTMLInputElement>('input[type="password"]');
+
+ passwordFields.forEach(passwordField => {
+ const form = passwordField.closest('form');
+ const usernameField = findUsernameField(passwordField);
+
+ forms.push({
+ form,
+ usernameField,
+ passwordField
+ });
+ });
+
+ return forms;
+}
+
+function findUsernameField(passwordField: HTMLInputElement): HTMLInputElement | null {
+ const form = passwordField.closest('form');
+ const candidates = form ? form.querySelectorAll<HTMLInputElement>('input') : document.querySelectorAll<HTMLInputElement>('input');
+
+ for (const input of Array.from(candidates)) {
+ if (input === passwordField) continue;
+
+ // Check input type
+ const type = input.type.toLowerCase();
+ if (type === 'text' || type === 'email') {
+ // Check common username/email patterns
+ const attributes = [
+ input.type,
+ input.id,
+ input.name,
+ input.className,
+ input.placeholder
+ ].map(attr => attr?.toLowerCase() || '');
+
+ const patterns = ['user', 'email', 'login', 'identifier'];
+ if (patterns.some(pattern => attributes.some(attr => attr.includes(pattern)))) {
+ return input;
+ }
+ }
+ }
+
+ return null;
+}
\ No newline at end of file
diff --git a/browser-extensions/chrome/src/utilities/SqliteClient.tsx b/browser-extensions/chrome/src/utilities/SqliteClient.tsx
index c0a4b851e..8c95e3e75 100644
--- a/browser-extensions/chrome/src/utilities/SqliteClient.tsx
+++ b/browser-extensions/chrome/src/utilities/SqliteClient.tsx
@@ -9,7 +9,7 @@ class SqliteClient {
public async initializeFromBase64(base64String: string): Promise<void> {
try {
// Convert base64 to Uint8Array
- const binaryString = window.atob(base64String);
+ const binaryString = atob(base64String);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
diff --git a/browser-extensions/chrome/tailwind.content.config.js b/browser-extensions/chrome/tailwind.content.config.js
new file mode 100644
index 000000000..9141b5767
--- /dev/null
+++ b/browser-extensions/chrome/tailwind.content.config.js
@@ -0,0 +1,10 @@
+/** @type {import('tailwindcss').Config} */
+export default {
+ content: [
+ "./src/contentScript.ts",
+ ],
+ theme: {
+ extend: {},
+ },
+ plugins: [],
+}
\ No newline at end of file
diff --git a/browser-extensions/chrome/vite.config.js b/browser-extensions/chrome/vite.config.js
index 67f615828..6ff57340f 100644
--- a/browser-extensions/chrome/vite.config.js
+++ b/browser-extensions/chrome/vite.config.js
@@ -20,6 +20,10 @@ export default defineConfig({
{
src: 'node_modules/argon2-browser/dist/argon2.wasm',
dest: 'src'
+ },
+ {
+ src: 'src/styles/contentScript.css',
+ dest: '.'
}
]
}),
@@ -32,24 +36,36 @@ export default defineConfig({
],
},
},
- resolve: {
- alias: {
- '@': '/src', // Optional alias for cleaner imports
- },
- },
build: {
rollupOptions: {
input: {
popup: './src/popup.html',
- background: './src/background.ts'
+ background: './src/background.ts',
+ contentScript: './src/contentScript.ts',
+ contentStyles: './src/styles/contentScript.css'
},
output: {
entryFileNames: '[name].js',
+ assetFileNames: (assetInfo) => {
+ if (assetInfo.name && assetInfo.name.endsWith('contentScript.css')) {
+ return 'contentScript.css';
+ }
+ return '[name].[ext]';
+ },
format: 'es'
}
},
+ watch: {
+ include: ['src/**'],
+ exclude: ['node_modules/**']
+ },
outDir: 'dist',
},
+ resolve: {
+ alias: {
+ '@': '/src',
+ },
+ },
server: {
open: '/src/popup.html'
},