├── src ├── img │ └── icon │ │ ├── mitm_on_32.png │ │ └── mitm_on_64.png └── page │ ├── background │ ├── js │ │ ├── class │ │ │ ├── BrowserAction.js │ │ │ ├── Tabs.js │ │ │ ├── Logger.js │ │ │ ├── UUID.js │ │ │ ├── Interpreter.js │ │ │ ├── BlockingRule.js │ │ │ ├── Storage.js │ │ │ ├── Rule.js │ │ │ ├── RequestRule.js │ │ │ ├── ContentScript.js │ │ │ ├── ResponseRule.js │ │ │ ├── Factory.js │ │ │ └── HeaderRule.js │ │ └── background.js │ ├── background.html │ └── frame │ │ └── sandbox.html │ ├── options │ ├── js │ │ ├── options.js │ │ └── class │ │ │ ├── Information.js │ │ │ ├── DOM.js │ │ │ └── Collection.js │ ├── css │ │ ├── layout.css │ │ ├── normalize.css │ │ └── input.css │ └── options.html │ └── shared │ └── js │ └── class │ ├── Runtime.js │ ├── Binder.js │ └── Utils.js ├── manifest.json ├── README.md └── LICENSE /src/img/icon/mitm_on_32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dangkyokhoang/man-in-the-middle/HEAD/src/img/icon/mitm_on_32.png -------------------------------------------------------------------------------- /src/img/icon/mitm_on_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dangkyokhoang/man-in-the-middle/HEAD/src/img/icon/mitm_on_64.png -------------------------------------------------------------------------------- /src/page/background/js/class/BrowserAction.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | class BrowserAction { 4 | /** 5 | * @param {Function} listener 6 | * @return {void} 7 | */ 8 | static addListener(listener) { 9 | browser.browserAction.onClicked.addListener(listener); 10 | } 11 | } 12 | 13 | Binder.bind(BrowserAction); 14 | -------------------------------------------------------------------------------- /src/page/background/js/class/Tabs.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | class Tabs { 4 | /** 5 | * @return {void} 6 | */ 7 | static openOptionsPage() { 8 | browser.runtime.openOptionsPage().catch(Logger.log); 9 | } 10 | 11 | /** 12 | * Get details of a tab. 13 | * @return {Promise} 14 | */ 15 | static get(tabId) { 16 | return browser.tabs.get(tabId).catch(Logger.log); 17 | } 18 | } 19 | 20 | Binder.bindOwn(Tabs); 21 | -------------------------------------------------------------------------------- /src/page/options/js/options.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | Information.display(); 4 | 5 | Collection.startup(); 6 | 7 | Runtime.addEventListener('message', async ({sender, command, details}) => { 8 | if (sender !== 'backgroundPage') { 9 | return; 10 | } 11 | 12 | switch (command) { 13 | case 'update': 14 | return Collection.initialize(details.type, details.data); 15 | case 'log': 16 | return console.log(details.message); 17 | } 18 | }); 19 | -------------------------------------------------------------------------------- /src/page/background/js/class/Logger.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Used for debugging purposes. 5 | */ 6 | class Logger { 7 | /** 8 | * @param {*} value 9 | */ 10 | static log(value) { 11 | Runtime.sendMessage({ 12 | sender: 'backgroundPage', 13 | command: 'log', 14 | details: { 15 | message: value instanceof Error ? String(value) : value, 16 | } 17 | }); 18 | } 19 | } 20 | 21 | Binder.bind(Logger); 22 | -------------------------------------------------------------------------------- /src/page/options/js/class/Information.js: -------------------------------------------------------------------------------- 1 | class Information { 2 | /** 3 | * Display extension's information. 4 | * @return {void} 5 | */ 6 | static display() { 7 | Runtime.sendMessage({ 8 | sender: 'optionsPage', 9 | request: 'getInformation', 10 | }).then(information => { 11 | Object.entries(information).forEach(([label, text]) => { 12 | DOM.createNode({ 13 | tagName: 'DIV', 14 | parent: DOM.id('information'), 15 | children: [{ 16 | text: `${label.toUpperCase()} ${text}`, 17 | }], 18 | }); 19 | }); 20 | }); 21 | } 22 | } -------------------------------------------------------------------------------- /src/page/options/css/layout.css: -------------------------------------------------------------------------------- 1 | body { 2 | display: grid; 3 | grid-template-columns: repeat(2, 1fr); 4 | grid-template-rows: 10em 1fr; 5 | } 6 | 7 | body > section { 8 | margin: 0; 9 | padding: 1em 0; 10 | } 11 | 12 | .information { 13 | grid-column: 1 / 2; 14 | grid-row: 1 / 2; 15 | } 16 | 17 | .main { 18 | grid-column: 1 / 3; 19 | grid-row: 2 / 3; 20 | border-top: 1px solid var(--gray-0); 21 | 22 | } 23 | 24 | .help { 25 | grid-column: 2 / 3; 26 | grid-row: 1 / 2; 27 | text-align: right; 28 | } 29 | 30 | @media (max-width: 599px) { 31 | body { 32 | grid-template-columns: auto; 33 | grid-auto-rows: 10em auto auto; 34 | } 35 | 36 | .main { 37 | grid-column: 1 / 2; 38 | border-bottom: 1px solid var(--gray-0); 39 | } 40 | 41 | .help { 42 | grid-column: 1 / 2; 43 | grid-row: 3 / 4; 44 | text-align: initial; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | "name": "Man in the Middle", 4 | "version": "3.5.3", 5 | "description": "Modify requests, inject JavaScript and CSS into pages", 6 | "developer": { 7 | "name": "Hoang", 8 | "url": "https://github.com/dangkyokhoang/man-in-the-middle/" 9 | }, 10 | "applications": { 11 | "gecko": { 12 | "id": "{ce509397-203a-4f0d-a5b0-927d0d1a0e22}" 13 | } 14 | }, 15 | "permissions": [ 16 | "", 17 | "tabs", 18 | "storage", 19 | "unlimitedStorage", 20 | "webNavigation", 21 | "webRequest", 22 | "webRequestBlocking" 23 | ], 24 | "icons": { 25 | "64": "src/img/icon/mitm_on_64.png" 26 | }, 27 | "browser_action": { 28 | "default_icon": { 29 | "32": "src/img/icon/mitm_on_32.png" 30 | } 31 | }, 32 | "background": { 33 | "page": "src/page/background/background.html" 34 | }, 35 | "options_ui": { 36 | "page": "src/page/options/options.html", 37 | "open_in_tab": true 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/page/background/background.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Man in the Middle 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/page/options/css/normalize.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --gray-0: #d8d8d8; 3 | --gray-1: #f2f2f2; 4 | --green-0: #7cff7c; 5 | --green-1: #d7ffd7; 6 | --yellow-0: #fff132; 7 | --yellow-1: #fffac1; 8 | --red-0: #ff9279; 9 | } 10 | 11 | * { 12 | box-sizing: border-box; 13 | margin: 0; 14 | border: 0; 15 | padding: 0; 16 | color: black; 17 | line-height: 1.5; 18 | letter-spacing: 0.0125em; 19 | } 20 | 21 | html, body { 22 | font-size: 11px; 23 | font-family: 'Segoe UI', Arial, sans-serif; 24 | } 25 | 26 | body { 27 | margin: 2em; 28 | } 29 | 30 | h1, h2 { 31 | padding: 0.25em 0; 32 | } 33 | 34 | h1 { 35 | font-size: 2em; 36 | } 37 | 38 | h2 { 39 | font-size: 1.5em; 40 | } 41 | 42 | section, 43 | article { 44 | margin: 1em 0; 45 | } 46 | 47 | div { 48 | margin: 0.5em 0; 49 | } 50 | 51 | span + span { 52 | margin-left: 0.25em; 53 | } 54 | 55 | input, 56 | select, 57 | button { 58 | font: inherit; 59 | min-width: 0; 60 | } 61 | 62 | select { 63 | -moz-appearance: button; 64 | } 65 | 66 | button { 67 | cursor: pointer; 68 | } 69 | 70 | textarea { 71 | font-size: inherit; 72 | font-family: 'Courier New', Courier, monospace; 73 | } 74 | -------------------------------------------------------------------------------- /src/page/shared/js/class/Runtime.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | class Runtime { 4 | /** 5 | * Send message within the extension. 6 | * @param {Object} message 7 | * @return {Promise} 8 | * @see {@link https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/sendMessage} 9 | */ 10 | static sendMessage(message) { 11 | // Ignore the error: Receiving end doesn't exist 12 | return browser.runtime.sendMessage(message).catch(() => {}); 13 | } 14 | 15 | /** 16 | * @param {string} [key] 17 | */ 18 | static getManifest(key) { 19 | const manifest = browser.runtime.getManifest(); 20 | return key ? manifest[key] : manifest; 21 | } 22 | 23 | /** 24 | * @param {string} type 25 | * @param {Function} listener 26 | * @return {void} 27 | */ 28 | static addEventListener(type, listener) { 29 | const event = this.events[type]; 30 | 31 | if (type === 'message') { 32 | event.addListener(async (message, {id}) => { 33 | // As the extension can receive messages from other extensions, 34 | // the sender's identity must be verified. 35 | if (id !== browser.runtime.id) { 36 | return; 37 | } 38 | 39 | return listener(message); 40 | }); 41 | } else { 42 | event.addListener(listener); 43 | } 44 | } 45 | } 46 | 47 | Binder.bind(Runtime); 48 | 49 | Runtime.events = { 50 | 'message': browser.runtime.onMessage, 51 | 'installed': browser.runtime.onInstalled, 52 | }; 53 | -------------------------------------------------------------------------------- /src/page/options/options.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Man in the Middle — Options 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 |

Man in the Middle

15 |
16 |
17 |
18 |

Blocking Rules

19 |
20 |
21 |

Header Rules

22 |
23 |
24 |

Response Rules

25 |
26 |
27 |

Content Scripts

28 |
29 |
30 |
31 |

Help

32 |
33 | 37 | 41 |
42 |
43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/page/shared/js/class/Binder.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * This helps with binding object methods. 5 | * Note that this doesn't work with getters and setters. 6 | */ 7 | class Binder { 8 | /** 9 | * Bind all methods of an object. 10 | * @param {!Object} object 11 | * @return {void} 12 | */ 13 | static bind(object) { 14 | this.bindOwn(object); 15 | this.bindAncestors(object); 16 | } 17 | 18 | /** 19 | * @param {!Object} object 20 | * @return {void} 21 | */ 22 | static bindOwn(object) { 23 | this.getMethods(object).forEach(method => { 24 | object[method] = object[method].bind(object); 25 | }); 26 | } 27 | 28 | /** 29 | * @param {!Object} object 30 | * @return {void} 31 | */ 32 | static bindAncestors(object) { 33 | let ancestor = Object.getPrototypeOf(object); 34 | 35 | // Function and {} prototypes are not bound 36 | while (!this.exceptions.has(ancestor)) { 37 | this.bindOtherOwn(object, ancestor); 38 | ancestor = Object.getPrototypeOf(ancestor); 39 | } 40 | } 41 | 42 | /** 43 | * @param {!Object} object 44 | * @param {!Object} other 45 | * @return {void} 46 | */ 47 | static bindOtherOwn(object, other) { 48 | this.getMethods(other).forEach(method => { 49 | if (!object.hasOwnProperty(method)) { 50 | object[method] = other[method].bind(object); 51 | } 52 | }); 53 | } 54 | 55 | /** 56 | * Get all method names of an object. 57 | * @param {!Object} object 58 | * @return {string[]} 59 | */ 60 | static getMethods(object) { 61 | return Object.getOwnPropertyNames(object).filter(property => ( 62 | typeof object[property] === 'function' 63 | && property !== 'constructor' 64 | )); 65 | } 66 | } 67 | 68 | /** 69 | * @type {Set} 70 | * @see {Binder.bindAncestors} 71 | */ 72 | Binder.exceptions = new Set([ 73 | Object.getPrototypeOf(() => { 74 | }), 75 | Object.getPrototypeOf({}), 76 | null 77 | ]); 78 | -------------------------------------------------------------------------------- /src/page/background/js/class/UUID.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Generate universally unique identifiers. 5 | */ 6 | class UUID { 7 | /** 8 | * Generate a UUID. 9 | * @return {string} 10 | * @see {@link https://en.wikipedia.org/wiki/Universally_unique_identifier} 11 | */ 12 | static generate() { 13 | const time = this.timeOrigin + Math.floor(performance.now() * 1e6); 14 | // Since collisions may occur only if two UUIDs are generated 15 | // at the same time, i.e., within a same timestamp of time, 16 | // the exception list should be cleared on timestamp change. 17 | if (time > this.context.time) { 18 | this.context.time = time; 19 | this.context.exceptions.clear(); 20 | } 21 | 22 | let uuid; 23 | const uintArray = new Uint32Array(2); 24 | do { 25 | crypto.getRandomValues(uintArray); 26 | 27 | uuid = time.toString(16) 28 | + uintArray[0].toString(16).padStart(8, '0') 29 | + uintArray[1].toString(16).padStart(8, '0'); 30 | uuid = uuid.replace( 31 | /^(\w+)(\w{4})(\w{4})(\w{4})(\w{12})$/, 32 | '{$1-$2-$3-$4-$5}' 33 | ); 34 | // If the UUID already exists, 35 | // re-generate a new UUID. 36 | } while (this.context.exceptions.has(uuid)); 37 | 38 | // Add the generated UUID to the exception list 39 | this.context.exceptions.add(uuid); 40 | 41 | return uuid; 42 | } 43 | } 44 | 45 | Binder.bind(UUID); 46 | 47 | /** 48 | * Due to security concerns, browser might round 'performance.now()' results, 49 | * which affects the uniqueness of UUIDs. 50 | * This is a workaround to make sure UUIDs are unique. 51 | * @type {Object} 52 | * @property {Set} exceptions 53 | * @property {number} time 54 | * @see {UUID.generate} 55 | * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Performance/now#Reduced_time_precision} 56 | */ 57 | UUID.context = { 58 | exceptions: new Set, 59 | time: 0, 60 | }; 61 | 62 | /** 63 | * High resolution timestamp, since UNIX epoch. 64 | * @type {number} 65 | */ 66 | UUID.timeOrigin = Math.floor((performance.timeOrigin || Date.now()) * 1e6); 67 | -------------------------------------------------------------------------------- /src/page/background/js/class/Interpreter.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * This safely runs JavaScript codes. 5 | */ 6 | class Interpreter { 7 | /** 8 | * @param {InterpreterFunctionDetails} details 9 | * @return {Promise} 10 | */ 11 | static run(details) { 12 | return this.sendMessage(details).catch(Logger.log); 13 | } 14 | 15 | /** 16 | * @private 17 | * @param {Object} message 18 | * @return {Promise} 19 | */ 20 | static sendMessage(message) { 21 | return new Promise((resolve, reject) => { 22 | if (!this.sandbox) { 23 | reject('Sandbox unavailable'); 24 | } 25 | 26 | // Generate a UUID as message identifier 27 | const id = UUID.generate(); 28 | // This promise is resolved or rejected only when the sandbox 29 | // responses with a message with the same identifier. 30 | this.promises.set(id, {resolve, reject}); 31 | 32 | this.sandbox.postMessage({id, message}, '*'); 33 | }); 34 | } 35 | 36 | /** 37 | * @callback 38 | * @param {MessageEvent} event 39 | * @return {void} 40 | */ 41 | static messageListener({data}) { 42 | const {id, success, response} = data; 43 | 44 | if (!this.promises.has(id)) { 45 | return; 46 | } 47 | 48 | const promise = this.promises.get(id); 49 | success ? promise.resolve(response) : promise.reject(response); 50 | 51 | // As the promise has been fulfilled, 52 | // now forget it. 53 | this.promises.delete(id); 54 | } 55 | 56 | static startup() { 57 | /** 58 | * @private 59 | * @const 60 | * @type {Window} 61 | */ 62 | this.sandbox = frames[0]; 63 | } 64 | } 65 | 66 | Binder.bind(Interpreter); 67 | 68 | /** 69 | * @private 70 | * @const 71 | * @type {Map} 72 | */ 73 | Interpreter.promises = new Map; 74 | 75 | addEventListener('DOMContentLoaded', Interpreter.startup, true); 76 | addEventListener('message', Interpreter.messageListener, true); 77 | 78 | /** 79 | * @typedef {Object} InterpreterFunctionDetails 80 | * @property {string} functionBody 81 | * @property {Object} [args] 82 | */ 83 | -------------------------------------------------------------------------------- /src/page/background/js/background.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Initialize all rules on startup 4 | const initialization = Factory.initialize(); 5 | 6 | // If storage changes, re-initialize rules. 7 | Storage.addListener(changes => changes.forEach(async ([type]) => { 8 | if (!Factory.hasType(type)) { 9 | return; 10 | } 11 | 12 | // Re-initialize rules 13 | await Factory.initialize(type); 14 | 15 | // This makes sure rules are stored in the latest [array] format. 16 | await Factory.saveData(type); 17 | 18 | // Notify the options page 19 | Runtime.sendMessage({ 20 | sender: 'backgroundPage', 21 | command: 'update', 22 | details: { 23 | type, 24 | data: Factory.getData(type), 25 | }, 26 | }); 27 | })); 28 | 29 | // Handle requests from the options page 30 | Runtime.addEventListener('message', async ({sender, request, details}) => { 31 | if (sender !== 'optionsPage') { 32 | return; 33 | } 34 | 35 | switch (request) { 36 | case 'getInformation': 37 | return { 38 | version: Runtime.getManifest('version'), 39 | }; 40 | case 'add': 41 | return Factory.add(details.type); 42 | case 'remove': 43 | return Factory.remove(details.type, details.id); 44 | case 'modify': 45 | return Factory.modify(details.type, details.id, details.change); 46 | case 'getData': 47 | return Factory.getData(details.type); 48 | } 49 | }); 50 | 51 | Runtime.addEventListener('installed', async () => { 52 | const databaseVersion = await Storage.localGet('version'); 53 | const version = Runtime.getManifest('version'); 54 | 55 | const {result, difference} = Utils.versionCompare( 56 | databaseVersion, 57 | version 58 | ); 59 | 60 | // Version unchanged or 61 | // the extension version is lower than the database version 62 | if (result !== -1) { 63 | return; 64 | } 65 | 66 | await initialization; 67 | 68 | // If there's a major or minor update (not a patch one), 69 | // open the options page. 70 | if (difference === 'major' || difference === 'minor') { 71 | await Tabs.openOptionsPage(); 72 | } 73 | 74 | await Storage.localSet({version}); 75 | 76 | await Factory.upgradeDatabase(); 77 | }); 78 | 79 | // Open the options page if user clicks the extension icon 80 | BrowserAction.addListener(Tabs.openOptionsPage); 81 | -------------------------------------------------------------------------------- /src/page/background/js/class/BlockingRule.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Request blocking rule. 5 | */ 6 | class BlockingRule extends RequestRule { 7 | /** 8 | * Block or redirect requests. 9 | * @param {RequestDetails} details 10 | * @return {(browser.webRequest.BlockingResponse|void)} 11 | * @see {@link https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/webRequest/onBeforeRequest} 12 | */ 13 | async requestCallback(details) { 14 | // If redirect URL is set, 15 | // redirect the request to the redirect URL. 16 | // Otherwise, cancel the request. 17 | const redirectUrl = await this.getRedirectUrl(details); 18 | 19 | if (redirectUrl) { 20 | if (redirectUrl === details.url) { 21 | return {cancel: false}; 22 | } 23 | 24 | return {redirectUrl}; 25 | } 26 | 27 | return {cancel: true}; 28 | } 29 | 30 | /** 31 | * @param {string} textRedirectUrl 32 | * @return {void} 33 | */ 34 | setTextRedirectUrl(textRedirectUrl) { 35 | this.textRedirectUrl = textRedirectUrl; 36 | } 37 | 38 | /** 39 | * @private 40 | * @param {RequestDetails} details 41 | * @return {string} 42 | */ 43 | async getRedirectUrl(details) { 44 | if (this.textType === 'JavaScript') { 45 | return await this.constructor.executeScript( 46 | details, 47 | this.textRedirectUrl 48 | ); 49 | } 50 | 51 | let redirectUrl = this.textRedirectUrl; 52 | if (!redirectUrl) { 53 | return ''; 54 | } 55 | 56 | const {url} = details; 57 | 58 | // Find a RegExp filter that matches the URL 59 | const filter = this.urlFilter.url.find(({urlMatches}) => ( 60 | urlMatches && RegExp(urlMatches).test(url) 61 | )); 62 | // If a filter found, 63 | // replace '$i' in the redirect URL with capture groups. 64 | if (filter) { 65 | // Capture groups 66 | const matches = url.match(RegExp(filter.urlMatches)); 67 | for (let i = matches.length - 1; i > 0; i--) { 68 | const search = RegExp('\\$' + i.toString(), 'g'); 69 | redirectUrl = redirectUrl.replace(search, matches[i] || ''); 70 | } 71 | } 72 | 73 | return redirectUrl; 74 | } 75 | } 76 | 77 | Binder.bind(BlockingRule); 78 | 79 | /** 80 | * @inheritDoc 81 | */ 82 | BlockingRule.instances = new Map; 83 | 84 | /** 85 | * @type {BlockingRuleDetails} 86 | */ 87 | BlockingRule.default = { 88 | ...BlockingRule.default, 89 | textRedirectUrl: '', 90 | }; 91 | 92 | BlockingRule.fields = [ 93 | ...BlockingRule.fields, 94 | 'textRedirectUrl', 95 | ] 96 | 97 | /** 98 | * @inheritDoc 99 | */ 100 | BlockingRule.setters = { 101 | ...BlockingRule.setters, 102 | textRedirectUrl: 'setTextRedirectUrl', 103 | }; 104 | 105 | /** 106 | * @override 107 | * @type {Object} 108 | */ 109 | BlockingRule.requestEvent = browser.webRequest.onBeforeRequest; 110 | 111 | /** 112 | * @private 113 | * @type {Object} 114 | */ 115 | BlockingRule.defaultUrlExceptions = { 116 | url: [ 117 | {urlMatches: browser.runtime.getURL('/')}, 118 | ], 119 | }; 120 | 121 | /** 122 | * @typedef {RequestRuleDetails} BlockingRuleDetails 123 | * @property {string} redirectUrl 124 | */ 125 | -------------------------------------------------------------------------------- /src/page/background/js/class/Storage.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | class Storage { 4 | /** 5 | * @param {(string[]|string|void)} [keys] 6 | * @return {Promise} 7 | */ 8 | static syncGet(keys) { 9 | return browser.storage.sync.get(keys).then( 10 | data => Array.isArray(keys) || !keys ? data : data[keys], 11 | Logger.log 12 | ); 13 | } 14 | 15 | /** 16 | * @param {(string[]|string|void)} [key] 17 | * @return {Promise} 18 | */ 19 | static localGet(key) { 20 | return browser.storage.local.get(key).then( 21 | data => Array.isArray(key) || !key ? data : data[key], 22 | Logger.log 23 | ); 24 | } 25 | 26 | /** 27 | * @param {!Object} keys 28 | * @param {boolean} [silent] 29 | * @return {void} 30 | */ 31 | static syncSet(keys, silent = true) { 32 | browser.storage.sync.set(keys).catch(Logger.log); 33 | 34 | // If 'silent' is set to true, 35 | // changes made won't trigger storage-changed event listeners. 36 | silent && this.changes.push(Object.entries(keys)); 37 | } 38 | 39 | /** 40 | * @param {!Object} keys 41 | * @return {void} 42 | */ 43 | static localSet(keys) { 44 | browser.storage.local.set(keys).catch(Logger.log); 45 | } 46 | 47 | /** 48 | * Storage change event listener that triggers user-registered listeners. 49 | * @callback 50 | * @param {browser.storage.StorageChange} changes 51 | * @param {string} areaName 52 | * @return {void} 53 | */ 54 | static changedCallback(changes, areaName) { 55 | if (areaName !== 'sync') { 56 | return; 57 | } 58 | 59 | if (this.isSilent(changes)) { 60 | this.changes.shift(); 61 | return; 62 | } 63 | 64 | // Remap and filter changes 65 | const entries = Object.entries(changes) 66 | .filter(([, {newValue, oldValue}]) => ( 67 | !Utils.compare(newValue, oldValue) 68 | )); 69 | if (entries.length) { 70 | this.listeners.forEach(callback => callback(entries)); 71 | } 72 | } 73 | 74 | /** 75 | * Check if the change was made by Storage.set in silent mode. 76 | * @private 77 | * @param {Object} changes 78 | * @return {boolean} 79 | */ 80 | static isSilent(changes) { 81 | if (this.changes.length) { 82 | return Utils.compare( 83 | Object.entries(changes) 84 | .map(([key, {newValue}]) => [key, newValue]), 85 | this.changes[0] 86 | ); 87 | } 88 | return false; 89 | } 90 | 91 | /** 92 | * Add a listener for storage-changed events. 93 | * @param {Function} listener 94 | * @return {void} 95 | */ 96 | static addListener(listener) { 97 | this.listeners.add(listener); 98 | } 99 | } 100 | 101 | /** 102 | * This stores changes made by Storage.set in silent mode. 103 | * The storage-changed event listener must ignore those changes. 104 | * @private 105 | * @const 106 | * @type {Array} 107 | */ 108 | Storage.changes = []; 109 | 110 | /** 111 | * @private 112 | * @const 113 | * @type {Set} 114 | */ 115 | Storage.listeners = new Set; 116 | 117 | Binder.bindOwn(Storage); 118 | 119 | browser.storage.onChanged.addListener(Storage.changedCallback); 120 | -------------------------------------------------------------------------------- /src/page/options/css/input.css: -------------------------------------------------------------------------------- 1 | article { 2 | transition: margin 0.25s ease-out; 3 | } 4 | 5 | article > :first-child > input { 6 | background-color: var(--yellow-1); 7 | } 8 | 9 | article.enabled > :first-child > input { 10 | background-color: var(--green-1); 11 | } 12 | 13 | article:not(.active) { 14 | display: flex; 15 | cursor: pointer; 16 | } 17 | 18 | article:not(.active) > :first-child { 19 | margin: 0 0.25em 0 0; 20 | } 21 | 22 | article:not(.active) > :first-child > label, 23 | article:not(.active) > :not(:first-of-type) { 24 | display: none; 25 | } 26 | 27 | article:not(.active) > :first-child > input { 28 | border-radius: 1.5em; 29 | pointer-events: none; 30 | } 31 | 32 | article.active { 33 | /* Create big gaps between active and inactive elements */ 34 | margin: 2em 0; 35 | } 36 | 37 | article.active > :first-child > label { 38 | background-color: var(--yellow-0); 39 | cursor: pointer; 40 | } 41 | 42 | article.active.enabled > :first-child > label { 43 | background-color: var(--green-0); 44 | } 45 | 46 | .highlight-error { 47 | background-color: var(--red-0); 48 | } 49 | 50 | .highlight-warning { 51 | background-color: var(--yellow-0); 52 | } 53 | 54 | .highlight-ok { 55 | background-color: var(--green-0); 56 | } 57 | 58 | label { 59 | padding: 0.75em 1.25em; 60 | } 61 | 62 | input, 63 | select, 64 | button { 65 | border-radius: 1.5em; 66 | padding: 0.75em 1.25em; 67 | background-color: var(--gray-1); 68 | } 69 | 70 | textarea { 71 | width: 100%; 72 | min-width: 100%; 73 | max-width: 100%; 74 | min-height: 4.5em; 75 | background-color: inherit; 76 | } 77 | 78 | .input, 79 | .multiline-input { 80 | display: flex; 81 | min-width: 0; 82 | } 83 | 84 | .input > label, 85 | .multiline-input > label { 86 | background-color: var(--gray-0); 87 | } 88 | 89 | .input { 90 | width: 100%; 91 | } 92 | 93 | .input > label { 94 | border-radius: 1.5em 0 0 1.5em; 95 | white-space: nowrap; 96 | } 97 | 98 | .input > input, 99 | .input > select { 100 | flex-grow: 1; 101 | border-radius: 0 1.5em 1.5em 0; 102 | } 103 | 104 | .multiline-input { 105 | flex-direction: column; 106 | } 107 | 108 | .multiline-input > label { 109 | display: block; 110 | border-radius: 1.5em 1.5em 0 0; 111 | } 112 | 113 | .textarea { 114 | margin: 0; 115 | border-radius: 0 0 1.5em 1.5em; 116 | padding: 0.75em 1.25em; 117 | background-color: var(--gray-1); 118 | } 119 | 120 | .switch { 121 | /* Just like a button */ 122 | display: inline-block; 123 | position: relative; 124 | width: 7.5em; 125 | } 126 | 127 | .switch::after { 128 | display: inline-block; 129 | content: ''; 130 | } 131 | 132 | .switch > input { 133 | display: none; 134 | } 135 | 136 | .slider { 137 | position: absolute; 138 | top: 0; 139 | left: 0; 140 | right: 0; 141 | bottom: 0; 142 | border-radius: 1.5em; 143 | background-color: var(--yellow-0); 144 | cursor: pointer; 145 | } 146 | 147 | .slider > span { 148 | position: absolute; 149 | left: 0.25em; 150 | bottom: 0.25em; 151 | width: 5.75em; 152 | border-radius: 1.25em; 153 | padding: 0.5em 1em; 154 | background-color: var(--yellow-1); 155 | text-align: center; 156 | transition: transform 0.25s ease-out; 157 | } 158 | 159 | input:checked + .slider { 160 | background-color: var(--green-0); 161 | } 162 | 163 | input:checked + .slider > span { 164 | background-color: var(--green-1); 165 | transform: translateX(1.25em); 166 | } 167 | 168 | input:checked + .slider > span > :first-child { 169 | display: none; 170 | } 171 | 172 | input:not(:checked) + .slider > span > :last-child { 173 | display: none; 174 | } 175 | -------------------------------------------------------------------------------- /src/page/background/frame/sandbox.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 153 | 154 | 155 | -------------------------------------------------------------------------------- /src/page/background/js/class/Rule.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Rule skeleton. 5 | * @abstract 6 | */ 7 | class Rule { 8 | /** 9 | * Initialize a rule. 10 | * @param {RuleDetails} details 11 | */ 12 | constructor(details) { 13 | Binder.bind(this); 14 | 15 | /** 16 | * Unique rule ID. 17 | * @type {string} 18 | */ 19 | this.id = details && details.id ? details.id : UUID.generate(); 20 | 21 | /** 22 | * @protected 23 | * @type {boolean} 24 | */ 25 | this.active = false; 26 | 27 | this.update({...this.constructor.default, ...details}); 28 | this.activate(); 29 | 30 | this.constructor.instances.set(this.id, this); 31 | } 32 | 33 | /** 34 | * Register the rule with browser. 35 | * @protected 36 | * @abstract 37 | * @return {void} 38 | */ 39 | register() { 40 | } 41 | 42 | /** 43 | * @protected 44 | * @abstract 45 | * @return {void} 46 | */ 47 | unregister() { 48 | } 49 | 50 | /** 51 | * @return {void} 52 | */ 53 | activate() { 54 | if (this.enabled && !this.active) { 55 | this.register(); 56 | this.active = true; 57 | } 58 | } 59 | 60 | /** 61 | * @return {void} 62 | */ 63 | deactivate() { 64 | if (this.active) { 65 | this.unregister(); 66 | this.active = false; 67 | } 68 | } 69 | 70 | getDetails() { 71 | const details = {}; 72 | this.constructor.fields.forEach(key => { 73 | details[key] = this[key]; 74 | }); 75 | return details; 76 | } 77 | 78 | /** 79 | * Update rule details. 80 | * @param {Object} details 81 | * @return {void} 82 | */ 83 | update(details) { 84 | Object.entries(details).forEach(([key, value]) => { 85 | const setter = this[this.constructor.setters[key]]; 86 | setter && setter(value); 87 | }); 88 | } 89 | 90 | /** 91 | * @param {string} name 92 | * @return {void} 93 | */ 94 | setName(name) { 95 | this.name = name; 96 | } 97 | 98 | /** 99 | * Enable or disable the current rule. 100 | * @param {boolean} enabled 101 | */ 102 | setEnabled(enabled) { 103 | // If the property 'enabled' doesn't exist, 104 | // it means the rule is being initialized, 105 | // then don't activate the rule at the moment. 106 | const isInitialized = this.hasOwnProperty('enabled'); 107 | 108 | this.enabled = enabled; 109 | 110 | if (isInitialized) { 111 | this.enabled ? this.activate() : this.deactivate(); 112 | } 113 | } 114 | 115 | /** 116 | * @param {string[]} urlFilters 117 | * @return {void} 118 | */ 119 | setUrlFilters(urlFilters) { 120 | this.urlFilters = urlFilters; 121 | 122 | // ES6 destructuring causes IDE errors 123 | const filter = Utils.createUrlFilter(this.urlFilters); 124 | this.urlFilter = filter[0]; 125 | this.urlExceptions = filter[1]; 126 | 127 | if (this.active) { 128 | this.deactivate(); 129 | this.activate(); 130 | } 131 | } 132 | 133 | /** 134 | * @param {string[]} originUrlFilters 135 | * @return {void} 136 | */ 137 | setOriginUrlFilters(originUrlFilters) { 138 | this.originUrlFilters = originUrlFilters; 139 | 140 | const filter = Utils.createUrlFilter(this.originUrlFilters); 141 | this.originUrlFilter = filter[0]; 142 | this.originUrlExceptions = filter[1]; 143 | } 144 | 145 | /** 146 | * Remove the rule itself. 147 | * @return {void} 148 | */ 149 | remove() { 150 | this.deactivate(); 151 | this.constructor.instances.delete(this.id); 152 | } 153 | } 154 | 155 | /** 156 | * A map of created rule instances. 157 | * Children MUST have their own map. 158 | * @protected 159 | * @type {Map} 160 | */ 161 | Rule.instances = null; 162 | 163 | /** 164 | * Rule default details. 165 | * Children MUST inherit default details. 166 | * @type {Object} 167 | */ 168 | Rule.default = { 169 | name: '', 170 | enabled: true, 171 | urlFilters: [], 172 | originUrlFilters: [], 173 | }; 174 | 175 | /** 176 | * @type {string[]} 177 | */ 178 | Rule.fields = [ 179 | 'id', 180 | 'name', 181 | 'enabled', 182 | 'urlFilters', 183 | 'originUrlFilters', 184 | ]; 185 | 186 | /** 187 | * Rule property setters. 188 | * Children MUST inherit setters. 189 | * @protected 190 | * @type {Object} 191 | */ 192 | Rule.setters = { 193 | name: 'setName', 194 | enabled: 'setEnabled', 195 | urlFilters: 'setUrlFilters', 196 | originUrlFilters: 'setOriginUrlFilters', 197 | }; 198 | 199 | /** 200 | * @typedef {Object} RuleDetails 201 | * @property {string} [id] 202 | * @property {string} [name] 203 | * @property {boolean} [enabled] 204 | * @property {string[]} [urlFilters] 205 | * @property {string[]} [originUrlFilters] 206 | */ 207 | -------------------------------------------------------------------------------- /src/page/background/js/class/RequestRule.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Request interception rule. 5 | * @abstract 6 | */ 7 | class RequestRule extends Rule { 8 | /** 9 | * @abstract 10 | * @param {RequestDetails} details 11 | * @return {Object} 12 | */ 13 | requestCallback(details) { 14 | } 15 | 16 | /** 17 | * @protected 18 | * @param {RequestDetails} details 19 | * @param {string} functionBody 20 | * @return {Promise} 21 | */ 22 | static async executeScript(details, functionBody) { 23 | const args = {}; 24 | 25 | // Add request details to the arguments 26 | this.requestDetails.forEach(detail => { 27 | if (functionBody.includes(detail)) { 28 | args[detail] = details[detail]; 29 | } 30 | }); 31 | 32 | // Add tab details to the arguements 33 | if (this.tabDetails.some(detail => functionBody.includes(detail))) { 34 | // Add tab details to the arguments 35 | const tab = await Tabs.get(details.tabId); 36 | this.tabDetails.forEach(detail => { 37 | if (functionBody.includes(detail)) { 38 | args[detail] = tab[detail]; 39 | } 40 | }); 41 | } 42 | 43 | return Interpreter.run({ 44 | functionBody, 45 | args, 46 | }).catch(Logger.log); 47 | } 48 | 49 | /** 50 | * @inheritDoc 51 | */ 52 | register() { 53 | if (this.urlFilters.length) { 54 | this.constructor.requestEvent.addListener( 55 | this.filterRequest, 56 | {urls: ['']}, 57 | this.constructor.extraInfoSpec 58 | ); 59 | } 60 | } 61 | 62 | /** 63 | * @inheritDoc 64 | */ 65 | unregister() { 66 | this.constructor.requestEvent.removeListener(this.filterRequest); 67 | } 68 | 69 | /** 70 | * @param {RequestDetails} details 71 | * @return {(Object|void)} 72 | */ 73 | filterRequest(details) { 74 | // If origin URL or document URL is undefined, 75 | // let it be the request URL. 76 | if (!details.originUrl) { 77 | details.originUrl = details.url; 78 | } 79 | if (!details.documentUrl) { 80 | details.documentUrl = details.url; 81 | } 82 | 83 | const {url, originUrl, method} = details; 84 | if ( 85 | Utils.testUrl(url, this.urlFilter, false) 86 | && !Utils.testUrl(url, this.urlExceptions, false) 87 | && ( 88 | !this.method 89 | || method === this.method 90 | ) 91 | && ( 92 | Utils.testUrl(originUrl, this.originUrlFilter) 93 | && !Utils.testUrl(originUrl, this.originUrlExceptions, false) 94 | ) 95 | ) { 96 | return this.requestCallback(details); 97 | } 98 | } 99 | 100 | /** 101 | * @param {string} method 102 | * @return {void} 103 | */ 104 | setMethod(method) { 105 | this.method = method; 106 | } 107 | 108 | /** 109 | * @param {string} textType 110 | */ 111 | setTextType(textType) { 112 | this.textType = textType; 113 | } 114 | } 115 | 116 | /** 117 | * @const 118 | * @type {RequestRuleDetails} 119 | */ 120 | RequestRule.default = { 121 | ...RequestRule.default, 122 | method: '', 123 | textType: 'plaintext', 124 | }; 125 | 126 | RequestRule.fields = [ 127 | ...RequestRule.fields, 128 | 'method', 129 | 'textType', 130 | ]; 131 | 132 | /** 133 | * @inheritDoc 134 | */ 135 | RequestRule.setters = { 136 | ...RequestRule.setters, 137 | method: 'setMethod', 138 | textType: 'setTextType', 139 | }; 140 | 141 | /** 142 | * Children MUST declare their request event. 143 | * @type {Object} 144 | */ 145 | RequestRule.requestEvent = null; 146 | 147 | /** 148 | * Children MAY add their required extra info. 149 | * @type {string[]} 150 | */ 151 | RequestRule.extraInfoSpec = ['blocking']; 152 | 153 | /** 154 | * Request details accessible inside JavaScript function. 155 | * @type {string[]} 156 | */ 157 | RequestRule.requestDetails = [ 158 | 'requestHeaders', 159 | 'responseHeaders', 160 | 'responseBody', 161 | 'url', 162 | 'originUrl', 163 | 'documentUrl', 164 | 'method', 165 | 'proxyInfo', 166 | 'type', 167 | 'timeStamp', 168 | ]; 169 | 170 | /** 171 | * Tab details accessible inside JavaScript function. 172 | * @type {string[]} 173 | */ 174 | RequestRule.tabDetails = [ 175 | 'incognito', 176 | 'pinned', 177 | ]; 178 | 179 | /** 180 | * @typedef {RuleDetails} RequestRuleDetails 181 | * @property {RequestMethod} [method] 182 | * @property {string} [textType] 183 | */ 184 | 185 | /** 186 | * @typedef {string} RequestMethod 187 | * @enum { 188 | * '', 189 | * 'GET', 190 | * 'POST', 191 | * 'HEAD', 192 | * 'PUT', 193 | * 'DELETE', 194 | * 'CONNECT', 195 | * 'TRACE', 196 | * 'PATCH', 197 | * } 198 | */ 199 | 200 | /** 201 | * @typedef {object} RequestDetails 202 | * @property {string} url 203 | * @property {string} originUrl 204 | * @property {string} documentUrl 205 | * @property {string} method 206 | * @property {Object[]} requestHeaders 207 | * @property {Object[]} responseHeaders 208 | * @property {string} responseBody 209 | * @property {string} requestId 210 | * @property {string} type 211 | * @property {number} tabId 212 | */ 213 | -------------------------------------------------------------------------------- /src/page/background/js/class/ContentScript.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Content script rule. 5 | */ 6 | class ContentScript extends Rule { 7 | /** 8 | * @inheritDoc 9 | */ 10 | register() { 11 | if (this.code && this.urlFilters.length) { 12 | this.navigationEvent.addListener( 13 | this.navigateCallback, 14 | this.urlFilter 15 | ); 16 | } 17 | } 18 | 19 | /** 20 | * @inheritDoc 21 | */ 22 | unregister() { 23 | this.navigationEvent.removeListener(this.navigateCallback); 24 | } 25 | 26 | /** 27 | * Inject content scripts to tabs matching the filters. 28 | * @private 29 | * @param {NavigationDetails} 30 | * @return {void} 31 | */ 32 | async navigateCallback({tabId, frameId, url}) { 33 | if (Utils.testUrl(url, this.urlExceptions, false)) { 34 | return; 35 | } 36 | 37 | if (this.originUrlFilters.length) { 38 | // Origin URL is the top window's URL 39 | let originUrl; 40 | // If the current frame is the top window, 41 | // the origin URL is the navigation URL. 42 | if (frameId === 0) { 43 | originUrl = url; 44 | } else { 45 | const originFrame = await browser.webNavigation.getFrame({ 46 | tabId, 47 | frameId: 0, 48 | }); 49 | originUrl = originFrame.url; 50 | } 51 | 52 | if ( 53 | !Utils.testUrl(originUrl, this.originUrlFilter) 54 | || Utils.testUrl(originUrl, this.originUrlExceptions, false) 55 | ) { 56 | return; 57 | } 58 | } 59 | 60 | this.injector(tabId, { 61 | frameId, 62 | code: this.code, 63 | runAt: this.runAt, 64 | }).catch(Logger.log); 65 | } 66 | 67 | /** 68 | * @private 69 | * @param {string} code 70 | * @return {void} 71 | */ 72 | setCode(code) { 73 | /** 74 | * @private 75 | * @type {string} 76 | */ 77 | this.code = code; 78 | 79 | if (this.active) { 80 | this.deactivate(); 81 | this.activate(); 82 | } 83 | } 84 | 85 | /** 86 | * @private 87 | * @param {ScriptType} scriptType 88 | * @return {void} 89 | */ 90 | setScriptType(scriptType) { 91 | /** 92 | * @private 93 | * @type {ScriptType} 94 | */ 95 | this.scriptType = scriptType; 96 | /** 97 | * @private 98 | * @type {Function} 99 | */ 100 | this.injector = this.constructor.injectors[this.scriptType]; 101 | } 102 | 103 | /** 104 | * @private 105 | * @param {DOMEvent} domEvent 106 | * @return {void} 107 | */ 108 | setDOMEvent(domEvent) { 109 | const active = this.active; 110 | this.deactivate(); 111 | 112 | /** 113 | * @private 114 | * @type {DOMEvent} 115 | */ 116 | this.domEvent = domEvent; 117 | /** 118 | * @private 119 | * @type {WebExtEvent} 120 | */ 121 | this.navigationEvent = this.constructor.navigationEvents[this.domEvent]; 122 | /** 123 | * @private 124 | * @type {string} 125 | */ 126 | this.runAt = this.constructor.runAts[this.domEvent]; 127 | 128 | active && this.activate(); 129 | } 130 | } 131 | 132 | /** 133 | * @inheritDoc 134 | */ 135 | ContentScript.instances = new Map; 136 | 137 | /** 138 | * @override 139 | * @type {ContentScriptDetails} 140 | */ 141 | ContentScript.default = { 142 | ...ContentScript.default, 143 | code: '', 144 | scriptType: 'JavaScript', 145 | domEvent: 'completed', 146 | }; 147 | 148 | ContentScript.fields = [ 149 | ...ContentScript.fields, 150 | 'code', 151 | 'scriptType', 152 | 'domEvent', 153 | ]; 154 | 155 | /** 156 | * @inheritDoc 157 | */ 158 | ContentScript.setters = { 159 | ...ContentScript.setters, 160 | code: 'setCode', 161 | scriptType: 'setScriptType', 162 | domEvent: 'setDOMEvent', 163 | }; 164 | 165 | /** 166 | * @private 167 | * @type {Object} 168 | */ 169 | ContentScript.navigationEvents = { 170 | loading: browser.webNavigation.onCommitted, 171 | loaded: browser.webNavigation.onDOMContentLoaded, 172 | completed: browser.webNavigation.onCompleted, 173 | }; 174 | 175 | /** 176 | * @private 177 | * @type {Object} 178 | */ 179 | ContentScript.runAts = { 180 | loading: 'document_start', 181 | loaded: 'document_end', 182 | completed: 'document_idle', 183 | }; 184 | 185 | /** 186 | * @private 187 | * @type {Object} 188 | */ 189 | ContentScript.injectors = { 190 | JavaScript: browser.tabs.executeScript, 191 | CSS: browser.tabs.insertCSS, 192 | }; 193 | 194 | /** 195 | * @typedef {RuleDetails} ContentScriptDetails 196 | * @property {string} [code] 197 | * @property {ScriptType} [scriptType] 198 | * @property {DOMEvent} [domEvent] 199 | */ 200 | 201 | /** 202 | * @typedef {string} ScriptType 203 | * @enum { 204 | * 'Javascript', 205 | * 'CSS', 206 | * } 207 | */ 208 | 209 | /** 210 | * @typedef {string} DOMEvent 211 | * @enum { 212 | * 'loading', 213 | * 'loaded', 214 | * 'completed', 215 | * } 216 | */ 217 | 218 | /** 219 | * @typedef {object} NavigationDetails 220 | * @property {number} tabId 221 | * @property {number} frameId 222 | */ 223 | -------------------------------------------------------------------------------- /src/page/background/js/class/ResponseRule.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Request response body modification rule. 5 | */ 6 | class ResponseRule extends RequestRule { 7 | /** 8 | * Modify the response body of the request. 9 | * @param {RequestDetails} details 10 | * @return {void} 11 | * @see {@link https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/filterResponseData} 12 | */ 13 | async requestCallback(details) { 14 | if (!this.textResponse) { 15 | return; 16 | } 17 | 18 | const {requestId, responseHeaders} = details; 19 | 20 | // Detect charset 21 | let charset = this.constructor.detectCharset(responseHeaders); 22 | if (!charset && !this.constructor.textResources.has(details.type)) { 23 | // If the charset is undefined, 24 | // and the resource type is unknown, 25 | // then skip the request. 26 | return; 27 | } 28 | 29 | /** 30 | * @type {Object} 31 | */ 32 | const filter = browser.webRequest.filterResponseData(requestId); 33 | const encoder = new TextEncoder(); 34 | 35 | if (this.textType === 'plaintext') { 36 | filter.onstart = async () => { 37 | filter.write(encoder.encode(await this.getResponse())); 38 | filter.close(); 39 | }; 40 | return; 41 | } 42 | 43 | const decoder = new TextDecoder( 44 | charset || this.constructor.defaultEncoding 45 | ); 46 | 47 | // Request body as a property of the request details 48 | details.responseBody = ''; 49 | filter.ondata = (event) => { 50 | details.responseBody += decoder.decode(event.data, {stream: true}); 51 | }; 52 | 53 | filter.onstop = async () => { 54 | const responseBody = await this.getResponse(details); 55 | 56 | filter.write(encoder.encode(responseBody || details.responseBody)); 57 | filter.close(); 58 | }; 59 | } 60 | 61 | /** 62 | * @private 63 | * @param {RequestDetails} details 64 | * @return {(Promise|string)} 65 | */ 66 | getResponse(details) { 67 | switch (this.textType) { 68 | case 'plaintext': 69 | return this.textResponse; 70 | case 'JavaScript': 71 | return this.constructor.executeScript( 72 | details, 73 | this.textResponse 74 | ); 75 | } 76 | } 77 | 78 | /** 79 | * Get charset from Content-Type header. 80 | * @param {Object[]} responseHeaders 81 | * @return {(string|void)} 82 | */ 83 | static detectCharset(responseHeaders) { 84 | // Get the Content-Type header 85 | const header = responseHeaders.find(({name}) => ( 86 | name.toLowerCase() === 'content-type' 87 | )); 88 | if (!header) { 89 | return; 90 | } 91 | const value = header.value.toLowerCase(); 92 | 93 | const charset = this.encodings.find(charset => value.includes(charset)); 94 | if (charset) { 95 | return charset; 96 | } 97 | // If the charset is not detected, 98 | // but the content type is a text type, 99 | // return the default charset. 100 | if (this.textTypes.some(textType => value.includes(textType))) { 101 | return this.defaultEncoding; 102 | } 103 | } 104 | 105 | /** 106 | * @param {string} textResponse 107 | */ 108 | setTextResponse(textResponse) { 109 | this.textResponse = textResponse; 110 | } 111 | } 112 | 113 | Binder.bind(ResponseRule); 114 | 115 | /** 116 | * @inheritDoc 117 | */ 118 | ResponseRule.instances = new Map; 119 | 120 | /** 121 | * @type {ResponseRuleDetails} 122 | */ 123 | ResponseRule.default = { 124 | ...ResponseRule.default, 125 | textResponse: '', 126 | }; 127 | 128 | ResponseRule.fields = [ 129 | ...ResponseRule.fields, 130 | 'textResponse', 131 | ]; 132 | 133 | /** 134 | * @inheritDoc 135 | */ 136 | ResponseRule.setters = { 137 | ...ResponseRule.setters, 138 | textResponse: 'setTextResponse', 139 | }; 140 | 141 | /** 142 | * @override 143 | * @type {Object} 144 | */ 145 | ResponseRule.requestEvent = browser.webRequest.onHeadersReceived; 146 | 147 | /** 148 | * @const 149 | * @type {Object} 150 | */ 151 | ResponseRule.extraInfoSpec = [ 152 | ...ResponseRule.extraInfoSpec, 153 | 'responseHeaders', 154 | ]; 155 | 156 | /** 157 | * Types of text resources. 158 | * @type {Set} 159 | */ 160 | ResponseRule.textResources = new Set([ 161 | 'main_frame', 162 | 'sub_frame', 163 | 'web_manifest', 164 | 'script', 165 | 'stylesheet', 166 | ]); 167 | 168 | /** 169 | * Content types as texts. 170 | * @type {string[]} 171 | */ 172 | ResponseRule.textTypes = [ 173 | 'text', 174 | 'javascript', 175 | 'css', 176 | 'json', 177 | 'typescript', 178 | 'xml', 179 | ]; 180 | 181 | /** 182 | * Supported (common) encodings. 183 | * @type {string[]} 184 | * @see {@link https://en.wikipedia.org/wiki/Character_encoding} 185 | */ 186 | ResponseRule.encodings = [ 187 | 'utf-8', 188 | 'ascii', 189 | 'iso-8859-1', 190 | 'iso-8859-2', 191 | 'iso-8859-3', 192 | 'iso-8859-4', 193 | 'iso-8859-5', 194 | 'iso-8859-6', 195 | 'iso-8859-7', 196 | 'iso-8859-8', 197 | 'iso-8859-9', 198 | 'iso-8859-10', 199 | 'iso-8859-11', 200 | 'iso-8859-13', 201 | 'iso-8859-14', 202 | 'iso-8859-15', 203 | 'iso-8859-16', 204 | 'windows-1251', 205 | 'windows-1252', 206 | 'windows-1253', 207 | 'windows-1254', 208 | 'windows-1255', 209 | 'windows-1256', 210 | 'windows-1257', 211 | 'windows-1258', 212 | 'macintosh', 213 | 'koi8-r', 214 | 'koi8-u', 215 | 'shift_jis', 216 | 'euc-jp', 217 | 'iso-2022-jp', 218 | 'gb_2312-80', 219 | 'gbk', 220 | 'gb18030', 221 | 'big5', 222 | 'euc-kr', 223 | ]; 224 | 225 | /** 226 | * @type {string} 227 | */ 228 | ResponseRule.defaultEncoding = 'utf-8'; 229 | 230 | /** 231 | * @typedef {RequestRuleDetails} ResponseRuleDetails 232 | * @property {string} [textResponse] 233 | */ 234 | -------------------------------------------------------------------------------- /src/page/background/js/class/Factory.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Give ability to do any rule-related tasks. 5 | */ 6 | class Factory { 7 | /** 8 | * Initialize rule instances by types. 9 | * If no type is specified, initialize all types of rules. 10 | * @param {(string[]|string|void)} [types] 11 | * @param {Object} [data] 12 | * @return {Promise} 13 | */ 14 | static async initialize(types = this.getTypes(), data) { 15 | if (Array.isArray(types)) { 16 | for (const type of types) { 17 | await this.initialize(type, data ? data[type] : null); 18 | } 19 | return; 20 | } 21 | 22 | // String 23 | const type = types; 24 | 25 | // Remove existing rule instances of this type 26 | this.getRules(type).forEach(instance => instance.remove()); 27 | 28 | // Create new instances 29 | data = data || await this.readData(type); 30 | Array.isArray(data) && data.forEach(data => { 31 | let rule = {} 32 | if (Array.isArray(data)) { 33 | const {fields} = this.types.get(type); 34 | data.forEach((value, index) => { 35 | const field = fields[index]; 36 | rule[field] = value; 37 | }); 38 | } else { 39 | rule = data; 40 | } 41 | this.create(type, rule); 42 | }); 43 | } 44 | 45 | /** 46 | * Add a new rule. 47 | * @param {string} type 48 | */ 49 | static add(type) { 50 | const instance = this.create(type); 51 | 52 | // The rule data has been updated, 53 | // hence storage needs updating. 54 | this.saveData(type); 55 | 56 | // Return the details of the newly created rule 57 | const data = instance.getDetails(); 58 | return {...data, sync: true}; 59 | } 60 | 61 | /** 62 | * Modify details of a rule. 63 | * @param {string} type 64 | * @param {string} id 65 | * @param {Object} changes 66 | * @return {void} 67 | */ 68 | static modify(type, id, changes) { 69 | if (changes.hasOwnProperty('sync')) { 70 | if (changes.sync) { 71 | this.local.delete(id); 72 | } else { 73 | this.local.add(id); 74 | } 75 | } else { 76 | this.types.get(type).instances.get(id).update(changes); 77 | } 78 | 79 | // Update storage 80 | this.saveData(type); 81 | } 82 | 83 | /** 84 | * Remove a rule instance. 85 | * @param {string} type 86 | * @param {string} id 87 | * @return {void} 88 | */ 89 | static remove(type, id) { 90 | this.types.get(type).instances.get(id).remove(); 91 | 92 | // Update storage 93 | this.saveData(type); 94 | } 95 | 96 | /** 97 | * Get data of a type of rule. 98 | * @param {string} type 99 | * @param {boolean} raw 100 | * @return {Object[]} 101 | */ 102 | static getData(type, raw) { 103 | const rules = this.getRules(type) 104 | return raw 105 | ? rules 106 | : rules.map(rule => { 107 | const data = rule.getDetails(); 108 | const {id} = data; 109 | const sync = !this.local.has(id); 110 | return {...data, sync}; 111 | }); 112 | } 113 | 114 | /** 115 | * Get all types of rule. 116 | * @return {string[]} 117 | */ 118 | static getTypes() { 119 | return [...this.types.keys()]; 120 | } 121 | 122 | /** 123 | * Check if a type of rule exists. 124 | * @param {string} type 125 | * @return {boolean} 126 | */ 127 | static hasType(type) { 128 | return this.types.has(type); 129 | } 130 | 131 | /** 132 | * Create a rule instance. 133 | * @private 134 | * @param {string} type 135 | * @param {Object} [details] 136 | * @return {Rule} 137 | */ 138 | static create(type, details) { 139 | const constructor = this.types.get(type); 140 | return new constructor(details); 141 | } 142 | 143 | /** 144 | * Get all rule instances of a type. 145 | * @private 146 | * @param type 147 | * @return {Rule[]} 148 | */ 149 | static getRules(type) { 150 | return [...this.types.get(type).instances.values()]; 151 | } 152 | 153 | /** 154 | * Read rule data from storage. 155 | * @param type 156 | * @return {Promise} 157 | */ 158 | static async readData(type) { 159 | const {fields} = this.types.get(type); 160 | const index = fields.indexOf('id') 161 | const local = await Storage.localGet(type) || []; 162 | const sync = await Storage.syncGet(type) || []; 163 | const rules = [...local, ...sync]; 164 | 165 | local.forEach(data => this.local.add(data[index])); 166 | 167 | return rules; 168 | } 169 | 170 | /** 171 | * Save rule data to storage. 172 | * @private 173 | * @param {string} type 174 | * @return {void} 175 | */ 176 | static saveData(type) { 177 | const {fields} = this.types.get(type); 178 | const local = []; 179 | const sync = []; 180 | 181 | this.getData(type, true).forEach(rule => { 182 | const {id} = rule; 183 | const data = fields.map(field => rule[field]); 184 | 185 | if (this.local.has(id)) { 186 | local.push(data); 187 | } else { 188 | sync.push(data); 189 | } 190 | }); 191 | 192 | Storage.localSet({[type]: local}); 193 | Storage.syncSet({[type]: sync}); 194 | } 195 | 196 | static upgradeDatabase() { 197 | const types = this.getTypes(); 198 | 199 | types.forEach(type => this.saveData(type)); 200 | } 201 | } 202 | 203 | /** 204 | * A map of rule constructors. 205 | * @type {Map} 206 | */ 207 | Factory.types = new Map([ 208 | ['blockingRules', BlockingRule], 209 | ['headerRules', HeaderRule], 210 | ['responseRules', ResponseRule], 211 | ['contentScripts', ContentScript], 212 | ]); 213 | 214 | /** 215 | * Stores local rules' ids. 216 | * @type {Set} 217 | */ 218 | Factory.local = new Set; 219 | -------------------------------------------------------------------------------- /src/page/background/js/class/HeaderRule.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Request header modification rule. 5 | */ 6 | class HeaderRule extends RequestRule { 7 | /** 8 | * Modify request or response headers. 9 | * @param {RequestDetails} details 10 | * @return {(Promise|Object)} 11 | * @see {@link https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/webRequest/onBeforeRequest} 12 | */ 13 | requestCallback(details) { 14 | if (!this.textHeaders) { 15 | return; 16 | } 17 | 18 | const headers = details[this.headerType]; 19 | switch (this.textType) { 20 | case 'plaintext': 21 | return { 22 | [this.headerType]: this.textModify(headers), 23 | }; 24 | case 'JavaScript': 25 | return this.constructor.executeScript( 26 | details, 27 | this.getHeaderMethods() + this.textHeaders 28 | ).then(headers => ({ 29 | [this.headerType]: headers, 30 | })); 31 | } 32 | } 33 | 34 | /** 35 | * @private 36 | * @param {Object[]} headers 37 | */ 38 | textModify(headers) { 39 | if (!this.arrayHeaders) { 40 | // Convert text headers to array of new headers 41 | const lines = this.textHeaders.trim().split(/\s*[\r\n]\s*/); 42 | 43 | // Convert lines to arrays of pairs, remove invalid headers 44 | this.arrayHeaders = lines.reduce((headers, textHeader) => { 45 | const matches = textHeader.match(/(.+?)\s*:\s*(.*)/); 46 | if (matches) { 47 | // [, name, value] 48 | matches.shift(); 49 | headers.push(matches); 50 | } 51 | return headers; 52 | }, []); 53 | } 54 | 55 | this.arrayHeaders.forEach(([name, value]) => { 56 | // Find the current header in the list of existing headers 57 | const header = headers.find(header => ( 58 | header.name.toLowerCase() === name.toLowerCase() 59 | )); 60 | 61 | // If a header with the name exists, 62 | // replace the header's value. 63 | // Otherwise, add the current header to the header list. 64 | if (header) { 65 | header.value = value; 66 | } else if (value) { 67 | headers.push({name, value}); 68 | } 69 | }); 70 | 71 | return headers; 72 | } 73 | 74 | /** 75 | * Additional methods for the header array. 76 | * @return {string} 77 | */ 78 | getHeaderMethods() { 79 | return Object.entries(this.constructor.headerMethods).reduce( 80 | /** 81 | * @param {string} methods 82 | * @param {string} name 83 | * @param {string} args 84 | * @param {string} functionBody 85 | * @return {string} 86 | */ 87 | (methods, [name, [args, functionBody]]) => { 88 | if ( 89 | this.textHeaders.includes(`${this.headerType}.${name}`) 90 | || methods.includes(`this.${name}`) 91 | ) { 92 | methods = `${this.headerType}.${name}=` 93 | + `(function(${args}){${functionBody}` 94 | + `}).bind(${this.headerType});` 95 | + methods; 96 | } 97 | return methods; 98 | }, 99 | '' 100 | ); 101 | } 102 | 103 | /** 104 | * @param {string} textHeaders 105 | */ 106 | setTextHeaders(textHeaders) { 107 | this.textHeaders = textHeaders; 108 | this.arrayHeaders = null; 109 | } 110 | 111 | /** 112 | * @param {HeaderType} headerType 113 | */ 114 | setHeaderType(headerType) { 115 | const active = this.active; 116 | this.deactivate(); 117 | 118 | this.headerType = headerType; 119 | 120 | this.constructor.requestEvent = ( 121 | this.constructor.requestEvents[this.headerType] 122 | ); 123 | this.constructor.extraInfoSpec = ( 124 | this.constructor.extraInfoSpecs[this.headerType] 125 | ); 126 | 127 | active && this.activate(); 128 | } 129 | } 130 | 131 | Binder.bind(HeaderRule); 132 | 133 | /** 134 | * @inheritDoc 135 | */ 136 | HeaderRule.instances = new Map; 137 | 138 | /** 139 | * @type {HeaderRuleDetails} 140 | */ 141 | HeaderRule.default = { 142 | ...HeaderRule.default, 143 | textHeaders: '', 144 | headerType: 'requestHeaders', 145 | }; 146 | 147 | HeaderRule.fields = [ 148 | ...HeaderRule.fields, 149 | 'textHeaders', 150 | 'headerType', 151 | ]; 152 | 153 | /** 154 | * @inheritDoc 155 | */ 156 | HeaderRule.setters = { 157 | ...HeaderRule.setters, 158 | textHeaders: 'setTextHeaders', 159 | headerType: 'setHeaderType', 160 | }; 161 | 162 | /** 163 | * @const 164 | * @type {Object} 165 | */ 166 | HeaderRule.requestEvents = { 167 | requestHeaders: browser.webRequest.onBeforeSendHeaders, 168 | responseHeaders: browser.webRequest.onHeadersReceived, 169 | }; 170 | 171 | /** 172 | * @const 173 | * @type {Object} 174 | */ 175 | HeaderRule.extraInfoSpecs = { 176 | requestHeaders: [ 177 | ...HeaderRule.extraInfoSpec, 178 | 'requestHeaders', 179 | ], 180 | responseHeaders: [ 181 | ...HeaderRule.extraInfoSpec, 182 | 'responseHeaders', 183 | ], 184 | }; 185 | 186 | /** 187 | * Header array methods. 188 | * @type {Object} 189 | */ 190 | HeaderRule.headerMethods = { 191 | modify: [ 192 | 'pairs', 193 | `pairs.forEach(([name,value])=>this.set(name,value));` 194 | + `return this;` 195 | ], 196 | set: [ 197 | 'name,value', 198 | `const header=this.get(name);` 199 | + `if(header){header.value=value;}` 200 | + `else if(value){this.push({name,value});}` 201 | + `return this;`, 202 | ], 203 | get: [ 204 | 'name', 205 | `return this.find(` 206 | + `header=>header.name.toLowerCase()===name.toLowerCase());`, 207 | ], 208 | }; 209 | 210 | /** 211 | * @typedef {RequestRuleDetails} HeaderRuleDetails 212 | * @property {string} [textHeaders] 213 | * @property {HeaderType} [headerType] 214 | */ 215 | 216 | /** 217 | * @typedef {string} HeaderType 218 | * @enum { 219 | * 'requestHeaders', 220 | * 'responseHeaders' 221 | * } 222 | */ 223 | -------------------------------------------------------------------------------- /src/page/shared/js/class/Utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * A collection of useful functions. 5 | */ 6 | class Utils { 7 | /** 8 | * Compare two values. 9 | * @param {UtilsComparable} value1 10 | * @param {UtilsComparable} value2 11 | * @return {boolean} True if the two values are the same. 12 | * @throws {TypeError} 13 | * @see {Utils.isCyclic} 14 | */ 15 | static compare(value1, value2) { 16 | // Check if the two values are of the same primitive value or 17 | // object reference. 18 | if (value1 === value2) { 19 | return true; 20 | } 21 | 22 | // As the two values aren't both objects, 23 | // at least one of them is a primitive value. 24 | // Hence they're not the same. 25 | if ( 26 | typeof value1 !== 'object' 27 | || typeof value2 !== 'object' 28 | || !value1 29 | || !value2 30 | ) { 31 | return false; 32 | } 33 | 34 | if (this.isCyclic(value1) || this.isCyclic(value2)) { 35 | // throw TypeError('Cyclic object value'); 36 | return false; 37 | } 38 | 39 | // If the two constructors are different, 40 | // the two value are different. 41 | if (value1.constructor !== value2.constructor) { 42 | return false; 43 | } 44 | 45 | // This also applies to array 46 | const object1Keys = Object.keys(value1); 47 | const object2Keys = Object.keys(value2); 48 | if (object1Keys.length !== object2Keys.length) { 49 | return false; 50 | } 51 | 52 | return object1Keys.every(key => this.compare(value1[key], value2[key])); 53 | } 54 | 55 | /** 56 | * Check if an object is cyclic. 57 | * @private 58 | * @param {*} object 59 | * @param {Set} [seen] 60 | * @return {boolean} 61 | * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value} 62 | */ 63 | static isCyclic(object, seen = new Set) { 64 | if (typeof object !== 'object') { 65 | return false; 66 | } 67 | 68 | if (seen.has(object)) { 69 | return true; 70 | } 71 | 72 | seen.add(object); 73 | // Each path has its own set of seen objects 74 | return Object.values(object).some(value => ( 75 | this.isCyclic(value, new Set(seen)) 76 | )); 77 | } 78 | 79 | /** 80 | * Convert URL filter strings to UrlFilter and UrlExceptions objects. 81 | * @param {string[]} urlFilters 82 | * @return {Object[]} 83 | * @see {@link https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/events/UrlFilter} 84 | * @see {@link https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webNavigation/onCompleted} 85 | */ 86 | static createUrlFilter(urlFilters) { 87 | // [UrlFilter, UrlExceptions] 88 | const filter = [ 89 | {url: []}, 90 | {url: []}, 91 | ]; 92 | 93 | urlFilters.forEach(urlFilter => { 94 | // Type === 0 ? UrlFilter : UrlExceptions 95 | let type = 0; 96 | 97 | // Filters beginning with `!` are URL exceptions 98 | const exceptionMark = urlFilter.match(/^\s*!\s*/); 99 | if (exceptionMark) { 100 | // Remove the exception mark from the string 101 | urlFilter = urlFilter.substr(exceptionMark[0].length); 102 | type = 1; 103 | } 104 | 105 | // This tests if the URL filter string looks like a RegExp 106 | if ( 107 | urlFilter.substr(0, 1) === '/' 108 | && urlFilter.substr(-1, 1) === '/' 109 | ) { 110 | // If the string is a valid RegExp, 111 | // let the filter be a RegExp matching filter. 112 | try { 113 | const urlMatches = urlFilter.slice(1, -1); 114 | // Verify that the string is a valid RegExp 115 | RegExp(urlMatches); 116 | filter[type].url.push({urlMatches}); 117 | return; 118 | } catch (error) { 119 | Logger.log(error); 120 | } 121 | } 122 | // Or let the filter be a string filter by default 123 | filter[type].url.push({urlContains: urlFilter}); 124 | }); 125 | 126 | return filter; 127 | } 128 | 129 | /** 130 | * Check if the URL matches at least one of the filters or 131 | * if no filter is set (optional). 132 | * @param {string} url 133 | * @param {Object} filter 134 | * @param {boolean} [optional] 135 | * @return {boolean} 136 | * @see {Utils.createUrlFilter} 137 | */ 138 | static testUrl(url, filter, optional = true) { 139 | if (optional && filter.url.length === 0) { 140 | return true; 141 | } 142 | 143 | return filter.url.some(({urlContains, urlMatches}) => { 144 | if (urlContains) { 145 | return url.includes(urlContains); 146 | } else if (urlMatches) { 147 | return RegExp(urlMatches).test(url); 148 | } 149 | return false; 150 | }); 151 | } 152 | 153 | /** 154 | * Compare two versions. 155 | * @param {string} [version1] 156 | * @param {string} [version2] 157 | * @return {Object} 158 | */ 159 | static versionCompare(version1 = '', version2 = '') { 160 | // Parts of a version string 161 | const parts = ['major', 'minor', 'patch']; 162 | 163 | const version1Parts = version1.split('.').map(Number); 164 | const version2Parts = version2.split('.').map(Number); 165 | 166 | for (let i = 0; i < parts.length; i++) { 167 | if (version1Parts[i] < version2Parts[i]) { 168 | return { 169 | result: -1, 170 | difference: parts[i], 171 | }; 172 | } else if (version1Parts[i] > version2Parts[i]) { 173 | return { 174 | result: 1, 175 | difference: parts[i], 176 | }; 177 | } 178 | } 179 | return { 180 | result: 0, 181 | }; 182 | } 183 | } 184 | 185 | Binder.bindOwn(Utils); 186 | 187 | /** 188 | * @typedef {(primitive|Object|UtilsComparable[])} UtilsComparable 189 | */ 190 | 191 | /** 192 | * @typedef {(boolean|null|undefined|number|string|symbol)} primitive 193 | */ 194 | -------------------------------------------------------------------------------- /src/page/options/js/class/DOM.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Provide useful functions to work with DOM. 5 | */ 6 | class DOM { 7 | /** 8 | * Create node(s). 9 | * @param {NodeDetails} 10 | * @return {(HTMLElement|Node|void)} 11 | */ 12 | static createNode({ 13 | tagName, 14 | text, 15 | classList, 16 | attributes, 17 | parent, 18 | children, 19 | }) { 20 | let node; 21 | 22 | // Property 'tagName' prevails over 'text' 23 | if (tagName) { 24 | node = document.createElement(tagName); 25 | 26 | // Classes if exists, 27 | // are added to the element. 28 | if (classList && classList.length) { 29 | node.classList.add.apply(node.classList, classList); 30 | } 31 | 32 | if (attributes) { 33 | Object.entries(attributes).forEach(([name, value]) => { 34 | // An attribute is set only if it's a string 35 | if (typeof value === 'string') { 36 | node.setAttribute(name, value); 37 | } 38 | }); 39 | } 40 | 41 | // Recursively create children nodes 42 | if (children) { 43 | children.forEach(child => { 44 | if (child instanceof Node) { 45 | node.appendChild(child); 46 | } else { 47 | this.createNode({...child, parent: node}); 48 | } 49 | }); 50 | } 51 | } else if (text) { 52 | node = document.createTextNode(text); 53 | } else { 54 | return; 55 | } 56 | 57 | return parent ? parent.appendChild(node) : node; 58 | } 59 | 60 | /** 61 | * Build an input based on the instructions. 62 | * @param {Object} 63 | * @return {Object} 64 | */ 65 | static buildInput({parent, input, domValue}) { 66 | // A function to create input 67 | let builder; 68 | // The key of the DOM value to pass to the builder 69 | let key; 70 | 71 | switch (input.tagName.toUpperCase()) { 72 | case 'TEXTAREA': 73 | builder = this.createTextareaGroup; 74 | key = 'text'; 75 | break; 76 | case 'INPUT': 77 | builder = this.createInputGroup; 78 | key = 'text'; 79 | break; 80 | case 'SELECT': 81 | builder = this.createSelectGroup; 82 | key = 'selection'; 83 | break; 84 | case 'SWITCH': 85 | builder = this.createToggleSwitch; 86 | key = 'checked'; 87 | break; 88 | default: 89 | builder = this.createNode; 90 | key = 'text'; 91 | } 92 | 93 | return builder({...input, parent, [key]: domValue}); 94 | } 95 | 96 | /** 97 | * Create a textarea element group. 98 | * @param {TextareaGroupDetails} 99 | * @return {Object} 100 | */ 101 | static createTextareaGroup({label, parent, text, placeholder}) { 102 | const textarea = this.createNode({ 103 | tagName: 'TEXTAREA', 104 | attributes: {placeholder}, 105 | children: text ? [{text}] : [], 106 | }); 107 | 108 | const container = this.createNode({ 109 | tagName: 'DIV', 110 | classList: ['multiline-input'], 111 | parent, 112 | children: [ 113 | { 114 | tagName: 'LABEL', 115 | children: [{text: label}], 116 | }, 117 | { 118 | tagName: 'DIV', 119 | classList: ['textarea'], 120 | children: [textarea], 121 | } 122 | ] 123 | }); 124 | 125 | return {container, input: textarea}; 126 | } 127 | 128 | /** 129 | * Create an input element group. 130 | * @param {InputGroupDetails} 131 | * @return {Object} 132 | */ 133 | static createInputGroup({label, parent, text, placeholder}) { 134 | const input = this.createNode({ 135 | tagName: 'INPUT', 136 | attributes: { 137 | value: text, 138 | placeholder, 139 | }, 140 | }); 141 | 142 | const container = this.createNode({ 143 | tagName: 'DIV', 144 | classList: ['input'], 145 | parent, 146 | children: [ 147 | { 148 | tagName: 'LABEL', 149 | children: [{text: label}], 150 | }, 151 | input, 152 | ], 153 | }); 154 | 155 | return {container, input}; 156 | } 157 | 158 | /** 159 | * Create a select element group. 160 | * @param {SelectGroupDetails} 161 | * @return {Object} 162 | */ 163 | static createSelectGroup({label, parent, options, selection}) { 164 | const select = this.createNode({ 165 | tagName: 'SELECT', 166 | children: Object.entries(options).map(([value, text]) => ({ 167 | tagName: 'OPTION', 168 | attributes: { 169 | value, 170 | selected: value === selection ? '' : null, 171 | }, 172 | children: [{text}], 173 | })), 174 | }); 175 | 176 | const container = this.createNode({ 177 | tagName: 'DIV', 178 | classList: ['input'], 179 | parent, 180 | children: [ 181 | { 182 | tagName: 'LABEL', 183 | children: [{text: label}], 184 | }, 185 | select, 186 | ], 187 | }); 188 | 189 | return {container, input: select}; 190 | } 191 | 192 | /** 193 | * Create a toggle switch element. 194 | * @param {ToggleSwitchDetails} 195 | * @return {Object} 196 | */ 197 | static createToggleSwitch({parent, labels, checked}) { 198 | const checkbox = this.createNode({ 199 | tagName: 'INPUT', 200 | attributes: { 201 | type: 'checkbox', 202 | checked, 203 | }, 204 | }); 205 | 206 | const container = this.createNode({ 207 | tagName: 'SPAN', 208 | parent, 209 | children: [{ 210 | tagName: 'LABEL', 211 | classList: ['switch'], 212 | children: [ 213 | checkbox, 214 | { 215 | tagName: 'SPAN', 216 | classList: ['slider'], 217 | children: [ 218 | { 219 | tagName: 'SPAN', 220 | children: [ 221 | { 222 | tagName: 'SPAN', 223 | children: [{text: labels[0]}], 224 | }, 225 | { 226 | tagName: 'SPAN', 227 | children: [{text: labels[1]}], 228 | }, 229 | ], 230 | }, 231 | ], 232 | }, 233 | ], 234 | }], 235 | }); 236 | 237 | return {container, input: checkbox}; 238 | } 239 | 240 | /** 241 | * Create a button element. 242 | * @param {ButtonDetails} 243 | * @return {Object} 244 | */ 245 | static createButton({parent, text, highlight = []}) { 246 | const classList = highlight.length ? highlight : ['highlight-ok']; 247 | 248 | const button = this.createNode({ 249 | tagName: 'BUTTON', 250 | classList, 251 | children: [{text}], 252 | }); 253 | 254 | const container = this.createNode({ 255 | tagName: 'SPAN', 256 | parent, 257 | children: [button], 258 | }); 259 | 260 | return {container, button}; 261 | } 262 | 263 | /** 264 | * Get element value. 265 | * @param {DOMInput} element 266 | * @return {string} 267 | */ 268 | static value(element) { 269 | if (element.getAttribute('type') === 'checkbox') { 270 | return element.checked ? 'enabled' : 'disabled'; 271 | } 272 | return element.value; 273 | } 274 | 275 | /** 276 | * Activate an element. 277 | * @param {Element} element 278 | */ 279 | static activate(element) { 280 | if (this.isActive(element)) { 281 | return; 282 | } 283 | 284 | // Deactivate siblings 285 | Array.from(element.parentElement.children).forEach(sibling => { 286 | this.deactivate(sibling); 287 | }); 288 | // Activate the element 289 | element.classList.add('active'); 290 | } 291 | 292 | /** 293 | * Deactivate an element. 294 | * @param {Element} element 295 | */ 296 | static deactivate(element) { 297 | element.classList.remove('active'); 298 | } 299 | 300 | /** 301 | * Check if an element is active. 302 | * @param {Element} element 303 | * @return {boolean} True if the element is active. 304 | */ 305 | static isActive(element) { 306 | return element.classList.contains('active'); 307 | } 308 | 309 | /** 310 | * Enable an element. 311 | * @param {Element} element 312 | */ 313 | static enable(element) { 314 | element.classList.add('enabled'); 315 | } 316 | 317 | /** 318 | * Disable an element. 319 | * @param {Element} element 320 | */ 321 | static disable(element) { 322 | element.classList.remove('enabled'); 323 | } 324 | 325 | /** 326 | * Get element by ID. 327 | * @param {string} id 328 | * @return {(HTMLElement|null)} 329 | */ 330 | static id(id) { 331 | return document.getElementById(id); 332 | } 333 | } 334 | 335 | Binder.bind(DOM); 336 | 337 | /** 338 | * @typedef {Object} NodeDetails 339 | * @property {string} [tagName] 340 | * @property {string} [text] 341 | * @property {string[]} [classList] 342 | * @property {Object} [attributes] 343 | * @property {HTMLElement} [parent] 344 | * @property {NodeDetails[]} [children] 345 | */ 346 | 347 | /** 348 | * @typedef {Object} TextareaGroupDetails 349 | * @property {string} label 350 | * @property {HTMLElement} [parent] 351 | * @property {string} [text] 352 | * @property {string} [placeholder] 353 | */ 354 | 355 | /** 356 | * @typedef {Object} InputGroupDetails 357 | * @property {string} label 358 | * @property {HTMLElement} [parent] 359 | * @property {string} [text] 360 | * @property {string} [placeholder] 361 | */ 362 | 363 | /** 364 | * @typedef {Object} SelectGroupDetails 365 | * @property {string} label 366 | * @property {HTMLElement} [parent] 367 | * @property {Object} [options] 368 | * @property {string} [selection] 369 | */ 370 | 371 | /** 372 | * @typedef {Object} ToggleSwitchDetails 373 | * @property {HTMLElement} [parent] 374 | * @property {Object} [checked] 375 | */ 376 | 377 | /** 378 | * @typedef {HTMLElement} DOMInput 379 | * @property {boolean} [checked] 380 | * @property {string} [value] 381 | */ 382 | 383 | /** 384 | * @typedef {Object} ButtonDetails 385 | * @property {HTMLElement} [parent] 386 | * @property {Object} [text] 387 | * @property {string[]} [highlight] 388 | */ 389 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Man in the Middle 2 | 3 | [![License](https://img.shields.io/badge/License-GPLv3-blue.svg)](LICENSE) 4 | 5 | _Firefox Extension._ 6 | 7 | --- 8 | 9 | Allow user to block or redirect requests, modify request headers and responses, inject JavaScript and CSS into pages. 10 | 11 | --- 12 | 13 | **[Get Man in the Middle](https://addons.mozilla.org/en-US/firefox/addon/man-in-the-middle/)** on Firefox Add-ons. 14 | **[Get help](#rules)** writing rules. 15 | **[See changes](https://github.com/dangkyokhoang/man-in-the-middle/projects/1)** in the Project board. 16 | 17 | Use cases: 18 | - Block or redirect websites and requests; 19 | - Add, modify or remove request and response headers; 20 | - Modify response data; 21 | - Inject JavaScript into pages to make them function as desired; 22 | - Inject CSS into pages to style them as desired. 23 | 24 | 25 | ## Screenshots 26 | 27 | ![Block or redirect requests](https://addons.cdn.mozilla.net/user-media/previews/full/211/211170.png?modified=1542319742) 28 | _Use Blocking Rules to block or redirect requests._ 29 | 30 | ![Modify request and response headers](https://addons.cdn.mozilla.net/user-media/previews/full/211/211152.png?modified=1542280030) 31 | _Use Header Rules to modify request and response headers._ 32 | 33 | ![Use JavaScript to modify request headers](https://addons.cdn.mozilla.net/user-media/previews/full/211/211153.png?modified=1542280030) 34 | _Headers can be modified using JavaScript._ 35 | 36 | ![Use JavaScript to modify response body](https://addons.cdn.mozilla.net/user-media/previews/full/211/211154.png?modified=1542280030) 37 | _Use Response Rules to modify network responses._ 38 | 39 | ![Inject JavaScript and CSS into pages](https://addons.cdn.mozilla.net/user-media/previews/full/211/211151.png?modified=1542293585) 40 | _Use Content Scripts to inject JavaScript and CSS codes into pages._ 41 | 42 | ![Man in the Middle dark theme](https://addons.cdn.mozilla.net/user-media/previews/full/211/211160.png?modified=1542300620) 43 | _Content Scripts can even be injected to the extension's pages._ 44 | 45 | 46 | ## Rules 47 | Select rule properties for more details. 48 | 49 | ### Blocking Rules 50 | Rules to block or redirect requests. 51 | - [URL filters (Required)](#url-filters); 52 | - [Method](#method); 53 | - [Text redirect URL](#text-redirect-url); 54 | - [Text type](#text-type); 55 | - [Redirect URL](#redirect-url); 56 | - [Origin URL filters](#origin-url-filters). 57 | 58 | ### Header Rules 59 | Rules to modify request and response headers. 60 | - [Text headers (Required)](#text-headers); 61 | - [Text type](#text-type); 62 | - [Header type](#header-type); 63 | - [URL filters (Required)](#url-filters); 64 | - [Method](#method); 65 | - [Origin URL filters](#origin-url-filters). 66 | 67 | ### Response Rules 68 | Rules to modify network responses. 69 | - [Text response (Required)](#text-response); 70 | - [Text type](#text-type); 71 | - [URL filters (Required)](#url-filters); 72 | - [Method](#method); 73 | - [Origin URL filters](#origin-url-filters). 74 | 75 | ### Content Scripts 76 | Rules to inject JavaScript and CSS into pages. 77 | - [Code (Required)](#code); 78 | - [Script type](#script-type); 79 | - [URL filters (Required)](#url-filters); 80 | - [DOM event](#dom-event); 81 | - [Origin URL filters](#origin-url-filters). 82 | 83 | 84 | ## Properties 85 | 86 | ### URL filters 87 | Filter `request URL`s or `document URL`s. 88 | - Format: [RegExp pattern](#regexp-pattern) or [String filter](#string-filter). 89 | - Separator: `line break`, i.e, `'\n'`, `'\r'` or `'\r\n'`. 90 | - A filter that begins with an exclamation mark `'!'` is a `URL exception`. 91 | - A `URL` is satisfied if it matches at least one of the filters and DOES NOT match any `URL exception`. 92 | - A `URL` matches a filter if it matches the `RegExp pattern` or includes the `String filter`. 93 | - Examples: 94 | ```` 95 | Any site is matched 96 | http 97 | ```` 98 | ```` 99 | Any site is matched, but not www.google.com 100 | http 101 | !www.google.com 102 | ```` 103 | - Rules: [Blocking Rules](#blocking-rules), [Header Rules](#header-rules), [Response Rules](#response-rules) and [Content Scripts](#content-scripts). 104 | 105 | ### Method 106 | Filters `request method`s. 107 | - Value can be `'*'` or one of the HTTP request methods, i.e, `'GET'`, `'POST'`, `'HEAD'`, etc. 108 | - A `request method` is satisfied if it equals to the `method`. 109 | - Rules: [Blocking Rules](#blocking-rules), [Header Rules](#header-rules) and [Response Rules](#response-rules). 110 | 111 | ### Text redirect URL 112 | To redirect or block requests. 113 | - Format: `Plaintext` or [Restricted JavaScript](#restricted-javascript). 114 | - Type `Plaintext`: 115 | _A `URL` to redirect `request`s to._ 116 | - If not set, matched requests are blocked. 117 | - Parameters `'$n'` (`1 <= n <= 100`), in a `redirect URL` are replaced with capture groups from `RegExp pattern` [URL filter](#url-filters). 118 | - Examples: 119 | ```` 120 | Force secure connections for all HTTP requests. 121 | URL filter: /^http:(.*)/ 122 | Text redirect URL: https:$1 123 | ```` 124 | - Type [Restricted JavaScript](#restricted-javascript): 125 | _Returns a `URL` to redirect `request`s to._ 126 | - The code must `return` a string `URL`. 127 | - If `URL` is empty, matched requests are blocked; 128 | - If `URL` equals to the request's URL, the request is neither blocked nor redirected; 129 | - Otherwise, the request is redirected to `URL`. 130 | - Examples: 131 | ```` JavaScript 132 | // Facebook hours restricted to the range from 07:00 PM to 11:59 PM 133 | // URL filter: facebook.com, messenger.com 134 | // Text redirect URL: 135 | const date = new Date(); 136 | const hour = date.getHours(); 137 | return 19 <= hour && hour <= 23 ? url : ''; 138 | ```` 139 | - Rule: [Blocking Rules](#blocking-rules). 140 | 141 | ### Redirect URL 142 | DEPRECATED since version 3.4.0. Use [Text redirect URL](#text-redirect-url) instead. 143 | - Rules: [Blocking Rules](#blocking-rules). 144 | 145 | ### Origin URL filters 146 | Filter `document URL`s. 147 | - Format: [RegExp pattern](#regexp-pattern) or [String filter](#string-filter). 148 | - Separator: comma `','`. 149 | - A `document URL` is satisfied if one of the following is satisfied: 150 | - No `filter` is set (default); 151 | - The `document URL` matches one of the filters. 152 | - A `document URL` matches a filter if it matches the `RegExp pattern` or includes the `String filter`. 153 | - Rules: [Blocking Rules](#blocking-rules), [Header Rules](#header-rules), [Response Rules](#response-rules) and [Content Scripts](#content-scripts). 154 | 155 | ### Text headers 156 | To modify request or response headers. 157 | - Format: `Plaintext` or [Restricted JavaScript](#restricted-javascript). 158 | - Type `Plaintext`: 159 | _`Pair`s of headers._ 160 | - Separator: `line break`, i.e, `'\n'`, `'\r'` or `'\r\n'`. 161 | - A `Pair` is of the format: `name: value`. 162 | - If `name` is empty, the header is omitted. 163 | - If `value` is empty, the header with the name `name` is removed if it exists, or the header is omitted. 164 | - If a header with the name `name` exists, the header is modified. If there're more than one existing, the first is modified. 165 | - If no header with the name `name` exists, a new header is added. 166 | - Examples: 167 | ```` 168 | This overrides the default Accept header 169 | Accept: * 170 | ```` 171 | ```` 172 | This removes Referer header if it exists 173 | Referer: 174 | ```` 175 | ```` 176 | This adds new headers to the request 177 | Test-0: On 178 | Test-1: Off 179 | ```` 180 | - Type [Restricted JavaScript](#restricted-javascript): 181 | _Returns request or response headers._ 182 | - The code must `return` an array of objects, each objects has two properties: `'name'` and `'value'`. 183 | - The code may access `requestHeaders` or `responseHeaders`, depending on the [Header type](#header-type). 184 | - The header array `requestHeaders` or `responseHeaders` has its methods to make it easier to modify headers: 185 | - `get(name)` gets header by name; 186 | - `set(name, value)` replaces header value if it exists, or adds a new header; 187 | - `modify([ ...[name, value] ])` sets multiple pairs of headers. 188 | - Examples: 189 | ```` JavaScript 190 | // Header type: Request headers 191 | // This do nothing but log the request headers to the console. 192 | throw requestHeaders; 193 | ```` 194 | ```` JavaScript 195 | // This line 196 | const acceptHeader = requestHeaders.get('Accept'); 197 | // equals to the below 198 | const acceptHeader = const acceptHeader = requestHeaders.find(({name}) => ( 199 | name.toLowerCase() === 'accept' 200 | )); 201 | ```` 202 | ```` JavaScript 203 | // Header type: Request headers 204 | 205 | // This line 206 | requestHeaders.modify([ ['Accept', '*'] ]); 207 | // equals to this line 208 | requestHeaders.set('Accept', '*'); 209 | // and equals to the below lines 210 | const acceptHeader = requestHeaders.get('Accept'); 211 | if (acceptHeader) { 212 | acceptHeader.value = '*'; 213 | } else { 214 | requestHeaders.push({name: 'Accept', value: '*'}); 215 | } 216 | 217 | return requestHeaders; 218 | ```` 219 | ```` JavaScript 220 | // Header type: Request headers 221 | // This line 222 | requestHeaders.modify([ ['Referer', ''] ]); 223 | // equals to the below 224 | const refererHeaderIndex = requestHeaders.findIndex(({name}) => ( 225 | name.toLowerCase() === 'referer' 226 | )); 227 | // Remove Referer header 228 | if (refererHeaderIndex !== -1) { 229 | requestHeaders.splice(refererHeaderIndex, 1); 230 | } 231 | 232 | return requestHeaders; 233 | ```` 234 | ```` JavaScript 235 | // Header type: Response headers 236 | responseHeaders.push({ 237 | name: 'Set-Cookie', 238 | value: 'Firefox-Extension=Man in the Middle; HttpOnly', 239 | }); 240 | return responseHeaders; 241 | ```` 242 | - Rule: [Header Rules](#header-rules). 243 | 244 | ### Text type 245 | `'Plaintext'` or`'JavaScript'`. 246 | - Rule: [Blocking Rules](#blocking-rules), [Header Rules](#header-rules) and [Response Rules](#response-rules). 247 | 248 | ### Header type 249 | `'Request headers'` or `'Response headers'`. 250 | - Rule: [Header Rules](#header-rules). 251 | 252 | ### Text response 253 | To modify network responses. 254 | - Format: `Plaintext` or [Restricted JavaScript](#restricted-javascript). 255 | - Type `Plaintext`: 256 | _Any text as response body._ 257 | - Type [Restricted JavaScript](#restricted-javascript): 258 | _Returns response body._ 259 | - The code must `return` a string which is the response body. 260 | - The code may access `responseBody` and `responseHeaders`. 261 | - Examples: 262 | ```` JavaScript 263 | // Site: http://internetbadguys.com/ 264 | return ` 265 | 266 | 267 | 268 | 269 | 270 |

Bad guys are ${( 271 | responseBody.includes('phish.opendns.com/?url=') ? 'blocked' : 'coming' 272 | )}!

273 | 274 | `; 275 | ```` 276 | - Rule: [Response Rules](#response-rules). 277 | 278 | ### Code 279 | `JavaScript` or `CSS` code to be injected. 280 | - Rule: [Content Scripts](#content-scripts). 281 | 282 | ### Script type 283 | `'JavaScript'` or `'CSS'`. 284 | - To see error logs, open the `devtools > Console`. 285 | - Rule: [Content Scripts](#content-scripts). 286 | 287 | ### DOM event 288 | A stage of the `DOM` loading on which the code is injected. 289 | - Can be one of the following values: 290 | - `Loading`; 291 | - `Loaded`; 292 | - `Completed`. 293 | - Rule: [Content Scripts](#content-scripts). 294 | 295 | 296 | ## Formats 297 | 298 | ### RegExp pattern 299 | Begins with a slash `'/'` and ends with a slash `'/'`. 300 | - The characters inside the two slashes must form a valid RegExp, otherwise, the pattern is treated as a [String filter](#string-filter). 301 | - Examples: 302 | ```` 303 | /./ 304 | /faceb(\w{2})k\.[\w]+/ 305 | ```` 306 | - Properties: [URL filters](#url-filters) and [Origin URL filters](#origin-url-filters). 307 | 308 | ### String filter 309 | A string that is not a [RegExp pattern](#regexp-pattern). 310 | - Examples: 311 | ```` 312 | http 313 | facebook.com 314 | /invalid { RegExp/ 315 | ```` 316 | - Properties: [URL filters](#url-filters) and [Origin URL filters](#origin-url-filters). 317 | 318 | 319 | ### Restricted JavaScript 320 | A JavaScript function body that will be executed inside a sandbox. 321 | - The code may use only built-in objects and some APIs, which are: 322 | - `Object`, `Array`, `String`, `RegExp`, `JSON`, `Map`, `Set`, `Promise`, ...built-in objects; 323 | - `isFinite`, `isNaN`, `parseInt`, `parseFloat`; 324 | - `encodeURI`, `encodeURIComponent`, `decodeURI`, `decodeURIComponent`; 325 | - `crypto`, `performance`, `atob`, `btoa`, `fetch` and `XMLHttpRequest`. 326 | - The code may access request details and tab details, which are: 327 | - `url`, `originUrl`, `documentUrl`, `method`, `proxyInfo`, `type` (the type of the requested resource), `timeStamp`; 328 | - `incognito` (`true` if tab in private browsing), `pinned` (`true` if tab is pinned). 329 | - The function is `async`, hence, `await` can be used to perform asynchronous tasks. 330 | - The code should always `return` a value. 331 | - The code may `throw` a cloneable value. To see error logs, open the `devtools > Console`. 332 | - Properties: [Text redirect URL](#text-redirect-url), [Text headers](#text-headers) and [Text response](#text-response). 333 | 334 | 335 | 336 | ## Others 337 | 338 | - If you have questions or need help, feel free to message me at: 339 | [facebook/dangkyokhoang](https://www.facebook.com/dangkyokhoang). 340 | - If you have feature requests, suggestions, or you've found bugs, raise issues at: 341 | [man-in-the-middle/issues](https://github.com/dangkyokhoang/man-in-the-middle/issues). 342 | -------------------------------------------------------------------------------- /src/page/options/js/class/Collection.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Create and organize rule elements. 5 | */ 6 | class Collection { 7 | /** 8 | * Initialize rule elements by types. 9 | * If no type is specified, initialize all types of rules. 10 | * @param {(string[]|string|void)} [types] 11 | * @param {Object} [data] 12 | * @return {Promise} 13 | */ 14 | static async initialize(types = this.getTypes(), data) { 15 | if (Array.isArray(types)) { 16 | types.forEach(type => { 17 | this.initialize(type, data ? data[type] : null); 18 | }); 19 | return; 20 | } 21 | 22 | // String 23 | const type = types; 24 | 25 | // Remove existing rule elements of this type 26 | this.getRules(type).forEach(id => this.removeItem(type, id)); 27 | 28 | // Create new elements 29 | data = data || await this.getData(type); 30 | data && data.forEach(details => this.create(type, details)); 31 | } 32 | 33 | /** 34 | * Create and display rule element. 35 | * @param {string} type 36 | * @param {RuleDetails} details 37 | * @return {HTMLElement} 38 | */ 39 | static create(type, details) { 40 | const {id, enabled} = details; 41 | 42 | // Create rule wrapper element 43 | const parent = DOM.createNode({ 44 | tagName: 'ARTICLE', 45 | parent: this.containers[type], 46 | classList: enabled ? ['enabled'] : null, 47 | }); 48 | 49 | // Sequentially create input elements for rule properties 50 | for (const property of this.types[type]) { 51 | // Only display properties in the instructions 52 | if (!this.instructions.hasOwnProperty(property)) { 53 | continue; 54 | } 55 | 56 | const value = details[property]; 57 | const {valueType, input} = this.instructions[property]; 58 | const {tagName} = input; 59 | const domValue = this.toDomValue({value, tagName, valueType}); 60 | 61 | const element = DOM.buildInput({parent, input, domValue}); 62 | 63 | if (property === 'name') { 64 | // Clicking textarea group activates or deactivates the item 65 | element.container.addEventListener('click', ({target}) => { 66 | if (DOM.isActive(parent)) { 67 | if (target.tagName === 'LABEL') { 68 | DOM.deactivate(parent); 69 | } 70 | } else { 71 | DOM.activate(parent); 72 | element.input.focus(); 73 | } 74 | }); 75 | 76 | element.input.addEventListener('focus', () => { 77 | DOM.activate(parent); 78 | }); 79 | } 80 | 81 | if (property === 'enabled') { 82 | element.input.addEventListener('change', ({target}) => { 83 | if (DOM.value(target) === 'enabled') { 84 | DOM.enable(parent); 85 | } else { 86 | DOM.disable(parent); 87 | } 88 | }); 89 | } 90 | 91 | // On input change, 92 | // tell the background script to modify rule property. 93 | element.input.addEventListener('change', ({target}) => { 94 | this.modify(type, id, { 95 | [property]: this.toPropertyValue({ 96 | domValue: DOM.value(target), 97 | tagName, 98 | valueType, 99 | }), 100 | }); 101 | }); 102 | } 103 | 104 | // Create remove button for the rule item 105 | const button = DOM.createButton({ 106 | parent, 107 | text: 'Remove', 108 | highlight: ['highlight-error'], 109 | }); 110 | button.button.addEventListener('dblclick', () => this.remove(type, id)); 111 | 112 | // Add the rule item to the collection 113 | this.items[type].set(id, parent); 114 | 115 | return parent; 116 | } 117 | 118 | /** 119 | * Convert property value to DOM value. 120 | * @private 121 | * @param {Object} 122 | * @return {string|null} 123 | */ 124 | static toDomValue({value, tagName, valueType}) { 125 | switch (tagName) { 126 | case 'TEXTAREA': 127 | return valueType === 'string' ? value : value.join('\n'); 128 | case 'INPUT': 129 | return valueType === 'string' ? value : value.join(', '); 130 | case 'SELECT': 131 | return value; 132 | case 'SWITCH': 133 | return value ? '' : null; 134 | } 135 | } 136 | 137 | /** 138 | * Convert DOM value to property value. 139 | * @private 140 | * @param {Object} 141 | * @return {(string[]|string)} 142 | */ 143 | static toPropertyValue({domValue, tagName, valueType}) { 144 | switch (tagName) { 145 | case 'TEXTAREA': 146 | if (valueType === 'string') { 147 | return domValue; 148 | } 149 | return domValue.trim().split(/\s*[\r\n]\s*/).filter(Boolean); 150 | case 'INPUT': 151 | if (valueType === 'string') { 152 | return domValue; 153 | } 154 | return domValue.trim().split(/\s*,\s*/).filter(Boolean); 155 | case 'SELECT': 156 | // Always be text 157 | return domValue; 158 | case 'SWITCH': 159 | // Always be boolean 160 | return domValue === 'enabled'; 161 | } 162 | } 163 | 164 | /** 165 | * @callback 166 | * @param {string} type 167 | * @return {void} 168 | */ 169 | static add(type) { 170 | Runtime.sendMessage({ 171 | sender: 'optionsPage', 172 | request: 'add', 173 | details: {type}, 174 | }).then(details => { 175 | DOM.activate(this.create(type, details)); 176 | }); 177 | } 178 | 179 | /** 180 | * @callback 181 | * @param {string} type 182 | * @param {string} id 183 | * @return {void} 184 | */ 185 | static remove(type, id) { 186 | Runtime.sendMessage({ 187 | sender: 'optionsPage', 188 | request: 'remove', 189 | details: {type, id}, 190 | }).then(() => { 191 | this.removeItem(type, id); 192 | }); 193 | } 194 | 195 | /** 196 | * Remove the rule item from the item collection. 197 | * @param {string} type 198 | * @param {string} id 199 | * @return {void} 200 | */ 201 | static removeItem(type, id) { 202 | this.items[type].get(id).remove(); 203 | this.items[type].delete(id); 204 | } 205 | 206 | /** 207 | * @callback 208 | * @param {string} type 209 | * @param {string} id 210 | * @param {Object} change 211 | * @return {void} 212 | */ 213 | static modify(type, id, change) { 214 | Runtime.sendMessage({ 215 | sender: 'optionsPage', 216 | request: 'modify', 217 | details: {type, id, change}, 218 | }); 219 | } 220 | 221 | /** 222 | * Get rule data from the background script. 223 | * @param {string} type 224 | * @return {Promise} 225 | */ 226 | static getData(type) { 227 | return Runtime.sendMessage({ 228 | sender: 'optionsPage', 229 | request: 'getData', 230 | details: {type}, 231 | }); 232 | } 233 | 234 | /** 235 | * Get existing rule IDs of a type. 236 | * @param {string} type 237 | * @return {string[]} 238 | */ 239 | static getRules(type) { 240 | return [...this.items[type].keys()]; 241 | } 242 | 243 | /** 244 | * Get rule types. 245 | * @return {string[]} 246 | */ 247 | static getTypes() { 248 | return Object.keys(this.types); 249 | } 250 | 251 | /** 252 | * Create rule containers and add buttons on register. 253 | * @return {void} 254 | */ 255 | static startup() { 256 | // For each type of rule 257 | this.getTypes().forEach(type => { 258 | const section = DOM.id(type); 259 | 260 | // Create container 261 | this.containers[type] = DOM.createNode({ 262 | tagName: 'SECTION', 263 | parent: section, 264 | }); 265 | 266 | // Create add button 267 | const button = DOM.createButton({ 268 | parent: section, 269 | text: 'Add', 270 | highlight: ['highlight-ok'], 271 | }); 272 | button.button.addEventListener('click', () => this.add(type)); 273 | 274 | // Create a map to store created rule elements. 275 | this.items[type] = new Map; 276 | }); 277 | 278 | this.initialize(); 279 | } 280 | } 281 | 282 | Binder.bind(Collection); 283 | 284 | /** 285 | * Rule properties by type. 286 | * @type {Object} 287 | */ 288 | Collection.types = { 289 | blockingRules: [ 290 | 'name', 291 | 'urlFilters', 292 | 'method', 293 | 'textRedirectUrl', 294 | 'textType', 295 | 'originUrlFilters', 296 | 'enabled', 297 | 'sync', 298 | ], 299 | headerRules: [ 300 | 'name', 301 | 'textHeaders', 302 | 'textType', 303 | 'headerType', 304 | 'urlFilters', 305 | 'method', 306 | 'originUrlFilters', 307 | 'enabled', 308 | 'sync', 309 | ], 310 | responseRules: [ 311 | 'name', 312 | 'textResponse', 313 | 'textType', 314 | 'urlFilters', 315 | 'method', 316 | 'originUrlFilters', 317 | 'enabled', 318 | 'sync', 319 | ], 320 | contentScripts: [ 321 | 'name', 322 | 'code', 323 | 'scriptType', 324 | 'urlFilters', 325 | 'domEvent', 326 | 'originUrlFilters', 327 | 'enabled', 328 | 'sync', 329 | ], 330 | }; 331 | 332 | /** 333 | * Rule containers. 334 | * @type {Object} 335 | */ 336 | Collection.containers = {}; 337 | 338 | /** 339 | * Store all rule items. 340 | * @type {Object>} 341 | */ 342 | Collection.items = {}; 343 | 344 | /** 345 | * Instructions to display rule properties. 346 | * @type {Object} 347 | */ 348 | Collection.instructions = { 349 | // RequestRule 350 | name: { 351 | valueType: 'string', 352 | input: { 353 | tagName: 'INPUT', 354 | label: 'Name', 355 | placeholder: 'Rule name', 356 | }, 357 | }, 358 | enabled: { 359 | valueType: 'boolean', 360 | input: { 361 | tagName: 'SWITCH', 362 | labels: ['Disabled', 'Enabled'], 363 | }, 364 | }, 365 | sync: { 366 | valueType: 'boolean', 367 | input: { 368 | tagName: 'SWITCH', 369 | labels: ['Local', 'Sync'], 370 | }, 371 | }, 372 | urlFilters: { 373 | valueType: 'array', 374 | input: { 375 | tagName: 'TEXTAREA', 376 | label: 'URL filters (Required)', 377 | placeholder: 'String or /RegExp/ to filter URLs (Required)', 378 | }, 379 | }, 380 | method: { 381 | valueType: 'string', 382 | input: { 383 | tagName: 'SELECT', 384 | label: 'Method', 385 | options: { 386 | '': '*', 387 | GET: 'GET', 388 | POST: 'POST', 389 | HEAD: 'HEAD', 390 | PUT: 'PUT', 391 | DELETE: 'DELETE', 392 | OPTIONS: 'OPTIONS', 393 | TRACE: 'TRACE', 394 | PATCH: 'PATCH', 395 | }, 396 | }, 397 | }, 398 | originUrlFilters: { 399 | valueType: 'array', 400 | input: { 401 | tagName: 'INPUT', 402 | label: 'Origin URL filters', 403 | placeholder: 'Origin URL filters', 404 | }, 405 | }, 406 | // BlockingRule 407 | textRedirectUrl: { 408 | valueType: 'string', 409 | input: { 410 | tagName: 'TEXTAREA', 411 | label: 'Text redirect URL', 412 | placeholder: 'Plaintext or JavaScript to redirect requests', 413 | }, 414 | }, 415 | // HeaderRule 416 | textHeaders: { 417 | valueType: 'string', 418 | input: { 419 | tagName: 'TEXTAREA', 420 | label: 'Text headers (Required)', 421 | placeholder: 'Plaintext or JavaScript to modify headers (Required)', 422 | }, 423 | }, 424 | textType: { 425 | valueType: 'string', 426 | input: { 427 | tagName: 'SELECT', 428 | label: 'Text type', 429 | options: { 430 | plaintext: 'Plaintext', 431 | JavaScript: 'JavaScript', 432 | }, 433 | }, 434 | }, 435 | headerType: { 436 | valueType: 'string', 437 | input: { 438 | tagName: 'SELECT', 439 | label: 'Header type', 440 | options: { 441 | requestHeaders: 'Request headers', 442 | responseHeaders: 'Response headers', 443 | }, 444 | }, 445 | }, 446 | // ResponseRule 447 | textResponse: { 448 | valueType: 'string', 449 | input: { 450 | tagName: 'TEXTAREA', 451 | label: 'Text response (Required)', 452 | placeholder: 'Plaintext or JavaScript to modify response body (Required)', 453 | }, 454 | }, 455 | // ContentScript 456 | code: { 457 | valueType: 'string', 458 | input: { 459 | tagName: 'TEXTAREA', 460 | label: 'Code (Required)', 461 | placeholder: 'JavaScript or CSS as content script (Required)', 462 | }, 463 | }, 464 | scriptType: { 465 | valueType: 'string', 466 | input: { 467 | tagName: 'SELECT', 468 | label: 'Script type', 469 | options: { 470 | JavaScript: 'JavaScript', 471 | CSS: 'CSS', 472 | }, 473 | }, 474 | }, 475 | domEvent: { 476 | valueType: 'string', 477 | input: { 478 | tagName: 'SELECT', 479 | label: 'DOM event', 480 | options: { 481 | loading: 'Loading', 482 | loaded: 'Loaded', 483 | completed: 'Completed', 484 | }, 485 | }, 486 | }, 487 | }; 488 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------