/
autofill-overlay-iframe.service.ts
433 lines (380 loc) · 14 KB
/
autofill-overlay-iframe.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import { EVENTS } from "@bitwarden/common/autofill/constants";
import { ThemeType } from "@bitwarden/common/platform/enums";
import { setElementStyles } from "../../utils";
import {
BackgroundPortMessageHandlers,
AutofillOverlayIframeService as AutofillOverlayIframeServiceInterface,
AutofillOverlayIframeExtensionMessage,
AutofillOverlayIframeWindowMessageHandlers,
} from "../abstractions/autofill-overlay-iframe.service";
class AutofillOverlayIframeService implements AutofillOverlayIframeServiceInterface {
private port: chrome.runtime.Port | null = null;
private extensionOriginsSet: Set<string>;
private iframeMutationObserver: MutationObserver;
private iframe: HTMLIFrameElement;
private ariaAlertElement: HTMLDivElement;
private ariaAlertTimeout: number | NodeJS.Timeout;
private iframeStyles: Partial<CSSStyleDeclaration> = {
all: "initial",
position: "fixed",
display: "block",
zIndex: "2147483647",
lineHeight: "0",
overflow: "hidden",
transition: "opacity 125ms ease-out 0s",
visibility: "visible",
clipPath: "none",
pointerEvents: "auto",
margin: "0",
padding: "0",
colorScheme: "normal",
opacity: "0",
};
private defaultIframeAttributes: Record<string, string> = {
src: "",
title: "",
sandbox: "allow-scripts",
allowtransparency: "true",
tabIndex: "-1",
};
private foreignMutationsCount = 0;
private mutationObserverIterations = 0;
private mutationObserverIterationsResetTimeout: number | NodeJS.Timeout;
private readonly windowMessageHandlers: AutofillOverlayIframeWindowMessageHandlers = {
updateAutofillOverlayListHeight: (message) =>
this.updateElementStyles(this.iframe, message.styles),
getPageColorScheme: () => this.updateOverlayPageColorScheme(),
};
private readonly backgroundPortMessageHandlers: BackgroundPortMessageHandlers = {
initAutofillOverlayList: ({ message }) => this.initAutofillOverlayList(message),
updateIframePosition: ({ message }) => this.updateIframePosition(message.styles),
updateOverlayHidden: ({ message }) => this.updateElementStyles(this.iframe, message.styles),
};
constructor(
private iframePath: string,
private portName: string,
private shadow: ShadowRoot,
) {
this.extensionOriginsSet = new Set([
chrome.runtime.getURL("").slice(0, -1).toLowerCase(), // Remove the trailing slash and normalize the extension url to lowercase
"null",
]);
this.iframeMutationObserver = new MutationObserver(this.handleMutations);
}
/**
* Handles initialization of the iframe which includes applying initial styles
* to the iframe, setting the source, and adding listener that connects the
* iframe to the background script each time it loads. Can conditionally
* create an aria alert element to announce to screen readers when the iframe
* is loaded. The end result is append to the shadowDOM of the custom element
* that is declared.
*
*
* @param initStyles - Initial styles to apply to the iframe
* @param iframeTitle - Title to apply to the iframe
* @param ariaAlert - Text to announce to screen readers when the iframe is loaded
*/
initOverlayIframe(
initStyles: Partial<CSSStyleDeclaration>,
iframeTitle: string,
ariaAlert?: string,
) {
this.defaultIframeAttributes.src = chrome.runtime.getURL(this.iframePath);
this.defaultIframeAttributes.title = iframeTitle;
this.iframe = globalThis.document.createElement("iframe");
this.updateElementStyles(this.iframe, { ...this.iframeStyles, ...initStyles });
for (const [attribute, value] of Object.entries(this.defaultIframeAttributes)) {
this.iframe.setAttribute(attribute, value);
}
this.iframe.addEventListener(EVENTS.LOAD, this.setupPortMessageListener);
if (ariaAlert) {
this.createAriaAlertElement(ariaAlert);
}
this.shadow.appendChild(this.iframe);
}
/**
* Creates an aria alert element that is used to announce to screen readers
* when the iframe is loaded.
*
* @param ariaAlertText - Text to announce to screen readers when the iframe is loaded
*/
private createAriaAlertElement(ariaAlertText: string) {
this.ariaAlertElement = globalThis.document.createElement("div");
this.ariaAlertElement.setAttribute("role", "status");
this.ariaAlertElement.setAttribute("aria-live", "polite");
this.ariaAlertElement.setAttribute("aria-atomic", "true");
this.updateElementStyles(this.ariaAlertElement, {
position: "absolute",
top: "-9999px",
left: "-9999px",
width: "1px",
height: "1px",
overflow: "hidden",
opacity: "0",
pointerEvents: "none",
});
this.ariaAlertElement.textContent = ariaAlertText;
}
/**
* Sets up the port message listener to the extension background script. This
* listener is used to communicate between the iframe and the background script.
* This also facilitates announcing to screen readers when the iframe is loaded.
*/
private setupPortMessageListener = () => {
this.port = chrome.runtime.connect({ name: this.portName });
this.port.onDisconnect.addListener(this.handlePortDisconnect);
this.port.onMessage.addListener(this.handlePortMessage);
globalThis.addEventListener(EVENTS.MESSAGE, this.handleWindowMessage);
this.announceAriaAlert();
};
/**
* Announces the aria alert element to screen readers when the iframe is loaded.
*/
private announceAriaAlert() {
if (!this.ariaAlertElement) {
return;
}
this.ariaAlertElement.remove();
if (this.ariaAlertTimeout) {
clearTimeout(this.ariaAlertTimeout);
}
this.ariaAlertTimeout = setTimeout(() => this.shadow.appendChild(this.ariaAlertElement), 2000);
}
/**
* Handles disconnecting the port message listener from the extension background
* script. This also removes the listener that facilitates announcing to screen
* readers when the iframe is loaded.
*
* @param port - The port that is disconnected
*/
private handlePortDisconnect = (port: chrome.runtime.Port) => {
if (port.name !== this.portName) {
return;
}
this.updateElementStyles(this.iframe, { opacity: "0", height: "0px", display: "block" });
globalThis.removeEventListener("message", this.handleWindowMessage);
this.unobserveIframe();
this.port?.onMessage.removeListener(this.handlePortMessage);
this.port?.onDisconnect.removeListener(this.handlePortDisconnect);
this.port?.disconnect();
this.port = null;
};
/**
* Handles messages sent from the extension background script to the iframe.
* Triggers behavior within the iframe as well as on the custom element that
* contains the iframe element.
*
* @param message
* @param port
*/
private handlePortMessage = (
message: AutofillOverlayIframeExtensionMessage,
port: chrome.runtime.Port,
) => {
if (port.name !== this.portName) {
return;
}
if (this.backgroundPortMessageHandlers[message.command]) {
this.backgroundPortMessageHandlers[message.command]({ message, port });
return;
}
this.iframe.contentWindow?.postMessage(message, "*");
};
/**
* Handles messages sent from the iframe to the extension background script.
* Will adjust the border element to fit the user's set theme.
*
* @param message - The message sent from the iframe
*/
private initAutofillOverlayList(message: AutofillOverlayIframeExtensionMessage) {
const { theme } = message;
let borderColor: string;
let verifiedTheme = theme;
if (verifiedTheme === ThemeType.System) {
verifiedTheme = globalThis.matchMedia("(prefers-color-scheme: dark)").matches
? ThemeType.Dark
: ThemeType.Light;
}
if (verifiedTheme === ThemeType.Dark) {
borderColor = "#4c525f";
}
if (theme === ThemeType.Nord) {
borderColor = "#2E3440";
}
if (theme === ThemeType.SolarizedDark) {
borderColor = "#073642";
}
if (borderColor) {
this.updateElementStyles(this.iframe, { borderColor });
}
message.theme = verifiedTheme;
this.iframe.contentWindow?.postMessage(message, "*");
}
/**
* Updates the position of the iframe element. Will also announce
* to screen readers that the iframe is open.
*
* @param position - The position styles to apply to the iframe
*/
private updateIframePosition(position: Partial<CSSStyleDeclaration>) {
if (!globalThis.document.hasFocus()) {
return;
}
this.updateElementStyles(this.iframe, position);
setTimeout(() => this.updateElementStyles(this.iframe, { opacity: "1" }), 0);
this.announceAriaAlert();
}
/**
* Gets the page color scheme meta tag and sends a message to the iframe
* to update its color scheme. Will default to "normal" if the meta tag
* does not exist.
*/
private updateOverlayPageColorScheme() {
const colorSchemeValue = globalThis.document
.querySelector("meta[name='color-scheme']")
?.getAttribute("content");
this.iframe.contentWindow?.postMessage(
{ command: "updateOverlayPageColorScheme", colorScheme: colorSchemeValue || "normal" },
"*",
);
}
/**
* Handles messages sent from the iframe. If the message does not have a
* specified handler set, it passes the message to the background script.
*
* @param event - The message event
*/
private handleWindowMessage = (event: MessageEvent) => {
if (
!this.port ||
event.source !== this.iframe.contentWindow ||
!this.isFromExtensionOrigin(event.origin.toLowerCase())
) {
return;
}
const message = event.data;
if (this.windowMessageHandlers[message.command]) {
this.windowMessageHandlers[message.command](message);
return;
}
this.port.postMessage(event.data);
};
/**
* Accepts an element and updates the styles for that element. This method
* will also unobserve the element if it is the iframe element. This is
* done to ensure that we do not trigger the mutation observer when we
* update the styles for the iframe.
*
* @param customElement - The element to update the styles for
* @param styles - The styles to apply to the element
*/
private updateElementStyles(customElement: HTMLElement, styles: Partial<CSSStyleDeclaration>) {
if (!customElement) {
return;
}
this.unobserveIframe();
setElementStyles(customElement, styles, true);
this.iframeStyles = { ...this.iframeStyles, ...styles };
this.observeIframe();
}
/**
* Chrome returns null for any sandboxed iframe sources.
* Firefox references the extension URI as its origin.
* Any other origin value is a security risk.
*
* @param messageOrigin - The origin of the window message
*/
private isFromExtensionOrigin(messageOrigin: string): boolean {
return this.extensionOriginsSet.has(messageOrigin);
}
/**
* Handles mutations to the iframe element. The ensures that the iframe
* element's styles are not modified by a third party source.
*
* @param mutations - The mutations to the iframe element
*/
private handleMutations = (mutations: MutationRecord[]) => {
if (this.isTriggeringExcessiveMutationObserverIterations()) {
return;
}
for (let index = 0; index < mutations.length; index++) {
const mutation = mutations[index];
if (mutation.type !== "attributes") {
continue;
}
const element = mutation.target as HTMLElement;
if (mutation.attributeName !== "style") {
this.handleElementAttributeMutation(element);
continue;
}
this.iframe.removeAttribute("style");
this.updateElementStyles(this.iframe, this.iframeStyles);
}
};
/**
* Handles mutations to the iframe element's attributes. This ensures that
* the iframe element's attributes are not modified by a third party source.
*
* @param element - The element to handle attribute mutations for
*/
private handleElementAttributeMutation(element: HTMLElement) {
const attributes = Array.from(element.attributes);
for (let attributeIndex = 0; attributeIndex < attributes.length; attributeIndex++) {
const attribute = attributes[attributeIndex];
if (attribute.name === "style") {
continue;
}
if (this.foreignMutationsCount >= 10) {
this.port?.postMessage({ command: "forceCloseAutofillOverlay" });
break;
}
const defaultIframeAttribute = this.defaultIframeAttributes[attribute.name];
if (!defaultIframeAttribute) {
this.iframe.removeAttribute(attribute.name);
this.foreignMutationsCount++;
continue;
}
if (attribute.value === defaultIframeAttribute) {
continue;
}
this.iframe.setAttribute(attribute.name, defaultIframeAttribute);
this.foreignMutationsCount++;
}
}
/**
* Observes the iframe element for mutations to its style attribute.
*/
private observeIframe() {
this.iframeMutationObserver.observe(this.iframe, { attributes: true });
}
/**
* Unobserves the iframe element for mutations to its style attribute.
*/
private unobserveIframe() {
this.iframeMutationObserver?.disconnect();
}
/**
* Identifies if the mutation observer is triggering excessive iterations.
* Will remove the autofill overlay if any set mutation observer is
* triggering excessive iterations.
*/
private isTriggeringExcessiveMutationObserverIterations() {
const resetCounters = () => {
this.mutationObserverIterations = 0;
this.foreignMutationsCount = 0;
};
if (this.mutationObserverIterationsResetTimeout) {
clearTimeout(this.mutationObserverIterationsResetTimeout);
}
this.mutationObserverIterations++;
this.mutationObserverIterationsResetTimeout = setTimeout(() => resetCounters(), 2000);
if (this.mutationObserverIterations > 20) {
clearTimeout(this.mutationObserverIterationsResetTimeout);
resetCounters();
this.port?.postMessage({ command: "forceCloseAutofillOverlay" });
return true;
}
return false;
}
}
export default AutofillOverlayIframeService;