Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add clickjacking prevention measures through ClickValidator.ts (#1142)
Leendert de Borstf7850630657f
diff --git a/apps/browser-extension/src/entrypoints/contentScript/Form.ts b/apps/browser-extension/src/entrypoints/contentScript/Form.tsindex 2552eb420..35867e503 100644--- a/apps/browser-extension/src/entrypoints/contentScript/Form.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/Form.ts@@ -5,6 +5,7 @@ import { openAutofillPopup } from '@/entrypoints/contentScript/Popup';import type { Credential } from '@/utils/dist/shared/models/vault';import { FormDetector } from '@/utils/formDetector/FormDetector';import { FormFiller } from '@/utils/formDetector/FormFiller';+import { ClickValidator } from '@/utils/security/ClickValidator';/*** Global timestamp to track popup debounce time.@@ -14,6 +15,11 @@ import { FormFiller } from '@/utils/formDetector/FormFiller';*/let popupDebounceTime = 0;+/**+ * ClickValidator instance for form security validation+ */+const clickValidator = ClickValidator.getInstance();+/*** Check if popup can be shown based on debounce time.*/@@ -84,7 +90,7 @@ export function validateInputField(element: Element | null): { isValid: boolean;* @param credential - The credential to fill.* @param input - The input element that triggered the popup. Required when filling credentials to know which form to fill.*/-export function fillCredential(credential: Credential, input: HTMLInputElement) : void {+export async function fillCredential(credential: Credential, input: HTMLInputElement): Promise<void> {// Set debounce time to 300ms to prevent the popup from being shown again within 300ms because of autofill events.hidePopupFor(300);@@ -102,7 +108,7 @@ export function fillCredential(credential: Credential, input: HTMLInputElement)}const formFiller = new FormFiller(form, triggerInputEvents);- formFiller.fillFields(credential);+ await formFiller.fillFields(credential);}/**@@ -215,9 +221,16 @@ export function injectIcon(input: HTMLInputElement, container: HTMLElement): voiwindow.addEventListener('resize', updateIconPosition);// Add click event to trigger the autofill popup and refocus the input- icon.addEventListener('click', (e: MouseEvent) => {+ icon.addEventListener('click', async (e: MouseEvent) => {e.preventDefault();e.stopPropagation();++ // Validate the click for security+ if (!await clickValidator.validateClick(e)) {+ console.warn('[AliasVault Security] Blocked autofill popup opening due to security validation failure');+ return;+ }+setTimeout(() => actualInput.focus(), 0);openAutofillPopup(actualInput, container);});diff --git a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts b/apps/browser-extension/src/entrypoints/contentScript/Popup.tsindex 0af0c8a7d..9cf8781c6 100644--- a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/Popup.ts@@ -8,6 +8,7 @@ import { CreateIdentityGenerator } from '@/utils/dist/shared/identity-generator'import type { Credential } from '@/utils/dist/shared/models/vault';import { CreatePasswordGenerator, PasswordGenerator, PasswordSettings } from '@/utils/dist/shared/password-generator';import { FormDetector } from '@/utils/formDetector/FormDetector';+import { ClickValidator } from '@/utils/security/ClickValidator';import { SqliteClient } from '@/utils/SqliteClient';import { CredentialsResponse } from '@/utils/types/messaging/CredentialsResponse';import { IdentitySettingsResponse } from '@/utils/types/messaging/IdentitySettingsResponse';@@ -23,6 +24,11 @@ import { storage } from '#imports';*/let popupListeners = new WeakMap<HTMLElement, EventListener>();+/**+ * Global ClickValidator instance for content script security+ */+const clickValidator = ClickValidator.getInstance();+/*** Open (or refresh) the autofill popup including check if vault is locked.*/@@ -318,7 +324,7 @@ export async function createAutofillPopup(input: HTMLInputElement, credentials:}};- // Add click listener with capture and prevent removal.+ // Add click listener with capture and prevent removal and security validation.addReliableClickHandler(createButton, handleCreateClick);// Create search container.@@ -439,7 +445,7 @@ export async function createAutofillPopup(input: HTMLInputElement, credentials:addReliableClickHandler(contextMenu, handleContextMenuClick);};- // Add click handlers+ // Add click handlers with security validationaddReliableClickHandler(closeButton, (e: Event) => {handleCloseClick(e);});@@ -492,7 +498,7 @@ export async function createVaultLockedPopup(input: HTMLInputElement, rootContaiconst container = document.createElement('div');container.className = 'av-vault-locked-container';- // Make the entire container clickable+ // Make the entire container clickable with security validationaddReliableClickHandler(container, handleUnlockClick);container.style.cursor = 'pointer';@@ -534,7 +540,7 @@ export async function createVaultLockedPopup(input: HTMLInputElement, rootContaicloseButton.style.top = '50%';closeButton.style.transform = 'translateY(-50%)';- // Handle close button click+ // Handle close button click with security validationaddReliableClickHandler(closeButton, async (e) => {e.stopPropagation(); // Prevent opening the unlock popupawait dismissVaultLockedPopup();@@ -681,7 +687,7 @@ function createCredentialList(credentials: Credential[], input: HTMLInputElement</svg>`;- // Handle popout click+ // Handle popout click with security validationaddReliableClickHandler(popoutIcon, (e) => {e.stopPropagation(); // Prevent credential fillsendMessage('OPEN_POPUP_WITH_CREDENTIAL', { credentialId: cred.Id }, 'background');@@ -691,7 +697,7 @@ function createCredentialList(credentials: Credential[], input: HTMLInputElementitem.appendChild(credentialInfo);item.appendChild(popoutIcon);- // Update click handler to only trigger on credentialInfo+ // Update click handler to only trigger on credentialInfo with security validationaddReliableClickHandler(credentialInfo, () => {fillCredential(cred, input);removeExistingPopup(rootContainer);@@ -1706,14 +1712,32 @@ function getValidServiceUrl(): string {/*** Add click handler with mousedown/mouseup backup for better click reliability in shadow DOM.+ * Now includes optional security validation.** Some websites due to their design cause the AliasVault autofill to re-trigger when clicking* outside of the input field, which causes the AliasVault popup to close before the click event* is registered. This is a workaround to ensure the click event is always registered.*/-function addReliableClickHandler(element: HTMLElement, handler: (e: Event) => void): void {+function addReliableClickHandler(+ element: HTMLElement,+ handler: (e: Event) => void+): void {+ /**+ * Secure wrapper that validates clicks before executing handler+ */+ const secureHandler = async (e: Event): Promise<void> => {+ const mouseEvent = e as MouseEvent;++ if (!await clickValidator.validateClick(mouseEvent)) {+ console.warn(`[AliasVault Security] Blocked click action due to security validation failure`);+ return;+ }++ handler(e);+ };+// Add primary click listener with capture and prevent removal- element.addEventListener('click', handler, {+ element.addEventListener('click', secureHandler, {capture: true,passive: false});@@ -1726,11 +1750,11 @@ function addReliableClickHandler(element: HTMLElement, handler: (e: Event) => voisMouseDown = true;}, { capture: true });- element.addEventListener('mouseup', (e) => {+ element.addEventListener('mouseup', async (e) => {e.preventDefault();e.stopPropagation();if (isMouseDown) {- handler(e);+ await secureHandler(e);}isMouseDown = false;}, { capture: true });@@ -1755,7 +1779,6 @@ export async function createUpgradeRequiredPopup(input: HTMLInputElement, rootCoconst container = document.createElement('div');container.className = 'av-upgrade-required-container';- // Make the entire container clickableaddReliableClickHandler(container, handleUpgradeClick);container.style.cursor = 'pointer';diff --git a/apps/browser-extension/src/utils/formDetector/FormFiller.ts b/apps/browser-extension/src/utils/formDetector/FormFiller.tsindex dc7b4a697..301acc9e6 100644--- a/apps/browser-extension/src/utils/formDetector/FormFiller.ts+++ b/apps/browser-extension/src/utils/formDetector/FormFiller.ts@@ -2,10 +2,13 @@ import { Gender, IdentityHelperUtils } from "@/utils/dist/shared/identity-generaimport type { Credential } from "@/utils/dist/shared/models/vault";import { CombinedDateOptionPatterns, CombinedGenderOptionPatterns } from "@/utils/formDetector/FieldPatterns";import { FormFields } from "@/utils/formDetector/types/FormFields";+import { ClickValidator } from "@/utils/security/ClickValidator";/*** Class to fill the fields of a form with the given credential.*/export class FormFiller {+ private readonly clickValidator = ClickValidator.getInstance();+/*** Constructor.*/@@ -23,12 +26,223 @@ export class FormFiller {* Fill the fields of the form with the given credential.* @param credential The credential to fill the form with.*/- public fillFields(credential: Credential): void {+ public async fillFields(credential: Credential): Promise<void> {+ // Perform security validation before filling any fields+ if (!await this.validateFormSecurity()) {+ console.warn('[AliasVault Security] Autofill blocked due to security validation failure');+ return;+ }+this.fillBasicFields(credential);this.fillBirthdateFields(credential);this.fillGenderFields(credential);}+ /**+ * Validate form security to prevent autofill in potential clickjacking scenarios.+ * This method checks for various attack vectors including:+ * - Page-wide opacity manipulation+ * - Form field obstruction via overlays+ * - Suspicious element positioning+ * - Multiple forms with identical fields (potential decoy attacks)+ */+ private async validateFormSecurity(): Promise<boolean> {+ try {+ // Skip security validation in test environments where browser APIs may not be available+ if (typeof window === 'undefined' || typeof MouseEvent === 'undefined') {+ return true;+ }++ // 1. Check page-wide security using ClickValidator (detects body/HTML opacity tricks)+ const dummyEvent = new MouseEvent('click', {+ bubbles: true,+ cancelable: true,+ clientX: window.innerWidth / 2,+ clientY: window.innerHeight / 2+ });+ // Note: isTrusted is read-only and set by the browser++ if (!await this.clickValidator.validateClick(dummyEvent)) {+ console.warn('[AliasVault Security] Form autofill blocked: Page-wide attack detected');+ return false;+ }++ // 2. Check form field obstruction and positioning+ const formFields = this.getAllFormFields();+ for (const field of formFields) {+ if (!this.validateFieldSecurity(field)) {+ console.warn('[AliasVault Security] Form autofill blocked: Field obstruction detected', field);+ return false;+ }+ }++ // 3. Check for suspicious form duplication (decoy attack)+ if (this.detectDecoyForms()) {+ console.warn('[AliasVault Security] Form autofill blocked: Multiple suspicious forms detected');+ return false;+ }++ return true;+ } catch (error) {+ console.error('[AliasVault Security] Form security validation error:', error);+ return false; // Fail safely - block autofill if validation fails+ }+ }++ /**+ * Get all form fields that will be filled.+ */+ private getAllFormFields(): HTMLElement[] {+ const fields: HTMLElement[] = [];++ if (this.form.usernameField) {+ fields.push(this.form.usernameField);+ }+ if (this.form.passwordField) {+ fields.push(this.form.passwordField);+ }+ if (this.form.passwordConfirmField) {+ fields.push(this.form.passwordConfirmField);+ }+ if (this.form.emailField) {+ fields.push(this.form.emailField);+ }+ if (this.form.emailConfirmField) {+ fields.push(this.form.emailConfirmField);+ }++ return fields;+ }++ /**+ * Validate individual field security to detect obstruction attacks.+ */+ private validateFieldSecurity(field: HTMLElement): boolean {+ if (!field) {+ return true;+ }++ // Skip field validation in test environments where browser APIs may not be available+ if (typeof window === 'undefined' || typeof document === 'undefined' || !document.elementsFromPoint) {+ return true;+ }++ const rect = field.getBoundingClientRect();+ const centerX = rect.left + rect.width / 2;+ const centerY = rect.top + rect.height / 2;++ // Check if field is within viewport+ if (rect.width === 0 || rect.height === 0 ||+ centerX < 0 || centerY < 0 ||+ centerX > window.innerWidth || centerY > window.innerHeight) {+ console.warn('[AliasVault Security] Field outside viewport or zero-sized:', rect);+ return false;+ }++ // Use elementsFromPoint to check what's actually at the field center+ try {+ const elementsAtPoint = document.elementsFromPoint(centerX, centerY);++ if (elementsAtPoint.length === 0) {+ console.warn('[AliasVault Security] No elements found at field center');+ return false;+ }++ // Check if our field is in the element stack (or its parents/children)+ const fieldFound = elementsAtPoint.some(element =>+ element === field ||+ field.contains(element) ||+ element.contains(field)+ );++ if (!fieldFound) {+ console.warn('[AliasVault Security] Field is obstructed by other elements');+ return false;+ }++ // Check for suspicious covering elements+ const suspiciousCovering = elementsAtPoint.slice(0, 3).some(element => {+ if (element === field || field.contains(element) || element.contains(field)) {+ return false; // This is our field or related element+ }++ const style = getComputedStyle(element);++ // Check for nearly transparent overlays+ const opacity = parseFloat(style.opacity);+ if (opacity > 0 && opacity < 0.1) {+ console.warn('[AliasVault Security] Nearly transparent overlay detected:', element);+ return true;+ }++ // Check for high z-index elements (potential overlays)+ const zIndex = parseInt(style.zIndex) || 0;+ if (zIndex > 1000000) {+ console.warn('[AliasVault Security] Suspicious high z-index element:', element, zIndex);+ return true;+ }++ // Check for elements covering large areas (potential clickjacking overlays)+ const elementRect = element.getBoundingClientRect();+ if (elementRect.width >= window.innerWidth * 0.8 &&+ elementRect.height >= window.innerHeight * 0.8) {+ console.warn('[AliasVault Security] Large covering element detected:', element);+ return true;+ }++ return false;+ });++ return !suspiciousCovering;+ } catch (error) {+ console.warn('[AliasVault Security] Field validation error:', error);+ return false; // Fail safely+ }+ }++ /**+ * Detect potential decoy forms (multiple forms with similar fields).+ */+ private detectDecoyForms(): boolean {+ try {+ // Find all forms on the page+ const allForms = Array.from(document.querySelectorAll('form'));++ if (allForms.length <= 1) {+ return false; // Only one form, no decoy risk+ }++ let suspiciousFormCount = 0;++ for (const form of allForms) {+ const hasPasswordField = form.querySelector('input[type="password"]');+ const hasEmailField = form.querySelector('input[type="email"], input[name*="email" i], input[placeholder*="email" i]');+ const hasUsernameField = form.querySelector('input[type="text"], input[name*="user" i], input[placeholder*="user" i]');++ // Count forms with login-like patterns+ if (hasPasswordField && (hasEmailField || hasUsernameField)) {+ const formRect = form.getBoundingClientRect();+ const isVisible = formRect.width > 0 && formRect.height > 0;++ if (isVisible) {+ suspiciousFormCount++;+ }+ }+ }++ // If more than 2 visible login forms, it's suspicious+ if (suspiciousFormCount > 2) {+ console.warn('[AliasVault Security] Multiple login forms detected:', suspiciousFormCount);+ return true;+ }++ return false;+ } catch (error) {+ console.warn('[AliasVault Security] Decoy form detection error:', error);+ return false; // Don't block on detection errors+ }+ }+/*** Set value on an input element, handling both regular inputs and custom elements with shadow DOM.* @param element The element to set the value on@@ -324,13 +538,13 @@ export class FormFiller {private fillGenderFields(credential: Credential): void {switch (this.form.genderField.type) {case 'select':- this.fillGenderSelect(credential.Alias.Gender);+ this.fillGenderSelect(credential.Alias.Gender as Gender | undefined);break;case 'radio':- this.fillGenderRadio(credential.Alias.Gender);+ this.fillGenderRadio(credential.Alias.Gender as Gender | undefined);break;case 'text':- this.fillGenderText(credential.Alias.Gender);+ this.fillGenderText(credential.Alias.Gender as Gender | undefined);break;}}diff --git a/apps/browser-extension/src/utils/formDetector/__tests__/FormFiller.en.test.ts b/apps/browser-extension/src/utils/formDetector/__tests__/FormFiller.en.test.tsindex 20f7f96cc..f248e0155 100644--- a/apps/browser-extension/src/utils/formDetector/__tests__/FormFiller.en.test.ts+++ b/apps/browser-extension/src/utils/formDetector/__tests__/FormFiller.en.test.ts@@ -29,7 +29,7 @@ describe('FormFiller English', () => {});describe('fillBirthdateFields with English month names', () => {- it('should fill separate fields with English month names', () => {+ it('should fill separate fields with English month names', async () => {const { daySelect, monthSelect, yearSelect } = createDateSelects(document);// Add month options with English month names@@ -52,7 +52,7 @@ describe('FormFiller English', () => {year: yearSelect as unknown as HTMLInputElement};- formFiller.fillFields(mockCredential);+ await formFiller.fillFields(mockCredential);expect(daySelect.value).toBe('03');expect(monthSelect.value).toBe('February');diff --git a/apps/browser-extension/src/utils/formDetector/__tests__/FormFiller.generic.test.ts b/apps/browser-extension/src/utils/formDetector/__tests__/FormFiller.generic.test.tsindex 050cc8857..90685f4c3 100644--- a/apps/browser-extension/src/utils/formDetector/__tests__/FormFiller.generic.test.ts+++ b/apps/browser-extension/src/utils/formDetector/__tests__/FormFiller.generic.test.ts@@ -29,17 +29,17 @@ describe('FormFiller', () => {});describe('fillBasicFields', () => {- it('should fill username', () => {- formFiller.fillFields(mockCredential);+ it('should fill username', async () => {+ await formFiller.fillFields(mockCredential);expect(formFields.usernameField?.value).toBe('testuser');expect(wasTriggerCalledFor(mockTriggerInputEvents, formFields.usernameField)).toBe(true);});- it('should fill email and confirmation fields', () => {+ it('should fill email and confirmation fields', async () => {formFields.emailConfirmField = document.createElement('input');- formFiller.fillFields(mockCredential);+ await formFiller.fillFields(mockCredential);expect(formFields.emailField?.value).toBe('[email protected]');expect(formFields.emailConfirmField?.value).toBe('[email protected]');@@ -47,12 +47,12 @@ describe('FormFiller', () => {expect(wasTriggerCalledFor(mockTriggerInputEvents, formFields.emailConfirmField)).toBe(true);});- it('should use username as email when no email is provided and no username field exists', () => {+ it('should use username as email when no email is provided and no username field exists', async () => {// Create a credential with an empty email stringconst credentialWithoutEmail = { ...mockCredential, Alias: { ...mockCredential.Alias, Email: '' } };formFields.usernameField = null;- formFiller.fillFields(credentialWithoutEmail);+ await formFiller.fillFields(credentialWithoutEmail);expect(formFields.emailField?.value).toBe('testuser');expect(wasTriggerCalledFor(mockTriggerInputEvents, formFields.emailField)).toBe(true);@@ -61,7 +61,7 @@ describe('FormFiller', () => {it('should fill password and confirmation fields', async () => {formFields.passwordConfirmField = document.createElement('input');- formFiller.fillFields(mockCredential);+ await formFiller.fillFields(mockCredential);// Delay for 150ms to ensure the password field is filled as it uses a small delay between each character.await new Promise(resolve => setTimeout(resolve, 150));@@ -72,8 +72,8 @@ describe('FormFiller', () => {expect(wasTriggerCalledFor(mockTriggerInputEvents, formFields.passwordConfirmField)).toBe(true);});- it('should fill name fields correctly', () => {- formFiller.fillFields(mockCredential);+ it('should fill name fields correctly', async () => {+ await formFiller.fillFields(mockCredential);expect(formFields.fullNameField?.value).toBe('John Doe');expect(formFields.firstNameField?.value).toBe('John');@@ -85,38 +85,38 @@ describe('FormFiller', () => {});describe('fillBirthdateFields', () => {- it('should fill single birthdate field with correct format', () => {- formFiller.fillFields(mockCredential);+ it('should fill single birthdate field with correct format', async () => {+ await formFiller.fillFields(mockCredential);expect(formFields.birthdateField.single?.value).toBe('1991-02-03');expect(wasTriggerCalledFor(mockTriggerInputEvents, formFields.birthdateField.single)).toBe(true);});- it('should handle different date formats (mm/dd/yyyy)', () => {+ it('should handle different date formats (mm/dd/yyyy)', async () => {formFields.birthdateField.format = 'mm/dd/yyyy';- formFiller.fillFields(mockCredential);+ await formFiller.fillFields(mockCredential);expect(formFields.birthdateField.single?.value).toBe('02/03/1991');});- it('should handle different date formats (dd/mm/yyyy)', () => {+ it('should handle different date formats (dd/mm/yyyy)', async () => {formFields.birthdateField.format = 'dd/mm/yyyy';- formFiller.fillFields(mockCredential);+ await formFiller.fillFields(mockCredential);expect(formFields.birthdateField.single?.value).toBe('03/02/1991');});- it('should handle different date formats (dd-mm-yyyy)', () => {+ it('should handle different date formats (dd-mm-yyyy)', async () => {formFields.birthdateField.format = 'dd-mm-yyyy';- formFiller.fillFields(mockCredential);+ await formFiller.fillFields(mockCredential);expect(formFields.birthdateField.single?.value).toBe('03-02-1991');});- it('should handle different date formats (mm-dd-yyyy)', () => {+ it('should handle different date formats (mm-dd-yyyy)', async () => {formFields.birthdateField.format = 'mm-dd-yyyy';- formFiller.fillFields(mockCredential);+ await formFiller.fillFields(mockCredential);expect(formFields.birthdateField.single?.value).toBe('02-03-1991');});- it('should fill separate day/month/year select fields', () => {+ it('should fill separate day/month/year select fields', async () => {const { daySelect, monthSelect, yearSelect } = createDateSelects(document);// Add month options (1-12)@@ -136,7 +136,7 @@ describe('FormFiller', () => {year: yearSelect as unknown as HTMLInputElement};- formFiller.fillFields(mockCredential);+ await formFiller.fillFields(mockCredential);expect(daySelect.value).toBe('03');expect(monthSelect.value).toBe('02');@@ -148,7 +148,7 @@ describe('FormFiller', () => {});describe('fillGenderFields', () => {- it('should fill gender select field', () => {+ it('should fill gender select field', async () => {const selectElement = document.createElement('select');// Add options using createElement@@ -167,13 +167,13 @@ describe('FormFiller', () => {field: selectElement};- formFiller.fillFields(mockCredential);+ await formFiller.fillFields(mockCredential);expect(selectElement.value).toBe('m');expect(wasTriggerCalledFor(mockTriggerInputEvents, selectElement)).toBe(true);});- it('should handle radio button gender fields', () => {+ it('should handle radio button gender fields', async () => {const maleRadio = document.createElement('input');maleRadio.type = 'radio';const femaleRadio = document.createElement('input');@@ -189,7 +189,7 @@ describe('FormFiller', () => {}};- formFiller.fillFields(mockCredential);+ await formFiller.fillFields(mockCredential);expect(maleRadio.checked).toBe(true);expect(femaleRadio.checked).toBe(false);diff --git a/apps/browser-extension/src/utils/formDetector/__tests__/FormFiller.nl.test.ts b/apps/browser-extension/src/utils/formDetector/__tests__/FormFiller.nl.test.tsindex 49dff5cba..e97e4459e 100644--- a/apps/browser-extension/src/utils/formDetector/__tests__/FormFiller.nl.test.ts+++ b/apps/browser-extension/src/utils/formDetector/__tests__/FormFiller.nl.test.ts@@ -29,7 +29,7 @@ describe('FormFiller Dutch', () => {});describe('fillBirthdateFields with Dutch month names', () => {- it('should fill separate fields with Dutch month names', () => {+ it('should fill separate fields with Dutch month names', async () => {const { daySelect, monthSelect, yearSelect } = createDateSelects(document);// Add month options with Dutch month names@@ -52,7 +52,7 @@ describe('FormFiller Dutch', () => {year: yearSelect as unknown as HTMLInputElement};- formFiller.fillFields(mockCredential);+ await formFiller.fillFields(mockCredential);expect(daySelect.value).toBe('03');expect(monthSelect.value).toBe('Februari');diff --git a/apps/browser-extension/src/utils/security/ClickValidator.ts b/apps/browser-extension/src/utils/security/ClickValidator.tsnew file mode 100644index 000000000..e0e521afa--- /dev/null+++ b/apps/browser-extension/src/utils/security/ClickValidator.ts@@ -0,0 +1,133 @@+/**+ * ClickValidator - Simplified click validation system for content script security+ *+ * Validates user clicks with focus on content script shadow DOM scenarios:+ * - Detection of page-wide opacity tricks on BODY/HTML+ * - Basic gesture authenticity validation+ */+export class ClickValidator {+ private static instance: ClickValidator | null = null;++ /**+ * Get or create singleton instance+ */+ public static getInstance(): ClickValidator {+ if (!ClickValidator.instance) {+ ClickValidator.instance = new ClickValidator();+ }+ return ClickValidator.instance;+ }++ /**+ * Validate a click event (simplified for content scripts)+ */+ public async validateClick(event: MouseEvent): Promise<boolean> {++ try {+ // 1. Check for page-wide opacity tricks on BODY/HTML+ const opacityTrickResult = this.detectPageOpacityTricks();++ if (opacityTrickResult.detected) {+ return false;+ }++ // 2. Basic gesture validation+ const gestureResult = this.validateGesture(event);++ if (!gestureResult.valid) {+ return false;+ }++ return true;++ } catch (error) {+ console.error('[AliasVault Security] Click validation error:', error);+ return false;+ }+ }++ /**+ * Detect page-wide opacity tricks on BODY/HTML elements+ */+ private detectPageOpacityTricks(): { detected: boolean; reason?: string } {+ try {+ const html = document.documentElement;+ const body = document.body;++ // Check HTML element opacity+ if (html) {+ const htmlStyle = getComputedStyle(html);+ const htmlOpacity = parseFloat(htmlStyle.opacity);++ if (htmlOpacity < 0.9) {+ return {+ detected: true,+ reason: `HTML element opacity reduced to ${htmlOpacity} - potential clickjacking attempt`+ };+ }++ // Check for CSS filters that could obscure content+ if (htmlStyle.filter && htmlStyle.filter !== 'none') {+ return {+ detected: true,+ reason: `HTML element has CSS filter applied: ${htmlStyle.filter} - potential visual manipulation`+ };+ }+ }++ // Check BODY element opacity+ if (body) {+ const bodyStyle = getComputedStyle(body);+ const bodyOpacity = parseFloat(bodyStyle.opacity);++ if (bodyOpacity < 0.9) {+ return {+ detected: true,+ reason: `BODY element opacity reduced to ${bodyOpacity} - potential clickjacking attempt`+ };+ }++ // Check for CSS filters on body+ if (bodyStyle.filter && bodyStyle.filter !== 'none') {+ return {+ detected: true,+ reason: `BODY element has CSS filter applied: ${bodyStyle.filter} - potential visual manipulation`+ };+ }+ }++ return { detected: false };+ } catch (error) {+ return {+ detected: true,+ reason: `Error checking page opacity: ${error}`+ };+ }+ }++ /**+ * Validate gesture characteristics for human-like behavior+ */+ private validateGesture(event: MouseEvent): { valid: boolean; reason?: string } {+ // Check for basic gesture properties++ // Mouse events should have reasonable coordinates+ if (event.clientX < 0 || event.clientY < 0 ||+ event.clientX > window.innerWidth || event.clientY > window.innerHeight) {+ return {+ valid: false,+ reason: 'Click coordinates outside viewport'+ };+ }++ // Check for reasonable button values+ if (event.button !== 0) { // Only left-click should trigger credentials+ return {+ valid: false,+ reason: `Non-left-click detected: button ${event.button}`+ };+ }++ return { valid: true };+ }+}diff --git a/apps/browser-extension/src/utils/security/__tests__/clickjacking-test.html b/apps/browser-extension/src/utils/security/__tests__/clickjacking-test.htmlnew file mode 100644index 000000000..6f1b8c47b--- /dev/null+++ b/apps/browser-extension/src/utils/security/__tests__/clickjacking-test.html@@ -0,0 +1,286 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>ClickValidator Security Test - Clickjacking Attack Vectors</title>+ <style>+ body {+ font-family: Arial, sans-serif;+ margin: 20px;+ line-height: 1.6;+ }+ .test-section {+ border: 2px solid #333;+ margin: 20px 0;+ padding: 20px;+ background: #f9f9f9;+ }+ .test-description {+ background: #fff3cd;+ border: 1px solid #ffeaa7;+ padding: 10px;+ margin-bottom: 15px;+ border-radius: 4px;+ }+ .attack-button {+ background: #dc3545;+ color: white;+ padding: 10px 20px;+ border: none;+ border-radius: 4px;+ cursor: pointer;+ font-size: 16px;+ margin: 5px;+ }+ .legit-button {+ background: #28a745;+ color: white;+ padding: 10px 20px;+ border: none;+ border-radius: 4px;+ cursor: pointer;+ font-size: 16px;+ margin: 5px;+ }+ .control-panel {+ position: fixed;+ top: 10px;+ right: 10px;+ background: rgba(0,0,0,0.8);+ color: white;+ padding: 15px;+ border-radius: 8px;+ z-index: 10000;+ }+ .control-panel button {+ display: block;+ margin: 5px 0;+ padding: 8px 12px;+ background: #007bff;+ color: white;+ border: none;+ border-radius: 4px;+ cursor: pointer;+ }+ .input-field {+ width: 200px;+ padding: 8px;+ margin: 5px;+ border: 1px solid #ccc;+ border-radius: 4px;+ }++ /* Attack Vector Styles */+ .body-opacity-attack {+ /* This will be applied dynamically */+ }++ .overlay-attack {+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ background: rgba(255, 255, 255, 0.01);+ z-index: 9999;+ pointer-events: auto;+ display: none;+ }++ .invisible-overlay {+ position: absolute;+ background: transparent;+ z-index: 1000;+ pointer-events: auto;+ }++ .filter-attack {+ /* This will be applied dynamically */+ }++ </style>+</head>+<body>+ <div class="control-panel">+ <h3>Attack Controls</h3>+ <button onclick="toggleBodyOpacity()">Toggle Body Opacity Attack</button>+ <button onclick="toggleHtmlOpacity()">Toggle HTML Opacity Attack</button>+ <button onclick="toggleCssFilter()">Toggle CSS Filter Attack</button>+ <button onclick="toggleInvisibleOverlay()">Toggle Invisible Overlay</button>+ <button onclick="simulateRapidClicks()">Simulate Rapid Clicks</button>+ <button onclick="simulatePreciseClicks()">Simulate Precise Clicks</button>+ <button onclick="triggerUntrustedEvent()">Trigger Untrusted Event</button>+ <button onclick="resetAllAttacks()">Reset All Attacks</button>+ </div>++ <!-- Invisible overlay for clickjacking -->+ <div class="overlay-attack" id="invisibleOverlay"></div>++ <h1>ClickValidator Security Test Suite</h1>+ <p>This page contains various clickjacking attack vectors to test the AliasVault ClickValidator security measures.</p>++ <!-- Test Section 1: Body Opacity Attack -->+ <div class="test-section">+ <div class="test-description">+ <strong>Attack Vector 1: Body Opacity Reduction</strong><br>+ This attack reduces the body element's opacity to make the entire page semi-transparent, potentially hiding malicious overlays.+ </div>+ <input type="text" class="input-field" placeholder="Enter username..." />+ <input type="password" class="input-field" placeholder="Enter password..." />+ <button class="attack-button">Fill Credentials (Should be blocked when opacity < 0.9)</button>+ <button class="legit-button" onclick="logAction('Legitimate action')">Legitimate Action</button>+ </div>++ <!-- Test Section 2: HTML Element Opacity Attack -->+ <div class="test-section">+ <div class="test-description">+ <strong>Attack Vector 2: HTML Element Opacity Reduction</strong><br>+ This attack reduces the HTML root element's opacity to make the entire document semi-transparent.+ </div>+ <input type="text" class="input-field" placeholder="Enter email..." />+ <button class="attack-button">Fill Email (Should be blocked when HTML opacity < 0.9)</button>+ <button class="legit-button" onclick="logAction('Legitimate HTML test')">Legitimate Action</button>+ </div>++ <!-- Test Section 3: CSS Filter Attack -->+ <div class="test-section">+ <div class="test-description">+ <strong>Attack Vector 3: CSS Filter Manipulation</strong><br>+ This attack applies CSS filters (blur, brightness, etc.) to obscure content and hide malicious elements.+ </div>+ <input type="text" class="input-field" placeholder="Enter data..." />+ <button class="attack-button">Submit Data (Should be blocked when filters applied)</button>+ <button class="legit-button" onclick="logAction('Legitimate filter test')">Legitimate Action</button>+ </div>++ <!-- Test Section 4: Invisible Overlay Attack -->+ <div class="test-section">+ <div class="test-description">+ <strong>Attack Vector 4: Invisible Overlay</strong><br>+ This attack places an nearly invisible overlay over the entire page to intercept clicks.+ </div>+ <input type="text" class="input-field" placeholder="Enter credit card..." />+ <button class="attack-button">Process Payment (Should be blocked when overlay active)</button>+ <button class="legit-button" onclick="logAction('Legitimate overlay test')">Legitimate Action</button>+ </div>+++ <!-- Log Display -->+ <div class="test-section">+ <h3>Action Log</h3>+ <div id="actionLog" style="background: #f8f9fa; padding: 10px; border: 1px solid #dee2e6; height: 200px; overflow-y: scroll;"></div>+ <button onclick="clearLog()" class="legit-button">Clear Log</button>+ </div>++ <script>+ let attackStates = {+ bodyOpacity: false,+ htmlOpacity: false,+ cssFilter: false,+ invisibleOverlay: false+ };++ function logAction(action) {+ const timestamp = new Date().toLocaleTimeString();+ const logEntry = `[${timestamp}] ${action}`;+ const logDiv = document.getElementById('actionLog');+ logDiv.innerHTML += logEntry + '<br>';+ logDiv.scrollTop = logDiv.scrollHeight;+ console.log(logEntry);+ }++ function clearLog() {+ document.getElementById('actionLog').innerHTML = '';+ }++ function toggleBodyOpacity() {+ const body = document.body;+ if (!attackStates.bodyOpacity) {+ body.style.opacity = '0.5';+ attackStates.bodyOpacity = true;+ logAction('✅ ATTACK: Body opacity reduced to 0.5 (should be detected)');+ } else {+ body.style.opacity = '1';+ attackStates.bodyOpacity = false;+ logAction('❌ Body opacity restored to 1.0');+ }+ }++ function toggleHtmlOpacity() {+ const html = document.documentElement;+ if (!attackStates.htmlOpacity) {+ html.style.opacity = '0.7';+ attackStates.htmlOpacity = true;+ logAction('✅ ATTACK: HTML opacity reduced to 0.7 (should be detected)');+ } else {+ html.style.opacity = '1';+ attackStates.htmlOpacity = false;+ logAction('❌ HTML opacity restored to 1.0');+ }+ }++ function toggleCssFilter() {+ const body = document.body;+ if (!attackStates.cssFilter) {+ body.style.filter = 'blur(1px) brightness(0.8)';+ attackStates.cssFilter = true;+ logAction('✅ ATTACK: CSS filter applied (should be detected)');+ } else {+ body.style.filter = 'none';+ attackStates.cssFilter = false;+ logAction('❌ CSS filter removed');+ }+ }++ function toggleInvisibleOverlay() {+ const overlay = document.getElementById('invisibleOverlay');+ if (!attackStates.invisibleOverlay) {+ overlay.style.display = 'block';+ attackStates.invisibleOverlay = true;+ logAction('✅ ATTACK: Invisible overlay activated (clicks should be intercepted)');+ } else {+ overlay.style.display = 'none';+ attackStates.invisibleOverlay = false;+ logAction('❌ Invisible overlay deactivated');+ }+ }+++ function resetAllAttacks() {+ // Reset all visual attacks+ document.body.style.opacity = '1';+ document.body.style.filter = 'none';+ document.documentElement.style.opacity = '1';+ document.getElementById('invisibleOverlay').style.display = 'none';++ // Reset attack states+ attackStates = {+ bodyOpacity: false,+ htmlOpacity: false,+ cssFilter: false,+ invisibleOverlay: false+ };++ logAction('🔄 All attacks reset to normal state');+ }++ // Add click logging to all attack buttons+ document.querySelectorAll('.attack-button').forEach(button => {+ button.addEventListener('click', function(e) {+ logAction(`🔴 Attack button clicked: "${this.textContent}"`);+ });+ });++ document.querySelectorAll('.legit-button').forEach(button => {+ button.addEventListener('click', function(e) {+ logAction(`🟢 Legitimate button clicked: "${this.textContent}"`);+ });+ });++ // Log initial state+ logAction('📋 Clickjacking test page loaded - Ready for security testing');+ logAction('💡 Install AliasVault browser extension and test autofill security');+ </script>+</body>+</html>\ No newline at end of file