Skip to content

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

Add vault autolock timer to browser extension (#1131)

Leendert de Borst108a6855c28f
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index ce437f051..a415108b6 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -4,7 +4,7 @@ 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, CLIPBOARD_CLEAR_TIMEOUT_KEY } from '@/utils/Constants';
+import { GLOBAL_CONTEXT_MENU_ENABLED_KEY, CLIPBOARD_CLEAR_TIMEOUT_KEY, AUTO_LOCK_TIMEOUT_KEY } from '@/utils/Constants';
import type { EncryptionKeyDerivationParams } from '@/utils/dist/shared/models/metadata';
import { defineBackground, storage, browser } from '#imports';
@@ -17,6 +17,8 @@ let totalCountdownTime = 0;
let countdownStartTime = 0;
let offscreenDocumentCreated = false;
+let autoLockTimer: NodeJS.Timeout | null = null;
+
export default defineBackground({
/**
* This is the main entry point for the background script.
@@ -59,13 +61,14 @@ export default defineBackground({
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();
- }
- });
+ // Auto-lock management messages
+ onMessage('RESET_AUTO_LOCK_TIMER', () => handleResetAutoLockTimer());
+ onMessage('SET_AUTO_LOCK_TIMEOUT', ({ data }) => handleSetAutoLockTimeout(data as number));
+ onMessage('POPUP_OPENED', () => handlePopupOpened());
+ onMessage('POPUP_CLOSED', () => handlePopupClosed());
+
+ // Handle clipboard copied from context menu
+ onMessage('CLIPBOARD_COPIED_FROM_CONTEXT', () => handleClipboardCopied());
// Setup context menus
const isContextMenuEnabled = await storage.getItem(GLOBAL_CONTEXT_MENU_ENABLED_KEY) ?? true;
@@ -174,7 +177,7 @@ async function clearClipboardContent(): Promise<void> {
throw new Error(response?.message || 'Failed to clear clipboard via offscreen');
}
} else {
- // Firefox and Safari use mv2 and do not have offscreen document support, use direct clipboard access.
+ // Firefox and Safari use mv2 and can use direct clipboard access.
await navigator.clipboard.writeText('');
}
}
@@ -317,4 +320,79 @@ function handleGetClipboardCountdownState(): { remaining: number; total: number;
}
}
return null;
+}
+
+/**
+ * Reset the auto-lock timer.
+ */
+function handleResetAutoLockTimer(): void {
+ resetAutoLockTimer();
+}
+
+/**
+ * Handle popup opened - clear auto-lock timer.
+ */
+function handlePopupOpened(): void {
+ if (autoLockTimer) {
+ clearTimeout(autoLockTimer);
+ autoLockTimer = null;
+ console.info('[AUTO_LOCK] Timer cleared - popup opened');
+ }
+}
+
+/**
+ * Handle popup closed - restart auto-lock timer.
+ */
+function handlePopupClosed(): void {
+ resetAutoLockTimer();
+ console.info('[AUTO_LOCK] Timer restarted - popup closed');
+}
+
+/**
+ * Set the auto-lock timeout setting.
+ */
+async function handleSetAutoLockTimeout(timeout: number): Promise<boolean> {
+ await storage.setItem(AUTO_LOCK_TIMEOUT_KEY, timeout);
+ resetAutoLockTimer();
+ return true;
+}
+
+/**
+ * Reset the auto-lock timer based on current settings.
+ */
+async function resetAutoLockTimer(): Promise<void> {
+ // Clear existing timer
+ if (autoLockTimer) {
+ clearTimeout(autoLockTimer);
+ autoLockTimer = null;
+ }
+
+ // Get timeout setting
+ const timeout = await storage.getItem(AUTO_LOCK_TIMEOUT_KEY) as number ?? 0;
+
+ // Don't set timer if timeout is 0 (disabled) or if vault is already locked
+ if (timeout === 0) {
+ return;
+ }
+
+ // Check if vault is unlocked before setting timer
+ const encryptionKey = await storage.getItem('session:encryptionKey') as string | null;
+
+ if (!encryptionKey) {
+ // Vault is already locked, don't start timer
+ return;
+ }
+
+ // Set new timer
+ autoLockTimer = setTimeout(async () => {
+ try {
+ // Lock the vault using the existing handler
+ handleClearVault();
+
+ console.info('[AUTO_LOCK] Vault locked due to inactivity');
+ autoLockTimer = null;
+ } catch (error) {
+ console.error('[AUTO_LOCK] Error locking vault:', error);
+ }
+ }, timeout * 1000);
}
\ No newline at end of file
diff --git a/apps/browser-extension/src/entrypoints/contentScript/Form.ts b/apps/browser-extension/src/entrypoints/contentScript/Form.ts
index dccf7fff7..2552eb420 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/Form.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/Form.ts
@@ -1,3 +1,5 @@
+import { sendMessage } from 'webext-bridge/content-script';
+
import { openAutofillPopup } from '@/entrypoints/contentScript/Popup';
import type { Credential } from '@/utils/dist/shared/models/vault';
@@ -86,6 +88,11 @@ export function fillCredential(credential: Credential, input: HTMLInputElement)
// Set debounce time to 300ms to prevent the popup from being shown again within 300ms because of autofill events.
hidePopupFor(300);
+ // Reset auto-lock timer when autofilling
+ sendMessage('RESET_AUTO_LOCK_TIMER', {}, 'background').catch(() => {
+ // Ignore errors as background script might not be ready
+ });
+
const formDetector = new FormDetector(document, input);
const form = formDetector.getForm();
diff --git a/apps/browser-extension/src/entrypoints/popup/App.tsx b/apps/browser-extension/src/entrypoints/popup/App.tsx
index a87886dbc..bc3a8ba0c 100644
--- a/apps/browser-extension/src/entrypoints/popup/App.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/App.tsx
@@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { HashRouter as Router, Routes, Route } from 'react-router-dom';
+import { sendMessage } from 'webext-bridge/popup';
import { ClipboardCountdownBar } from '@/entrypoints/popup/components/ClipboardCountdownBar';
import BottomNav from '@/entrypoints/popup/components/Layout/BottomNav';
@@ -75,6 +76,23 @@ const App: React.FC = () => {
}
}, [isInitialLoading, setIsLoading]);
+ /**
+ * Notify background when popup opens/closes.
+ */
+ useEffect(() => {
+ // Notify background that popup is open
+ sendMessage('POPUP_OPENED', {}, 'background').catch(() => {
+ // Ignore errors as background script might not be ready
+ });
+
+ // Cleanup: notify background when popup closes
+ return () : void => {
+ sendMessage('POPUP_CLOSED', {}, 'background').catch(() => {
+ // Ignore errors on cleanup
+ });
+ };
+ }, []);
+
/**
* Print global message if it exists.
*/
diff --git a/apps/browser-extension/src/entrypoints/popup/components/HelpModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/HelpModal.tsx
new file mode 100644
index 000000000..81e63bfeb
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/components/HelpModal.tsx
@@ -0,0 +1,84 @@
+import React, { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+type HelpModalProps = {
+ titleKey: string;
+ contentKey: string;
+ className?: string;
+}
+
+/**
+ * Reusable help modal component with a question mark icon button.
+ * Shows a modal popup with help information when clicked.
+ */
+const HelpModal: React.FC<HelpModalProps> = ({ titleKey, contentKey, className = '' }) => {
+ const { t } = useTranslation();
+ const [showModal, setShowModal] = useState(false);
+
+ return (
+ <>
+ <button
+ onClick={() => setShowModal(true)}
+ className={`${className}`}
+ type="button"
+ aria-label="Help"
+ >
+ <svg
+ className="w-4 h-4 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 cursor-help"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={2}
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
+ />
+ </svg>
+ </button>
+
+ {showModal && (
+ <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
+ <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-sm w-full">
+ <div className="flex items-center justify-between mb-4">
+ <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
+ {t(titleKey)}
+ </h3>
+ <button
+ onClick={() => setShowModal(false)}
+ className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
+ aria-label={t('common.close')}
+ >
+ <svg
+ className="w-5 h-5"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={2}
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ d="M6 18L18 6M6 6l12 12"
+ />
+ </svg>
+ </button>
+ </div>
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {t(contentKey)}
+ </p>
+ <button
+ onClick={() => setShowModal(false)}
+ className="mt-4 w-full px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-md transition-colors"
+ >
+ {t('common.close')}
+ </button>
+ </div>
+ </div>
+ )}
+ </>
+ );
+};
+
+export default HelpModal;
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/Settings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/Settings.tsx
index 007747f59..e200ac261 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/Settings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/Settings.tsx
@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom';
import { sendMessage } from 'webext-bridge/popup';
import HeaderButton from '@/entrypoints/popup/components/HeaderButton';
+import HelpModal from '@/entrypoints/popup/components/HelpModal';
import { HeaderIconType } from '@/entrypoints/popup/components/Icons/HeaderIcons';
import LanguageSwitcher from '@/entrypoints/popup/components/LanguageSwitcher';
import { useAuth } from '@/entrypoints/popup/context/AuthContext';
@@ -14,7 +15,7 @@ import { useApiUrl } from '@/entrypoints/popup/utils/ApiUrlUtility';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
import { AppInfo } from '@/utils/AppInfo';
-import { DISABLED_SITES_KEY, GLOBAL_AUTOFILL_POPUP_ENABLED_KEY, GLOBAL_CONTEXT_MENU_ENABLED_KEY, TEMPORARY_DISABLED_SITES_KEY, CLIPBOARD_CLEAR_TIMEOUT_KEY } from '@/utils/Constants';
+import { DISABLED_SITES_KEY, GLOBAL_AUTOFILL_POPUP_ENABLED_KEY, GLOBAL_CONTEXT_MENU_ENABLED_KEY, TEMPORARY_DISABLED_SITES_KEY, CLIPBOARD_CLEAR_TIMEOUT_KEY, AUTO_LOCK_TIMEOUT_KEY } from '@/utils/Constants';
import { storage, browser } from "#imports";
@@ -50,6 +51,7 @@ const Settings: React.FC = () => {
isContextMenuEnabled: true
});
const [clipboardTimeout, setClipboardTimeout] = useState<number>(10);
+ const [autoLockTimeout, setAutoLockTimeout] = useState<number>(0);
/**
* Get current tab in browser.
@@ -128,6 +130,10 @@ const Settings: React.FC = () => {
const timeout = await storage.getItem(CLIPBOARD_CLEAR_TIMEOUT_KEY) as number ?? 10;
setClipboardTimeout(timeout);
+ // Load auto-lock timeout
+ const autoLockTimeoutValue = await storage.getItem(AUTO_LOCK_TIMEOUT_KEY) as number ?? 0;
+ setAutoLockTimeout(autoLockTimeoutValue);
+
setSettings({
disabledUrls,
temporaryDisabledUrls: cleanedTemporaryDisabledUrls,
@@ -243,6 +249,15 @@ const Settings: React.FC = () => {
setClipboardTimeout(timeout);
};
+ /**
+ * Set auto-lock timeout.
+ */
+ const setAutoLockTimeoutSetting = async (timeout: number) : Promise<void> => {
+ await storage.setItem(AUTO_LOCK_TIMEOUT_KEY, timeout);
+ await sendMessage('SET_AUTO_LOCK_TIMEOUT', timeout, 'background');
+ setAutoLockTimeout(timeout);
+ };
+
/**
* Open keyboard shortcuts configuration page.
*/
@@ -418,7 +433,7 @@ const Settings: React.FC = () => {
<h3 className="text-md font-semibold text-gray-900 dark:text-white mb-3">{t('settings.security')}</h3>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
<div className="p-4">
- <div>
+ <div className="mb-6">
<p className="text-sm font-medium text-gray-900 dark:text-white mb-2">{t('settings.clipboardClearTimeout')}</p>
<p className="text-xs text-gray-600 dark:text-gray-400 mb-3">{t('settings.clipboardClearTimeoutDescription')}</p>
<select
@@ -432,6 +447,34 @@ const Settings: React.FC = () => {
<option value="15">{t('settings.clipboardClear15Seconds')}</option>
</select>
</div>
+
+ <div>
+ <div className="flex items-center mb-2">
+ <p className="text-sm font-medium text-gray-900 dark:text-white">{t('settings.autoLockTimeout')}</p>
+ <HelpModal
+ titleKey="settings.autoLockTimeout"
+ contentKey="settings.autoLockTimeoutHelp"
+ className="ml-2"
+ />
+ </div>
+ <p className="text-xs text-gray-600 dark:text-gray-400 mb-3">{t('settings.autoLockTimeoutDescription')}</p>
+ <select
+ value={autoLockTimeout}
+ onChange={(e) => setAutoLockTimeoutSetting(Number(e.target.value))}
+ className="w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md text-gray-900 dark:text-white focus:ring-primary-500 focus:border-primary-500"
+ >
+ <option value="0">{t('settings.autoLockNever')}</option>
+ <option value="5">{t('settings.autoLock5Seconds')}</option>
+ <option value="60">{t('settings.autoLock1Minute')}</option>
+ <option value="300">{t('settings.autoLock5Minutes')}</option>
+ <option value="900">{t('settings.autoLock15Minutes')}</option>
+ <option value="1800">{t('settings.autoLock30Minutes')}</option>
+ <option value="3600">{t('settings.autoLock1Hour')}</option>
+ <option value="14400">{t('settings.autoLock4Hours')}</option>
+ <option value="28800">{t('settings.autoLock8Hours')}</option>
+ <option value="86400">{t('settings.autoLock24Hours')}</option>
+ </select>
+ </div>
</div>
</div>
</section>
diff --git a/apps/browser-extension/src/i18n/locales/en.json b/apps/browser-extension/src/i18n/locales/en.json
index 9011a4e33..286231052 100644
--- a/apps/browser-extension/src/i18n/locales/en.json
+++ b/apps/browser-extension/src/i18n/locales/en.json
@@ -320,6 +320,19 @@
"clipboardClear5Seconds": "Clear after 5 seconds",
"clipboardClear10Seconds": "Clear after 10 seconds",
"clipboardClear15Seconds": "Clear after 15 seconds",
+ "autoLockTimeout": "Auto-lock timeout",
+ "autoLockTimeoutDescription": "Automatically lock the vault after a period of inactivity",
+ "autoLockTimeoutHelp": "The timer resets when you open the browser extension or use autofill on a webpage. The vault will only lock after the specified period of inactivity (no autofill usage or extension popup opened). The vault will always lock when the browser is closed, regardless of this setting.",
+ "autoLockNever": "Never",
+ "autoLock5Seconds": "5 seconds (debug)",
+ "autoLock1Minute": "1 minute",
+ "autoLock5Minutes": "5 minutes",
+ "autoLock15Minutes": "15 minutes",
+ "autoLock30Minutes": "30 minutes",
+ "autoLock1Hour": "1 hour",
+ "autoLock4Hours": "4 hours",
+ "autoLock8Hours": "8 hours",
+ "autoLock24Hours": "24 hours",
"versionPrefix": "Version ",
"validation": {
"apiUrlRequired": "API URL is required",
diff --git a/apps/browser-extension/src/utils/Constants.ts b/apps/browser-extension/src/utils/Constants.ts
index 17e0b9eec..b7944232f 100644
--- a/apps/browser-extension/src/utils/Constants.ts
+++ b/apps/browser-extension/src/utils/Constants.ts
@@ -5,6 +5,7 @@ export const GLOBAL_CONTEXT_MENU_ENABLED_KEY = 'local:aliasvault_global_context_
export const VAULT_LOCKED_DISMISS_UNTIL_KEY = 'local:aliasvault_vault_locked_dismiss_until';
export const TEMPORARY_DISABLED_SITES_KEY = 'local:aliasvault_temporary_disabled_sites';
export const CLIPBOARD_CLEAR_TIMEOUT_KEY = 'local:aliasvault_clipboard_clear_timeout';
+export const AUTO_LOCK_TIMEOUT_KEY = 'local:aliasvault_auto_lock_timeout';
// TODO: store these settings in the actual vault when updating the datamodel for roadmap v1.0.
export const LAST_CUSTOM_EMAIL_KEY = 'local:aliasvault_last_custom_email';