Add PAC modifiers w/ custom proxies and other stuff

This commit is contained in:
Ilya Ig. Petrov 2017-01-15 15:04:01 +00:00
parent 704ed61a7c
commit bbd134b871
6 changed files with 448 additions and 53 deletions

View File

@ -26,6 +26,23 @@ window.utils = {
},
getProp(obj, path = this.mandatory()) {
const props = path.split('.');
if (!props.length) {
throw new TypeError('Property must be supplied.');
}
const lastProp = props.pop();
for( const prop of props ) {
if (!(prop in obj)) {
return undefined;
}
obj = obj[prop];
}
return obj[lastProp];
},
areSettingsNotControlledFor(details) {
return ['controlled_by_other', 'not_controllable']

View File

@ -415,7 +415,7 @@
desc: 'Основной PAC-скрипт от автора расширения.' +
' Блокировка определятся по доменному имени или IP адресу.' +
' Работает на switch-ах. <br/>' +
' <a href="https://rebrand.ly/anticensority">Страница проекта</a>.',
' <a href="https://rebrand.ly/ac-anticensority">Страница проекта</a>.',
/*
Don't use in system configs! Because Windows does poor caching.

View File

@ -0,0 +1,252 @@
'use strict';
{ // Private namespace starts.
const kitchenStorageKey = 'pac-kitchen-kept-mods';
const kitchenStartsMark = '\n\n//%#@@@@@@ PAC_KITCHEN_STARTS @@@@@@#%';
const configs = {
ifProxyHttpsUrlsOnly: {
dflt: false,
label: 'проксировать только HTTP<span style="border-bottom: 1px solid black">S</span>-сайты',
desc: 'Проксировать только сайты, доступные по шифрованному протоколу HTTPS. Прокси и провайдер смогут видеть только адреса посещаемых вами ресурсов, но не их содержимое.',
index: 0,
},
ifUseSecureProxiesOnly: {
dflt: false,
label: 'только шифрованная связь с прокси',
desc: 'Шифровать соединение до прокси от провайдера. Провайдер всё же сможет видеть адреса (но не содержимое) посещаемых вами ресурсов из протокола DNS.',
index: 1,
},
ifUsePacScriptProxies: {
dflt: true,
label: 'использовать прокси PAC-скрипта',
desc: 'Использовать прокси от авторов PAC-скрипта.',
index: 2,
},
ifUseLocalTor: {
dflt: false,
label: 'использовать свой локальный TOR',
desc: 'Установите TOR на свой компьютер и используйте его как прокси. <a href="https://rebrand.ly/ac-tor">ВАЖНО</a>',
index: 3,
},
customProxyStringRaw: {
dflt: '',
label: 'использовать свои прокси',
url: 'https://rebrand.ly/ac-own-proxy',
index: 4,
},
};
const getDefaults = function getDefaults() {
return Object.keys(configs).reduce((acc, key) => {
acc[key] = configs[key].dflt;
return acc;
}, {});
};
const getCurrentConfigs = function getCurrentConfigs() {
const json = localStorage.getItem(kitchenStorageKey);
if (!json) {
return null;
}
return new PacModifiers(JSON.parse(json));
};
const getOrderedConfigsForUser = function getOrderedConfigs() {
const pacMods = getCurrentConfigs() || {};
return Object.keys(configs).reduce((arr, key) => {
const conf = configs[key]
arr[conf.index] = conf;
conf.value = (key in pacMods) ? pacMods[key] : conf.dflt;
conf.key = key;
return arr;
}, []);
};
class PacModifiers {
constructor(mods = {}) {
const defaults = getDefaults();
const ifAllDefaults =
Object.keys(defaults)
.every(
(prop) => !(prop in mods) || Boolean(defaults[prop]) === Boolean(mods[prop])
);
Object.assign(this, defaults, mods);
this.ifNoMods = ifAllDefaults ? true : false;
let customProxyArray = [];
if (this.customProxyStringRaw) {
customProxyArray = this.customProxyStringRaw
.replace(/#.*$/mg, '') // Strip comments.
.split( /(?:[^\S\r\n]*(?:;|\r?\n)+[^\S\r\n]*)+/g ).filter( (p) => p.trim() );
if (this.ifUseSecureProxiesOnly) {
customProxyArray = customProxyArray.filter( (p) => !p.startsWith('HTTP ') );
}
}
if (this.ifUseLocalTor) {
customProxyArray.push('SOCKS5 localhost:9050', 'SOCKS5 localhost:9150');
}
if (customProxyArray.length) {
this.customProxyArray = customProxyArray;
this.filteredCustomsString = customProxyArray.join('; ');
} else {
if (!this.ifUsePacScriptProxies) {
throw new TypeError('Нет ни одного прокси, удовлетворяющего вашим требованиям!');
}
this.customProxyArray = false;
this.filteredCustomsString = '';
}
}
};
window.apis.pacKitchen = {
getConfigs: getOrderedConfigsForUser,
cook(pacData, pacMods = window.utils.mandatory()) {
return pacMods.ifNoMods ? pacData : pacData + `${ kitchenStartsMark }
;+function(global) {
"use strict";
const originalFindProxyForURL = FindProxyForURL;
global.FindProxyForURL = function(url, host) {
${function() {
let res = '';
if (pacMods.ifProxyHttpsUrlsOnly) {
res = `
if (!url.startsWith("https")) {
return "DIRECT";
}
`;
if(
!pacMods.ifUseSecureProxiesOnly &&
!pacMods.filteredCustomsString &&
pacMods.ifUsePacScriptProxies
) {
return res + `
return originalFindProxyForURL(url, host);`;
}
}
return res + `
const originalProxyString = originalFindProxyForURL(url, host);
let originalProxyArray = originalProxyString.split(/(?:\\s*;\\s*)+/g).filter( (p) => p );
if (originalProxyArray.every( (p) => /^DIRECT$/i.test(p) )) {
// Directs only or null, no proxies.
return originalProxyString;
}
return ` +
function() {
if (!pacMods.ifUsePacScriptProxies) {
return '"' + pacMods.filteredCustomsString + '"';
}
let filteredOriginalsExp = 'originalProxyString';
if (pacMods.ifUseSecureProxiesOnly) {
filteredOriginalsExp =
'originalProxyArray.filter( (p) => !p.toUpperCase().startsWith("HTTP ") ).join("; ")';
}
if ( !pacMods.filteredCustomsString ) {
return filteredOriginalsExp;
}
return '"' + pacMods.filteredCustomsString + '; " + ' + filteredOriginalsExp;
}() + ' + "; DIRECT";'; // Without DIRECT you will get 'PROXY CONN FAILED' pac-error.
}()}
};
}(this);`;
},
keepCookedNow(pacMods = window.utils.mandatory(), cb) {
if (typeof(pacMods) === 'function') {
cb = pacMods;
const pacMods = getCurrentConfigs();
if (!pacMods) {
return cb(TypeError('PAC mods were never initialized.'));
}
} else {
try {
pacMods = new PacModifiers(pacMods);
} catch(e) {
return cb(e);
}
localStorage.setItem(kitchenStorageKey, JSON.stringify(pacMods));
}
chrome.proxy.settings.get({}, (details) => {
if (
details.levelOfControl === 'controlled_by_this_extension'
) {
const pac = window.utils.getProp(details, 'value.pacScript');
if (pac && pac.data) {
// Delete old kitchen modifications.
pac.data = pac.data.replace(
new RegExp(kitchenStartsMark + '[\\s\\S]*$', 'g'),
''
);
return chrome.proxy.settings.set(details, cb);
}
}
return cb(
null,
null,
[new TypeError('PAC-скрипт не обнаружен, но настройки будут активированы при установке PAC-скрипта.')]
);
});
},
resetToDefaultsVoid() {
delete localStorage[kitchenStorageKey];
this.keepCookedNow({});
},
};
const originalSet = chrome.proxy.settings.set.bind( chrome.proxy.settings );
chrome.proxy.settings.set = function(details, cb) {
const pac = window.utils.getProp(details, 'value.pacScript');
if (!(pac && pac.data)) {
return originalSet(details, cb);
}
const pacMods = getCurrentConfigs();
if (pacMods) {
pac.data = window.apis.pacKitchen.cook( pac.data, pacMods );
}
originalSet({ value: details.value }, cb);
};
} // Private namespace ends.

View File

@ -1,10 +1,10 @@
{
"manifest_version": 2,
"name": "__MSG_extName__",
"name": "__MSG_extName__ 0.18",
"default_locale": "ru",
"description": "__MSG_extDesc__",
"version": "0.0.0.17",
"version": "0.0.0.18",
"icons": {
"128": "/icons/default-128.png"
},
@ -26,14 +26,15 @@
"scripts": [
"00-init-apis.js",
"11-api-error-handlers.js",
"12-api-sync-pac-script-with-pac-provider.js",
"13-pac-kitchen.js",
"15-api-sync-pac-script-with-pac-provider.js",
"20-api-fixes.js",
"30-block-informer.js",
"40-context-menus.js"
]
},
"browser_action": {
"default_title": "Этот сайт благословлён 0.17",
"default_title": "Этот сайт благословлён 0.18",
"default_popup": "/pages/choose-pac-provider/index.html"
},
"options_ui": {

View File

@ -1,8 +1,7 @@
<!DOCTYPE html>
<html style="display: none">
<html style="display: none; will-change: contents, display">
<head>
<title>Выбор провайдера PAC</title>
<link rel="stylesheet" href="./vendor/font-awesome/css/font-awesome.min.css">
<style>
:root {
--ribbon-color: #4169e1; /* #1a6cc8 */
@ -25,7 +24,7 @@
white-space: nowrap;
word-break: keep-all;
}
li > * {
li, li > * {
vertical-align: middle;
}
input[type="radio"], label {
@ -56,14 +55,22 @@
display: none;
color: red;
}
li.provider {
li.info-row {
display: table;
width: 100%;
position: relative;
}
.desc i {
vertical-align: bottom;
font-size: 1.1em;
.info-sign {
font-size: 1.4em;
vertical-align: middle;
line-height: 100%;
margin-left: 0.1em;
}
.info-url {
float: right;
text-decoration: none;
line-height: initial;
vertical-align: bottom !important;
}
/* Source: https://jsfiddle.net/greypants/zgCb7/ */
.desc {
@ -109,13 +116,31 @@
top: -1em;
content: "";
display: block;
height: 1.8em;
height: 1.6em;
left: 75%;
width: calc(25% + 0.6em);
}
footer {
margin: 2em 0 1em 0;
#custom-proxy-string-raw ~ textarea {
width: 100%;
height: 7em;
margin-top: 0.3em;
font-size: 0.9em;
}
#custom-proxy-string-raw:not(:checked) ~ textarea {
display: none;
}
.control-row {
display: table;
width: 100%;
margin: 1em 0 1em 0;
}
.control-row > * {
display: table-cell;
}
.control-row a:nth-child(2) {
text-decoration: none;
margin-left: 1em;
text-align: right;
}
</style>
</head>
@ -130,16 +155,25 @@
<div style="white-space: nowrap">
Обновлялись: <span class="update-date">...</span>
</div>
<span id="status">Загрузка...</span>
<span id="status" style="will-change: contents">Загрузка...</span>
<hr/>
<div>
<ul id="pac-mods">
<li class="control-row">
<input type="button" value="Применить" id="apply-mods" disabled/>
<a href id="reset-mods">К изначальным!</a>
</li>
</ul>
</div>
<hr/>
<div id="configs-panel">
<header>Я ❤️ уведомления:</header>
<ul id="list-of-handlers">
</ul>
</div>
<footer style="display: table; width: 100%;">
<input type="button" value="Готово" class="close-button" style="display: table-cell">
<a href="../troubleshoot/index.html" style="text-decoration: none; margin-left: 1em; display: table-cell; text-align: right;">
<footer class="control-row">
<input type="button" value="Готово" class="close-button">
<a href="../troubleshoot/index.html">
Проблемы?
</a>
</footer>

View File

@ -1,4 +1,12 @@
'use strict';
const START = Date.now();
document.getElementById('pac-mods').onchange = function() {
this.classList.add('changed');
document.getElementById('apply-mods').disabled = false;
};
chrome.runtime.getBackgroundPage( (backgroundPage) =>
backgroundPage.apis.errorHandlers.installListenersOnAsync(
@ -8,7 +16,7 @@ chrome.runtime.getBackgroundPage( (backgroundPage) =>
const setStatusTo = (msg) => {
getStatus().innerHTML = msg;
getStatus().innerHTML = msg || 'Хорошего настроения вам!';
};
@ -58,7 +66,7 @@ chrome.runtime.getBackgroundPage( (backgroundPage) =>
document.querySelector('.close-button').onclick = () => window.close();
// RADIOS
// RADIOS FOR PROVIDERS
const currentProviderRadio = () => {
@ -95,7 +103,7 @@ chrome.runtime.getBackgroundPage( (backgroundPage) =>
}
setStatusTo(
`<span style="color:red">
${err ? '🔥 Ошибка!' : 'Некритичная ошибка.'}
${err ? '🔥&#xFE0E; Ошибка!' : 'Некритичная ошибка.'}
</span>
<br/>
<span style="font-size: 0.9em; color: darkred">${message}</span>
@ -131,42 +139,44 @@ chrome.runtime.getBackgroundPage( (backgroundPage) =>
} else {
setStatusTo(afterStatus);
}
enableDisableInputs();
if (!err) {
onSuccess && onSuccess();
}
enableDisableInputs();
});
};
const ul = document.querySelector('#list-of-providers');
const _firstChild = ul.firstChild;
for(
const providerKey of Object.keys(antiCensorRu.pacProviders).sort()
) {
const provider = antiCensorRu.getPacProvider(providerKey);
const li = document.createElement('li');
li.className = 'provider';
li.innerHTML = `
<input type="radio" name="pacProvider" id="${providerKey}">
<label for="${providerKey}"> ${provider.label}</label>
<a href class="link-button checked-radio-panel"
id="update-${providerKey}"> [обновить]</a>
<div class="desc">
<i class="fa fa-question-circle" aria-hidden="true"></i>
<div class="tooltip">${provider.desc}</div>
</div>`;
li.querySelector('.link-button').onclick =
() => {
conduct(
'Обновляем...', (cb) => antiCensorRu.syncWithPacProviderAsync(cb),
'Обновлено.'
);
return false;
};
ul.insertBefore( li, _firstChild );
{
const ul = document.querySelector('#list-of-providers');
const _firstChild = ul.firstChild;
for(
const providerKey of Object.keys(antiCensorRu.pacProviders).sort()
) {
const provider = antiCensorRu.getPacProvider(providerKey);
const li = document.createElement('li');
li.className = 'info-row';
li.innerHTML = `
<input type="radio" name="pacProvider" id="${providerKey}">
<label for="${providerKey}"> ${provider.label}</label>
<a href class="link-button checked-radio-panel"
id="update-${providerKey}"> [обновить]</a>
<div class="desc">
<span class="info-sign">🛈</span>
<div class="tooltip">${provider.desc}</div>
</div>`;
li.querySelector('.link-button').onclick =
() => {
conduct(
'Обновляем...', (cb) => antiCensorRu.syncWithPacProviderAsync(cb),
'Обновлено.'
);
return false;
};
ul.insertBefore( li, _firstChild );
}
checkChosenProvider();
}
checkChosenProvider();
const radios = [].slice.apply(
document.querySelectorAll('[name=pacProvider]')
@ -201,7 +211,87 @@ chrome.runtime.getBackgroundPage( (backgroundPage) =>
};
}
const conpanel = document.getElementById('list-of-handlers');
// PAC MODS PANEL
{
const pacKitchen = backgroundPage.apis.pacKitchen;
const modPanel = document.getElementById('pac-mods');
const _firstChild = modPanel.firstChild;
const keyToLi = {};
const customProxyStringKey = 'customProxyStringRaw';
pacKitchen.getConfigs().forEach( (conf) => {
const key = conf.key;
const iddy = conf.key.replace(/([A-Z])/g, (_, p) => '-' + p.toLowerCase());
const li = document.createElement('li');
li.className = 'info-row';
keyToLi[key] = li;
console.log(key, conf.value);
li.innerHTML = `
<input type="checkbox" id="${iddy}" ${ conf.value ? 'checked' : '' }/>
<label for="${iddy}"> ${ conf.label }</label>`;
if (key !== customProxyStringKey) {
li.innerHTML += `<div class="desc">
<span class="info-sign">🛈</span>
<div class="tooltip">${conf.desc}</div>
</div>`;
} else {
li.innerHTML += `<a href="${conf.url}" class="info-sign info-url">🛈</a><br/>
<textarea
placeholder="SOCKS5 localhost:9050; # TOR Expert
SOCKS5 localhost:9150; # TOR Browser
HTTPS foobar.com:3143;
HTTPS 11.22.33.44:8080;">${conf.value || ''}</textarea>`;
li.querySelector('textarea').onkeyup = function() {
this.dispatchEvent(new Event('change', { 'bubbles': true }));
};
}
modPanel.insertBefore( li, _firstChild );
});
document.getElementById('apply-mods').onclick = () => {
const configs = Object.keys(keyToLi).reduce( (configs, key) => {
if (key !== customProxyStringKey) {
configs[key] = keyToLi[key].querySelector('input').checked;
} else {
configs[key] = keyToLi[key].querySelector('input').checked
&& keyToLi[key].querySelector('textarea').value.trim();
}
return configs;
}, {});
if (configs[customProxyStringKey]) {
configs[customProxyStringKey] = keyToLi[customProxyStringKey].querySelector('textarea').value;
}
conduct(
'Применяем настройки...',
(cb) => pacKitchen.keepCookedNow(configs, cb),
'Настройки применены.',
() => { document.getElementById('apply-mods').disabled = true; }
);
};
document.getElementById('reset-mods').onclick = () => {
pacKitchen.resetToDefaultsVoid();
window.close();
};
}
// NOTIFICATIONS PANEL
const conPanel = document.getElementById('list-of-handlers');
errorHandlers.getEventsMap().forEach( (value, name) => {
const li = document.createElement('li');
@ -219,7 +309,7 @@ chrome.runtime.getBackgroundPage( (backgroundPage) =>
);
};
conpanel.appendChild(li);
conPanel.appendChild(li);
});
@ -239,6 +329,7 @@ chrome.runtime.getBackgroundPage( (backgroundPage) =>
document.querySelector('#update-' + id).click();
}
document.documentElement.style.display = '';
console.log(Date.now() - START);
})
);