Skip to content

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

Add loginDetector tests (#1694)

Leendert de Borst4516cc9d9311
diff --git a/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.debouncing.test.ts b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.debouncing.test.ts
new file mode 100644
index 000000000..f976dcaf8
--- /dev/null
+++ b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.debouncing.test.ts
@@ -0,0 +1,120 @@
+import { describe, it, expect, afterEach, vi } from 'vitest';
+
+import { LoginDetector } from '../LoginDetector';
+
+import { createTestEnvironment, cleanupTestEnvironment, setGlobalWindow } from './TestUtils';
+
+describe('LoginDetector debouncing', () => {
+ let detector: LoginDetector;
+
+ afterEach(() => {
+ if (detector) {
+ detector.destroy();
+ }
+ cleanupTestEnvironment();
+ });
+
+ it('should debounce duplicate submissions within 5 seconds', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="text" id="username" value="testuser">
+ <input type="password" id="password" value="testpass">
+ <button type="submit">Login</button>
+ </form>
+ </body></html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+
+ // First submission
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+ vi.advanceTimersByTime(100);
+
+ // Second submission (should be debounced)
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+ vi.advanceTimersByTime(100);
+
+ // Third submission (should be debounced)
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+ vi.advanceTimersByTime(100);
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
+ it('should allow new submission with different password', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="text" id="username" value="testuser">
+ <input type="password" id="password" value="firstpass">
+ <button type="submit">Login</button>
+ </form>
+ </body></html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ const passwordInput = document.getElementById('password') as HTMLInputElement;
+
+ // First submission
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+ vi.advanceTimersByTime(100);
+
+ // Change password and submit again
+ passwordInput.value = 'secondpass';
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+ vi.advanceTimersByTime(100);
+
+ expect(callback).toHaveBeenCalledTimes(2);
+ expect(callback.mock.calls[0][0].password).toBe('firstpass');
+ expect(callback.mock.calls[1][0].password).toBe('secondpass');
+ });
+
+ it('should allow submission after 5 seconds have passed', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="text" id="username" value="testuser">
+ <input type="password" id="password" value="testpass">
+ <button type="submit">Login</button>
+ </form>
+ </body></html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+
+ // First submission
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+ vi.advanceTimersByTime(100);
+
+ // Wait 5+ seconds
+ vi.advanceTimersByTime(5000);
+
+ // Second submission (should be allowed)
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+ vi.advanceTimersByTime(100);
+
+ expect(callback).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.dynamicForms.test.ts b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.dynamicForms.test.ts
new file mode 100644
index 000000000..543d1dfd2
--- /dev/null
+++ b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.dynamicForms.test.ts
@@ -0,0 +1,101 @@
+import { describe, it, expect, afterEach, vi } from 'vitest';
+
+import { LoginDetector } from '../LoginDetector';
+
+import {
+ createTestEnvironment,
+ cleanupTestEnvironment,
+ setGlobalWindow,
+ setGlobalHTMLElements,
+ MockMutationObserver,
+} from './TestUtils';
+
+describe('LoginDetector dynamic form monitoring', () => {
+ let detector: LoginDetector;
+
+ afterEach(() => {
+ if (detector) {
+ detector.destroy();
+ }
+ cleanupTestEnvironment();
+ });
+
+ it('should monitor dynamically added forms when MutationObserver triggers', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body></body></html>
+ `);
+
+ setGlobalHTMLElements(window);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ // Dynamically add a form
+ const form = document.createElement('form');
+ form.innerHTML = `
+ <input type="text" id="username" value="dynamicuser">
+ <input type="password" id="password" value="dynamicpass">
+ <button type="submit">Login</button>
+ `;
+ document.body.appendChild(form);
+
+ // Get the MutationObserver and trigger it manually with the new form
+ const observer = (document.body as unknown as { __mutationObserver: MockMutationObserver }).__mutationObserver;
+ if (observer) {
+ observer.trigger([{
+ type: 'childList',
+ addedNodes: [form] as unknown as NodeList,
+ removedNodes: [] as unknown as NodeList,
+ target: document.body,
+ previousSibling: null,
+ nextSibling: null,
+ attributeName: null,
+ attributeNamespace: null,
+ oldValue: null,
+ }]);
+ }
+
+ vi.runAllTimers();
+
+ // Submit the dynamic form
+ form.dispatchEvent(new window.Event('submit', { bubbles: true }));
+ vi.runAllTimers();
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ expect(callback.mock.calls[0][0].username).toBe('dynamicuser');
+ });
+
+ it('should not add duplicate listeners to monitored forms', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="text" id="username" value="testuser">
+ <input type="password" id="password" value="testpass">
+ <button type="submit">Login</button>
+ </form>
+ </body></html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ // Re-trigger form monitoring (should be no-op)
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+
+ // Should only capture once despite potential duplicate initialization
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.errorHandling.test.ts b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.errorHandling.test.ts
new file mode 100644
index 000000000..a9c109f28
--- /dev/null
+++ b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.errorHandling.test.ts
@@ -0,0 +1,54 @@
+import { describe, it, expect, afterEach, vi } from 'vitest';
+
+import { LoginDetector } from '../LoginDetector';
+
+import { createTestEnvironment, cleanupTestEnvironment, setGlobalWindow } from './TestUtils';
+
+describe('LoginDetector error handling', () => {
+ let detector: LoginDetector;
+
+ afterEach(() => {
+ if (detector) {
+ detector.destroy();
+ }
+ cleanupTestEnvironment();
+ });
+
+ it('should continue calling other callbacks even if one throws', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="text" id="username" value="testuser">
+ <input type="password" id="password" value="testpass">
+ <button type="submit">Login</button>
+ </form>
+ </body></html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const errorCallback = vi.fn().mockImplementation(() => {
+ throw new Error('Callback error');
+ });
+ const successCallback = vi.fn();
+
+ // Spy on console.error
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ detector.onLoginCapture(errorCallback);
+ detector.onLoginCapture(successCallback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+
+ expect(errorCallback).toHaveBeenCalledTimes(1);
+ expect(successCallback).toHaveBeenCalledTimes(1);
+ expect(consoleSpy).toHaveBeenCalled();
+
+ consoleSpy.mockRestore();
+ });
+});
diff --git a/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.excludedDomains.test.ts b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.excludedDomains.test.ts
new file mode 100644
index 000000000..2a26d4ea1
--- /dev/null
+++ b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.excludedDomains.test.ts
@@ -0,0 +1,50 @@
+import { describe, it, expect, afterEach, vi } from 'vitest';
+
+import { LoginDetector } from '../LoginDetector';
+
+import { createTestEnvironment, cleanupTestEnvironment, setGlobalWindow } from './TestUtils';
+
+describe('LoginDetector excluded domains', () => {
+ let detector: LoginDetector;
+
+ afterEach(() => {
+ if (detector) {
+ detector.destroy();
+ }
+ cleanupTestEnvironment();
+ });
+
+ const excludedUrls = [
+ 'https://aliasvault.net/login',
+ 'https://subdomain.aliasvault.net/login',
+ 'https://127.0.0.1/login',
+ 'https://0.0.0.0/login',
+ ];
+
+ excludedUrls.forEach((url) => {
+ it(`should skip ${url}`, () => {
+ const { document, window } = createTestEnvironment(
+ `<html><body>
+ <form>
+ <input type="text" value="user">
+ <input type="password" value="pass">
+ </form>
+ </body></html>`,
+ url
+ );
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+ expect(callback).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.lifecycle.test.ts b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.lifecycle.test.ts
new file mode 100644
index 000000000..eeb92a4b7
--- /dev/null
+++ b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.lifecycle.test.ts
@@ -0,0 +1,173 @@
+import { describe, it, expect, afterEach, vi } from 'vitest';
+
+import { LoginDetector } from '../LoginDetector';
+
+import { createTestEnvironment, cleanupTestEnvironment, setGlobalWindow } from './TestUtils';
+
+describe('LoginDetector lifecycle', () => {
+ let detector: LoginDetector;
+
+ afterEach(() => {
+ if (detector) {
+ detector.destroy();
+ }
+ cleanupTestEnvironment();
+ });
+
+ describe('constructor', () => {
+ it('should create an instance with provided document', () => {
+ const { document, window } = createTestEnvironment('<html><body></body></html>');
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ expect(detector).toBeInstanceOf(LoginDetector);
+ });
+ });
+
+ describe('initialize', () => {
+ it('should not initialize twice', () => {
+ const { document, window } = createTestEnvironment('<html><body></body></html>');
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+ detector.initialize(); // Second call should be no-op
+
+ expect(detector).toBeInstanceOf(LoginDetector);
+ });
+
+ it('should skip initialization for excluded domains', () => {
+ const { document, window } = createTestEnvironment(
+ '<html><body><form><input type="password"></form></body></html>',
+ 'https://aliasvault.net/login'
+ );
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+ expect(callback).not.toHaveBeenCalled();
+ });
+
+ it('should skip initialization for localhost', () => {
+ const { document, window } = createTestEnvironment(
+ '<html><body><form><input type="password"></form></body></html>',
+ 'https://localhost/login'
+ );
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+ expect(callback).not.toHaveBeenCalled();
+ });
+
+ it('should skip initialization for HTTP (non-HTTPS) pages', () => {
+ const { document, window } = createTestEnvironment(
+ '<html><body><form><input type="password"></form></body></html>',
+ 'http://example.com/login'
+ );
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+ expect(callback).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('onLoginCapture', () => {
+ it('should register a callback and return unsubscribe function', () => {
+ const { document, window } = createTestEnvironment('<html><body></body></html>');
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ const callback = vi.fn();
+
+ const unsubscribe = detector.onLoginCapture(callback);
+
+ expect(typeof unsubscribe).toBe('function');
+
+ unsubscribe();
+ });
+
+ it('should allow multiple callbacks to be registered', () => {
+ const { document, window } = createTestEnvironment('<html><body></body></html>');
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ const callback1 = vi.fn();
+ const callback2 = vi.fn();
+
+ detector.onLoginCapture(callback1);
+ detector.onLoginCapture(callback2);
+
+ // Both should be registered (functionality tested in submission tests)
+ });
+ });
+
+ describe('destroy', () => {
+ it('should clean up resources', () => {
+ const { document, window } = createTestEnvironment('<html><body></body></html>');
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+ detector.destroy();
+
+ // After destroy, should be able to initialize again
+ detector.initialize();
+ });
+
+ it('should clear all callbacks', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="text" id="username" value="testuser">
+ <input type="password" id="password" value="testpass">
+ <button type="submit">Login</button>
+ </form>
+ </body></html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ detector.destroy();
+
+ // Reinitialize and submit - callback should not be called
+ detector.initialize();
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+ expect(callback).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.submission.test.ts b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.submission.test.ts
new file mode 100644
index 000000000..80eeb5a12
--- /dev/null
+++ b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.submission.test.ts
@@ -0,0 +1,233 @@
+import { describe, it, expect, afterEach, vi } from 'vitest';
+
+import { LoginDetector } from '../LoginDetector';
+
+import { createTestEnvironment, cleanupTestEnvironment, setGlobalWindow } from './TestUtils';
+
+import type { CapturedLogin } from '../types';
+
+describe('LoginDetector form submission', () => {
+ let detector: LoginDetector;
+
+ afterEach(() => {
+ if (detector) {
+ detector.destroy();
+ }
+ cleanupTestEnvironment();
+ });
+
+ describe('credential capture', () => {
+ it('should capture login when form with username and password is submitted', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form id="login-form">
+ <input type="text" id="username" name="username" value="testuser">
+ <input type="password" id="password" name="password" value="testpass123">
+ <button type="submit">Login</button>
+ </form>
+ </body></html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+
+ expect(callback).toHaveBeenCalledTimes(1);
+
+ const capturedLogin: CapturedLogin = callback.mock.calls[0][0];
+ expect(capturedLogin.username).toBe('testuser');
+ expect(capturedLogin.password).toBe('testpass123');
+ expect(capturedLogin.domain).toBe('example.com');
+ expect(capturedLogin.url).toBe('https://example.com/login');
+ expect(capturedLogin.timestamp).toBeGreaterThan(0);
+ });
+
+ it('should capture login with email field as username', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="email" id="email" name="email" value="[email protected]">
+ <input type="password" id="password" name="password" value="password123">
+ <button type="submit">Login</button>
+ </form>
+ </body></html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ const capturedLogin: CapturedLogin = callback.mock.calls[0][0];
+ expect(capturedLogin.username).toBe('[email protected]');
+ });
+
+ it('should extract suggested name from page', () => {
+ const { document, window } = createTestEnvironment(`
+ <html>
+ <head><title>Login - My Awesome Service</title></head>
+ <body>
+ <form>
+ <input type="text" id="username" value="testuser">
+ <input type="password" id="password" value="testpass">
+ </form>
+ </body>
+ </html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ expect(callback.mock.calls[0][0].suggestedName).toBeDefined();
+ });
+ });
+
+ describe('empty fields', () => {
+ it('should not capture when password field is empty', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="text" id="username" value="testuser">
+ <input type="password" id="password" value="">
+ <button type="submit">Login</button>
+ </form>
+ </body></html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+
+ expect(callback).not.toHaveBeenCalled();
+ });
+
+ it('should not capture when username field is empty', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="text" id="username" value="">
+ <input type="password" id="password" value="testpass">
+ <button type="submit">Login</button>
+ </form>
+ </body></html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+
+ expect(callback).not.toHaveBeenCalled();
+ });
+
+ it('should not capture when form has no password field', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="text" id="username" value="testuser">
+ <input type="text" id="search" value="query">
+ <button type="submit">Search</button>
+ </form>
+ </body></html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+
+ expect(callback).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('multiple forms', () => {
+ it('should monitor multiple forms on the page', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form id="form1">
+ <input type="text" value="user1">
+ <input type="password" value="pass1">
+ </form>
+ <form id="form2">
+ <input type="text" value="user2">
+ <input type="password" value="pass2">
+ </form>
+ </body></html>
+ `);
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ // Submit first form
+ const form1 = document.getElementById('form1');
+ form1?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+ vi.advanceTimersByTime(100);
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ expect(callback.mock.calls[0][0].username).toBe('user1');
+
+ // Wait to avoid debouncing
+ vi.advanceTimersByTime(5000);
+
+ // Submit second form
+ const form2 = document.getElementById('form2');
+ form2?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+ vi.advanceTimersByTime(100);
+
+ expect(callback).toHaveBeenCalledTimes(2);
+ expect(callback.mock.calls[1][0].username).toBe('user2');
+ });
+ });
+});
diff --git a/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.visibility.test.ts b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.visibility.test.ts
new file mode 100644
index 000000000..244438cb3
--- /dev/null
+++ b/apps/browser-extension/src/utils/loginDetector/__tests__/LoginDetector.visibility.test.ts
@@ -0,0 +1,127 @@
+import { describe, it, expect, afterEach, vi } from 'vitest';
+
+import { LoginDetector } from '../LoginDetector';
+
+import { createTestEnvironment, cleanupTestEnvironment, setGlobalWindow } from './TestUtils';
+
+import type { CapturedLogin } from '../types';
+
+describe('LoginDetector visibility checks', () => {
+ let detector: LoginDetector;
+
+ afterEach(() => {
+ if (detector) {
+ detector.destroy();
+ }
+ cleanupTestEnvironment();
+ });
+
+ describe('hidden password fields', () => {
+ it('should skip password fields with display:none', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="text" id="username" value="testuser">
+ <input type="password" id="hidden-password" value="hiddenpass" style="display: none;">
+ <input type="password" id="visible-password" value="visiblepass">
+ <button type="submit">Login</button>
+ </form>
+ </body></html>
+ `);
+
+ window.getComputedStyle = vi.fn().mockImplementation((element: HTMLElement) => {
+ if (element.id === 'hidden-password') {
+ return { display: 'none', visibility: 'visible', opacity: '1' };
+ }
+ return { display: 'block', visibility: 'visible', opacity: '1' };
+ });
+
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ const capturedLogin: CapturedLogin = callback.mock.calls[0][0];
+ expect(capturedLogin.password).toBe('visiblepass');
+ });
+
+ it('should skip password fields with visibility:hidden', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="text" id="username" value="testuser">
+ <input type="password" id="hidden-password" value="hiddenpass">
+ <input type="password" id="visible-password" value="visiblepass">
+ </form>
+ </body></html>
+ `);
+
+ window.getComputedStyle = vi.fn().mockImplementation((element: HTMLElement) => {
+ if (element.id === 'hidden-password') {
+ return { display: 'block', visibility: 'hidden', opacity: '1' };
+ }
+ return { display: 'block', visibility: 'visible', opacity: '1' };
+ });
+
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ expect(callback.mock.calls[0][0].password).toBe('visiblepass');
+ });
+
+ it('should skip password fields with opacity:0', () => {
+ const { document, window } = createTestEnvironment(`
+ <html><body>
+ <form>
+ <input type="text" id="username" value="testuser">
+ <input type="password" id="hidden-password" value="hiddenpass">
+ <input type="password" id="visible-password" value="visiblepass">
+ </form>
+ </body></html>
+ `);
+
+ window.getComputedStyle = vi.fn().mockImplementation((element: HTMLElement) => {
+ if (element.id === 'hidden-password') {
+ return { display: 'block', visibility: 'visible', opacity: '0' };
+ }
+ return { display: 'block', visibility: 'visible', opacity: '1' };
+ });
+
+ setGlobalWindow(window);
+
+ detector = new LoginDetector(document);
+ detector.initialize();
+
+ const callback = vi.fn();
+ detector.onLoginCapture(callback);
+
+ const form = document.querySelector('form');
+ form?.dispatchEvent(new window.Event('submit', { bubbles: true }));
+
+ vi.runAllTimers();
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ expect(callback.mock.calls[0][0].password).toBe('visiblepass');
+ });
+ });
+});
diff --git a/apps/browser-extension/src/utils/loginDetector/__tests__/TestUtils.ts b/apps/browser-extension/src/utils/loginDetector/__tests__/TestUtils.ts
new file mode 100644
index 000000000..86ca82290
--- /dev/null
+++ b/apps/browser-extension/src/utils/loginDetector/__tests__/TestUtils.ts
@@ -0,0 +1,127 @@
+import { JSDOM } from 'jsdom';
+import { vi } from 'vitest';
+
+/**
+ * Mock MutationObserver for tests.
+ */
+export class MockMutationObserver {
+ private callback: MutationCallback;
+ private target: Node | null = null;
+
+ /**
+ * Creates a new MockMutationObserver instance.
+ * @param callback - The callback function to be invoked when mutations occur.
+ */
+ public constructor(callback: MutationCallback) {
+ this.callback = callback;
+ }
+
+ /**
+ * Starts observing the target node for mutations.
+ * @param target - The target node to observe.
+ * @param _options - Configuration options for the observer.
+ */
+ public observe(target: Node, _options?: MutationObserverInit): void {
+ this.target = target;
+ // Store the observer for potential mutation triggering
+ (target as unknown as { __mutationObserver: MockMutationObserver }).__mutationObserver = this;
+ }
+
+ /**
+ * Stops observing mutations.
+ */
+ public disconnect(): void {
+ if (this.target) {
+ delete (this.target as unknown as { __mutationObserver?: MockMutationObserver }).__mutationObserver;
+ }
+ this.target = null;
+ }
+
+ /**
+ * Returns an empty list of pending mutation records.
+ * @returns Empty array of MutationRecords.
+ */
+ public takeRecords(): MutationRecord[] {
+ return [];
+ }
+
+ /**
+ * Trigger the mutation callback with synthetic mutations.
+ * @param mutations - The mutations to trigger.
+ */
+ public trigger(mutations: Partial<MutationRecord>[]): void {
+ this.callback(mutations as MutationRecord[], this);
+ }
+}
+
+// Set up global MutationObserver mock
+(global as unknown as { MutationObserver: typeof MockMutationObserver }).MutationObserver = MockMutationObserver;
+
+/**
+ * Test environment containing dom, window, and document.
+ */
+export interface ITestEnvironment {
+ dom: JSDOM;
+ window: JSDOM['window'];
+ document: Document;
+}
+
+/**
+ * Helper to create a JSDOM instance with proper window mocks for testing.
+ * @param html - The HTML content to use for the document.
+ * @param url - The URL to use for the document location.
+ * @returns The test environment with dom, window, and document.
+ */
+export const createTestEnvironment = (
+ html: string,
+ url: string = 'https://example.com/login'
+): ITestEnvironment => {
+ const dom = new JSDOM(html, {
+ url,
+ runScripts: 'dangerously',
+ resources: 'usable',
+ });
+
+ const { window } = dom;
+ const { document } = window;
+
+ // Mock MutationObserver on the window
+ (window as unknown as { MutationObserver: typeof MockMutationObserver }).MutationObserver = MockMutationObserver;
+
+ // Mock getComputedStyle for visibility checks
+ window.getComputedStyle = vi.fn().mockImplementation((element: HTMLElement) => ({
+ display: element.style.display || 'block',
+ visibility: element.style.visibility || 'visible',
+ opacity: element.style.opacity || '1',
+ }));
+
+ // Mock setTimeout/clearTimeout
+ vi.useFakeTimers();
+
+ return { dom, window, document };
+};
+
+/**
+ * Helper to clean up test environment.
+ */
+export const cleanupTestEnvironment = (): void => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+};
+
+/**
+ * Sets up the global window reference for tests.
+ * @param window - The JSDOM window to set as global.
+ */
+export const setGlobalWindow = (window: JSDOM['window']): void => {
+ (global as unknown as { window: typeof window }).window = window;
+};
+
+/**
+ * Sets up global HTML element constructors for instanceof checks.
+ * @param window - The JSDOM window to use for element constructors.
+ */
+export const setGlobalHTMLElements = (window: JSDOM['window']): void => {
+ (global as unknown as { HTMLFormElement: typeof window.HTMLFormElement }).HTMLFormElement = window.HTMLFormElement;
+ (global as unknown as { HTMLElement: typeof window.HTMLElement }).HTMLElement = window.HTMLElement;
+};
diff --git a/apps/browser-extension/src/utils/loginDetector/index.ts b/apps/browser-extension/src/utils/loginDetector/index.ts
index 86b22e967..c2b4eca3c 100644
--- a/apps/browser-extension/src/utils/loginDetector/index.ts
+++ b/apps/browser-extension/src/utils/loginDetector/index.ts
@@ -12,4 +12,5 @@ export type {
SitePreference,
LoginSaveSettings,
LoginCaptureCallback,
+ SavePromptPersistedState,
} from './types';
diff --git a/apps/browser-extension/src/utils/loginDetector/types.ts b/apps/browser-extension/src/utils/loginDetector/types.ts
index 6be3718e8..59381fa4f 100644
--- a/apps/browser-extension/src/utils/loginDetector/types.ts
+++ b/apps/browser-extension/src/utils/loginDetector/types.ts
@@ -93,3 +93,20 @@ export type LoginSaveSettings = {
* Callback type for login capture events.
*/
export type LoginCaptureCallback = (login: CapturedLogin) => void;
+
+/**
+ * Persisted state for save prompt across page navigations.
+ * Used to restore the prompt on traditional form submissions with redirects.
+ */
+export type SavePromptPersistedState = {
+ /** The captured login credentials */
+ login: CapturedLogin;
+ /** Remaining time in milliseconds when the page navigated */
+ remainingTimeMs: number;
+ /** Initial auto-dismiss duration (for resetting if needed) */
+ initialAutoDismissMs: number;
+ /** Timestamp when this state was saved */
+ savedAt: number;
+ /** The domain where the prompt was shown (to validate on restore) */
+ domain: string;
+};