Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add clipboard clear and timer logic to background.ts, add offscreen API for Chrome 109+ (#881)
Leendert de Borstd70eb0a4471d
diff --git a/apps/browser-extension/public/offscreen.html b/apps/browser-extension/public/offscreen.htmlnew file mode 100644index 000000000..069b396b1--- /dev/null+++ b/apps/browser-extension/public/offscreen.html@@ -0,0 +1,12 @@+<!DOCTYPE html>+<html>+<head>+ <meta charset="utf-8">+ <title>AliasVault Offscreen Document</title>+ <!-- The offscreen.html is used for clipboard clearing. It is a hidden document that runs in a hidden context with access to clipboard operations. -->+</head>+<body>+ <textarea id="text"></textarea>+ <script src="offscreen.js"></script>+</body>+</html>diff --git a/apps/browser-extension/public/offscreen.js b/apps/browser-extension/public/offscreen.jsnew file mode 100644index 000000000..461adfc9b--- /dev/null+++ b/apps/browser-extension/public/offscreen.js@@ -0,0 +1,39 @@+/**+ * Offscreen document for clipboard operations.+ * This document runs in a hidden context with access to clipboard operations.+ */++// Listen for messages from the service worker+chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {+ if (message.type === 'CLEAR_CLIPBOARD') {+ clearClipboard()+ .then(() => {+ sendResponse({ success: true, message: 'Clipboard cleared successfully' });+ })+ .catch((error) => {+ console.error('[OFFSCREEN] Failed to clear clipboard:', error);+ sendResponse({ success: false, message: error.message });+ });+ // Return true to indicate we'll send response asynchronously+ return true;+ }+});++const textEl = document.querySelector('#text');++/**+ * Clear the clipboard by writing a space using execCommand.+ */+async function clearClipboard() {+ try {+ // Use execCommand to clear clipboard+ console.log(textEl);+ textEl.value = '\u200B'; // Zero-width space+ textEl.select();+ console.log(textEl.value);+ document.execCommand('copy');+ } catch (error) {+ console.error('[OFFSCREEN] Error clearing clipboard:', error);+ throw error;+ }+}\ No newline at end of filediff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.tsindex 5e5740ff4..6b645f705 100644--- a/apps/browser-extension/src/entrypoints/background.ts+++ b/apps/browser-extension/src/entrypoints/background.ts@@ -4,11 +4,19 @@ import { setupContextMenus } from '@/entrypoints/background/ContextMenu';import { handleOpenPopup, handlePopupWithCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearVault, handleCreateIdentity, handleGetCredentials, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVault, handleSyncVault, handleUploadVault } from '@/entrypoints/background/VaultMessageHandler';-import { GLOBAL_CONTEXT_MENU_ENABLED_KEY } from '@/utils/Constants';+import { GLOBAL_CONTEXT_MENU_ENABLED_KEY, CLIPBOARD_CLEAR_TIMEOUT_KEY } from '@/utils/Constants';import type { EncryptionKeyDerivationParams } from '@/utils/dist/shared/models/metadata';import { defineBackground, storage, browser } from '#imports';+let clipboardClearTimer: NodeJS.Timeout | null = null;+let countdownInterval: NodeJS.Timeout | null = null;+let remainingTime = 0;+let currentCountdownId = 0;+let totalCountdownTime = 0;+let countdownStartTime = 0;+let offscreenDocumentCreated = false;+export default defineBackground({/*** This is the main entry point for the background script.@@ -44,6 +52,21 @@ export default defineBackground({onMessage('GET_PERSISTED_FORM_VALUES', () => handleGetPersistedFormValues());onMessage('CLEAR_PERSISTED_FORM_VALUES', () => handleClearPersistedFormValues());+ // Clipboard management messages+ onMessage('CLIPBOARD_COPIED', () => handleClipboardCopied());+ onMessage('CANCEL_CLIPBOARD_CLEAR', () => handleCancelClipboardClear());+ onMessage('GET_CLIPBOARD_CLEAR_TIMEOUT', () => handleGetClipboardClearTimeout());+ onMessage('SET_CLIPBOARD_CLEAR_TIMEOUT', ({ data }) => handleSetClipboardClearTimeout(data as number));+ onMessage('GET_CLIPBOARD_COUNTDOWN_STATE', () => handleGetClipboardCountdownState());++ // Also handle runtime messages from content scripts+ browser.runtime.onMessage.addListener((message) => {+ if (message.type === 'CLIPBOARD_COPIED_FROM_CONTEXT') {+ // Trigger the same clipboard clear logic+ handleClipboardCopied();+ }+ });+// Setup context menusconst isContextMenuEnabled = await storage.getItem(GLOBAL_CONTEXT_MENU_ENABLED_KEY) ?? true;if (isContextMenuEnabled) {@@ -87,4 +110,209 @@ function getActiveElementIdentifier() : string {return target.id || target.name || '';}return '';+}++/**+ * Create offscreen document if it doesn't exist.+ */+async function createOffscreenDocument(): Promise<void> {+ if (offscreenDocumentCreated) {+ return;+ }++ try {+ // Check if chrome.offscreen API is available (Chrome 109+)+ if (!chrome.offscreen) {+ console.warn('[CLIPBOARD] Offscreen API not available, falling back to direct clipboard access');+ return;+ }++ // Check if offscreen document already exists+ if (chrome.runtime.getContexts) {+ const existingContexts = await chrome.runtime.getContexts({+ contextTypes: ['OFFSCREEN_DOCUMENT'],+ documentUrls: [chrome.runtime.getURL('offscreen.html')]+ });++ if (existingContexts.length > 0) {+ offscreenDocumentCreated = true;+ return;+ }+ }++ // Create offscreen document+ await chrome.offscreen.createDocument({+ url: 'offscreen.html',+ reasons: [chrome.offscreen.Reason.CLIPBOARD],+ justification: 'Clear clipboard after timeout for security'+ });++ offscreenDocumentCreated = true;+ } catch (error) {+ console.error('[CLIPBOARD] Failed to create offscreen document:', error);+ offscreenDocumentCreated = false;+ }+}++/**+ * Clear clipboard using offscreen document or fallback method.+ */+async function clearClipboardContent(): Promise<void> {+ // Try to use offscreen document if available (Chrome 109+)+ if (chrome.offscreen) {+ // Ensure offscreen document exists+ await createOffscreenDocument();++ // Send message to offscreen document to clear clipboard+ const response = await chrome.runtime.sendMessage({ type: 'CLEAR_CLIPBOARD' });++ if (response?.success) {+ console.info('[CLIPBOARD] Clipboard cleared via offscreen document');+ } else {+ throw new Error(response?.message || 'Failed to clear clipboard via offscreen');+ }+ } else {+ // Fallback: try direct clipboard access (may not work in service worker)+ await navigator.clipboard.writeText(' ');+ }+}++/**+ * Handle clipboard copied event - starts countdown and timer to clear clipboard.+ */+async function handleClipboardCopied() : Promise<void> {+ const timeout = await storage.getItem(CLIPBOARD_CLEAR_TIMEOUT_KEY) as number ?? 10;++ // Clear any existing timer+ if (clipboardClearTimer) {+ clearTimeout(clipboardClearTimer);+ clipboardClearTimer = null;+ }+ if (countdownInterval) {+ clearInterval(countdownInterval);+ countdownInterval = null;+ }++ // Don't set timer if timeout is 0 (disabled)+ if (timeout === 0) {+ return;+ }++ // Generate new countdown ID+ currentCountdownId = Date.now();+ const thisCountdownId = currentCountdownId;+ countdownStartTime = Date.now();+ totalCountdownTime = timeout;++ remainingTime = timeout;++ // Send initial countdown immediately with ID+ sendMessage('CLIPBOARD_COUNTDOWN', { remaining: remainingTime, total: timeout, id: thisCountdownId }, 'popup').catch(() => {});++ // Send countdown updates to popup every 100ms for smooth animation+ let elapsed = 0;+ countdownInterval = setInterval(() => {+ // Check if this countdown is still active+ if (thisCountdownId !== currentCountdownId) {+ if (countdownInterval) {+ clearInterval(countdownInterval);+ }+ return;+ }++ elapsed += 0.1;+ remainingTime = Math.max(0, timeout - elapsed);+ sendMessage('CLIPBOARD_COUNTDOWN', { remaining: remainingTime, total: timeout, id: thisCountdownId }, 'popup').catch(() => {});++ if (elapsed >= timeout && countdownInterval) {+ clearInterval(countdownInterval);+ countdownInterval = null;+ }+ }, 100);++ // Set timer to clear clipboard+ clipboardClearTimer = setTimeout(async () => {+ try {+ // Clear clipboard using offscreen document or fallback+ await clearClipboardContent();++ // Clean up regardless of success/failure+ clipboardClearTimer = null;+ if (countdownInterval) {+ clearInterval(countdownInterval);+ countdownInterval = null;+ }++ // Reset countdown tracking+ currentCountdownId = 0;+ countdownStartTime = 0;+ totalCountdownTime = 0;++ sendMessage('CLIPBOARD_CLEARED', {}, 'popup').catch(() => {});+ } catch (error) {+ console.error('[CLIPBOARD] Error during clipboard clear:', error);++ // Clean up even on error+ clipboardClearTimer = null;+ if (countdownInterval) {+ clearInterval(countdownInterval);+ countdownInterval = null;+ }+ currentCountdownId = 0;+ countdownStartTime = 0;+ totalCountdownTime = 0;+ sendMessage('CLIPBOARD_CLEARED', {}, 'popup').catch(() => {});+ }+ }, timeout * 1000);+}++/**+ * Cancel clipboard clear countdown and timer.+ */+function handleCancelClipboardClear(): void {+ if (clipboardClearTimer) {+ clearTimeout(clipboardClearTimer);+ clipboardClearTimer = null;+ }+ if (countdownInterval) {+ clearInterval(countdownInterval);+ countdownInterval = null;+ }+ sendMessage('CLIPBOARD_COUNTDOWN_CANCELLED', {}, 'popup').catch(() => {});+}++/**+ * Get the clipboard clear timeout setting.+ */+async function handleGetClipboardClearTimeout(): Promise<number> {+ const timeout = await storage.getItem(CLIPBOARD_CLEAR_TIMEOUT_KEY) as number ?? 10;+ return timeout;+}++/**+ * Set the clipboard clear timeout setting.+ */+async function handleSetClipboardClearTimeout(data: number): Promise<boolean> {+ await storage.setItem(CLIPBOARD_CLEAR_TIMEOUT_KEY, data);+ return true;+}++/**+ * Get the current clipboard countdown state.+ */+function handleGetClipboardCountdownState(): { remaining: number; total: number; id: number } | null {+ // Calculate actual remaining time based on elapsed time+ if (currentCountdownId && countdownStartTime && totalCountdownTime) {+ const elapsed = (Date.now() - countdownStartTime) / 1000;+ const actualRemaining = Math.max(0, totalCountdownTime - elapsed);++ if (actualRemaining > 0) {+ return {+ remaining: actualRemaining,+ total: totalCountdownTime,+ id: currentCountdownId+ };+ }+ }+ return null;}\ No newline at end of filediff --git a/apps/browser-extension/wxt.config.ts b/apps/browser-extension/wxt.config.tsindex 53f9d81df..b31a9fddd 100644--- a/apps/browser-extension/wxt.config.ts+++ b/apps/browser-extension/wxt.config.ts@@ -17,7 +17,9 @@ export default defineConfig({"storage","activeTab","contextMenus",- "scripting"+ "scripting",+ "clipboardWrite",+ "offscreen"],host_permissions: ["<all_urls>"