Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add browser extension pin unlock scaffolding (#1338)
Leendert de Borstb14f22f9ad79
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.tsindex 3ab0c912b..f42773163 100644--- a/apps/browser-extension/src/entrypoints/background.ts+++ b/apps/browser-extension/src/entrypoints/background.ts@@ -9,7 +9,7 @@ import { handleClipboardCopied, handleCancelClipboardClear, handleGetClipboardClimport { setupContextMenus } from '@/entrypoints/background/ContextMenu';import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, handlePasskeyPopupResponse, handleGetRequestData } from '@/entrypoints/background/PasskeyHandler';import { handleOpenPopup, handlePopupWithCredential, handleOpenPopupCreateCredential, 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 { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearVault, handleCreateIdentity, handleGetCredentials, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handleLockVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVault, handleSyncVault, handleUploadVault } from '@/entrypoints/background/VaultMessageHandler';import { GLOBAL_CONTEXT_MENU_ENABLED_KEY } from '@/utils/Constants';import { EncryptionKeyDerivationParams } from "@/utils/dist/shared/models/metadata";@@ -41,6 +41,7 @@ export default defineBackground({onMessage('UPLOAD_VAULT', ({ data }) => handleUploadVault(data));onMessage('SYNC_VAULT', () => handleSyncVault());+ onMessage('LOCK_VAULT', () => handleLockVault());onMessage('CLEAR_VAULT', () => handleClearVault());onMessage('OPEN_POPUP', () => handleOpenPopup());diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex 080017053..f7cd07c80 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -234,6 +234,13 @@ export function handleClearVault(return { success: true };}+/**+ * Lock the vault by clearing the encryption key from browser storage. This will force the user to unlock the vault again.+ */+export function handleLockVault(): void {+ storage.removeItem('session:encryptionKey');+}+/*** Get all credentials.*/diff --git a/apps/browser-extension/src/entrypoints/popup/App.tsx b/apps/browser-extension/src/entrypoints/popup/App.tsxindex 9e22443f8..9fd47c208 100644--- a/apps/browser-extension/src/entrypoints/popup/App.tsx+++ b/apps/browser-extension/src/entrypoints/popup/App.tsx@@ -4,6 +4,7 @@ import { HashRouter as Router, Routes, Route, useLocation } from 'react-router-dimport { sendMessage } from 'webext-bridge/popup';import DefaultLayout from '@/entrypoints/popup/components/Layout/DefaultLayout';+import Header from '@/entrypoints/popup/components/Layout/Header';import PasskeyLayout from '@/entrypoints/popup/components/Layout/PasskeyLayout';import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';import { useApp } from '@/entrypoints/popup/context/AppContext';@@ -31,6 +32,7 @@ import ContextMenuSettings from '@/entrypoints/popup/pages/settings/ContextMenuSimport LanguageSettings from '@/entrypoints/popup/pages/settings/LanguageSettings';import PasskeySettings from '@/entrypoints/popup/pages/settings/PasskeySettings';import Settings from '@/entrypoints/popup/pages/settings/Settings';+import VaultUnlockSettings from '@/entrypoints/popup/pages/settings/VaultUnlockSettings';import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';@@ -45,6 +47,8 @@ enum LayoutType {DEFAULT = 'default',/** Minimal layout for passkey operations - logo only, no footer */PASSKEY = 'passkey',+ /** Auth layout for login/unlock pages - no footer menu */+ AUTH = 'auth',}/**@@ -114,6 +118,32 @@ const AppContent: React.FC<{</PasskeyLayout>);+ case LayoutType.AUTH:+ // Auth layout - header only, no footer menu for login/unlock pages+ return (+ <div className="min-h-screen min-w-[350px] bg-white dark:bg-gray-900 flex flex-col max-h-[600px]">+ {loadingOverlay}+ <Header+ routes={routes}+ rightButtons={headerButtons}+ />+ <main+ className="flex-1 overflow-y-auto bg-gray-100 dark:bg-gray-900"+ style={{+ paddingTop: '64px',+ height: '100%',+ }}+ >+ {message && (+ <div className="p-4">+ <p className="text-red-500">{message}</p>+ </div>+ )}+ {routesComponent}+ </main>+ </div>+ );+case LayoutType.DEFAULT:default:// Default layout with full header, footer, navigation@@ -147,8 +177,8 @@ const App: React.FC = () => {const routes: RouteConfig[] = React.useMemo(() => [{ path: '/', element: <Index />, showBackButton: false },{ path: '/reinitialize', element: <Reinitialize />, showBackButton: false },- { path: '/login', element: <Login />, showBackButton: false },- { path: '/unlock', element: <Unlock />, showBackButton: false },+ { path: '/login', element: <Login />, showBackButton: false, layout: LayoutType.AUTH },+ { path: '/unlock', element: <Unlock />, showBackButton: false, layout: LayoutType.AUTH },{ path: '/unlock-success', element: <UnlockSuccess />, showBackButton: false },{ path: '/upgrade', element: <Upgrade />, showBackButton: false },{ path: '/auth-settings', element: <AuthSettings />, showBackButton: true, title: t('settings.title') },@@ -161,6 +191,7 @@ const App: React.FC = () => {{ path: '/emails', element: <EmailsList />, showBackButton: false },{ path: '/emails/:id', element: <EmailDetails />, showBackButton: true, title: t('emails.title') },{ path: '/settings', element: <Settings />, showBackButton: false },+ { path: '/settings/unlock-method', element: <VaultUnlockSettings />, showBackButton: true, title: t('settings.unlockMethod.title') },{ path: '/settings/autofill', element: <AutofillSettings />, showBackButton: true, title: t('settings.autofillSettings') },{ path: '/settings/context-menu', element: <ContextMenuSettings />, showBackButton: true, title: t('settings.contextMenuSettings') },{ path: '/settings/clipboard', element: <ClipboardSettings />, showBackButton: true, title: t('settings.clipboardSettings') },diff --git a/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx b/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsxindex 90f3b5923..39cb4f481 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx@@ -103,6 +103,7 @@ const Reinitialize: React.FC = () => {if (!isLoggedIn) {navigate('/login', { replace: true });} else if (!dbAvailable) {+ // Navigate to unified unlock page (handles both PIN and password)navigate('/unlock', { replace: true });}} else if (shouldRunSync) {diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsxindex 40adc9c02..a9d60bb63 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx@@ -1,6 +1,6 @@import { Buffer } from 'buffer';-import React, { useEffect, useState } from 'react';+import React, { useEffect, useState, useCallback, useRef } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';@@ -19,12 +19,26 @@ import SrpUtility from '@/entrypoints/popup/utils/SrpUtility';import { VAULT_LOCKED_DISMISS_UNTIL_KEY } from '@/utils/Constants';import type { VaultResponse } from '@/utils/dist/shared/models/webapi';import EncryptionUtility from '@/utils/EncryptionUtility';+import {+ getFailedAttempts,+ getPinLength,+ isPinEnabled,+ isPinLocked,+ PinLockedError,+ resetFailedAttempts,+ unlockWithPin+} from '@/utils/PinUnlockService';import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';import { storage } from '#imports';/**- * Unlock page+ * Unlock mode type+ */+type UnlockMode = 'pin' | 'password';++/**+ * Unified unlock page that handles both PIN and password unlock*/const Unlock: React.FC = () => {const { t } = useTranslation();@@ -37,8 +51,23 @@ const Unlock: React.FC = () => {const webApi = useWebApi();const srpUtil = new SrpUtility(webApi);+ // Unlock mode state+ const [unlockMode, setUnlockMode] = useState<UnlockMode>('password');+ const [pinAvailable, setPinAvailable] = useState<boolean>(false);++ // Password unlock stateconst [password, setPassword] = useState('');const [showPassword, setShowPassword] = useState(false);++ // PIN unlock state+ const [pin, setPin] = useState('');+ const [pinLength, setPinLength] = useState<number>(6);+ const [failedAttempts, setFailedAttempts] = useState<number>(0);+ const [isLocked, setIsLocked] = useState<boolean>(false);+ const inputRef = useRef<HTMLInputElement>(null);+ const containerRef = useRef<HTMLDivElement>(null);++ // Common stateconst [error, setError] = useState<string | null>(null);const { showLoading, hideLoading, setIsInitialLoading } = useLoading();@@ -64,8 +93,39 @@ const Unlock: React.FC = () => {return true;};+ /**+ * Initialize unlock page - check status and PIN availability+ */useEffect(() => {- checkStatus();+ /**+ * Initialize unlock page - check status and PIN availability+ */+ const initialize = async (): Promise<void> => {+ // First check PIN availability and set initial mode+ const [enabled, length, attempts, locked] = await Promise.all([+ isPinEnabled(),+ getPinLength(),+ getFailedAttempts(),+ isPinLocked()+ ]);++ setPinAvailable(enabled && !locked);+ setPinLength(length || 6);+ setFailedAttempts(attempts);+ setIsLocked(locked);++ // Default to PIN mode if available, otherwise password+ if (enabled && !locked) {+ setUnlockMode('pin');+ } else {+ setUnlockMode('password');+ }++ // Then check API status+ await checkStatus();+ };++ initialize();// eslint-disable-next-line react-hooks/exhaustive-deps}, []); // Only run once on mount@@ -87,9 +147,56 @@ const Unlock: React.FC = () => {}, [setHeaderButtons, t]);/**- * Handle submit+ * Keep input focused for PIN mode+ */+ useEffect(() => {+ if (unlockMode !== 'pin') {+ return;+ }++ /**+ * Focus the hidden input element+ */+ const focusInput = (): void => {+ if (inputRef.current) {+ inputRef.current.focus();+ }+ };++ /**+ * Re-focus input whenever user clicks anywhere on the page+ */+ const handleClick = (): void => {+ focusInput();+ };++ /**+ * Re-focus input when window/extension regains focus+ */+ const handleFocus = (): void => {+ focusInput();+ };++ focusInput();++ const container = containerRef.current;+ if (container) {+ container.addEventListener('click', handleClick);+ }+ window.addEventListener('focus', handleFocus);++ return (): void => {+ if (container) {+ container.removeEventListener('click', handleClick);+ }+ window.removeEventListener('focus', handleFocus);+ };+ }, [unlockMode]);++ /**+ * Handle password unlock*/- const handleSubmit = async (e: React.FormEvent) : Promise<void> => {+ const handlePasswordSubmit = async (e: React.FormEvent) : Promise<void> => {e.preventDefault();setError(null);showLoading();@@ -131,9 +238,12 @@ const Unlock: React.FC = () => {return;}- // Clear dismiss until (which can be enabled after user has dimissed vault is locked popup) to ensure popup is shown.+ // Clear dismiss untilawait storage.setItem(VAULT_LOCKED_DISMISS_UNTIL_KEY, 0);+ // Reset PIN failed attempts on successful password unlock+ await resetFailedAttempts();+navigate('/reinitialize', { replace: true });} catch (err) {// Check if it's a version incompatibility error@@ -148,6 +258,93 @@ const Unlock: React.FC = () => {}};+ /**+ * Handle PIN input change+ */+ const handlePinChange = useCallback(async (newPin: string): Promise<void> => {+ setPin(newPin);+ setError(null);++ // Auto-submit when PIN length is reached+ if (newPin.length === pinLength) {+ await handlePinUnlock(newPin);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [pinLength]);++ /**+ * Handle numpad button click+ */+ const handleNumpadClick = (digit: string): void => {+ if (pin.length < 8) {+ handlePinChange(pin + digit);+ }+ };++ /**+ * Handle backspace+ */+ const handleBackspace = (): void => {+ setPin(pin.slice(0, -1));+ setError(null);+ };++ /**+ * Handle PIN unlock+ */+ const handlePinUnlock = async (pinToUse: string = pin): Promise<void> => {+ if (pinToUse.length !== pinLength) {+ return;+ }++ setError(null);+ showLoading();++ try {+ // Unlock with PIN+ const passwordHashBase64 = await unlockWithPin(pinToUse);++ // Get latest vault from API+ const vaultResponseJson = await webApi.get<VaultResponse>('Vault');++ // Store the encryption key in session storage+ await dbContext.storeEncryptionKey(passwordHashBase64);++ // Initialize the SQLite context with the vault data+ const sqliteClient = await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);++ // Check if there are pending migrations+ if (await sqliteClient.hasPendingMigrations()) {+ navigate('/upgrade', { replace: true });+ hideLoading();+ return;+ }++ // Clear dismiss until+ await storage.setItem(VAULT_LOCKED_DISMISS_UNTIL_KEY, 0);++ navigate('/reinitialize', { replace: true });+ hideLoading();+ } catch (err: any) {+ if (err instanceof PinLockedError) {+ setIsLocked(true);+ setPinAvailable(false);+ setUnlockMode('password');+ setError(t('settings.unlockMethod.pinLocked'));+ } else {+ console.error('PIN unlock failed:', err);+ setError((err as Error).message);+ setPin('');+ hideLoading();++ // Update failed attempts+ const newAttempts = await getFailedAttempts();+ setFailedAttempts(newAttempts);+ }+ hideLoading();+ }+ };+/*** Handle logout*/@@ -155,9 +352,141 @@ const Unlock: React.FC = () => {app.logout();};+ /**+ * Switch to password mode+ */+ const switchToPassword = () : void => {+ setUnlockMode('password');+ setError(null);+ };++ /**+ * Switch to PIN mode+ */+ const switchToPin = () : void => {+ setUnlockMode('pin');+ setError(null);+ };++ // Generate PIN dots display+ const pinDots = Array.from({ length: pinLength }, (_, i) => (+ <div+ key={i}+ className={`w-4 h-4 rounded-full border-2 transition-all ${+ i < pin.length+ ? 'bg-primary-500 border-primary-500'+ : 'bg-transparent border-gray-300 dark:border-gray-600'+ }`}+ />+ ));++ // Render PIN unlock UI+ if (unlockMode === 'pin') {+ return (+ <div ref={containerRef} className="flex flex-col items-center justify-center p-4 bg-gray-50 dark:bg-gray-900">+ <div className="w-full max-w-md">+ {/* Logo */}+ <div className="text-center mb-4">+ <h1 className="text-xl font-bold text-gray-900 dark:text-white mb-1">+ {t('auth.unlockTitle')}+ </h1>+ <p className="text-sm text-gray-600 dark:text-gray-400">+ {t('auth.enterPinToUnlock')}+ </p>+ </div>++ {/* PIN Dots Display */}+ <div className="flex justify-center gap-2 mb-4">+ {pinDots}+ </div>++ {/* Error Message */}+ {error && (+ <div className="mb-3 p-2 bg-red-100 dark:bg-red-900/30 border border-red-300 dark:border-red-700 rounded-md text-red-800 dark:text-red-300 text-xs text-center">+ {error}+ </div>+ )}++ {/* Hidden Input for Keyboard Entry */}+ <input+ ref={inputRef}+ type="password"+ inputMode="numeric"+ pattern="[0-9]*"+ maxLength={8}+ value={pin}+ onChange={(e) => handlePinChange(e.target.value.replace(/\D/g, ''))}+ className="w-0 h-0 opacity-0 absolute"+ autoFocus+ aria-label="PIN input"+ />++ {/* On-Screen Numpad */}+ <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-4 mb-3">+ <div className="grid grid-cols-3 gap-2">+ {/* Numbers 1-9 */}+ {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((num) => (+ <button+ key={num}+ type="button"+ onClick={() => handleNumpadClick(num.toString())}+ className="h-16 flex items-center justify-center text-xl font-semibold bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-900 dark:text-white rounded-lg transition-colors active:scale-95"+ >+ {num}+ </button>+ ))}++ {/* Empty space, 0, Backspace */}+ <div />+ <button+ type="button"+ onClick={() => handleNumpadClick('0')}+ className="h-16 flex items-center justify-center text-xl font-semibold bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-900 dark:text-white rounded-lg transition-colors active:scale-95"+ >+ 0+ </button>+ <button+ type="button"+ onClick={handleBackspace}+ className="h-16 flex items-center justify-center bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-900 dark:text-white rounded-lg transition-colors active:scale-95"+ aria-label="Backspace"+ >+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2M3 12l6.414 6.414a2 2 0 001.414.586H19a2 2 0 002-2V7a2 2 0 00-2-2h-8.172a2 2 0 00-1.414.586L3 12z" />+ </svg>+ </button>+ </div>+ </div>++ {/* Divider */}+ <div className="flex items-center gap-3 my-3">+ <div className="flex-1 border-t border-gray-300 dark:border-gray-600" />+ <span className="text-xs text-gray-500 dark:text-gray-400">{t('common.or')}</span>+ <div className="flex-1 border-t border-gray-300 dark:border-gray-600" />+ </div>++ {/* Use Password Button */}+ <button+ type="button"+ onClick={switchToPassword}+ className="w-full bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline transition-colors text-sm"+ >+ {t('auth.useMasterPassword')}+ </button>++ {/* Tip */}+ <p className="mt-2 text-center text-xs text-gray-500 dark:text-gray-400">+ {t('auth.pinUnlockTip')}+ </p>+ </div>+ </div>+ );+ }++ // Render password unlock UIreturn (<div>- <form onSubmit={handleSubmit} className="bg-white dark:bg-gray-700 w-full shadow-md rounded px-8 pt-6 pb-8 mb-4">+ <form onSubmit={handlePasswordSubmit} className="bg-white dark:bg-gray-700 w-full shadow-md rounded px-8 pt-6 pb-8 mb-4">{/* User Avatar and Username Section */}<div className="flex items-center space-x-3 mb-6"><div className="flex-shrink-0">@@ -218,8 +547,26 @@ const Unlock: React.FC = () => {{t('auth.unlockVault')}</Button>+ {/* Switch to PIN button if PIN is available */}+ {pinAvailable && (+ <>+ <div className="flex items-center gap-3 my-4">+ <div className="flex-1 border-t border-gray-300 dark:border-gray-600" />+ <span className="text-xs text-gray-500 dark:text-gray-400">{t('common.or')}</span>+ <div className="flex-1 border-t border-gray-300 dark:border-gray-600" />+ </div>+ <button+ type="button"+ onClick={switchToPin}+ className="w-full bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline transition-colors"+ >+ {t('auth.unlockWithPin')}+ </button>+ </>+ )}+<div className="font-medium text-gray-500 dark:text-gray-200 mt-6">- {t('auth.switchAccounts')} <button onClick={handleLogout} className="text-primary-700 hover:underline dark:text-primary-500">{t('auth.logout')}</button>+ {t('auth.switchAccounts')} <button type="button" onClick={handleLogout} className="text-primary-700 hover:underline dark:text-primary-500">{t('auth.logout')}</button></div></form></div>diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsxindex 89ef7b4d0..92782e227 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx@@ -13,7 +13,8 @@ import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';import { AppInfo } from '@/utils/AppInfo';-import { browser } from "#imports";+import { browser, storage } from "#imports";+import { sendMessage } from 'webext-bridge/popup';/*** Settings page component.@@ -26,6 +27,7 @@ const Settings: React.FC = () => {const { setIsInitialLoading } = useLoading();const { loadApiUrl, getDisplayUrl } = useApiUrl();const navigate = useNavigate();+ const [showLogoutConfirm, setShowLogoutConfirm] = React.useState(false);/*** Open the client tab.@@ -109,9 +111,21 @@ const Settings: React.FC = () => {* Handle logout.*/const handleLogout = async () : Promise<void> => {+ setShowLogoutConfirm(false);app.logout();};+ /**+ * Handle lock vault.+ */+ const handleLock = async () : Promise<void> => {+ // Lock the vault+ await sendMessage('LOCK_VAULT', {}, 'background');++ // Navigate to unlock page+ navigate('/unlock');+ };+/*** Navigate to autofill settings.*/@@ -140,6 +154,13 @@ const Settings: React.FC = () => {navigate('/settings/auto-lock');};+ /**+ * Navigate to unlock method settings.+ */+ const navigateToUnlockMethodSettings = () : void => {+ navigate('/settings/unlock-method');+ };+/*** Navigate to context menu settings.*/@@ -182,36 +203,90 @@ const Settings: React.FC = () => {</p></div></div>- <button- onClick={handleLogout}- title={t('settings.logout')}- className="p-2 bg-red-100 hover:bg-red-200 dark:bg-red-900/30 dark:hover:bg-red-900/50 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 rounded-md transition-colors"- >+ <div className="flex gap-2">+ <button+ onClick={handleLock}+ title={t('settings.lock')}+ className="p-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-600 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 rounded-md transition-colors"+ >+ <svg+ className="w-5 h-5"+ fill="none"+ stroke="currentColor"+ strokeWidth={2}+ viewBox="0 0 24 24"+ aria-label={t('settings.lock')}+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"+ />+ </svg>+ </button>+ <button+ onClick={() => setShowLogoutConfirm(true)}+ title={t('settings.logout')}+ className="p-2 bg-red-100 hover:bg-red-200 dark:bg-red-900/30 dark:hover:bg-red-900/50 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 rounded-md transition-colors"+ >+ <svg+ className="w-5 h-5"+ fill="none"+ stroke="currentColor"+ strokeWidth={2}+ viewBox="0 0 24 24"+ aria-label={t('settings.logout')}+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"+ />+ </svg>+ </button>+ </div>+ </div>+ </div>+ </div>+ </section>++ {/* Settings Navigation Section */}+ <section>+ <h3 className="text-md font-semibold text-gray-900 dark:text-white mb-3">{t('settings.preferences')}</h3>+ <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">+ <div className="divide-y divide-gray-200 dark:divide-gray-700">+ {/* Vault Unlock Method */}+ <button+ onClick={navigateToUnlockMethodSettings}+ className="w-full px-4 py-3 flex items-center justify-between hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"+ >+ <div className="flex items-center"><svg- className="w-5 h-5"+ className="w-5 h-5 mr-3 text-gray-600 dark:text-gray-400"fill="none"stroke="currentColor"strokeWidth={2}viewBox="0 0 24 24"- aria-label={t('settings.logout')}><pathstrokeLinecap="round"strokeLinejoin="round"- d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"+ d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"/></svg>- </button>- </div>- </div>- </div>- </section>+ <span className="text-gray-900 dark:text-white">{t('settings.unlockMethod.title')}</span>+ </div>+ <svg+ className="w-4 h-4 text-gray-400"+ fill="none"+ stroke="currentColor"+ strokeWidth={2}+ viewBox="0 0 24 24"+ >+ <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />+ </svg>+ </button>- {/* Settings Navigation Section */}- <section>- <h3 className="text-md font-semibold text-gray-900 dark:text-white mb-3">{t('settings.preferences')}</h3>- <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">- <div className="divide-y divide-gray-200 dark:divide-gray-700">{/* Autofill Settings */}<buttononClick={navigateToAutofillSettings}@@ -479,6 +554,34 @@ const Settings: React.FC = () => {<div className="text-center text-gray-400 dark:text-gray-600">{t('settings.versionPrefix')}{AppInfo.VERSION} ({getDisplayUrl()})</div>++ {/* Logout Confirmation Modal */}+ {showLogoutConfirm && (+ <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">+ <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-sm w-full mx-4">+ <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3">+ {t('settings.logoutConfirmTitle')}+ </h3>+ <p className="text-sm text-gray-600 dark:text-gray-400 mb-6">+ {t('settings.logoutConfirmMessage')}+ </p>+ <div className="flex gap-3">+ <button+ onClick={() => setShowLogoutConfirm(false)}+ className="flex-1 px-4 py-2 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-900 dark:text-white rounded-md transition-colors"+ >+ {t('common.cancel')}+ </button>+ <button+ onClick={handleLogout}+ className="flex-1 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-md transition-colors"+ >+ {t('settings.logout')}+ </button>+ </div>+ </div>+ </div>+ )}</div>);};diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsxnew file mode 100644index 000000000..6fd278ba4--- /dev/null+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/VaultUnlockSettings.tsx@@ -0,0 +1,363 @@+import React, { useEffect, useState, useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import Button from '@/entrypoints/popup/components/Button';+import HelpModal from '@/entrypoints/popup/components/Dialogs/HelpModal';+import { useAuth } from '@/entrypoints/popup/context/AuthContext';+import { useDb } from '@/entrypoints/popup/context/DbContext';+import { useLoading } from '@/entrypoints/popup/context/LoadingContext';++import {+ isPinEnabled,+ setupPin,+ disablePin,+ isValidPin,+ getFailedAttempts,+ isPinLocked+} from '@/utils/PinUnlockService';++/**+ * Vault unlock method settings page component.+ */+const VaultUnlockSettings: React.FC = () => {+ const { t } = useTranslation();+ const authContext = useAuth();+ const dbContext = useDb();+ const { setIsInitialLoading, showLoading, hideLoading } = useLoading();++ const [pinEnabled, setPinEnabled] = useState<boolean>(false);+ const [error, setError] = useState<string | null>(null);+ const [success, setSuccess] = useState<string | null>(null);+ const [showPinSetup, setShowPinSetup] = useState<boolean>(false);+ const [pinSetupStep, setPinSetupStep] = useState<number>(1); // 1 = enter, 2 = confirm+ const [newPin, setNewPin] = useState<string>('');+ const [confirmPin, setConfirmPin] = useState<string>('');+ const [failedAttempts, setFailedAttempts] = useState<number>(0);+ const [isLocked, setIsLocked] = useState<boolean>(false);++ /**+ * Load PIN settings.+ */+ const loadSettings = useCallback(async (): Promise<void> => {+ try {+ const [enabled, attempts, locked] = await Promise.all([+ isPinEnabled(),+ getFailedAttempts(),+ isPinLocked()+ ]);++ setPinEnabled(enabled);+ setFailedAttempts(attempts);+ setIsLocked(locked);+ setIsInitialLoading(false);+ } catch (err: any) {+ console.error('Failed to load PIN settings:', err);+ setError(t('settings.unlockMethod.loadError'));+ setIsInitialLoading(false);+ }+ }, [setIsInitialLoading, t]);++ useEffect(() => {+ loadSettings();+ }, [loadSettings]);++ /**+ * Handle enable PIN - show setup modal.+ */+ const handleEnablePin = (): void => {+ setError(null);+ setSuccess(null);++ // Check if we have the encryption key in memory+ if (!dbContext.dbAvailable) {+ setError(t('settings.unlockMethod.unlockVaultFirst'));+ return;+ }++ setPinSetupStep(1);+ setNewPin('');+ setConfirmPin('');+ setShowPinSetup(true);+ };++ /**+ * Handle PIN setup submission (step 1: enter PIN).+ */+ const handlePinSetupNext = (e: React.FormEvent): void => {+ e.preventDefault();+ setError(null);++ // Validate PIN format+ if (!isValidPin(newPin)) {+ setError(t('settings.unlockMethod.invalidPinFormat'));+ return;+ }++ // Move to confirmation step+ setPinSetupStep(2);+ };++ /**+ * Handle PIN setup submission (step 2: confirm PIN).+ */+ const handlePinSetupSubmit = async (e: React.FormEvent): Promise<void> => {+ e.preventDefault();+ setError(null);+ setSuccess(null);++ // Validate PIN confirmation+ if (newPin !== confirmPin) {+ setError(t('settings.unlockMethod.pinMismatch'));+ return;+ }++ try {+ showLoading();++ // Get the encryption key from session storage+ const encryptionKeyResponse = await chrome.storage.session.get('encryptionKey');+ const encryptionKey = encryptionKeyResponse.encryptionKey as string;++ if (!encryptionKey) {+ setError(t('settings.unlockMethod.unlockVaultFirst'));+ hideLoading();+ return;+ }++ // Setup PIN with the encryption key+ await setupPin(newPin, encryptionKey);++ setPinEnabled(true);+ setShowPinSetup(false);+ setPinSetupStep(1);+ setNewPin('');+ setConfirmPin('');+ setSuccess(t('settings.unlockMethod.enableSuccess'));+ hideLoading();+ } catch (err: any) {+ console.error('Failed to enable PIN:', err);+ setError(err.message || t('settings.unlockMethod.enableError'));+ hideLoading();+ }+ };++ /**+ * Handle disable PIN.+ */+ const handleDisablePin = async (): Promise<void> => {+ setError(null);+ setSuccess(null);++ try {+ showLoading();+ await disablePin();+ setPinEnabled(false);+ setIsLocked(false);+ setFailedAttempts(0);+ setSuccess(t('settings.unlockMethod.disableSuccess'));+ hideLoading();+ } catch (err: any) {+ console.error('Failed to disable PIN:', err);+ setError(t('settings.unlockMethod.disableError'));+ hideLoading();+ }+ };+++ return (+ <div className="space-y-4">+ {/* Error/Success Messages */}+ {error && (+ <div className="p-3 bg-red-100 dark:bg-red-900/30 border border-red-300 dark:border-red-700 rounded-md text-red-800 dark:text-red-300 text-sm">+ {error}+ </div>+ )}+ {success && (+ <div className="p-3 bg-green-100 dark:bg-green-900/30 border border-green-300 dark:border-green-700 rounded-md text-green-800 dark:text-green-300 text-sm">+ {success}+ </div>+ )}++ {/* Locked Warning */}+ {isLocked && (+ <div className="p-3 bg-yellow-100 dark:bg-yellow-900/30 border border-yellow-300 dark:border-yellow-700 rounded-md text-yellow-800 dark:text-yellow-300 text-sm">+ {t('settings.unlockMethod.pinLocked')}+ </div>+ )}++ {/* PIN Code option */}+ <section>+ <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 className="flex items-center justify-between">+ <div className="flex items-center">+ <svg className="w-5 h-5 mr-2 text-gray-600 dark:text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14" />+ </svg>+ <div>+ <div className="flex items-center">+ <p className="font-medium text-gray-900 dark:text-white">{t('settings.unlockMethod.pin')}</p>+ <HelpModal+ titleKey="settings.unlockMethod.pin"+ contentKey="settings.unlockMethod.helpText"+ className="ml-2"+ />+ </div>+ <p className="text-sm mt-1 text-gray-600 dark:text-gray-400">+ {t('settings.unlockMethod.pinDescription')}+ </p>+ </div>+ </div>+ <button+ onClick={pinEnabled && !isLocked ? handleDisablePin : handleEnablePin}+ className={`px-4 py-2 rounded-md transition-colors ${+ pinEnabled && !isLocked+ ? 'bg-green-500 hover:bg-green-600 text-white'+ : 'bg-red-500 hover:bg-red-600 text-white'+ }`}+ >+ {pinEnabled && !isLocked ? t('settings.enabled') : t('settings.disabled')}+ </button>+ </div>++ {/* Reset PIN if locked */}+ {isLocked && (+ <div className="mt-4">+ <Button onClick={handleEnablePin} className="w-full">+ {t('settings.unlockMethod.resetPin')}+ </Button>+ </div>+ )}+ </div>+ </div>+ </section>++ {/* Master Password option (always enabled, cannot be toggled) */}+ <section>+ <div className="bg-gray-50 dark:bg-gray-700/30 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 opacity-75">+ <div className="p-4">+ <div className="flex items-center justify-between">+ <div className="flex items-center">+ <svg className="w-5 h-5 mr-2 text-gray-600 dark:text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />+ </svg>+ <div>+ <p className="font-medium text-gray-900 dark:text-white">{t('settings.unlockMethod.password')}</p>+ <p className="text-sm mt-1 text-gray-600 dark:text-gray-400">+ {t('settings.unlockMethod.passwordDescription')}+ </p>+ </div>+ </div>+ <div className="px-4 py-2 rounded-md bg-gray-300 text-gray-600 dark:bg-gray-600 dark:text-gray-300 cursor-not-allowed">+ {t('settings.enabled')}+ </div>+ </div>+ </div>+ </div>+ </section>++ {/* PIN Setup Modal */}+ {showPinSetup && (+ <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">+ <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-md w-full mx-4 relative">+ {/* Cancel button in top right corner */}+ <button+ type="button"+ onClick={() => {+ setShowPinSetup(false);+ setPinSetupStep(1);+ setNewPin('');+ setConfirmPin('');+ setError(null);+ }}+ className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition-colors"+ aria-label="Cancel"+ >+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />+ </svg>+ </button>++ {/* Step 1: Enter PIN */}+ {pinSetupStep === 1 && (+ <>+ <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4 pr-8">+ {t('settings.unlockMethod.setupPin')}+ </h3>+ <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">+ {t('settings.unlockMethod.enterNewPinDescription')}+ </p>+ <form onSubmit={handlePinSetupNext}>+ <div className="mb-4">+ <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">+ {t('settings.unlockMethod.enterNewPin')}+ </label>+ <input+ type="password"+ inputMode="numeric"+ pattern="[0-9]*"+ maxLength={8}+ value={newPin}+ onChange={(e) => setNewPin(e.target.value.replace(/\D/g, ''))}+ placeholder={t('settings.unlockMethod.pinPlaceholder')}+ className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-center text-2xl tracking-widest"+ autoFocus+ />+ </div>+ {error && (+ <div className="mb-4 text-red-500 dark:text-red-400 text-sm">+ {error}+ </div>+ )}+ <Button type="submit">+ {t('settings.unlockMethod.next')}+ </Button>+ </form>+ </>+ )}++ {/* Step 2: Confirm PIN */}+ {pinSetupStep === 2 && (+ <>+ <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4 pr-8">+ {t('settings.unlockMethod.confirmPinTitle')}+ </h3>+ <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">+ {t('settings.unlockMethod.confirmPinDescription')}+ </p>+ <form onSubmit={handlePinSetupSubmit}>+ <div className="mb-4">+ <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">+ {t('settings.unlockMethod.confirmPin')}+ </label>+ <input+ type="password"+ inputMode="numeric"+ pattern="[0-9]*"+ maxLength={8}+ value={confirmPin}+ onChange={(e) => setConfirmPin(e.target.value.replace(/\D/g, ''))}+ placeholder={t('settings.unlockMethod.pinPlaceholder')}+ className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-center text-2xl tracking-widest"+ autoFocus+ />+ </div>+ {error && (+ <div className="mb-4 text-red-500 dark:text-red-400 text-sm">+ {error}+ </div>+ )}+ <Button type="submit">+ {t('settings.unlockMethod.confirm')}+ </Button>+ </form>+ </>+ )}+ </div>+ </div>+ )}+ </div>+ );+};++export default VaultUnlockSettings;diff --git a/apps/browser-extension/src/i18n/locales/en.json b/apps/browser-extension/src/i18n/locales/en.jsonindex 03156b22a..e73d453af 100644--- a/apps/browser-extension/src/i18n/locales/en.json+++ b/apps/browser-extension/src/i18n/locales/en.json@@ -17,6 +17,14 @@"twoFactorNote": "Note: if you don't have access to your authenticator device, you can reset your 2FA with a recovery code by logging in via the website.","masterPassword": "Master Password","unlockVault": "Unlock Vault",+ "unlockWithPin": "Unlock with PIN",+ "enterPin": "Enter Your PIN",+ "enterPinToUnlock": "Enter your PIN to unlock your vault",+ "pinPlaceholder": "••••",+ "unlock": "Unlock",+ "usePassword": "Use Password",+ "useMasterPassword": "Use Master Password",+ "pinUnlockTip": "You can also type your PIN using your keyboard","unlockTitle": "Unlock Your Vault","unlockDescription": "Enter your master password to unlock your vault.","logout": "Logout",@@ -52,6 +60,7 @@"error": "Error","success": "Success","cancel": "Cancel",+ "confirm": "Confirm","back": "Back","use": "Use","delete": "Delete",@@ -304,6 +313,9 @@"openWebApp": "Open web app","loggedIn": "Logged in","logout": "Logout",+ "lock": "Lock",+ "logoutConfirmTitle": "Confirm Logout",+ "logoutConfirmMessage": "Are you sure you want to logout? You will need to log in again to access your vault.","globalSettings": "Global Settings","autofillPopup": "Autofill popup","activeOnAllSites": "Active on all sites (unless disabled below)",@@ -378,6 +390,49 @@"apiUrlInvalid": "Please enter a valid API URL","clientUrlRequired": "Client URL is required","clientUrlInvalid": "Please enter a valid client URL"+ },+ "unlockMethod": {+ "title": "Vault Unlock Method",+ "methods": "Unlock Methods",+ "helpText": "Choose how you want to unlock your vault. You can use your master password (always available) or set up a quick 4-8 digit PIN for faster access. After 4 failed PIN attempts, you'll need to use your master password.",+ "password": "Master Password",+ "passwordDescription": "Always available as fallback",+ "alwaysEnabled": "Always Enabled",+ "enabled": "Enabled",+ "disabled": "Disabled",+ "pin": "PIN Code",+ "pinDescription": "Unlock vault with PIN code",+ "pinEnabled": "Quick unlock with PIN enabled",+ "pinDisabled": "Use master password to unlock",+ "pinLockedDescription": "PIN locked after too many failed attempts",+ "enablePin": "Enable PIN Unlock",+ "disablePin": "Disable PIN Unlock",+ "resetPin": "Reset PIN",+ "testPin": "Test PIN",+ "setupPin": "Setup PIN Code",+ "setupPinDescription": "Enter a 4-8 digit PIN that you'll use to quickly unlock your vault. Your vault encryption key will be encrypted with this PIN and stored locally.",+ "enterNewPin": "Enter new PIN (4-8 digits)",+ "enterNewPinDescription": "Choose a 4-8 digit PIN code",+ "confirmPin": "Confirm PIN",+ "confirmPinTitle": "Confirm Your PIN",+ "confirmPinDescription": "Enter your PIN again to confirm",+ "confirm": "Confirm",+ "next": "Next",+ "back": "Back",+ "pinPlaceholder": "••••",+ "enterPinToTest": "Enter your PIN to test:",+ "invalidPinFormat": "PIN must be 4-8 digits",+ "pinMismatch": "PINs do not match",+ "enableSuccess": "PIN unlock enabled successfully!",+ "enableError": "Failed to enable PIN unlock. Please try again.",+ "disableSuccess": "PIN unlock disabled successfully.",+ "disableError": "Failed to disable PIN unlock. Please try again.",+ "testSuccess": "PIN is correct!",+ "testError": "Incorrect PIN.",+ "loadError": "Failed to load unlock method settings.",+ "unlockVaultFirst": "Please unlock your vault with your master password first.",+ "pinLocked": "PIN unlock has been disabled after 4 failed attempts. Please use your master password to unlock your vault.",+ "failedAttempts": "failed attempts"}},"passkeys": {diff --git a/apps/browser-extension/src/utils/PinUnlockService.ts b/apps/browser-extension/src/utils/PinUnlockService.tsnew file mode 100644index 000000000..e5afafe3b--- /dev/null+++ b/apps/browser-extension/src/utils/PinUnlockService.ts@@ -0,0 +1,292 @@+/**+ * PinUnlockService - Handles PIN-based vault unlock+ *+ * This service allows users to set a 4-8 digit PIN to unlock their vault instead+ * of entering their full master password. The vault encryption key is encrypted+ * with a key derived from the PIN and stored locally.+ *+ * Security features:+ * - 4 failed attempts maximum before requiring full password+ * - PIN must be 4-8 digits+ * - Encryption key derived using PBKDF2 with random salt+ * - Failed attempts counter stored separately+ */++const PIN_ENABLED_KEY = 'aliasvault_pin_enabled';+const PIN_ENCRYPTED_KEY_KEY = 'aliasvault_pin_encrypted_key';+const PIN_SALT_KEY = 'aliasvault_pin_salt';+const PIN_LENGTH_KEY = 'aliasvault_pin_length';+const PIN_FAILED_ATTEMPTS_KEY = 'aliasvault_pin_failed_attempts';+const MAX_PIN_ATTEMPTS = 4;+const MIN_PIN_LENGTH = 4;+const MAX_PIN_LENGTH = 8;++/**+ * Error thrown when PIN is locked after too many failed attempts.+ */+export class PinLockedError extends Error {+ /**+ * Creates a new instance of PinLockedError.+ * @param message - The error message.+ */+ public constructor(message: string = 'PIN locked after too many failed attempts') {+ super(message);+ this.name = 'PinLockedError';+ }+}++/**+ * Check if PIN unlock is enabled+ */+export async function isPinEnabled(): Promise<boolean> {+ try {+ const result = await chrome.storage.local.get([PIN_ENABLED_KEY]);+ return result[PIN_ENABLED_KEY] === true;+ } catch {+ return false;+ }+}++/**+ * Get the length of the configured PIN+ */+export async function getPinLength(): Promise<number | null> {+ try {+ const result = await chrome.storage.local.get([PIN_LENGTH_KEY]);+ return result[PIN_LENGTH_KEY] || null;+ } catch {+ return null;+ }+}++/**+ * Validate PIN format (4-8 digits)+ */+export function isValidPin(pin: string): boolean {+ const pinRegex = /^\d{4,8}$/;+ return pinRegex.test(pin);+}++/**+ * Get failed attempts count+ */+export async function getFailedAttempts(): Promise<number> {+ try {+ const result = await chrome.storage.local.get([PIN_FAILED_ATTEMPTS_KEY]);+ return result[PIN_FAILED_ATTEMPTS_KEY] || 0;+ } catch {+ return 0;+ }+}++/**+ * Check if PIN attempts are exhausted+ */+export async function isPinLocked(): Promise<boolean> {+ const attempts = await getFailedAttempts();+ return attempts >= MAX_PIN_ATTEMPTS;+}++/**+ * Setup PIN unlock+ * Encrypts the vault encryption key with the PIN and stores it+ *+ * @param pin - The PIN to set (4-8 digits)+ * @param vaultEncryptionKey - The base64-encoded vault encryption key to protect+ */+export async function setupPin(pin: string, vaultEncryptionKey: string): Promise<void> {+ if (!isValidPin(pin)) {+ throw new Error(`PIN must be ${MIN_PIN_LENGTH}-${MAX_PIN_LENGTH} digits`);+ }++ try {+ // Generate random salt+ const salt = crypto.getRandomValues(new Uint8Array(16));+ const saltBase64 = arrayBufferToBase64(salt.buffer);++ // Derive key from PIN using PBKDF2+ const pinKey = await derivePinKey(pin, salt);++ // Encrypt the vault encryption key+ const iv = crypto.getRandomValues(new Uint8Array(12));+ const encryptedKey = await crypto.subtle.encrypt(+ { name: 'AES-GCM', iv },+ pinKey,+ new TextEncoder().encode(vaultEncryptionKey)+ );++ // Combine IV + encrypted data+ const combined = new Uint8Array(iv.length + encryptedKey.byteLength);+ combined.set(iv, 0);+ combined.set(new Uint8Array(encryptedKey), iv.length);+ const encryptedKeyBase64 = arrayBufferToBase64(combined.buffer);++ // Store encrypted key, salt, PIN length, and enable flag+ await chrome.storage.local.set({+ [PIN_ENABLED_KEY]: true,+ [PIN_ENCRYPTED_KEY_KEY]: encryptedKeyBase64,+ [PIN_SALT_KEY]: saltBase64,+ [PIN_LENGTH_KEY]: pin.length,+ [PIN_FAILED_ATTEMPTS_KEY]: 0+ });++ } catch (error: unknown) {+ if (error instanceof Error) {+ throw new Error(`Failed to setup PIN: ${error.message}`);+ }+ throw new Error('Failed to setup PIN');+ }+}++/**+ * Unlock with PIN+ * Returns the decrypted vault encryption key+ *+ * @param pin - The PIN to use for unlocking+ * @returns The decrypted vault encryption key (base64)+ */+export async function unlockWithPin(pin: string): Promise<string> {+ if (!isValidPin(pin)) {+ throw new Error('Invalid PIN format');+ }++ // Check if locked due to too many attempts+ if (await isPinLocked()) {+ throw new Error('Too many failed attempts. Please use your master password.');+ }++ try {+ // Get stored data+ const result = await chrome.storage.local.get([+ PIN_ENCRYPTED_KEY_KEY,+ PIN_SALT_KEY,+ PIN_FAILED_ATTEMPTS_KEY+ ]);++ const encryptedKeyBase64 = result[PIN_ENCRYPTED_KEY_KEY];+ const saltBase64 = result[PIN_SALT_KEY];++ if (!encryptedKeyBase64 || !saltBase64) {+ throw new Error('PIN unlock is not configured');+ }++ // Decode encrypted package+ const combined = new Uint8Array(base64ToArrayBuffer(encryptedKeyBase64));+ const iv = combined.slice(0, 12);+ const encryptedData = combined.slice(12);++ // Derive key from PIN+ const salt = new Uint8Array(base64ToArrayBuffer(saltBase64));+ const pinKey = await derivePinKey(pin, salt);++ // Decrypt the vault encryption key+ const decryptedData = await crypto.subtle.decrypt(+ { name: 'AES-GCM', iv },+ pinKey,+ encryptedData+ );++ const vaultEncryptionKey = new TextDecoder().decode(decryptedData);++ // Reset failed attempts on success+ await chrome.storage.local.set({ [PIN_FAILED_ATTEMPTS_KEY]: 0 });++ return vaultEncryptionKey;+ } catch {+ // Increment failed attempts+ const currentAttempts = await getFailedAttempts();+ const newAttempts = currentAttempts + 1;+ await chrome.storage.local.set({ [PIN_FAILED_ATTEMPTS_KEY]: newAttempts });++ // If max attempts reached, disable PIN and clear stored data+ if (newAttempts >= MAX_PIN_ATTEMPTS) {+ throw new PinLockedError();+ }++ throw new Error(`Incorrect PIN. ${MAX_PIN_ATTEMPTS - newAttempts} attempts remaining.`);+ }+}++/**+ * Disable PIN unlock and clear all stored data+ */+export async function disablePin(): Promise<void> {+ try {+ await chrome.storage.local.remove([+ PIN_ENABLED_KEY,+ PIN_ENCRYPTED_KEY_KEY,+ PIN_SALT_KEY,+ PIN_LENGTH_KEY,+ PIN_FAILED_ATTEMPTS_KEY+ ]);+ } catch (error) {+ console.error('[PinUnlockService] Failed to disable PIN:', error);+ throw error;+ }+}++/**+ * Reset failed attempts counter+ * Called after successful password unlock+ */+export async function resetFailedAttempts(): Promise<void> {+ try {+ await chrome.storage.local.set({ [PIN_FAILED_ATTEMPTS_KEY]: 0 });+ } catch (error) {+ console.error('[PinUnlockService] Failed to reset failed attempts:', error);+ }+}++/**+ * Derive encryption key from PIN using PBKDF2+ */+async function derivePinKey(pin: string, salt: Uint8Array): Promise<CryptoKey> {+ // Import PIN as key material+ const pinMaterial = await crypto.subtle.importKey(+ 'raw',+ new TextEncoder().encode(pin),+ 'PBKDF2',+ false,+ ['deriveKey']+ );++ // Derive AES-GCM key using PBKDF2+ const pinKey = await crypto.subtle.deriveKey(+ {+ name: 'PBKDF2',+ salt: salt,+ iterations: 100000, // 100k iterations for security+ hash: 'SHA-256'+ },+ pinMaterial,+ { name: 'AES-GCM', length: 256 },+ false,+ ['encrypt', 'decrypt']+ );++ return pinKey;+}++/**+ * Convert ArrayBuffer to base64 string+ */+function arrayBufferToBase64(buffer: ArrayBuffer): string {+ const bytes = new Uint8Array(buffer);+ let binary = '';+ for (let i = 0; i < bytes.byteLength; i++) {+ binary += String.fromCharCode(bytes[i]);+ }+ return btoa(binary);+}++/**+ * Convert base64 string to ArrayBuffer+ */+function base64ToArrayBuffer(base64: string): ArrayBuffer {+ const binary = atob(base64);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) {+ bytes[i] = binary.charCodeAt(i);+ }+ return bytes.buffer;+}