Skip to content

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

Update shadow root form detection in browser extension autofill (#2319)

Leendert de Borst76583655e100
diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.ts
index 6d5dc80b3..da093760e 100644
--- a/apps/browser-extension/src/entrypoints/content.ts
+++ b/apps/browser-extension/src/entrypoints/content.ts
@@ -18,6 +18,7 @@ import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { LoginDetector } from '@/utils/loginDetector';
import type { CapturedLogin } from '@/utils/loginDetector';
import { onMessage, sendMessage } from '@/utils/messaging/ExtensionMessaging';
+import { getDeepActiveElement, getDeepElementById, getDeepEventTarget } from '@/utils/ShadowDom';
import { t } from '@/i18n/StandaloneI18n';
@@ -503,14 +504,16 @@ export default defineContentScript({
* can globally disable autofill via av-disable="true" on <body> while still opting specific
* subtrees back in with av-enable="true".
*/
- if (!isAvAutofillAllowed(e.target as Element)) {
- devLog('[Autofill] focusin skipped: av-disable marker active for', e.target);
+ const focusedElement = getDeepEventTarget(e);
+
+ if (!isAvAutofillAllowed(focusedElement)) {
+ devLog('[Autofill] focusin skipped: av-disable marker active for', focusedElement);
return;
}
- const { isValid, inputElement } = validateInputField(e.target as Element);
+ const { isValid, inputElement } = validateInputField(focusedElement);
if (!isValid) {
- devLog('[Autofill] focusin skipped: not a fillable input field', e.target);
+ devLog('[Autofill] focusin skipped: not a fillable input field', focusedElement);
}
if (isValid && inputElement) {
/**
@@ -588,7 +591,7 @@ export default defineContentScript({
if (ctx.isInvalid) {
return;
}
- const activeElement = document.activeElement;
+ const activeElement = getDeepActiveElement(document);
if (activeElement) {
void showPopupForElement(activeElement);
}
@@ -603,7 +606,7 @@ export default defineContentScript({
});
// Check if currently something is focused, if so, apply check for that element
- const currentFocusedElement = document.activeElement;
+ const currentFocusedElement = getDeepActiveElement(document);
if (currentFocusedElement) {
showPopupForElement(currentFocusedElement);
}
@@ -631,7 +634,7 @@ export default defineContentScript({
return { success: false, error: 'No element identifier provided' };
}
- const target = document.getElementById(elementIdentifier) ?? document.getElementsByName(elementIdentifier)[0];
+ const target = getDeepElementById(document, elementIdentifier) ?? document.getElementsByName(elementIdentifier)[0];
if (isPopupType(popupType)) {
const { isValid, inputElement } = validateInputField(target);
@@ -665,7 +668,7 @@ export default defineContentScript({
*/
let resolvedInput: HTMLInputElement | null = null;
if (elementIdentifier) {
- const target = document.getElementById(elementIdentifier) ?? document.getElementsByName(elementIdentifier)[0] ?? null;
+ const target = getDeepElementById(document, elementIdentifier) ?? document.getElementsByName(elementIdentifier)[0] ?? null;
const { isValid, inputElement } = validateInputField(target);
if (isValid && inputElement) {
resolvedInput = inputElement;
diff --git a/apps/browser-extension/src/utils/ShadowDom.ts b/apps/browser-extension/src/utils/ShadowDom.ts
new file mode 100644
index 000000000..379d10ecf
--- /dev/null
+++ b/apps/browser-extension/src/utils/ShadowDom.ts
@@ -0,0 +1,223 @@
+/**
+ * Helpers for working with pages that render (part of) their content inside open shadow roots.
+ */
+
+import { devLog } from '@/utils/DevLogger';
+
+/**
+ * Upper bound on the number of shadow roots a single deep query descends into, to limit scans to
+ * sane max values. Component-heavy pages are known to run well into the hundreds, therefore we
+ * set this to a high value.
+ */
+const MAX_SHADOW_ROOTS = 2000;
+
+/**
+ * Get the shadow root a node lives in, or null when it is in the normal DOM.
+ * @param node - The node to resolve the root for.
+ * @returns The containing ShadowRoot, or null when the node is not inside a shadow root.
+ */
+export function getContainingShadowRoot(node: Node | null): ShadowRoot | null {
+ const root = node?.getRootNode() as ShadowRoot | undefined;
+ return root?.host ? root : null;
+}
+
+/**
+ * Get the root node (Document or ShadowRoot) a node belongs to.
+ * @param node - The node to resolve the root for.
+ * @returns The node's Document or ShadowRoot.
+ */
+export function getQueryRoot(node: Node): Document | ShadowRoot {
+ return node.getRootNode() as Document | ShadowRoot;
+}
+
+/**
+ * Like `Element.parentElement`, but hops from the top of a shadow root to its host element
+ * instead of returning null.
+ * @param element - The element to get the parent of.
+ * @returns The parent element in the composed tree, or null at the top of the root node.
+ */
+export function getComposedParentElement(element: Element | null): Element | null {
+ if (!element) {
+ return null;
+ }
+
+ if (element.parentElement) {
+ return element.parentElement;
+ }
+
+ return getContainingShadowRoot(element)?.host ?? null;
+}
+
+/**
+ * Collect the shadow hosts an element sits inside, innermost first.
+ * @param element - The element to resolve the hosts for.
+ * @param maxDepth - Maximum number of hosts to walk up to.
+ * @returns The shadow hosts wrapping the element, innermost first; empty when it is not in a shadow tree.
+ */
+export function getShadowHostChain(element: Element | null, maxDepth: number = 3): Element[] {
+ const hosts: Element[] = [];
+ let current: Element | null = element;
+
+ while (current && hosts.length < maxDepth) {
+ const host = getContainingShadowRoot(current)?.host ?? null;
+ if (!host) {
+ break;
+ }
+
+ hosts.push(host);
+ current = host;
+ }
+
+ return hosts;
+}
+
+/**
+ * Similar to `Element.closest()`, but continues the search at the shadow host when the element's own shadow root contains no match.
+ * @param element - The element to start searching from.
+ * @param selector - The CSS selector to match against.
+ * @returns The nearest matching ancestor in the composed tree, or null when there is none.
+ */
+export function closestAcrossShadow(element: Element | null, selector: string): HTMLElement | null {
+ let current: Element | null = element;
+
+ while (current) {
+ const match = current.closest(selector) as HTMLElement | null;
+ if (match) {
+ return match;
+ }
+ current = getContainingShadowRoot(current)?.host ?? null;
+ }
+
+ return null;
+}
+
+/**
+ * Similar to `Node.contains()`, but treats a shadow host as containing its shadow root.
+ * @param ancestor - The candidate ancestor element.
+ * @param node - The node to test.
+ * @returns True when node is ancestor itself or sits below it in the composed tree.
+ */
+export function composedContains(ancestor: Element | null, node: Node | null): boolean {
+ if (!ancestor || !node) {
+ return false;
+ }
+
+ let current: Node | null = node;
+ while (current) {
+ if (current === ancestor) {
+ return true;
+ }
+
+ // At the top of a shadow tree parentNode is the ShadowRoot itself — continue at its host.
+ const parent = current.parentNode as (Node & { host?: Element }) | null;
+ current = parent ? (parent.host ?? parent) : null;
+ }
+
+ return false;
+}
+
+/**
+ * Resolve the element a focus/pointer event really originated from, looking through shadow
+ * boundaries. Events crossing an open shadow root are retargeted to the host, so `event.target`
+ * alone would report the custom element instead of the input the user actually focused.
+ * @param event - The event to resolve the target for.
+ * @returns The deepest element in the event's composed path, falling back to `event.target`.
+ */
+export function getDeepEventTarget(event: Event): Element | null {
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : [];
+ const deepest = path[0] as Element | undefined;
+
+ // Node.ELEMENT_NODE — duck-typed so it also holds for nodes from another realm.
+ if (deepest && deepest.nodeType === 1) {
+ return deepest;
+ }
+
+ return event.target as Element | null;
+}
+
+/**
+ * Resolve the focused element, descending through open shadow roots. `document.activeElement`
+ * only reports the outermost host for content inside a shadow tree.
+ * @param documentOrRoot - The document (or shadow root) to start from.
+ * @returns The deepest focused element, or null when nothing is focused.
+ */
+export function getDeepActiveElement(documentOrRoot: Document | ShadowRoot): Element | null {
+ let active = documentOrRoot.activeElement;
+
+ while (active?.shadowRoot?.activeElement) {
+ active = active.shadowRoot.activeElement;
+ }
+
+ return active;
+}
+
+/**
+ * Collect every open shadow root reachable from the given root.
+ * @param root - The root to scan.
+ * @returns The reachable shadow roots, outermost first.
+ */
+export function collectShadowRoots(root: Document | ShadowRoot | Element): ShadowRoot[] {
+ const shadowRoots: ShadowRoot[] = [];
+ const seen = new Set<ShadowRoot>();
+ const queue: (Document | ShadowRoot | Element)[] = [root];
+
+ while (queue.length > 0 && shadowRoots.length < MAX_SHADOW_ROOTS) {
+ const current = queue.shift()!;
+
+ for (const element of Array.from(current.querySelectorAll<HTMLElement>('*'))) {
+ const shadowRoot = element.shadowRoot;
+ if (shadowRoot && !seen.has(shadowRoot)) {
+ seen.add(shadowRoot);
+ shadowRoots.push(shadowRoot);
+ queue.push(shadowRoot);
+
+ if (shadowRoots.length >= MAX_SHADOW_ROOTS) {
+ devLog(`[ShadowDom] Shadow root scan truncated at ${MAX_SHADOW_ROOTS} roots; deeper components are not visible to detection.`);
+ break;
+ }
+ }
+ }
+ }
+
+ return shadowRoots;
+}
+
+/**
+ * Similar to `querySelectorAll`, but also descends into open shadow roots.
+ * @param root - The root to query from.
+ * @param selector - The CSS selector to match.
+ * @returns The matching elements from the normal DOM and every reachable shadow root.
+ */
+export function queryAllDeep<T extends Element>(root: Document | ShadowRoot | Element, selector: string): T[] {
+ const results: T[] = Array.from(root.querySelectorAll<T>(selector));
+
+ for (const shadowRoot of collectShadowRoots(root)) {
+ results.push(...Array.from(shadowRoot.querySelectorAll<T>(selector)));
+ }
+
+ return results;
+}
+
+/**
+ * Like `document.getElementById`, but also searches open shadow roots. IDs inside a shadow tree
+ * are scoped to that tree, so the same id may legitimately exist more than once; the normal DOM
+ * match wins, then shadow trees in document order.
+ * @param documentOrRoot - The document to search.
+ * @param elementId - The id to look for.
+ * @returns The first matching element, or null when there is none.
+ */
+export function getDeepElementById(documentOrRoot: Document | ShadowRoot, elementId: string): HTMLElement | null {
+ const lightMatch = documentOrRoot.getElementById(elementId) as HTMLElement | null;
+ if (lightMatch) {
+ return lightMatch;
+ }
+
+ for (const shadowRoot of collectShadowRoots(documentOrRoot)) {
+ const match = shadowRoot.getElementById(elementId);
+ if (match) {
+ return match as HTMLElement;
+ }
+ }
+
+ return null;
+}
diff --git a/apps/browser-extension/src/utils/autofill/Autofill.ts b/apps/browser-extension/src/utils/autofill/Autofill.ts
index 5e8c8a1fd..d7fe1e966 100644
--- a/apps/browser-extension/src/utils/autofill/Autofill.ts
+++ b/apps/browser-extension/src/utils/autofill/Autofill.ts
@@ -10,6 +10,8 @@
* shouldn't be encouraged (e.g. AliasVault's own login form).
*/
+import { getComposedParentElement } from '@/utils/ShadowDom';
+
/**
* Walk up the DOM from the given element and determine whether AliasVault
* autofill is allowed. The nearest ancestor (or the element itself) carrying
@@ -28,7 +30,7 @@ export function isAvAutofillAllowed(element: Element | null): boolean {
if (current.getAttribute('av-disable') === 'true') {
return false;
}
- current = current.parentElement;
+ current = getComposedParentElement(current);
}
return true;
}
@@ -56,7 +58,7 @@ export function isAvSuppressSave(element: Element | null): boolean {
if (value === 'false') {
return false;
}
- current = current.parentElement;
+ current = getComposedParentElement(current);
}
return false;
}
diff --git a/apps/browser-extension/src/utils/formDetector/FormDetector.ts b/apps/browser-extension/src/utils/formDetector/FormDetector.ts
index c7db66d01..85ec0708f 100644
--- a/apps/browser-extension/src/utils/formDetector/FormDetector.ts
+++ b/apps/browser-extension/src/utils/formDetector/FormDetector.ts
@@ -1,4 +1,5 @@
import { devLog } from "@/utils/DevLogger";
+import { closestAcrossShadow, collectShadowRoots, getComposedParentElement, getQueryRoot, getShadowHostChain, queryAllDeep } from "@/utils/ShadowDom";
import { CombinedEmailVerificationPatterns, CombinedFieldExclusionPatterns, CombinedFieldPatterns, CombinedGenderOptionPatterns, CombinedStopWords, type FieldPatternEntry, includeTerms, specificIncludeTerms } from "./FieldPatterns";
import { DetectedFieldType, type FormFields } from "./types/FormFields";
@@ -24,6 +25,13 @@ export class FormDetector {
private readonly clickedElement: HTMLElement | null;
private readonly visibilityCache: Map<HTMLElement, boolean>;
+ /**
+ * Shadow roots per search root, cached for the lifetime of this detector. Field lookup runs once
+ * per field type (a dozen times or more for a full form scan) and each scan walks every element
+ * below the root, which is far too expensive to repeat on a component-heavy page.
+ */
+ private readonly shadowRootCache: Map<Document | HTMLElement, ShadowRoot[]> = new Map();
+
/** Which element/check caused the last isElementVisible() call to return false (devLog diagnostics). */
private lastHiddenReason: string | null = null;
@@ -39,7 +47,7 @@ export class FormDetector {
*/
if (clickedElement) {
// Check parents strictly (including opacity)
- let parent = clickedElement.parentElement;
+ let parent = getComposedParentElement(clickedElement) as HTMLElement | null;
let parentVisible = true;
while (parent && parent !== this.document.body) {
@@ -47,7 +55,7 @@ export class FormDetector {
parentVisible = false;
break;
}
- parent = parent.parentElement;
+ parent = getComposedParentElement(parent) as HTMLElement | null;
}
// Check element itself without opacity check (allow opacity:0 for transitions)
@@ -232,8 +240,7 @@ export class FormDetector {
* Get the form wrapper element.
*/
private getFormWrapper(): HTMLElement | null {
- const wrapper = this.clickedElement?.closest('form, [role="dialog"]') as HTMLElement | null;
- return wrapper;
+ return closestAcrossShadow(this.clickedElement, 'form, [role="dialog"]');
}
/**
@@ -302,7 +309,7 @@ export class FormDetector {
// Also check associated labels
if (input.id || input.getAttribute('name')) {
- const label = this.document.querySelector(`label[for="${input.id || input.getAttribute('name')}"]`);
+ const label = getQueryRoot(input).querySelector(`label[for="${input.id || input.getAttribute('name')}"]`);
if (label) {
attributesToCheck.push(label.textContent?.toLowerCase() ?? '');
}
@@ -346,7 +353,7 @@ export class FormDetector {
.filter(a => a.length > 0);
if (input.id || input.getAttribute('name')) {
- const label = this.document.querySelector(`label[for="${input.id || input.getAttribute('name')}"]`);
+ const label = getQueryRoot(input).querySelector(`label[for="${input.id || input.getAttribute('name')}"]`);
if (label) {
attributesToCheck.push(label.textContent?.toLowerCase() ?? '');
}
@@ -477,6 +484,41 @@ export class FormDetector {
return element;
}
+ /**
+ * Get every open shadow root below the given search root, reusing the result within this detector.
+ * @param root - The root to scan.
+ * @returns The reachable shadow roots.
+ */
+ private getShadowRoots(root: Document | HTMLElement): ShadowRoot[] {
+ let shadowRoots = this.shadowRootCache.get(root);
+ if (!shadowRoots) {
+ shadowRoots = collectShadowRoots(root);
+ this.shadowRootCache.set(root, shadowRoots);
+ }
+ return shadowRoots;
+ }
+
+ /**
+ * Get the custom-element hosts that describe the given input, innermost first.
+ *
+ * This is the inverse of {@link getActualInputElement}: a text field component such as
+ * `<x-text-input id="login-username" name="username" autocomplete="username">` keeps every
+ * identifying attribute (and the `<span slot="label">` text) on the host, while the real `<input>`
+ * it renders inside its shadow root carries none of it. Without the host, that input is
+ * indistinguishable from an unlabelled text box.
+ *
+ * Only hosts wrapping exactly one input are returned, so attributes are never borrowed from a
+ * component that renders several fields at once.
+ * @param input - The input to resolve the describing hosts for.
+ * @returns The describing hosts, innermost first; empty when the input is not shadow-hosted.
+ */
+ private getDescribingHosts(input: HTMLElement): HTMLElement[] {
+ return getShadowHostChain(input).filter(host => {
+ const shadowRoot = (host as HTMLElement & { shadowRoot?: ShadowRoot }).shadowRoot;
+ return shadowRoot != null && shadowRoot.querySelectorAll('input, textarea').length === 1;
+ }) as HTMLElement[];
+ }
+
/**
* Check if an element and all its parents are visible.
* This checks for display:none, visibility:hidden, and optionally opacity:0
@@ -650,7 +692,8 @@ export class FormDetector {
return true;
}
- current = current.parentElement;
+ // Crosses open shadow boundaries to find the actual form element.
+ current = getComposedParentElement(current) as HTMLElement | null;
}
// Cache and return true for the original element
@@ -671,28 +714,25 @@ export class FormDetector {
checkVisibility: boolean = true
): HTMLInputElement[] {
const patterns = includeTerms(entry);
+
+ /*
+ * Search the normal DOM plus every open shadow root below it. Web components frequently render
+ * the real fields inside their shadow root, where a plain querySelectorAll never reaches.
+ * The roots are collected once and reused for both queries below.
+ */
+ const searchRoot: Document | HTMLFormElement = form ?? this.document;
+ const searchRoots: (Document | ShadowRoot | HTMLElement)[] = [searchRoot, ...this.getShadowRoots(searchRoot)];
+
// Query for standard input elements, select elements, and elements with type attributes
- const standardCandidates = form
- ? Array.from(form.querySelectorAll<HTMLElement>('input, select, [type]'))
- : Array.from(this.document.querySelectorAll<HTMLElement>('input, select, [type]'));
+ const standardCandidates = searchRoots.flatMap(root => Array.from(root.querySelectorAll<HTMLElement>('input, select, [type]')));
- /**
- * Also find any custom elements that might contain shadow DOM inputs
- * Look for elements with shadow roots that contain input elements
+ /*
+ * Also consider the custom elements that render inputs inside their shadow root. Every such
+ * element is the host of one of the roots collected above.
*/
- const allElements = form
- ? Array.from(form.querySelectorAll<HTMLElement>('*'))
- : Array.from(this.document.querySelectorAll<HTMLElement>('*'));
-
- const shadowDOMCandidates = allElements.filter(el => {
- // Check if element has shadow DOM with input elements
- const elementWithShadow = el as HTMLElement & { shadowRoot?: ShadowRoot };
- if (elementWithShadow.shadowRoot) {
- const shadowInput = elementWithShadow.shadowRoot.querySelector('input, textarea');
- return shadowInput !== null;
- }
- return false;
- });
+ const shadowDOMCandidates = this.getShadowRoots(searchRoot)
+ .filter(shadowRoot => shadowRoot.querySelector('input, textarea') !== null)
+ .map(shadowRoot => shadowRoot.host as HTMLElement);
// Combine and deduplicate candidates
const allCandidates = [...standardCandidates, ...shadowDOMCandidates];
@@ -782,28 +822,52 @@ export class FormDetector {
continue;
}
+ /*
+ * Hosts that describe this input (empty unless the input is rendered inside a web component's
+ * element's shadow root). Their attributes and slotted labels are treated as the input's own.
+ */
+ const describingHosts = this.getDescribingHosts(input);
+
+ /**
+ * Read an attribute from the input, falling back to the describing hosts.
+ * @param names - The attribute names to try, in order of preference.
+ * @returns The first value found, or an empty string.
+ */
+ const readAttribute = (...names: string[]): string => {
+ for (const element of [input, ...describingHosts]) {
+ for (const name of names) {
+ const value = element.getAttribute(name);
+ if (value) {
+ return value.toLowerCase();
+ }
+ }
+ }
+ return '';
+ };
+
/**
* Check autocomplete attribute for direct field type matching.
* First check our custom data-av-autocomplete attribute (set by AliasVault when disabling
* native browser autofill), then fall back to the regular autocomplete attribute.
*/
- const autocomplete = (input.getAttribute('data-av-autocomplete') ?? input.getAttribute('autocomplete'))?.toLowerCase() ?? '';
+ const autocomplete = readAttribute('data-av-autocomplete', 'autocomplete');
- // Direct autocomplete matches take highest priority (score -2, higher than type=email at -1)
- if (autocomplete) {
+ // Check for direct autocomplete matches
+ const autocompleteTokens = new Set(autocomplete.split(/\s+/).filter(Boolean));
+ if (autocompleteTokens.size > 0) {
// Match autocomplete="username" for username patterns
- if (entry === CombinedFieldPatterns.username && autocomplete === 'username') {
+ if (entry === CombinedFieldPatterns.username && autocompleteTokens.has('username')) {
matches.push({ input: input as HTMLInputElement, score: -2 });
continue;
}
// Match autocomplete="email" for email patterns
- if (entry === CombinedFieldPatterns.email && autocomplete === 'email') {
+ if (entry === CombinedFieldPatterns.email && autocompleteTokens.has('email')) {
matches.push({ input: input as HTMLInputElement, score: -2 });
continue;
}
// Match autocomplete="current-password" or "new-password" for password patterns
if (entry === CombinedFieldPatterns.password &&
- (autocomplete === 'current-password' || autocomplete === 'new-password')) {
+ (autocompleteTokens.has('current-password') || autocompleteTokens.has('new-password'))) {
matches.push({ input: input as HTMLInputElement, score: -2 });
continue;
}
@@ -813,7 +877,7 @@ export class FormDetector {
* Check aria-describedby ID for direct field type matching (e.g., aria-describedby="usernameMessage")
* Only match if it's a clear username indicator (not usernameConfirm, etc.)
*/
- const ariaDescribedById = input.getAttribute('aria-describedby')?.toLowerCase() ?? '';
+ const ariaDescribedById = readAttribute('aria-describedby');
if (ariaDescribedById) {
// Match aria-describedby containing "username" for username patterns
if (entry === CombinedFieldPatterns.username &&
@@ -823,31 +887,38 @@ export class FormDetector {
}
}
- // Collect all text attributes to check
- const attributesToCheck = [
- input.id,
- input.getAttribute('name'),
- input.getAttribute('placeholder'),
- input.getAttribute('class'),
- autocomplete
- ]
+ /*
+ * Collect all text attributes to check.
+ */
+ const attributesToCheck = [input, ...describingHosts]
+ .flatMap(element => [
+ element.id,
+ element.getAttribute('name'),
+ element.getAttribute('placeholder'),
+ element.getAttribute('class'),
+ ])
+ .concat(autocomplete)
.map(a => a?.toLowerCase() ?? '');
- // Check for associated labels if input has an ID or name
- if (input.id || input.getAttribute('name')) {
- const label = this.document.querySelector(`label[for="${input.id || input.getAttribute('name')}"]`);
- if (label) {
- attributesToCheck.push(label.textContent?.toLowerCase() ?? '');
+ // Check for associated labels if the input (or a describing host) has an ID or name
+ for (const element of [input, ...describingHosts]) {
+ const labelTarget = element.id || element.getAttribute('name');
+ if (labelTarget) {
+ const label = getQueryRoot(element).querySelector(`label[for="${labelTarget}"]`);
+ if (label) {
+ attributesToCheck.push(label.textContent?.toLowerCase() ?? '');
+ }
}
}
// Check aria-describedby for additional field hints
- const ariaDescribedBy = input.getAttribute('aria-describedby');
+ const ariaDescribedBy = readAttribute('aria-describedby');
if (ariaDescribedBy) {
// aria-describedby can contain multiple space-separated IDs
const describedByIds = ariaDescribedBy.split(/\s+/);
for (const descId of describedByIds) {
- const describedByElement = this.document.getElementById(descId);
+ // IDs are scoped to the tree the input lives in, so resolve them against its own root.
+ const describedByElement = getQueryRoot(input).getElementById(descId) ?? this.document.getElementById(descId);
if (describedByElement) {
attributesToCheck.push(describedByElement.textContent?.toLowerCase() ?? '');
}
@@ -855,17 +926,28 @@ export class FormDetector {
}
// Check aria-label attribute
- const ariaLabel = input.getAttribute('aria-label');
+ const ariaLabel = readAttribute('aria-label');
if (ariaLabel) {
- attributesToCheck.push(ariaLabel.toLowerCase());
+ attributesToCheck.push(ariaLabel);
}
/**
* Check for slot-based labels (e.g., <span slot="label">Email or username</span>)
- * Look for slot elements within the input's parent hierarchy
+ * Look for slot elements within the input's parent hierarchy.
*/
- let slotParent: HTMLElement | null = input;
- for (let depth = 0; depth < 3 && slotParent; depth++) {
+ const slotSearchRoots: HTMLElement[] = [];
+ let slotWalker: HTMLElement | null = input;
+ for (let depth = 0; depth < 3 && slotWalker; depth++) {
+ slotSearchRoots.push(slotWalker);
+ slotWalker = getComposedParentElement(slotWalker) as HTMLElement | null;
+ }
+ for (const host of describingHosts) {
+ if (!slotSearchRoots.includes(host)) {
+ slotSearchRoots.push(host);
+ }
+ }
+
+ for (const slotParent of slotSearchRoots) {
const slotElements = slotParent.querySelectorAll('[slot="label"], [slot="helper-text"]');
for (const slotEl of Array.from(slotElements)) {
const slotText = slotEl.textContent?.toLowerCase() ?? '';
@@ -885,7 +967,6 @@ export class FormDetector {
}
}
}
- slotParent = slotParent.parentElement;
}
// Check for sibling elements with class containing "label"
@@ -1030,7 +1111,7 @@ export class FormDetector {
*/
let labelText = '';
if (field.id || fieldName) {
- const label = this.document.querySelector(`label[for="${field.id || fieldName}"]`);
+ const label = getQueryRoot(field).querySelector(`label[for="${field.id || fieldName}"]`);
if (label) {
labelText = (label.textContent || '').toLowerCase();
}
@@ -1396,9 +1477,11 @@ export class FormDetector {
let searchRoot: HTMLElement = this.clickedElement;
let depth = 0;
- // Go up to find a reasonable container (max 15 levels)
- while (searchRoot.parentElement && depth < 15) {
- searchRoot = searchRoot.parentElement;
+ // Go up to find a reasonable container (max 15 levels).
+ let searchParent = getComposedParentElement(searchRoot) as HTMLElement | null;
+ while (searchParent && depth < 15) {
+ searchRoot = searchParent;
+ searchParent = getComposedParentElement(searchRoot) as HTMLElement | null;
depth++;
// Stop if we found a form, dialog, or main container
@@ -1467,7 +1550,7 @@ export class FormDetector {
// Additional heuristics for TOTP fields that may not match patterns
const allInputs = form
? Array.from(form.querySelectorAll<HTMLInputElement>('input'))
- : Array.from(this.document.querySelectorAll<HTMLInputElement>('input'));
+ : queryAllDeep<HTMLInputElement>(this.document, 'input');
for (const input of allInputs) {
if (!this.isElementVisible(input)) {
@@ -1654,9 +1737,8 @@ export class FormDetector {
const formWrapper = this.getFormWrapper();
// Check both the clicked element and the actual input element
- const elementsToCheck = [this.clickedElement, actualElement].filter((el, index, arr) =>
- el && arr.indexOf(el) === index // Remove duplicates
- );
+ const elementsToCheck = [this.clickedElement, actualElement, ...this.getDescribingHosts(actualElement)]
+ .filter((el, index, arr) => el && arr.indexOf(el) === index);
/*
* When detecting field type from a clicked element, skip visibility checks
diff --git a/apps/browser-extension/src/utils/formDetector/FormFiller.ts b/apps/browser-extension/src/utils/formDetector/FormFiller.ts
index ade740b95..b93ce3e1d 100644
--- a/apps/browser-extension/src/utils/formDetector/FormFiller.ts
+++ b/apps/browser-extension/src/utils/formDetector/FormFiller.ts
@@ -3,6 +3,7 @@ import type { Credential } from "@/utils/dist/core/models/vault";
import { CombinedDateOptionPatterns, CombinedGenderOptionPatterns } from "@/utils/formDetector/FieldPatterns";
import { type FormFields } from "@/utils/formDetector/types/FormFields";
import { ClickValidator } from "@/utils/security/ClickValidator";
+import { composedContains } from "@/utils/ShadowDom";
/**
* Class to fill the fields of a form with the given credential.
*/
@@ -168,12 +169,15 @@ export class FormFiller {
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)
- );
+ /**
+ * Check if our field is in the element stack (or its parents/children)
+ * @param element - The element to check.
+ * @returns True when the element belongs to the field's own composed subtree or its ancestors.
+ */
+ const isFieldOrRelated = (element: Element): boolean =>
+ element === field || composedContains(field, element) || composedContains(element, field);
+
+ const fieldFound = elementsAtPoint.some(isFieldOrRelated);
if (!fieldFound) {
console.warn('[AliasVault Security] Field is obstructed by other elements');
@@ -182,7 +186,7 @@ export class FormFiller {
// Check for suspicious covering elements
const suspiciousCovering = elementsAtPoint.slice(0, 3).some(element => {
- if (element === field || field.contains(element) || element.contains(field)) {
+ if (isFieldOrRelated(element)) {
return false; // This is our field or related element
}
diff --git a/apps/browser-extension/src/utils/formDetector/__tests__/FormDetector.shadowform.test.ts b/apps/browser-extension/src/utils/formDetector/__tests__/FormDetector.shadowform.test.ts
new file mode 100644
index 000000000..a1c1e4082
--- /dev/null
+++ b/apps/browser-extension/src/utils/formDetector/__tests__/FormDetector.shadowform.test.ts
@@ -0,0 +1,187 @@
+import { describe, expect, it } from 'vitest';
+
+import { isAvAutofillAllowed } from '@/utils/autofill/Autofill';
+import { closestAcrossShadow, composedContains, getDeepActiveElement, getDeepElementById, getDeepEventTarget, queryAllDeep } from '@/utils/ShadowDom';
+
+import { FormDetector } from '../FormDetector';
+
+import { createTestDom, FormField, testField } from './TestUtils';
+
+/**
+ * Web components that render an entire login form inside a single open shadow root, instead of
+ * the one-input-per-custom-element pattern covered by FormDetector.shadowdom.test.ts.
+ */
+describe('FormDetector shadow-root-hosted form tests', () => {
+ describe('Login form with its own form element inside a shadow root', () => {
+ const htmlFile = 'shadow-root-1.html';
+
+ testField(FormField.Username, 'username', htmlFile);
+ testField(FormField.Password, 'password', htmlFile);
+
+ it('should detect a login form for a field inside the shadow root', () => {
+ const document = createTestDom(htmlFile).window.document;
+ const username = getDeepElementById(document, 'username');
+
+ expect(new FormDetector(document, username as HTMLElement).containsLoginForm()).toBe(true);
+ });
+
+ it('should classify the shadow-hosted password field as a password field', () => {
+ const document = createTestDom(htmlFile).window.document;
+ const password = getDeepElementById(document, 'password');
+
+ expect(new FormDetector(document, password as HTMLElement).getDetectedFieldType()).toBe('password');
+ });
+
+ it('should find the shadow-hosted form and its inputs from the document root', () => {
+ const document = createTestDom(htmlFile).window.document;
+
+ expect(queryAllDeep(document, 'form')).toHaveLength(1);
+ expect(queryAllDeep(document, 'input').map(input => input.id)).toEqual(['username', 'password']);
+ });
+ });
+
+ describe('Login form inside a shadow root without a form element', () => {
+ const htmlFile = 'shadow-root-2.html';
+
+ testField(FormField.Username, 'username', htmlFile);
+ testField(FormField.Password, 'password', htmlFile);
+
+ it('should detect a login form even without a form wrapper', () => {
+ const document = createTestDom(htmlFile).window.document;
+ const username = getDeepElementById(document, 'username');
+
+ expect(new FormDetector(document, username as HTMLElement).containsLoginForm()).toBe(true);
+ });
+ });
+
+ describe('Login form whose fields are identified only by their custom element host', () => {
+ const htmlFile = 'shadow-root-4.html';
+
+ /**
+ * Resolve the real input a component renders inside its shadow root.
+ * @param document - The test document.
+ * @param hostId - The id of the custom element host.
+ * @returns The input inside the host's shadow root.
+ */
+ const shadowInputOf = (document: Document, hostId: string): HTMLInputElement => {
+ const host = document.getElementById(hostId);
+ return host!.shadowRoot!.querySelector('input') as HTMLInputElement;
+ };
+
+ it('should keep the real inputs out of the normal DOM', () => {
+ const document = createTestDom(htmlFile).window.document;
+
+ expect(document.querySelectorAll('input')).toHaveLength(0);
+ expect(queryAllDeep(document, 'input')).toHaveLength(2);
+ });
+
+ /*
+ * Focusing the field hands the detector the input inside the shadow root, which carries nothing
+ * but type="text". Everything identifying it — id, name, autocomplete and the slotted
+ * "Email or username" label — sits on the host outside the shadow boundary.
+ */
+ it('should classify the shadow-rendered username field from its host metadata', () => {
+ const document = createTestDom(htmlFile).window.document;
+ const input = shadowInputOf(document, 'login-username');
+
+ expect(input.getAttribute('name')).toBeNull();
+
+ const detector = new FormDetector(document, input);
+ expect(detector.containsLoginForm()).toBe(true);
+ expect(detector.getDetectedFieldType()).toBe('username');
+ });
+
+ it('should classify the shadow-rendered password field from its host metadata', () => {
+ const document = createTestDom(htmlFile).window.document;
+ const input = shadowInputOf(document, 'login-password');
+
+ const detector = new FormDetector(document, input);
+ expect(detector.containsLoginForm()).toBe(true);
+ expect(detector.getDetectedFieldType()).toBe('password');
+ });
+
+ it('should still classify the field when the host itself is the clicked element', () => {
+ const document = createTestDom(htmlFile).window.document;
+ const host = document.getElementById('login-username') as HTMLElement;
+
+ expect(new FormDetector(document, host).getDetectedFieldType()).toBe('username');
+ });
+
+ it('should resolve fill targets to the real inputs rather than the custom element hosts', () => {
+ const document = createTestDom(htmlFile).window.document;
+ const form = new FormDetector(document, shadowInputOf(document, 'login-username')).getForm();
+
+ // "Email or username" matches the email patterns first, so the field lands on emailField.
+ expect(form?.emailField).toBe(shadowInputOf(document, 'login-username'));
+ expect(form?.passwordField).toBe(shadowInputOf(document, 'login-password'));
+ });
+ });
+
+ describe('Login form nested two shadow roots deep', () => {
+ const htmlFile = 'shadow-root-3.html';
+
+ testField(FormField.Username, 'username', htmlFile);
+ testField(FormField.Password, 'password', htmlFile);
+
+ it('should reach inputs inside nested shadow roots from the document root', () => {
+ const document = createTestDom(htmlFile).window.document;
+
+ expect(queryAllDeep(document, 'input').map(input => input.id)).toEqual(['username', 'password']);
+ });
+ });
+});
+
+describe('Shadow DOM traversal helper tests', () => {
+ const htmlFile = 'shadow-root-1.html';
+
+ it('should resolve the real input from a retargeted focusin event', () => {
+ const document = createTestDom(htmlFile).window.document;
+ const host = document.querySelector('gramps-jslogin');
+ const password = getDeepElementById(document, 'password') as HTMLInputElement;
+
+ let deepTarget: Element | null = null;
+ let retargetedTarget: EventTarget | null = null;
+ document.addEventListener('focusin', (event) => {
+ deepTarget = getDeepEventTarget(event);
+ retargetedTarget = event.target;
+ });
+
+ password.focus();
+
+ // The event itself is retargeted to the host — which is exactly why the deep lookup is needed.
+ expect(retargetedTarget).toBe(host);
+ expect(deepTarget).toBe(password);
+ });
+
+ it('should descend into the shadow root for the active element', () => {
+ const document = createTestDom(htmlFile).window.document;
+ const host = document.querySelector('gramps-jslogin');
+ const password = getDeepElementById(document, 'password') as HTMLInputElement;
+
+ password.focus();
+
+ expect(document.activeElement).toBe(host);
+ expect(getDeepActiveElement(document)).toBe(password);
+ });
+
+ it('should cross the shadow boundary for closest() and contains()', () => {
+ const document = createTestDom(htmlFile).window.document;
+ const host = document.querySelector('gramps-jslogin');
+ const username = getDeepElementById(document, 'username') as HTMLInputElement;
+
+ expect(closestAcrossShadow(username, 'form')?.id).toBe('login-form');
+ expect(closestAcrossShadow(username, 'body')).toBe(document.body);
+ expect(composedContains(host, username)).toBe(true);
+ expect(host?.contains(username)).toBe(false);
+ });
+
+ it('should honour an av-disable marker on body for fields inside a shadow root', () => {
+ const document = createTestDom(htmlFile).window.document;
+ const username = getDeepElementById(document, 'username') as HTMLInputElement;
+
+ expect(isAvAutofillAllowed(username)).toBe(true);
+
+ document.body.setAttribute('av-disable', 'true');
+ expect(isAvAutofillAllowed(username)).toBe(false);
+ });
+});
diff --git a/apps/browser-extension/src/utils/formDetector/__tests__/TestUtils.ts b/apps/browser-extension/src/utils/formDetector/__tests__/TestUtils.ts
index c6a2ab2a5..b58971ef8 100644
--- a/apps/browser-extension/src/utils/formDetector/__tests__/TestUtils.ts
+++ b/apps/browser-extension/src/utils/formDetector/__tests__/TestUtils.ts
@@ -8,6 +8,7 @@ import { Gender } from '@/utils/dist/core/models/identity';
import type { Credential } from '@/utils/dist/core/models/vault';
import { FormDetector } from '@/utils/formDetector/FormDetector';
import { type FormFields } from '@/utils/formDetector/types/FormFields';
+import { getDeepElementById } from '@/utils/ShadowDom';
export enum FormField {
Username = 'username',
@@ -78,8 +79,8 @@ export const testField = (fieldName: FormField, elementId: string, htmlFile: str
it(`should detect ${fieldName} field`, () => {
const { document, result } = setupFormTest(htmlFile, elementId);
- // First verify the test element exists
- const expectedElement = document.getElementById(elementId);
+ // First verify the test element exists (may live inside a component's shadow root)
+ const expectedElement = getDeepElementById(document, elementId);
if (!expectedElement) {
throw new Error(`Test setup failed: Element with id "${elementId}" not found in test HTML. Check if the element is present in the test HTML file: ${htmlFile}`);
}
@@ -140,8 +141,8 @@ const setupFormTest = (htmlFile: string, focusedElementId: string) : { document:
});
const document = dom.window.document;
- // Set focus on specified element if provided
- let focusedElement = document.getElementById(focusedElementId);
+ // Set focus on specified element if provided (may live inside a component's shadow root)
+ let focusedElement = getDeepElementById(document, focusedElementId);
if (!focusedElement) {
throw new Error(`Focus element with id "${focusedElementId}" not found in test HTML`);
}
diff --git a/apps/browser-extension/src/utils/formDetector/__tests__/test-forms/shadow-root-1.html b/apps/browser-extension/src/utils/formDetector/__tests__/test-forms/shadow-root-1.html
new file mode 100644
index 000000000..f821e4eae
--- /dev/null
+++ b/apps/browser-extension/src/utils/formDetector/__tests__/test-forms/shadow-root-1.html
@@ -0,0 +1,64 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Shadow Root Login Form Test 1</title>
+</head>
+<body>
+ <!--
+ A whole login form (both inputs plus its own <form>) inside a single open shadow root,
+ rather than the one-custom-element-per-input pattern in slot-based-form.html.
+
+ Markup taken from Gramps Web, which is Lit based, including the lit marker comments and
+ the Material web component buttons.
+ -->
+ <gramps-jslogin tree="test"></gramps-jslogin>
+
+ <script>
+ class GrampsJsLogin extends HTMLElement {
+ connectedCallback() {
+ if (this.shadowRoot) {
+ return;
+ }
+
+ const shadowRoot = this.attachShadow({ mode: 'open' });
+ shadowRoot.innerHTML = `
+ <div id="login-container">
+ <form id="login-form">
+ <h2><!--?lit$999198365$-->Log in to Gramps Web</h2>
+ <!--?lit$999198365$-->
+ <div class="text-field-wrapper">
+ <input id="username" name="username" type="text" autocomplete="username" autocapitalize="off" placeholder=" " required="">
+ <label for="username"><!--?lit$999198365$-->Username</label>
+ </div>
+ <div class="text-field-wrapper">
+ <input id="password" name="password" type="password" autocomplete="current-password" placeholder=" " required="">
+ <label for="password"><!--?lit$999198365$-->Password</label>
+ </div>
+ <div class="button-container">
+ <!--?lit$999198365$-->
+ <md-outlined-button value="">
+ <!--?lit$999198365$-->Register new account
+ </md-outlined-button>
+
+ <md-filled-button type="submit" value="">
+ <!--?lit$999198365$-->login
+ </md-filled-button>
+ </div>
+ <mwc-circular-progress indeterminate="" density="-7" closed="" id="login-progress" style="display:none; margin-top: 0.5em;" progress="0">
+ </mwc-circular-progress>
+ <p class="forgot-password">
+ <span class="link"><!--?lit$999198365$-->Lost password?</span>
+ </p>
+
+ <!--?lit$999198365$-->
+ <!--?lit$999198365$-->
+ </form>
+ </div>
+ `;
+ }
+ }
+
+ customElements.define('gramps-jslogin', GrampsJsLogin);
+ </script>
+</body>
+</html>
diff --git a/apps/browser-extension/src/utils/formDetector/__tests__/test-forms/shadow-root-2.html b/apps/browser-extension/src/utils/formDetector/__tests__/test-forms/shadow-root-2.html
new file mode 100644
index 000000000..3196db299
--- /dev/null
+++ b/apps/browser-extension/src/utils/formDetector/__tests__/test-forms/shadow-root-2.html
@@ -0,0 +1,37 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Shadow Root Login Form Test 2</title>
+</head>
+<body>
+ <!--
+ Variant of shadow-root-1.html where the component skips the <form> element entirely and
+ submits through a click handler, so the detector has no wrapper to scope its search to.
+ -->
+ <my-login></my-login>
+
+ <script>
+ class MyLogin extends HTMLElement {
+ connectedCallback() {
+ if (this.shadowRoot) {
+ return;
+ }
+
+ const shadowRoot = this.attachShadow({ mode: 'open' });
+ shadowRoot.innerHTML = `
+ <div class="login">
+ <h2>Sign in</h2>
+ <input id="username" name="username" type="text" autocomplete="username" placeholder=" ">
+ <label for="username">Username</label>
+ <input id="password" name="password" type="password" autocomplete="current-password" placeholder=" ">
+ <label for="password">Password</label>
+ <button type="submit">Log in</button>
+ </div>
+ `;
+ }
+ }
+
+ customElements.define('my-login', MyLogin);
+ </script>
+</body>
+</html>
diff --git a/apps/browser-extension/src/utils/formDetector/__tests__/test-forms/shadow-root-3.html b/apps/browser-extension/src/utils/formDetector/__tests__/test-forms/shadow-root-3.html
new file mode 100644
index 000000000..48249c726
--- /dev/null
+++ b/apps/browser-extension/src/utils/formDetector/__tests__/test-forms/shadow-root-3.html
@@ -0,0 +1,47 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Shadow Root Login Form Test 3</title>
+</head>
+<body>
+ <!--
+ Variant of shadow-root-1.html nested two shadow roots deep: an app shell component renders
+ another component, which owns the actual form. Only a recursive traversal reaches these
+ fields.
+ -->
+ <outer-shell></outer-shell>
+
+ <script>
+ class InnerLogin extends HTMLElement {
+ connectedCallback() {
+ if (this.shadowRoot) {
+ return;
+ }
+
+ const shadowRoot = this.attachShadow({ mode: 'open' });
+ shadowRoot.innerHTML = `
+ <form id="login-form">
+ <input id="username" name="username" type="text" autocomplete="username" placeholder=" ">
+ <label for="username">Username</label>
+ <input id="password" name="password" type="password" autocomplete="current-password" placeholder=" ">
+ <label for="password">Password</label>
+ </form>
+ `;
+ }
+ }
+
+ class OuterShell extends HTMLElement {
+ connectedCallback() {
+ if (this.shadowRoot) {
+ return;
+ }
+
+ this.attachShadow({ mode: 'open' }).innerHTML = '<inner-login></inner-login>';
+ }
+ }
+
+ customElements.define('inner-login', InnerLogin);
+ customElements.define('outer-shell', OuterShell);
+ </script>
+</body>
+</html>
diff --git a/apps/browser-extension/src/utils/formDetector/__tests__/test-forms/shadow-root-4.html b/apps/browser-extension/src/utils/formDetector/__tests__/test-forms/shadow-root-4.html
new file mode 100644
index 000000000..4d359576b
--- /dev/null
+++ b/apps/browser-extension/src/utils/formDetector/__tests__/test-forms/shadow-root-4.html
@@ -0,0 +1,83 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Shadow Root Login Form Test 4</title>
+</head>
+<body>
+ <!--
+ A login form built entirely from custom elements, with not a single <input> in the normal
+ DOM: <x-text-input> renders the real input inside its shadow root and keeps every
+ identifying attribute (id, name, autocomplete) plus the visible label
+ (<span slot="label">) on the host in the normal DOM.
+
+ Note that <x-form> is a custom element, not a <form>, so there is no form wrapper to scope
+ detection to either.
+ -->
+ <x-auth-flow class="relative" step-name="login">
+ <span slot="login" feature-name="LoginStep">
+ <x-partial name="LoginStep" src="/svc/partial/login-step">
+ <x-auth-login device-type="desktop" oidc-enabled="true">
+ <x-tabpanel pagenames="login_username_and_password,login_otp_app" pageindex="1">
+ <x-form id="login" method="post" action="/svc/account/login" slot="login_username_and_password">
+ <x-auth-modal class="shadow-sm" pagename="login_username_and_password">
+ <div class="font-sans bg-ui-modalbackground">
+ <h1 class="text-24 text-center font-bold">Log In</h1>
+ <fieldset class="relative p-0 border-0 flex flex-col grow bg-transparent">
+ <x-text-input id="login-username" name="username" autocomplete="username webauthn" required="" helper-text-placeholder="&nbsp;" value="" aria-disabled="false" appearance="secondary">
+ <span slot="label">
+ Email or username
+ </span>
+ </x-text-input>
+ </fieldset>
+ <fieldset class="relative p-0 border-0 flex flex-col grow bg-transparent">
+ <x-text-input id="login-password" class="oidc oidc-hide" name="password" type="password" autocomplete="current-password" helper-text-placeholder="&nbsp;" required="" aria-disabled="false" appearance="secondary">
+ <span slot="label">
+ Password
+ </span>
+ <span slot="trailingIconButton">
+ <button id="login-password-visibility-toggle" type="button">Show password</button>
+ </span>
+ </x-text-input>
+ </fieldset>
+ </div>
+ <div slot="primaryButton" class="w-100">
+ <button class="login w-100 oidc oidc-hide" type="button">Log In</button>
+ </div>
+ </x-auth-modal>
+ </x-form>
+ </x-tabpanel>
+ </x-auth-login>
+ </x-partial>
+ </span>
+ </x-auth-flow>
+
+ <script>
+ /*
+ * The shadow root deliberately renders a bare <input> that carries nothing but its type:
+ * the component keeps name/id/autocomplete/label on the host, so detection has to look
+ * outward through the shadow boundary to recognise the field at all.
+ */
+ class XTextInput extends HTMLElement {
+ connectedCallback() {
+ if (this.shadowRoot) {
+ return;
+ }
+
+ const shadowRoot = this.attachShadow({ mode: 'open' });
+ shadowRoot.innerHTML = `
+ <div class="input-container">
+ <label part="label"><slot name="label"></slot></label>
+ <div class="input-wrapper">
+ <input part="input" type="${this.getAttribute('type') || 'text'}">
+ <slot name="trailingIconButton"></slot>
+ </div>
+ <div class="helper-text"><slot name="helper-text"></slot></div>
+ </div>
+ `;
+ }
+ }
+
+ customElements.define('x-text-input', XTextInput);
+ </script>
+</body>
+</html>
diff --git a/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts b/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts
index 6417f6a19..179629ac2 100644
--- a/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts
+++ b/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts
@@ -1,6 +1,7 @@
import { isAvAutofillAllowed, isAvSuppressSave } from '@/utils/autofill/Autofill';
import { extractFaviconUrlSimple } from '@/utils/favicon';
import { FormDetector } from '@/utils/formDetector/FormDetector';
+import { closestAcrossShadow, collectShadowRoots, queryAllDeep } from '@/utils/ShadowDom';
import type { CapturedLogin, LoginSubmissionEvent, LoginCaptureCallback } from './types';
@@ -27,6 +28,9 @@ export class LoginDetector {
/** MutationObserver for dynamically added forms */
private mutationObserver: MutationObserver | null = null;
+ /** Shadow roots already handed to the MutationObserver, to avoid observing them twice */
+ private readonly observedShadowRoots: WeakSet<ShadowRoot> = new WeakSet();
+
/** Debounce timer to prevent duplicate captures */
private captureDebounceTimer: number | null = null;
private lastCapturedLogin: CapturedLogin | null = null;
@@ -97,8 +101,7 @@ export class LoginDetector {
* Find and monitor all existing forms on the page.
*/
private monitorExistingForms(): void {
- const forms = this.document.querySelectorAll('form');
- forms.forEach(form => this.monitorForm(form));
+ queryAllDeep<HTMLFormElement>(this.document, 'form').forEach(form => this.monitorForm(form));
}
/**
@@ -112,11 +115,17 @@ export class LoginDetector {
this.monitorForm(node);
} else if (node instanceof HTMLElement) {
// Check for forms inside added elements
- const forms = node.querySelectorAll('form');
- forms.forEach(form => this.monitorForm(form));
+ queryAllDeep<HTMLFormElement>(node, 'form').forEach(form => this.monitorForm(form));
// Check for buttons added to existing forms
this.checkForNewButtonsInForms(node);
+
+ /*
+ * A newly added web component often attaches its shadow root only after
+ * the host lands in the DOM, so rescan on the next tick as well as right away.
+ */
+ this.observeShadowRoots(node);
+ setTimeout(() => this.observeShadowRootsAndForms(node), 0);
}
}
}
@@ -126,6 +135,35 @@ export class LoginDetector {
childList: true,
subtree: true,
});
+
+ // Observe every open shadow root reachable from the document
+ this.observeShadowRoots(this.document);
+ }
+
+ /**
+ * Observe every open shadow root reachable from the given root.
+ */
+ private observeShadowRoots(root: Document | HTMLElement): void {
+ if (!this.mutationObserver) {
+ return;
+ }
+
+ for (const shadowRoot of collectShadowRoots(root)) {
+ if (this.observedShadowRoots.has(shadowRoot)) {
+ continue;
+ }
+
+ this.observedShadowRoots.add(shadowRoot);
+ this.mutationObserver.observe(shadowRoot, { childList: true, subtree: true });
+ }
+ }
+
+ /**
+ * Observe newly reachable shadow roots and monitor any forms they already contain.
+ */
+ private observeShadowRootsAndForms(root: Document | HTMLElement): void {
+ this.observeShadowRoots(root);
+ queryAllDeep<HTMLFormElement>(root, 'form').forEach(form => this.monitorForm(form));
}
/**
@@ -134,19 +172,20 @@ export class LoginDetector {
private checkForNewButtonsInForms(element: HTMLElement): void {
// Check if the element itself is a button
if (this.isSubmitButton(element)) {
- const form = element.closest('form');
+ const form = closestAcrossShadow(element, 'form') as HTMLFormElement | null;
if (form && this.monitoredForms.has(form)) {
this.monitorButton(element, form);
}
}
// Check for buttons inside the element
- const buttons = element.querySelectorAll<HTMLElement>(
+ const buttons = queryAllDeep<HTMLElement>(
+ element,
'button[type="submit"], input[type="submit"], button:not([type]), [role="button"]'
);
for (const button of buttons) {
- const form = button.closest('form');
+ const form = closestAcrossShadow(button, 'form') as HTMLFormElement | null;
if (form && this.monitoredForms.has(form)) {
this.monitorButton(button, form);
}