From 1317d16dbfc5efa0c42832eaff4fc8023d221fed Mon Sep 17 00:00:00 2001 From: koops76 Date: Tue, 27 Jun 2017 19:59:19 +0300 Subject: [PATCH 01/35] Add icon badge in Chromium --- chromium/background.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/chromium/background.js b/chromium/background.js index 4a17201c73e6..f4805abca94d 100644 --- a/chromium/background.js +++ b/chromium/background.js @@ -127,6 +127,14 @@ var updateState = function() { chrome.browserAction.setTitle({ title: "HTTPS Everywhere (" + iconState + ")" }); + + const appliedCount = applied ? Object.keys(applied).length : 0; + + chrome.browserAction.setBadgeBackgroundColor({color: "#00cc00"}); + + const showBadge = appliedCount > 0 && isExtensionEnabled; + + chrome.browserAction.setBadgeText({text: showBadge ? "" + appliedCount : ""}); }); } @@ -192,6 +200,8 @@ AppliedRulesets.prototype = { this.active_tab_rules[tabId] = {}; this.active_tab_rules[tabId][ruleset.name] = ruleset; } + + updateState(); }, getRulesets: function(tabId) { From aaedc49f8a1c78c804c34482f19d6c481235b378 Mon Sep 17 00:00:00 2001 From: koops76 Date: Tue, 27 Jun 2017 20:35:38 +0300 Subject: [PATCH 02/35] Update rules.js --- chromium/rules.js | 989 +++++++++++++++++++++++++++------------------- 1 file changed, 575 insertions(+), 414 deletions(-) diff --git a/chromium/rules.js b/chromium/rules.js index 18c0870670a1..5078b4606e78 100644 --- a/chromium/rules.js +++ b/chromium/rules.js @@ -1,493 +1,654 @@ "use strict"; -// Stubs so this runs under nodejs. They get overwritten later by util.js -var VERB=1; -var DBUG=2; -var INFO=3; -var NOTE=4; -var WARN=5; -function log(){} - -// To reduce memory usage for the numerous rules/cookies with trivial rules -const trivial_rule_to = "https:"; -const trivial_rule_from_c = new RegExp("^http:"); -const trivial_cookie_name_c = new RegExp(".*"); -const trivial_cookie_host_c = new RegExp(".*"); - /** - * A single rule - * @param from - * @param to - * @constructor + * Fetch and parse XML to be loaded as RuleSets. + * + * @param url: a relative URL to local XML */ -function Rule(from, to) { - if (from === "^http:" && to === "https:") { - // This is a trivial rule, rewriting http->https with no complex RegExp. - this.to = trivial_rule_to; - this.from_c = trivial_rule_from_c; - } else { - // This is a non-trivial rule. - this.to = to; - this.from_c = new RegExp(from); +function loadExtensionFile(url, returnType) { + var xhr = new XMLHttpRequest(); + // Use blocking XHR to ensure everything is loaded by the time + // we return. + xhr.open("GET", chrome.extension.getURL(url), false); + xhr.send(null); + // Get file contents + if (xhr.readyState != 4) { + return; + } + if (returnType === 'xml') { + return xhr.responseXML; } + return xhr.responseText; } + +// Rules are loaded here +var all_rules = new RuleSets(localStorage); + +// Allow users to enable `platform="mixedcontent"` rulesets +var enableMixedRulesets = false; +storage.get({enableMixedRulesets: false}, function(item) { + enableMixedRulesets = item.enableMixedRulesets; + all_rules.addFromXml(loadExtensionFile('rules/default.rulesets', 'xml')); +}); + +var USER_RULE_KEY = 'userRules'; +// Records which tabId's are active in the HTTPS Switch Planner (see +// devtools-panel.js). +var switchPlannerEnabledFor = {}; +// Detailed information recorded when the HTTPS Switch Planner is active. +// Structure is: +// switchPlannerInfo[tabId]["rw"/"nrw"][resource_host][active_content][url]; +// rw / nrw stand for "rewritten" versus "not rewritten" +var switchPlannerInfo = {}; + +// Is HTTPSe enabled, or has it been manually disabled by the user? +var isExtensionEnabled = true; + +// Load prefs about whether http nowhere is on. Structure is: +// { httpNowhere: true/false } +var httpNowhereOn = false; +storage.get({httpNowhere: false}, function(item) { + httpNowhereOn = item.httpNowhere; + updateState(); +}); +chrome.storage.onChanged.addListener(function(changes, areaName) { + if (areaName === 'sync' || areaName === 'local') { + for (var key in changes) { + if (key === 'httpNowhere') { + httpNowhereOn = changes[key].newValue; + updateState(); + } + } + } +}); +chrome.tabs.onActivated.addListener(function() { + updateState(); +}); +chrome.windows.onFocusChanged.addListener(function() { + updateState(); +}); +chrome.webNavigation.onCompleted.addListener(function() { + updateState(); +}); + +/** +* Load stored user rules + **/ +var getStoredUserRules = function() { + var oldUserRuleString = localStorage.getItem(USER_RULE_KEY); + var oldUserRules = []; + if (oldUserRuleString) { + oldUserRules = JSON.parse(oldUserRuleString); + } + return oldUserRules; +}; +var wr = chrome.webRequest; + /** - * Regex-Compile a pattern - * @param pattern The pattern to compile - * @constructor + * Load all stored user rules */ -function Exclusion(pattern) { - this.pattern_c = new RegExp(pattern); +var loadStoredUserRules = function() { + var rules = getStoredUserRules(); + var i; + for (i = 0; i < rules.length; ++i) { + all_rules.addUserRule(rules[i]); + } + log('INFO', 'loaded ' + i + ' stored user rules'); +}; + +loadStoredUserRules(); + +function getActiveRulesetCount() { + const applied = activeRulesets.getRulesets(tabs[0].id); + + if (!applied) + { + return 0; + } + + let activeCount = 0; + + for (const key in applied) { + if (applied[key].active) { + activeCount++; + } + } + + return activeCount; } /** - * Generates a CookieRule - * @param host The host regex to compile - * @param cookiename The cookie name Regex to compile - * @constructor + * Set the icon color correctly + * inactive: extension is enabled, but no rules were triggered on this page. + * blocking: extension is in "block all HTTP requests" mode. + * active: extension is enabled and rewrote URLs on this page. + * disabled: extension is disabled from the popup menu. */ -function CookieRule(host, cookiename) { - if (host === ".*" || host === ".+" || host === ".") { - // Some cookie rules trivially match any host. - this.host_c = trivial_cookie_host_c; +var updateState = function() { + chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { + if (!tabs || tabs.length === 0) { + return; + } + + const activeCount = getActiveRulesetCount(); + + var iconState = "inactive"; + if (!isExtensionEnabled) { + iconState = "disabled"; + } else if (httpNowhereOn) { + iconState = "blocking"; + } else if (activeCount > 0) { + iconState = "active"; + } + chrome.browserAction.setIcon({ + path: { + "38": "icons/icon-" + iconState + "-38.png" + } + }); + chrome.browserAction.setTitle({ + title: "HTTPS Everywhere (" + iconState + ")" + }); + + chrome.browserAction.setBadgeBackgroundColor({color: "#00cc00"}); + + const showBadge = activeCount > 0 && isExtensionEnabled; + + chrome.browserAction.setBadgeText({text: showBadge ? "" + activeCount : ""}); + }); +} + +/** + * Adds a new user rule + * @param params: params defining the rule + * @param cb: Callback to call after success/fail + * */ +var addNewRule = function(params, cb) { + if (all_rules.addUserRule(params)) { + // If we successfully added the user rule, save it in local + // storage so it's automatically applied when the extension is + // reloaded. + var oldUserRules = getStoredUserRules(); + // TODO: there's a race condition here, if this code is ever executed from multiple + // client windows in different event loops. + oldUserRules.push(params); + // TODO: can we exceed the max size for storage? + localStorage.setItem(USER_RULE_KEY, JSON.stringify(oldUserRules)); + cb(true); } else { - this.host_c = new RegExp(host); + cb(false); } +}; - if (cookiename === ".*" || cookiename === ".+" || cookiename === ".") { - // About 50% of cookie rules trivially match any name. - this.name_c = trivial_cookie_name_c; - } else { - this.name_c = new RegExp(cookiename); +/** + * Removes a user rule + * @param ruleset: the ruleset to remove + * */ +var removeRule = function(ruleset) { + if (all_rules.removeUserRule(ruleset)) { + // If we successfully removed the user rule, remove it in local storage too + var oldUserRules = getStoredUserRules(); + for (let x = 0; x < oldUserRules.length; x++) { + if (oldUserRules[x].host == ruleset.name && + oldUserRules[x].redirectTo == ruleset.rules[0].to && + String(RegExp(oldUserRules[x].urlMatcher)) == String(ruleset.rules[0].from_c)) { + oldUserRules.splice(x, 1); + break; + } + } + localStorage.setItem(USER_RULE_KEY, JSON.stringify(oldUserRules)); } } /** - *A collection of rules - * @param set_name The name of this set - * @param default_state activity state - * @param note Note will be displayed in popup - * @constructor - */ -function RuleSet(set_name, default_state, note) { - this.name = set_name; - this.rules = []; - this.exclusions = null; - this.cookierules = null; - this.active = default_state; - this.default_state = default_state; - this.note = note; + * Adds a listener for removed tabs + * */ +function AppliedRulesets() { + this.active_tab_rules = {}; + + var that = this; + chrome.tabs.onRemoved.addListener(function(tabId, info) { + that.removeTab(tabId); + }); } -RuleSet.prototype = { - /** - * Check if a URI can be rewritten and rewrite it - * @param urispec The uri to rewrite - * @returns {*} null or the rewritten uri - */ - apply: function(urispec) { - var returl = null; - // If we're covered by an exclusion, go home - if (this.exclusions !== null) { - for (var i = 0; i < this.exclusions.length; ++i) { - if (this.exclusions[i].pattern_c.test(urispec)) { - log(DBUG, "excluded uri " + urispec); - return null; - } - } +AppliedRulesets.prototype = { + addRulesetToTab: function(tabId, ruleset) { + if (tabId in this.active_tab_rules) { + this.active_tab_rules[tabId][ruleset.name] = ruleset; + } else { + this.active_tab_rules[tabId] = {}; + this.active_tab_rules[tabId][ruleset.name] = ruleset; } - // Okay, now find the first rule that triggers - for(var i = 0; i < this.rules.length; ++i) { - returl = urispec.replace(this.rules[i].from_c, - this.rules[i].to); - if (returl != urispec) { - return returl; - } + updateState(); + }, + + getRulesets: function(tabId) { + if (tabId in this.active_tab_rules) { + return this.active_tab_rules[tabId]; } return null; }, - /** - * Deep equivalence comparison - * @param ruleset The ruleset to compare with - * @returns true or false, depending on whether it's deeply equivalent - */ - isEquivalentTo: function(ruleset) { - if(this.name != ruleset.name || - this.note != ruleset.note || - this.state != ruleset.state || - this.default_state != ruleset.default_state) { - return false; - } + removeTab: function(tabId) { + delete this.active_tab_rules[tabId]; + } +}; - try { - var this_exclusions_length = this.exclusions.length; - } catch(e) { - var this_exclusions_length = 0; - } +// FIXME: change this name +var activeRulesets = new AppliedRulesets(); - try { - var ruleset_exclusions_length = ruleset.exclusions.length; - } catch(e) { - var ruleset_exclusions_length = 0; - } +var urlBlacklist = new Set(); +var domainBlacklist = new Set(); - try { - var this_rules_length = this.rules.length; - } catch(e) { - var this_rules_length = 0; - } +// redirect counter workaround +// TODO: Remove this code if they ever give us a real counter +var redirectCounter = {}; - try { - var ruleset_rules_length = ruleset.rules.length; - } catch(e) { - var ruleset_rules_length = 0; - } +/** + * Called before a HTTP(s) request. Does the heavy lifting + * Cancels the request/redirects it to HTTPS. URL modification happens in here. + * @param details of the handler, see Chrome doc + * */ +function onBeforeRequest(details) { + // If HTTPSe has been disabled by the user, return immediately. + if (!isExtensionEnabled) { + return; + } - if(this_exclusions_length != ruleset_exclusions_length || - this_rules_length != ruleset_rules_length) { - return false; - } - if(this_exclusions_length > 0) { - for(let x = 0; x < this.exclusions.length; x++){ - if(this.exclusions[x].pattern_c != ruleset.exclusions[x].pattern_c) { - return false; - } - } - } - if(this_rules_length > 0) { - for(let x = 0; x < this.rules.length; x++){ - if(this.rules[x].to != ruleset.rules[x].to) { - return false; - } - } - } - return true; + var uri = document.createElement('a'); + uri.href = details.url; + + // Should the request be canceled? + var shouldCancel = ( + httpNowhereOn && + uri.protocol === 'http:' && + !/\.onion$/.test(uri.hostname) && + !/^localhost$/.test(uri.hostname) && + !/^127(\.[0-9]{1,3}){3}$/.test(uri.hostname) && + !/^0\.0\.0\.0$/.test(uri.hostname) + ); + + // Normalise hosts such as "www.example.com." + var canonical_host = uri.hostname; + if (canonical_host.charAt(canonical_host.length - 1) == ".") { + while (canonical_host.charAt(canonical_host.length - 1) == ".") + canonical_host = canonical_host.slice(0,-1); + uri.hostname = canonical_host; } -}; + // If there is a username / password, put them aside during the ruleset + // analysis process + var using_credentials_in_url = false; + if (uri.password || uri.username) { + using_credentials_in_url = true; + var tmp_user = uri.username; + var tmp_pass = uri.password; + uri.username = null; + uri.password = null; + } -/** - * Initialize Rule Sets - * @param ruleActiveStates default state for rules - * @constructor - */ -function RuleSets(ruleActiveStates) { - // Load rules into structure - this.targets = {}; + var canonical_url = uri.href; + if (details.url != canonical_url && !using_credentials_in_url) { + log(INFO, "Original url " + details.url + + " changed before processing to " + canonical_url); + } + if (urlBlacklist.has(canonical_url)) { + return {cancel: shouldCancel}; + } - // A cache for potentiallyApplicableRulesets - this.ruleCache = new Map(); + if (details.type == "main_frame") { + activeRulesets.removeTab(details.tabId); + } - // A cache for cookie hostnames. - this.cookieHostCache = new Map(); + var potentiallyApplicable = all_rules.potentiallyApplicableRulesets(uri.hostname); - // A hash of rule name -> active status (true/false). - this.ruleActiveStates = ruleActiveStates; -} + if (redirectCounter[details.requestId] >= 8) { + log(NOTE, "Redirect counter hit for " + canonical_url); + urlBlacklist.add(canonical_url); + var hostname = uri.hostname; + domainBlacklist.add(hostname); + log(WARN, "Domain blacklisted " + hostname); + return {cancel: shouldCancel}; + } + var newuristr = null; -RuleSets.prototype = { - /** - * Iterate through data XML and load rulesets - */ - addFromXml: function(ruleXml) { - var sets = ruleXml.getElementsByTagName("ruleset"); - for (var i = 0; i < sets.length; ++i) { - try { - this.parseOneRuleset(sets[i]); - } catch (e) { - log(WARN, 'Error processing ruleset:' + e); - } + for (let ruleset of potentiallyApplicable) { + activeRulesets.addRulesetToTab(details.tabId, ruleset); + if (ruleset.active && !newuristr) { + newuristr = ruleset.apply(canonical_url); } - }, + } - /** - * Load a user rule - * @param params - * @returns {boolean} - */ - addUserRule : function(params) { - log(INFO, 'adding new user rule for ' + JSON.stringify(params)); - var new_rule_set = new RuleSet(params.host, true, "user rule"); - var new_rule = new Rule(params.urlMatcher, params.redirectTo); - new_rule_set.rules.push(new_rule); - if (!(params.host in this.targets)) { - this.targets[params.host] = []; - } - this.ruleCache.delete(params.host); - // TODO: maybe promote this rule? - this.targets[params.host].push(new_rule_set); - if (new_rule_set.name in this.ruleActiveStates) { - new_rule_set.active = (this.ruleActiveStates[new_rule_set.name] == "true"); - } - log(INFO, 'done adding rule'); - return true; - }, + if (newuristr && using_credentials_in_url) { + // re-insert userpass info which was stripped temporarily + var uri_with_credentials = document.createElement('a'); + uri_with_credentials.href = newuristr; + uri_with_credentials.username = tmp_user; + uri_with_credentials.password = tmp_pass; + newuristr = uri_with_credentials.href; + } + + // In Switch Planner Mode, record any non-rewriteable + // HTTP URIs by parent hostname, along with the resource type. + if (switchPlannerEnabledFor[details.tabId] && uri.protocol !== "https:") { + writeToSwitchPlanner(details.type, + details.tabId, + canonical_host, + details.url, + newuristr); + } - /** - * Remove a user rule - * @param params - * @returns {boolean} - */ - removeUserRule: function(ruleset) { - log(INFO, 'removing user rule for ' + JSON.stringify(ruleset)); - this.ruleCache.delete(ruleset.name); - for(let x = 0; x < this.targets[ruleset.name].length; x++) { - if(this.targets[ruleset.name][x].isEquivalentTo(ruleset)) { - this.targets[ruleset.name].splice(x, 1); + if (httpNowhereOn) { + // If loading a main frame, try the HTTPS version as an alternative to + // failing. + if (shouldCancel) { + if (!newuristr) { + return {redirectUrl: canonical_url.replace(/^http:/, "https:")}; + } else { + return {redirectUrl: newuristr.replace(/^http:/, "https:")}; } } - if (this.targets[ruleset.name].length == 0) { - delete this.targets[ruleset.name]; + if (newuristr && newuristr.substring(0, 5) === "http:") { + // Abort early if we're about to redirect to HTTP in HTTP Nowhere mode + return {cancel: true}; } - log(INFO, 'done removing rule'); - return true; - }, + } - /** - * Does the loading of a ruleset. - * @param ruletag The whole tag to parse - */ - parseOneRuleset: function(ruletag) { - var default_state = true; - var note = ""; - var default_off = ruletag.getAttribute("default_off"); - if (default_off) { - default_state = false; - note += default_off + "\n"; - } + if (newuristr) { + return {redirectUrl: newuristr}; + } else { + return {cancel: shouldCancel}; + } +} - // If a ruleset declares a platform, and we don't match it, treat it as - // off-by-default. In practice, this excludes "mixedcontent" & "cacert" rules. - var platform = ruletag.getAttribute("platform"); - if (platform) { - default_state = false; - if (platform == "mixedcontent" && enableMixedRulesets) { - default_state = true; - } - note += "Platform(s): " + platform + "\n"; - } - var rule_set = new RuleSet(ruletag.getAttribute("name"), - default_state, - note.trim()); +// Map of which values for the `type' enum denote active vs passive content. +// https://developer.chrome.com/extensions/webRequest.html#event-onBeforeRequest +var activeTypes = { stylesheet: 1, script: 1, object: 1, other: 1}; - // Read user prefs - if (rule_set.name in this.ruleActiveStates) { - rule_set.active = (this.ruleActiveStates[rule_set.name] == "true"); - } +// We consider sub_frame to be passive even though it can contain JS or flash. +// This is because code running in the sub_frame cannot access the main frame's +// content, by same-origin policy. This is true even if the sub_frame is on the +// same domain but different protocol - i.e. HTTP while the parent is HTTPS - +// because same-origin policy includes the protocol. This also mimics Chrome's +// UI treatment of insecure subframes. +var passiveTypes = { main_frame: 1, sub_frame: 1, image: 1, xmlhttprequest: 1}; - var rules = ruletag.getElementsByTagName("rule"); - for(var j = 0; j < rules.length; j++) { - rule_set.rules.push(new Rule(rules[j].getAttribute("from"), - rules[j].getAttribute("to"))); - } +/** + * Record a non-HTTPS URL loaded by a given hostname in the Switch Planner, for + * use in determining which resources need to be ported to HTTPS. + * (Reminder: Switch planner is the pro-tool enabled by switching into debug-mode) + * + * @param type: type of the resource (see activeTypes and passiveTypes arrays) + * @param tab_id: The id of the tab + * @param resource_host: The host of the original url + * @param resource_url: the original url + * @param rewritten_url: The url rewritten to + * */ +function writeToSwitchPlanner(type, tab_id, resource_host, resource_url, rewritten_url) { + var rw = "rw"; + if (rewritten_url == null) + rw = "nrw"; + + var active_content = 0; + if (activeTypes[type]) { + active_content = 1; + } else if (passiveTypes[type]) { + active_content = 0; + } else { + log(WARN, "Unknown type from onBeforeRequest details: `" + type + "', assuming active"); + active_content = 1; + } - var exclusions = ruletag.getElementsByTagName("exclusion"); - if (exclusions.length > 0) { - rule_set.exclusions = []; - for (var j = 0; j < exclusions.length; j++) { - rule_set.exclusions.push( - new Exclusion(exclusions[j].getAttribute("pattern"))); - } - } + if (!switchPlannerInfo[tab_id]) { + switchPlannerInfo[tab_id] = {}; + switchPlannerInfo[tab_id]["rw"] = {}; + switchPlannerInfo[tab_id]["nrw"] = {}; + } + if (!switchPlannerInfo[tab_id][rw][resource_host]) + switchPlannerInfo[tab_id][rw][resource_host] = {}; + if (!switchPlannerInfo[tab_id][rw][resource_host][active_content]) + switchPlannerInfo[tab_id][rw][resource_host][active_content] = {}; - var cookierules = ruletag.getElementsByTagName("securecookie"); - if (cookierules.length > 0) { - rule_set.cookierules = []; - for(var j = 0; j < cookierules.length; j++) { - rule_set.cookierules.push( - new CookieRule(cookierules[j].getAttribute("host"), - cookierules[j].getAttribute("name"))); - } - } + switchPlannerInfo[tab_id][rw][resource_host][active_content][resource_url] = 1; +} - var targets = ruletag.getElementsByTagName("target"); - for(var j = 0; j < targets.length; j++) { - var host = targets[j].getAttribute("host"); - if (!(host in this.targets)) { - this.targets[host] = []; - } - this.targets[host].push(rule_set); - } - }, +/** + * Return the number of properties in an object. For associative maps, this is + * their size. + * @param obj: object to calc the size for + * */ +function objSize(obj) { + if (typeof obj == 'undefined') return 0; + var size = 0, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) size++; + } + return size; +} - /** - * Return a list of rulesets that apply to this host - * @param host The host to check - * @returns {*} (empty) list - */ - potentiallyApplicableRulesets: function(host) { - // Have we cached this result? If so, return it! - var cached_item = this.ruleCache.get(host); - if (cached_item !== undefined) { - log(DBUG, "Ruleset cache hit for " + host + " items:" + cached_item.length); - return cached_item; - } - log(DBUG, "Ruleset cache miss for " + host); +/** + * Make an array of asset hosts by score so we can sort them, + * presenting the most important ones first. + * */ +function sortSwitchPlanner(tab_id, rewritten) { + var asset_host_list = []; + if (typeof switchPlannerInfo[tab_id] === 'undefined' || + typeof switchPlannerInfo[tab_id][rewritten] === 'undefined') { + return []; + } + var tabInfo = switchPlannerInfo[tab_id][rewritten]; + for (var asset_host in tabInfo) { + var ah = tabInfo[asset_host]; + var activeCount = objSize(ah[1]); + var passiveCount = objSize(ah[0]); + var score = activeCount * 100 + passiveCount; + asset_host_list.push([score, activeCount, passiveCount, asset_host]); + } + asset_host_list.sort(function(a,b){return a[0]-b[0];}); + return asset_host_list; +} - var tmp; - var results = []; - if (this.targets[host]) { - // Copy the host targets so we don't modify them. - results = results.concat(this.targets[host]); - } +/** +* Format the switch planner output for presentation to a user. +* */ +function switchPlannerSmallHtmlSection(tab_id, rewritten) { + var asset_host_list = sortSwitchPlanner(tab_id, rewritten); + if (asset_host_list.length == 0) { + return "none"; + } - // Ensure host is well-formed (RFC 1035) - if (host.indexOf("..") != -1 || host.length > 255) { - log(WARN,"Malformed host passed to potentiallyApplicableRulesets: " + host); - return null; - } + var output = ""; + for (var i = asset_host_list.length - 1; i >= 0; i--) { + var host = asset_host_list[i][3]; + var activeCount = asset_host_list[i][1]; + var passiveCount = asset_host_list[i][2]; - // Replace each portion of the domain with a * in turn - var segmented = host.split("."); - for (var i = 0; i < segmented.length; ++i) { - tmp = segmented[i]; - segmented[i] = "*"; - results = results.concat(this.targets[segmented.join(".")]); - segmented[i] = tmp; + output += "" + host + ": "; + if (activeCount > 0) { + output += activeCount + " active"; + if (passiveCount > 0) + output += ", "; } - // now eat away from the left, with *, so that for x.y.z.google.com we - // check *.z.google.com and *.google.com (we did *.y.z.google.com above) - for (var i = 2; i <= segmented.length - 2; ++i) { - var t = "*." + segmented.slice(i,segmented.length).join("."); - results = results.concat(this.targets[t]); + if (passiveCount > 0) { + output += passiveCount + " passive"; } + output += "
"; + } + return output; +} - // Clean the results list, which may contain duplicates or undefined entries - var resultSet = new Set(results); - resultSet.delete(undefined); - - log(DBUG,"Applicable rules for " + host + ":"); - if (resultSet.size == 0) { - log(DBUG, " None"); - } else { - for (let target of resultSet.values()) { - log(DBUG, " " + target.name); - } - } +/** + * Create switch planner sections + * */ +function switchPlannerRenderSections(tab_id, f) { + return "Unrewritten HTTP resources loaded from this tab (enable HTTPS on " + + "these domains and add them to HTTPS Everywhere):
" + + f(tab_id, "nrw") + + "
Resources rewritten successfully from this tab (update these " + + "in your source code):
" + + f(tab_id, "rw"); +} - // Insert results into the ruleset cache - this.ruleCache.set(host, resultSet); +/** + * Generate the small switch planner html content + * */ +function switchPlannerSmallHtml(tab_id) { + return switchPlannerRenderSections(tab_id, switchPlannerSmallHtmlSection); +} - // Cap the size of the cache. (Limit chosen somewhat arbitrarily) - if (this.ruleCache.size > 1000) { - // Map.prototype.keys() returns keys in insertion order, so this is a FIFO. - this.ruleCache.delete(this.ruleCache.keys().next().value); +/** + * Generate a HTML link from urls in map + * map: the map containing the urls + * */ +function linksFromKeys(map) { + if (typeof map == 'undefined') return ""; + var output = ""; + for (var key in map) { + if (map.hasOwnProperty(key)) { + output += "" + key + "
"; } + } + return output; +} - return resultSet; - }, +/** + * Generate the detailed html fot the switch planner + * */ +function switchPlannerDetailsHtml(tab_id) { + return switchPlannerRenderSections(tab_id, switchPlannerDetailsHtmlSection); +} - /** - * Check to see if the Cookie object c meets any of our cookierule criteria for being marked as secure. - * @param cookie The cookie to test - * @returns {*} ruleset or null - */ - shouldSecureCookie: function(cookie) { - var hostname = cookie.domain; - // cookie domain scopes can start with . - while (hostname.charAt(0) == ".") { - hostname = hostname.slice(1); - } +/** + * Generate the detailed html fot the switch planner, by section + * */ +function switchPlannerDetailsHtmlSection(tab_id, rewritten) { + var asset_host_list = sortSwitchPlanner(tab_id, rewritten); + var output = ""; + + for (var i = asset_host_list.length - 1; i >= 0; i--) { + var host = asset_host_list[i][3]; + var activeCount = asset_host_list[i][1]; + var passiveCount = asset_host_list[i][2]; + + output += "" + host + ": "; + if (activeCount > 0) { + output += activeCount + " active
"; + output += linksFromKeys(switchPlannerInfo[tab_id][rewritten][host][1]); + } + if (passiveCount > 0) { + output += "
" + passiveCount + " passive
"; + output += linksFromKeys(switchPlannerInfo[tab_id][rewritten][host][0]); + } + output += "
"; + } + return output; +} - if (!this.safeToSecureCookie(hostname)) { - return null; - } +/** + * monitor cookie changes. Automatically convert them to secure cookies + * @param changeInfo Cookie changed info, see Chrome doc + * */ +function onCookieChanged(changeInfo) { + if (!changeInfo.removed && !changeInfo.cookie.secure && isExtensionEnabled) { + if (all_rules.shouldSecureCookie(changeInfo.cookie)) { + var cookie = {name:changeInfo.cookie.name, + value:changeInfo.cookie.value, + path:changeInfo.cookie.path, + httpOnly:changeInfo.cookie.httpOnly, + expirationDate:changeInfo.cookie.expirationDate, + storeId:changeInfo.cookie.storeId, + secure: true}; + + // Host-only cookies don't set the domain field. + if (!changeInfo.cookie.hostOnly) { + cookie.domain = changeInfo.cookie.domain; + } - var potentiallyApplicable = this.potentiallyApplicableRulesets(hostname); - for (let ruleset of potentiallyApplicable) { - if (ruleset.cookierules !== null && ruleset.active) { - for (var j = 0; j < ruleset.cookierules.length; j++) { - var cr = ruleset.cookierules[j]; - if (cr.host_c.test(cookie.domain) && cr.name_c.test(cookie.name)) { - return ruleset; - } - } + // The cookie API is magical -- we must recreate the URL from the domain and path. + if (changeInfo.cookie.domain[0] == ".") { + cookie.url = "https://www" + changeInfo.cookie.domain + cookie.path; + } else { + cookie.url = "https://" + changeInfo.cookie.domain + cookie.path; } + // We get repeated events for some cookies because sites change their + // value repeatedly and remove the "secure" flag. + log(DBUG, + "Securing cookie " + cookie.name + " for " + changeInfo.cookie.domain + ", was secure=" + changeInfo.cookie.secure); + chrome.cookies.set(cookie); } - return null; - }, + } +} - /** - * Check if it is secure to secure the cookie (=patch the secure flag in). - * @param domain The domain of the cookie - * @returns {*} true or false - */ - safeToSecureCookie: function(domain) { - // Check if the domain might be being served over HTTP. If so, it isn't - // safe to secure a cookie! We can't always know this for sure because - // observing cookie-changed doesn't give us enough context to know the - // full origin URI. - - // First, if there are any redirect loops on this domain, don't secure - // cookies. XXX This is not a very satisfactory heuristic. Sometimes we - // would want to secure the cookie anyway, because the URLs that loop are - // not authenticated or not important. Also by the time the loop has been - // observed and the domain blacklisted, a cookie might already have been - // flagged as secure. - - if (domainBlacklist.has(domain)) { - log(INFO, "cookies for " + domain + "blacklisted"); - return false; - } - var cached_item = this.cookieHostCache.get(domain); - if (cached_item !== undefined) { - log(DBUG, "Cookie host cache hit for " + domain); - return cached_item; +/** + * handling redirects, breaking loops + * @param details details for the redirect (see chrome doc) + * */ +function onBeforeRedirect(details) { + // Catch redirect loops (ignoring about:blank, etc. caused by other extensions) + var prefix = details.redirectUrl.substring(0, 5); + if (prefix === "http:" || prefix === "https") { + if (details.requestId in redirectCounter) { + redirectCounter[details.requestId] += 1; + log(DBUG, "Got redirect id "+details.requestId+ + ": "+redirectCounter[details.requestId]); + } else { + redirectCounter[details.requestId] = 1; + } } - log(DBUG, "Cookie host cache miss for " + domain); +} - // If we passed that test, make up a random URL on the domain, and see if - // we would HTTPSify that. +// Registers the handler for requests +// See: https://github.com/EFForg/https-everywhere/issues/10039 +wr.onBeforeRequest.addListener(onBeforeRequest, {urls: [""]}, ["blocking"]); - var nonce_path = "/" + Math.random().toString(); - var test_uri = "http://" + domain + nonce_path + nonce_path; - // Cap the size of the cookie cache (limit chosen somewhat arbitrarily) - if (this.cookieHostCache.size > 250) { - // Map.prototype.keys() returns keys in insertion order, so this is a FIFO. - this.cookieHostCache.delete(this.cookieHostCache.keys().next().value); - } +// Try to catch redirect loops on URLs we've redirected to HTTPS. +wr.onBeforeRedirect.addListener(onBeforeRedirect, {urls: ["https://*/*"]}); - log(INFO, "Testing securecookie applicability with " + test_uri); - var potentiallyApplicable = this.potentiallyApplicableRulesets(domain); - for (let ruleset of potentiallyApplicable) { - if (!ruleset.active) { - continue; - } - if (ruleset.apply(test_uri)) { - log(INFO, "Cookie domain could be secured."); - this.cookieHostCache.set(domain, true); - return true; - } - } - log(INFO, "Cookie domain could NOT be secured."); - this.cookieHostCache.set(domain, false); - return false; - }, - /** - * Rewrite an URI - * @param urispec The uri to rewrite - * @param host The host of this uri - * @returns {*} the new uri or null - */ - rewriteURI: function(urispec, host) { - var newuri = null; - var potentiallyApplicable = this.potentiallyApplicableRulesets(host); - for (let ruleset of potentiallyApplicable) { - if (ruleset.active && (newuri = ruleset.apply(urispec))) { - return newuri; - } - } - return null; - } -}; +// Listen for cookies set/updated and secure them if applicable. This function is async/nonblocking. +chrome.cookies.onChanged.addListener(onCookieChanged); -// Export for HTTPS Rewriter if applicable. -if (typeof exports != 'undefined') { - exports.RuleSets = RuleSets; +/** + * disable switch Planner + * @param tabId the Tab to disable for + */ +function disableSwitchPlannerFor(tabId) { + delete switchPlannerEnabledFor[tabId]; + // Clear stored URL info. + delete switchPlannerInfo[tabId]; } + +/** + * Enable switch planner for specific tab + * @param tabId the tab to enable it for + */ +function enableSwitchPlannerFor(tabId) { + switchPlannerEnabledFor[tabId] = true; +} + +// Listen for connection from the DevTools panel so we can set up communication. +chrome.runtime.onConnect.addListener(function (port) { + if (port.name == "devtools-page") { + chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){ + var tabId = message.tabId; + + var disableOnCloseCallback = function(port) { + log(DBUG, "Devtools window for tab " + tabId + " closed, clearing data."); + disableSwitchPlannerFor(tabId); + }; + + if (message.type === "enable") { + enableSwitchPlannerFor(tabId); + port.onDisconnect.addListener(disableOnCloseCallback); + } else if (message.type === "disable") { + disableSwitchPlannerFor(tabId); + } else if (message.type === "getSmallHtml") { + sendResponse({html: switchPlannerSmallHtml(tabId)}); + } + }); + } +}); From c4cf57cf7c4c849484c542bca46486b84b87e2f4 Mon Sep 17 00:00:00 2001 From: koops76 Date: Tue, 27 Jun 2017 20:37:46 +0300 Subject: [PATCH 03/35] Update rules.js --- chromium/rules.js | 989 +++++++++++++++++++--------------------------- 1 file changed, 414 insertions(+), 575 deletions(-) diff --git a/chromium/rules.js b/chromium/rules.js index 5078b4606e78..18c0870670a1 100644 --- a/chromium/rules.js +++ b/chromium/rules.js @@ -1,654 +1,493 @@ "use strict"; -/** - * Fetch and parse XML to be loaded as RuleSets. - * - * @param url: a relative URL to local XML - */ -function loadExtensionFile(url, returnType) { - var xhr = new XMLHttpRequest(); - // Use blocking XHR to ensure everything is loaded by the time - // we return. - xhr.open("GET", chrome.extension.getURL(url), false); - xhr.send(null); - // Get file contents - if (xhr.readyState != 4) { - return; - } - if (returnType === 'xml') { - return xhr.responseXML; - } - return xhr.responseText; -} - - -// Rules are loaded here -var all_rules = new RuleSets(localStorage); - -// Allow users to enable `platform="mixedcontent"` rulesets -var enableMixedRulesets = false; -storage.get({enableMixedRulesets: false}, function(item) { - enableMixedRulesets = item.enableMixedRulesets; - all_rules.addFromXml(loadExtensionFile('rules/default.rulesets', 'xml')); -}); - -var USER_RULE_KEY = 'userRules'; -// Records which tabId's are active in the HTTPS Switch Planner (see -// devtools-panel.js). -var switchPlannerEnabledFor = {}; -// Detailed information recorded when the HTTPS Switch Planner is active. -// Structure is: -// switchPlannerInfo[tabId]["rw"/"nrw"][resource_host][active_content][url]; -// rw / nrw stand for "rewritten" versus "not rewritten" -var switchPlannerInfo = {}; - -// Is HTTPSe enabled, or has it been manually disabled by the user? -var isExtensionEnabled = true; - -// Load prefs about whether http nowhere is on. Structure is: -// { httpNowhere: true/false } -var httpNowhereOn = false; -storage.get({httpNowhere: false}, function(item) { - httpNowhereOn = item.httpNowhere; - updateState(); -}); -chrome.storage.onChanged.addListener(function(changes, areaName) { - if (areaName === 'sync' || areaName === 'local') { - for (var key in changes) { - if (key === 'httpNowhere') { - httpNowhereOn = changes[key].newValue; - updateState(); - } - } - } -}); -chrome.tabs.onActivated.addListener(function() { - updateState(); -}); -chrome.windows.onFocusChanged.addListener(function() { - updateState(); -}); -chrome.webNavigation.onCompleted.addListener(function() { - updateState(); -}); +// Stubs so this runs under nodejs. They get overwritten later by util.js +var VERB=1; +var DBUG=2; +var INFO=3; +var NOTE=4; +var WARN=5; +function log(){} + +// To reduce memory usage for the numerous rules/cookies with trivial rules +const trivial_rule_to = "https:"; +const trivial_rule_from_c = new RegExp("^http:"); +const trivial_cookie_name_c = new RegExp(".*"); +const trivial_cookie_host_c = new RegExp(".*"); /** -* Load stored user rules - **/ -var getStoredUserRules = function() { - var oldUserRuleString = localStorage.getItem(USER_RULE_KEY); - var oldUserRules = []; - if (oldUserRuleString) { - oldUserRules = JSON.parse(oldUserRuleString); - } - return oldUserRules; -}; -var wr = chrome.webRequest; - -/** - * Load all stored user rules + * A single rule + * @param from + * @param to + * @constructor */ -var loadStoredUserRules = function() { - var rules = getStoredUserRules(); - var i; - for (i = 0; i < rules.length; ++i) { - all_rules.addUserRule(rules[i]); - } - log('INFO', 'loaded ' + i + ' stored user rules'); -}; - -loadStoredUserRules(); - -function getActiveRulesetCount() { - const applied = activeRulesets.getRulesets(tabs[0].id); - - if (!applied) - { - return 0; - } - - let activeCount = 0; - - for (const key in applied) { - if (applied[key].active) { - activeCount++; - } +function Rule(from, to) { + if (from === "^http:" && to === "https:") { + // This is a trivial rule, rewriting http->https with no complex RegExp. + this.to = trivial_rule_to; + this.from_c = trivial_rule_from_c; + } else { + // This is a non-trivial rule. + this.to = to; + this.from_c = new RegExp(from); } - - return activeCount; } /** - * Set the icon color correctly - * inactive: extension is enabled, but no rules were triggered on this page. - * blocking: extension is in "block all HTTP requests" mode. - * active: extension is enabled and rewrote URLs on this page. - * disabled: extension is disabled from the popup menu. + * Regex-Compile a pattern + * @param pattern The pattern to compile + * @constructor */ -var updateState = function() { - chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { - if (!tabs || tabs.length === 0) { - return; - } - - const activeCount = getActiveRulesetCount(); - - var iconState = "inactive"; - if (!isExtensionEnabled) { - iconState = "disabled"; - } else if (httpNowhereOn) { - iconState = "blocking"; - } else if (activeCount > 0) { - iconState = "active"; - } - chrome.browserAction.setIcon({ - path: { - "38": "icons/icon-" + iconState + "-38.png" - } - }); - chrome.browserAction.setTitle({ - title: "HTTPS Everywhere (" + iconState + ")" - }); - - chrome.browserAction.setBadgeBackgroundColor({color: "#00cc00"}); - - const showBadge = activeCount > 0 && isExtensionEnabled; - - chrome.browserAction.setBadgeText({text: showBadge ? "" + activeCount : ""}); - }); +function Exclusion(pattern) { + this.pattern_c = new RegExp(pattern); } /** - * Adds a new user rule - * @param params: params defining the rule - * @param cb: Callback to call after success/fail - * */ -var addNewRule = function(params, cb) { - if (all_rules.addUserRule(params)) { - // If we successfully added the user rule, save it in local - // storage so it's automatically applied when the extension is - // reloaded. - var oldUserRules = getStoredUserRules(); - // TODO: there's a race condition here, if this code is ever executed from multiple - // client windows in different event loops. - oldUserRules.push(params); - // TODO: can we exceed the max size for storage? - localStorage.setItem(USER_RULE_KEY, JSON.stringify(oldUserRules)); - cb(true); + * Generates a CookieRule + * @param host The host regex to compile + * @param cookiename The cookie name Regex to compile + * @constructor + */ +function CookieRule(host, cookiename) { + if (host === ".*" || host === ".+" || host === ".") { + // Some cookie rules trivially match any host. + this.host_c = trivial_cookie_host_c; } else { - cb(false); + this.host_c = new RegExp(host); } -}; -/** - * Removes a user rule - * @param ruleset: the ruleset to remove - * */ -var removeRule = function(ruleset) { - if (all_rules.removeUserRule(ruleset)) { - // If we successfully removed the user rule, remove it in local storage too - var oldUserRules = getStoredUserRules(); - for (let x = 0; x < oldUserRules.length; x++) { - if (oldUserRules[x].host == ruleset.name && - oldUserRules[x].redirectTo == ruleset.rules[0].to && - String(RegExp(oldUserRules[x].urlMatcher)) == String(ruleset.rules[0].from_c)) { - oldUserRules.splice(x, 1); - break; - } - } - localStorage.setItem(USER_RULE_KEY, JSON.stringify(oldUserRules)); + if (cookiename === ".*" || cookiename === ".+" || cookiename === ".") { + // About 50% of cookie rules trivially match any name. + this.name_c = trivial_cookie_name_c; + } else { + this.name_c = new RegExp(cookiename); } } /** - * Adds a listener for removed tabs - * */ -function AppliedRulesets() { - this.active_tab_rules = {}; - - var that = this; - chrome.tabs.onRemoved.addListener(function(tabId, info) { - that.removeTab(tabId); - }); + *A collection of rules + * @param set_name The name of this set + * @param default_state activity state + * @param note Note will be displayed in popup + * @constructor + */ +function RuleSet(set_name, default_state, note) { + this.name = set_name; + this.rules = []; + this.exclusions = null; + this.cookierules = null; + this.active = default_state; + this.default_state = default_state; + this.note = note; } -AppliedRulesets.prototype = { - addRulesetToTab: function(tabId, ruleset) { - if (tabId in this.active_tab_rules) { - this.active_tab_rules[tabId][ruleset.name] = ruleset; - } else { - this.active_tab_rules[tabId] = {}; - this.active_tab_rules[tabId][ruleset.name] = ruleset; +RuleSet.prototype = { + /** + * Check if a URI can be rewritten and rewrite it + * @param urispec The uri to rewrite + * @returns {*} null or the rewritten uri + */ + apply: function(urispec) { + var returl = null; + // If we're covered by an exclusion, go home + if (this.exclusions !== null) { + for (var i = 0; i < this.exclusions.length; ++i) { + if (this.exclusions[i].pattern_c.test(urispec)) { + log(DBUG, "excluded uri " + urispec); + return null; + } + } } - updateState(); - }, - - getRulesets: function(tabId) { - if (tabId in this.active_tab_rules) { - return this.active_tab_rules[tabId]; + // Okay, now find the first rule that triggers + for(var i = 0; i < this.rules.length; ++i) { + returl = urispec.replace(this.rules[i].from_c, + this.rules[i].to); + if (returl != urispec) { + return returl; + } } return null; }, - removeTab: function(tabId) { - delete this.active_tab_rules[tabId]; - } -}; + /** + * Deep equivalence comparison + * @param ruleset The ruleset to compare with + * @returns true or false, depending on whether it's deeply equivalent + */ + isEquivalentTo: function(ruleset) { + if(this.name != ruleset.name || + this.note != ruleset.note || + this.state != ruleset.state || + this.default_state != ruleset.default_state) { + return false; + } -// FIXME: change this name -var activeRulesets = new AppliedRulesets(); + try { + var this_exclusions_length = this.exclusions.length; + } catch(e) { + var this_exclusions_length = 0; + } -var urlBlacklist = new Set(); -var domainBlacklist = new Set(); + try { + var ruleset_exclusions_length = ruleset.exclusions.length; + } catch(e) { + var ruleset_exclusions_length = 0; + } -// redirect counter workaround -// TODO: Remove this code if they ever give us a real counter -var redirectCounter = {}; + try { + var this_rules_length = this.rules.length; + } catch(e) { + var this_rules_length = 0; + } -/** - * Called before a HTTP(s) request. Does the heavy lifting - * Cancels the request/redirects it to HTTPS. URL modification happens in here. - * @param details of the handler, see Chrome doc - * */ -function onBeforeRequest(details) { - // If HTTPSe has been disabled by the user, return immediately. - if (!isExtensionEnabled) { - return; - } + try { + var ruleset_rules_length = ruleset.rules.length; + } catch(e) { + var ruleset_rules_length = 0; + } - var uri = document.createElement('a'); - uri.href = details.url; - - // Should the request be canceled? - var shouldCancel = ( - httpNowhereOn && - uri.protocol === 'http:' && - !/\.onion$/.test(uri.hostname) && - !/^localhost$/.test(uri.hostname) && - !/^127(\.[0-9]{1,3}){3}$/.test(uri.hostname) && - !/^0\.0\.0\.0$/.test(uri.hostname) - ); - - // Normalise hosts such as "www.example.com." - var canonical_host = uri.hostname; - if (canonical_host.charAt(canonical_host.length - 1) == ".") { - while (canonical_host.charAt(canonical_host.length - 1) == ".") - canonical_host = canonical_host.slice(0,-1); - uri.hostname = canonical_host; + if(this_exclusions_length != ruleset_exclusions_length || + this_rules_length != ruleset_rules_length) { + return false; + } + if(this_exclusions_length > 0) { + for(let x = 0; x < this.exclusions.length; x++){ + if(this.exclusions[x].pattern_c != ruleset.exclusions[x].pattern_c) { + return false; + } + } + } + if(this_rules_length > 0) { + for(let x = 0; x < this.rules.length; x++){ + if(this.rules[x].to != ruleset.rules[x].to) { + return false; + } + } + } + return true; } - // If there is a username / password, put them aside during the ruleset - // analysis process - var using_credentials_in_url = false; - if (uri.password || uri.username) { - using_credentials_in_url = true; - var tmp_user = uri.username; - var tmp_pass = uri.password; - uri.username = null; - uri.password = null; - } +}; - var canonical_url = uri.href; - if (details.url != canonical_url && !using_credentials_in_url) { - log(INFO, "Original url " + details.url + - " changed before processing to " + canonical_url); - } - if (urlBlacklist.has(canonical_url)) { - return {cancel: shouldCancel}; - } +/** + * Initialize Rule Sets + * @param ruleActiveStates default state for rules + * @constructor + */ +function RuleSets(ruleActiveStates) { + // Load rules into structure + this.targets = {}; - if (details.type == "main_frame") { - activeRulesets.removeTab(details.tabId); - } + // A cache for potentiallyApplicableRulesets + this.ruleCache = new Map(); - var potentiallyApplicable = all_rules.potentiallyApplicableRulesets(uri.hostname); + // A cache for cookie hostnames. + this.cookieHostCache = new Map(); - if (redirectCounter[details.requestId] >= 8) { - log(NOTE, "Redirect counter hit for " + canonical_url); - urlBlacklist.add(canonical_url); - var hostname = uri.hostname; - domainBlacklist.add(hostname); - log(WARN, "Domain blacklisted " + hostname); - return {cancel: shouldCancel}; - } + // A hash of rule name -> active status (true/false). + this.ruleActiveStates = ruleActiveStates; +} - var newuristr = null; - for (let ruleset of potentiallyApplicable) { - activeRulesets.addRulesetToTab(details.tabId, ruleset); - if (ruleset.active && !newuristr) { - newuristr = ruleset.apply(canonical_url); +RuleSets.prototype = { + /** + * Iterate through data XML and load rulesets + */ + addFromXml: function(ruleXml) { + var sets = ruleXml.getElementsByTagName("ruleset"); + for (var i = 0; i < sets.length; ++i) { + try { + this.parseOneRuleset(sets[i]); + } catch (e) { + log(WARN, 'Error processing ruleset:' + e); + } } - } - - if (newuristr && using_credentials_in_url) { - // re-insert userpass info which was stripped temporarily - var uri_with_credentials = document.createElement('a'); - uri_with_credentials.href = newuristr; - uri_with_credentials.username = tmp_user; - uri_with_credentials.password = tmp_pass; - newuristr = uri_with_credentials.href; - } + }, - // In Switch Planner Mode, record any non-rewriteable - // HTTP URIs by parent hostname, along with the resource type. - if (switchPlannerEnabledFor[details.tabId] && uri.protocol !== "https:") { - writeToSwitchPlanner(details.type, - details.tabId, - canonical_host, - details.url, - newuristr); - } + /** + * Load a user rule + * @param params + * @returns {boolean} + */ + addUserRule : function(params) { + log(INFO, 'adding new user rule for ' + JSON.stringify(params)); + var new_rule_set = new RuleSet(params.host, true, "user rule"); + var new_rule = new Rule(params.urlMatcher, params.redirectTo); + new_rule_set.rules.push(new_rule); + if (!(params.host in this.targets)) { + this.targets[params.host] = []; + } + this.ruleCache.delete(params.host); + // TODO: maybe promote this rule? + this.targets[params.host].push(new_rule_set); + if (new_rule_set.name in this.ruleActiveStates) { + new_rule_set.active = (this.ruleActiveStates[new_rule_set.name] == "true"); + } + log(INFO, 'done adding rule'); + return true; + }, - if (httpNowhereOn) { - // If loading a main frame, try the HTTPS version as an alternative to - // failing. - if (shouldCancel) { - if (!newuristr) { - return {redirectUrl: canonical_url.replace(/^http:/, "https:")}; - } else { - return {redirectUrl: newuristr.replace(/^http:/, "https:")}; + /** + * Remove a user rule + * @param params + * @returns {boolean} + */ + removeUserRule: function(ruleset) { + log(INFO, 'removing user rule for ' + JSON.stringify(ruleset)); + this.ruleCache.delete(ruleset.name); + for(let x = 0; x < this.targets[ruleset.name].length; x++) { + if(this.targets[ruleset.name][x].isEquivalentTo(ruleset)) { + this.targets[ruleset.name].splice(x, 1); } } - if (newuristr && newuristr.substring(0, 5) === "http:") { - // Abort early if we're about to redirect to HTTP in HTTP Nowhere mode - return {cancel: true}; + if (this.targets[ruleset.name].length == 0) { + delete this.targets[ruleset.name]; } - } + log(INFO, 'done removing rule'); + return true; + }, - if (newuristr) { - return {redirectUrl: newuristr}; - } else { - return {cancel: shouldCancel}; - } -} + /** + * Does the loading of a ruleset. + * @param ruletag The whole tag to parse + */ + parseOneRuleset: function(ruletag) { + var default_state = true; + var note = ""; + var default_off = ruletag.getAttribute("default_off"); + if (default_off) { + default_state = false; + note += default_off + "\n"; + } + // If a ruleset declares a platform, and we don't match it, treat it as + // off-by-default. In practice, this excludes "mixedcontent" & "cacert" rules. + var platform = ruletag.getAttribute("platform"); + if (platform) { + default_state = false; + if (platform == "mixedcontent" && enableMixedRulesets) { + default_state = true; + } + note += "Platform(s): " + platform + "\n"; + } -// Map of which values for the `type' enum denote active vs passive content. -// https://developer.chrome.com/extensions/webRequest.html#event-onBeforeRequest -var activeTypes = { stylesheet: 1, script: 1, object: 1, other: 1}; + var rule_set = new RuleSet(ruletag.getAttribute("name"), + default_state, + note.trim()); -// We consider sub_frame to be passive even though it can contain JS or flash. -// This is because code running in the sub_frame cannot access the main frame's -// content, by same-origin policy. This is true even if the sub_frame is on the -// same domain but different protocol - i.e. HTTP while the parent is HTTPS - -// because same-origin policy includes the protocol. This also mimics Chrome's -// UI treatment of insecure subframes. -var passiveTypes = { main_frame: 1, sub_frame: 1, image: 1, xmlhttprequest: 1}; + // Read user prefs + if (rule_set.name in this.ruleActiveStates) { + rule_set.active = (this.ruleActiveStates[rule_set.name] == "true"); + } -/** - * Record a non-HTTPS URL loaded by a given hostname in the Switch Planner, for - * use in determining which resources need to be ported to HTTPS. - * (Reminder: Switch planner is the pro-tool enabled by switching into debug-mode) - * - * @param type: type of the resource (see activeTypes and passiveTypes arrays) - * @param tab_id: The id of the tab - * @param resource_host: The host of the original url - * @param resource_url: the original url - * @param rewritten_url: The url rewritten to - * */ -function writeToSwitchPlanner(type, tab_id, resource_host, resource_url, rewritten_url) { - var rw = "rw"; - if (rewritten_url == null) - rw = "nrw"; - - var active_content = 0; - if (activeTypes[type]) { - active_content = 1; - } else if (passiveTypes[type]) { - active_content = 0; - } else { - log(WARN, "Unknown type from onBeforeRequest details: `" + type + "', assuming active"); - active_content = 1; - } + var rules = ruletag.getElementsByTagName("rule"); + for(var j = 0; j < rules.length; j++) { + rule_set.rules.push(new Rule(rules[j].getAttribute("from"), + rules[j].getAttribute("to"))); + } - if (!switchPlannerInfo[tab_id]) { - switchPlannerInfo[tab_id] = {}; - switchPlannerInfo[tab_id]["rw"] = {}; - switchPlannerInfo[tab_id]["nrw"] = {}; - } - if (!switchPlannerInfo[tab_id][rw][resource_host]) - switchPlannerInfo[tab_id][rw][resource_host] = {}; - if (!switchPlannerInfo[tab_id][rw][resource_host][active_content]) - switchPlannerInfo[tab_id][rw][resource_host][active_content] = {}; + var exclusions = ruletag.getElementsByTagName("exclusion"); + if (exclusions.length > 0) { + rule_set.exclusions = []; + for (var j = 0; j < exclusions.length; j++) { + rule_set.exclusions.push( + new Exclusion(exclusions[j].getAttribute("pattern"))); + } + } - switchPlannerInfo[tab_id][rw][resource_host][active_content][resource_url] = 1; -} + var cookierules = ruletag.getElementsByTagName("securecookie"); + if (cookierules.length > 0) { + rule_set.cookierules = []; + for(var j = 0; j < cookierules.length; j++) { + rule_set.cookierules.push( + new CookieRule(cookierules[j].getAttribute("host"), + cookierules[j].getAttribute("name"))); + } + } -/** - * Return the number of properties in an object. For associative maps, this is - * their size. - * @param obj: object to calc the size for - * */ -function objSize(obj) { - if (typeof obj == 'undefined') return 0; - var size = 0, key; - for (key in obj) { - if (obj.hasOwnProperty(key)) size++; - } - return size; -} + var targets = ruletag.getElementsByTagName("target"); + for(var j = 0; j < targets.length; j++) { + var host = targets[j].getAttribute("host"); + if (!(host in this.targets)) { + this.targets[host] = []; + } + this.targets[host].push(rule_set); + } + }, -/** - * Make an array of asset hosts by score so we can sort them, - * presenting the most important ones first. - * */ -function sortSwitchPlanner(tab_id, rewritten) { - var asset_host_list = []; - if (typeof switchPlannerInfo[tab_id] === 'undefined' || - typeof switchPlannerInfo[tab_id][rewritten] === 'undefined') { - return []; - } - var tabInfo = switchPlannerInfo[tab_id][rewritten]; - for (var asset_host in tabInfo) { - var ah = tabInfo[asset_host]; - var activeCount = objSize(ah[1]); - var passiveCount = objSize(ah[0]); - var score = activeCount * 100 + passiveCount; - asset_host_list.push([score, activeCount, passiveCount, asset_host]); - } - asset_host_list.sort(function(a,b){return a[0]-b[0];}); - return asset_host_list; -} + /** + * Return a list of rulesets that apply to this host + * @param host The host to check + * @returns {*} (empty) list + */ + potentiallyApplicableRulesets: function(host) { + // Have we cached this result? If so, return it! + var cached_item = this.ruleCache.get(host); + if (cached_item !== undefined) { + log(DBUG, "Ruleset cache hit for " + host + " items:" + cached_item.length); + return cached_item; + } + log(DBUG, "Ruleset cache miss for " + host); -/** -* Format the switch planner output for presentation to a user. -* */ -function switchPlannerSmallHtmlSection(tab_id, rewritten) { - var asset_host_list = sortSwitchPlanner(tab_id, rewritten); - if (asset_host_list.length == 0) { - return "none"; - } + var tmp; + var results = []; + if (this.targets[host]) { + // Copy the host targets so we don't modify them. + results = results.concat(this.targets[host]); + } - var output = ""; - for (var i = asset_host_list.length - 1; i >= 0; i--) { - var host = asset_host_list[i][3]; - var activeCount = asset_host_list[i][1]; - var passiveCount = asset_host_list[i][2]; + // Ensure host is well-formed (RFC 1035) + if (host.indexOf("..") != -1 || host.length > 255) { + log(WARN,"Malformed host passed to potentiallyApplicableRulesets: " + host); + return null; + } - output += "" + host + ": "; - if (activeCount > 0) { - output += activeCount + " active"; - if (passiveCount > 0) - output += ", "; + // Replace each portion of the domain with a * in turn + var segmented = host.split("."); + for (var i = 0; i < segmented.length; ++i) { + tmp = segmented[i]; + segmented[i] = "*"; + results = results.concat(this.targets[segmented.join(".")]); + segmented[i] = tmp; } - if (passiveCount > 0) { - output += passiveCount + " passive"; + // now eat away from the left, with *, so that for x.y.z.google.com we + // check *.z.google.com and *.google.com (we did *.y.z.google.com above) + for (var i = 2; i <= segmented.length - 2; ++i) { + var t = "*." + segmented.slice(i,segmented.length).join("."); + results = results.concat(this.targets[t]); } - output += "
"; - } - return output; -} -/** - * Create switch planner sections - * */ -function switchPlannerRenderSections(tab_id, f) { - return "Unrewritten HTTP resources loaded from this tab (enable HTTPS on " + - "these domains and add them to HTTPS Everywhere):
" + - f(tab_id, "nrw") + - "
Resources rewritten successfully from this tab (update these " + - "in your source code):
" + - f(tab_id, "rw"); -} - -/** - * Generate the small switch planner html content - * */ -function switchPlannerSmallHtml(tab_id) { - return switchPlannerRenderSections(tab_id, switchPlannerSmallHtmlSection); -} + // Clean the results list, which may contain duplicates or undefined entries + var resultSet = new Set(results); + resultSet.delete(undefined); -/** - * Generate a HTML link from urls in map - * map: the map containing the urls - * */ -function linksFromKeys(map) { - if (typeof map == 'undefined') return ""; - var output = ""; - for (var key in map) { - if (map.hasOwnProperty(key)) { - output += "" + key + "
"; + log(DBUG,"Applicable rules for " + host + ":"); + if (resultSet.size == 0) { + log(DBUG, " None"); + } else { + for (let target of resultSet.values()) { + log(DBUG, " " + target.name); + } } - } - return output; -} -/** - * Generate the detailed html fot the switch planner - * */ -function switchPlannerDetailsHtml(tab_id) { - return switchPlannerRenderSections(tab_id, switchPlannerDetailsHtmlSection); -} + // Insert results into the ruleset cache + this.ruleCache.set(host, resultSet); -/** - * Generate the detailed html fot the switch planner, by section - * */ -function switchPlannerDetailsHtmlSection(tab_id, rewritten) { - var asset_host_list = sortSwitchPlanner(tab_id, rewritten); - var output = ""; - - for (var i = asset_host_list.length - 1; i >= 0; i--) { - var host = asset_host_list[i][3]; - var activeCount = asset_host_list[i][1]; - var passiveCount = asset_host_list[i][2]; - - output += "" + host + ": "; - if (activeCount > 0) { - output += activeCount + " active
"; - output += linksFromKeys(switchPlannerInfo[tab_id][rewritten][host][1]); - } - if (passiveCount > 0) { - output += "
" + passiveCount + " passive
"; - output += linksFromKeys(switchPlannerInfo[tab_id][rewritten][host][0]); - } - output += "
"; - } - return output; -} + // Cap the size of the cache. (Limit chosen somewhat arbitrarily) + if (this.ruleCache.size > 1000) { + // Map.prototype.keys() returns keys in insertion order, so this is a FIFO. + this.ruleCache.delete(this.ruleCache.keys().next().value); + } -/** - * monitor cookie changes. Automatically convert them to secure cookies - * @param changeInfo Cookie changed info, see Chrome doc - * */ -function onCookieChanged(changeInfo) { - if (!changeInfo.removed && !changeInfo.cookie.secure && isExtensionEnabled) { - if (all_rules.shouldSecureCookie(changeInfo.cookie)) { - var cookie = {name:changeInfo.cookie.name, - value:changeInfo.cookie.value, - path:changeInfo.cookie.path, - httpOnly:changeInfo.cookie.httpOnly, - expirationDate:changeInfo.cookie.expirationDate, - storeId:changeInfo.cookie.storeId, - secure: true}; - - // Host-only cookies don't set the domain field. - if (!changeInfo.cookie.hostOnly) { - cookie.domain = changeInfo.cookie.domain; - } + return resultSet; + }, - // The cookie API is magical -- we must recreate the URL from the domain and path. - if (changeInfo.cookie.domain[0] == ".") { - cookie.url = "https://www" + changeInfo.cookie.domain + cookie.path; - } else { - cookie.url = "https://" + changeInfo.cookie.domain + cookie.path; - } - // We get repeated events for some cookies because sites change their - // value repeatedly and remove the "secure" flag. - log(DBUG, - "Securing cookie " + cookie.name + " for " + changeInfo.cookie.domain + ", was secure=" + changeInfo.cookie.secure); - chrome.cookies.set(cookie); + /** + * Check to see if the Cookie object c meets any of our cookierule criteria for being marked as secure. + * @param cookie The cookie to test + * @returns {*} ruleset or null + */ + shouldSecureCookie: function(cookie) { + var hostname = cookie.domain; + // cookie domain scopes can start with . + while (hostname.charAt(0) == ".") { + hostname = hostname.slice(1); } - } -} -/** - * handling redirects, breaking loops - * @param details details for the redirect (see chrome doc) - * */ -function onBeforeRedirect(details) { - // Catch redirect loops (ignoring about:blank, etc. caused by other extensions) - var prefix = details.redirectUrl.substring(0, 5); - if (prefix === "http:" || prefix === "https") { - if (details.requestId in redirectCounter) { - redirectCounter[details.requestId] += 1; - log(DBUG, "Got redirect id "+details.requestId+ - ": "+redirectCounter[details.requestId]); - } else { - redirectCounter[details.requestId] = 1; - } + if (!this.safeToSecureCookie(hostname)) { + return null; } -} - -// Registers the handler for requests -// See: https://github.com/EFForg/https-everywhere/issues/10039 -wr.onBeforeRequest.addListener(onBeforeRequest, {urls: [""]}, ["blocking"]); + var potentiallyApplicable = this.potentiallyApplicableRulesets(hostname); + for (let ruleset of potentiallyApplicable) { + if (ruleset.cookierules !== null && ruleset.active) { + for (var j = 0; j < ruleset.cookierules.length; j++) { + var cr = ruleset.cookierules[j]; + if (cr.host_c.test(cookie.domain) && cr.name_c.test(cookie.name)) { + return ruleset; + } + } + } + } + return null; + }, -// Try to catch redirect loops on URLs we've redirected to HTTPS. -wr.onBeforeRedirect.addListener(onBeforeRedirect, {urls: ["https://*/*"]}); + /** + * Check if it is secure to secure the cookie (=patch the secure flag in). + * @param domain The domain of the cookie + * @returns {*} true or false + */ + safeToSecureCookie: function(domain) { + // Check if the domain might be being served over HTTP. If so, it isn't + // safe to secure a cookie! We can't always know this for sure because + // observing cookie-changed doesn't give us enough context to know the + // full origin URI. + + // First, if there are any redirect loops on this domain, don't secure + // cookies. XXX This is not a very satisfactory heuristic. Sometimes we + // would want to secure the cookie anyway, because the URLs that loop are + // not authenticated or not important. Also by the time the loop has been + // observed and the domain blacklisted, a cookie might already have been + // flagged as secure. + + if (domainBlacklist.has(domain)) { + log(INFO, "cookies for " + domain + "blacklisted"); + return false; + } + var cached_item = this.cookieHostCache.get(domain); + if (cached_item !== undefined) { + log(DBUG, "Cookie host cache hit for " + domain); + return cached_item; + } + log(DBUG, "Cookie host cache miss for " + domain); + // If we passed that test, make up a random URL on the domain, and see if + // we would HTTPSify that. -// Listen for cookies set/updated and secure them if applicable. This function is async/nonblocking. -chrome.cookies.onChanged.addListener(onCookieChanged); + var nonce_path = "/" + Math.random().toString(); + var test_uri = "http://" + domain + nonce_path + nonce_path; -/** - * disable switch Planner - * @param tabId the Tab to disable for - */ -function disableSwitchPlannerFor(tabId) { - delete switchPlannerEnabledFor[tabId]; - // Clear stored URL info. - delete switchPlannerInfo[tabId]; -} + // Cap the size of the cookie cache (limit chosen somewhat arbitrarily) + if (this.cookieHostCache.size > 250) { + // Map.prototype.keys() returns keys in insertion order, so this is a FIFO. + this.cookieHostCache.delete(this.cookieHostCache.keys().next().value); + } -/** - * Enable switch planner for specific tab - * @param tabId the tab to enable it for - */ -function enableSwitchPlannerFor(tabId) { - switchPlannerEnabledFor[tabId] = true; -} + log(INFO, "Testing securecookie applicability with " + test_uri); + var potentiallyApplicable = this.potentiallyApplicableRulesets(domain); + for (let ruleset of potentiallyApplicable) { + if (!ruleset.active) { + continue; + } + if (ruleset.apply(test_uri)) { + log(INFO, "Cookie domain could be secured."); + this.cookieHostCache.set(domain, true); + return true; + } + } + log(INFO, "Cookie domain could NOT be secured."); + this.cookieHostCache.set(domain, false); + return false; + }, -// Listen for connection from the DevTools panel so we can set up communication. -chrome.runtime.onConnect.addListener(function (port) { - if (port.name == "devtools-page") { - chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){ - var tabId = message.tabId; - - var disableOnCloseCallback = function(port) { - log(DBUG, "Devtools window for tab " + tabId + " closed, clearing data."); - disableSwitchPlannerFor(tabId); - }; - - if (message.type === "enable") { - enableSwitchPlannerFor(tabId); - port.onDisconnect.addListener(disableOnCloseCallback); - } else if (message.type === "disable") { - disableSwitchPlannerFor(tabId); - } else if (message.type === "getSmallHtml") { - sendResponse({html: switchPlannerSmallHtml(tabId)}); + /** + * Rewrite an URI + * @param urispec The uri to rewrite + * @param host The host of this uri + * @returns {*} the new uri or null + */ + rewriteURI: function(urispec, host) { + var newuri = null; + var potentiallyApplicable = this.potentiallyApplicableRulesets(host); + for (let ruleset of potentiallyApplicable) { + if (ruleset.active && (newuri = ruleset.apply(urispec))) { + return newuri; } - }); + } + return null; } -}); +}; + +// Export for HTTPS Rewriter if applicable. +if (typeof exports != 'undefined') { + exports.RuleSets = RuleSets; +} From a9330927856c5fe4c952ecfdb0f9d9c311f88a85 Mon Sep 17 00:00:00 2001 From: koops76 Date: Tue, 27 Jun 2017 20:38:03 +0300 Subject: [PATCH 04/35] Update background.js --- chromium/background.js | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/chromium/background.js b/chromium/background.js index f4805abca94d..5078b4606e78 100644 --- a/chromium/background.js +++ b/chromium/background.js @@ -98,6 +98,25 @@ var loadStoredUserRules = function() { loadStoredUserRules(); +function getActiveRulesetCount() { + const applied = activeRulesets.getRulesets(tabs[0].id); + + if (!applied) + { + return 0; + } + + let activeCount = 0; + + for (const key in applied) { + if (applied[key].active) { + activeCount++; + } + } + + return activeCount; +} + /** * Set the icon color correctly * inactive: extension is enabled, but no rules were triggered on this page. @@ -110,13 +129,15 @@ var updateState = function() { if (!tabs || tabs.length === 0) { return; } - var applied = activeRulesets.getRulesets(tabs[0].id) + + const activeCount = getActiveRulesetCount(); + var iconState = "inactive"; if (!isExtensionEnabled) { iconState = "disabled"; } else if (httpNowhereOn) { iconState = "blocking"; - } else if (applied) { + } else if (activeCount > 0) { iconState = "active"; } chrome.browserAction.setIcon({ @@ -128,13 +149,11 @@ var updateState = function() { title: "HTTPS Everywhere (" + iconState + ")" }); - const appliedCount = applied ? Object.keys(applied).length : 0; - chrome.browserAction.setBadgeBackgroundColor({color: "#00cc00"}); - const showBadge = appliedCount > 0 && isExtensionEnabled; + const showBadge = activeCount > 0 && isExtensionEnabled; - chrome.browserAction.setBadgeText({text: showBadge ? "" + appliedCount : ""}); + chrome.browserAction.setBadgeText({text: showBadge ? "" + activeCount : ""}); }); } From 418bc16215f1dc317b883fd2949fac7e9464ba83 Mon Sep 17 00:00:00 2001 From: koops76 Date: Tue, 27 Jun 2017 20:44:33 +0300 Subject: [PATCH 05/35] Update background.js --- chromium/background.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chromium/background.js b/chromium/background.js index 5078b4606e78..61711259915e 100644 --- a/chromium/background.js +++ b/chromium/background.js @@ -98,8 +98,8 @@ var loadStoredUserRules = function() { loadStoredUserRules(); -function getActiveRulesetCount() { - const applied = activeRulesets.getRulesets(tabs[0].id); +function getActiveRulesetCount(id) { + const applied = activeRulesets.getRulesets(id); if (!applied) { @@ -130,7 +130,7 @@ var updateState = function() { return; } - const activeCount = getActiveRulesetCount(); + const activeCount = getActiveRulesetCount(tabs[0].id); var iconState = "inactive"; if (!isExtensionEnabled) { From 8fcbf4df33e7b24448275f75b0cbc9ea4f5c6540 Mon Sep 17 00:00:00 2001 From: koops76 Date: Thu, 6 Jul 2017 23:46:15 +0300 Subject: [PATCH 06/35] Update background.js --- chromium/background.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chromium/background.js b/chromium/background.js index 3ea0e2180a75..4cd62c7b0f86 100644 --- a/chromium/background.js +++ b/chromium/background.js @@ -152,7 +152,7 @@ var updateState = function() { chrome.browserAction.setBadgeBackgroundColor({color: "#00cc00"}); const showBadge = activeCount > 0 && isExtensionEnabled; - + chrome.browserAction.setBadgeText({text: showBadge ? "" + activeCount : ""}); }); } @@ -219,8 +219,6 @@ AppliedRulesets.prototype = { this.active_tab_rules[tabId] = {}; this.active_tab_rules[tabId][ruleset.name] = ruleset; } - - updateState(); }, getRulesets: function(tabId) { @@ -321,6 +319,8 @@ function onBeforeRequest(details) { } } + updateState(); + if (newuristr && using_credentials_in_url) { // re-insert userpass info which was stripped temporarily var uri_with_credentials = document.createElement('a'); From f15f47f7a415506703cd4d29e153f417d4608171 Mon Sep 17 00:00:00 2001 From: koops76 Date: Fri, 14 Jul 2017 20:57:24 +0300 Subject: [PATCH 07/35] Fix translations --- translations | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/translations b/translations index 303723c38fa6..020039651cd1 160000 --- a/translations +++ b/translations @@ -1 +1 @@ -Subproject commit 303723c38fa6d607872c94ccd24604d0a5c190e4 +Subproject commit 020039651cd14b2ac1066a56dd4843816788a511 From 58eac657a371e528c0016663cc147dbbb96845a4 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 04:36:55 +0300 Subject: [PATCH 08/35] 1 --- chromium/options.html | 24 ++++++++++----------- chromium/options.js | 45 ++++++++++++++++++++------------------- chromium/popup.html | 46 ++++++++++++++++++++-------------------- chromium/popup.js | 2 ++ chromium/send-message.js | 11 ++++------ chromium/translation.js | 17 ++++++--------- 6 files changed, 70 insertions(+), 75 deletions(-) diff --git a/chromium/options.html b/chromium/options.html index 3a7ae116aa33..9a25f15adb93 100644 --- a/chromium/options.html +++ b/chromium/options.html @@ -1,22 +1,20 @@ - + - - - - + -
+
-
-
-
- -
- -
+
+
+ +
+ + + + diff --git a/chromium/options.js b/chromium/options.js index d979c504e0f2..b7401809aa7a 100644 --- a/chromium/options.js +++ b/chromium/options.js @@ -1,28 +1,29 @@ -document.addEventListener("DOMContentLoaded", () => { +'use strict' - let json_data; - let import_button = document.querySelector("#import"); +document.addEventListener('DOMContentLoaded', () => { + let jsonData + const importButton = document.getElementById('import') - function import_json(e) { - e.preventDefault(); + function importJson (e) { + const file = event.target.files[0] + const reader = new FileReader() + reader.addEventListener('error', evt => { + reject(new Error('FileReader error: ' + evt.target.error.name)) + } - let settings = JSON.parse(json_data); - sendMessage("import_settings", settings, resp => { - document.querySelector("#import-confirmed").style.display = "block"; - document.querySelector("form").style.display = "none"; - }); - } + reader.addEventListener('load', evt => { + resolve(evt.target.result) + }) - document.querySelector("#import-settings").addEventListener("change", event => { - const file = event.target.files[0]; - const reader = new FileReader(); - reader.onload = event => { - json_data = event.target.result; - import_button.disabled = false; - }; + reader.readAsText(file) + + const settings = JSON.parse(jsonData) + sendMessage('import_settings', settings, function () {}) + } - reader.readAsText(file); - }); + document.getElementById('import-settings').addEventListener('change', event => { + importButton.disabled = (event.target.files.length === 0) + }) - document.querySelector("form").addEventListener("submit", import_json); -}); + importButton.addEventListener('click', importJson) +}) diff --git a/chromium/popup.html b/chromium/popup.html index b6c92d4cf855..0163b65a7271 100644 --- a/chromium/popup.html +++ b/chromium/popup.html @@ -1,6 +1,6 @@ - + @@ -16,58 +16,58 @@
-

+

- +
- +
- +
-

-

+

+

-

-

+

+

-

-

- -

(Version: )

+

+

+ +

(Version: )

diff --git a/chromium/popup.js b/chromium/popup.js index 1aeea420ccc2..6aab8ce88cad 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -191,6 +191,8 @@ document.addEventListener("DOMContentLoaded", function () { httpNowhereCheckbox.setAttribute('checked', ''); } }); + + e("add-rule-link").addEventListener("click", addManualRule); }); diff --git a/chromium/send-message.js b/chromium/send-message.js index 2ed895523d79..54516ce0a722 100644 --- a/chromium/send-message.js +++ b/chromium/send-message.js @@ -1,8 +1,5 @@ -function sendMessage(type, object, callback) { - var packet = {}; - packet.type = type; - if(object){ - packet.object = object; - } - chrome.runtime.sendMessage(packet, callback); +'use strict' + +function sendMessage (type, object, callback) { + chrome.runtime.sendMessage({ type, object }, callback) } diff --git a/chromium/translation.js b/chromium/translation.js index 61ae5ff14808..c0f955684b4f 100644 --- a/chromium/translation.js +++ b/chromium/translation.js @@ -1,11 +1,8 @@ -document.addEventListener("DOMContentLoaded", function () { - // auto-translate all elements with i18n attributes - var elem = document.querySelectorAll("[i18n]"); - for (let el of elem) { - el.innerHTML = chrome.i18n.getMessage(el.getAttribute("i18n")); - } +'use strict' - // other translations - e("aboutTitle").setAttribute("title", chrome.i18n.getMessage("about_title")); - e("add-rule-link").addEventListener("click", addManualRule); -}); +document.addEventListener('DOMContentLoaded', () => { + // auto-translate all elements with data-i18n attributes + for (const el of document.querySelectorAll('[data-i18n]')) { + el.innerText = chrome.i18n.getMessage(el.getAttribute('data-i18n')) + } +}) From 27dfd25d0700e2c0042fb0581955118e34e2b78e Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 07:33:19 +0300 Subject: [PATCH 09/35] 1 --- chromium/options.html | 5 +++++ chromium/options.js | 36 +++++++++++++++++++++--------------- 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/chromium/options.html b/chromium/options.html index 9a25f15adb93..9ee8a57aeb30 100644 --- a/chromium/options.html +++ b/chromium/options.html @@ -5,6 +5,11 @@ +
+ + +
+
diff --git a/chromium/options.js b/chromium/options.js index b7401809aa7a..ec60562e8048 100644 --- a/chromium/options.js +++ b/chromium/options.js @@ -1,29 +1,35 @@ 'use strict' -document.addEventListener('DOMContentLoaded', () => { - let jsonData - const importButton = document.getElementById('import') - - function importJson (e) { - const file = event.target.files[0] +function readFile (file) { + return new Promise((resolve, reject) => { const reader = new FileReader() - reader.addEventListener('error', evt => { - reject(new Error('FileReader error: ' + evt.target.error.name)) + + reader.addEventListener('error', event => { + reject(new Error('FileReader error: ' + event.target.error.name)) } - reader.addEventListener('load', evt => { - resolve(evt.target.result) + reader.addEventListener('load', event => { + resolve(event.target.result) }) reader.readAsText(file) - - const settings = JSON.parse(jsonData) + }) +} + +document.addEventListener('DOMContentLoaded', () => { + const importButton = document.getElementById('import') + + importButton.addEventListener('click', async event => { + const file = event.target.files[0] + + const fileContents = await readFile(file) + + const settings = JSON.parse(fileContents) + sendMessage('import_settings', settings, function () {}) - } + }) document.getElementById('import-settings').addEventListener('change', event => { importButton.disabled = (event.target.files.length === 0) }) - - importButton.addEventListener('click', importJson) }) From 39591d310125c13bb9bbaa4a955cfddb7183b6cf Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 09:37:33 +0300 Subject: [PATCH 10/35] 1 --- chromium/options.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chromium/options.js b/chromium/options.js index ec60562e8048..49bc352358fa 100644 --- a/chromium/options.js +++ b/chromium/options.js @@ -6,7 +6,7 @@ function readFile (file) { reader.addEventListener('error', event => { reject(new Error('FileReader error: ' + event.target.error.name)) - } + }) reader.addEventListener('load', event => { resolve(event.target.result) From 1ecee5dac03f6c444b0476a5dd6edbe4ee7e21aa Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 10:16:59 +0300 Subject: [PATCH 11/35] 1 --- chromium/options.css | 8 ++++---- chromium/options.html | 8 +++++++- chromium/options.js | 20 ++++++++++++++------ chromium/send-message.js | 6 ++++-- 4 files changed, 29 insertions(+), 13 deletions(-) diff --git a/chromium/options.css b/chromium/options.css index 1e9f0418e2b9..0252f2bce0e4 100644 --- a/chromium/options.css +++ b/chromium/options.css @@ -1,17 +1,17 @@ -.section-header{ +.section-header { margin-bottom: 10px; } -.section-header-span{ +.section-header-span { border-bottom: 1px solid #ccc; font-size: 15px; } -#import{ +#import { margin-bottom: 10px; float: right; } -#import-confirmed{ +#import-confirmed { display: none; } diff --git a/chromium/options.html b/chromium/options.html index 9ee8a57aeb30..19c612c8f4be 100644 --- a/chromium/options.html +++ b/chromium/options.html @@ -7,15 +7,21 @@
+ +
-
+
+ +
+
+ diff --git a/chromium/options.js b/chromium/options.js index 49bc352358fa..f09431315beb 100644 --- a/chromium/options.js +++ b/chromium/options.js @@ -17,16 +17,24 @@ function readFile (file) { } document.addEventListener('DOMContentLoaded', () => { - const importButton = document.getElementById('import') + const showAppliedCount = document.getElementById('show-applied-count') - importButton.addEventListener('click', async event => { - const file = event.target.files[0] + sendMessage('get_show_applied_count').then(value => { + showAppliedCount.checked = on + showAppliedCount.addEventListener('change', event => { + sendMessage('set_show_applied_count', showAppliedCount.checked) + }) + }) - const fileContents = await readFile(file) + const importButton = document.getElementById('import') - const settings = JSON.parse(fileContents) + importButton.addEventListener('click', event => { + const file = event.target.files[0] - sendMessage('import_settings', settings, function () {}) + readFile(file).then(data => { + const settings = JSON.parse(fileContents) + sendMessage('import_settings', settings) + }) }) document.getElementById('import-settings').addEventListener('change', event => { diff --git a/chromium/send-message.js b/chromium/send-message.js index 54516ce0a722..859afefed337 100644 --- a/chromium/send-message.js +++ b/chromium/send-message.js @@ -1,5 +1,7 @@ 'use strict' -function sendMessage (type, object, callback) { - chrome.runtime.sendMessage({ type, object }, callback) +function sendMessage (type, object) { + return new Promise(resolve => { + chrome.runtime.sendMessage({ type, object }, resolve) + }) } From 6bc6c1c0de38eb9cb5e92115a7b9f3adadcdfd9d Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 10:33:04 +0300 Subject: [PATCH 12/35] 1 --- chromium/options.js | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/chromium/options.js b/chromium/options.js index f09431315beb..8d081a48a50c 100644 --- a/chromium/options.js +++ b/chromium/options.js @@ -17,12 +17,14 @@ function readFile (file) { } document.addEventListener('DOMContentLoaded', () => { - const showAppliedCount = document.getElementById('show-applied-count') - - sendMessage('get_show_applied_count').then(value => { - showAppliedCount.checked = on - showAppliedCount.addEventListener('change', event => { - sendMessage('set_show_applied_count', showAppliedCount.checked) + const showAppliedCountCheckbox = document.getElementById('show-applied-count') + + sendMessage('get_option', { showAppliedCount: true }).then(value => { + showAppliedCountCheckbox.checked = on + showAppliedCountCheckbox.addEventListener('change', event => { + sendMessage('set_option', { showAppliedCount: showAppliedCountCheckbox.checked }).then(() => { + sendMessage('update_state') + }) }) }) From 3ed9b01bfa6c29d4e61c38f0d51182b6047f636c Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 10:46:18 +0300 Subject: [PATCH 13/35] 1 --- chromium/background.js | 35 +++++++++++++++++++++-------------- chromium/options.js | 4 +--- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/chromium/background.js b/chromium/background.js index cd2928a89099..14c47b829f61 100644 --- a/chromium/background.js +++ b/chromium/background.js @@ -52,23 +52,30 @@ var switchPlannerInfo = {}; // Is HTTPSe enabled, or has it been manually disabled by the user? var isExtensionEnabled = true; -// Load prefs about whether http nowhere is on. Structure is: -// { httpNowhere: true/false } -var httpNowhereOn = false; -storage.get({httpNowhere: false}, function(item) { - httpNowhereOn = item.httpNowhere; +// Load preferences. Structure is: +// { httpNowhere: Boolean, showAppliedCount: Boolean } + +let httpNowhere = false; +let showAppliedCount = true; + +storage.get({ httpNowhere: false, showAppliedCount: true }, item => { + { httpNowhere, showAppliedCount } = item; updateState(); }); -chrome.storage.onChanged.addListener(function(changes, areaName) { + +chrome.storage.onChanged.addListener((changes, areaName) => { if (areaName === 'sync' || areaName === 'local') { - for (var key in changes) { - if (key === 'httpNowhere') { - httpNowhereOn = changes[key].newValue; - updateState(); - } + if ('httpNowhere' in changes) { + httpNowhere = changes.httpNowhere.newValue; + updateState(); + } + if ('showAppliedCount' in changes) { + showAppliedCount = changes.showAppliedCount.newValue; + updateState(); } } }); + if (chrome.tabs) { chrome.tabs.onActivated.addListener(function() { updateState(); @@ -150,7 +157,7 @@ var updateState = function() { if (!isExtensionEnabled) { iconState = "disabled"; - } else if (httpNowhereOn) { + } else if (httpNowhere) { iconState = "blocking"; } else if (activeCount > 0) { iconState = "active"; @@ -272,7 +279,7 @@ function onBeforeRequest(details) { // Should the request be canceled? var shouldCancel = ( - httpNowhereOn && + httpNowhere && uri.protocol === 'http:' && !/\.onion$/.test(uri.hostname) && !/^localhost$/.test(uri.hostname) && @@ -352,7 +359,7 @@ function onBeforeRequest(details) { newuristr); } - if (httpNowhereOn) { + if (httpNowhere) { // If loading a main frame, try the HTTPS version as an alternative to // failing. if (shouldCancel) { diff --git a/chromium/options.js b/chromium/options.js index 8d081a48a50c..982e3fdf98f2 100644 --- a/chromium/options.js +++ b/chromium/options.js @@ -22,9 +22,7 @@ document.addEventListener('DOMContentLoaded', () => { sendMessage('get_option', { showAppliedCount: true }).then(value => { showAppliedCountCheckbox.checked = on showAppliedCountCheckbox.addEventListener('change', event => { - sendMessage('set_option', { showAppliedCount: showAppliedCountCheckbox.checked }).then(() => { - sendMessage('update_state') - }) + sendMessage('set_option', { showAppliedCount: showAppliedCountCheckbox.checked }) }) }) From 71ad37b2d362c0d6b4b5f223c1f816e92b980ad3 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 10:49:51 +0300 Subject: [PATCH 14/35] 1 --- chromium/options.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chromium/options.html b/chromium/options.html index 19c612c8f4be..d8be4a9845e9 100644 --- a/chromium/options.html +++ b/chromium/options.html @@ -6,7 +6,7 @@
- + From a97b1d88f86cdbcda687e9ae284e0a945fd78ae1 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 11:07:46 +0300 Subject: [PATCH 15/35] 1 --- chromium/background.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chromium/background.js b/chromium/background.js index 14c47b829f61..ab2c2588a5bc 100644 --- a/chromium/background.js +++ b/chromium/background.js @@ -173,7 +173,7 @@ var updateState = function() { chrome.browserAction.setBadgeBackgroundColor({color: "#00cc00"}); - const showBadge = activeCount > 0 && isExtensionEnabled; + const showBadge = activeCount > 0 && isExtensionEnabled && showAppliedCount; chrome.browserAction.setBadgeText({text: showBadge ? "" + activeCount : ""}); }); From 828a2da9ed4b20e614617ec8c8841055d3e67bfc Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 11:28:17 +0300 Subject: [PATCH 16/35] 1 --- chromium/background.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/chromium/background.js b/chromium/background.js index ab2c2588a5bc..b0b0d72736de 100644 --- a/chromium/background.js +++ b/chromium/background.js @@ -59,7 +59,8 @@ let httpNowhere = false; let showAppliedCount = true; storage.get({ httpNowhere: false, showAppliedCount: true }, item => { - { httpNowhere, showAppliedCount } = item; + httpNowhere = item.httpNowhere + showAppliedCount = item.showAppliedCount; updateState(); }); From d64529dff177757913cb0513c74e822d3a44ead3 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 11:33:04 +0300 Subject: [PATCH 17/35] 1 --- chromium/options.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chromium/options.js b/chromium/options.js index 982e3fdf98f2..89661ccacec3 100644 --- a/chromium/options.js +++ b/chromium/options.js @@ -19,8 +19,8 @@ function readFile (file) { document.addEventListener('DOMContentLoaded', () => { const showAppliedCountCheckbox = document.getElementById('show-applied-count') - sendMessage('get_option', { showAppliedCount: true }).then(value => { - showAppliedCountCheckbox.checked = on + sendMessage('get_option', { showAppliedCount: true }).then(item => { + showAppliedCountCheckbox.checked = item.showAppliedCount showAppliedCountCheckbox.addEventListener('change', event => { sendMessage('set_option', { showAppliedCount: showAppliedCountCheckbox.checked }) }) From f95230584f506f4adc91c61d89c225588856639e Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 11:41:41 +0300 Subject: [PATCH 18/35] 1 --- chromium/popup.html | 1 + 1 file changed, 1 insertion(+) diff --git a/chromium/popup.html b/chromium/popup.html index 0163b65a7271..9f24b216b526 100644 --- a/chromium/popup.html +++ b/chromium/popup.html @@ -1,3 +1,4 @@ + From 41765b24fffba7a9cf4a1a6bfe9c66a6b16b5dbf Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 16:14:15 +0300 Subject: [PATCH 19/35] 1 --- chromium/popup.css | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/chromium/popup.css b/chromium/popup.css index 82c3dbb35b7e..38e33853a9e9 100644 --- a/chromium/popup.css +++ b/chromium/popup.css @@ -18,8 +18,7 @@ h1, h2, h3, .rule { /* Initially hide section (until rules get added). */ section.rules { - position: fixed; - visibility: hidden; + display: none; } .rule{ From e50d2e545d146962b9ba6281bef13a5a28ebad93 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 16:15:37 +0300 Subject: [PATCH 20/35] 1 --- chromium/popup.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/chromium/popup.js b/chromium/popup.js index 6aab8ce88cad..58c5eba1f0b4 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -155,8 +155,7 @@ function gotTab(tabArray) { listDiv = unstableRules; } appendRuleLineToListDiv(rulesets[r], listDiv); - listDiv.style.position = "static"; - listDiv.style.visibility = "visible"; + listDiv.style.display = 'block'; } // Only show the "Add a rule" link if we're on an HTTPS page if (/^https:/.test(activeTab.url)) { From 9efed512bacc4e6476943c7f199c7f88825e0520 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 16:20:57 +0300 Subject: [PATCH 21/35] 1 --- chromium/popup.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/chromium/popup.js b/chromium/popup.js index 58c5eba1f0b4..3bde6c333722 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -151,11 +151,15 @@ function gotTab(tabArray) { sendMessage("get_active_rulesets", activeTab.id, function(rulesets){ for (var r in rulesets) { var listDiv = stableRules; + if (!rulesets[r].default_state) { listDiv = unstableRules; } + appendRuleLineToListDiv(rulesets[r], listDiv); - listDiv.style.display = 'block'; + + // Un-hide the div + listDiv.className = ''; } // Only show the "Add a rule" link if we're on an HTTPS page if (/^https:/.test(activeTab.url)) { From da01ee29a9536de73b656f81652bd6ba27b3087f Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 16:28:43 +0300 Subject: [PATCH 22/35] 1 --- chromium/popup.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chromium/popup.js b/chromium/popup.js index 3bde6c333722..512d4f9b0b09 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -174,7 +174,7 @@ function gotTab(tabArray) { document.addEventListener("DOMContentLoaded", function () { stableRules = document.getElementById("StableRules"); unstableRules = document.getElementById("UnstableRules"); - chrome.tabs.query({ active: true, currentWindow: true }, gotTab); + chrome.tabs.query({ active: true }, gotTab); // Set up the enabled/disabled switch & hide/show rules updateEnabledDisabledUI(); From 503a261db9cc71538f06d520d244c3bd77e89fdc Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 16:42:34 +0300 Subject: [PATCH 23/35] 1 --- chromium/popup.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chromium/popup.js b/chromium/popup.js index 512d4f9b0b09..8e02ff1f4a57 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -174,7 +174,7 @@ function gotTab(tabArray) { document.addEventListener("DOMContentLoaded", function () { stableRules = document.getElementById("StableRules"); unstableRules = document.getElementById("UnstableRules"); - chrome.tabs.query({ active: true }, gotTab); + chrome.tabs.query({ active: true, lastFocusedWindow: true }, gotTab); // Set up the enabled/disabled switch & hide/show rules updateEnabledDisabledUI(); From 106ea8f9257ce6c54524fc7f86bf654256f7c063 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 17:01:47 +0300 Subject: [PATCH 24/35] 1 --- chromium/popup.js | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/chromium/popup.js b/chromium/popup.js index 8e02ff1f4a57..cde9681d5c36 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -1,5 +1,9 @@ "use strict"; +function sendMessageCallback(type, object, callback) { + chrome.runtime.sendMessage({ type, object }, callback); +} + var stableRules = null; var unstableRules = null; var hostReg = /.*\/\/[^$/]*\//; @@ -21,14 +25,14 @@ function toggleRuleLine(checkbox, ruleset, tab_id) { tab_id: tab_id }; - sendMessage("set_ruleset_active_status", set_ruleset, function(){ + sendMessageCallback("set_ruleset_active_status", set_ruleset, function(){ if (ruleset_active != ruleset.default_state) { localStorage[ruleset.name] = ruleset_active; } else { delete localStorage[ruleset.name]; // purge the name from the cache so that this unchecking is persistent. - sendMessage("delete_from_ruleset_cache", ruleset.name); + sendMessageCallback("delete_from_ruleset_cache", ruleset.name); } // Now reload the selected tab of the current window. @@ -95,7 +99,7 @@ function appendRuleLineToListDiv(ruleset, list_div) { line.appendChild(remove); remove.addEventListener("click", function(){ - sendMessage("remove_rule", ruleset); + sendMessageCallback("remove_rule", ruleset); list_div.removeChild(line); }); } @@ -109,7 +113,7 @@ function appendRuleLineToListDiv(ruleset, list_div) { // Change the UI to reflect extension enabled/disabled function updateEnabledDisabledUI() { - sendMessage("get_is_extension_enabled", null, function(enabled){ + sendMessageCallback("get_is_extension_enabled", null, function(enabled){ document.getElementById('onoffswitch').checked = enabled; // Hide or show the rules sections if (enabled) { @@ -117,7 +121,7 @@ function updateEnabledDisabledUI() { } else { document.body.className = "disabled" } - sendMessage("update_state"); + sendMessageCallback("update_state"); }); } @@ -130,13 +134,13 @@ function toggleEnabledDisabled() { window.close(); } - sendMessage("get_is_extension_enabled", null, function(enabled){ + sendMessageCallback("get_is_extension_enabled", null, function(enabled){ if (enabled) { // User wants to disable us - sendMessage("set_is_extension_enabled", false, extension_toggle_effect); + sendMessageCallback("set_is_extension_enabled", false, extension_toggle_effect); } else { // User wants to enable us - sendMessage("set_is_extension_enabled", true, extension_toggle_effect); + sendMessageCallback("set_is_extension_enabled", true, extension_toggle_effect); } }); } @@ -148,7 +152,7 @@ function toggleEnabledDisabled() { function gotTab(tabArray) { var activeTab = tabArray[0]; - sendMessage("get_active_rulesets", activeTab.id, function(rulesets){ + sendMessageCallback("get_active_rulesets", activeTab.id, function(rulesets){ for (var r in rulesets) { var listDiv = stableRules; @@ -236,7 +240,7 @@ function addManualRule() { redirectTo : e("new-rule-redirect").value, urlMatcher : e("new-rule-regex").value }; - sendMessage("add_new_rule", params, function() { + sendMessageCallback("add_new_rule", params, function() { location.reload(); }); }); @@ -265,11 +269,11 @@ function toggleHttpNowhere() { function getOption_(opt, defaultOpt, callback) { var details = {}; details[opt] = defaultOpt; - sendMessage("get_option", details, callback); + sendMessageCallback("get_option", details, callback); } function setOption_(opt, value) { var details = {}; details[opt] = value; - sendMessage("set_option", details); + sendMessageCallback("set_option", details); } From 4f96de79ac925d76edb811ff416f087f216ec226 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 18:46:17 +0300 Subject: [PATCH 25/35] Refactor popup.js --- chromium/popup.js | 352 +++++++++++++++++----------------------------- 1 file changed, 129 insertions(+), 223 deletions(-) diff --git a/chromium/popup.js b/chromium/popup.js index cde9681d5c36..c327f89c0eed 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -1,279 +1,185 @@ -"use strict"; +'use strict' -function sendMessageCallback(type, object, callback) { - chrome.runtime.sendMessage({ type, object }, callback); +function sendMessageCallback (type, object, callback) { + chrome.runtime.sendMessage({ type, object }, callback) } -var stableRules = null; -var unstableRules = null; -var hostReg = /.*\/\/[^$/]*\//; - -function e(id) { - return document.getElementById(id); -} - -/** - * Handles rule (de)activation in the popup - * @param checkbox checkbox being clicked - * @param ruleset the ruleset tied tot he checkbox - */ -function toggleRuleLine(checkbox, ruleset, tab_id) { - var ruleset_active = checkbox.checked; - var set_ruleset = { - active: ruleset_active, - name: ruleset.name, - tab_id: tab_id - }; - - sendMessageCallback("set_ruleset_active_status", set_ruleset, function(){ - - if (ruleset_active != ruleset.default_state) { - localStorage[ruleset.name] = ruleset_active; - } else { - delete localStorage[ruleset.name]; - // purge the name from the cache so that this unchecking is persistent. - sendMessageCallback("delete_from_ruleset_cache", ruleset.name); - } - - // Now reload the selected tab of the current window. - chrome.tabs.reload(); - }); -} +let stableRules = null +let unstableRules = null +const hostReg = /.*\/\/[^$/]*\// /** * Creates a rule line (including checkbox and icon) for the popup * @param ruleset the ruleset to build the line for * @returns {*} */ -function appendRuleLineToListDiv(ruleset, list_div) { - +function appendRuleLineToListDiv (ruleset, list_div) { // parent block for line - var line = document.createElement("div"); - line.className = "rule checkbox"; + const line = document.createElement('div') + line.className = 'rule checkbox' - // label "container" - var label = document.createElement("label"); + // label 'container' + const label = document.createElement('label') // checkbox - var checkbox = document.createElement("input"); - checkbox.type = "checkbox"; - if (ruleset.active) { - checkbox.setAttribute("checked", ""); - } - checkbox.onchange = function(ev) { - toggleRuleLine(checkbox, ruleset, tab_id); - }; - label.appendChild(checkbox); + const checkbox = document.createElement('input') + checkbox.type = 'checkbox' + checkbox.checked = ruleset.active + + checkbox.addEventListener('change', () => { + setRulesetActive(ruleset, checkbox.checked) + }) + + label.appendChild(checkbox) // favicon (from chrome's cache) - var favicon = document.createElement("img"); - favicon.className = "favicon"; - favicon.src = "chrome://favicon/"; - for (let rule of ruleset.rules) { - var host = hostReg.exec(rule.to); + const favicon = document.createElement('img') + favicon.className = 'favicon' + + for (const rule of ruleset.rules) { + const host = hostReg.exec(rule.to)[0] if (host) { - favicon.src += host[0]; - break; + favicon.src = 'chrome://favicon/' + host + break } } - if (navigator.userAgent.match("Chrome")) { - var xhr = new XMLHttpRequest(); - try { - xhr.open("GET", favicon.src, true); - label.appendChild(favicon); - } catch (e) {} - } + label.appendChild(favicon) // label text - var text = document.createElement("span"); - text.innerText = ruleset.name; + const text = document.createElement('span') + text.innerText = ruleset.name + if (ruleset.note.length) { - text.title = ruleset.note; + text.title = ruleset.note } - if(ruleset.note == "user rule") { - var remove = document.createElement("img"); - remove.src = chrome.extension.getURL("remove.png"); - remove.className = "remove"; - line.appendChild(remove); + if (ruleset.note == 'user rule') { + const remove = document.createElement('img') + remove.src = chrome.extension.getURL('remove.png') + remove.className = 'remove' + line.appendChild(remove) - remove.addEventListener("click", function(){ - sendMessageCallback("remove_rule", ruleset); - list_div.removeChild(line); - }); + remove.addEventListener('click', function () { + backgroundPage.removeRule(ruleset) + list_div.removeChild(line) + }) } - label.appendChild(text); - - line.appendChild(label); - - list_div.appendChild(line); -} - -// Change the UI to reflect extension enabled/disabled -function updateEnabledDisabledUI() { - sendMessageCallback("get_is_extension_enabled", null, function(enabled){ - document.getElementById('onoffswitch').checked = enabled; - // Hide or show the rules sections - if (enabled) { - document.body.className = "" - } else { - document.body.className = "disabled" - } - sendMessageCallback("update_state"); - }); + label.appendChild(text) + line.appendChild(label) + list_div.appendChild(line) } // Toggle extension enabled/disabled status -function toggleEnabledDisabled() { - var extension_toggle_effect = function(){ - updateEnabledDisabledUI(); +function setEnabled (enabled) { + sendMessageCallback('set_is_extension_enabled', enabled, () => { // The extension state changed, so reload this tab. - chrome.tabs.reload(); - window.close(); - } - - sendMessageCallback("get_is_extension_enabled", null, function(enabled){ - if (enabled) { - // User wants to disable us - sendMessageCallback("set_is_extension_enabled", false, extension_toggle_effect); - } else { - // User wants to enable us - sendMessageCallback("set_is_extension_enabled", true, extension_toggle_effect); - } - }); + chrome.tabs.reload() + window.close() + }) } /** - * Create the list of rules for a specific tab - * @param tabArray + * Fill in content into the popup on load */ -function gotTab(tabArray) { - var activeTab = tabArray[0]; +document.addEventListener('DOMContentLoaded', () => { + const stableRules = document.getElementById('StableRules') + const unstableRules = document.getElementById('UnstableRules') + chrome.tabs.query({ active: true, lastFocusedWindow: true }, tabs => { + const activeTab = tabs[0] - sendMessageCallback("get_active_rulesets", activeTab.id, function(rulesets){ - for (var r in rulesets) { - var listDiv = stableRules; + sendMessageCallback('get_active_rulesets', activeTab.id, rulesets => { + for (const r in rulesets) { + const listDiv = rulesets[r].default_state ? stableRules : unstableRules - if (!rulesets[r].default_state) { - listDiv = unstableRules; - } + appendRuleLineToListDiv(rulesets[r], listDiv) - appendRuleLineToListDiv(rulesets[r], listDiv); + // Un-hide the div + listDiv.className = '' + } - // Un-hide the div - listDiv.className = ''; - } - // Only show the "Add a rule" link if we're on an HTTPS page - if (/^https:/.test(activeTab.url)) { - show(e("add-rule-link")); - } - }); -} + // Only show the "Add a rule" link if we're on an HTTPS page + const isHttps = activeTab.url.slice(0, 6) === 'https:' -/** - * Fill in content into the popup on load - */ -document.addEventListener("DOMContentLoaded", function () { - stableRules = document.getElementById("StableRules"); - unstableRules = document.getElementById("UnstableRules"); - chrome.tabs.query({ active: true, lastFocusedWindow: true }, gotTab); + document.getElementById('add-rule-link').style.display = isHttps ? 'block' : 'none' + }) + }) // Set up the enabled/disabled switch & hide/show rules - updateEnabledDisabledUI(); - document.getElementById('onoffswitch').addEventListener('click', toggleEnabledDisabled); + sendMessageCallback('get_is_extension_enabled', null, enabled => { + const extensionEnabled = document.getElementById('onoffswitch') + extensionEnabled.checked = enabled + extensionEnabled.addEventListener('change', event => { + setEnabled(event.target.checked) + }) + + // Hide or show the rules sections + document.body.className = enabled ? '' : 'disabled' + }) + // Print the extension's current version. - var the_manifest = chrome.runtime.getManifest(); - var version_info = document.getElementById('current-version'); - version_info.innerText = the_manifest.version; + const version_info = document.getElementById('current-version') + version_info.innerText = chrome.runtime.getManifest().version // Set up toggle checkbox for HTTP nowhere mode - getOption_('httpNowhere', false, function(item) { - var httpNowhereCheckbox = document.getElementById('http-nowhere-checkbox'); - httpNowhereCheckbox.addEventListener('click', toggleHttpNowhere, false); - var httpNowhereEnabled = item.httpNowhere; - if (httpNowhereEnabled) { - httpNowhereCheckbox.setAttribute('checked', ''); - } - }); - - e("add-rule-link").addEventListener("click", addManualRule); -}); + getOption_('httpNowhere', false, item => { + const httpNowhereCheckbox = document.getElementById('http-nowhere-checkbox'); + httpNowhereCheckbox.checked = item.httpNowhere; + httpNowhereCheckbox.addEventListener('change', event => { + setHttpNowhere(event.target.checked) + }) + }) - -var escapeForRegex = function( value ) { - return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); -}; - -function hide(elem) { - elem.style.display = "none"; -} - -function show(elem) { - elem.style.display = "block"; -} + document.getElementById('add-rule-link').addEventListener('click', addManualRule) +}) /** * Handles the manual addition of rules */ -function addManualRule() { - chrome.tabs.query({ active: true, currentWindow: true }, function(tab) { - hide(e("add-rule-link")); - show(e("add-new-rule-div")); - var newUrl = document.createElement('a'); - newUrl.href = tab[0].url; - newUrl.protocol = "https:"; - e("new-rule-host").value = newUrl.host; - var oldUrl = document.createElement('a'); - oldUrl.href = tab[0].url; - oldUrl.protocol = "http:"; - var oldMatcher = "^" + escapeForRegex(oldUrl.protocol + "//" + oldUrl.host+ "/"); - e("new-rule-regex").value = oldMatcher; - var redirectPath = newUrl.protocol + "//" + newUrl.host + "/"; - e("new-rule-redirect").value = redirectPath; - e("new-rule-name").value = "Manual rule for " + oldUrl.host; - e("add-new-rule-button").addEventListener("click", function() { - var params = { - host : e("new-rule-host").value, - redirectTo : e("new-rule-redirect").value, - urlMatcher : e("new-rule-regex").value - }; - sendMessageCallback("add_new_rule", params, function() { - location.reload(); - }); - }); - - e("cancel-new-rule").addEventListener("click", function() { - show(e("add-rule-link")); - hide(e("add-new-rule-div")); - }); - e("new-rule-show-advanced-link").addEventListener("click", function() { - show(e("new-rule-advanced")); - hide(e("new-rule-regular-text")); - }); - e("new-rule-hide-advanced-link").addEventListener("click", function() { - hide(e("new-rule-advanced")); - show(e("new-rule-regular-text")); - }); - }); -} - -function toggleHttpNowhere() { - getOption_('httpNowhere', false, function(item) { - setOption_('httpNowhere', !item.httpNowhere); - }); +function addManualRule () { + chrome.tabs.query({ active: true, currentWindow: true }, tab => { + const url = new URL(tab[0].url) + document.getElementById('add-new-rule-div').style.display = 'block' + document.getElementById('add-rule-link').style.display = 'none' + document.getElementById('new-rule-host').value = url.host + document.getElementById('new-rule-regex').value = '^http:' + document.getElementById('new-rule-redirect').value = 'https:' + document.getElementById('new-rule-name').value = 'Manual rule for ' + url.host + document.getElementById('add-new-rule-button').addEventListener('click', () => { + backgroundPage.addNewRule({ + host: document.getElementById('new-rule-host').value, + redirectTo: document.getElementById('new-rule-redirect').value, + urlMatcher: document.getElementById('new-rule-regex').value + }, () => { + location.reload() + }) + }) + + document.getElementById('cancel-new-rule').addEventListener('click', () => { + document.getElementById('add-rule-link').style.display = 'block' + document.getElementById('add-new-rule-div').style.display = 'none' + }) + document.getElementById('new-rule-show-advanced-link').addEventListener('click', () => { + document.getElementById('new-rule-advanced').style.display = 'block' + document.getElementById('new-rule-regular-text').style.display = 'none' + }) + document.getElementById('new-rule-hide-advanced-link').addEventListener('click', () => { + document.getElementById('new-rule-advanced').style.display = 'none' + document.getElementById('new-rule-regular-text').style.display = 'block' + }) + }) } -function getOption_(opt, defaultOpt, callback) { - var details = {}; - details[opt] = defaultOpt; - sendMessageCallback("get_option", details, callback); +function getOption_ (opt, defaultOpt, callback) { + let details = {} + details[opt] = defaultOpt + sendMessageCallback('get_option', details, callback) } -function setOption_(opt, value) { - var details = {}; - details[opt] = value; - sendMessageCallback("set_option", details); +function setOption_ (opt, value) { + let details = {} + details[opt] = value + sendMessageCallback('set_option', details) } From 0bf6ff4fdf4f68411ac2e6b6e6a6182012febd09 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 19:18:32 +0300 Subject: [PATCH 26/35] More refactorings --- chromium/popup.js | 87 ++++++++++++++++++++++++++++++----------------- 1 file changed, 55 insertions(+), 32 deletions(-) diff --git a/chromium/popup.js b/chromium/popup.js index c327f89c0eed..bb45c6143c47 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -4,16 +4,41 @@ function sendMessageCallback (type, object, callback) { chrome.runtime.sendMessage({ type, object }, callback) } -let stableRules = null -let unstableRules = null const hostReg = /.*\/\/[^$/]*\// +/** + * Handles rule (de)activation in the popup + * @param checkbox checkbox being clicked + * @param ruleset the ruleset tied tot he checkbox + */ +function setRulesetActive (ruleset, tabId, active) { + const rulesetData = { + active, + name: ruleset.name, + tab_id: tabId + } + + sendMessageCallback('set_ruleset_active_status', rulesetData, () => { + if (active !== ruleset.default_state) { + localStorage[ruleset.name] = active + } else { + delete localStorage[ruleset.name] + + // Purge the name from the cache so that this unchecking is persistent. + sendMessageCallback('delete_from_ruleset_cache', ruleset.name) + } + + // Now reload the selected tab of the current window. + chrome.tabs.reload() + }) +} + /** * Creates a rule line (including checkbox and icon) for the popup * @param ruleset the ruleset to build the line for * @returns {*} */ -function appendRuleLineToListDiv (ruleset, list_div) { +function appendRuleLineToListDiv (ruleset, tabId, listDiv) { // parent block for line const line = document.createElement('div') line.className = 'rule checkbox' @@ -27,7 +52,7 @@ function appendRuleLineToListDiv (ruleset, list_div) { checkbox.checked = ruleset.active checkbox.addEventListener('change', () => { - setRulesetActive(ruleset, checkbox.checked) + setRulesetActive(ruleset, tabId, checkbox.checked) }) label.appendChild(checkbox) @@ -54,24 +79,24 @@ function appendRuleLineToListDiv (ruleset, list_div) { text.title = ruleset.note } - if (ruleset.note == 'user rule') { + if (ruleset.note === 'user rule') { const remove = document.createElement('img') remove.src = chrome.extension.getURL('remove.png') remove.className = 'remove' line.appendChild(remove) remove.addEventListener('click', function () { - backgroundPage.removeRule(ruleset) - list_div.removeChild(line) + sendMessageCallback('remove_rule', ruleset) + listDiv.removeChild(line) }) } label.appendChild(text) line.appendChild(label) - list_div.appendChild(line) + listDiv.appendChild(line) } -// Toggle extension enabled/disabled status +// Set extension enabled/disabled status function setEnabled (enabled) { sendMessageCallback('set_is_extension_enabled', enabled, () => { // The extension state changed, so reload this tab. @@ -80,6 +105,15 @@ function setEnabled (enabled) { }) } +// Set HTTP nowhere mode +function setHttpNowhere (enabled) { + sendMessageCallback('set_option', { httpNowhere: enabled }, () => { + // The extension state changed, so reload this tab. + chrome.tabs.reload() + window.close() + }) +} + /** * Fill in content into the popup on load */ @@ -90,10 +124,10 @@ document.addEventListener('DOMContentLoaded', () => { const activeTab = tabs[0] sendMessageCallback('get_active_rulesets', activeTab.id, rulesets => { - for (const r in rulesets) { - const listDiv = rulesets[r].default_state ? stableRules : unstableRules + for (const name in rulesets) { + const listDiv = rulesets[name].default_state ? stableRules : unstableRules - appendRuleLineToListDiv(rulesets[r], listDiv) + appendRuleLineToListDiv(rulesets[name], activeTab.id, listDiv) // Un-hide the div listDiv.className = '' @@ -117,16 +151,15 @@ document.addEventListener('DOMContentLoaded', () => { // Hide or show the rules sections document.body.className = enabled ? '' : 'disabled' }) - // Print the extension's current version. - const version_info = document.getElementById('current-version') - version_info.innerText = chrome.runtime.getManifest().version + const versionInfo = document.getElementById('current-version') + versionInfo.innerText = chrome.runtime.getManifest().version // Set up toggle checkbox for HTTP nowhere mode - getOption_('httpNowhere', false, item => { - const httpNowhereCheckbox = document.getElementById('http-nowhere-checkbox'); - httpNowhereCheckbox.checked = item.httpNowhere; + sendMessageCallback({ httpNowhere: false }, item => { + const httpNowhereCheckbox = document.getElementById('http-nowhere-checkbox') + httpNowhereCheckbox.checked = item.httpNowhere httpNowhereCheckbox.addEventListener('change', event => { setHttpNowhere(event.target.checked) }) @@ -148,11 +181,13 @@ function addManualRule () { document.getElementById('new-rule-redirect').value = 'https:' document.getElementById('new-rule-name').value = 'Manual rule for ' + url.host document.getElementById('add-new-rule-button').addEventListener('click', () => { - backgroundPage.addNewRule({ + const params = { host: document.getElementById('new-rule-host').value, redirectTo: document.getElementById('new-rule-redirect').value, urlMatcher: document.getElementById('new-rule-regex').value - }, () => { + } + + sendMessageCallback('add_new_rule', params, () => { location.reload() }) }) @@ -171,15 +206,3 @@ function addManualRule () { }) }) } - -function getOption_ (opt, defaultOpt, callback) { - let details = {} - details[opt] = defaultOpt - sendMessageCallback('get_option', details, callback) -} - -function setOption_ (opt, value) { - let details = {} - details[opt] = value - sendMessageCallback('set_option', details) -} From b22c1073a72e485c4d2497a2d60f97b2987f0ac8 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 19:19:51 +0300 Subject: [PATCH 27/35] 1 --- chromium/popup.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chromium/popup.js b/chromium/popup.js index bb45c6143c47..a3f2ce8be185 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -4,8 +4,6 @@ function sendMessageCallback (type, object, callback) { chrome.runtime.sendMessage({ type, object }, callback) } -const hostReg = /.*\/\/[^$/]*\// - /** * Handles rule (de)activation in the popup * @param checkbox checkbox being clicked @@ -33,6 +31,8 @@ function setRulesetActive (ruleset, tabId, active) { }) } +const hostReg = /.*\/\/[^$/]*\// + /** * Creates a rule line (including checkbox and icon) for the popup * @param ruleset the ruleset to build the line for From 3353ad023f829f0a680fee7608e279ac4616c432 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 19:28:36 +0300 Subject: [PATCH 28/35] And more --- chromium/popup.js | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/chromium/popup.js b/chromium/popup.js index a3f2ce8be185..7e1e135eeb03 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -1,9 +1,5 @@ 'use strict' -function sendMessageCallback (type, object, callback) { - chrome.runtime.sendMessage({ type, object }, callback) -} - /** * Handles rule (de)activation in the popup * @param checkbox checkbox being clicked @@ -16,14 +12,14 @@ function setRulesetActive (ruleset, tabId, active) { tab_id: tabId } - sendMessageCallback('set_ruleset_active_status', rulesetData, () => { + sendMessage('set_ruleset_active_status', rulesetData).then(() => { if (active !== ruleset.default_state) { localStorage[ruleset.name] = active } else { delete localStorage[ruleset.name] // Purge the name from the cache so that this unchecking is persistent. - sendMessageCallback('delete_from_ruleset_cache', ruleset.name) + sendMessage('delete_from_ruleset_cache', ruleset.name) } // Now reload the selected tab of the current window. @@ -86,7 +82,7 @@ function appendRuleLineToListDiv (ruleset, tabId, listDiv) { line.appendChild(remove) remove.addEventListener('click', function () { - sendMessageCallback('remove_rule', ruleset) + sendMessage('remove_rule', ruleset) listDiv.removeChild(line) }) } @@ -98,7 +94,7 @@ function appendRuleLineToListDiv (ruleset, tabId, listDiv) { // Set extension enabled/disabled status function setEnabled (enabled) { - sendMessageCallback('set_is_extension_enabled', enabled, () => { + sendMessage('set_is_extension_enabled', enabled).then(() => { // The extension state changed, so reload this tab. chrome.tabs.reload() window.close() @@ -107,7 +103,7 @@ function setEnabled (enabled) { // Set HTTP nowhere mode function setHttpNowhere (enabled) { - sendMessageCallback('set_option', { httpNowhere: enabled }, () => { + sendMessage('set_option', { httpNowhere: enabled }).then(() => { // The extension state changed, so reload this tab. chrome.tabs.reload() window.close() @@ -123,7 +119,7 @@ document.addEventListener('DOMContentLoaded', () => { chrome.tabs.query({ active: true, lastFocusedWindow: true }, tabs => { const activeTab = tabs[0] - sendMessageCallback('get_active_rulesets', activeTab.id, rulesets => { + sendMessage('get_active_rulesets', activeTab.id).then(rulesets => { for (const name in rulesets) { const listDiv = rulesets[name].default_state ? stableRules : unstableRules @@ -141,7 +137,7 @@ document.addEventListener('DOMContentLoaded', () => { }) // Set up the enabled/disabled switch & hide/show rules - sendMessageCallback('get_is_extension_enabled', null, enabled => { + sendMessage('get_is_extension_enabled').then(enabled => { const extensionEnabled = document.getElementById('onoffswitch') extensionEnabled.checked = enabled extensionEnabled.addEventListener('change', event => { @@ -157,7 +153,7 @@ document.addEventListener('DOMContentLoaded', () => { versionInfo.innerText = chrome.runtime.getManifest().version // Set up toggle checkbox for HTTP nowhere mode - sendMessageCallback({ httpNowhere: false }, item => { + sendMessage('get_option', { httpNowhere: false }).then(item => { const httpNowhereCheckbox = document.getElementById('http-nowhere-checkbox') httpNowhereCheckbox.checked = item.httpNowhere httpNowhereCheckbox.addEventListener('change', event => { @@ -187,7 +183,7 @@ function addManualRule () { urlMatcher: document.getElementById('new-rule-regex').value } - sendMessageCallback('add_new_rule', params, () => { + sendMessage('add_new_rule', params).then(() => { location.reload() }) }) From 2844477287470750c3873891b720e27cf530f2ae Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 19:36:29 +0300 Subject: [PATCH 29/35] Fix extension-breaking bug --- chromium/background.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chromium/background.js b/chromium/background.js index b0b0d72736de..92b7c25ce31f 100644 --- a/chromium/background.js +++ b/chromium/background.js @@ -148,7 +148,7 @@ var updateState = function() { if (!chrome.tabs) { return; } - chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { + chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) { if (!tabs || tabs.length === 0) { return; } From 406f46e9d22e49614fd20ff58409598640b9fb77 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 19:37:18 +0300 Subject: [PATCH 30/35] 1 --- chromium/popup.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chromium/popup.js b/chromium/popup.js index 7e1e135eeb03..3c58ed9c131f 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -168,8 +168,8 @@ document.addEventListener('DOMContentLoaded', () => { * Handles the manual addition of rules */ function addManualRule () { - chrome.tabs.query({ active: true, currentWindow: true }, tab => { - const url = new URL(tab[0].url) + chrome.tabs.query({ active: true, lastFocusedWindow: true }, tabs => { + const url = new URL(tabs[0].url) document.getElementById('add-new-rule-div').style.display = 'block' document.getElementById('add-rule-link').style.display = 'none' document.getElementById('new-rule-host').value = url.host From ad19246bdf3a475ffb2a4cffe07bb19a2f00cef9 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 19:54:00 +0300 Subject: [PATCH 31/35] only chrome --- chromium/popup.js | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/chromium/popup.js b/chromium/popup.js index 3c58ed9c131f..2ab86c440ebd 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -53,19 +53,21 @@ function appendRuleLineToListDiv (ruleset, tabId, listDiv) { label.appendChild(checkbox) - // favicon (from chrome's cache) - const favicon = document.createElement('img') - favicon.className = 'favicon' - - for (const rule of ruleset.rules) { - const host = hostReg.exec(rule.to)[0] - if (host) { - favicon.src = 'chrome://favicon/' + host - break + if (navigator.userAgent.match('Chrome')) { + // favicon (from chrome's cache) + const favicon = document.createElement('img') + favicon.className = 'favicon' + + for (const rule of ruleset.rules) { + const host = hostReg.exec(rule.to)[0] + if (host) { + favicon.src = 'chrome://favicon/' + host + break + } } - } - label.appendChild(favicon) + label.appendChild(favicon) + } // label text const text = document.createElement('span') From 44ff2cdeb9328c0e283f695983e312b81cbcad59 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 20:14:20 +0300 Subject: [PATCH 32/35] Temporarily disable favicons --- chromium/popup.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/chromium/popup.js b/chromium/popup.js index 2ab86c440ebd..771061595a89 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -53,7 +53,9 @@ function appendRuleLineToListDiv (ruleset, tabId, listDiv) { label.appendChild(checkbox) - if (navigator.userAgent.match('Chrome')) { + // Temporarily disabled until we will find a better way. + + if (false && navigator.userAgent.match('Chrome')) { // favicon (from chrome's cache) const favicon = document.createElement('img') favicon.className = 'favicon' From c85e9848380e2600e0ee304bb9a9fddaded921de Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 20:44:04 +0300 Subject: [PATCH 33/35] add export button --- chromium/options.html | 1 + 1 file changed, 1 insertion(+) diff --git a/chromium/options.html b/chromium/options.html index d8be4a9845e9..cc5297c48516 100644 --- a/chromium/options.html +++ b/chromium/options.html @@ -23,6 +23,7 @@ + From 8d32e87d9c424c2cbb5cc12f301435145fd012df Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 20:57:49 +0300 Subject: [PATCH 34/35] Export --- chromium/options.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/chromium/options.js b/chromium/options.js index 89661ccacec3..fff8841d00e6 100644 --- a/chromium/options.js +++ b/chromium/options.js @@ -16,6 +16,15 @@ function readFile (file) { }) } +function saveFile (blob, fileName) { + const blobUrl = URL.createObjectURL(blob) + + const anchor = document.createElement('a') + anchor.href = blobUrl + anchor.download = fileName + anchor.click() +} + document.addEventListener('DOMContentLoaded', () => { const showAppliedCountCheckbox = document.getElementById('show-applied-count') @@ -40,4 +49,10 @@ document.addEventListener('DOMContentLoaded', () => { document.getElementById('import-settings').addEventListener('change', event => { importButton.disabled = (event.target.files.length === 0) }) + + document.getElementById('rulesetSettingsExport').addEventListener('click', () => { + const json = JSON.stringify(localStorage) + const blob = new Blob([ json ], { type: 'application/json' }) + saveFile(blob, 'settings.json') + }) }) From ca447fdc61a231e7a6c848a24aae014e36cfd222 Mon Sep 17 00:00:00 2001 From: koops76 Date: Mon, 14 Aug 2017 21:16:18 +0300 Subject: [PATCH 35/35] import --- chromium/options.html | 1 + chromium/options.js | 9 +++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/chromium/options.html b/chromium/options.html index cc5297c48516..dd3f5ff2978e 100644 --- a/chromium/options.html +++ b/chromium/options.html @@ -24,6 +24,7 @@ + diff --git a/chromium/options.js b/chromium/options.js index fff8841d00e6..9383fda1d691 100644 --- a/chromium/options.js +++ b/chromium/options.js @@ -36,9 +36,10 @@ document.addEventListener('DOMContentLoaded', () => { }) const importButton = document.getElementById('import') + const importSettings = document.getElementById('import-settings') importButton.addEventListener('click', event => { - const file = event.target.files[0] + const file = importSettings.files[0] readFile(file).then(data => { const settings = JSON.parse(fileContents) @@ -52,7 +53,11 @@ document.addEventListener('DOMContentLoaded', () => { document.getElementById('rulesetSettingsExport').addEventListener('click', () => { const json = JSON.stringify(localStorage) - const blob = new Blob([ json ], { type: 'application/json' }) + const blob = new Blob([json], { type: 'application/json' }) saveFile(blob, 'settings.json') }) + + document.getElementById('rulesetSettingsImport').addEventListener('click', () => { + + }) })