File: unexpectedScriptLoad.js

package info (click to toggle)
firefox 147.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,683,324 kB
  • sloc: cpp: 7,607,156; javascript: 6,532,492; ansic: 3,775,158; python: 1,415,368; xml: 634,556; asm: 438,949; java: 186,241; sh: 62,751; makefile: 18,079; objc: 13,092; perl: 12,808; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (275 lines) | stat: -rw-r--r-- 8,902 bytes parent folder | download | duplicates (2)
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
/* 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/. */

/**
 * This singleton class controls the Unexpected Script Load Dialog.
 */
var UnexpectedScriptLoadPanel = new (class {
  /** @type {Console?} */
  #console;

  /**
   * The URL of the script being handled by the panel.
   *
   * @type {string}
   */
  #scriptName = "";

  get console() {
    if (!this.#console) {
      this.#console = console.createInstance({
        maxLogLevelPref: "browser.unexpectedScriptLoad.logLevel",
        prefix: "UnexpectedScriptLoad",
      });
    }
    return this.#console;
  }

  /**
   * Where the lazy elements are stored.
   *
   * @type {Record<string, Element>?}
   */
  #lazyElements;

  /**
   * Lazily creates the dom elements, and lazily selects them.
   *
   * @returns {Record<string, Element>}
   */
  get elements() {
    if (!this.#lazyElements) {
      this.#lazyElements = {
        dialogCloseButton: document.querySelector(".dialogClose"),
        reportCheckbox: document.querySelector("#reportCheckbox"),
        emailCheckbox: document.querySelector("#emailCheckbox"),
        emailInput: document.querySelector("#emailInput"),
        allowButton: document.querySelector("#allow-button"),
        blockButton: document.querySelector("#block-button"),
        scriptUrl: document.querySelector(".scriptUrl"),
        unexpectedScriptLoadDetail1: document.querySelector(
          "#unexpected-script-load-detail-1"
        ),
        moreInfoLink: document.querySelector("#more-info-link"),
        learnMoreLink: document.querySelector("#learn-more-link"),
        telemetryDisabledMessage: document.querySelector(
          "#telemetry-disabled-message"
        ),
      };
    }

    return this.#lazyElements;
  }

  /**
   * Initializes the panel when the script loads.
   */
  init() {
    this.console?.log("UnexpectedScriptLoadPanel initialized");

    let args = window.arguments[0];
    let action = args.action;
    this.#scriptName = args.scriptName;
    this.elements.scriptUrl.textContent = this.#scriptName;

    let uploadEnabled = Services.prefs.getBoolPref(
      "datareporting.healthreport.uploadEnabled",
      false
    );

    if (action === "allow") {
      this.setupAllowLayout();
      Glean.unexpectedScriptLoad.scriptAllowedOpened.record();
    } else if (action === "block") {
      Glean.unexpectedScriptLoad.scriptBlockedOpened.record();
      this.setupBlockLayout(uploadEnabled);
    }
    this.setupEventHandlers();

    if (uploadEnabled) {
      this.elements.telemetryDisabledMessage.setAttribute("hidden", "true");
    } else {
      this.elements.telemetryDisabledMessage.removeAttribute("hidden");
    }
    this.elements.reportCheckbox.disabled = !uploadEnabled;
    this.elements.emailCheckbox.disabled = !uploadEnabled;
    this.elements.emailInput.disabled = !uploadEnabled;
    this.elements.emailInput.readOnly = !uploadEnabled;
  }

  setupEventHandlers() {
    this.elements.dialogCloseButton.addEventListener("click", () => {
      this.close(true);
    });
    // This is needed because a simple <a> element on the page run afoul
    // of the "Content windows may never have chrome windows as their openers"
    // error, so we use openTrustedLinkIn instead."
    this.elements.moreInfoLink.addEventListener("click", () => {
      this.onLearnMoreLink();
    });
    this.elements.learnMoreLink.addEventListener("click", () => {
      this.onLearnMoreLink();
    });
    this.elements.allowButton.addEventListener("click", () => {
      this.onAllow();
    });
    this.elements.blockButton.addEventListener("click", () => {
      this.onBlock();
    });
    // If the user has filled in their email, but not checked the report checkbox,
    // we automatically check both report checkboxes when the email input loses focus.
    this.elements.emailInput.addEventListener("change", e => {
      const hasEmail = this.elements.emailInput.value.trim() !== "";
      if (!hasEmail) {
        return;
      }

      // If the user has typed in the email field, and clicks the (unchecked)
      // email checkbox, on blur we would set the email checkbox to checked,
      // then the click event would toggle it back to unchecked. So we need to
      // defer the check to the next event loop tick.
      setTimeout(() => {
        this.console?.warn(`Rechecking checkboxes`);
        if (this.elements.emailInput.value.trim()) {
          this.elements.emailCheckbox.checked = true;
          this.elements.reportCheckbox.checked = true;
        }
      }, 0);

      // The email input field is _inside_ the email checkbox, so we need to
      // stop the click event from propagating to the checkbox
      e.stopPropagation();
    });
    // If the user unchecks the report email checkbox, clear the email field
    // This is a little complicated because
    this.elements.emailCheckbox.addEventListener("change", () => {
      if (!this.elements.emailCheckbox.checked) {
        this.elements.emailInput.value = "";
      }
    });
    // If the user unchecks the report checkbox, clear the email field
    this.elements.reportCheckbox.addEventListener("change", () => {
      if (!this.elements.reportCheckbox.checked) {
        this.elements.emailCheckbox.checked = false;
        this.elements.emailInput.value = "";
      }
    });
  }

  setupAllowLayout() {
    this.elements.unexpectedScriptLoadDetail1.setAttribute(
      "data-l10n-id",
      "unexpected-script-load-detail-1-allow"
    );
    this.elements.allowButton.setAttribute("type", "primary");
    this.elements.blockButton.setAttribute("type", "");
  }

  setupBlockLayout(uploadEnabled) {
    this.elements.unexpectedScriptLoadDetail1.setAttribute(
      "data-l10n-id",
      "unexpected-script-load-detail-1-block"
    );
    this.elements.reportCheckbox.checked = uploadEnabled;
    this.elements.allowButton.setAttribute("type", "");
    this.elements.blockButton.setAttribute("type", "primary");
  }

  /**
   * Hide the pop up (for event handlers).
   *
   * @param {boolean} userDismissed
   */
  close(userDismissed) {
    this.console?.log("UnexpectedScriptLoadPanel is closing");
    if (userDismissed) {
      Glean.unexpectedScriptLoad.dialogDismissed.record();
    }
    window.close();
    GleanPings.unexpectedScriptLoad.submit();
  }

  /*
   * Handler for clicking the learn more link from linked text
   * within the translations panel.
   */
  onLearnMoreLink() {
    Glean.unexpectedScriptLoad.moreInfoOpened.record();
    this.close(false);

    // This is an ugly hack.
    // If a modal is open, we will not focus the tab we are opening, even if we ask to
    //  ref: https://searchfox.org/mozilla-central/rev/fcb776c1d580000af961677f6df3aeef67168a6f/browser/components/tabbrowser/content/tabbrowser.js#438
    // However we do not remove the window-modal-open until _after_ the dialog is closed
    // which is after we open the tab.
    //  ref: https://searchfox.org/mozilla-central/rev/fcb776c1d580000af961677f6df3aeef67168a6f/browser/base/content/browser.js#5180
    window.top.document.documentElement.removeAttribute("window-modal-open");

    window.browsingContext.top.window.openTrustedLinkIn(
      "https://support.mozilla.org/kb/unexpected-script-load",
      "tab"
    );
  }

  maybeReport() {
    if (this.elements.reportCheckbox.checked) {
      let extra = {
        script_url: this.#scriptName,
      };

      if (this.elements.emailCheckbox.checked) {
        extra.user_email = this.elements.emailInput.value.trim();
      }

      Glean.unexpectedScriptLoad.scriptReported.record(extra);
    }
  }

  onBlock() {
    this.console?.log("UnexpectedScriptLoadPanel.onBlock() called");
    Glean.unexpectedScriptLoad.scriptBlocked.record();
    this.maybeReport();

    Services.prefs.setBoolPref(
      "security.block_parent_unrestricted_js_loads.temporary",
      true
    );

    window.browsingContext.top.window.gNotificationBox
      .getNotificationWithValue("unexpected-script-notification")
      ?.close();

    Services.obs.notifyObservers(
      null,
      "UnexpectedJavaScriptLoad-UserTookAction"
    );

    this.close(false);
  }

  onAllow() {
    this.console?.log("UnexpectedScriptLoadPanel.onAllow() called");
    Glean.unexpectedScriptLoad.scriptAllowed.record();
    this.maybeReport();

    Services.prefs.setBoolPref(
      "security.allow_parent_unrestricted_js_loads",
      true
    );

    window.browsingContext.top.window.gNotificationBox
      .getNotificationWithValue("unexpected-script-notification")
      ?.close();

    Services.obs.notifyObservers(
      null,
      "UnexpectedJavaScriptLoad-UserTookAction"
    );

    this.close(false);
  }
})();

// Call the init method when the script loads
UnexpectedScriptLoadPanel.init();