1 // Copyright (c) 2009 by Doug Kearns <dougkearns@gmail.com>
2 // Copyright (c) 2009-2012 Kris Maglione <maglione.k at Gmail>
4 // This work is licensed for reuse under an MIT license. Details are
5 // given in the LICENSE.txt file included with this file.
9 // - fix Sanitize autocommand
10 // - add warning for TIMESPAN_EVERYTHING?
13 // - finish 1.9.0 support if we're going to support sanitizing in Melodactyl
15 defineModule("sanitizer", {
16 exports: ["Range", "Sanitizer", "sanitizer"],
17 require: ["config", "prefs", "services", "util"]
20 lazyRequire("messages", ["_"]);
21 lazyRequire("overlay", ["overlay"]);
22 lazyRequire("storage", ["storage"]);
23 lazyRequire("template", ["template"]);
25 let tmp = Object.create(this);
26 JSMLoader.loadSubScript("chrome://browser/content/sanitize.js", tmp);
27 tmp.Sanitizer.prototype.__proto__ = Class.prototype;
29 var Range = Struct("min", "max");
30 update(Range.prototype, {
31 contains: function (date) date == null ||
32 (this.min == null || date >= this.min) && (this.max == null || date <= this.max),
34 get isEternity() this.max == null && this.min == null,
35 get isSession() this.max == null && this.min == sanitizer.sessionStart,
37 get native() this.isEternity ? null : [this.min || 0, this.max == null ? Number.MAX_VALUE : this.max]
40 var Item = Class("SanitizeItem", {
41 init: function (name, params) {
43 this.description = params.description;
46 // Hack for completion:
47 "0": Class.Property({ get: function () this.name }),
48 "1": Class.Property({ get: function () this.description }),
50 description: Messages.Localized(""),
52 get cpdPref() (this.builtin ? "" : Item.PREFIX) + Item.BRANCH + Sanitizer.argToPref(this.name),
53 get shutdownPref() (this.builtin ? "" : Item.PREFIX) + Item.SHUTDOWN_BRANCH + Sanitizer.argToPref(this.name),
54 get cpd() prefs.get(this.cpdPref),
55 get shutdown() prefs.get(this.shutdownPref),
57 shouldSanitize: function (shutdown) (!shutdown || this.builtin || this.persistent) &&
58 prefs.get(shutdown ? this.shutdownPref : this.pref)
60 PREFIX: config.prefs.branch.root,
61 BRANCH: "privacy.cpd.",
62 SHUTDOWN_BRANCH: "privacy.clearOnShutdown."
65 var Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference], tmp.Sanitizer), {
66 sessionStart: Date.now() * 1000,
71 util.addObserver(this);
73 services.add("cookies", "@mozilla.org/cookiemanager;1", [Ci.nsICookieManager, Ci.nsICookieManager2,
74 Ci.nsICookieService]);
75 services.add("loginManager", "@mozilla.org/login-manager;1", Ci.nsILoginManager);
76 services.add("permissions", "@mozilla.org/permissionmanager;1", Ci.nsIPermissionManager);
80 this.addItem("all", { description: "Sanitize all items", shouldSanitize: function () false });
82 this.addItem("cache", { builtin: true, description: "Cache" });
83 this.addItem("downloads", { builtin: true, description: "Download history" });
84 this.addItem("formdata", { builtin: true, description: "Saved form and search history" });
85 this.addItem("offlineapps", { builtin: true, description: "Offline website data" });
86 this.addItem("passwords", { builtin: true, description: "Saved passwords" });
87 this.addItem("sessions", { builtin: true, description: "Authenticated sessions" });
89 // These builtin methods don't support hosts or otherwise have
90 // insufficient granularity
91 this.addItem("cookies", {
93 description: "Cookies",
95 action: function (range, host) {
96 for (let c in Sanitizer.iterCookies(host))
97 if (range.contains(c.creationTime) || timespan.isSession && c.isSession)
98 services.cookies.remove(c.host, c.name, c.path, false);
102 this.addItem("history", {
104 description: "Browsing history",
106 sessionHistory: true,
107 action: function (range, host) {
109 services.history.removePagesFromHost(host, true);
111 if (range.isEternity)
112 services.history.removeAllPages();
114 services.history.removeVisitsByTimeframe(range.native[0], Math.min(Date.now() * 1000, range.native[1])); // XXX
115 services.observer.notifyObservers(null, "browser:purge-session-history", "");
118 if (!host || util.isDomainURL(prefs.get("general.open_location.last_url"), host))
119 prefs.reset("general.open_location.last_url");
124 var { ForgetAboutSite } = Cu.import("resource://gre/modules/ForgetAboutSite.jsm", {});
128 this.addItem("host", {
129 description: "All data from the given host",
130 action: function (range, host) {
132 ForgetAboutSite.removeDataFromDomain(host);
135 this.addItem("sitesettings", {
137 description: "Site preferences",
139 action: function (range, host) {
143 for (let p in Sanitizer.iterPermissions(host)) {
144 services.permissions.remove(util.createURI(p.host), p.type);
145 services.permissions.add(util.createURI(p.host), p.type, 0);
147 for (let p in iter(services.contentPrefs.getPrefs(util.createURI(host))))
148 services.contentPrefs.removePref(util.createURI(host), p.QueryInterface(Ci.nsIProperty).name);
151 // "Allow this site to open popups" ...
152 services.permissions.removeAll();
154 services.contentPrefs.removeGroupedPrefs();
157 // "Never remember passwords" ...
158 for each (let domain in services.loginManager.getAllDisabledHosts())
159 if (!host || util.isSubdomain(domain, host))
160 services.loginManager.setLoginSavingEnabled(host, true);
165 function ourItems(persistent) [
166 item for (item in values(self.itemMap))
167 if (!item.builtin && (!persistent || item.persistent) && item.name !== "all")
170 function prefOverlay(branch, persistent, local) update(Object.create(local), {
172 ["preferences", { id: branch.substr(Item.PREFIX.length) + "history",
174 template.map(ourItems(persistent), function (item)
175 ["preference", { type: "bool", id: branch + item.name, name: branch + item.name }])]
177 init: function init(win) {
178 let pane = win.document.getElementById("SanitizeDialogPane");
179 for (let [, pref] in iter(pane.preferences))
180 pref.updateElements();
181 init.superapply(this, arguments);
185 util.timeout(function () { // Load order issue...
187 let (branch = Item.PREFIX + Item.SHUTDOWN_BRANCH) {
188 overlay.overlayWindow("chrome://browser/content/preferences/sanitize.xul",
189 function (win) prefOverlay(branch, true, {
192 ["groupbox", { orient: "horizontal", xmlns: "xul" },
193 ["caption", { label: config.appName + /*L*/" (see :help privacy)" }],
194 ["grid", { flex: "1" },
196 ["column", { flex: "1" }],
197 ["column", { flex: "1" }]],
199 let (items = ourItems(true))
200 template.map(util.range(0, Math.ceil(items.length / 2)), function (i)
202 template.map(items.slice(i * 2, i * 2 + 2), function (item)
203 ["checkbox", { xmlns: XUL, label: item.description, preference: branch + item.name }])])]]]
207 let (branch = Item.PREFIX + Item.BRANCH) {
208 overlay.overlayWindow("chrome://browser/content/sanitize.xul",
209 function (win) prefOverlay(branch, false, {
212 ["listitem", { xmlns: "xul", label: /*L*/"See :help privacy for the following:",
213 disabled: "true", style: "font-style: italic; font-weight: bold;" }],
214 template.map(ourItems(), function ([item, desc])
215 ["listitem", { xmlns: "xul", preference: branch + item,
216 type: "checkbox", label: config.appName + ", " + desc,
217 onsyncfrompreference: "return gSanitizePromptDialog.onReadGeneric();" }])
220 ready: function ready(win) {
221 let elem = win.document.getElementById("itemList");
222 elem.setAttribute("rows", elem.itemCount);
223 win.Sanitizer = Class("Sanitizer", win.Sanitizer, {
224 sanitize: function sanitize() {
225 self.withSavedValues(["sanitizing"], function () {
226 self.sanitizing = true;
227 sanitize.superapply(this, arguments);
228 sanitizer.sanitizeItems([item.name for (item in values(self.itemMap))
229 if (item.shouldSanitize(false))],
230 Range.fromArray(this.range || []));
242 addItem: function addItem(name, params) {
243 let item = this.itemMap[name] || Item(name, params);
244 this.itemMap[name] = item;
246 for (let [k, prop] in iterOwnProperties(params))
247 if (!("value" in prop) || !callable(prop.value) && !(k in item))
248 Object.defineProperty(item, k, prop);
250 let names = Set([name].concat(params.contains || []).map(function (e) "clear-" + e));
252 storage.addObserver("sanitizer",
253 function (key, event, arg) {
255 params.action.apply(params, arg);
257 Class.objectGlobal(params.action));
259 if (params.privateEnter || params.privateLeave)
260 storage.addObserver("private-mode",
261 function (key, event, arg) {
262 let meth = params[arg ? "privateEnter" : "privateLeave"];
266 Class.objectGlobal(params.action));
270 "browser:purge-domain-data": function (subject, host) {
271 storage.fireEvent("sanitize", "domain", host);
272 // If we're sanitizing, our own sanitization functions will already
273 // be called, and with much greater granularity. Only process this
274 // event if it's triggered externally.
275 if (!this.sanitizing)
276 this.sanitizeItems(null, Range(), data);
278 "browser:purge-session-history": function (subject, data) {
280 if (!this.sanitizing)
281 this.sanitizeItems(null, Range(this.sessionStart), null, "sessionHistory");
283 "quit-application-granted": function (subject, data) {
284 if (this.runAtShutdown && !this.sanitizeItems(null, Range(), null, "shutdown"))
285 this.ranAtShutdown = true;
287 "private-browsing": function (subject, data) {
289 storage.privateMode = true;
290 else if (data == "exit")
291 storage.privateMode = false;
292 storage.fireEvent("private-mode", "change", storage.privateMode);
297 * Returns a load context for the given thing, to be used with
298 * interfaces needing one for per-window private browsing support.
300 * @param {Window|Document|Node} thing The thing for which to return
303 getContext: function getContext(thing) {
304 if (!Ci.nsILoadContext)
307 if (thing instanceof Ci.nsIDOMNode && thing.ownerDocument)
308 thing = thing.ownerDocument;
309 if (thing instanceof Ci.nsIDOMDocument)
310 thing = thing.defaultView;
311 if (thing instanceof Ci.nsIInterfaceRequestor)
312 thing = thing.getInterface(Ci.nsIWebNavigation);
313 return thing.QueryInterface(Ci.nsILoadContext);
316 get ranAtShutdown() config.prefs.get("didSanitizeOnShutdown"),
317 set ranAtShutdown(val) config.prefs.set("didSanitizeOnShutdown", Boolean(val)),
318 get runAtShutdown() prefs.get("privacy.sanitize.sanitizeOnShutdown"),
319 set runAtShutdown(val) prefs.set("privacy.sanitize.sanitizeOnShutdown", Boolean(val)),
321 sanitize: function sanitize(items, range)
322 this.withSavedValues(["sanitizing"], function () {
323 this.sanitizing = true;
324 let errors = this.sanitizeItems(items, range, null);
326 for (let itemName in values(items)) {
328 let item = this.items[Sanitizer.argToPref(itemName)];
329 if (item && !this.itemMap[itemName].override) {
330 item.range = range.native;
331 if ("clear" in item && item.canClear)
336 errors = errors || {};
337 errors[itemName] = e;
338 util.dump("Error sanitizing " + itemName);
345 sanitizeItems: function sanitizeItems(items, range, host, key)
346 this.withSavedValues(["sanitizing"], function () {
347 this.sanitizing = true;
349 items = Object.keys(this.itemMap);
352 for (let itemName in values(items))
354 if (!key || this.itemMap[itemName][key])
355 storage.fireEvent("sanitizer", "clear-" + itemName, [range, host]);
358 errors = errors || {};
359 errors[itemName] = e;
360 util.dump("Error sanitizing " + itemName);
373 UNPERMS: Class.Memoize(function () iter(this.PERMS).map(Array.reverse).toObject()),
377 allow: /*L*/"Allowed",
379 session: /*L*/"Allowed for the current session",
380 list: /*L*/"List all cookies for domain",
381 clear: /*L*/"Clear all cookies for domain",
382 "clear-persistent": /*L*/"Clear all persistent cookies for domain",
383 "clear-session": /*L*/"Clear all session cookies for domain"
387 offlineapps: "offlineApps",
388 sitesettings: "siteSettings"
390 argToPref: function (arg) Sanitizer.argPrefMap[arg] || arg,
391 prefToArg: function (pref) pref.replace(/.*\./, "").toLowerCase(),
393 iterCookies: function iterCookies(host) {
394 for (let c in iter(services.cookies, Ci.nsICookie2))
395 if (!host || util.isSubdomain(c.rawHost, host) ||
396 c.host[0] == "." && c.host.length < host.length
397 && host.indexOf(c.host) == host.length - c.host.length)
401 iterPermissions: function iterPermissions(host) {
402 for (let p in iter(services.permissions, Ci.nsIPermission))
403 if (!host || util.isSubdomain(p.host, host))
407 load: function initLoad(dactyl, modules, window) {
408 if (!sanitizer.firstRun++ && sanitizer.runAtShutdown && !sanitizer.ranAtShutdown)
409 sanitizer.sanitizeItems(null, Range(), null, "shutdown");
410 sanitizer.ranAtShutdown = false;
412 autocommands: function initAutocommands(dactyl, modules, window) {
413 const { autocommands } = modules;
415 storage.addObserver("private-mode",
416 function (key, event, value) {
417 autocommands.trigger("PrivateMode", { state: value });
419 storage.addObserver("sanitizer",
420 function (key, event, value) {
421 if (event == "domain")
422 autocommands.trigger("SanitizeDomain", { domain: value });
424 autocommands.trigger("Sanitize", { name: event.substr("clear-".length), domain: value[1] });
427 commands: function initCommands(dactyl, modules, window) {
428 const { commands } = modules;
429 commands.add(["sa[nitize]"],
430 "Clear private data",
432 dactyl.assert(!modules.options['private'], _("command.sanitize.privateMode"));
434 if (args["-host"] && !args.length && !args.bang)
437 let timespan = args["-timespan"] || modules.options["sanitizetimespan"];
440 let [match, num, unit] = /^(\d+)([mhdw])$/.exec(timespan) || [];
441 range[args["-older"] ? "max" : "min"] =
442 match ? 1000 * (Date.now() - 1000 * parseInt(num, 10) * { m: 60, h: 3600, d: 3600 * 24, w: 3600 * 24 * 7 }[unit])
443 : (timespan[0] == "s" ? sanitizer.sessionStart : null);
445 let opt = modules.options.get("sanitizeitems");
447 dactyl.assert(args.length == 0, _("error.trailingCharacters"));
449 dactyl.assert(opt.validator(args), _("error.invalidArgument"));
450 opt = { __proto__: opt, value: args.slice() };
453 let items = Object.keys(sanitizer.itemMap).slice(1).filter(opt.has, opt);
455 function sanitize(items) {
456 sanitizer.range = range.native;
457 sanitizer.ignoreTimespan = range.min == null;
458 sanitizer.sanitizing = true;
460 args["-host"].forEach(function (host) {
461 sanitizer.sanitizing = true;
462 sanitizer.sanitizeItems(items, range, host);
466 sanitizer.sanitize(items, range);
469 if (array.nth(opt.value, function (i) i == "all" || /^!/.test(i), 0) == "all" && !args["-host"])
470 modules.commandline.input(_("sanitize.prompt.deleteAll") + " ",
472 if (resp.match(/^y(es)?$/i)) {
474 dactyl.echomsg(_("command.sanitize.allDeleted"));
477 dactyl.echo(_("command.sanitize.noneDeleted"));
484 argCount: "*", // FIXME: should be + and 0
486 completer: function (context) {
487 context.title = ["Privacy Item", "Description"];
488 context.completions = modules.options.get("sanitizeitems").values;
490 domains: function (args) args["-host"] || [],
493 names: ["-host", "-h"],
494 description: "Only sanitize items referring to listed host or hosts",
495 completer: function (context, args) {
496 context.filters.push(function (item)
497 !args["-host"].some(function (host) util.isSubdomain(item.text, host)));
498 modules.completion.domain(context);
500 type: modules.CommandOption.LIST
502 names: ["-older", "-o"],
503 description: "Sanitize items older than timespan",
504 type: modules.CommandOption.NOARG
506 names: ["-timespan", "-t"],
507 description: "Timespan for which to sanitize items",
508 completer: function (context) modules.options.get("sanitizetimespan").completer(context),
509 type: modules.CommandOption.STRING,
510 validator: function (arg) modules.options.get("sanitizetimespan").validator(arg)
516 function getPerms(host) {
517 let uri = util.createURI(host);
519 return Sanitizer.UNPERMS[services.permissions.testPermission(uri, "cookie")];
522 function setPerms(host, perm) {
523 let uri = util.createURI(host);
524 services.permissions.remove(uri.host, "cookie");
525 services.permissions.add(uri, "cookie", Sanitizer.PERMS[perm]);
527 commands.add(["cookies", "ck"],
528 "Change cookie permissions for sites",
530 let host = args.shift();
533 args = modules.options["cookies"];
535 for (let [, cmd] in Iterator(args))
538 for (let c in Sanitizer.iterCookies(host))
539 services.cookies.remove(c.host, c.name, c.path, false);
541 case "clear-persistent":
543 case "clear-session":
544 for (let c in Sanitizer.iterCookies(host))
545 if (c.isSession == session)
546 services.cookies.remove(c.host, c.name, c.path, false);
550 modules.commandline.commandOutput(template.tabular(
551 ["Host", "Expiry (UTC)", "Path", "Name", "Value"],
552 ["padding-right: 1em", "padding-right: 1em", "padding-right: 1em", "max-width: 12em; overflow: hidden;", "padding-left: 1ex;"],
554 c.isSession ? ["span", { highlight: "Enabled" }, "session"]
555 : (new Date(c.expiry * 1000).toJSON() || "Never").replace(/:\d\d\.000Z/, "").replace("T", " ").replace(/-/g, "/"),
559 for (c in Sanitizer.iterCookies(host)))));
562 util.assert(cmd in Sanitizer.PERMS, _("error.invalidArgument"));
567 completer: function (context, args) {
568 switch (args.completeArg) {
570 modules.completion.visibleHosts(context);
571 context.title[1] = "Current Permissions";
572 context.keys.description = function desc(host) {
574 for (let c in Sanitizer.iterCookies(host))
575 count[c.isSession + 0]++;
576 return [Sanitizer.COMMANDS[getPerms(host)], " (session: ", count[1], " persistent: ", count[0], ")"].join("");
580 context.completions = Sanitizer.COMMANDS;
586 completion: function initCompletion(dactyl, modules, window) {
587 modules.completion.visibleHosts = function completeHosts(context) {
588 let res = util.visibleHosts(window.content);
589 if (context.filter && !res.some(function (host) host.indexOf(context.filter) >= 0))
590 res.push(context.filter);
592 context.title = ["Domain"];
593 context.anchored = false;
594 context.compare = modules.CompletionContext.Sort.unsorted;
595 context.keys = { text: util.identity, description: util.identity };
596 context.completions = res;
599 options: function initOptions(dactyl, modules) {
600 const options = modules.options;
602 options.add(["sanitizeitems", "si"],
603 "The default list of private items to sanitize",
606 get values() values(sanitizer.itemMap).toArray(),
608 completer: function completer(context, extra) {
609 if (context.filter[0] == "!")
611 return completer.superapply(this, arguments);
614 has: function has(val)
615 let (res = array.nth(this.value, function (v) v == "all" || v.replace(/^!/, "") == val, 0))
616 res && !/^!/.test(res),
618 validator: function (values) values.length &&
619 values.every(function (val) val === "all" || Set.has(sanitizer.itemMap, val.replace(/^!/, "")))
622 options.add(["sanitizeshutdown", "ss"],
623 "The items to sanitize automatically at shutdown",
627 get values() [i for (i in values(sanitizer.itemMap)) if (i.persistent || i.builtin)],
628 getter: function () !sanitizer.runAtShutdown ? [] : [
629 item.name for (item in values(sanitizer.itemMap))
630 if (item.shouldSanitize(true))
632 setter: function (value) {
633 if (value.length === 0)
634 sanitizer.runAtShutdown = false;
636 sanitizer.runAtShutdown = true;
637 let have = Set(value);
638 for (let item in values(sanitizer.itemMap))
639 prefs.set(item.shutdownPref,
640 Boolean(Set.has(have, item.name) ^ Set.has(have, "all")));
646 options.add(["sanitizetimespan", "sts"],
647 "The default sanitizer time span",
650 completer: function (context) {
651 context.compare = context.constructor.Sort.Unsorted;
652 context.completions = this.values;
656 "session": "The current session",
657 "10m": "Last ten minutes",
662 validator: bind("test", /^(a(ll)?|s(ession)|\d+[mhdw])$/)
665 options.add(["cookies", "ck"],
666 "The default mode for newly added cookie permissions",
667 "stringlist", "session",
668 { get values() Sanitizer.COMMANDS });
670 options.add(["cookieaccept", "ca"],
671 "When to accept cookies",
674 PREF: "network.cookie.cookieBehavior",
676 ["all", "Accept all cookies"],
677 ["samesite", "Accept all non-third-party cookies"],
678 ["none", "Accept no cookies"]
680 getter: function () (this.values[prefs.get(this.PREF)] || ["all"])[0],
681 setter: function (val) {
682 prefs.set(this.PREF, this.values.map(function (i) i[0]).indexOf(val));
689 options.add(["cookielifetime", "cl"],
690 "The lifetime for which to accept cookies",
691 "string", "default", {
692 PREF: "network.cookie.lifetimePolicy",
693 PREF_DAYS: "network.cookie.lifetime.days",
695 ["default", "The lifetime requested by the setter"],
696 ["prompt", "Always prompt for a lifetime"],
697 ["session", "The current session"]
699 getter: function () (this.values[prefs.get(this.PREF)] || [prefs.get(this.PREF_DAYS)])[0],
700 setter: function (value) {
701 let val = this.values.map(function (i) i[0]).indexOf(value);
703 prefs.set(this.PREF, val);
705 prefs.set(this.PREF, 3);
706 prefs.set(this.PREF_DAYS, parseInt(value));
711 validator: function validator(val) parseInt(val) == val || validator.superapply(this, arguments)
718 // catch(e){dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack);}
720 // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: