summaryrefslogtreecommitdiffstats
path: root/toolkit/components/formautofill/FormAutofillChild.sys.mjs
blob: c40bfddbce994d483946499158f81d0220cc5e00 (plain)
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  AutoCompleteChild: "resource://gre/actors/AutoCompleteChild.sys.mjs",
  FormAutofill: "resource://autofill/FormAutofill.sys.mjs",
  FormAutofillContent: "resource://autofill/FormAutofillContent.sys.mjs",
  FormAutofillUtils: "resource://gre/modules/shared/FormAutofillUtils.sys.mjs",
  setTimeout: "resource://gre/modules/Timer.sys.mjs",
});

const observer = {
  QueryInterface: ChromeUtils.generateQI([
    "nsIWebProgressListener",
    "nsISupportsWeakReference",
  ]),

  onLocationChange(aWebProgress, aRequest, aLocation, aFlags) {
    // Only handle pushState/replaceState here.
    if (
      !(aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT) ||
      !(aWebProgress.loadType & Ci.nsIDocShell.LOAD_CMD_PUSHSTATE)
    ) {
      return;
    }
    const window = aWebProgress.DOMWindow;
    const formAutofillChild = window.windowGlobalChild.getActor("FormAutofill");
    formAutofillChild.onPageNavigation();
  },

  onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) {
    if (
      // if restoring a previously-rendered presentation (bfcache)
      aStateFlags & Ci.nsIWebProgressListener.STATE_RESTORING &&
      aStateFlags & Ci.nsIWebProgressListener.STATE_STOP
    ) {
      return;
    }

    if (!(aStateFlags & Ci.nsIWebProgressListener.STATE_START)) {
      return;
    }

    // We only care about when a page triggered a load, not the user. For example:
    // clicking refresh/back/forward, typing a URL and hitting enter, and loading a bookmark aren't
    // likely to be when a user wants to save a formautofill data.
    let channel = aRequest.QueryInterface(Ci.nsIChannel);
    let triggeringPrincipal = channel.loadInfo.triggeringPrincipal;
    if (
      triggeringPrincipal.isNullPrincipal ||
      triggeringPrincipal.equals(
        Services.scriptSecurityManager.getSystemPrincipal()
      )
    ) {
      return;
    }

    // Don't handle history navigation, reload, or pushState not triggered via chrome UI.
    // e.g. history.go(-1), location.reload(), history.replaceState()
    if (!(aWebProgress.loadType & Ci.nsIDocShell.LOAD_CMD_NORMAL)) {
      return;
    }

    const window = aWebProgress.DOMWindow;
    const formAutofillChild = window.windowGlobalChild.getActor("FormAutofill");
    formAutofillChild.onPageNavigation();
  },
};

/**
 * Handles content's interactions for the frame.
 */
export class FormAutofillChild extends JSWindowActorChild {
  constructor() {
    super();

    this._nextHandleElement = null;
    this._alreadyDOMContentLoaded = false;
    this._hasDOMContentLoadedHandler = false;
    this._hasPendingTask = false;
    this.testListener = null;

    lazy.AutoCompleteChild.addPopupStateListener(this);
  }

  didDestroy() {
    lazy.AutoCompleteChild.removePopupStateListener(this);
    lazy.FormAutofillContent.didDestroy();
  }

  popupStateChanged(messageName, data, target) {
    let docShell;
    try {
      docShell = this.docShell;
    } catch (ex) {
      lazy.AutoCompleteChild.removePopupStateListener(this);
      return;
    }

    if (!lazy.FormAutofill.isAutofillEnabled) {
      return;
    }

    const { chromeEventHandler } = docShell;

    switch (messageName) {
      case "FormAutoComplete:PopupClosed": {
        lazy.FormAutofillContent.onPopupClosed(data.selectedRowStyle);
        Services.tm.dispatchToMainThread(() => {
          chromeEventHandler.removeEventListener(
            "keydown",
            lazy.FormAutofillContent._onKeyDown,
            true
          );
        });

        break;
      }
      case "FormAutoComplete:PopupOpened": {
        lazy.FormAutofillContent.onPopupOpened();
        chromeEventHandler.addEventListener(
          "keydown",
          lazy.FormAutofillContent._onKeyDown,
          true
        );
        break;
      }
    }
  }

  /**
   * Invokes the FormAutofillContent to identify the autofill fields
   * and consider opening the dropdown menu for the focused field
   *
   */
  _doIdentifyAutofillFields() {
    if (this._hasPendingTask) {
      return;
    }
    this._hasPendingTask = true;

    lazy.setTimeout(() => {
      const isAnyFieldIdentified =
        lazy.FormAutofillContent.identifyAutofillFields(
          this._nextHandleElement
        );
      if (isAnyFieldIdentified) {
        if (lazy.FormAutofill.captureOnFormRemoval) {
          this.registerDOMDocFetchSuccessEventListener(
            this._nextHandleElement.ownerDocument
          );
        }
        if (lazy.FormAutofill.captureOnPageNavigation) {
          this.registerProgressListener();
        }
      }

      this._hasPendingTask = false;
      this._nextHandleElement = null;
      // This is for testing purpose only which sends a notification to indicate that the
      // form has been identified, and ready to open popup.
      this.sendAsyncMessage("FormAutofill:FieldsIdentified");
      lazy.FormAutofillContent.updateActiveInput();
    });
  }

  /**
   * Gets the highest accessible docShell
   *
   * @returns {DocShell} highest accessible docShell
   */
  getHighestDocShell() {
    const window = this.document.defaultView;

    let docShell;
    for (
      let browsingContext = BrowsingContext.getFromWindow(window);
      browsingContext?.docShell;
      browsingContext = browsingContext.parent
    ) {
      docShell = browsingContext.docShell;
    }

    return docShell
      .QueryInterface(Ci.nsIInterfaceRequestor)
      .getInterface(Ci.nsIWebProgress);
  }

  /**
   * After being notified of a page navigation, we check whether
   * the navigated window is the active window or one of its parents
   * (active window = FormAutofillContent.activeHandler.window)
   *
   * @returns {boolean} whether the navigation affects the active window
   */
  isActiveWindowNavigation() {
    const activeWindow = lazy.FormAutofillContent.activeHandler.window;
    const navigatedWindow = this.document.defaultView;
    const navigatedBrowsingContext =
      BrowsingContext.getFromWindow(navigatedWindow);

    for (
      let browsingContext = BrowsingContext.getFromWindow(activeWindow);
      browsingContext?.docShell;
      browsingContext = browsingContext.parent
    ) {
      if (navigatedBrowsingContext === browsingContext) {
        return true;
      }
    }
    return false;
  }

  /**
   * Infer a form submission after document is navigated
   */
  onPageNavigation() {
    const activeElement =
      lazy.FormAutofillContent.activeFieldDetail?.elementWeakRef.deref();

    if (!this.isActiveWindowNavigation()) {
      return;
    }

    const formSubmissionReason =
      lazy.FormAutofillUtils.FORM_SUBMISSION_REASON.PAGE_NAVIGATION;

    // We only capture the form of the active field right now,
    // this means that we might miss some fields (see bug 1871356)
    lazy.FormAutofillContent.formSubmitted(activeElement, formSubmissionReason);
  }

  /**
   * After a form submission we unregister the
   * nsIWebProgressListener from the top level doc shell
   */
  unregisterProgressListener() {
    const docShell = this.getHighestDocShell();
    try {
      docShell.removeProgressListener(observer);
    } catch (ex) {
      // Ignore NS_ERROR_FAILURE if the progress listener was not registered
    }
  }

  /**
   * After a focusin event and after we identified formautofill fields,
   * we set up a nsIWebProgressListener that notifies of a request state
   * change or window location change in the top level doc shell
   */
  registerProgressListener() {
    const docShell = this.getHighestDocShell();

    const flags =
      Ci.nsIWebProgress.NOTIFY_STATE_DOCUMENT |
      Ci.nsIWebProgress.NOTIFY_LOCATION;
    try {
      docShell.addProgressListener(observer, flags);
    } catch (ex) {
      // Ignore NS_ERROR_FAILURE if the progress listener was already added
    }
  }

  /**
   * After a focusin event and after we identify formautofill fields,
   * we set up an event listener for the DOMDocFetchSuccess event
   *
   * @param {Document} document The document we want to be notified by of a DOMDocFetchSuccess event
   */
  registerDOMDocFetchSuccessEventListener(document) {
    document.setNotifyFetchSuccess(true);

    // Is removed after a DOMDocFetchSuccess event (bug 1864855)
    /* eslint-disable mozilla/balanced-listeners */
    this.docShell.chromeEventHandler.addEventListener(
      "DOMDocFetchSuccess",
      this,
      true
    );
  }

  /**
   * After a DOMDocFetchSuccess event, we register an event listener for the DOMFormRemoved event
   *
   * @param {Document} document The document we want to be notified by of a DOMFormRemoved event
   */
  registerDOMFormRemovedEventListener(document) {
    document.setNotifyFormOrPasswordRemoved(true);

    // Is removed after a DOMFormRemoved event (bug 1864855)
    /* eslint-disable mozilla/balanced-listeners */
    this.docShell.chromeEventHandler.addEventListener(
      "DOMFormRemoved",
      this,
      true
    );
  }

  /**
   * After a DOMDocFetchSuccess event we remove the DOMDocFetchSuccess event listener
   *
   * @param {Document} document The document we are notified by of a DOMDocFetchSuccess event
   */
  unregisterDOMDocFetchSuccessEventListener(document) {
    document.setNotifyFetchSuccess(false);
    this.docShell.chromeEventHandler.removeEventListener(
      "DOMDocFetchSuccess",
      this
    );
  }

  /**
   * After a DOMFormRemoved event we remove the DOMFormRemoved event listener
   *
   * @param {Document} document The document we are notified by of a DOMFormRemoved event
   */
  unregisterDOMFormRemovedEventListener(document) {
    document.setNotifyFormOrPasswordRemoved(false);
    this.docShell.chromeEventHandler.removeEventListener(
      "DOMFormRemoved",
      this
    );
  }

  shouldIgnoreFormAutofillEvent(event) {
    let nodePrincipal = event.target.nodePrincipal;
    return (
      nodePrincipal.isSystemPrincipal ||
      nodePrincipal.isNullPrincipal ||
      nodePrincipal.schemeIs("about")
    );
  }

  handleEvent(evt) {
    if (!evt.isTrusted) {
      return;
    }
    if (this.shouldIgnoreFormAutofillEvent(evt)) {
      return;
    }

    switch (evt.type) {
      case "focusin": {
        if (lazy.FormAutofill.isAutofillEnabled) {
          this.onFocusIn(evt);
        }
        break;
      }
      case "DOMFormBeforeSubmit": {
        if (lazy.FormAutofill.isAutofillEnabled) {
          this.onDOMFormBeforeSubmit(evt);
        }
        break;
      }
      case "DOMFormRemoved": {
        this.onDOMFormRemoved(evt);
        break;
      }
      case "DOMDocFetchSuccess": {
        this.onDOMDocFetchSuccess(evt);
        break;
      }

      default: {
        throw new Error("Unexpected event type");
      }
    }
  }

  onFocusIn(evt) {
    lazy.FormAutofillContent.updateActiveInput();

    let element = evt.target;
    if (!lazy.FormAutofillUtils.isCreditCardOrAddressFieldType(element)) {
      return;
    }
    this._nextHandleElement = element;

    if (!this._alreadyDOMContentLoaded) {
      let doc = element.ownerDocument;
      if (doc.readyState === "loading") {
        if (!this._hasDOMContentLoadedHandler) {
          this._hasDOMContentLoadedHandler = true;
          doc.addEventListener(
            "DOMContentLoaded",
            () => this._doIdentifyAutofillFields(),
            { once: true }
          );
        }
        return;
      }
      this._alreadyDOMContentLoaded = true;
    }

    this._doIdentifyAutofillFields();
  }

  /**
   * Handle the DOMFormBeforeSubmit event.
   *
   * @param {Event} evt
   */
  onDOMFormBeforeSubmit(evt) {
    const formElement = evt.target;

    const formSubmissionReason =
      lazy.FormAutofillUtils.FORM_SUBMISSION_REASON.FORM_SUBMIT_EVENT;

    lazy.FormAutofillContent.formSubmitted(formElement, formSubmissionReason);
  }

  /**
   * Handle the DOMFormRemoved event.
   *
   * Infers a form submission when the form is removed
   * after a successful fetch or XHR request.
   *
   * @param {Event} evt DOMFormRemoved
   */
  onDOMFormRemoved(evt) {
    const document = evt.composedTarget.ownerDocument;

    const formSubmissionReason =
      lazy.FormAutofillUtils.FORM_SUBMISSION_REASON.FORM_REMOVAL_AFTER_FETCH;

    lazy.FormAutofillContent.formSubmitted(evt.target, formSubmissionReason);

    this.unregisterDOMFormRemovedEventListener(document);
  }

  /**
   * Handle the DOMDocFetchSuccess event.
   *
   * Sets up an event listener for the DOMFormRemoved event
   * and unregisters the event listener for DOMDocFetchSuccess event.
   *
   * @param {Event} evt DOMDocFetchSuccess
   */
  onDOMDocFetchSuccess(evt) {
    const document = evt.target;

    this.registerDOMFormRemovedEventListener(document);

    this.unregisterDOMDocFetchSuccessEventListener(document);
  }

  receiveMessage(message) {
    if (!lazy.FormAutofill.isAutofillEnabled) {
      return;
    }

    const doc = this.document;

    switch (message.name) {
      case "FormAutofill:PreviewProfile": {
        lazy.FormAutofillContent.previewProfile(doc);
        break;
      }
      case "FormAutofill:ClearForm": {
        lazy.FormAutofillContent.clearForm();
        break;
      }
      case "FormAutofill:FillForm": {
        lazy.FormAutofillContent.activeHandler.autofillFormFields(message.data);
        break;
      }
    }
  }
}