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",
29 logConsole = console.createInstance({
30 prefix: "** Sanitizer.jsm",
31 maxLogLevelPref: "browser.sanitizer.loglevel",
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();
168 // Check if we should sanitize on shutdown.
169 this.shouldSanitizeOnShutdown = Services.prefs.getBoolPref(
170 Sanitizer.PREF_SANITIZE_ON_SHUTDOWN,
173 Services.prefs.addObserver(Sanitizer.PREF_SANITIZE_ON_SHUTDOWN, this, true);
174 // Add a pending shutdown sanitization, if necessary.
175 if (this.shouldSanitizeOnShutdown) {
176 let itemsToClear = getItemsToClearFromPrefBranch(
177 Sanitizer.PREF_SHUTDOWN_BRANCH
179 addPendingSanitization("shutdown", itemsToClear, {});
181 // Shutdown sanitization is always pending, but the user may change the
182 // sanitize on shutdown prefs during the session. Then the pending
183 // sanitization would become stale and must be updated.
184 Services.prefs.addObserver(Sanitizer.PREF_SHUTDOWN_BRANCH, this, true);
186 // Make sure that we are triggered during shutdown.
187 let shutdownClient = lazy.PlacesUtils.history.shutdownClient.jsclient;
188 // We need to pass to sanitize() (through sanitizeOnShutdown) a state object
189 // that tracks the status of the shutdown blocker. This `progress` object
190 // will be updated during sanitization and reported with the crash in case of
191 // a shutdown timeout.
192 // We use the `options` argument to pass the `progress` object to sanitize().
193 let progress = { isShutdown: true, clearHonoringExceptions: true };
194 shutdownClient.addBlocker(
195 "sanitize.js: Sanitize on shutdown",
196 () => sanitizeOnShutdown(progress),
197 { fetchState: () => ({ progress }) }
200 this.shouldSanitizeNewTabContainer = Services.prefs.getBoolPref(
201 this.PREF_NEWTAB_SEGREGATION,
204 if (this.shouldSanitizeNewTabContainer) {
205 addPendingSanitization("newtab-container", [], {});
208 let i = pendingSanitizations.findIndex(s => s.id == "newtab-container");
210 pendingSanitizations.splice(i, 1);
211 sanitizeNewTabSegregation();
214 // Finally, run the sanitizations that were left pending, because we crashed
215 // before completing them.
216 for (let { itemsToClear, options } of pendingSanitizations) {
218 // We need to set this flag to watch out for the users exceptions like we do on shutdown
219 options.progress = { clearHonoringExceptions: true };
220 await this.sanitize(itemsToClear, options);
223 "A previously pending sanitization failed: ",
232 * Returns a 2 element array representing the start and end times,
233 * in the uSec-since-epoch format that PRTime likes. If we should
234 * clear everything, this function returns null.
236 * @param ts [optional] a timespan to convert to start and end time.
237 * Falls back to the privacy.sanitize.timeSpan preference
238 * if this argument is omitted.
239 * If this argument is provided, it has to be one of the
240 * Sanitizer.TIMESPAN_* constants. This function will
241 * throw an error otherwise.
243 * @return {Array} a 2-element Array containing the start and end times.
246 if (ts === undefined) {
247 ts = Services.prefs.getIntPref(Sanitizer.PREF_TIMESPAN);
249 if (ts === Sanitizer.TIMESPAN_EVERYTHING) {
253 // PRTime is microseconds while JS time is milliseconds
254 var endDate = Date.now() * 1000;
256 case Sanitizer.TIMESPAN_5MIN:
257 var startDate = endDate - 300000000; // 5*60*1000000
259 case Sanitizer.TIMESPAN_HOUR:
260 startDate = endDate - 3600000000; // 1*60*60*1000000
262 case Sanitizer.TIMESPAN_2HOURS:
263 startDate = endDate - 7200000000; // 2*60*60*1000000
265 case Sanitizer.TIMESPAN_4HOURS:
266 startDate = endDate - 14400000000; // 4*60*60*1000000
268 case Sanitizer.TIMESPAN_TODAY:
269 var d = new Date(); // Start with today
270 d.setHours(0); // zero us back to midnight...
273 d.setMilliseconds(0);
274 startDate = d.valueOf() * 1000; // convert to epoch usec
276 case Sanitizer.TIMESPAN_24HOURS:
277 startDate = endDate - 86400000000; // 24*60*60*1000000
280 throw new Error("Invalid time span for clear private data: " + ts);
282 return [startDate, endDate];
286 * Deletes privacy sensitive data in a batch, according to user preferences.
287 * Returns a promise which is resolved if no errors occurred. If an error
288 * occurs, a message is reported to the console and all other items are still
289 * cleared before the promise is finally rejected.
291 * @param [optional] itemsToClear
292 * Array of items to be cleared. if specified only those
293 * items get cleared, irrespectively of the preference settings.
294 * @param [optional] options
295 * Object whose properties are options for this sanitization:
296 * - ignoreTimespan (default: true): Time span only makes sense in
297 * certain cases. Consumers who want to only clear some private
298 * data can opt in by setting this to false, and can optionally
299 * specify a specific range.
300 * If timespan is not ignored, and range is not set, sanitize() will
301 * use the value of the timespan pref to determine a range.
302 * - range (default: null): array-tuple of [from, to] timestamps
303 * - privateStateForNewWindow (default: "non-private"): when clearing
304 * open windows, defines the private state for the newly opened window.
305 * @returns {object} An object containing debug information about the
306 * sanitization progress. This state object is also used as
307 * AsyncShutdown metadata.
309 async sanitize(itemsToClear = null, options = {}) {
310 let progress = options.progress;
311 // initialise the principals collector
312 gPrincipalsCollector = new lazy.PrincipalsCollector();
314 progress = options.progress = {};
318 itemsToClear = getItemsToClearFromPrefBranch(this.PREF_CPD_BRANCH);
320 let promise = sanitizeInternal(this.items, itemsToClear, options);
322 // Depending on preferences, the sanitizer may perform asynchronous
323 // work before it starts cleaning up the Places database (e.g. closing
324 // windows). We need to make sure that the connection to that database
325 // hasn't been closed by the time we use it.
326 // Though, if this is a sanitize on shutdown, we already have a blocker.
327 if (!progress.isShutdown) {
328 let shutdownClient = lazy.PlacesUtils.history.shutdownClient.jsclient;
329 shutdownClient.addBlocker("sanitize.js: Sanitize", promise, {
330 fetchState: () => ({ progress }),
337 Services.obs.notifyObservers(null, "sanitizer-sanitization-complete");
342 observe(subject, topic, data) {
343 if (topic == "nsPref:changed") {
345 data.startsWith(this.PREF_SHUTDOWN_BRANCH) &&
346 this.shouldSanitizeOnShutdown
348 // Update the pending shutdown sanitization.
349 removePendingSanitization("shutdown");
350 let itemsToClear = getItemsToClearFromPrefBranch(
351 Sanitizer.PREF_SHUTDOWN_BRANCH
353 addPendingSanitization("shutdown", itemsToClear, {});
354 } else if (data == this.PREF_SANITIZE_ON_SHUTDOWN) {
355 this.shouldSanitizeOnShutdown = Services.prefs.getBoolPref(
356 Sanitizer.PREF_SANITIZE_ON_SHUTDOWN,
359 removePendingSanitization("shutdown");
360 if (this.shouldSanitizeOnShutdown) {
361 let itemsToClear = getItemsToClearFromPrefBranch(
362 Sanitizer.PREF_SHUTDOWN_BRANCH
364 addPendingSanitization("shutdown", itemsToClear, {});
366 } else if (data == this.PREF_NEWTAB_SEGREGATION) {
367 this.shouldSanitizeNewTabContainer = Services.prefs.getBoolPref(
368 this.PREF_NEWTAB_SEGREGATION,
371 removePendingSanitization("newtab-container");
372 if (this.shouldSanitizeNewTabContainer) {
373 addPendingSanitization("newtab-container", [], {});
379 QueryInterface: ChromeUtils.generateQI([
381 "nsISupportsWeakReference",
384 // This method is meant to be used by tests.
385 async runSanitizeOnShutdown() {
386 // The collector needs to be reset for each test, as the collection only happens
387 // once and does not update after that.
388 // Pretend that it has never been initialized to mimic the actual browser behavior
389 // by setting it to null.
390 // The actually initialization will happen either via sanitize() or directly in
391 // sanitizeOnShutdown.
392 gPrincipalsCollector = null;
393 return sanitizeOnShutdown({
395 clearHonoringExceptions: true,
399 // When making any changes to the sanitize implementations here,
400 // please check whether the changes are applicable to Android
401 // (mobile/android/modules/geckoview/GeckoViewStorageController.jsm) as well.
407 TelemetryStopwatch.start("FX_SANITIZE_CACHE", refObj);
408 await clearData(range, Ci.nsIClearDataService.CLEAR_ALL_CACHES);
409 TelemetryStopwatch.finish("FX_SANITIZE_CACHE", refObj);
414 async clear(range, { progress }, clearHonoringExceptions) {
416 TelemetryStopwatch.start("FX_SANITIZE_COOKIES_2", refObj);
417 // This is true if called by sanitizeOnShutdown.
418 // On shutdown we clear by principal to be able to honor the users exceptions
419 if (clearHonoringExceptions) {
420 progress.step = "getAllPrincipals";
421 let principalsForShutdownClearing =
422 await gPrincipalsCollector.getAllPrincipals(progress);
423 await maybeSanitizeSessionPrincipals(
425 principalsForShutdownClearing,
426 Ci.nsIClearDataService.CLEAR_COOKIES |
427 Ci.nsIClearDataService.CLEAR_COOKIE_BANNER_EXECUTED_RECORD
433 Ci.nsIClearDataService.CLEAR_COOKIES |
434 Ci.nsIClearDataService.CLEAR_COOKIE_BANNER_EXECUTED_RECORD
437 await clearData(range, Ci.nsIClearDataService.CLEAR_MEDIA_DEVICES);
438 TelemetryStopwatch.finish("FX_SANITIZE_COOKIES_2", refObj);
443 async clear(range, { progress }, clearHonoringExceptions) {
444 // This is true if called by sanitizeOnShutdown.
445 // On shutdown we clear by principal to be able to honor the users exceptions
446 if (clearHonoringExceptions) {
447 progress.step = "getAllPrincipals";
448 let principalsForShutdownClearing =
449 await gPrincipalsCollector.getAllPrincipals(progress);
450 await maybeSanitizeSessionPrincipals(
452 principalsForShutdownClearing,
453 Ci.nsIClearDataService.CLEAR_DOM_STORAGES |
454 Ci.nsIClearDataService.CLEAR_COOKIE_BANNER_EXECUTED_RECORD
460 Ci.nsIClearDataService.CLEAR_DOM_STORAGES |
461 Ci.nsIClearDataService.CLEAR_COOKIE_BANNER_EXECUTED_RECORD
468 async clear(range, { progress }) {
469 // TODO: This check is needed for the case that this method is invoked directly and not via the sanitizer.sanitize API.
470 // This can be removed once bug 1803799 has landed.
471 if (!gPrincipalsCollector) {
472 gPrincipalsCollector = new lazy.PrincipalsCollector();
474 progress.step = "getAllPrincipals";
475 let principals = await gPrincipalsCollector.getAllPrincipals(progress);
477 TelemetryStopwatch.start("FX_SANITIZE_HISTORY", refObj);
478 progress.step = "clearing browsing history";
481 Ci.nsIClearDataService.CLEAR_HISTORY |
482 Ci.nsIClearDataService.CLEAR_SESSION_HISTORY |
483 Ci.nsIClearDataService.CLEAR_CONTENT_BLOCKING_RECORDS
486 // storageAccessAPI permissions record every site that the user
487 // interacted with and thus mirror history quite closely. It makes
488 // sense to clear them when we clear history. However, since their absence
489 // indicates that we can purge cookies and site data for tracking origins without
490 // user interaction, we need to ensure that we only delete those permissions that
491 // do not have any existing storage.
492 progress.step = "clearing user interaction";
493 await new Promise(resolve => {
494 Services.clearData.deleteUserInteractionForClearingHistory(
496 range ? range[0] : 0,
500 TelemetryStopwatch.finish("FX_SANITIZE_HISTORY", refObj);
508 TelemetryStopwatch.start("FX_SANITIZE_FORMDATA", refObj);
510 // Clear undo history of all search bars.
511 for (let currentWindow of Services.wm.getEnumerator(
514 let currentDocument = currentWindow.document;
516 // searchBar may not exist if it's in the customize mode.
517 let searchBar = currentDocument.getElementById("searchbar");
519 let input = searchBar.textbox;
521 input.editor?.clearUndoRedo();
524 let tabBrowser = currentWindow.gBrowser;
526 // No tab browser? This means that it's too early during startup (typically,
527 // Session Restore hasn't completed yet). Since we don't have find
528 // bars at that stage and since Session Restore will not restore
529 // find bars further down during startup, we have nothing to clear.
532 for (let tab of tabBrowser.tabs) {
533 if (tabBrowser.isFindBarInitialized(tab)) {
534 tabBrowser.getCachedFindBar(tab).clear();
537 // Clear any saved find value
538 tabBrowser._lastFindValue = "";
545 let change = { op: "remove" };
547 [change.firstUsedStart, change.firstUsedEnd] = range;
549 await lazy.FormHistory.update(change).catch(e => {
550 seenException = new Error("Error " + e.result + ": " + e.message);
556 TelemetryStopwatch.finish("FX_SANITIZE_FORMDATA", refObj);
566 TelemetryStopwatch.start("FX_SANITIZE_DOWNLOADS", refObj);
567 await clearData(range, Ci.nsIClearDataService.CLEAR_DOWNLOADS);
568 TelemetryStopwatch.finish("FX_SANITIZE_DOWNLOADS", refObj);
575 TelemetryStopwatch.start("FX_SANITIZE_SESSIONS", refObj);
578 Ci.nsIClearDataService.CLEAR_AUTH_TOKENS |
579 Ci.nsIClearDataService.CLEAR_AUTH_CACHE
581 TelemetryStopwatch.finish("FX_SANITIZE_SESSIONS", refObj);
588 TelemetryStopwatch.start("FX_SANITIZE_SITESETTINGS", refObj);
591 Ci.nsIClearDataService.CLEAR_PERMISSIONS |
592 Ci.nsIClearDataService.CLEAR_CONTENT_PREFERENCES |
593 Ci.nsIClearDataService.CLEAR_DOM_PUSH_NOTIFICATIONS |
594 Ci.nsIClearDataService.CLEAR_CLIENT_AUTH_REMEMBER_SERVICE |
595 Ci.nsIClearDataService.CLEAR_CERT_EXCEPTIONS |
596 Ci.nsIClearDataService.CLEAR_CREDENTIAL_MANAGER_STATE |
597 Ci.nsIClearDataService.CLEAR_COOKIE_BANNER_EXCEPTION
599 TelemetryStopwatch.finish("FX_SANITIZE_SITESETTINGS", refObj);
604 _canCloseWindow(win) {
605 if (win.CanCloseWindow()) {
606 // We already showed PermitUnload for the window, so let's
607 // make sure we don't do it again when we actually close the
609 win.skipNextCanClose = true;
614 _resetAllWindowClosures(windowList) {
615 for (let win of windowList) {
616 win.skipNextCanClose = false;
619 async clear(range, { privateStateForNewWindow = "non-private" }) {
620 // NB: this closes all *browser* windows, not other windows like the library, about window,
621 // browser console, etc.
623 // Keep track of the time in case we get stuck in la-la-land because of onbeforeunload
625 let startDate = Date.now();
627 // First check if all these windows are OK with being closed:
629 for (let someWin of Services.wm.getEnumerator("navigator:browser")) {
630 windowList.push(someWin);
631 // If someone says "no" to a beforeunload prompt, we abort here:
632 if (!this._canCloseWindow(someWin)) {
633 this._resetAllWindowClosures(windowList);
635 "Sanitize could not close windows: cancelled by user"
639 // ...however, beforeunload prompts spin the event loop, and so the code here won't get
640 // hit until the prompt has been dismissed. If more than 1 minute has elapsed since we
641 // started prompting, stop, because the user might not even remember initiating the
642 // 'forget', and the timespans will be all wrong by now anyway:
643 if (Date.now() > startDate + 60 * 1000) {
644 this._resetAllWindowClosures(windowList);
645 throw new Error("Sanitize could not close windows: timeout");
649 if (!windowList.length) {
653 // If/once we get here, we should actually be able to close all windows.
656 TelemetryStopwatch.start("FX_SANITIZE_OPENWINDOWS", refObj);
658 // First create a new window. We do this first so that on non-mac, we don't
659 // accidentally close the app by closing all the windows.
660 let handler = Cc["@mozilla.org/browser/clh;1"].getService(
663 let defaultArgs = handler.defaultArgs;
664 let features = "chrome,all,dialog=no," + privateStateForNewWindow;
665 let newWindow = windowList[0].openDialog(
666 AppConstants.BROWSER_CHROME_URL,
672 let onFullScreen = null;
673 if (AppConstants.platform == "macosx") {
674 onFullScreen = function (e) {
675 newWindow.removeEventListener("fullscreen", onFullScreen);
676 let docEl = newWindow.document.documentElement;
677 let sizemode = docEl.getAttribute("sizemode");
678 if (!newWindow.fullScreen && sizemode == "fullscreen") {
679 docEl.setAttribute("sizemode", "normal");
686 newWindow.addEventListener("fullscreen", onFullScreen);
689 let promiseReady = new Promise(resolve => {
690 // Window creation and destruction is asynchronous. We need to wait
691 // until all existing windows are fully closed, and the new window is
692 // fully open, before continuing. Otherwise the rest of the sanitizer
693 // could run too early (and miss new cookies being set when a page
694 // closes) and/or run too late (and not have a fully-formed window yet
695 // in existence). See bug 1088137.
696 let newWindowOpened = false;
697 let onWindowOpened = function (subject, topic, data) {
698 if (subject != newWindow) {
702 Services.obs.removeObserver(
704 "browser-delayed-startup-finished"
706 if (AppConstants.platform == "macosx") {
707 newWindow.removeEventListener("fullscreen", onFullScreen);
709 newWindowOpened = true;
710 // If we're the last thing to happen, invoke callback.
711 if (numWindowsClosing == 0) {
712 TelemetryStopwatch.finish("FX_SANITIZE_OPENWINDOWS", refObj);
717 let numWindowsClosing = windowList.length;
718 let onWindowClosed = function () {
720 if (numWindowsClosing == 0) {
721 Services.obs.removeObserver(
723 "xul-window-destroyed"
725 // If we're the last thing to happen, invoke callback.
726 if (newWindowOpened) {
727 TelemetryStopwatch.finish("FX_SANITIZE_OPENWINDOWS", refObj);
732 Services.obs.addObserver(
734 "browser-delayed-startup-finished"
736 Services.obs.addObserver(onWindowClosed, "xul-window-destroyed");
739 // Start the process of closing windows
740 while (windowList.length) {
741 windowList.pop().close();
749 async clear(range) {},
752 // Combine History and Form Data clearing for the
753 // new clear history dialog box.
754 historyAndFormData: {
755 async clear(range, { progress }) {
756 progress.step = "getAllPrincipals";
757 let principals = await gPrincipalsCollector.getAllPrincipals(progress);
759 TelemetryStopwatch.start("FX_SANITIZE_HISTORY", refObj);
760 progress.step = "clearing browsing history";
763 Ci.nsIClearDataService.CLEAR_HISTORY |
764 Ci.nsIClearDataService.CLEAR_SESSION_HISTORY |
765 Ci.nsIClearDataService.CLEAR_CONTENT_BLOCKING_RECORDS
768 // storageAccessAPI permissions record every site that the user
769 // interacted with and thus mirror history quite closely. It makes
770 // sense to clear them when we clear history. However, since their absence
771 // indicates that we can purge cookies and site data for tracking origins without
772 // user interaction, we need to ensure that we only delete those permissions that
773 // do not have any existing storage.
774 progress.step = "clearing user interaction";
775 await new Promise(resolve => {
776 Services.clearData.deleteUserInteractionForClearingHistory(
778 range ? range[0] : 0,
782 TelemetryStopwatch.finish("FX_SANITIZE_HISTORY", refObj);
787 TelemetryStopwatch.start("FX_SANITIZE_FORMDATA", refObj);
789 // Clear undo history of all search bars.
790 for (let currentWindow of Services.wm.getEnumerator(
793 let currentDocument = currentWindow.document;
795 // searchBar may not exist if it's in the customize mode.
796 let searchBar = currentDocument.getElementById("searchbar");
798 let input = searchBar.textbox;
800 input.editor?.clearUndoRedo();
803 let tabBrowser = currentWindow.gBrowser;
805 // No tab browser? This means that it's too early during startup (typically,
806 // Session Restore hasn't completed yet). Since we don't have find
807 // bars at that stage and since Session Restore will not restore
808 // find bars further down during startup, we have nothing to clear.
811 for (let tab of tabBrowser.tabs) {
812 if (tabBrowser.isFindBarInitialized(tab)) {
813 tabBrowser.getCachedFindBar(tab).clear();
816 // Clear any saved find value
817 tabBrowser._lastFindValue = "";
824 let change = { op: "remove" };
826 [change.firstUsedStart, change.firstUsedEnd] = range;
828 await lazy.FormHistory.update(change).catch(e => {
829 seenException = new Error("Error " + e.result + ": " + e.message);
835 TelemetryStopwatch.finish("FX_SANITIZE_FORMDATA", refObj);
843 async clear(range, { progress }, clearHonoringExceptions) {
845 TelemetryStopwatch.start("FX_SANITIZE_COOKIES_2", refObj);
846 // This is true if called by sanitizeOnShutdown.
847 // On shutdown we clear by principal to be able to honor the users exceptions
848 if (clearHonoringExceptions) {
849 progress.step = "getAllPrincipals";
850 let principalsForShutdownClearing =
851 await gPrincipalsCollector.getAllPrincipals(progress);
852 await maybeSanitizeSessionPrincipals(
854 principalsForShutdownClearing,
855 Ci.nsIClearDataService.CLEAR_COOKIES |
856 Ci.nsIClearDataService.CLEAR_COOKIE_BANNER_EXECUTED_RECORD |
857 Ci.nsIClearDataService.CLEAR_DOM_STORAGES |
858 Ci.nsIClearDataService.CLEAR_AUTH_TOKENS |
859 Ci.nsIClearDataService.CLEAR_AUTH_CACHE
865 Ci.nsIClearDataService.CLEAR_COOKIES |
866 Ci.nsIClearDataService.CLEAR_COOKIE_BANNER_EXECUTED_RECORD |
867 Ci.nsIClearDataService.CLEAR_DOM_STORAGES |
868 Ci.nsIClearDataService.CLEAR_AUTH_TOKENS |
869 Ci.nsIClearDataService.CLEAR_AUTH_CACHE
872 await clearData(range, Ci.nsIClearDataService.CLEAR_MEDIA_DEVICES);
873 TelemetryStopwatch.finish("FX_SANITIZE_COOKIES_2", refObj);
879 async function sanitizeInternal(items, aItemsToClear, options) {
880 let { ignoreTimespan = true, range, progress } = options;
881 let seenError = false;
882 // Shallow copy the array, as we are going to modify it in place later.
883 if (!Array.isArray(aItemsToClear)) {
884 throw new Error("Must pass an array of items to clear.");
886 let itemsToClear = [...aItemsToClear];
888 // Store the list of items to clear, in case we are killed before we
889 // get a chance to complete.
890 let uid = gPendingSanitizationSerial++;
891 // Shutdown sanitization is managed outside.
892 if (!progress.isShutdown) {
893 addPendingSanitization(uid, itemsToClear, options);
896 // Store the list of items to clear, for debugging/forensics purposes
897 for (let k of itemsToClear) {
898 progress[k] = "ready";
899 // Create a progress object specific to each cleaner. We'll pass down this
900 // to the cleaners instead of the main progress object, so they don't end
901 // up overriding properties each other.
902 // This specific progress is deleted if the cleaner completes successfully,
903 // so the metadata will only contain progress of unresolved cleaners.
904 progress[k + "Progress"] = {};
907 // Ensure open windows get cleared first, if they're in our list, so that
908 // they don't stick around in the recently closed windows list, and so we
909 // can cancel the whole thing if the user selects to keep a window open
910 // from a beforeunload prompt.
911 let openWindowsIndex = itemsToClear.indexOf("openWindows");
912 if (openWindowsIndex != -1) {
913 itemsToClear.splice(openWindowsIndex, 1);
914 await items.openWindows.clear(
916 Object.assign(options, { progress: progress.openWindowsProgress })
918 progress.openWindows = "cleared";
919 delete progress.openWindowsProgress;
922 // If we ignore timespan, clear everything,
923 // otherwise, pick a range.
924 if (!ignoreTimespan && !range) {
925 range = Sanitizer.getClearRange();
928 // For performance reasons we start all the clear tasks at once, then wait
929 // for their promises later.
930 // Some of the clear() calls may raise exceptions (for example bug 265028),
931 // we catch and store them, but continue to sanitize as much as possible.
932 // Callers should check returned errors and give user feedback
933 // about items that could not be sanitized
935 TelemetryStopwatch.start("FX_SANITIZE_TOTAL", refObj);
937 let annotateError = (name, ex) => {
938 progress[name] = "failed";
940 console.error("Error sanitizing " + name, ex);
943 // Array of objects in form { name, promise }.
944 // `name` is the item's name and `promise` may be a promise, if the
945 // sanitization is asynchronous, or the function return value, otherwise.
947 for (let name of itemsToClear) {
948 progress[name] = "blocking";
949 let item = items[name];
951 // Catch errors here, so later we can just loop through these.
957 Object.assign(options, { progress: progress[name + "Progress"] }),
958 progress.clearHonoringExceptions
962 progress[name] = "cleared";
963 delete progress[name + "Progress"];
965 ex => annotateError(name, ex)
969 annotateError(name, ex);
972 await Promise.all(handles.map(h => h.promise));
974 // Sanitization is complete.
975 TelemetryStopwatch.finish("FX_SANITIZE_TOTAL", refObj);
976 if (!progress.isShutdown) {
977 removePendingSanitization(uid);
981 throw new Error("Error sanitizing");
985 async function sanitizeOnShutdown(progress) {
986 log("Sanitizing on shutdown");
987 if (lazy.useOldClearHistoryDialog) {
988 progress.sanitizationPrefs = {
989 privacy_sanitize_sanitizeOnShutdown: Services.prefs.getBoolPref(
990 "privacy.sanitize.sanitizeOnShutdown"
992 privacy_clearOnShutdown_cookies: Services.prefs.getBoolPref(
993 "privacy.clearOnShutdown.cookies"
995 privacy_clearOnShutdown_history: Services.prefs.getBoolPref(
996 "privacy.clearOnShutdown.history"
998 privacy_clearOnShutdown_formdata: Services.prefs.getBoolPref(
999 "privacy.clearOnShutdown.formdata"
1001 privacy_clearOnShutdown_downloads: Services.prefs.getBoolPref(
1002 "privacy.clearOnShutdown.downloads"
1004 privacy_clearOnShutdown_cache: Services.prefs.getBoolPref(
1005 "privacy.clearOnShutdown.cache"
1007 privacy_clearOnShutdown_sessions: Services.prefs.getBoolPref(
1008 "privacy.clearOnShutdown.sessions"
1010 privacy_clearOnShutdown_offlineApps: Services.prefs.getBoolPref(
1011 "privacy.clearOnShutdown.offlineApps"
1013 privacy_clearOnShutdown_siteSettings: Services.prefs.getBoolPref(
1014 "privacy.clearOnShutdown.siteSettings"
1016 privacy_clearOnShutdown_openWindows: Services.prefs.getBoolPref(
1017 "privacy.clearOnShutdown.openWindows"
1021 progress.sanitizationPrefs = {
1022 privacy_sanitize_sanitizeOnShutdown: Services.prefs.getBoolPref(
1023 "privacy.sanitize.sanitizeOnShutdown"
1025 privacy_clearOnShutdown_v2_cookiesAndStorage: Services.prefs.getBoolPref(
1026 "privacy.clearOnShutdown_v2.cookiesAndStorage"
1028 privacy_clearOnShutdown_v2_historyAndFormData: Services.prefs.getBoolPref(
1029 "privacy.clearOnShutdown_v2.historyAndFormData"
1031 privacy_clearOnShutdown_v2_cache: Services.prefs.getBoolPref(
1032 "privacy.clearOnShutdown_v2.cache"
1034 privacy_clearOnShutdown_v2_siteSettings: Services.prefs.getBoolPref(
1035 "privacy.clearOnShutdown_v2.siteSettings"
1037 privacy_clearOnShutdown_v2_downloads: Services.prefs.getBoolPref(
1038 "privacy.clearOnShutdown_v2.downloads"
1043 let needsSyncSavePrefs = false;
1044 if (Sanitizer.shouldSanitizeOnShutdown) {
1045 // Need to sanitize upon shutdown
1046 progress.advancement = "shutdown-cleaner";
1047 let shutdownBranch = lazy.useOldClearHistoryDialog
1048 ? Sanitizer.PREF_SHUTDOWN_BRANCH
1049 : Sanitizer.PREF_SHUTDOWN_V2_BRANCH;
1050 let itemsToClear = getItemsToClearFromPrefBranch(shutdownBranch);
1051 await Sanitizer.sanitize(itemsToClear, { progress });
1053 // We didn't crash during shutdown sanitization, so annotate it to avoid
1054 // sanitizing again on startup.
1055 removePendingSanitization("shutdown");
1056 needsSyncSavePrefs = true;
1059 if (Sanitizer.shouldSanitizeNewTabContainer) {
1060 progress.advancement = "newtab-segregation";
1061 sanitizeNewTabSegregation();
1062 removePendingSanitization("newtab-container");
1063 needsSyncSavePrefs = true;
1066 if (needsSyncSavePrefs) {
1067 Services.prefs.savePrefFile(null);
1070 if (!Sanitizer.shouldSanitizeOnShutdown) {
1071 // In case the user has not activated sanitizeOnShutdown but has explicitely set exceptions
1072 // to always clear particular origins, we clear those here
1074 progress.advancement = "session-permission";
1077 let selectedPrincipals = [];
1078 // Let's see if we have to forget some particular site.
1079 for (let permission of Services.perms.all) {
1081 permission.type != "cookie" ||
1082 permission.capability != Ci.nsICookiePermission.ACCESS_SESSION
1087 // We consider just permissions set for http, https and file URLs.
1088 if (!isSupportedPrincipal(permission.principal)) {
1093 "Custom session cookie permission detected for: " +
1094 permission.principal.asciiSpec
1098 // We use just the URI here, because permissions ignore OriginAttributes.
1099 // The principalsCollector is lazy, this is computed only once
1100 if (!gPrincipalsCollector) {
1101 gPrincipalsCollector = new lazy.PrincipalsCollector();
1103 let principals = await gPrincipalsCollector.getAllPrincipals(progress);
1104 selectedPrincipals.push(
1105 ...extractMatchingPrincipals(principals, permission.principal.host)
1108 await maybeSanitizeSessionPrincipals(
1111 Ci.nsIClearDataService.CLEAR_ALL_CACHES |
1112 Ci.nsIClearDataService.CLEAR_COOKIES |
1113 Ci.nsIClearDataService.CLEAR_DOM_STORAGES |
1114 Ci.nsIClearDataService.CLEAR_EME
1116 progress.sanitizationPrefs.session_permission_exceptions = exceptions;
1118 progress.advancement = "done";
1121 // Extracts the principals matching matchUri as root domain.
1122 function extractMatchingPrincipals(principals, matchHost) {
1123 return principals.filter(principal => {
1124 return Services.eTLD.hasRootDomain(matchHost, principal.host);
1128 /** This method receives a list of principals and it checks if some of them or
1129 * some of their sub-domain need to be sanitize.
1130 * @param {Object} progress - Object to keep track of the sanitization progress, prefs and mode
1131 * @param {nsIPrincipal[]} principals - The principals generated by the PrincipalsCollector
1132 * @param {int} flags - The cleaning categories that need to be cleaned for the principals.
1133 * @returns {Promise} - Resolves once the clearing of the principals to be cleared is done
1135 async function maybeSanitizeSessionPrincipals(progress, principals, flags) {
1136 log("Sanitizing " + principals.length + " principals");
1139 let permissions = new Map();
1140 Services.perms.getAllWithTypePrefix("cookie").forEach(perm => {
1141 permissions.set(perm.principal.origin, perm);
1144 principals.forEach(principal => {
1145 progress.step = "checking-principal";
1146 let cookieAllowed = cookiesAllowedForDomainOrSubDomain(
1150 progress.step = "principal-checked:" + cookieAllowed;
1152 if (!cookieAllowed) {
1153 promises.push(sanitizeSessionPrincipal(progress, principal, flags));
1157 progress.step = "promises:" + promises.length;
1158 if (promises.length) {
1159 await Promise.all(promises);
1160 await new Promise(resolve =>
1161 Services.clearData.cleanupAfterDeletionAtShutdown(flags, resolve)
1164 progress.step = "promises resolved";
1167 function cookiesAllowedForDomainOrSubDomain(principal, permissions) {
1168 log("Checking principal: " + principal.asciiSpec);
1170 // If we have the 'cookie' permission for this principal, let's return
1172 let cookiePermission = checkIfCookiePermissionIsSet(principal);
1173 if (cookiePermission != null) {
1174 return cookiePermission;
1177 for (let perm of permissions.values()) {
1178 if (perm.type != "cookie") {
1179 permissions.delete(perm.principal.origin);
1182 // We consider just permissions set for http, https and file URLs.
1183 if (!isSupportedPrincipal(perm.principal)) {
1184 permissions.delete(perm.principal.origin);
1188 // We don't care about scheme, port, and anything else.
1189 if (Services.eTLD.hasRootDomain(perm.principal.host, principal.host)) {
1190 log("Cookie check on principal: " + perm.principal.asciiSpec);
1191 let rootDomainCookiePermission = checkIfCookiePermissionIsSet(
1194 if (rootDomainCookiePermission != null) {
1195 return rootDomainCookiePermission;
1200 log("Cookie not allowed.");
1205 * Checks if a cookie permission is set for a given principal
1206 * @returns {boolean} - true: cookie permission "ACCESS_ALLOW", false: cookie permission "ACCESS_DENY"/"ACCESS_SESSION"
1207 * @returns {null} - No cookie permission is set for this principal
1209 function checkIfCookiePermissionIsSet(principal) {
1210 let p = Services.perms.testPermissionFromPrincipal(principal, "cookie");
1212 if (p == Ci.nsICookiePermission.ACCESS_ALLOW) {
1213 log("Cookie allowed!");
1218 p == Ci.nsICookiePermission.ACCESS_DENY ||
1219 p == Ci.nsICookiePermission.ACCESS_SESSION
1221 log("Cookie denied or session!");
1224 // This is an old profile with unsupported permission values
1225 if (p != Ci.nsICookiePermission.ACCESS_DEFAULT) {
1226 log("Not supported cookie permission: " + p);
1232 async function sanitizeSessionPrincipal(progress, principal, flags) {
1233 log("Sanitizing principal: " + principal.asciiSpec);
1235 await new Promise(resolve => {
1236 progress.sanitizePrincipal = "started";
1237 Services.clearData.deleteDataFromPrincipal(
1239 true /* user request */,
1244 progress.sanitizePrincipal = "completed";
1247 function sanitizeNewTabSegregation() {
1248 let identity = lazy.ContextualIdentityService.getPrivateIdentity(
1249 "userContextIdInternal.thumbnail"
1252 Services.clearData.deleteDataFromOriginAttributesPattern({
1253 userContextId: identity.userContextId,
1259 * Gets an array of items to clear from the given pref branch.
1260 * @param branch The pref branch to fetch.
1261 * @return Array of items to clear
1263 function getItemsToClearFromPrefBranch(branch) {
1264 branch = Services.prefs.getBranch(branch);
1265 return Object.keys(Sanitizer.items).filter(itemName => {
1267 return branch.getBoolPref(itemName);
1275 * These functions are used to track pending sanitization on the next startup
1276 * in case of a crash before a sanitization could happen.
1277 * @param id A unique id identifying the sanitization
1278 * @param itemsToClear The items to clear
1279 * @param options The Sanitize options
1281 function addPendingSanitization(id, itemsToClear, options) {
1282 let pendingSanitizations = safeGetPendingSanitizations();
1283 pendingSanitizations.push({ id, itemsToClear, options });
1284 Services.prefs.setStringPref(
1285 Sanitizer.PREF_PENDING_SANITIZATIONS,
1286 JSON.stringify(pendingSanitizations)
1290 function removePendingSanitization(id) {
1291 let pendingSanitizations = safeGetPendingSanitizations();
1292 let i = pendingSanitizations.findIndex(s => s.id == id);
1293 let [s] = pendingSanitizations.splice(i, 1);
1294 Services.prefs.setStringPref(
1295 Sanitizer.PREF_PENDING_SANITIZATIONS,
1296 JSON.stringify(pendingSanitizations)
1301 function getAndClearPendingSanitizations() {
1302 let pendingSanitizations = safeGetPendingSanitizations();
1303 if (pendingSanitizations.length) {
1304 Services.prefs.clearUserPref(Sanitizer.PREF_PENDING_SANITIZATIONS);
1306 return pendingSanitizations;
1309 function safeGetPendingSanitizations() {
1312 Services.prefs.getStringPref(Sanitizer.PREF_PENDING_SANITIZATIONS, "[]")
1315 console.error("Invalid JSON value for pending sanitizations: ", ex);
1320 async function clearData(range, flags) {
1322 await new Promise(resolve => {
1323 Services.clearData.deleteDataInTimeRange(
1326 true /* user request */,
1332 await new Promise(resolve => {
1333 Services.clearData.deleteData(flags, resolve);
1338 function isSupportedPrincipal(principal) {
1339 return ["http", "https", "file"].some(scheme => principal.schemeIs(scheme));