1 // -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
7 import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
11 ChromeUtils.defineESModuleGetters(lazy, {
12 ContextualIdentityService:
13 "resource://gre/modules/ContextualIdentityService.sys.mjs",
14 FormHistory: "resource://gre/modules/FormHistory.sys.mjs",
15 PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
16 PrincipalsCollector: "resource://gre/modules/PrincipalsCollector.sys.mjs",
19 XPCOMUtils.defineLazyPreferenceGetter(
21 "useOldClearHistoryDialog",
22 "privacy.sanitize.useOldClearHistoryDialog",
27 function log(...msgs) {
29 logConsole = console.createInstance({
31 maxLogLevelPref: "browser.sanitizer.loglevel",
35 logConsole.log(...msgs);
38 // Used as unique id for pending sanitizations.
39 var gPendingSanitizationSerial = 0;
41 var gPrincipalsCollector = null;
43 export var Sanitizer = {
45 * Whether we should sanitize on shutdown.
47 PREF_SANITIZE_ON_SHUTDOWN: "privacy.sanitize.sanitizeOnShutdown",
50 * During a sanitization this is set to a JSON containing an array of the
51 * pending sanitizations. This allows to retry sanitizations on startup in
52 * case they dind't run or were interrupted by a crash.
53 * Use addPendingSanitization and removePendingSanitization to manage it.
55 PREF_PENDING_SANITIZATIONS: "privacy.sanitize.pending",
58 * Pref branches to fetch sanitization options from.
60 PREF_CPD_BRANCH: "privacy.cpd.",
61 PREF_SHUTDOWN_BRANCH: "privacy.clearOnShutdown.",
62 PREF_SHUTDOWN_V2_BRANCH: "privacy.clearOnShutdown_v2.",
65 * The fallback timestamp used when no argument is given to
66 * Sanitizer.getClearRange.
68 PREF_TIMESPAN: "privacy.sanitize.timeSpan",
71 * Pref to newTab segregation. If true, on shutdown, the private container
72 * used in about:newtab is cleaned up. Exposed because used in tests.
74 PREF_NEWTAB_SEGREGATION:
75 "privacy.usercontext.about_newtab_segregation.enabled",
78 * Time span constants corresponding to values of the privacy.sanitize.timeSpan
79 * pref. Used to determine how much history to clear, for various items
81 TIMESPAN_EVERYTHING: 0,
90 * Mapping time span constants to get total time in ms from the selected
94 TIMESPAN_5MIN: 300000, // 5*60*1000
95 TIMESPAN_HOUR: 3600000, // 60*60*1000
96 TIMESPAN_2HOURS: 7200000, // 2*60*60*1000
97 TIMESPAN_4HOURS: 14400000, // 4*60*60*1000
98 TIMESPAN_24HOURS: 86400000, // 24*60*60*1000
99 get TIMESPAN_TODAY() {
100 return Date.now() - new Date().setHours(0, 0, 0, 0);
101 }, // time spent today
105 * Whether we should sanitize on shutdown.
106 * When this is set, a pending sanitization should also be added and removed
107 * when shutdown sanitization is complete. This allows to retry incomplete
108 * sanitizations on startup.
110 shouldSanitizeOnShutdown: false,
113 * Whether we should sanitize the private container for about:newtab.
115 shouldSanitizeNewTabContainer: false,
118 * Shows a sanitization dialog to the user. Returns after the dialog box has
121 * @param parentWindow the browser window to use as parent for the created
123 * @param {string} mode - flag to let the dialog know if it is opened
124 * using the clear on shutdown (clearOnShutdown) settings option
125 * in about:preferences or in a clear site data context (clearSiteData)
127 * @throws if parentWindow is undefined or doesn't have a gDialogBox.
129 showUI(parentWindow, mode) {
130 // Treat the hidden window as not being a parent window:
132 parentWindow?.document.documentURI ==
133 "chrome://browser/content/hiddenWindowMac.xhtml"
138 let dialogFile = lazy.useOldClearHistoryDialog
140 : "sanitize_v2.xhtml";
142 if (parentWindow?.gDialogBox) {
143 parentWindow.gDialogBox.open(`chrome://browser/content/${dialogFile}`, {
144 inBrowserWindow: true,
148 Services.ww.openWindow(
150 `chrome://browser/content/${dialogFile}`,
152 "chrome,titlebar,dialog,centerscreen,modal",
153 { needNativeUI: true, mode }
159 * Performs startup tasks:
160 * - Checks if sanitizations were not completed during the last session.
161 * - Registers sanitize-on-shutdown.
164 // First, collect pending sanitizations from the last session, before we
165 // add pending sanitizations for this session.
166 let pendingSanitizations = getAndClearPendingSanitizations();
167 log("Pending sanitizations:", pendingSanitizations);
169 // Check if we should sanitize on shutdown.
170 this.shouldSanitizeOnShutdown = Services.prefs.getBoolPref(
171 Sanitizer.PREF_SANITIZE_ON_SHUTDOWN,
174 Services.prefs.addObserver(Sanitizer.PREF_SANITIZE_ON_SHUTDOWN, this, true);
175 // Add a pending shutdown sanitization, if necessary.
176 if (this.shouldSanitizeOnShutdown) {
177 let itemsToClear = getItemsToClearFromPrefBranch(
178 Sanitizer.PREF_SHUTDOWN_BRANCH
180 addPendingSanitization("shutdown", itemsToClear, {});
182 // Shutdown sanitization is always pending, but the user may change the
183 // sanitize on shutdown prefs during the session. Then the pending
184 // sanitization would become stale and must be updated.
185 Services.prefs.addObserver(Sanitizer.PREF_SHUTDOWN_BRANCH, this, true);
187 // Make sure that we are triggered during shutdown.
188 let shutdownClient = lazy.PlacesUtils.history.shutdownClient.jsclient;
189 // We need to pass to sanitize() (through sanitizeOnShutdown) a state object
190 // that tracks the status of the shutdown blocker. This `progress` object
191 // will be updated during sanitization and reported with the crash in case of
192 // a shutdown timeout.
193 // We use the `options` argument to pass the `progress` object to sanitize().
194 let progress = { isShutdown: true, clearHonoringExceptions: true };
195 shutdownClient.addBlocker(
196 "sanitize.js: Sanitize on shutdown",
197 () => sanitizeOnShutdown(progress),
198 { fetchState: () => ({ progress }) }
201 this.shouldSanitizeNewTabContainer = Services.prefs.getBoolPref(
202 this.PREF_NEWTAB_SEGREGATION,
205 if (this.shouldSanitizeNewTabContainer) {
206 addPendingSanitization("newtab-container", [], {});
209 let i = pendingSanitizations.findIndex(s => s.id == "newtab-container");
211 pendingSanitizations.splice(i, 1);
212 sanitizeNewTabSegregation();
215 // Finally, run the sanitizations that were left pending, because we crashed
216 // before completing them.
217 for (let { itemsToClear, options } of pendingSanitizations) {
219 // We need to set this flag to watch out for the users exceptions like we do on shutdown
220 options.progress = { clearHonoringExceptions: true };
221 await this.sanitize(itemsToClear, options);
224 "A previously pending sanitization failed: ",
233 * Returns a 2 element array representing the start and end times,
234 * in the uSec-since-epoch format that PRTime likes. If we should
235 * clear everything, this function returns null.
237 * @param ts [optional] a timespan to convert to start and end time.
238 * Falls back to the privacy.sanitize.timeSpan preference
239 * if this argument is omitted.
240 * If this argument is provided, it has to be one of the
241 * Sanitizer.TIMESPAN_* constants. This function will
242 * throw an error otherwise.
244 * @return {Array} a 2-element Array containing the start and end times.
247 if (ts === undefined) {
248 ts = Services.prefs.getIntPref(Sanitizer.PREF_TIMESPAN);
250 if (ts === Sanitizer.TIMESPAN_EVERYTHING) {
254 // PRTime is microseconds while JS time is milliseconds
255 var endDate = Date.now() * 1000;
257 case Sanitizer.TIMESPAN_5MIN:
258 var startDate = endDate - 300000000; // 5*60*1000000
260 case Sanitizer.TIMESPAN_HOUR:
261 startDate = endDate - 3600000000; // 1*60*60*1000000
263 case Sanitizer.TIMESPAN_2HOURS:
264 startDate = endDate - 7200000000; // 2*60*60*1000000
266 case Sanitizer.TIMESPAN_4HOURS:
267 startDate = endDate - 14400000000; // 4*60*60*1000000
269 case Sanitizer.TIMESPAN_TODAY:
270 var d = new Date(); // Start with today
271 d.setHours(0); // zero us back to midnight...
274 d.setMilliseconds(0);
275 startDate = d.valueOf() * 1000; // convert to epoch usec
277 case Sanitizer.TIMESPAN_24HOURS:
278 startDate = endDate - 86400000000; // 24*60*60*1000000
281 throw new Error("Invalid time span for clear private data: " + ts);
283 return [startDate, endDate];
287 * Deletes privacy sensitive data in a batch, according to user preferences.
288 * Returns a promise which is resolved if no errors occurred. If an error
289 * occurs, a message is reported to the console and all other items are still
290 * cleared before the promise is finally rejected.
292 * @param [optional] itemsToClear
293 * Array of items to be cleared. if specified only those
294 * items get cleared, irrespectively of the preference settings.
295 * @param [optional] options
296 * Object whose properties are options for this sanitization:
297 * - ignoreTimespan (default: true): Time span only makes sense in
298 * certain cases. Consumers who want to only clear some private
299 * data can opt in by setting this to false, and can optionally
300 * specify a specific range.
301 * If timespan is not ignored, and range is not set, sanitize() will
302 * use the value of the timespan pref to determine a range.
303 * - range (default: null): array-tuple of [from, to] timestamps
304 * - privateStateForNewWindow (default: "non-private"): when clearing
305 * open windows, defines the private state for the newly opened window.
306 * @returns {object} An object containing debug information about the
307 * sanitization progress. This state object is also used as
308 * AsyncShutdown metadata.
310 async sanitize(itemsToClear = null, options = {}) {
311 let progress = options.progress;
312 // initialise the principals collector
313 gPrincipalsCollector = new lazy.PrincipalsCollector();
315 progress = options.progress = {};
319 itemsToClear = getItemsToClearFromPrefBranch(this.PREF_CPD_BRANCH);
321 let promise = sanitizeInternal(this.items, itemsToClear, options);
323 // Depending on preferences, the sanitizer may perform asynchronous
324 // work before it starts cleaning up the Places database (e.g. closing
325 // windows). We need to make sure that the connection to that database
326 // hasn't been closed by the time we use it.
327 // Though, if this is a sanitize on shutdown, we already have a blocker.
328 if (!progress.isShutdown) {
329 let shutdownClient = lazy.PlacesUtils.history.shutdownClient.jsclient;
330 shutdownClient.addBlocker("sanitize.js: Sanitize", promise, {
331 fetchState: () => ({ progress }),
338 Services.obs.notifyObservers(null, "sanitizer-sanitization-complete");
343 observe(subject, topic, data) {
344 if (topic == "nsPref:changed") {
346 data.startsWith(this.PREF_SHUTDOWN_BRANCH) &&
347 this.shouldSanitizeOnShutdown
349 // Update the pending shutdown sanitization.
350 removePendingSanitization("shutdown");
351 let itemsToClear = getItemsToClearFromPrefBranch(
352 Sanitizer.PREF_SHUTDOWN_BRANCH
354 addPendingSanitization("shutdown", itemsToClear, {});
355 } else if (data == this.PREF_SANITIZE_ON_SHUTDOWN) {
356 this.shouldSanitizeOnShutdown = Services.prefs.getBoolPref(
357 Sanitizer.PREF_SANITIZE_ON_SHUTDOWN,
360 removePendingSanitization("shutdown");
361 if (this.shouldSanitizeOnShutdown) {
362 let itemsToClear = getItemsToClearFromPrefBranch(
363 Sanitizer.PREF_SHUTDOWN_BRANCH
365 addPendingSanitization("shutdown", itemsToClear, {});
367 } else if (data == this.PREF_NEWTAB_SEGREGATION) {
368 this.shouldSanitizeNewTabContainer = Services.prefs.getBoolPref(
369 this.PREF_NEWTAB_SEGREGATION,
372 removePendingSanitization("newtab-container");
373 if (this.shouldSanitizeNewTabContainer) {
374 addPendingSanitization("newtab-container", [], {});
380 QueryInterface: ChromeUtils.generateQI([
382 "nsISupportsWeakReference",
385 // This method is meant to be used by tests.
386 async runSanitizeOnShutdown() {
387 // The collector needs to be reset for each test, as the collection only happens
388 // once and does not update after that.
389 // Pretend that it has never been initialized to mimic the actual browser behavior
390 // by setting it to null.
391 // The actually initialization will happen either via sanitize() or directly in
392 // sanitizeOnShutdown.
393 gPrincipalsCollector = null;
394 return sanitizeOnShutdown({
396 clearHonoringExceptions: true,
401 * Migrate old sanitize prefs to the new prefs for the new
402 * clear history dialog. Does nothing if the migration was completed before
403 * based on the pref privacy.sanitize.cpd.hasMigratedToNewPrefs or
404 * privacy.sanitize.clearOnShutdown.hasMigratedToNewPrefs
406 * @param {string} context - one of "clearOnShutdown" or "cpd", which indicates which
407 * pref branch to migrate prefs from based on the dialog context
409 maybeMigratePrefs(context) {
411 Services.prefs.getBoolPref(
412 `privacy.sanitize.${context}.hasMigratedToNewPrefs`
418 let cookies = Services.prefs.getBoolPref(`privacy.${context}.cookies`);
419 let history = Services.prefs.getBoolPref(`privacy.${context}.history`);
420 let cache = Services.prefs.getBoolPref(`privacy.${context}.cache`);
421 let siteSettings = Services.prefs.getBoolPref(
422 `privacy.${context}.siteSettings`
426 context == "clearOnShutdown" ? "clearOnShutdown_v2" : "clearHistory";
428 // We set cookiesAndStorage to true if cookies are enabled for clearing on shutdown
429 // regardless of what sessions and offlineApps are set to
430 // This is because cookie clearing behaviour takes precedence over sessions and offlineApps clearing.
431 Services.prefs.setBoolPref(
432 `privacy.${newContext}.cookiesAndStorage`,
436 // we set historyFormDataAndDownloads to true if history is enabled for clearing on
437 // shutdown, regardless of what form data is set to.
438 // This is because history clearing behavious takes precedence over formdata clearing.
439 Services.prefs.setBoolPref(
440 `privacy.${newContext}.historyFormDataAndDownloads`,
444 // cache and siteSettings follow the old dialog prefs
445 Services.prefs.setBoolPref(`privacy.${newContext}.cache`, cache);
447 Services.prefs.setBoolPref(
448 `privacy.${newContext}.siteSettings`,
452 Services.prefs.setBoolPref(
453 `privacy.sanitize.${context}.hasMigratedToNewPrefs`,
458 // When making any changes to the sanitize implementations here,
459 // please check whether the changes are applicable to Android
460 // (mobile/android/modules/geckoview/GeckoViewStorageController.sys.mjs) as well.
466 TelemetryStopwatch.start("FX_SANITIZE_CACHE", refObj);
467 await clearData(range, Ci.nsIClearDataService.CLEAR_ALL_CACHES);
468 TelemetryStopwatch.finish("FX_SANITIZE_CACHE", refObj);
473 async clear(range, { progress }, clearHonoringExceptions) {
475 TelemetryStopwatch.start("FX_SANITIZE_COOKIES_2", refObj);
476 // This is true if called by sanitizeOnShutdown.
477 // On shutdown we clear by principal to be able to honor the users exceptions
478 if (clearHonoringExceptions) {
479 progress.step = "getAllPrincipals";
480 let principalsForShutdownClearing =
481 await gPrincipalsCollector.getAllPrincipals(progress);
482 await maybeSanitizeSessionPrincipals(
484 principalsForShutdownClearing,
485 Ci.nsIClearDataService.CLEAR_COOKIES |
486 Ci.nsIClearDataService.CLEAR_COOKIE_BANNER_EXECUTED_RECORD |
487 Ci.nsIClearDataService.CLEAR_FINGERPRINTING_PROTECTION_STATE |
488 Ci.nsIClearDataService.CLEAR_BOUNCE_TRACKING_PROTECTION_STATE
494 Ci.nsIClearDataService.CLEAR_COOKIES |
495 Ci.nsIClearDataService.CLEAR_COOKIE_BANNER_EXECUTED_RECORD |
496 Ci.nsIClearDataService.CLEAR_FINGERPRINTING_PROTECTION_STATE |
497 Ci.nsIClearDataService.CLEAR_BOUNCE_TRACKING_PROTECTION_STATE
500 await clearData(range, Ci.nsIClearDataService.CLEAR_MEDIA_DEVICES);
501 TelemetryStopwatch.finish("FX_SANITIZE_COOKIES_2", refObj);
506 async clear(range, { progress }, clearHonoringExceptions) {
507 // This is true if called by sanitizeOnShutdown.
508 // On shutdown we clear by principal to be able to honor the users exceptions
509 if (clearHonoringExceptions) {
510 progress.step = "getAllPrincipals";
511 let principalsForShutdownClearing =
512 await gPrincipalsCollector.getAllPrincipals(progress);
513 await maybeSanitizeSessionPrincipals(
515 principalsForShutdownClearing,
516 Ci.nsIClearDataService.CLEAR_DOM_STORAGES |
517 Ci.nsIClearDataService.CLEAR_COOKIE_BANNER_EXECUTED_RECORD |
518 Ci.nsIClearDataService.CLEAR_FINGERPRINTING_PROTECTION_STATE
524 Ci.nsIClearDataService.CLEAR_DOM_STORAGES |
525 Ci.nsIClearDataService.CLEAR_COOKIE_BANNER_EXECUTED_RECORD |
526 Ci.nsIClearDataService.CLEAR_FINGERPRINTING_PROTECTION_STATE
533 async clear(range, { progress }) {
534 // TODO: This check is needed for the case that this method is invoked directly and not via the sanitizer.sanitize API.
535 // This can be removed once bug 1803799 has landed.
536 if (!gPrincipalsCollector) {
537 gPrincipalsCollector = new lazy.PrincipalsCollector();
539 progress.step = "getAllPrincipals";
540 let principals = await gPrincipalsCollector.getAllPrincipals(progress);
542 TelemetryStopwatch.start("FX_SANITIZE_HISTORY", refObj);
543 progress.step = "clearing browsing history";
546 Ci.nsIClearDataService.CLEAR_HISTORY |
547 Ci.nsIClearDataService.CLEAR_SESSION_HISTORY |
548 Ci.nsIClearDataService.CLEAR_CONTENT_BLOCKING_RECORDS
551 // storageAccessAPI permissions record every site that the user
552 // interacted with and thus mirror history quite closely. It makes
553 // sense to clear them when we clear history. However, since their absence
554 // indicates that we can purge cookies and site data for tracking origins without
555 // user interaction, we need to ensure that we only delete those permissions that
556 // do not have any existing storage.
557 progress.step = "clearing user interaction";
558 await new Promise(resolve => {
559 Services.clearData.deleteUserInteractionForClearingHistory(
561 range ? range[0] : 0,
565 TelemetryStopwatch.finish("FX_SANITIZE_HISTORY", refObj);
573 TelemetryStopwatch.start("FX_SANITIZE_FORMDATA", refObj);
575 // Clear undo history of all search bars.
576 for (let currentWindow of Services.wm.getEnumerator(
579 let currentDocument = currentWindow.document;
581 // searchBar may not exist if it's in the customize mode.
582 let searchBar = currentDocument.getElementById("searchbar");
584 let input = searchBar.textbox;
586 input.editor?.clearUndoRedo();
589 let tabBrowser = currentWindow.gBrowser;
591 // No tab browser? This means that it's too early during startup (typically,
592 // Session Restore hasn't completed yet). Since we don't have find
593 // bars at that stage and since Session Restore will not restore
594 // find bars further down during startup, we have nothing to clear.
597 for (let tab of tabBrowser.tabs) {
598 if (tabBrowser.isFindBarInitialized(tab)) {
599 tabBrowser.getCachedFindBar(tab).clear();
602 // Clear any saved find value
603 tabBrowser._lastFindValue = "";
610 let change = { op: "remove" };
612 [change.firstUsedStart, change.firstUsedEnd] = range;
614 await lazy.FormHistory.update(change).catch(e => {
615 seenException = new Error("Error " + e.result + ": " + e.message);
621 TelemetryStopwatch.finish("FX_SANITIZE_FORMDATA", refObj);
631 TelemetryStopwatch.start("FX_SANITIZE_DOWNLOADS", refObj);
632 await clearData(range, Ci.nsIClearDataService.CLEAR_DOWNLOADS);
633 TelemetryStopwatch.finish("FX_SANITIZE_DOWNLOADS", refObj);
640 TelemetryStopwatch.start("FX_SANITIZE_SESSIONS", refObj);
643 Ci.nsIClearDataService.CLEAR_AUTH_TOKENS |
644 Ci.nsIClearDataService.CLEAR_AUTH_CACHE
646 TelemetryStopwatch.finish("FX_SANITIZE_SESSIONS", refObj);
653 TelemetryStopwatch.start("FX_SANITIZE_SITESETTINGS", refObj);
656 Ci.nsIClearDataService.CLEAR_PERMISSIONS |
657 Ci.nsIClearDataService.CLEAR_CONTENT_PREFERENCES |
658 Ci.nsIClearDataService.CLEAR_DOM_PUSH_NOTIFICATIONS |
659 Ci.nsIClearDataService.CLEAR_CLIENT_AUTH_REMEMBER_SERVICE |
660 Ci.nsIClearDataService.CLEAR_CERT_EXCEPTIONS |
661 Ci.nsIClearDataService.CLEAR_CREDENTIAL_MANAGER_STATE |
662 Ci.nsIClearDataService.CLEAR_COOKIE_BANNER_EXCEPTION |
663 Ci.nsIClearDataService.CLEAR_FINGERPRINTING_PROTECTION_STATE
665 TelemetryStopwatch.finish("FX_SANITIZE_SITESETTINGS", refObj);
670 _canCloseWindow(win) {
671 if (win.CanCloseWindow()) {
672 // We already showed PermitUnload for the window, so let's
673 // make sure we don't do it again when we actually close the
675 win.skipNextCanClose = true;
680 _resetAllWindowClosures(windowList) {
681 for (let win of windowList) {
682 win.skipNextCanClose = false;
685 async clear(range, { privateStateForNewWindow = "non-private" }) {
686 // NB: this closes all *browser* windows, not other windows like the library, about window,
687 // browser console, etc.
689 // Keep track of the time in case we get stuck in la-la-land because of onbeforeunload
691 let startDate = Date.now();
693 // First check if all these windows are OK with being closed:
695 for (let someWin of Services.wm.getEnumerator("navigator:browser")) {
696 windowList.push(someWin);
697 // If someone says "no" to a beforeunload prompt, we abort here:
698 if (!this._canCloseWindow(someWin)) {
699 this._resetAllWindowClosures(windowList);
701 "Sanitize could not close windows: cancelled by user"
705 // ...however, beforeunload prompts spin the event loop, and so the code here won't get
706 // hit until the prompt has been dismissed. If more than 1 minute has elapsed since we
707 // started prompting, stop, because the user might not even remember initiating the
708 // 'forget', and the timespans will be all wrong by now anyway:
709 if (Date.now() > startDate + 60 * 1000) {
710 this._resetAllWindowClosures(windowList);
711 throw new Error("Sanitize could not close windows: timeout");
715 if (!windowList.length) {
719 // If/once we get here, we should actually be able to close all windows.
722 TelemetryStopwatch.start("FX_SANITIZE_OPENWINDOWS", refObj);
724 // First create a new window. We do this first so that on non-mac, we don't
725 // accidentally close the app by closing all the windows.
726 let handler = Cc["@mozilla.org/browser/clh;1"].getService(
729 let defaultArgs = handler.defaultArgs;
730 let features = "chrome,all,dialog=no," + privateStateForNewWindow;
731 let newWindow = windowList[0].openDialog(
732 AppConstants.BROWSER_CHROME_URL,
738 let onFullScreen = null;
739 if (AppConstants.platform == "macosx") {
740 onFullScreen = function (e) {
741 newWindow.removeEventListener("fullscreen", onFullScreen);
742 let docEl = newWindow.document.documentElement;
743 let sizemode = docEl.getAttribute("sizemode");
744 if (!newWindow.fullScreen && sizemode == "fullscreen") {
745 docEl.setAttribute("sizemode", "normal");
752 newWindow.addEventListener("fullscreen", onFullScreen);
755 let promiseReady = new Promise(resolve => {
756 // Window creation and destruction is asynchronous. We need to wait
757 // until all existing windows are fully closed, and the new window is
758 // fully open, before continuing. Otherwise the rest of the sanitizer
759 // could run too early (and miss new cookies being set when a page
760 // closes) and/or run too late (and not have a fully-formed window yet
761 // in existence). See bug 1088137.
762 let newWindowOpened = false;
763 let onWindowOpened = function (subject) {
764 if (subject != newWindow) {
768 Services.obs.removeObserver(
770 "browser-delayed-startup-finished"
772 if (AppConstants.platform == "macosx") {
773 newWindow.removeEventListener("fullscreen", onFullScreen);
775 newWindowOpened = true;
776 // If we're the last thing to happen, invoke callback.
777 if (numWindowsClosing == 0) {
778 TelemetryStopwatch.finish("FX_SANITIZE_OPENWINDOWS", refObj);
783 let numWindowsClosing = windowList.length;
784 let onWindowClosed = function () {
786 if (numWindowsClosing == 0) {
787 Services.obs.removeObserver(
789 "xul-window-destroyed"
791 // If we're the last thing to happen, invoke callback.
792 if (newWindowOpened) {
793 TelemetryStopwatch.finish("FX_SANITIZE_OPENWINDOWS", refObj);
798 Services.obs.addObserver(
800 "browser-delayed-startup-finished"
802 Services.obs.addObserver(onWindowClosed, "xul-window-destroyed");
805 // Start the process of closing windows
806 while (windowList.length) {
807 windowList.pop().close();
818 // Combine History and Form Data clearing for the
819 // new clear history dialog box.
820 historyFormDataAndDownloads: {
821 async clear(range, { progress }) {
822 progress.step = "getAllPrincipals";
823 let principals = await gPrincipalsCollector.getAllPrincipals(progress);
825 TelemetryStopwatch.start("FX_SANITIZE_HISTORY", refObj);
826 progress.step = "clearing browsing history";
829 Ci.nsIClearDataService.CLEAR_HISTORY |
830 Ci.nsIClearDataService.CLEAR_SESSION_HISTORY |
831 Ci.nsIClearDataService.CLEAR_CONTENT_BLOCKING_RECORDS
834 // storageAccessAPI permissions record every site that the user
835 // interacted with and thus mirror history quite closely. It makes
836 // sense to clear them when we clear history. However, since their absence
837 // indicates that we can purge cookies and site data for tracking origins without
838 // user interaction, we need to ensure that we only delete those permissions that
839 // do not have any existing storage.
840 progress.step = "clearing user interaction";
841 await new Promise(resolve => {
842 Services.clearData.deleteUserInteractionForClearingHistory(
844 range ? range[0] : 0,
848 TelemetryStopwatch.finish("FX_SANITIZE_HISTORY", refObj);
853 TelemetryStopwatch.start("FX_SANITIZE_FORMDATA", refObj);
855 // Clear undo history of all search bars.
856 for (let currentWindow of Services.wm.getEnumerator(
859 let currentDocument = currentWindow.document;
861 // searchBar may not exist if it's in the customize mode.
862 let searchBar = currentDocument.getElementById("searchbar");
864 let input = searchBar.textbox;
866 input.editor?.clearUndoRedo();
869 let tabBrowser = currentWindow.gBrowser;
871 // No tab browser? This means that it's too early during startup (typically,
872 // Session Restore hasn't completed yet). Since we don't have find
873 // bars at that stage and since Session Restore will not restore
874 // find bars further down during startup, we have nothing to clear.
877 for (let tab of tabBrowser.tabs) {
878 if (tabBrowser.isFindBarInitialized(tab)) {
879 tabBrowser.getCachedFindBar(tab).clear();
882 // Clear any saved find value
883 tabBrowser._lastFindValue = "";
890 let change = { op: "remove" };
892 [change.firstUsedStart, change.firstUsedEnd] = range;
894 await lazy.FormHistory.update(change).catch(e => {
895 seenException = new Error("Error " + e.result + ": " + e.message);
901 TelemetryStopwatch.finish("FX_SANITIZE_FORMDATA", refObj);
908 TelemetryStopwatch.start("FX_SANITIZE_DOWNLOADS", refObj);
909 await clearData(range, Ci.nsIClearDataService.CLEAR_DOWNLOADS);
910 TelemetryStopwatch.finish("FX_SANITIZE_DOWNLOADS", refObj);
915 async clear(range, { progress }, clearHonoringExceptions) {
917 TelemetryStopwatch.start("FX_SANITIZE_COOKIES_2", refObj);
918 // This is true if called by sanitizeOnShutdown.
919 // On shutdown we clear by principal to be able to honor the users exceptions
920 if (clearHonoringExceptions) {
921 progress.step = "getAllPrincipals";
922 let principalsForShutdownClearing =
923 await gPrincipalsCollector.getAllPrincipals(progress);
924 await maybeSanitizeSessionPrincipals(
926 principalsForShutdownClearing,
927 Ci.nsIClearDataService.CLEAR_COOKIES_AND_SITE_DATA
933 Ci.nsIClearDataService.CLEAR_COOKIES_AND_SITE_DATA
936 await clearData(range, Ci.nsIClearDataService.CLEAR_MEDIA_DEVICES);
937 TelemetryStopwatch.finish("FX_SANITIZE_COOKIES_2", refObj);
943 async function sanitizeInternal(items, aItemsToClear, options) {
944 let { ignoreTimespan = true, range, progress } = options;
945 let seenError = false;
946 // Shallow copy the array, as we are going to modify it in place later.
947 if (!Array.isArray(aItemsToClear)) {
948 throw new Error("Must pass an array of items to clear.");
950 let itemsToClear = [...aItemsToClear];
952 // Store the list of items to clear, in case we are killed before we
953 // get a chance to complete.
954 let uid = gPendingSanitizationSerial++;
955 // Shutdown sanitization is managed outside.
956 if (!progress.isShutdown) {
957 addPendingSanitization(uid, itemsToClear, options);
960 // Store the list of items to clear, for debugging/forensics purposes
961 for (let k of itemsToClear) {
962 progress[k] = "ready";
963 // Create a progress object specific to each cleaner. We'll pass down this
964 // to the cleaners instead of the main progress object, so they don't end
965 // up overriding properties each other.
966 // This specific progress is deleted if the cleaner completes successfully,
967 // so the metadata will only contain progress of unresolved cleaners.
968 progress[k + "Progress"] = {};
971 // Ensure open windows get cleared first, if they're in our list, so that
972 // they don't stick around in the recently closed windows list, and so we
973 // can cancel the whole thing if the user selects to keep a window open
974 // from a beforeunload prompt.
975 let openWindowsIndex = itemsToClear.indexOf("openWindows");
976 if (openWindowsIndex != -1) {
977 itemsToClear.splice(openWindowsIndex, 1);
978 await items.openWindows.clear(
980 Object.assign(options, { progress: progress.openWindowsProgress })
982 progress.openWindows = "cleared";
983 delete progress.openWindowsProgress;
986 // If we ignore timespan, clear everything,
987 // otherwise, pick a range.
988 if (!ignoreTimespan && !range) {
989 range = Sanitizer.getClearRange();
992 // For performance reasons we start all the clear tasks at once, then wait
993 // for their promises later.
994 // Some of the clear() calls may raise exceptions (for example bug 265028),
995 // we catch and store them, but continue to sanitize as much as possible.
996 // Callers should check returned errors and give user feedback
997 // about items that could not be sanitized
999 TelemetryStopwatch.start("FX_SANITIZE_TOTAL", refObj);
1001 let annotateError = (name, ex) => {
1002 progress[name] = "failed";
1004 console.error("Error sanitizing " + name, ex);
1007 // Array of objects in form { name, promise }.
1008 // `name` is the item's name and `promise` may be a promise, if the
1009 // sanitization is asynchronous, or the function return value, otherwise.
1010 log("Running sanitization for:", itemsToClear);
1012 for (let name of itemsToClear) {
1013 progress[name] = "blocking";
1014 let item = items[name];
1016 // Catch errors here, so later we can just loop through these.
1022 Object.assign(options, { progress: progress[name + "Progress"] }),
1023 progress.clearHonoringExceptions
1027 progress[name] = "cleared";
1028 delete progress[name + "Progress"];
1030 ex => annotateError(name, ex)
1034 annotateError(name, ex);
1037 await Promise.all(handles.map(h => h.promise));
1039 log("All sanitizations are complete");
1040 TelemetryStopwatch.finish("FX_SANITIZE_TOTAL", refObj);
1041 if (!progress.isShutdown) {
1042 removePendingSanitization(uid);
1046 throw new Error("Error sanitizing");
1050 async function sanitizeOnShutdown(progress) {
1051 log("Sanitizing on shutdown");
1052 if (lazy.useOldClearHistoryDialog) {
1053 progress.sanitizationPrefs = {
1054 privacy_sanitize_sanitizeOnShutdown: Services.prefs.getBoolPref(
1055 "privacy.sanitize.sanitizeOnShutdown"
1057 privacy_clearOnShutdown_cookies: Services.prefs.getBoolPref(
1058 "privacy.clearOnShutdown.cookies"
1060 privacy_clearOnShutdown_history: Services.prefs.getBoolPref(
1061 "privacy.clearOnShutdown.history"
1063 privacy_clearOnShutdown_formdata: Services.prefs.getBoolPref(
1064 "privacy.clearOnShutdown.formdata"
1066 privacy_clearOnShutdown_downloads: Services.prefs.getBoolPref(
1067 "privacy.clearOnShutdown.downloads"
1069 privacy_clearOnShutdown_cache: Services.prefs.getBoolPref(
1070 "privacy.clearOnShutdown.cache"
1072 privacy_clearOnShutdown_sessions: Services.prefs.getBoolPref(
1073 "privacy.clearOnShutdown.sessions"
1075 privacy_clearOnShutdown_offlineApps: Services.prefs.getBoolPref(
1076 "privacy.clearOnShutdown.offlineApps"
1078 privacy_clearOnShutdown_siteSettings: Services.prefs.getBoolPref(
1079 "privacy.clearOnShutdown.siteSettings"
1081 privacy_clearOnShutdown_openWindows: Services.prefs.getBoolPref(
1082 "privacy.clearOnShutdown.openWindows"
1086 // Perform a migration if this is the first time sanitizeOnShutdown is
1087 // running for the user with the new dialog
1088 Sanitizer.maybeMigratePrefs("clearOnShutdown");
1090 progress.sanitizationPrefs = {
1091 privacy_sanitize_sanitizeOnShutdown: Services.prefs.getBoolPref(
1092 "privacy.sanitize.sanitizeOnShutdown"
1094 privacy_clearOnShutdown_v2_cookiesAndStorage: Services.prefs.getBoolPref(
1095 "privacy.clearOnShutdown_v2.cookiesAndStorage"
1097 privacy_clearOnShutdown_v2_historyFormDataAndDownloads:
1098 Services.prefs.getBoolPref(
1099 "privacy.clearOnShutdown_v2.historyFormDataAndDownloads"
1101 privacy_clearOnShutdown_v2_cache: Services.prefs.getBoolPref(
1102 "privacy.clearOnShutdown_v2.cache"
1104 privacy_clearOnShutdown_v2_siteSettings: Services.prefs.getBoolPref(
1105 "privacy.clearOnShutdown_v2.siteSettings"
1110 let needsSyncSavePrefs = false;
1111 if (Sanitizer.shouldSanitizeOnShutdown) {
1112 // Need to sanitize upon shutdown
1113 progress.advancement = "shutdown-cleaner";
1114 let shutdownBranch = lazy.useOldClearHistoryDialog
1115 ? Sanitizer.PREF_SHUTDOWN_BRANCH
1116 : Sanitizer.PREF_SHUTDOWN_V2_BRANCH;
1117 let itemsToClear = getItemsToClearFromPrefBranch(shutdownBranch);
1118 await Sanitizer.sanitize(itemsToClear, { progress });
1120 // We didn't crash during shutdown sanitization, so annotate it to avoid
1121 // sanitizing again on startup.
1122 removePendingSanitization("shutdown");
1123 needsSyncSavePrefs = true;
1126 if (Sanitizer.shouldSanitizeNewTabContainer) {
1127 progress.advancement = "newtab-segregation";
1128 sanitizeNewTabSegregation();
1129 removePendingSanitization("newtab-container");
1130 needsSyncSavePrefs = true;
1133 if (needsSyncSavePrefs) {
1134 Services.prefs.savePrefFile(null);
1137 if (!Sanitizer.shouldSanitizeOnShutdown) {
1138 // In case the user has not activated sanitizeOnShutdown but has explicitely set exceptions
1139 // to always clear particular origins, we clear those here
1141 progress.advancement = "session-permission";
1144 let selectedPrincipals = [];
1145 // Let's see if we have to forget some particular site.
1146 for (let permission of Services.perms.all) {
1148 permission.type != "cookie" ||
1149 permission.capability != Ci.nsICookiePermission.ACCESS_SESSION
1154 // We consider just permissions set for http, https and file URLs.
1155 if (!isSupportedPrincipal(permission.principal)) {
1160 "Custom session cookie permission detected for: " +
1161 permission.principal.asciiSpec
1165 // We use just the URI here, because permissions ignore OriginAttributes.
1166 // The principalsCollector is lazy, this is computed only once
1167 if (!gPrincipalsCollector) {
1168 gPrincipalsCollector = new lazy.PrincipalsCollector();
1170 let principals = await gPrincipalsCollector.getAllPrincipals(progress);
1171 selectedPrincipals.push(
1172 ...extractMatchingPrincipals(principals, permission.principal.host)
1175 await maybeSanitizeSessionPrincipals(
1178 Ci.nsIClearDataService.CLEAR_ALL_CACHES |
1179 Ci.nsIClearDataService.CLEAR_COOKIES |
1180 Ci.nsIClearDataService.CLEAR_DOM_STORAGES |
1181 Ci.nsIClearDataService.CLEAR_EME |
1182 Ci.nsIClearDataService.CLEAR_BOUNCE_TRACKING_PROTECTION_STATE
1184 progress.sanitizationPrefs.session_permission_exceptions = exceptions;
1186 progress.advancement = "done";
1189 // Extracts the principals matching matchUri as root domain.
1190 function extractMatchingPrincipals(principals, matchHost) {
1191 return principals.filter(principal => {
1192 return Services.eTLD.hasRootDomain(matchHost, principal.host);
1196 /** This method receives a list of principals and it checks if some of them or
1197 * some of their sub-domain need to be sanitize.
1198 * @param {Object} progress - Object to keep track of the sanitization progress, prefs and mode
1199 * @param {nsIPrincipal[]} principals - The principals generated by the PrincipalsCollector
1200 * @param {int} flags - The cleaning categories that need to be cleaned for the principals.
1201 * @returns {Promise} - Resolves once the clearing of the principals to be cleared is done
1203 async function maybeSanitizeSessionPrincipals(progress, principals, flags) {
1204 log("Sanitizing " + principals.length + " principals");
1207 let permissions = new Map();
1208 Services.perms.getAllWithTypePrefix("cookie").forEach(perm => {
1209 permissions.set(perm.principal.origin, perm);
1212 principals.forEach(principal => {
1213 progress.step = "checking-principal";
1214 let cookieAllowed = cookiesAllowedForDomainOrSubDomain(
1218 progress.step = "principal-checked:" + cookieAllowed;
1220 if (!cookieAllowed) {
1221 promises.push(sanitizeSessionPrincipal(progress, principal, flags));
1225 progress.step = "promises:" + promises.length;
1226 if (promises.length) {
1227 await Promise.all(promises);
1228 await new Promise(resolve =>
1229 Services.clearData.cleanupAfterDeletionAtShutdown(flags, resolve)
1232 progress.step = "promises resolved";
1235 function cookiesAllowedForDomainOrSubDomain(principal, permissions) {
1236 log("Checking principal: " + principal.asciiSpec);
1238 // If we have the 'cookie' permission for this principal, let's return
1240 let cookiePermission = checkIfCookiePermissionIsSet(principal);
1241 if (cookiePermission != null) {
1242 return cookiePermission;
1245 for (let perm of permissions.values()) {
1246 if (perm.type != "cookie") {
1247 permissions.delete(perm.principal.origin);
1250 // We consider just permissions set for http, https and file URLs.
1251 if (!isSupportedPrincipal(perm.principal)) {
1252 permissions.delete(perm.principal.origin);
1256 // We don't care about scheme, port, and anything else.
1257 if (Services.eTLD.hasRootDomain(perm.principal.host, principal.host)) {
1258 log("Cookie check on principal: " + perm.principal.asciiSpec);
1259 let rootDomainCookiePermission = checkIfCookiePermissionIsSet(
1262 if (rootDomainCookiePermission != null) {
1263 return rootDomainCookiePermission;
1268 log("Cookie not allowed.");
1273 * Checks if a cookie permission is set for a given principal
1274 * @returns {boolean} - true: cookie permission "ACCESS_ALLOW", false: cookie permission "ACCESS_DENY"/"ACCESS_SESSION"
1275 * @returns {null} - No cookie permission is set for this principal
1277 function checkIfCookiePermissionIsSet(principal) {
1278 let p = Services.perms.testPermissionFromPrincipal(principal, "cookie");
1280 if (p == Ci.nsICookiePermission.ACCESS_ALLOW) {
1281 log("Cookie allowed!");
1286 p == Ci.nsICookiePermission.ACCESS_DENY ||
1287 p == Ci.nsICookiePermission.ACCESS_SESSION
1289 log("Cookie denied or session!");
1292 // This is an old profile with unsupported permission values
1293 if (p != Ci.nsICookiePermission.ACCESS_DEFAULT) {
1294 log("Not supported cookie permission: " + p);
1300 async function sanitizeSessionPrincipal(progress, principal, flags) {
1301 log("Sanitizing principal: " + principal.asciiSpec);
1303 await new Promise(resolve => {
1304 progress.sanitizePrincipal = "started";
1305 Services.clearData.deleteDataFromPrincipal(
1307 true /* user request */,
1312 progress.sanitizePrincipal = "completed";
1315 function sanitizeNewTabSegregation() {
1316 let identity = lazy.ContextualIdentityService.getPrivateIdentity(
1317 "userContextIdInternal.thumbnail"
1320 Services.clearData.deleteDataFromOriginAttributesPattern({
1321 userContextId: identity.userContextId,
1327 * Gets an array of items to clear from the given pref branch.
1328 * @param branch The pref branch to fetch.
1329 * @return Array of items to clear
1331 function getItemsToClearFromPrefBranch(branch) {
1332 branch = Services.prefs.getBranch(branch);
1333 return Object.keys(Sanitizer.items).filter(itemName => {
1335 return branch.getBoolPref(itemName);
1343 * These functions are used to track pending sanitization on the next startup
1344 * in case of a crash before a sanitization could happen.
1345 * @param id A unique id identifying the sanitization
1346 * @param itemsToClear The items to clear
1347 * @param options The Sanitize options
1349 function addPendingSanitization(id, itemsToClear, options) {
1350 let pendingSanitizations = safeGetPendingSanitizations();
1351 pendingSanitizations.push({ id, itemsToClear, options });
1352 Services.prefs.setStringPref(
1353 Sanitizer.PREF_PENDING_SANITIZATIONS,
1354 JSON.stringify(pendingSanitizations)
1358 function removePendingSanitization(id) {
1359 let pendingSanitizations = safeGetPendingSanitizations();
1360 let i = pendingSanitizations.findIndex(s => s.id == id);
1361 let [s] = pendingSanitizations.splice(i, 1);
1362 Services.prefs.setStringPref(
1363 Sanitizer.PREF_PENDING_SANITIZATIONS,
1364 JSON.stringify(pendingSanitizations)
1369 function getAndClearPendingSanitizations() {
1370 let pendingSanitizations = safeGetPendingSanitizations();
1371 if (pendingSanitizations.length) {
1372 Services.prefs.clearUserPref(Sanitizer.PREF_PENDING_SANITIZATIONS);
1374 return pendingSanitizations;
1377 function safeGetPendingSanitizations() {
1380 Services.prefs.getStringPref(Sanitizer.PREF_PENDING_SANITIZATIONS, "[]")
1383 console.error("Invalid JSON value for pending sanitizations: ", ex);
1388 async function clearData(range, flags) {
1390 await new Promise(resolve => {
1391 Services.clearData.deleteDataInTimeRange(
1394 true /* user request */,
1400 await new Promise(resolve => {
1401 Services.clearData.deleteData(flags, resolve);
1406 function isSupportedPrincipal(principal) {
1407 return ["http", "https", "file"].some(scheme => principal.schemeIs(scheme));