-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathProxyEngineChrome.ts
More file actions
566 lines (459 loc) · 15.9 KB
/
Copy pathProxyEngineChrome.ts
File metadata and controls
566 lines (459 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
import { ProxyServer, CompiledProxyRule, SmartProfileType, CompiledProxyRuleType } from "./definitions";
import { api } from "../lib/environment";
import { Debug, DiagDebug } from "../lib/Debug";
import { Settings } from "./Settings";
export class ProxyEngineChrome {
/** Chrome only. Updating Chrome proxy config. */
public static updateChromeProxyConfig() {
let settingsActive = Settings.active;
if (settingsActive.activeProfile.profileType == SmartProfileType.SystemProxy) {
let config = {
mode: "system"
};
api.proxy.settings.set(
{ value: config, scope: "regular" },
function () {
if (api.runtime.lastError) {
Debug.error("updateChromeProxyConfig failed with ", api.runtime.lastError);
}
});
return;
}
else if (settingsActive.activeProfile.profileType == SmartProfileType.Direct) {
let config = {
mode: "direct"
};
api.proxy.settings.set(
{ value: config, scope: "regular" },
function () {
if (api.runtime.lastError) {
Debug.error("updateChromeProxyConfig failed with ", api.runtime.lastError);
}
});
return;
}
// generate PAC script specific to Chrome
let pacScript = this.generateChromePacScript();
let config = {
mode: "pac_script",
pacScript: {
data: pacScript
}
};
api.proxy.settings.set(
{ value: config, scope: "regular" },
function () {
if (api.runtime.lastError) {
Debug.error("updateChromeProxyConfig failed with ", api.runtime.lastError);
}
});
}
private static generateChromePacScript(): string {
//let settings = Settings.current;
let settingsActive = Settings.active;
let profileType = settingsActive.activeProfile.profileType;
let resultCurrentProxyServer = this.convertActiveProxyServer(settingsActive.currentProxyServer);
let compiledRules = settingsActive.activeProfile.compiledRules;
let compiledRules_WhitelistRules = this.regexHostArrayToString(compiledRules.WhitelistRules).join(",");
let compiledRules_Rules = this.regexHostArrayToString(compiledRules.Rules).join(",");
let compiledRules_WhitelistSubscriptionRules = this.regexHostArrayToString(compiledRules.WhitelistSubscriptionRules).join(",");
let compiledRules_SubscriptionRules = this.regexHostArrayToString(compiledRules.SubscriptionRules).join(",");
let pacTemplateString = `
const compiledRules = {
/** User defined whitelist rules. P2 */
WhitelistRules: [${compiledRules_WhitelistRules}],
/** User defined rules. P1 */
Rules: [${compiledRules_Rules}],
/** Subscription whitelist rules. P3 */
WhitelistSubscriptionRules: [${compiledRules_WhitelistSubscriptionRules}],
/** Subscription rules. P4 */
SubscriptionRules: [${compiledRules_SubscriptionRules}]
};
const SmartProfileType = {
Direct: ${SmartProfileType.Direct},
SystemProxy: ${SmartProfileType.SystemProxy},
SmartRules: ${SmartProfileType.SmartRules},
AlwaysEnabledBypassRules: ${SmartProfileType.AlwaysEnabledBypassRules},
IgnoreFailureRules: ${SmartProfileType.IgnoreFailureRules},
}
const CompiledProxyRuleType = {
RegexHost: ${CompiledProxyRuleType.RegexHost},
RegexUrl: ${CompiledProxyRuleType.RegexUrl},
Exact: ${CompiledProxyRuleType.Exact},
SearchUrl: ${CompiledProxyRuleType.SearchUrl},
SearchDomain: ${CompiledProxyRuleType.SearchDomain},
SearchDomainSubdomain: ${CompiledProxyRuleType.SearchDomainSubdomain},
SearchDomainAndPath: ${CompiledProxyRuleType.SearchDomainAndPath},
SearchDomainSubdomainAndPath: ${CompiledProxyRuleType.SearchDomainSubdomainAndPath}
}
const activeProfileType = +'${profileType}';
const currentProxyServer = "${resultCurrentProxyServer}";
const resultDirect = "DIRECT";
const resultSystem = "SYSTEM";
const verboseDiagnostics = ${(DiagDebug?.enabled == true)}; // set to true for verbose logs using chrome flag. https://support.google.com/chrome/a/answer/6271171?hl=en#zippy=%2Cview-network-data%2Cget-network-logs
// -------------------------
// required PAC function that will be called to determine
// if a proxy should be used.
function FindProxyForURL(url, host, noDiagnostics) {
if (verboseDiagnostics && !noDiagnostics) {
let finalResult = FindProxyForURL(url, host, true);
alert('SmartProxy-FindProxyForURL-Result=' + finalResult + '; host=' + host + '; url=' + url + '; activeProfile=' + activeProfileType);
return finalResult;
}
if (activeProfileType == SmartProfileType.SystemProxy)
return resultSystem;
if (activeProfileType == SmartProfileType.Direct || !host)
return resultDirect;
host = host.toLowerCase();
// applying ProxyPerOrigin
// is not applicable for Chromium
// correcting 'host' because it doesn't include port number
const hostAndPort = extractHostFromUrl(url)?.toLowerCase() || host;
if (activeProfileType == SmartProfileType.AlwaysEnabledBypassRules) {
// user skip the bypass rules/ don't apply proxy
let userMatchedRule = findMatchedUrlInRules(url, host, hostAndPort, compiledRules.Rules);
if (userMatchedRule) {
return makeResultForAlwaysEnabledForced(userMatchedRule)
}
// user bypass rules/ apply proxy by force
let userWhitelistMatchedRule = findMatchedUrlInRules(url, host, hostAndPort, compiledRules.WhitelistRules)
if (userWhitelistMatchedRule) {
return resultDirect;
}
// subscription skip bypass rules/ don't apply proxy
let subMatchedRule = findMatchedUrlInRules(url, host, hostAndPort, compiledRules.SubscriptionRules);
if (subMatchedRule) {
return makeResultForAlwaysEnabledForced(subMatchedRule)
}
// subscription bypass rules/ apply proxy by force
let subWhitelistMatchedRule = findMatchedUrlInRules(url, host, hostAndPort, compiledRules.WhitelistSubscriptionRules)
if (subWhitelistMatchedRule) {
return resultDirect;
}
//** Always Enabled is forced by a rule, so other rules can't skip it */
function makeResultForAlwaysEnabledForced(matchedRule) {
if (matchedRule.proxy)
// this rule has its own proxy setup
return matchedRule.proxy;
return currentProxyServer;
}
// no rule is matched, going with proxy
return currentProxyServer;
}
if (activeProfileType == SmartProfileType.SmartRules) {
// user whitelist rules/ don't apply proxy
let userWhitelistMatchedRule = findMatchedUrlInRules(url, host, hostAndPort, compiledRules.WhitelistRules)
if (userWhitelistMatchedRule) {
return makeResultForWhitelistRule(userWhitelistMatchedRule);
}
// user rules/ apply proxy
let userMatchedRule = findMatchedUrlInRules(url, host, hostAndPort, compiledRules.Rules);
if (userMatchedRule) {
return makeResultForMatchedRule(userMatchedRule);
}
// subscription whitelist rules/ don't apply proxy
let subWhitelistMatchedRule = findMatchedUrlInRules(url, host, hostAndPort, compiledRules.WhitelistSubscriptionRules)
if (subWhitelistMatchedRule) {
return makeResultForWhitelistRule(subWhitelistMatchedRule);
}
// subscription rules/ apply proxy
let subMatchedRule = findMatchedUrlInRules(url, host, hostAndPort, compiledRules.SubscriptionRules);
if (subMatchedRule) {
return makeResultForMatchedRule(subMatchedRule);
}
/**
* Generate result for matched whitelist rule
*/
const makeResultForWhitelistRule = () => {
return resultDirect;
}
/**
* Generate result for matched proxy rule
*/
function makeResultForMatchedRule(matchedRule) {
if (matchedRule.proxy)
// this rule has its own proxy setup
return matchedRule.proxy;
return currentProxyServer;
}
}
if (activeProfileType == SmartProfileType.IgnoreFailureRules) {
// NOTE: this is not a proxy profile, it is used elsewhere
// No logic is needed here
}
// let the browser decide
return "";
}
function findMatchedUrlInRules(searchUrl, host, hostAndPort, rules) {
if (searchUrl == null || rules == null || rules.length == 0)
return null;
let schemaLessUrlLowerCase = null;
let lowerCaseUrl = searchUrl.toLowerCase();
try {
for (let rule of rules) {
switch (rule.compiledRuleType) {
case CompiledProxyRuleType.SearchDomainSubdomain:
// domain
if (host == rule.search)
return rule;
// subdomains
if (host.endsWith('.' + rule.search))
return rule;
break;
case CompiledProxyRuleType.SearchDomainSubdomainAndPath:
{
schemaLessUrlLowerCase ??= removeSchemaFromUrl(lowerCaseUrl);
if (schemaLessUrlLowerCase == null)
continue;
if (schemaLessUrlLowerCase.startsWith(rule.search))
return rule;
rule.searchHost ??= extractHostFromInvalidUrl(rule.search);
if (rule.searchHost != null) {
// should be the same
if (rule.searchHost != host && !host.endsWith('.' + rule.searchHost))
continue;
// after this state, we are sure that the url is for the same domain, now just checking the path
}
// subdomains
if (schemaLessUrlLowerCase.includes('.' + rule.search))
return rule;
break;
}
case CompiledProxyRuleType.SearchDomainAndPath:
schemaLessUrlLowerCase ??= removeSchemaFromUrl(lowerCaseUrl);
if (schemaLessUrlLowerCase == null)
continue;
if (schemaLessUrlLowerCase.startsWith(rule.search))
return rule;
break;
case CompiledProxyRuleType.SearchUrl:
if (lowerCaseUrl.startsWith(rule.search))
return rule;
break;
case CompiledProxyRuleType.RegexUrl:
// Using original url with case sensitivity
if (rule.regex.test(searchUrl))
return rule;
break;
case CompiledProxyRuleType.RegexHost:
if (regexHostMatches(rule.regex, host, rule.normalizeIpHostMatch === true))
return rule;
break;
case CompiledProxyRuleType.SearchDomain:
if (rule.search == host)
return rule;
break;
case CompiledProxyRuleType.Exact:
if (lowerCaseUrl == rule.search)
return rule;
break;
}
}
// reaching this point nothing is matched
// if host has custom port number we need to check again
if (host != hostAndPort) {
host = hostAndPort;
for (let rule of rules) {
// NOTE: Only rules that work on hostName should be checked, others can be ignored
switch (rule.compiledRuleType) {
case CompiledProxyRuleType.SearchDomainSubdomain:
// domain
if (host == rule.search)
return rule;
// subdomains
if (host.endsWith('.' + rule.search))
return rule;
break;
case CompiledProxyRuleType.SearchDomainSubdomainAndPath:
{
schemaLessUrlLowerCase ??= removeSchemaFromUrl(lowerCaseUrl);
if (schemaLessUrlLowerCase == null) {
continue;
}
if (schemaLessUrlLowerCase.startsWith(rule.search))
return rule;
rule.searchHost ??= extractHostFromInvalidUrl(rule.search);
if (rule.searchHost != null) {
// should be the same
if (rule.searchHost != host && !host.endsWith('.' + rule.searchHost))
continue;
// after this state, we are sure that the url is for the same domain, now just checking the path
}
// subdomains
if (schemaLessUrlLowerCase.includes('.' + rule.search))
return rule;
break;
}
case CompiledProxyRuleType.RegexHost:
if (regexHostMatches(rule.regex, host, rule.normalizeIpHostMatch === true))
return rule;
break;
case CompiledProxyRuleType.SearchDomain:
if (rule.search == host)
return rule;
break;
case CompiledProxyRuleType.Exact:
case CompiledProxyRuleType.RegexUrl:
case CompiledProxyRuleType.SearchUrl:
case CompiledProxyRuleType.SearchDomainAndPath:
break;
}
}
}
} catch (e) {
console.warn('SmartProxy> findMatchForUrl failed for ' + lowerCaseUrl, e);
}
return null;
}
function removeSchemaFromUrl(url) {
if (url == null)
return url;
const schemaSep = '://';
let index = url.indexOf(schemaSep);
if (index > -1)
return url.substring(index + schemaSep.length, url.length);
else
return url;
}
function hostMayNeedIpNormalization(host) {
if (!host)
return false;
if (host.charCodeAt(0) === 91)
return true;
const firstColon = host.indexOf(':');
if (firstColon < 0)
return false;
if (host.indexOf(':', firstColon + 1) >= 0)
return true;
let hasDot = false;
for (let index = 0; index < firstColon; index++) {
const charCode = host.charCodeAt(index);
if (charCode === 46) {
hasDot = true;
continue;
}
if (charCode < 48 || charCode > 57)
return false;
}
if (!hasDot)
return false;
for (let index = firstColon + 1; index < host.length; index++) {
const charCode = host.charCodeAt(index);
if (charCode < 48 || charCode > 57)
return false;
}
return true;
}
function regexHostMatches(regex, host, normalizeIpHostMatch) {
if (!regex || !host)
return false;
if (regex.test(host))
return true;
if (normalizeIpHostMatch !== true || !hostMayNeedIpNormalization(host))
return false;
const normalizedHost = normalizeIpForMatching(host);
if (normalizedHost == null || normalizedHost === host)
return false;
return regex.test(normalizedHost);
}
function normalizeIpForMatching(host) {
if (!host)
return null;
let h = host.trim();
const bracketedHostMatch = h.match(/^\[([^\]]+)\](?::\d+)?$/);
if (bracketedHostMatch) {
h = bracketedHostMatch[1];
} else {
h = h.replace(/^\[|\]$/g, '');
}
const ipv4Tail = h.match(/(\d+\.\d+\.\d+\.\d+)(?::\d+)?$/);
if (ipv4Tail)
return ipv4Tail[1];
if (h.indexOf(':') >= 0) {
const groups = expandIPv6ToGroups(h);
if (groups)
return groups.join(':');
return h;
}
return h;
}
function expandIPv6ToGroups(ipv6) {
ipv6 = ipv6.replace(/^\[|\]$/g, '').toLowerCase();
if (ipv6.indexOf('.') >= 0)
return null;
const parts = ipv6.split('::');
if (parts.length > 2)
return null;
const left = parts[0] ? parts[0].split(':').filter(Boolean) : [];
const right = parts[1] ? parts[1].split(':').filter(Boolean) : [];
const missing = 8 - (left.length + right.length);
if (missing < 0)
return null;
const full = [];
for (const part of left)
full.push(part.padStart(4, '0'));
for (let i = 0; i < missing; i++)
full.push('0000');
for (const part of right)
full.push(part.padStart(4, '0'));
if (full.length !== 8)
return null;
return full;
}
function extractHostFromInvalidUrl(url) {
try {
if (!url.includes(":/"))
url = 'http://' + url;
return extractHostFromUrl(url);
}
catch (e) { return null; }
}
function extractHostFromUrl(url) {
// Unescaped RegEx (/^(?:\w)*\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
const extractPattern = (/^(?:\\w)*\\:\\/\\/([^\\/?#]+)(?:[\\/?#]|$)/i);
const match = extractPattern.exec(url);
if (!match) {
return null;
}
const [, host] = match;
return host;
}`;
return pacTemplateString;
};
private static convertActiveProxyServer(proxyServer: ProxyServer): string {
const resultDirect = "DIRECT";
// invalid active proxy server
if (!proxyServer || !proxyServer.host || !proxyServer.protocol || !proxyServer.port)
return resultDirect;
switch (proxyServer.protocol) {
case "HTTP":
return `PROXY ${proxyServer.host}:${proxyServer.port}`;
case "HTTPS":
return `HTTPS ${proxyServer.host}:${proxyServer.port}`;
case "SOCKS4":
return `SOCKS4 ${proxyServer.host}:${proxyServer.port}`;
case "SOCKS5":
return `SOCKS5 ${proxyServer.host}:${proxyServer.port}`;
}
// invalid proxy protocol
return resultDirect;
}
private static regexHostArrayToString(compiledRules: CompiledProxyRule[]) {
let compiledRulesAsStringArray = [];
for (let index = 0; index < compiledRules.length; index++) {
let rule = compiledRules[index];
let search: string;
if (rule.search) {
search = `unescape('${escape(rule.search)}')`;
}
else
search = 'null';
if (rule.proxy) {
compiledRulesAsStringArray.push(`{search:${search},regex:${rule.regex?.toString() || 'null'},compiledRuleType:${rule.compiledRuleType},normalizeIpHostMatch:${rule.normalizeIpHostMatch === true},proxy:"${this.convertActiveProxyServer(rule.proxy)}"}`);
} else {
compiledRulesAsStringArray.push(`{search:${search},regex:${rule.regex?.toString() || 'null'},compiledRuleType:${rule.compiledRuleType},normalizeIpHostMatch:${rule.normalizeIpHostMatch === true}}`);
}
}
return compiledRulesAsStringArray;
}
}