summaryrefslogtreecommitdiffstats
path: root/toolkit/components/reportbrokensite/ReportBrokenSiteChild.sys.mjs
blob: 8220f5b4b6aec0f4948e64765669f46d0c6d2d32 (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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/* 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/. */

import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";

const SCREENSHOT_FORMAT = { format: "jpeg", quality: 75 };

function RunScriptInFrame(win, script) {
  const contentPrincipal = win.document.nodePrincipal;
  const sandbox = Cu.Sandbox([contentPrincipal], {
    sandboxName: "Report Broken Site webcompat.com helper",
    sandboxPrototype: win,
    sameZoneAs: win,
    originAttributes: contentPrincipal.originAttributes,
  });
  return Cu.evalInSandbox(script, sandbox, null, "sandbox eval code", 1);
}

class ConsoleLogHelper {
  static PREVIEW_MAX_ITEMS = 10;
  static LOG_LEVELS = ["debug", "info", "warn", "error"];

  #windowId = undefined;

  constructor(windowId) {
    this.#windowId = windowId;
  }

  getLoggedMessages(alsoIncludePrivate = true) {
    return this.getConsoleAPIMessages().concat(
      this.getScriptErrors(alsoIncludePrivate)
    );
  }

  getConsoleAPIMessages() {
    const ConsoleAPIStorage = Cc[
      "@mozilla.org/consoleAPI-storage;1"
    ].getService(Ci.nsIConsoleAPIStorage);
    let messages = ConsoleAPIStorage.getEvents(this.#windowId);
    return messages.map(evt => {
      const { columnNumber, filename, level, lineNumber, timeStamp } = evt;

      const args = [];
      for (const arg of evt.arguments) {
        args.push(this.#getArgs(arg));
      }

      const message = {
        level,
        log: args,
        uri: filename,
        pos: `${lineNumber}:${columnNumber}`,
      };

      return { timeStamp, message };
    });
  }

  getScriptErrors(alsoIncludePrivate) {
    const messages = Services.console.getMessageArray();
    return messages
      .filter(message => {
        if (message instanceof Ci.nsIScriptError) {
          if (!alsoIncludePrivate && message.isFromPrivateWindow) {
            return false;
          }
          if (this.#windowId && this.#windowId !== message.innerWindowID) {
            return false;
          }
          return true;
        }

        // If this is not an nsIScriptError and we need to do window-based
        // filtering we skip this message.
        return false;
      })
      .map(error => {
        const {
          timeStamp,
          errorMessage,
          sourceName,
          lineNumber,
          columnNumber,
          logLevel,
        } = error;
        const message = {
          level: ConsoleLogHelper.LOG_LEVELS[logLevel],
          log: [errorMessage],
          uri: sourceName,
          pos: `${lineNumber}:${columnNumber}`,
        };
        return { timeStamp, message };
      });
  }

  #getPreview(value) {
    switch (typeof value) {
      case "symbol":
        return value.toString();

      case "function":
        return "function ()";

      case "object":
        if (value === null) {
          return null;
        }
        if (Array.isArray(value)) {
          return `(${value.length})[...]`;
        }
        return "{...}";

      case "undefined":
        return "undefined";

      default:
        try {
          structuredClone(value);
        } catch (_) {
          return `${value}` || "?";
        }
        return value;
    }
  }

  #getArrayPreview(arr) {
    const preview = [];
    let count = 0;
    for (const value of arr) {
      if (++count > ConsoleLogHelper.PREVIEW_MAX_ITEMS) {
        break;
      }
      preview.push(this.#getPreview(value));
    }

    return preview;
  }

  #getObjectPreview(obj) {
    const preview = {};
    let count = 0;
    for (const key of Object.keys(obj)) {
      if (++count > ConsoleLogHelper.PREVIEW_MAX_ITEMS) {
        break;
      }
      preview[key] = this.#getPreview(obj[key]);
    }

    return preview;
  }

  #getArgs(value) {
    if (typeof value === "object" && value !== null) {
      if (Array.isArray(value)) {
        return this.#getArrayPreview(value);
      }
      return this.#getObjectPreview(value);
    }

    return this.#getPreview(value);
  }
}

const FrameworkDetector = {
  hasFastClickPageScript(window) {
    if (window.FastClick) {
      return true;
    }

    for (const property in window) {
      try {
        const proto = window[property].prototype;
        if (proto && proto.needsClick) {
          return true;
        }
      } catch (_) {}
    }

    return false;
  },

  hasMobifyPageScript(window) {
    return !!window.Mobify?.Tag;
  },

  hasMarfeelPageScript(window) {
    return !!window.marfeel;
  },

  checkWindow(window) {
    const script = `
      (function() {
        function ${FrameworkDetector.hasFastClickPageScript};
        function ${FrameworkDetector.hasMobifyPageScript};
        function ${FrameworkDetector.hasMarfeelPageScript};
        const win = window.wrappedJSObject || window;
        return {
          fastclick: hasFastClickPageScript(win),
          mobify: hasMobifyPageScript(win),
          marfeel: hasMarfeelPageScript(win),
        }
      })();
    `;
    return RunScriptInFrame(window, script);
  },
};

function getSysinfoProperty(propertyName, defaultValue) {
  try {
    return Services.sysinfo.getProperty(propertyName);
  } catch (e) {}
  return defaultValue;
}

const BrowserInfo = {
  getAppInfo() {
    const { userAgent } = Cc[
      "@mozilla.org/network/protocol;1?name=http"
    ].getService(Ci.nsIHttpProtocolHandler);
    return {
      applicationName: Services.appinfo.name,
      buildId: Services.appinfo.appBuildID,
      defaultUserAgent: userAgent,
      updateChannel: AppConstants.MOZ_UPDATE_CHANNEL,
      version: AppConstants.MOZ_APP_VERSION_DISPLAY,
    };
  },

  getPrefs() {
    const prefs = {};
    for (const [name, dflt] of Object.entries({
      "layers.acceleration.force-enabled": undefined,
      "gfx.webrender.software": undefined,
      "browser.opaqueResponseBlocking": undefined,
      "extensions.InstallTrigger.enabled": undefined,
      "privacy.resistFingerprinting": undefined,
      "privacy.globalprivacycontrol.enabled": undefined,
    })) {
      prefs[name] = Services.prefs.getBoolPref(name, dflt);
    }
    const cookieBehavior = "network.cookie.cookieBehavior";
    prefs[cookieBehavior] = Services.prefs.getIntPref(cookieBehavior);
    return prefs;
  },

  getPlatformInfo() {
    let memoryMB = getSysinfoProperty("memsize", null);
    if (memoryMB) {
      memoryMB = Math.round(memoryMB / 1024 / 1024);
    }

    const info = {
      fissionEnabled: Services.appinfo.fissionAutostart,
      memoryMB,
      osArchitecture: getSysinfoProperty("arch", null),
      osName: getSysinfoProperty("name", null),
      osVersion: getSysinfoProperty("version", null),
      os: AppConstants.platform,
    };
    if (AppConstants.platform === "android") {
      info.device = getSysinfoProperty("device", null);
      info.isTablet = getSysinfoProperty("tablet", false);
    }
    return info;
  },

  getAllData() {
    return {
      app: BrowserInfo.getAppInfo(),
      prefs: BrowserInfo.getPrefs(),
      platform: BrowserInfo.getPlatformInfo(),
    };
  },
};

export class ReportBrokenSiteChild extends JSWindowActorChild {
  #getWebCompatInfo(docShell) {
    return Promise.all([
      this.#getConsoleLogs(docShell),
      this.sendQuery(
        "GetWebcompatInfoOnlyAvailableInParentProcess",
        SCREENSHOT_FORMAT
      ),
    ]).then(([consoleLog, infoFromParent]) => {
      const { antitracking, graphics, locales, screenshot, security } =
        infoFromParent;

      const browser = BrowserInfo.getAllData();
      browser.graphics = graphics;
      browser.locales = locales;
      browser.security = security;

      const win = docShell.domWindow;
      const frameworks = FrameworkDetector.checkWindow(win);

      if (browser.platform.os !== "linux") {
        delete browser.prefs["layers.acceleration.force-enabled"];
      }

      return {
        antitracking,
        browser,
        consoleLog,
        devicePixelRatio: win.devicePixelRatio,
        frameworks,
        languages: win.navigator.languages,
        screenshot,
        url: win.location.href,
        userAgent: win.navigator.userAgent,
      };
    });
  }

  async #getConsoleLogs(docShell) {
    return this.#getLoggedMessages()
      .flat()
      .sort((a, b) => a.timeStamp - b.timeStamp)
      .map(m => m.message);
  }

  #getLoggedMessages(alsoIncludePrivate = false) {
    const windowId = this.contentWindow.windowGlobalChild.innerWindowId;
    const helper = new ConsoleLogHelper(windowId, alsoIncludePrivate);
    return helper.getLoggedMessages();
  }

  #formatReportDataForWebcompatCom({
    reason,
    description,
    reportUrl,
    reporterConfig,
    webcompatInfo,
  }) {
    const extra_labels = [];

    const message = Object.assign({}, reporterConfig, {
      url: reportUrl,
      category: reason,
      description,
      details: {},
      extra_labels,
    });

    const payload = {
      message,
    };

    if (webcompatInfo) {
      const {
        antitracking,
        browser,
        devicePixelRatio,
        consoleLog,
        frameworks,
        languages,
        screenshot,
        url,
        userAgent,
      } = webcompatInfo;

      const {
        blockList,
        isPrivateBrowsing,
        hasMixedActiveContentBlocked,
        hasMixedDisplayContentBlocked,
        hasTrackingContentBlocked,
      } = antitracking;

      message.blockList = blockList;

      const { app, graphics, prefs, platform, security } = browser;

      const { applicationName, version, updateChannel, defaultUserAgent } = app;

      const {
        fissionEnabled,
        memoryMb,
        osArchitecture,
        osName,
        osVersion,
        device,
        isTablet,
      } = platform;

      const additionalData = {
        applicationName,
        blockList,
        devicePixelRatio,
        finalUserAgent: userAgent,
        fissionEnabled,
        gfxData: graphics,
        hasMixedActiveContentBlocked,
        hasMixedDisplayContentBlocked,
        hasTrackingContentBlocked,
        isPB: isPrivateBrowsing,
        languages,
        memoryMb,
        osArchitecture,
        osName,
        osVersion,
        prefs,
        updateChannel,
        userAgent: defaultUserAgent,
        version,
      };
      if (security !== undefined) {
        additionalData.sec = security;
      }
      if (device !== undefined) {
        additionalData.device = device;
      }
      if (isTablet !== undefined) {
        additionalData.isTablet = isTablet;
      }

      const specialPrefs = {};
      for (const pref of [
        "layers.acceleration.force-enabled",
        "gfx.webrender.software",
      ]) {
        specialPrefs[pref] = prefs[pref];
      }

      const details = Object.assign(message.details, specialPrefs, {
        additionalData,
        buildId: browser.buildId,
        blockList,
        channel: browser.updateChannel,
        hasTouchScreen: browser.graphics.hasTouchScreen,
      });

      // If the user enters a URL unrelated to the current tab,
      // don't bother sending a screnshot or logs/etc
      let sendRecordedPageSpecificDetails = false;
      try {
        const givenUri = new URL(reportUrl);
        const recordedUri = new URL(url);
        sendRecordedPageSpecificDetails =
          givenUri.origin == recordedUri.origin &&
          givenUri.pathname == recordedUri.pathname;
      } catch (_) {}

      if (sendRecordedPageSpecificDetails) {
        payload.screenshot = screenshot;

        details.consoleLog = consoleLog;
        details.frameworks = frameworks;
        details["mixed active content blocked"] =
          antitracking.hasMixedActiveContentBlocked;
        details["mixed passive content blocked"] =
          antitracking.hasMixedDisplayContentBlocked;
        details["tracking content blocked"] =
          antitracking.hasTrackingContentBlocked
            ? `true (${antitracking.blockList})`
            : "false";

        if (antitracking.hasTrackingContentBlocked) {
          extra_labels.push(
            `type-tracking-protection-${antitracking.blockList}`
          );
        }

        for (const [framework, active] of Object.entries(frameworks)) {
          if (!active) {
            continue;
          }
          details[framework] = true;
          extra_labels.push(`type-${framework}`);
        }
      }
    }

    return payload;
  }

  #stripNonASCIIChars(str) {
    // eslint-disable-next-line no-control-regex
    return str.replace(/[^\x00-\x7F]/g, "");
  }

  async receiveMessage(msg) {
    const { docShell } = this;
    switch (msg.name) {
      case "SendDataToWebcompatCom": {
        const win = docShell.domWindow;
        const expectedEndpoint = msg.data.endpointUrl;
        if (win.location.href == expectedEndpoint) {
          // Ensure that the tab has fully loaded and is waiting for messages
          const onLoad = () => {
            const payload = this.#formatReportDataForWebcompatCom(msg.data);
            const json = this.#stripNonASCIIChars(JSON.stringify(payload));
            const expectedOrigin = JSON.stringify(
              new URL(expectedEndpoint).origin
            );
            // webcompat.com checks that the message comes from its own origin
            const script = `
            const wrtReady = window.wrappedJSObject?.wrtReady;
            if (wrtReady) {
              console.info("Report Broken Site is waiting");
            }
            Promise.resolve(wrtReady).then(() => {
              console.debug(${json});
              postMessage(${json}, ${expectedOrigin})
            });`;
            RunScriptInFrame(win, script);
          };
          if (win.document.readyState == "complete") {
            onLoad();
          } else {
            win.addEventListener("load", onLoad, { once: true });
          }
        }
        return null;
      }
      case "GetWebCompatInfo": {
        return this.#getWebCompatInfo(docShell);
      }
      case "GetConsoleLog": {
        return this.#getLoggedMessages();
      }
    }
    return null;
  }
}