1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
9 ChromeUtils.defineESModuleGetters(lazy, {
10 AddonManager: "resource://gre/modules/AddonManager.sys.mjs",
11 BrowserUtils: "resource://gre/modules/BrowserUtils.sys.mjs",
12 FXA_PWDMGR_HOST: "resource://gre/modules/FxAccountsCommon.sys.mjs",
13 FXA_PWDMGR_REALM: "resource://gre/modules/FxAccountsCommon.sys.mjs",
14 LoginBreaches: "resource:///modules/LoginBreaches.sys.mjs",
15 LoginHelper: "resource://gre/modules/LoginHelper.sys.mjs",
16 PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
17 Region: "resource://gre/modules/Region.sys.mjs",
20 ChromeUtils.defineLazyGetter(lazy, "fxAccounts", () => {
21 return ChromeUtils.importESModule(
22 "resource://gre/modules/FxAccounts.sys.mjs"
23 ).getFxAccountsSingleton();
26 XPCOMUtils.defineLazyServiceGetter(
29 "@mozilla.org/tracking-db-service;1",
30 "nsITrackingDBService"
33 let idToTextMap = new Map([
34 [Ci.nsITrackingDBService.TRACKERS_ID, "tracker"],
35 [Ci.nsITrackingDBService.TRACKING_COOKIES_ID, "cookie"],
36 [Ci.nsITrackingDBService.CRYPTOMINERS_ID, "cryptominer"],
37 [Ci.nsITrackingDBService.FINGERPRINTERS_ID, "fingerprinter"],
38 [Ci.nsITrackingDBService.SOCIAL_ID, "social"],
41 const MONITOR_API_ENDPOINT = Services.urlFormatter.formatURLPref(
42 "browser.contentblocking.report.endpoint_url"
45 const SECURE_PROXY_ADDON_ID = "secure-proxy@mozilla.com";
47 const SCOPE_MONITOR = [
49 "https://identity.mozilla.com/apps/monitor",
52 const SCOPE_VPN = "profile https://identity.mozilla.com/account/subscriptions";
53 const VPN_ENDPOINT = `${Services.prefs.getStringPref(
54 "identity.fxaccounts.auth.uri"
55 )}oauth/subscriptions/active`;
57 // The ID of the vpn subscription, if we see this ID attached to a user's account then they have subscribed to vpn.
58 const VPN_SUB_ID = Services.prefs.getStringPref(
59 "browser.contentblocking.report.vpn_sub_id"
63 const INVALID_OAUTH_TOKEN = "Invalid OAuth token";
64 const USER_UNSUBSCRIBED_TO_MONITOR = "User is not subscribed to Monitor";
65 const SERVICE_UNAVAILABLE = "Service unavailable";
66 const UNEXPECTED_RESPONSE = "Unexpected response";
67 const UNKNOWN_ERROR = "Unknown error";
69 // Valid response info for successful Monitor data
70 const MONITOR_RESPONSE_PROPS = [
74 "numBreachesResolved",
78 let gTestOverride = null;
79 let monitorResponse = null;
80 let entrypoint = "direct";
82 export class AboutProtectionsParent extends JSWindowActorParent {
87 // Some tests wish to override certain functions with ones that mostly do nothing.
88 static setTestOverride(callback) {
89 gTestOverride = callback;
93 * Fetches and validates data from the Monitor endpoint. If successful, then return
94 * expected data. Otherwise, throw the appropriate error depending on the status code.
96 * @return valid data from endpoint.
98 async fetchUserBreachStats(token) {
99 if (monitorResponse && monitorResponse.timestamp) {
100 var timeDiff = Date.now() - monitorResponse.timestamp;
101 let oneDayInMS = 24 * 60 * 60 * 1000;
102 if (timeDiff >= oneDayInMS) {
103 monitorResponse = null;
105 return monitorResponse;
110 const headers = new Headers();
111 headers.append("Authorization", `Bearer ${token}`);
112 const request = new Request(MONITOR_API_ENDPOINT, { headers });
113 const response = await fetch(request);
116 // Validate the shape of the response is what we're expecting.
117 const json = await response.json();
119 // Make sure that we're getting the expected data.
121 for (let prop in json) {
122 isValid = MONITOR_RESPONSE_PROPS.includes(prop);
129 monitorResponse = isValid ? json : new Error(UNEXPECTED_RESPONSE);
131 monitorResponse.timestamp = Date.now();
134 // Check the reason for the error
135 switch (response.status) {
138 monitorResponse = new Error(INVALID_OAUTH_TOKEN);
141 monitorResponse = new Error(USER_UNSUBSCRIBED_TO_MONITOR);
144 monitorResponse = new Error(SERVICE_UNAVAILABLE);
147 monitorResponse = new Error(UNKNOWN_ERROR);
152 if (monitorResponse instanceof Error) {
153 throw monitorResponse;
155 return monitorResponse;
159 * Retrieves login data for the user.
163 * potentiallyBreachedLogins: Number,
164 * mobileDeviceConnected: Boolean }}
166 async getLoginData() {
167 if (gTestOverride && "getLoginData" in gTestOverride) {
168 return gTestOverride.getLoginData();
172 if (await lazy.fxAccounts.getSignedInUser()) {
173 await lazy.fxAccounts.device.refreshDeviceList();
176 console.error("There was an error fetching login data: ", e.message);
179 const userFacingLogins =
180 Services.logins.countLogins("", "", "") -
181 Services.logins.countLogins(
182 lazy.FXA_PWDMGR_HOST,
184 lazy.FXA_PWDMGR_REALM
187 let potentiallyBreachedLogins = null;
188 // Get the stats for number of potentially breached Lockwise passwords
189 // if the Primary Password isn't locked.
190 if (userFacingLogins && Services.logins.isLoggedIn) {
191 const logins = await lazy.LoginHelper.getAllUserFacingLogins();
192 potentiallyBreachedLogins =
193 await lazy.LoginBreaches.getPotentialBreachesByLoginGUID(logins);
196 let mobileDeviceConnected =
197 lazy.fxAccounts.device.recentDeviceList &&
198 lazy.fxAccounts.device.recentDeviceList.filter(
199 device => device.type == "mobile"
203 numLogins: userFacingLogins,
204 potentiallyBreachedLogins: potentiallyBreachedLogins
205 ? potentiallyBreachedLogins.size
207 mobileDeviceConnected,
212 * Retrieves monitor data for the user.
214 * @return {{ monitoredEmails: Number,
215 * numBreaches: Number,
217 * userEmail: String|null,
221 async getMonitorData() {
222 if (gTestOverride && "getMonitorData" in gTestOverride) {
223 monitorResponse = gTestOverride.getMonitorData();
224 monitorResponse.timestamp = Date.now();
225 // In a test, expect this to not fetch from the monitor endpoint due to the timestamp guaranteeing we use the cache.
226 monitorResponse = await this.fetchUserBreachStats();
227 return monitorResponse;
230 let monitorData = {};
231 let userEmail = null;
232 let token = await this.getMonitorScopedOAuthToken();
236 monitorData = await this.fetchUserBreachStats(token);
238 // Send back user's email so the protections report can direct them to the proper
239 // OAuth flow on Monitor.
240 const { email } = await lazy.fxAccounts.getSignedInUser();
243 // If no account exists, then the user is not logged in with an fxAccount.
245 errorMessage: "No account",
249 console.error(e.message);
250 monitorData.errorMessage = e.message;
252 // If the user's OAuth token is invalid, we clear the cached token and refetch
253 // again. If OAuth token is invalid after the second fetch, then the monitor UI
254 // will simply show the "no logins" UI version.
255 if (e.message === INVALID_OAUTH_TOKEN) {
256 await lazy.fxAccounts.removeCachedOAuthToken({ token });
257 token = await this.getMonitorScopedOAuthToken();
260 monitorData = await this.fetchUserBreachStats(token);
262 console.error(e.message);
264 } else if (e.message === USER_UNSUBSCRIBED_TO_MONITOR) {
265 // Send back user's email so the protections report can direct them to the proper
266 // OAuth flow on Monitor.
267 const { email } = await lazy.fxAccounts.getSignedInUser();
270 monitorData.errorMessage = e.message || "An error ocurred.";
277 error: !!monitorData.errorMessage,
281 async getMonitorScopedOAuthToken() {
285 token = await lazy.fxAccounts.getOAuthToken({ scope: SCOPE_MONITOR });
288 "There was an error fetching the user's token: ",
297 * The proxy card will only show if the user is in the US, has the browser language in "en-US",
298 * and does not yet have Proxy installed.
300 async shouldShowProxyCard() {
301 const region = lazy.Region.home || "";
302 const languages = Services.prefs.getComplexValue(
303 "intl.accept_languages",
304 Ci.nsIPrefLocalizedString
306 const alreadyInstalled = await lazy.AddonManager.getAddonByID(
307 SECURE_PROXY_ADDON_ID
311 region.toLowerCase() === "us" &&
313 languages.data.toLowerCase().includes("en-us")
317 async VPNSubStatus() {
318 // For testing, set vpn sub status manually
319 if (gTestOverride && "vpnOverrides" in gTestOverride) {
320 return gTestOverride.vpnOverrides();
325 vpnToken = await lazy.fxAccounts.getOAuthToken({ scope: SCOPE_VPN });
328 "There was an error fetching the user's token: ",
331 // there was an error, assume user is not subscribed to VPN
334 let headers = new Headers();
335 headers.append("Authorization", `Bearer ${vpnToken}`);
336 const request = new Request(VPN_ENDPOINT, { headers });
337 const res = await fetch(request);
339 const result = await res.json();
340 for (let sub of result) {
341 if (sub.subscriptionId == VPN_SUB_ID) {
347 // unknown logic: assume user is not subscribed to VPN
351 async receiveMessage(aMessage) {
352 let win = this.browsingContext.top.embedderElement.ownerGlobal;
353 switch (aMessage.name) {
354 case "OpenAboutLogins":
355 lazy.LoginHelper.openPasswordManager(win, {
356 entryPoint: "aboutprotections",
359 case "OpenContentBlockingPreferences":
360 win.openPreferences("privacy-trackingprotection", {
361 origin: "about-protections",
364 case "OpenSyncPreferences":
365 win.openTrustedLinkIn("about:preferences#sync", "tab");
367 case "FetchContentBlockingEvents":
369 let displayNames = new Services.intl.DisplayNames(undefined, {
371 style: "abbreviated",
375 // Weekdays starting Sunday (7) to Saturday (6).
376 let weekdays = [7, 1, 2, 3, 4, 5, 6].map(day => displayNames.of(day));
377 dataToSend.weekdays = weekdays;
379 if (lazy.PrivateBrowsingUtils.isWindowPrivate(win)) {
380 dataToSend.isPrivate = true;
383 let sumEvents = await lazy.TrackingDBService.sumAllEvents();
385 await lazy.TrackingDBService.getEarliestRecordedDate();
386 let eventsByDate = await lazy.TrackingDBService.getEventsByDateRange(
392 for (let result of eventsByDate) {
393 let count = result.getResultByName("count");
394 let type = result.getResultByName("type");
395 let timestamp = result.getResultByName("timestamp");
396 dataToSend[timestamp] = dataToSend[timestamp] || { total: 0 };
397 dataToSend[timestamp][idToTextMap.get(type)] = count;
398 dataToSend[timestamp].total += count;
399 // Record the largest amount of tracking events found per day,
400 // to create the tallest column on the graph and compare other days to.
401 if (largest < dataToSend[timestamp].total) {
402 largest = dataToSend[timestamp].total;
405 dataToSend.largest = largest;
406 dataToSend.earliestDate = earliestDate;
407 dataToSend.sumEvents = sumEvents;
411 case "FetchMonitorData":
412 return this.getMonitorData();
414 case "FetchUserLoginsData":
415 return this.getLoginData();
417 case "ClearMonitorCache":
418 monitorResponse = null;
421 case "GetShowProxyCard":
422 let card = await this.shouldShowProxyCard();
425 case "RecordEntryPoint":
426 entrypoint = aMessage.data.entrypoint;
429 case "FetchEntryPoint":
432 case "FetchVPNSubStatus":
433 return this.VPNSubStatus();
435 case "FetchShowVPNCard":
436 return lazy.BrowserUtils.shouldShowVPNPromo();