This commit is contained in:
ilyaigpetrov 2023-05-04 20:35:40 +05:00
parent f98c81ff84
commit 44af8bd85a
2 changed files with 100 additions and 93 deletions

View File

@ -11,36 +11,38 @@
const modsKey = 'mods'; const modsKey = 'mods';
let proxyHostToCredsList = {}; let proxyHostToCredsList = {};
const ifAuthSupported = chrome.webRequest && chrome.webRequest.onAuthRequired && !globalThis.apis.version.ifMini; const ifAuthSupported = chrome.webRequest &&
chrome.webRequest.onAuthRequired &&
!globalThis.apis.version.ifMini;
if (ifAuthSupported) { if (ifAuthSupported) {
const requestIdToTries = {}; const requestIdToTries = {};
chrome.webRequest.onAuthRequired.addListener( chrome.webRequest.onAuthRequired.addListener(
(details) => { (details) => {
if (!details.isProxy) { if (!details.isProxy) {
return {}; return {};
} }
const proxyHost = `${details.challenger.host}:${details.challenger.port}`; const proxyHost = `${details.challenger.host}:${details.challenger.port}`;
const credsList = proxyHostToCredsList[proxyHost]; const credsList = proxyHostToCredsList[proxyHost];
if (!credsList) { if (!credsList) {
return {}; // No creds found for this proxy. return {}; // No creds found for this proxy.
} }
const requestId = details.requestId; const requestId = details.requestId;
const tries = requestIdToTries[requestId] || 0; const tries = requestIdToTries[requestId] || 0;
if (tries > credsList.length) { if (tries > credsList.length) {
return {}; // All creds for this proxy were tried already. return {}; // All creds for this proxy were tried already.
} }
requestIdToTries[requestId] = tries + 1; requestIdToTries[requestId] = tries + 1;
return { return {
authCredentials: credsList[tries], authCredentials: credsList[tries],
}; };
}, },
{urls: ['<all_urls>']}, {urls: ['<all_urls>']},
['blocking'], ['blocking'],
); );
const forgetRequestId = (details) => { const forgetRequestId = (details) => {
@ -50,13 +52,13 @@
}; };
chrome.webRequest.onCompleted.addListener( chrome.webRequest.onCompleted.addListener(
forgetRequestId, forgetRequestId,
{urls: ['<all_urls>']}, {urls: ['<all_urls>']},
); );
chrome.webRequest.onErrorOccurred.addListener( chrome.webRequest.onErrorOccurred.addListener(
forgetRequestId, forgetRequestId,
{urls: ['<all_urls>']}, {urls: ['<all_urls>']},
); );
} }
@ -198,21 +200,21 @@
const pacMods = getCurrentConfigs(); const pacMods = getCurrentConfigs();
const configs = getDefaultConfigs(); const configs = getDefaultConfigs();
return Object.keys(configs) return Object.keys(configs)
.sort((keyA, keyB) => configs[keyA].order - configs[keyB].order) .sort((keyA, keyB) => configs[keyA].order - configs[keyB].order)
.reduce((arr, key) => { .reduce((arr, key) => {
const conf = configs[key]; const conf = configs[key];
if(typeof(conf.order) === 'number') { if (typeof(conf.order) === 'number') {
if(!category || category === (conf.category || 'general')) { if (!category || category === (conf.category || 'general')) {
conf.value = pacMods[key]; conf.value = pacMods[key];
conf.key = key; conf.key = key;
conf.category = category || 'general'; conf.category = category || 'general';
arr.push(conf); arr.push(conf);
} }
} }
return arr; return arr;
}, []); }, []);
}; };
@ -221,18 +223,19 @@
mods = mods || {}; // null? mods = mods || {}; // null?
const configs = getDefaultConfigs(); const configs = getDefaultConfigs();
const ifNoMods = Object.keys(configs) const ifNoMods = Object.keys(configs)
.every((dProp) => { .every((dProp) => {
const ifDflt = ( const ifDflt = (
!( !(
dProp in mods && dProp in mods &&
Boolean(configs[dProp].dflt) !== Boolean(mods[dProp]) Boolean(configs[dProp].dflt) !== Boolean(mods[dProp])
) )
); );
const ifMods = configs[dProp].ifDfltMods; // If default value implies PAC-script modification. const ifMods = configs[dProp].ifDfltMods;
return ifDflt ? !ifMods : ifMods; // If default value implies PAC-script modification.
return ifDflt ? !ifMods : ifMods;
}); });
const self = {}; const self = {};
const gdft = getDefaults(); const gdft = getDefaults();
@ -242,10 +245,10 @@
let customProxyArray = []; let customProxyArray = [];
if (self.customProxyStringRaw) { if (self.customProxyStringRaw) {
customProxyArray = self.customProxyStringRaw customProxyArray = self.customProxyStringRaw
.replace(/#.*$/mg, '') // Strip comments. .replace(/#.*$/mg, '') // Strip comments.
.split( /(?:\s*(?:;\r?\n)+\s*)+/g ) .split( /(?:\s*(?:;\r?\n)+\s*)+/g )
.map( (p) => p.trim() ) .map( (p) => p.trim() )
.filter( (p) => p && /\s+/g.test(p) ); // At least one space is required. .filter( (p) => p && /\s+/g.test(p) ); // At least one space is required.
if (self.ifUseSecureProxiesOnly) { if (self.ifUseSecureProxiesOnly) {
customProxyArray = customProxyArray.filter( (pStr) => /^HTTPS\s/.test(pStr) ); customProxyArray = customProxyArray.filter( (pStr) => /^HTTPS\s/.test(pStr) );
} }
@ -279,7 +282,7 @@
} }
proxyHostToCredsList = {}; proxyHostToCredsList = {};
protectedProxies.forEach(({ hostname, port, username, password }) => { protectedProxies.forEach(({hostname, port, username, password}) => {
proxyHostToCredsList[`${hostname}:${port}`] = proxyHostToCredsList[`${hostname}:${port}`] =
proxyHostToCredsList[`${hostname}:${port}`] || []; proxyHostToCredsList[`${hostname}:${port}`] || [];
@ -317,7 +320,7 @@
if (self.ifMindExceptions && self.exceptions) { if (self.ifMindExceptions && self.exceptions) {
self.included = []; self.included = [];
self.excluded = []; self.excluded = [];
for(const host of Object.keys(self.exceptions)) { for (const host of Object.keys(self.exceptions)) {
const ifProxy = self.exceptions[host] || false; const ifProxy = self.exceptions[host] || false;
if (ifProxy) { if (ifProxy) {
self.included.push(host); self.included.push(host);
@ -328,14 +331,14 @@
['included', 'excluded'].forEach((who) => { ['included', 'excluded'].forEach((who) => {
self[who] = self[who] self[who] = self[who]
.map( (domain) => domain.split('').reverse() ) .map( (domain) => domain.split('').reverse() )
.sort() .sort()
.map( (rDomain) => rDomain.reverse().join('') ); .map( (rDomain) => rDomain.reverse().join('') );
}); });
if (self.included.length && !self.filteredCustomsString) { if (self.included.length && !self.filteredCustomsString) {
return [null, self, new TypeError( return [null, self, new TypeError(
'Имеются сайты, добавленные вручную. Они проксироваться не будут, т.к. нет СВОИХ проски, удовлетворяющих вашим требованиям! Если прокси всё же имеются, то проверьте требования (модификаторы).' 'Имеются сайты, добавленные вручную. Они проксироваться не будут, т.к. нет СВОИХ проски, удовлетворяющих вашим требованиям! Если прокси всё же имеются, то проверьте требования (модификаторы).',
)]; )];
} }
} }
@ -352,8 +355,8 @@
cook(pacData, pacMods = mandatory()) { cook(pacData, pacMods = mandatory()) {
pacData = pacData.replace( pacData = pacData.replace(
new RegExp(kitchenStartsMark + '[\\s\\S]*$', 'g'), new RegExp(kitchenStartsMark + '[\\s\\S]*$', 'g'),
'' '',
); );
/a/.test('a'); // GC RegExp.input and friends. /a/.test('a'); // GC RegExp.input and friends.
@ -470,9 +473,9 @@
/******/ return "DIRECT"; /******/ return "DIRECT";
/******/ } /******/ }
/******/ // Always proxy it! /******/ // Always proxy it!
${ pacMods.filteredCustomsString ${ pacMods.filteredCustomsString ?
? `/******/ return filteredCustomProxies + "; " + directIfAllowed;` `/******/ return filteredCustomProxies + "; " + directIfAllowed;` :
: '/******/ /* No custom proxies -- continue. */' '/******/ /* No custom proxies -- continue. */'
} }
/******/ } /******/ }
/******/ /* EXCEPTIONS END */ /******/ /* EXCEPTIONS END */
@ -484,7 +487,7 @@ ${ pacMods.filteredCustomsString
? '.replace(/DIRECT/g, "")' ? '.replace(/DIRECT/g, "")'
: ' + "; " + directIfAllowed' : ' + "; " + directIfAllowed'
};`; };`;
if( if (
!pacMods.ifUseSecureProxiesOnly && !pacMods.ifUseSecureProxiesOnly &&
!pacMods.filteredCustomsString && !pacMods.filteredCustomsString &&
pacMods.ifUsePacScriptProxies pacMods.ifUsePacScriptProxies
@ -502,9 +505,9 @@ ${ pacMods.filteredCustomsString
/******/ return "DIRECT"; /******/ return "DIRECT";
/******/ } /******/ }
/******/ return ` + /******/ return ` +
((pacMods.filteredCustomsString && !pacMods.ifUseOwnProxiesOnlyForOwnSites) ((pacMods.filteredCustomsString && !pacMods.ifUseOwnProxiesOnlyForOwnSites) ?
? 'filteredCustomProxies + "; " + ' 'filteredCustomProxies + "; " + ' :
: '' ''
) + ) +
function() { function() {
@ -525,9 +528,9 @@ ${ pacMods.filteredCustomsString
/******/ }; /******/ };
${ ${
!pacMods.replaceDirectWith !pacMods.replaceDirectWith ?
? '' '' :
: ` `
/******/ const oldTmp = tmp; /******/ const oldTmp = tmp;
/******/ tmp = function(url, host) { /******/ tmp = function(url, host) {
/******/ const ip = dnsResolve(host); /******/ const ip = dnsResolve(host);
@ -579,9 +582,9 @@ ${
new Promise((resolve) => new Promise((resolve) =>
details details ?
? resolve(details) resolve(details) :
: chrome.proxy.settings.get({}, timeouted(resolve) ), chrome.proxy.settings.get({}, timeouted(resolve) ),
).then((details) => { ).then((details) => {
@ -596,7 +599,7 @@ ${
kitchenState(ifIncontinence, true); kitchenState(ifIncontinence, true);
cb(null, null, new TypeError( cb(null, null, new TypeError(
'Не найдено активного PAC-скрипта! Изменения будут применены при возвращении контроля настроек прокси или установке нового PAC-скрипта.' 'Не найдено активного PAC-скрипта! Изменения будут применены при возвращении контроля настроек прокси или установке нового PAC-скрипта.'
)); ));
}); });
@ -606,7 +609,11 @@ ${
checkIncontinence(details) { checkIncontinence(details) {
if ( kitchenState(ifIncontinence) ) { if ( kitchenState(ifIncontinence) ) {
this.setNowAsync(details, (err) => { if (err) { throw err; } }); // TODO: suppress? this.setNowAsync(details, (err) => {
if (err) {
throw err;
}
}); // TODO: suppress?
} }
}, },
@ -630,25 +637,25 @@ ${
kitchenState(modsKey, pacMods); kitchenState(modsKey, pacMods);
} }
this.setNowAsync( this.setNowAsync(
(err, res, ...setWarns) => { (err, res, ...setWarns) => {
const accWarns = modsWarns.concat(setWarns); // Acc = accumulated. const accWarns = modsWarns.concat(setWarns); // Acc = accumulated.
if (err) { if (err) {
return cb(err, res, ...accWarns); return cb(err, res, ...accWarns);
} }
if (!ifProxiesChanged) { if (!ifProxiesChanged) {
return cb(null, res, ...accWarns); return cb(null, res, ...accWarns);
} }
const newHosts = (pacMods.customProxyArray || []).map( (ps) => ps.split(/\s+/)[1] ); const newHosts = (pacMods.customProxyArray || []).map( (ps) => ps.split(/\s+/)[1] );
globalThis.utils.fireRequest( globalThis.utils.fireRequest(
'ip-to-host-replace-all', 'ip-to-host-replace-all',
newHosts, newHosts,
(err, res, ...moreWarns) => (err, res, ...moreWarns) =>
cb(err, res, ...accWarns, ...moreWarns), cb(err, res, ...accWarns, ...moreWarns),
); );
}, },
); );
}, },

View File

@ -8,7 +8,7 @@ import getApp from './components/App';
chrome.runtime.getBackgroundPage( (bgWindow) => chrome.runtime.getBackgroundPage( (bgWindow) =>
bgWindow.apis.errorHandlers.installListenersOn( bgWindow.apis.errorHandlers.installListenersOn(
window, 'PUP', async() => { window, 'PUP', async () => {
/* /*
`Extension context invalidated` error is thrown if `window.closed` is true and call to `Extension context invalidated` error is thrown if `window.closed` is true and call to
`window.chrome.i18n` or other `window.chrome` api happens. Use bgWindow.chrome instead. `window.chrome.i18n` or other `window.chrome` api happens. Use bgWindow.chrome instead.