]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/sanitizer.jsm
2db1dfe54d1455ce9faebf3933e788649b8f84bd
[dactyl.git] / common / modules / sanitizer.jsm
1 // Copyright (c) 2009 by Doug Kearns <dougkearns@gmail.com>
2 // Copyright (c) 2009-2013 Kris Maglione <maglione.k at Gmail>
3 //
4 // This work is licensed for reuse under an MIT license. Details are
5 // given in the LICENSE.txt file included with this file.
6 "use strict";
7
8 // TODO:
9 //   - fix Sanitize autocommand
10 //   - add warning for TIMESPAN_EVERYTHING?
11
12 // FIXME:
13 //   - finish 1.9.0 support if we're going to support sanitizing in Melodactyl
14
15 defineModule("sanitizer", {
16     exports: ["Range", "Sanitizer", "sanitizer"],
17     require: ["config", "prefs", "services", "util"]
18 });
19
20 lazyRequire("messages", ["_"]);
21 lazyRequire("overlay", ["overlay"]);
22 lazyRequire("storage", ["storage"]);
23 lazyRequire("template", ["template"]);
24
25 let tmp = Object.create(this);
26 JSMLoader.loadSubScript("chrome://browser/content/sanitize.js", tmp);
27 tmp.Sanitizer.prototype.__proto__ = Class.prototype;
28
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),
33
34     get isEternity() this.max == null && this.min == null,
35     get isSession() this.max == null && this.min == sanitizer.sessionStart,
36
37     get native() this.isEternity ? null : [this.min || 0, this.max == null ? Number.MAX_VALUE : this.max]
38 });
39
40 var Item = Class("SanitizeItem", {
41     init: function (name, params) {
42         this.name = name;
43         this.description = params.description;
44     },
45
46     // Hack for completion:
47     "0": Class.Property({ get: function () this.name }),
48     "1": Class.Property({ get: function () this.description }),
49
50     description: Messages.Localized(""),
51
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),
56
57     shouldSanitize: function (shutdown) (!shutdown || this.builtin || this.persistent) &&
58         prefs.get(shutdown ? this.shutdownPref : this.pref)
59 }, {
60     PREFIX: config.prefs.branch.root,
61     BRANCH: "privacy.cpd.",
62     SHUTDOWN_BRANCH: "privacy.clearOnShutdown."
63 });
64
65 var Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference], tmp.Sanitizer), {
66     sessionStart: Date.now() * 1000,
67
68     init: function () {
69         const self = this;
70
71         util.addObserver(this);
72
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);
77
78         this.itemMap = {};
79
80         this.addItem("all", { description: "Sanitize all items", shouldSanitize: function () false });
81         // Builtin items
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" });
88
89         // These builtin methods don't support hosts or otherwise have
90         // insufficient granularity
91         this.addItem("cookies", {
92             builtin: true,
93             description: "Cookies",
94             persistent: true,
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);
99             },
100             override: true
101         });
102         this.addItem("history", {
103             builtin: true,
104             description: "Browsing history",
105             persistent: true,
106             sessionHistory: true,
107             action: function (range, host) {
108                 if (host)
109                     services.history.removePagesFromHost(host, true);
110                 else {
111                     if (range.isEternity)
112                         services.history.removeAllPages();
113                     else
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", "");
116                 }
117
118                 if (!host || util.isDomainURL(prefs.get("general.open_location.last_url"), host))
119                     prefs.reset("general.open_location.last_url");
120             },
121             override: true
122         });
123         try {
124             var { ForgetAboutSite } = Cu.import("resource://gre/modules/ForgetAboutSite.jsm", {});
125         }
126         catch (e) {}
127         if (ForgetAboutSite)
128             this.addItem("host", {
129                 description: "All data from the given host",
130                 action: function (range, host) {
131                     if (host)
132                         ForgetAboutSite.removeDataFromDomain(host);
133                 }
134             });
135         this.addItem("sitesettings", {
136             builtin: true,
137             description: "Site preferences",
138             persistent: true,
139             action: function (range, host) {
140                 if (range.isSession)
141                     return;
142                 if (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);
146                     }
147                     for (let p in iter(services.contentPrefs.getPrefs(util.createURI(host))))
148                         services.contentPrefs.removePref(util.createURI(host), p.QueryInterface(Ci.nsIProperty).name);
149                 }
150                 else {
151                     // "Allow this site to open popups" ...
152                     services.permissions.removeAll();
153                     // Zoom level, ...
154                     services.contentPrefs.removeGroupedPrefs();
155                 }
156
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);
161             },
162             override: true
163         });
164
165         function ourItems(persistent) [
166             item for (item in values(self.itemMap))
167             if (!item.builtin && (!persistent || item.persistent) && item.name !== "all")
168         ];
169
170         function prefOverlay(branch, persistent, local) update(Object.create(local), {
171             before: [
172                 ["preferences", { id: branch.substr(Item.PREFIX.length) + "history",
173                                   xmlns: "xul" },
174                   template.map(ourItems(persistent), item =>
175                       ["preference", { type: "bool", id: branch + item.name, name: branch + item.name }])]
176             ],
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);
182             }
183         });
184
185         util.timeout(function () { // Load order issue...
186
187             let (branch = Item.PREFIX + Item.SHUTDOWN_BRANCH) {
188                 overlay.overlayWindow("chrome://browser/content/preferences/sanitize.xul",
189                                       function (win) prefOverlay(branch, true, {
190                     append: {
191                         SanitizeDialogPane:
192                             ["groupbox", { orient: "horizontal", xmlns: "xul" },
193                               ["caption", { label: config.appName + /*L*/" (see :help privacy)" }],
194                               ["grid", { flex: "1" },
195                                 ["columns", {},
196                                     ["column", { flex: "1" }],
197                                     ["column", { flex: "1" }]],
198                                 ["rows", {},
199                                   let (items = ourItems(true))
200                                      template.map(util.range(0, Math.ceil(items.length / 2)), i =>
201                                          ["row", {},
202                                              template.map(items.slice(i * 2, i * 2 + 2), item =>
203                                                 ["checkbox", { xmlns: XUL, label: item.description, preference: branch + item.name }])])]]]
204                     }
205                 }));
206             }
207             let (branch = Item.PREFIX + Item.BRANCH) {
208                 overlay.overlayWindow("chrome://browser/content/sanitize.xul",
209                                    function (win) prefOverlay(branch, false, {
210                     append: {
211                         itemList: [
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(), ([item, desc]) =>
215                                 ["listitem", { xmlns: "xul", preference: branch + item,
216                                                type: "checkbox", label: config.appName + ", " + desc,
217                                                onsyncfrompreference: "return gSanitizePromptDialog.onReadGeneric();" }])
218                         ]
219                     },
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 || []));
231                                 }, this);
232                             }
233                         });
234                     }
235                 }));
236             }
237         });
238     },
239
240     firstRun: 0,
241
242     addItem: function addItem(name, params) {
243         let item = this.itemMap[name] || Item(name, params);
244         this.itemMap[name] = item;
245
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);
249
250         let names = Set([name].concat(params.contains || []).map(e => "clear-" + e));
251         if (params.action)
252             storage.addObserver("sanitizer",
253                 function (key, event, arg) {
254                     if (event in names)
255                         params.action.apply(params, arg);
256                 },
257                 Class.objectGlobal(params.action));
258
259         if (params.privateEnter || params.privateLeave)
260             storage.addObserver("private-mode",
261                 function (key, event, arg) {
262                     let meth = params[arg ? "privateEnter" : "privateLeave"];
263                     if (meth)
264                         meth.call(params);
265                 },
266                 Class.objectGlobal(params.action));
267     },
268
269     observers: {
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);
277         },
278         "browser:purge-session-history": function (subject, data) {
279             // See above.
280             if (!this.sanitizing)
281                 this.sanitizeItems(null, Range(this.sessionStart), null, "sessionHistory");
282         },
283         "quit-application-granted": function (subject, data) {
284             if (this.runAtShutdown && !this.sanitizeItems(null, Range(), null, "shutdown"))
285                 this.ranAtShutdown = true;
286         },
287         "private-browsing": function (subject, data) {
288             if (data == "enter")
289                 storage.privateMode = true;
290             else if (data == "exit")
291                 storage.privateMode = false;
292             storage.fireEvent("private-mode", "change", storage.privateMode);
293         }
294     },
295
296     /**
297      * Returns a load context for the given thing, to be used with
298      * interfaces needing one for per-window private browsing support.
299      *
300      * @param {Window|Document|Node} thing The thing for which to return
301      *      a load context.
302      */
303     getContext: function getContext(thing) {
304         if (!Ci.nsILoadContext)
305             return null;
306
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);
314     },
315
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)),
320
321     sanitize: function sanitize(items, range)
322         this.withSavedValues(["sanitizing"], function () {
323             this.sanitizing = true;
324             let errors = this.sanitizeItems(items, range, null);
325
326             for (let itemName in values(items)) {
327                 try {
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)
332                             item.clear();
333                     }
334                 }
335                 catch (e) {
336                     errors = errors || {};
337                     errors[itemName] = e;
338                     util.dump("Error sanitizing " + itemName);
339                     util.reportError(e);
340                 }
341             }
342             return errors;
343         }),
344
345     sanitizeItems: function sanitizeItems(items, range, host, key)
346         this.withSavedValues(["sanitizing"], function () {
347             this.sanitizing = true;
348             if (items == null)
349                 items = Object.keys(this.itemMap);
350
351             let errors;
352             for (let itemName in values(items))
353                 try {
354                     if (!key || this.itemMap[itemName][key])
355                         storage.fireEvent("sanitizer", "clear-" + itemName, [range, host]);
356                 }
357                 catch (e) {
358                     errors = errors || {};
359                     errors[itemName] = e;
360                     util.dump("Error sanitizing " + itemName);
361                     util.reportError(e);
362                 }
363             return errors;
364         })
365 }, {
366     PERMS: {
367         unset:   0,
368         allow:   1,
369         deny:    2,
370         session: 8
371     },
372
373     UNPERMS: Class.Memoize(function () iter(this.PERMS).map(Array.reverse).toObject()),
374
375     COMMANDS: {
376         unset:   /*L*/"Unset",
377         allow:   /*L*/"Allowed",
378         deny:    /*L*/"Denied",
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"
384     },
385
386     argPrefMap: {
387         offlineapps:  "offlineApps",
388         sitesettings: "siteSettings"
389     },
390     argToPref: function (arg) Sanitizer.argPrefMap[arg] || arg,
391     prefToArg: function (pref) pref.replace(/.*\./, "").toLowerCase(),
392
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)
398                 yield c;
399
400     },
401     iterPermissions: function iterPermissions(host) {
402         for (let p in iter(services.permissions, Ci.nsIPermission))
403             if (!host || util.isSubdomain(p.host, host))
404                 yield p;
405     }
406 }, {
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;
411     },
412     autocommands: function initAutocommands(dactyl, modules, window) {
413         const { autocommands } = modules;
414
415         storage.addObserver("private-mode",
416             function (key, event, value) {
417                 autocommands.trigger("PrivateMode", { state: value });
418             }, window);
419         storage.addObserver("sanitizer",
420             function (key, event, value) {
421                 if (event == "domain")
422                     autocommands.trigger("SanitizeDomain", { domain: value });
423                 else if (!value[1])
424                     autocommands.trigger("Sanitize", { name: event.substr("clear-".length), domain: value[1] });
425             }, window);
426     },
427     commands: function initCommands(dactyl, modules, window) {
428         const { commands } = modules;
429         commands.add(["sa[nitize]"],
430             "Clear private data",
431             function (args) {
432                 dactyl.assert(!modules.options['private'], _("command.sanitize.privateMode"));
433
434                 if (args["-host"] && !args.length && !args.bang)
435                     args[0] = "all";
436
437                 let timespan = args["-timespan"] || modules.options["sanitizetimespan"];
438
439                 let range = Range();
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);
444
445                 let opt = modules.options.get("sanitizeitems");
446                 if (args.bang)
447                     dactyl.assert(args.length == 0, _("error.trailingCharacters"));
448                 else {
449                     dactyl.assert(opt.validator(args), _("error.invalidArgument"));
450                     opt = { __proto__: opt, value: args.slice() };
451                 }
452
453                 let items = Object.keys(sanitizer.itemMap).slice(1).filter(opt.has, opt);
454
455                 function sanitize(items) {
456                     sanitizer.range = range.native;
457                     sanitizer.ignoreTimespan = range.min == null;
458                     sanitizer.sanitizing = true;
459                     if (args["-host"]) {
460                         args["-host"].forEach(function (host) {
461                             sanitizer.sanitizing = true;
462                             sanitizer.sanitizeItems(items, range, host);
463                         });
464                     }
465                     else
466                         sanitizer.sanitize(items, range);
467                 }
468
469                 if (array.nth(opt.value, i => i == "all" || /^!/.test(i), 0) == "all" && !args["-host"])
470                     modules.commandline.input(_("sanitize.prompt.deleteAll") + " ",
471                         function (resp) {
472                             if (resp.match(/^y(es)?$/i)) {
473                                 sanitize(items);
474                                 dactyl.echomsg(_("command.sanitize.allDeleted"));
475                             }
476                             else
477                                 dactyl.echo(_("command.sanitize.noneDeleted"));
478                         });
479                 else
480                     sanitize(items);
481
482             },
483             {
484                 argCount: "*", // FIXME: should be + and 0
485                 bang: true,
486                 completer: function (context) {
487                     context.title = ["Privacy Item", "Description"];
488                     context.completions = modules.options.get("sanitizeitems").values;
489                 },
490                 domains: function (args) args["-host"] || [],
491                 options: [
492                     {
493                         names: ["-host", "-h"],
494                         description: "Only sanitize items referring to listed host or hosts",
495                         completer: function (context, args) {
496                             context.filters.push(item =>
497                                 !args["-host"].some(host => util.isSubdomain(item.text, host)));
498                             modules.completion.domain(context);
499                         },
500                         type: modules.CommandOption.LIST
501                     }, {
502                         names: ["-older", "-o"],
503                         description: "Sanitize items older than timespan",
504                         type: modules.CommandOption.NOARG
505                     }, {
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)
511                     }
512                 ],
513                 privateData: true
514             });
515
516             function getPerms(host) {
517                 let uri = util.createURI(host);
518                 if (uri)
519                     return Sanitizer.UNPERMS[services.permissions.testPermission(uri, "cookie")];
520                 return "unset";
521             }
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]);
526             }
527             commands.add(["cookies", "ck"],
528                 "Change cookie permissions for sites",
529                 function (args) {
530                     let host = args.shift();
531                     let session = true;
532                     if (!args.length)
533                         args = modules.options["cookies"];
534
535                     for (let [, cmd] in Iterator(args))
536                         switch (cmd) {
537                         case "clear":
538                             for (let c in Sanitizer.iterCookies(host))
539                                 services.cookies.remove(c.host, c.name, c.path, false);
540                             break;
541                         case "clear-persistent":
542                             session = false;
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);
547                             return;
548
549                         case "list":
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;"],
553                                 ([c.host,
554                                   c.isSession ? ["span", { highlight: "Enabled" }, "session"]
555                                               : (new Date(c.expiry * 1000).toJSON() || "Never").replace(/:\d\d\.000Z/, "").replace("T", " ").replace(/-/g, "/"),
556                                   c.path,
557                                   c.name,
558                                   c.value]
559                                   for (c in Sanitizer.iterCookies(host)))));
560                             return;
561                         default:
562                             util.assert(cmd in Sanitizer.PERMS, _("error.invalidArgument"));
563                             setPerms(host, cmd);
564                         }
565                 }, {
566                     argCount: "+",
567                     completer: function (context, args) {
568                         switch (args.completeArg) {
569                         case 0:
570                             modules.completion.visibleHosts(context);
571                             context.title[1] = "Current Permissions";
572                             context.keys.description = function desc(host) {
573                                 let count = [0, 0];
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("");
577                             };
578                             break;
579                         case 1:
580                             context.completions = Sanitizer.COMMANDS;
581                             break;
582                         }
583                     },
584                 });
585     },
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(host => host.indexOf(context.filter) >= 0))
590                 res.push(context.filter);
591
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;
597         };
598     },
599     options: function initOptions(dactyl, modules) {
600         const options = modules.options;
601
602         options.add(["sanitizeitems", "si"],
603             "The default list of private items to sanitize",
604             "stringlist", "all",
605             {
606                 get values() values(sanitizer.itemMap).toArray(),
607
608                 completer: function completer(context, extra) {
609                     if (context.filter[0] == "!")
610                         context.advance(1);
611                     return completer.superapply(this, arguments);
612                 },
613
614                 has: function has(val)
615                     let (res = array.nth(this.value, v => (v == "all" || v.replace(/^!/, "") == val),
616                                          0))
617                         res && !/^!/.test(res),
618
619                 validator: function (values) values.length &&
620                     values.every(val => (val === "all" || Set.has(sanitizer.itemMap, val.replace(/^!/, ""))))
621             });
622
623         options.add(["sanitizeshutdown", "ss"],
624             "The items to sanitize automatically at shutdown",
625             "stringlist", "",
626             {
627                 initialValue: true,
628                 get values() [i for (i in values(sanitizer.itemMap)) if (i.persistent || i.builtin)],
629                 getter: function () !sanitizer.runAtShutdown ? [] : [
630                     item.name for (item in values(sanitizer.itemMap))
631                     if (item.shouldSanitize(true))
632                 ],
633                 setter: function (value) {
634                     if (value.length === 0)
635                         sanitizer.runAtShutdown = false;
636                     else {
637                         sanitizer.runAtShutdown = true;
638                         let have = Set(value);
639                         for (let item in values(sanitizer.itemMap))
640                             prefs.set(item.shutdownPref,
641                                       Boolean(Set.has(have, item.name) ^ Set.has(have, "all")));
642                     }
643                     return value;
644                 }
645             });
646
647         options.add(["sanitizetimespan", "sts"],
648             "The default sanitizer time span",
649             "string", "all",
650             {
651                 completer: function (context) {
652                     context.compare = context.constructor.Sort.Unsorted;
653                     context.completions = this.values;
654                 },
655                 values: {
656                     "all":     "Everything",
657                     "session": "The current session",
658                     "10m":     "Last ten minutes",
659                     "1h":      "Past hour",
660                     "1d":      "Past day",
661                     "1w":      "Past week"
662                 },
663                 validator: bind("test", /^(a(ll)?|s(ession)|\d+[mhdw])$/)
664             });
665
666         options.add(["cookies", "ck"],
667             "The default mode for newly added cookie permissions",
668             "stringlist", "session",
669             { get values() Sanitizer.COMMANDS });
670
671         options.add(["cookieaccept", "ca"],
672             "When to accept cookies",
673             "string", "all",
674             {
675                 PREF: "network.cookie.cookieBehavior",
676                 values: [
677                     ["all", "Accept all cookies"],
678                     ["samesite", "Accept all non-third-party cookies"],
679                     ["none", "Accept no cookies"]
680                 ],
681                 getter: function () (this.values[prefs.get(this.PREF)] || ["all"])[0],
682                 setter: function (val) {
683                     prefs.set(this.PREF, this.values.map(i => i[0]).indexOf(val));
684                     return val;
685                 },
686                 initialValue: true,
687                 persist: false
688             });
689
690         options.add(["cookielifetime", "cl"],
691             "The lifetime for which to accept cookies",
692             "string", "default", {
693                 PREF: "network.cookie.lifetimePolicy",
694                 PREF_DAYS: "network.cookie.lifetime.days",
695                 values: [
696                     ["default", "The lifetime requested by the setter"],
697                     ["prompt",  "Always prompt for a lifetime"],
698                     ["session", "The current session"]
699                 ],
700                 getter: function () (this.values[prefs.get(this.PREF)] || [prefs.get(this.PREF_DAYS)])[0],
701                 setter: function (value) {
702                     let val = this.values.map(i => i[0]).indexOf(value);
703                     if (val > -1)
704                         prefs.set(this.PREF, val);
705                     else {
706                         prefs.set(this.PREF, 3);
707                         prefs.set(this.PREF_DAYS, parseInt(value));
708                     }
709                 },
710                 initialValue: true,
711                 persist: false,
712                 validator: function validator(val) parseInt(val) == val || validator.superapply(this, arguments)
713             });
714     }
715 });
716
717 endModule();
718
719 // catch(e){dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack);}
720
721 // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: