diff --git a/chromium/background.js b/chromium/background.js index 408389fb02d0..33f23f0d68cf 100644 --- a/chromium/background.js +++ b/chromium/background.js @@ -1,4 +1,13 @@ -"use strict"; +'use strict'; + +const storage = chrome.storage.sync || chrome.storage.local; + +const utils = window.utils || { + log (msg) { + console.log(msg); + } +}; + /** * Fetch and parse XML to be loaded as RuleSets. * @@ -8,7 +17,7 @@ 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.open('GET', chrome.extension.getURL(url), false); xhr.send(null); // Get file contents if (xhr.readyState != 4) { @@ -37,7 +46,7 @@ var USER_RULE_KEY = 'userRules'; var switchPlannerEnabledFor = {}; // Detailed information recorded when the HTTPS Switch Planner is active. // Structure is: -// switchPlannerInfo[tabId]["rw"/"nrw"][resource_host][active_content][url]; +// switchPlannerInfo[tabId]['rw'/'nrw'][resource_host][active_content][url]; // rw / nrw stand for "rewritten" versus "not rewritten" var switchPlannerInfo = {}; @@ -105,27 +114,27 @@ loadStoredUserRules(); * active: extension is enabled and rewrote URLs on this page. * disabled: extension is disabled from the popup menu. */ -var updateState = function() { - chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { +function updateState() { + chrome.tabs.query({ active: true, currentWindow: true }, tabs => { if (!tabs || tabs.length === 0) { return; } - var applied = activeRulesets.getRulesets(tabs[0].id) - var iconState = "inactive"; + const applied = activeRulesets.getRulesets(tabs[0].id) + let iconState = 'inactive'; if (!isExtensionEnabled) { - iconState = "disabled"; + iconState = 'disabled'; } else if (httpNowhereOn) { - iconState = "blocking"; + iconState = 'blocking'; } else if (applied) { - iconState = "active"; + iconState = 'active'; } chrome.browserAction.setIcon({ path: { - "38": "icons/icon-" + iconState + "-38.png" + '38': 'icons/icon-' + iconState + '-38.png' } }); chrome.browserAction.setTitle({ - title: "HTTPS Everywhere (" + iconState + ")" + title: 'HTTPS Everywhere (' + iconState + ')' }); }); } @@ -227,68 +236,59 @@ function onBeforeRequest(details) { const uri = new URL(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; - } + const shouldCancel = httpNowhereOn && + !uri.protocol === 'https:' && + !uri.hostname.slice(-6) === '.onion' && + !uri.hostname === 'localhost' && + !/^127(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}$/.test(uri.hostname); - // 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; - } + // Normalise hosts such as "www.example.com." or ".www.example.com" + uri.hostname = uri.hostname.replace(/^\.+|\.+$/g, ''); + + // If there is a username/password, put them aside during the ruleset analysis process + const tmp_user = uri.username, + tmp_pass = uri.password; + + uri.username = ''; + uri.password = ''; + + const canonical_url = uri.href; - 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 (details.url !== canonical_url) { + log(INFO, 'Original url ' + details.url + + ' changed before processing to ' + canonical_url); } + if (urlBlacklist.has(canonical_url)) { return {cancel: shouldCancel}; } - if (details.type == "main_frame") { + if (details.type == 'main_frame') { activeRulesets.removeTab(details.tabId); } - var potentiallyApplicable = all_rules.potentiallyApplicableRulesets(uri.hostname); + const potentiallyApplicable = all_rules.potentiallyApplicableRulesets(uri.hostname); if (redirectCounter[details.requestId] >= 8) { - log(NOTE, "Redirect counter hit for " + canonical_url); + log(NOTE, 'Redirect counter hit for ' + canonical_url); urlBlacklist.add(canonical_url); var hostname = uri.hostname; domainBlacklist.add(hostname); - log(WARN, "Domain blacklisted " + hostname); + log(WARN, 'Domain blacklisted ' + hostname); return {cancel: shouldCancel}; } - var newuristr = null; + let newuristr = null; - for (let ruleset of potentiallyApplicable) { + for (const ruleset of potentiallyApplicable) { activeRulesets.addRulesetToTab(details.tabId, ruleset); + if (ruleset.active && !newuristr) { newuristr = ruleset.apply(canonical_url); } } - if (newuristr && using_credentials_in_url) { + if (newuristr) { // re-insert userpass info which was stripped temporarily const uri_with_credentials = new URL(newuristr); uri_with_credentials.username = tmp_user; @@ -296,43 +296,35 @@ function onBeforeRequest(details) { 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); + // 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); } 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 loading a main frame, try the HTTPS version as an alternative to failing. + if (shouldCancel && details.type == 'main_frame') { + const currentUrl = newuristr || canonical_url; + const redirectUrl = currentUrl.replace(/^http:/, 'https:'); + + return { redirectUrl }; } - if (newuristr && newuristr.substring(0, 5) === "http:") { - // Abort early if we're about to redirect to HTTP in HTTP Nowhere mode - return {cancel: true}; + + // Abort early if we're about to redirect to HTTP in HTTP Nowhere mode + if (newuristr && newuristr.slice(0, 5) === 'http:') { + return { cancel: true }; } } if (newuristr) { - return {redirectUrl: newuristr}; + return { redirectUrl: newuristr }; } else { - return {cancel: shouldCancel}; + return { cancel: shouldCancel }; } } - // 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}; // 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 @@ -340,7 +332,8 @@ var activeTypes = { stylesheet: 1, script: 1, object: 1, other: 1}; // 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}; + +const activeTypes = { object: true, other: true, script: true, stylesheet: true, image: false, main_frame: false, sub_frame: false, xmlhttprequest: false }; /** * Record a non-HTTPS URL loaded by a given hostname in the Switch Planner, for @@ -354,31 +347,27 @@ var passiveTypes = { main_frame: 1, sub_frame: 1, image: 1, xmlhttprequest: 1}; * @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; + let rw = 'rw'; + if (rewritten_url === null) + rw = 'nrw'; + + let active_content = activeTypes[type]; + if (active_content === undefined) { + log(WARN, `Unknown type from onBeforeRequest details: "${type}", assuming active.`); + active_content = true; } if (!switchPlannerInfo[tab_id]) { switchPlannerInfo[tab_id] = {}; - switchPlannerInfo[tab_id]["rw"] = {}; - switchPlannerInfo[tab_id]["nrw"] = {}; + 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] = {}; - switchPlannerInfo[tab_id][rw][resource_host][active_content][resource_url] = 1; + switchPlannerInfo[tab_id][rw][resource_host][active_content][resource_url] = true; } /** @@ -387,9 +376,9 @@ function writeToSwitchPlanner(type, tab_id, resource_host, resource_url, rewritt * @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 === undefined) return 0; + let size = 0; + for (const key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; @@ -400,20 +389,20 @@ function objSize(obj) { * 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') { + const asset_host_list = []; + if (switchPlannerInfo[tab_id] === undefined || + 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; + const tabInfo = switchPlannerInfo[tab_id][rewritten]; + for (const asset_host in tabInfo) { + const ah = tabInfo[asset_host]; + const activeCount = objSize(ah[1]); + const passiveCount = objSize(ah[0]); + const 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];}); + asset_host_list.sort((a,b) => a[0] - b[0]); return asset_host_list; } @@ -423,25 +412,25 @@ function sortSwitchPlanner(tab_id, rewritten) { function switchPlannerSmallHtmlSection(tab_id, rewritten) { var asset_host_list = sortSwitchPlanner(tab_id, rewritten); if (asset_host_list.length == 0) { - return "none"; + return 'none'; } - var output = ""; + 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 + ": "; + output += '' + host + ': '; if (activeCount > 0) { - output += activeCount + " active"; + output += activeCount + ' active'; if (passiveCount > 0) - output += ", "; + output += ', '; } if (passiveCount > 0) { - output += passiveCount + " passive"; + output += passiveCount + ' passive'; } - output += "
"; + output += '
'; } return output; } @@ -450,12 +439,12 @@ function switchPlannerSmallHtmlSection(tab_id, rewritten) { * 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"); + 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'); } /** @@ -470,11 +459,11 @@ function switchPlannerSmallHtml(tab_id) { * map: the map containing the urls * */ function linksFromKeys(map) { - if (typeof map == 'undefined') return ""; - var output = ""; + if (typeof map == 'undefined') return ''; + var output = ''; for (var key in map) { if (map.hasOwnProperty(key)) { - output += "" + key + "
"; + output += '' + key + '
'; } } return output; @@ -492,23 +481,23 @@ function switchPlannerDetailsHtml(tab_id) { * */ function switchPlannerDetailsHtmlSection(tab_id, rewritten) { var asset_host_list = sortSwitchPlanner(tab_id, rewritten); - var output = ""; + 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 + ": "; + output += '' + host + ': '; if (activeCount > 0) { - output += activeCount + " active
"; + output += activeCount + ' active
'; output += linksFromKeys(switchPlannerInfo[tab_id][rewritten][host][1]); } if (passiveCount > 0) { - output += "
" + passiveCount + " passive
"; + output += '
' + passiveCount + ' passive
'; output += linksFromKeys(switchPlannerInfo[tab_id][rewritten][host][0]); } - output += "
"; + output += '
'; } return output; } @@ -534,15 +523,15 @@ function onCookieChanged(changeInfo) { } // 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; + if (changeInfo.cookie.domain[0] == '.') { + cookie.url = 'https://www' + changeInfo.cookie.domain + cookie.path; } else { - cookie.url = "https://" + changeInfo.cookie.domain + cookie.path; + 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); + 'Securing cookie ' + cookie.name + ' for ' + changeInfo.cookie.domain + ', was secure=' + changeInfo.cookie.secure); chrome.cookies.set(cookie); } } @@ -555,11 +544,11 @@ function onCookieChanged(changeInfo) { 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 (prefix === 'http:' || prefix === 'https') { if (details.requestId in redirectCounter) { redirectCounter[details.requestId] += 1; - log(DBUG, "Got redirect id "+details.requestId+ - ": "+redirectCounter[details.requestId]); + log(DBUG, 'Got redirect id '+details.requestId+ + ': '+redirectCounter[details.requestId]); } else { redirectCounter[details.requestId] = 1; } @@ -568,11 +557,11 @@ function onBeforeRedirect(details) { // Registers the handler for requests // See: https://github.com/EFForg/https-everywhere/issues/10039 -wr.onBeforeRequest.addListener(onBeforeRequest, {urls: ["*://*/*"]}, ["blocking"]); +wr.onBeforeRequest.addListener(onBeforeRequest, {urls: ['*://*/*']}, ['blocking']); // Try to catch redirect loops on URLs we've redirected to HTTPS. -wr.onBeforeRedirect.addListener(onBeforeRedirect, {urls: ["https://*/*"]}); +wr.onBeforeRedirect.addListener(onBeforeRedirect, {urls: ['https://*/*']}); // Listen for cookies set/updated and secure them if applicable. This function is async/nonblocking. @@ -598,21 +587,21 @@ function enableSwitchPlannerFor(tabId) { // Listen for connection from the DevTools panel so we can set up communication. chrome.runtime.onConnect.addListener(function (port) { - if (port.name == "devtools-page") { + 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."); + log(DBUG, 'Devtools window for tab ' + tabId + ' closed, clearing data.'); disableSwitchPlannerFor(tabId); }; - if (message.type === "enable") { + if (message.type === 'enable') { enableSwitchPlannerFor(tabId); port.onDisconnect.addListener(disableOnCloseCallback); - } else if (message.type === "disable") { + } else if (message.type === 'disable') { disableSwitchPlannerFor(tabId); - } else if (message.type === "getSmallHtml") { + } else if (message.type === 'getSmallHtml') { sendResponse({html: switchPlannerSmallHtml(tabId)}); } }); diff --git a/chromium/chrome-resources/css/chrome_shared.css b/chromium/chrome-resources/css/chrome_shared.css deleted file mode 100644 index 3f1ebbd05bc8..000000000000 --- a/chromium/chrome-resources/css/chrome_shared.css +++ /dev/null @@ -1,106 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -/* This file holds CSS that should be shared, in theory, by all user-visible - * chrome:// pages. */ - -@import url("widgets.css"); - - @import url("chromeos/ui_account_tweaks.css"); - - -/* Prevent CSS from overriding the hidden property. */ -[hidden] { - display: none !important; -} - -html.loading * { - -webkit-transition-delay: 0 !important; - -webkit-transition-duration: 0 !important; -} - -body { - cursor: default; - margin: 0; -} - -p { - line-height: 1.8em; -} - -h1, -h2, -h3 { - -webkit-user-select: none; - font-weight: normal; - /* Makes the vertical size of the text the same for all fonts. */ - line-height: 1; -} - -h1 { - font-size: 1.5em; -} - -h2 { - font-size: 1.3em; - margin-bottom: 0.4em; -} - -h3 { - color: black; - font-size: 1.2em; - margin-bottom: 0.8em; -} - -a { - color: rgb(17, 85, 204); - text-decoration: underline; -} - -a:active { - color: rgb(5, 37, 119); -} - -/* Elements that need to be LTR even in an RTL context, but should align - * right. (Namely, URLs, search engine names, etc.) - */ -html[dir='rtl'] .weakrtl { - direction: ltr; - text-align: right; -} - -/* Input fields in search engine table need to be weak-rtl. Since those input - * fields are generated for all cr.ListItem elements (and we only want weakrtl - * on some), the class needs to be on the enclosing div. - */ -html[dir='rtl'] div.weakrtl input { - direction: ltr; - text-align: right; -} - -html[dir='rtl'] .favicon-cell.weakrtl { - -webkit-padding-end: 22px; - -webkit-padding-start: 0; -} - -/* weakrtl for selection drop downs needs to account for the fact that - * Webkit does not honor the text-align attribute for the select element. - * (See Webkit bug #40216) - */ -html[dir='rtl'] select.weakrtl { - direction: rtl; -} - -html[dir='rtl'] select.weakrtl option { - direction: ltr; -} - -/* WebKit does not honor alignment for text specified via placeholder attribute. - * This CSS is a workaround. Please remove once WebKit bug is fixed. - * https://bugs.webkit.org/show_bug.cgi?id=63367 - */ -html[dir='rtl'] input.weakrtl::-webkit-input-placeholder, -html[dir='rtl'] .weakrtl input::-webkit-input-placeholder { - direction: rtl; -} diff --git a/chromium/chrome-resources/css/widgets.css b/chromium/chrome-resources/css/widgets.css deleted file mode 100644 index d319b049a7b1..000000000000 --- a/chromium/chrome-resources/css/widgets.css +++ /dev/null @@ -1,305 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -/* This file defines styles for form controls. The order of rule blocks is - * important as there are some rules with equal specificity that rely on order - * as a tiebreaker. These are marked with OVERRIDE. */ - -/* Default state **************************************************************/ - -:-webkit-any(button, - input[type='button'], - input[type='submit']):not(.custom-appearance):not(.link-button), -select, -input[type='checkbox'], -input[type='radio'] { - -webkit-appearance: none; - -webkit-user-select: none; - background-image: -webkit-linear-gradient(#ededed, #ededed 38%, #dedede); - border: 1px solid rgba(0, 0, 0, 0.25); - border-radius: 2px; - box-shadow: 0 1px 0 rgba(0, 0, 0, 0.08), - inset 0 1px 2px rgba(255, 255, 255, 0.75); - color: #444; - font: inherit; - margin: 0 1px 0 0; - text-shadow: 0 1px 0 rgb(240, 240, 240); -} - -:-webkit-any(button, - input[type='button'], - input[type='submit']):not(.custom-appearance):not(.link-button), -select { - min-height: 2em; - min-width: 4em; - - /* The following platform-specific rule is necessary to get adjacent - * buttons, text inputs, and so forth to align on their borders while also - * aligning on the text's baselines. */ - padding-bottom: 1px; - -} - -:-webkit-any(button, - input[type='button'], - input[type='submit']):not(.custom-appearance):not(.link-button) { - -webkit-padding-end: 10px; - -webkit-padding-start: 10px; -} - -select { - -webkit-appearance: none; - -webkit-padding-end: 20px; - -webkit-padding-start: 6px; - /* OVERRIDE */ - background-image: url('../images/select.png'), - -webkit-linear-gradient(#ededed, #ededed 38%, #dedede); - background-position: right center; - background-repeat: no-repeat; -} - -html[dir='rtl'] select { - background-position: center left; -} - -input[type='checkbox'] { - bottom: 2px; - height: 13px; - position: relative; - vertical-align: middle; - width: 13px; -} - -input[type='radio'] { - /* OVERRIDE */ - border-radius: 100%; - bottom: 3px; - height: 15px; - position: relative; - vertical-align: middle; - width: 15px; -} - -/* TODO(estade): add more types here? */ -input[type='password'], -input[type='search'], -input[type='text'], -input[type='url'], -input:not([type]), -textarea { - border: 1px solid #bfbfbf; - border-radius: 2px; - box-sizing: border-box; - color: #444; - font: inherit; - margin: 0; - /* Use min-height to accommodate addditional padding for touch as needed. */ - min-height: 2em; - padding: 3px; - - /* For better alignment between adjacent buttons and inputs. */ - padding-bottom: 4px; - -} - -input[type='search'] { - -webkit-appearance: textfield; - /* NOTE: Keep a relatively high min-width for this so we don't obscure the end - * of the default text in relatively spacious languages (i.e. German). */ - min-width: 160px; -} - -/* Remove when https://bugs.webkit.org/show_bug.cgi?id=51499 is fixed. - * TODO(dbeam): are there more types that would benefit from this? */ -input[type='search']::-webkit-textfield-decoration-container { - direction: inherit; -} - -/* Checked ********************************************************************/ - -input[type='checkbox']:checked::before { - -webkit-user-select: none; - background-image: url('../images/check.png'); - background-size: 100% 100%; - content: ''; - display: block; - height: 100%; - width: 100%; -} - -input[type='radio']:checked::before { - background-color: #666; - border-radius: 100%; - bottom: 3px; - content: ''; - display: block; - left: 3px; - position: absolute; - right: 3px; - top: 3px; -} - -/* Hover **********************************************************************/ - -:enabled:hover:-webkit-any( - select, - input[type='checkbox'], - input[type='radio'], - :-webkit-any( - button, - input[type='button'], - input[type='submit']):not(.custom-appearance):not(.link-button)) { - background-image: -webkit-linear-gradient(#f0f0f0, #f0f0f0 38%, #e0e0e0); - border-color: rgba(0, 0, 0, 0.3); - box-shadow: 0 1px 0 rgba(0, 0, 0, 0.12), - inset 0 1px 2px rgba(255, 255, 255, 0.95); - color: black; -} - -:enabled:hover:-webkit-any(select) { - /* OVERRIDE */ - background-image: url('../images/select.png'), - -webkit-linear-gradient(#f0f0f0, #f0f0f0 38%, #e0e0e0); -} - -/* Active *********************************************************************/ - -:enabled:active:-webkit-any( - select, - input[type='checkbox'], - input[type='radio'], - :-webkit-any( - button, - input[type='button'], - input[type='submit']):not(.custom-appearance):not(.link-button)) { - background-image: -webkit-linear-gradient(#e7e7e7, #e7e7e7 38%, #d7d7d7); - box-shadow: none; - text-shadow: none; -} - -:enabled:active:-webkit-any(select) { - /* OVERRIDE */ - background-image: url('../images/select.png'), - -webkit-linear-gradient(#e7e7e7, #e7e7e7 38%, #d7d7d7); -} - -/* Disabled *******************************************************************/ - -:disabled:-webkit-any( - button, - input[type='button'], - input[type='submit']):not(.custom-appearance):not(.link-button), -select:disabled { - background-image: -webkit-linear-gradient(#f1f1f1, #f1f1f1 38%, #e6e6e6); - border-color: rgba(80, 80, 80, 0.2); - box-shadow: 0 1px 0 rgba(80, 80, 80, 0.08), - inset 0 1px 2px rgba(255, 255, 255, 0.75); - color: #aaa; -} - -select:disabled { - /* OVERRIDE */ - background-image: url('../images/disabled_select.png'), - -webkit-linear-gradient(#f1f1f1, #f1f1f1 38%, #e6e6e6); -} - -input:disabled:-webkit-any([type='checkbox'], - [type='radio']) { - opacity: .75; -} - -input:disabled:-webkit-any([type='password'], - [type='search'], - [type='text'], - [type='url'], - :not([type])) { - color: #999; -} - -/* Focus **********************************************************************/ - -:enabled:focus:-webkit-any( - select, - input[type='checkbox'], - input[type='password'], - input[type='radio'], - input[type='search'], - input[type='text'], - input[type='url'], - input:not([type]), - :-webkit-any( - button, - input[type='button'], - input[type='submit']):not(.custom-appearance):not(.link-button)) { - /* OVERRIDE */ - -webkit-transition: border-color 200ms; - /* We use border color because it follows the border radius (unlike outline). - * This is particularly noticeable on mac. */ - border-color: rgb(77, 144, 254); - outline: none; -} - -/* Link buttons ***************************************************************/ - -.link-button { - -webkit-box-shadow: none; - background: transparent none; - border: none; - color: rgb(17, 85, 204); - cursor: pointer; - /* Input elements have -webkit-small-control which can override the body font. - * Resolve this by using 'inherit'. */ - font: inherit; - margin: 0; - padding: 0 4px; -} - -.link-button:hover { - text-decoration: underline; -} - -.link-button:active { - color: rgb(5, 37, 119); - text-decoration: underline; -} - -.link-button[disabled] { - color: #999; - cursor: default; - text-decoration: none; -} - -/* Checkbox/radio helpers ****************************************************** - * - * .checkbox and .radio classes wrap labels. Checkboxes and radios should use - * these classes with the markup structure: - * - *
- * - *
- */ - -:-webkit-any(.checkbox, .radio) label { - /* Don't expand horizontally: . */ - display: -webkit-inline-box; - padding-bottom: 7px; - padding-top: 7px; -} - -:-webkit-any(.checkbox, .radio) label input ~ span { - -webkit-margin-start: 0.6em; - /* Make sure long spans wrap at the same horizontal position they start. */ - display: block; -} - -:-webkit-any(.checkbox, .radio) label:hover { - color: black; -} - -label > input:disabled:-webkit-any([type='checkbox'], [type='radio']) ~ span { - color: #999; -} diff --git a/chromium/chrome-resources/images/check.png b/chromium/chrome-resources/images/check.png deleted file mode 100644 index 0321d1b45d94..000000000000 Binary files a/chromium/chrome-resources/images/check.png and /dev/null differ diff --git a/chromium/chrome-resources/update-from-chrome-svn.sh b/chromium/chrome-resources/update-from-chrome-svn.sh deleted file mode 100755 index a5225ade2816..000000000000 --- a/chromium/chrome-resources/update-from-chrome-svn.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/sh - -HOST='https://src.chromium.org' -BASE='chrome/trunk/src/ui/webui/resources' -FILES=' -css/chrome_shared.css -css/widgets.css -images/check.png' - -for FILE in $FILES; do - wget --force-directories --no-host-directories --cut-dirs=6 $HOST/$BASE/$FILE -done - diff --git a/chromium/devtools-panel.html b/chromium/devtools-panel.html index 1fcb5e8026bc..4cfbd9a14550 100644 --- a/chromium/devtools-panel.html +++ b/chromium/devtools-panel.html @@ -1,32 +1,24 @@ - - - - - -
- - -

-

- Switch Planner mode helps prepare for your site's switch to HTTPS by generating - a report of external HTTP resources that might not yet be available on HTTPS. -

- After enabling, navigate around your site and try to exercise all - functionality in order to get a comprehensive list of external resources. -

- For each group of resources listed as "Unrewritten," find out whether they - are available on HTTPS. If so: add a rule to HTTPS Everywhere! If not: try - to make them available over HTTPS or use a different resource or provider. - Otherwise your site will generate - Mixed Content - (passive or active) errors when you turn on HTTPS. -

- For most accurate results, disable ad blockers before using. Closing this - panel will deactivate Switch Planner mode and clear stored data. + + + + + + + +

+ + +
+

Switch Planner mode helps prepare for your site's switch to HTTPS by generating a report of external HTTP resources that might not yet be available on HTTPS.

+

After enabling, navigate around your site and try to exercise all functionality in order to get a comprehensive list of external resources.

+

For each group of resources listed as "Unrewritten," find out whether they are available on HTTPS. If so: add a rule to HTTPS Everywhere! If not: try to make them available over HTTPS or use a different resource or provider. Otherwise your site will generate Mixed Content (passive or active) errors when you turn on HTTPS.

+

For most accurate results, disable ad blockers before using. Closing this panel will deactivate Switch Planner mode and clear stored data.

+
+
- -
- + + + diff --git a/chromium/devtools-panel.js b/chromium/devtools-panel.js index db216dbeb27b..2f455880f4aa 100644 --- a/chromium/devtools-panel.js +++ b/chromium/devtools-panel.js @@ -1,6 +1,4 @@ -function e(id) { - return document.getElementById(id); -} +'use strict'; /** * Send message to main extension for HTML to display @@ -17,12 +15,14 @@ function sendMessage(type) { * Turn on the Switch Planner recording mode, and hide the long description. */ function enableSwitchPlanner() { - sendMessage("enable"); - e("SwitchPlannerDescription").style.display = "none"; - e("SwitchPlannerDetails").style.display = "block"; + sendMessage('enable'); + document.getElementById('SwitchPlannerDescription').style.display = 'none'; + document.getElementById('SwitchPlannerDetails').style.display = 'block'; + // Hack: Fetch and display summary information from background page // once per second. - setInterval(display, 1000); + + setInterval(update, 1000); chrome.devtools.inspectedWindow.reload(); } @@ -31,7 +31,7 @@ function enableSwitchPlanner() { * the long description is restored. */ function disableSwitchPlanner() { - sendMessage("disable"); + sendMessage('disable'); document.location.reload(); } @@ -39,26 +39,28 @@ function disableSwitchPlanner() { * Fetch summary HTML of the planner results from the background page for * display in the devtools panel. */ -function display() { +function update() { chrome.runtime.sendMessage({ - type: "getSmallHtml", + type: 'getSmallHtml', tabId: chrome.devtools.inspectedWindow.tabId, - }, function(response) { - e("SwitchPlannerDetails").innerHTML = response.html; - e("SwitchPlannerResults").style.display = "block"; + }, response => { + document.getElementById('SwitchPlannerDetails').innerHTML = response.html; + document.getElementById('SwitchPlannerResults').style.display = 'block'; }); } -window.onload = function() { +document.addEventListener('DOMContentLoaded', () => { // Open a connection to the background page. Right now this is only used // by the background page so it knows when the devtools pane has closed. // We don't receive messages from the background page currently, though that // may be a future improvement. Sending messages to the background page doesn't // require an existing connection. - chrome.runtime.connect({ name: "devtools-page" }); - var checkbox = e("SwitchPlannerCheckbox"); - checkbox.addEventListener("change", function() { + chrome.runtime.connect({ name: 'devtools-page' }); + + var checkbox = document.getElementById('SwitchPlannerCheckbox'); + + checkbox.addEventListener('change', () => { if (checkbox.checked) { enableSwitchPlanner(); } else { @@ -66,12 +68,14 @@ window.onload = function() { } }); - e("SwitchPlannerDetailsLink").addEventListener("click", function() { - window.open("switch-planner.html?tab=" + chrome.devtools.inspectedWindow.tabId); + document.getElementById('SwitchPlannerDetailsLink').addEventListener('click', () => { + window.open('switch-planner.html?tab=' + chrome.devtools.inspectedWindow.tabId); }); + // Since this is rendered in a devtools console, we have to make clicks on the // link open a new window. - e("MixedContentLink").addEventListener("click", function(e) { + + document.getElementById('MixedContentLink').addEventListener('click', e => { window.open(e.target.href); }); -}; +}); diff --git a/chromium/devtools.html b/chromium/devtools.html index e90b4905627d..0a30bc85e678 100644 --- a/chromium/devtools.html +++ b/chromium/devtools.html @@ -1,6 +1,10 @@ - - - - - - + + + + + + + + + + diff --git a/chromium/devtools.js b/chromium/devtools.js index 343bee094295..ab1985f37478 100644 --- a/chromium/devtools.js +++ b/chromium/devtools.js @@ -1,6 +1,7 @@ -chrome.devtools.panels.create("HTTPS Everywhere", - "icons/icon-active-38.png", - "devtools-panel.html", - function(panel) { - } +'use strict'; + +chrome.devtools.panels.create('HTTPS Everywhere', + 'icons/icon-active-38.png', + 'devtools-panel.html', + function (panel) {} ); diff --git a/chromium/incognito-cache-clearing.js b/chromium/incognito-cache-clearing.js index b650253c317a..83d9bafcec83 100644 --- a/chromium/incognito-cache-clearing.js +++ b/chromium/incognito-cache-clearing.js @@ -1,4 +1,5 @@ -"use strict"; +'use strict'; + // This file keeps track of incognito sessions, and clears any caches after // an entire incognito session is closed (i.e. all incognito windows are closed). @@ -20,7 +21,7 @@ function detect_incognito_creation(window) { * Called if an incognito session is destroyed. */ function destroy_caches() { - log(DBUG, "Destroying caches."); + log(DBUG, 'Destroying caches.'); all_rules.cookieHostCache.clear(); all_rules.ruleCache.clear(); } diff --git a/chromium/manifest.json b/chromium/manifest.json index a3d91a79311c..a551129e56ac 100644 --- a/chromium/manifest.json +++ b/chromium/manifest.json @@ -6,7 +6,7 @@ "scripts": [ "rules.js", "storage.js", - "util.js", + "utils.js", "background.js", "incognito-cache-clearing.js" ] diff --git a/chromium/popup.html b/chromium/popup.html index 2a400c5a7bd0..549ab009311a 100644 --- a/chromium/popup.html +++ b/chromium/popup.html @@ -1,72 +1,59 @@ + - - - - - - - - - - - - - - -
-

-
- -
-
+ + + HTTPS Everywhere + + + +
+

+
+
+
- -
-
-
- - -
- -
-
- - -
-
-

-

+ +
-
-

-

+
+ +
-
- - - - +
+
+ + +
+
+

+

+
+
+

+

+
+
+ + + diff --git a/chromium/popup.js b/chromium/popup.js index 6289e8fb06ba..6bd690b638fa 100644 --- a/chromium/popup.js +++ b/chromium/popup.js @@ -1,22 +1,14 @@ -"use strict"; +'use strict'; var backgroundPage = chrome.extension.getBackgroundPage(); var stableRules = null; var unstableRules = null; var hostReg = /.*\/\/[^$/]*\//; -var storage = backgroundPage.storage; -function e(id) { - return document.getElementById(id); -} +const storage = chrome.storage.sync || chrome.storage.local; -/** - * Handles rule (de)activation in the popup - * @param checkbox checkbox being clicked - * @param ruleset the ruleset tied tot he checkbox - */ -function toggleRuleLine(checkbox, ruleset) { - ruleset.active = checkbox.checked; +function setRulesetActive(ruleset, active) { + ruleset.active = active; if (ruleset.active != ruleset.default_state) { localStorage[ruleset.name] = ruleset.active; @@ -35,220 +27,164 @@ function toggleRuleLine(checkbox, ruleset) { * @returns {*} */ function appendRuleLineToListDiv(ruleset, list_div) { - // parent block for line - var line = document.createElement("div"); - line.className = "rule checkbox"; + var line = document.createElement('div'); + line.className = 'rule checkbox'; - // label "container" - var label = document.createElement("label"); + // label 'container' + var 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); - }; + var 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/"; + var favicon = document.createElement('img'); + favicon.className = 'favicon'; + for (let rule of ruleset.rules) { var host = hostReg.exec(rule.to); if (host) { - favicon.src += host[0]; + favicon.src = 'chrome://favicon/' + host[0]; break; } } - 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"); + var text = document.createElement('span'); text.innerText = ruleset.name; + if (ruleset.note.length) { text.title = ruleset.note; } - if(ruleset.note == "user rule") { - var remove = document.createElement("img"); - remove.src = chrome.extension.getURL("remove.png"); - remove.className = "remove"; + if(ruleset.note == 'user rule') { + var remove = document.createElement('img'); + remove.src = chrome.extension.getURL('remove.png'); + remove.className = 'remove'; line.appendChild(remove); - remove.addEventListener("click", function(){ + 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() { +/** + * 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, currentWindow: true }, tabArray => { + var activeTab = tabArray[0]; + var rulesets = backgroundPage.activeRulesets.getRulesets(activeTab.id); + + for (var r in rulesets) { + var listDiv = stableRules; + if (!rulesets[r].default_state) { + listDiv = unstableRules; + } + appendRuleLineToListDiv(rulesets[r], listDiv); + listDiv.style.position = 'static'; + listDiv.style.visibility = 'visible'; + } + // Only show the 'Add a rule' link if we're on an HTTPS page + if (/^https:/.test(activeTab.url)) { + document.getElementById('add-rule-link').style.display = 'block'; + } + }); + + // Set up the enabled/disabled switch & hide/show rules document.getElementById('onoffswitch').checked = backgroundPage.isExtensionEnabled; - // Hide or show the rules sections - if (backgroundPage.isExtensionEnabled) { - document.body.className = "" - } else { - document.body.className = "disabled" - } - backgroundPage.updateState(); -} -// Toggle extension enabled/disabled status -function toggleEnabledDisabled() { + // Hide or show the rules sections if (backgroundPage.isExtensionEnabled) { - // User wants to disable us - backgroundPage.isExtensionEnabled = false; + document.body.className = '' } else { - // User wants to enable us - backgroundPage.isExtensionEnabled = true; + document.body.className = 'disabled' } - updateEnabledDisabledUI(); - // The extension state changed, so reload this tab. - chrome.tabs.reload(); - window.close(); -} -/** - * Create the list of rules for a specific tab - * @param tabArray - */ -function gotTab(tabArray) { - var activeTab = tabArray[0]; - var rulesets = backgroundPage.activeRulesets.getRulesets(activeTab.id); - - for (var r in rulesets) { - var listDiv = stableRules; - if (!rulesets[r].default_state) { - listDiv = unstableRules; - } - appendRuleLineToListDiv(rulesets[r], listDiv); - listDiv.style.position = "static"; - listDiv.style.visibility = "visible"; - } - // Only show the "Add a rule" link if we're on an HTTPS page - if (/^https:/.test(activeTab.url)) { - show(e("add-rule-link")); - } -} - -/** - * 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, currentWindow: true }, gotTab); + document.getElementById('onoffswitch').addEventListener('change', evt => { + // The extension state changed, so reload this tab. + backgroundPage.updateState(); - // Set up the enabled/disabled switch & hide/show rules - updateEnabledDisabledUI(); - document.getElementById('onoffswitch').addEventListener('click', toggleEnabledDisabled); + chrome.tabs.reload(); + window.close(); + }); // 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; + document.getElementById('current-version').innerText = chrome.runtime.getManifest().version; // Set up toggle checkbox for HTTP nowhere mode - getOption_('httpNowhere', false, function(item) { + getOption_('httpNowhere', false, item => { var httpNowhereCheckbox = document.getElementById('http-nowhere-checkbox'); - httpNowhereCheckbox.addEventListener('click', toggleHttpNowhere, false); - var httpNowhereEnabled = item.httpNowhere; - if (httpNowhereEnabled) { - httpNowhereCheckbox.setAttribute('checked', ''); - } + httpNowhereCheckbox.checked = item.httpNowhere; + httpNowhereCheckbox.addEventListener('change', toggleHttpNowhere, false); }); - // 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")); + // auto-translate all elements with data-i18n attributes + var elements = document.querySelectorAll('[data-i18n]'); + for (const element of elements) { + el.innerText = chrome.i18n.getMessage(el.getAttribute('data-i18n')); } // other translations - e("aboutTitle").setAttribute("title", chrome.i18n.getMessage("about_title")); - e("add-rule-link").addEventListener("click", addManualRule); + document.getElementById('aboutTitle').setAttribute('title', chrome.i18n.getMessage('about_title')); + document.getElementById('add-rule-link').addEventListener('click', addManualRule); }); - -var escapeForRegex = function( value ) { - return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); -}; - -function hide(elem) { - elem.style.display = "none"; -} - -function show(elem) { - elem.style.display = "block"; -} - /** * 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 - }; - backgroundPage.addNewRule(params, function() { + 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(); }); }); - e("cancel-new-rule").addEventListener("click", function() { - show(e("add-rule-link")); - hide(e("add-new-rule-div")); + document.getElementById('cancel-new-rule').addEventListener('click', () => { + document.getElementById('add-rule-link').style.display = 'block'; + document.getElementById('add-new-rule-div').style.display = 'none'; }); - e("new-rule-show-advanced-link").addEventListener("click", function() { - show(e("new-rule-advanced")); - hide(e("new-rule-regular-text")); + 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'; }); - e("new-rule-hide-advanced-link").addEventListener("click", function() { - hide(e("new-rule-advanced")); - show(e("new-rule-regular-text")); + document.getElementById('new-rule-hide-advanced-link').addEventListener('click', () => { + document.getElementById('new-rule-regular-text').style.display = 'block'; + document.getElementById('new-rule-advanced').style.display = 'none'; }); }); } -function toggleHttpNowhere() { - getOption_('httpNowhere', false, function(item) { - setOption_('httpNowhere', !item.httpNowhere); - }); -} - function getOption_(opt, defaultOpt, callback) { var details = {}; details[opt] = defaultOpt; diff --git a/chromium/rules.js b/chromium/rules.js index 896ebe8670e3..3a070fd2626a 100644 --- a/chromium/rules.js +++ b/chromium/rules.js @@ -1,17 +1,23 @@ -"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(){} +'use strict'; + +let utils = { + log (msg) { + console.log(msg); + } +}; + +if (typeof window !== 'undefined') { + utils = window.utils || utils; +} + +if (typeof require !== 'undefined') { + utils = require('./utils.js') || utils; +} // 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(".*"); +const trivial_rule_to = 'https:'; +const trivial_rule_from_c = /^http:/; +const trivial_cookie_c = /.+/; /** * A single rule @@ -20,7 +26,7 @@ const trivial_cookie_host_c = new RegExp(".*"); * @constructor */ function Rule(from, to) { - if (from === "^http:" && to === "https:") { + 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; @@ -47,16 +53,16 @@ function Exclusion(pattern) { * @constructor */ function CookieRule(host, cookiename) { - if (host === ".*" || host === ".+" || host === ".") { + if (host === '.*' || host === '.+' || host === '.') { // Some cookie rules trivially match any host. - this.host_c = trivial_cookie_host_c; + this.host_c = trivial_cookie_c; } else { this.host_c = new RegExp(host); } - if (cookiename === ".*" || cookiename === ".+" || cookiename === ".") { + if (cookiename === '.*' || cookiename === '.+' || cookiename === '.') { // About 50% of cookie rules trivially match any name. - this.name_c = trivial_cookie_name_c; + this.name_c = trivial_cookie_c; } else { this.name_c = new RegExp(cookiename); } @@ -91,7 +97,7 @@ RuleSet.prototype = { if (this.exclusions !== null) { for (let exclusion of this.exclusions) { if (exclusion.pattern_c.test(urispec)) { - log(DBUG, "excluded uri " + urispec); + utils.log('excluded uri ' + urispec, 1); return null; } } @@ -193,12 +199,12 @@ RuleSets.prototype = { * Iterate through data XML and load rulesets */ addFromXml: function(ruleXml) { - var sets = ruleXml.getElementsByTagName("ruleset"); + var sets = ruleXml.getElementsByTagName('ruleset'); for (let s of sets) { try { this.parseOneRuleset(s); } catch (e) { - log(WARN, 'Error processing ruleset:' + e); + utils.log('Error processing ruleset:' + e, 5); } } }, @@ -209,8 +215,8 @@ RuleSets.prototype = { * @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"); + utils.log('adding new user rule for ' + JSON.stringify(params), 2); + 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)) { @@ -220,9 +226,9 @@ RuleSets.prototype = { // 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"); + new_rule_set.active = (this.ruleActiveStates[new_rule_set.name] == 'true'); } - log(INFO, 'done adding rule'); + utils.log('done adding rule', 2); return true; }, @@ -232,7 +238,7 @@ RuleSets.prototype = { * @returns {boolean} */ removeUserRule: function(ruleset) { - log(INFO, 'removing user rule for ' + JSON.stringify(ruleset)); + utils.log('removing user rule for ' + JSON.stringify(ruleset), 2); this.ruleCache.delete(ruleset.name); this.targets[ruleset.name] = this.targets[ruleset.name].filter(r => !(r.isEquivalentTo(ruleset)) @@ -240,7 +246,7 @@ RuleSets.prototype = { if (this.targets[ruleset.name].length == 0) { delete this.targets[ruleset.name]; } - log(INFO, 'done removing rule'); + utils.log('done removing rule', 2); return true; }, @@ -250,61 +256,61 @@ RuleSets.prototype = { */ parseOneRuleset: function(ruletag) { var default_state = true; - var note = ""; - var default_off = ruletag.getAttribute("default_off"); + var note = ''; + var default_off = ruletag.getAttribute('default_off'); if (default_off) { default_state = false; - note += default_off + "\n"; + 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"); + // off-by-default. In practice, this excludes 'mixedcontent' & 'cacert' rules. + var platform = ruletag.getAttribute('platform'); if (platform) { default_state = false; - if (platform == "mixedcontent" && enableMixedRulesets) { + if (platform == 'mixedcontent' && enableMixedRulesets) { default_state = true; } - note += "Platform(s): " + platform + "\n"; + note += 'Platform(s): ' + platform + '\n'; } - var rule_set = new RuleSet(ruletag.getAttribute("name"), + var rule_set = new RuleSet(ruletag.getAttribute('name'), default_state, note.trim()); // Read user prefs if (rule_set.name in this.ruleActiveStates) { - rule_set.active = (this.ruleActiveStates[rule_set.name] == "true"); + rule_set.active = (this.ruleActiveStates[rule_set.name] == 'true'); } - var rules = ruletag.getElementsByTagName("rule"); + var rules = ruletag.getElementsByTagName('rule'); for (let rule of rules) { - rule_set.rules.push(new Rule(rule.getAttribute("from"), - rule.getAttribute("to"))); + rule_set.rules.push(new Rule(rule.getAttribute('from'), + rule.getAttribute('to'))); } - var exclusions = ruletag.getElementsByTagName("exclusion"); + var exclusions = ruletag.getElementsByTagName('exclusion'); if (exclusions.length > 0) { rule_set.exclusions = []; for (let exclusion of exclusions) { rule_set.exclusions.push( - new Exclusion(exclusion.getAttribute("pattern"))); + new Exclusion(exclusion.getAttribute('pattern'))); } } - var cookierules = ruletag.getElementsByTagName("securecookie"); + var cookierules = ruletag.getElementsByTagName('securecookie'); if (cookierules.length > 0) { rule_set.cookierules = []; for (let cookierule of cookierules) { rule_set.cookierules.push( - new CookieRule(cookierule.getAttribute("host"), - cookierule.getAttribute("name"))); + new CookieRule(cookierule.getAttribute('host'), + cookierule.getAttribute('name'))); } } - var targets = ruletag.getElementsByTagName("target"); + var targets = ruletag.getElementsByTagName('target'); for (let target of targets) { - var host = target.getAttribute("host"); + var host = target.getAttribute('host'); if (!(host in this.targets)) { this.targets[host] = []; } @@ -321,10 +327,10 @@ RuleSets.prototype = { // 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); + utils.log('Ruleset cache hit for ' + host + ' items:' + cached_item.length, 1); return cached_item; } - log(DBUG, "Ruleset cache miss for " + host); + utils.log('Ruleset cache miss for ' + host, 1); var tmp; var results = []; @@ -334,23 +340,23 @@ RuleSets.prototype = { } // Ensure host is well-formed (RFC 1035) - if (host.indexOf("..") != -1 || host.length > 255) { - log(WARN,"Malformed host passed to potentiallyApplicableRulesets: " + host); + if (host.indexOf('..') != -1 || host.length > 255) { + utils.log('Malformed host passed to potentiallyApplicableRulesets: ' + host, 4); return null; } // Replace each portion of the domain with a * in turn - var segmented = host.split("."); + var segmented = host.split('.'); for (let s of segmented) { tmp = s; - s = "*"; - results = results.concat(this.targets[segmented.join(".")]); + s = '*'; + results = results.concat(this.targets[segmented.join('.')]); s = tmp; } // 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("."); + var t = '*.' + segmented.slice(i,segmented.length).join('.'); results = results.concat(this.targets[t]); } @@ -358,12 +364,12 @@ RuleSets.prototype = { var resultSet = new Set(results); resultSet.delete(undefined); - log(DBUG,"Applicable rules for " + host + ":"); + utils.log('Applicable rules for ' + host + ':', 1); if (resultSet.size == 0) { - log(DBUG, " None"); + utils.log(' None', 1); } else { for (let target of resultSet.values()) { - log(DBUG, " " + target.name); + utils.log(' ' + target.name, 1); } } @@ -387,7 +393,7 @@ RuleSets.prototype = { shouldSecureCookie: function(cookie) { var hostname = cookie.domain; // cookie domain scopes can start with . - while (hostname.charAt(0) == ".") { + while (hostname[0] === '.') { hostname = hostname.slice(1); } @@ -428,21 +434,21 @@ RuleSets.prototype = { // flagged as secure. if (domainBlacklist.has(domain)) { - log(INFO, "cookies for " + domain + "blacklisted"); + utils.log('cookies for ' + domain + 'blacklisted', 2); return false; } var cached_item = this.cookieHostCache.get(domain); if (cached_item !== undefined) { - log(DBUG, "Cookie host cache hit for " + domain); + utils.log('Cookie host cache hit for ' + domain, 1); return cached_item; } - log(DBUG, "Cookie host cache miss for " + domain); + utils.log('Cookie host cache miss for ' + domain, 1); // If we passed that test, make up a random URL on the domain, and see if // we would HTTPSify that. - var nonce_path = "/" + Math.random().toString(); - var test_uri = "http://" + domain + nonce_path + nonce_path; + 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) { @@ -450,19 +456,19 @@ RuleSets.prototype = { this.cookieHostCache.delete(this.cookieHostCache.keys().next().value); } - log(INFO, "Testing securecookie applicability with " + test_uri); + utils.log('Testing securecookie applicability with ' + test_uri, 2); 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."); + utils.log('Cookie domain could be secured.', 2); this.cookieHostCache.set(domain, true); return true; } } - log(INFO, "Cookie domain could NOT be secured."); + utils.log('Cookie domain could NOT be secured.', 2); this.cookieHostCache.set(domain, false); return false; }, @@ -485,7 +491,6 @@ RuleSets.prototype = { } }; -// Export for HTTPS Rewriter if applicable. -if (typeof exports != 'undefined') { - exports.RuleSets = RuleSets; +if (typeof module !== 'undefined') { + module.exports = { Rule, Exclusion, CookieRule, RuleSet, RuleSets }; } diff --git a/chromium/storage.js b/chromium/storage.js deleted file mode 100644 index 2597ca379fba..000000000000 --- a/chromium/storage.js +++ /dev/null @@ -1,7 +0,0 @@ -var storage = chrome.storage.local; -if (chrome.storage.sync) { - storage = chrome.storage.sync; -} -if (typeof exports != 'undefined') { - exports = storage; -} diff --git a/chromium/switch-planner.html b/chromium/switch-planner.html index 87fe4b5ef13a..4ad0f6a82481 100644 --- a/chromium/switch-planner.html +++ b/chromium/switch-planner.html @@ -1,7 +1,11 @@ - - - - - -
- + + + + + Switch planner + + +
+ + + diff --git a/chromium/switch-planner.js b/chromium/switch-planner.js index 5ed4d8381f70..67caf0023197 100644 --- a/chromium/switch-planner.js +++ b/chromium/switch-planner.js @@ -1,7 +1,5 @@ -window.onload = function() { +document.addEventListener('DOMContentLoaded', () => { var backgroundPage = chrome.extension.getBackgroundPage(); var tab = document.location.search.match(/tab=([^&]*)/)[1]; - document.getElementById("content").innerHTML = - backgroundPage.switchPlannerDetailsHtml(tab); -}; - + document.getElementById('content').innerHTML = backgroundPage.switchPlannerDetailsHtml(tab); +}); diff --git a/chromium/util.js b/chromium/util.js deleted file mode 100644 index 6ecb52b6b2c9..000000000000 --- a/chromium/util.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; - -var VERB = 1; -var DBUG = 2; -var INFO = 3; -var NOTE = 4; -var WARN = 5; -// FYI: Logging everything is /very/ slow. Chrome will log & buffer -// these console logs even when the debug tools are closed. :( - -// TODO: Add an easy UI to change the log level. -// (Developers can just type DEFAULT_LOG_LEVEL=VERB in the console) -var DEFAULT_LOG_LEVEL = NOTE; -console.log("Hey developer! Want to see more verbose logging?"); -console.log("Type this into the console: DEFAULT_LOG_LEVEL=VERB"); -console.log("Accepted levels are VERB, DBUG, INFO, NOTE and WARN, default is NOTE"); - -function log(level, str) { - if (level >= DEFAULT_LOG_LEVEL) { - if (level === WARN) { - // Show warning with a little yellow icon in Chrome. - console.warn(str); - } else { - console.log(str); - } - } -} diff --git a/chromium/utils.js b/chromium/utils.js new file mode 100644 index 000000000000..f9c9583da4ef --- /dev/null +++ b/chromium/utils.js @@ -0,0 +1,37 @@ +'use strict'; + +// Logging everything is *very* slow since the browser will retain console logs even when the developer tools window is closed. + +if (typeof window !== 'undefined') { + console.log('Hey developer! Want to see more verbose logging?'); + console.log('Type this into the console: utils.minLogLevel = 1'); + console.log('Accepted levels are 1-5, default is 4.'); +} + +const utils = { + minLogLevel: 4, + + log (str, level) { + level = level || 1; + + if (level >= utils.minLogLevel) { + if (level >= 5) { + console.error(str); + } else if (level >= 4) { + console.warn(str); + } else if (level >= 3) { + console.info(str); + } else { + console.log(str); + } + } + } +} + +if (typeof window !== 'undefined') { + window.utils = utils; +} + +if (typeof module !== 'undefined') { + module.exports = utils; +}