-
Notifications
You must be signed in to change notification settings - Fork 276
/
_worker.js
1028 lines (830 loc) · 34.5 KB
/
_worker.js
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
addEventListener('fetch', event => {
const url = new URL(event.request.url);
thisProxyServerUrlHttps = `${url.protocol}//${url.hostname}/`;
thisProxyServerUrl_hostOnly = url.host;
//console.log(thisProxyServerUrlHttps);
//console.log(thisProxyServerUrl_hostOnly);
event.respondWith(handleRequest(event.request))
})
const str = "/";
const lastVisitProxyCookie = "__PROXY_VISITEDSITE__";
const passwordCookieName = "__PROXY_PWD__";
const proxyHintCookieName = "__PROXY_HINT__";
const password = "";
const showPasswordPage = true;
const replaceUrlObj = "__location____"
var thisProxyServerUrlHttps;
var thisProxyServerUrl_hostOnly;
// const CSSReplace = ["https://", "http://"];
const proxyHintInjection = `
//---***========================================***---提示使用代理---***========================================***---
setTimeout(() => {
if (document.readyState === 'complete' || document.readyState === 'interactive') {
var hint = \`Warning: You are currently using a web proxy, the original link is \${window.location.pathname}. Please note that you are using a proxy, and do not log in to any website. Click to close this hint. 警告:您当前正在使用网络代理,原始链接为\${window.location.pathname}。请注意您正在使用代理,请勿登录任何网站。单击关闭此提示。\`;
console.log(1);
document.body.insertAdjacentHTML(
'afterbegin',
\`<div style="position:fixed;left:0px;top:0px;width:100%;margin:0px;padding:0px;z-index:9999999999999999999;user-select:none;cursor:pointer;" id="__PROXY_HINT_DIV__" onclick="document.getElementById('__PROXY_HINT_DIV__').remove();">
<span style="position:absolute;width:100%;min-height:30px;font-size:20px;color:yellow;background:red;text-align:center;border-radius:5px;">
\${hint}
</span>
</div>\`
);
}else{
alert(\`Warning: You are currently using a web proxy, the original link is \${window.location.pathname}. Please note that you are using a proxy, and do not log in to any website.\`);
}
}, 3000);
`;
const httpRequestInjection = `
//---***========================================***---information---***========================================***---
var now = new URL(window.location.href);
var base = now.host;
var protocol = now.protocol;
var nowlink = protocol + "//" + base + "/";
var oriUrlStr = window.location.href.substring(nowlink.length);
var oriUrl = new URL(oriUrlStr);
var path = now.pathname.substring(1);
console.log("***************************----" + path);
if(!path.startsWith("http")) path = "https://" + path;
var original_host = path.substring(path.indexOf("://") + "://".length);
original_host = original_host.split('/')[0];
var mainOnly = path.substring(0, path.indexOf("://")) + "://" + original_host + "/";
//---***========================================***---通用func---***========================================***---
function changeURL(relativePath){
if(relativePath == null) return null;
try{
if(relativePath.startsWith("data:") || relativePath.startsWith("mailto:") || relativePath.startsWith("javascript:") || relativePath.startsWith("chrome") || relativePath.startsWith("edge")) return relativePath;
}catch{
// duckduckgo mysterious BUG that will trigger sometimes, just ignore ...
}
try{
if(relativePath && relativePath.startsWith(nowlink)) relativePath = relativePath.substring(nowlink.length);
if(relativePath && relativePath.startsWith(base + "/")) relativePath = relativePath.substring(base.length + 1);
if(relativePath && relativePath.startsWith(base)) relativePath = relativePath.substring(base.length);
}catch{
//ignore
}
try {
var absolutePath = new URL(relativePath, path).href;
absolutePath = absolutePath.replace(window.location.href, path);
absolutePath = absolutePath.replace(encodeURI(window.location.href), path);
absolutePath = absolutePath.replace(encodeURIComponent(window.location.href), path);
absolutePath = absolutePath.replace(nowlink, mainOnly);
absolutePath = absolutePath.replace(nowlink, encodeURI(mainOnly));
absolutePath = absolutePath.replace(nowlink, encodeURIComponent(mainOnly));
absolutePath = absolutePath.replace(nowlink, mainOnly.substring(0,mainOnly.length - 1));
absolutePath = absolutePath.replace(nowlink, encodeURI(mainOnly.substring(0,mainOnly.length - 1)));
absolutePath = absolutePath.replace(nowlink, encodeURIComponent(mainOnly.substring(0,mainOnly.length - 1)));
absolutePath = absolutePath.replace(base, original_host);
absolutePath = nowlink + absolutePath;
return absolutePath;
} catch (e) {
console.log("Exception occured: " + e.message + path + " " + relativePath);
return "";
}
}
//---***========================================***---注入网络---***========================================***---
function networkInject(){
//inject network request
var originalOpen = XMLHttpRequest.prototype.open;
var originalFetch = window.fetch;
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
url = changeURL(url);
console.log("R:" + url);
return originalOpen.apply(this, arguments);
};
window.fetch = function(input, init) {
var url;
if (typeof input === 'string') {
url = input;
} else if (input instanceof Request) {
url = input.url;
} else {
url = input;
}
url = changeURL(url);
console.log("R:" + url);
if (typeof input === 'string') {
return originalFetch(url, init);
} else {
const newRequest = new Request(url, input);
return originalFetch(newRequest, init);
}
};
console.log("NETWORK REQUEST METHOD INJECTED");
}
//---***========================================***---注入window.open---***========================================***---
function windowOpenInject(){
const originalOpen = window.open;
// Override window.open function
window.open = function (url, name, specs) {
let modifiedUrl = changeURL(url);
return originalOpen.call(window, modifiedUrl, name, specs);
};
console.log("WINDOW OPEN INJECTED");
}
//---***========================================***---注入append元素---***========================================***---
function appendChildInject(){
const originalAppendChild = Node.prototype.appendChild;
Node.prototype.appendChild = function(child) {
try{
if(child.src){
child.src = changeURL(child.src);
}
if(child.href){
child.href = changeURL(child.href);
}
}catch{
//ignore
}
return originalAppendChild.call(this, child);
};
console.log("APPEND CHILD INJECTED");
}
//---***========================================***---注入元素的src和href---***========================================***---
function elementPropertyInject(){
const originalSetAttribute = HTMLElement.prototype.setAttribute;
HTMLElement.prototype.setAttribute = function (name, value) {
if (name == "src" || name == "href") {
value = changeURL(value);
//console.log("~~~~~~" + value);
}
originalSetAttribute.call(this, name, value);
};
console.log("ELEMENT PROPERTY (new Proxy) INJECTED");
}
//---***========================================***---注入location---***========================================***---
class ProxyLocation {
constructor(originalLocation) {
this.originalLocation = originalLocation;
}
// 方法:重新加载页面
reload(forcedReload) {
this.originalLocation.reload(forcedReload);
}
// 方法:替换当前页面
replace(url) {
this.originalLocation.replace(changeURL(url));
}
// 方法:分配一个新的 URL
assign(url) {
this.originalLocation.assign(changeURL(url));
}
// 属性:获取和设置 href
get href() {
return oriUrlStr;
}
set href(url) {
this.originalLocation.href = changeURL(url);
}
// 属性:获取和设置 protocol
get protocol() {
return this.originalLocation.protocol;
}
set protocol(value) {
this.originalLocation.protocol = changeURL(value);
}
// 属性:获取和设置 host
get host() {
console.log("*host");
return original_host;
}
set host(value) {
console.log("*host");
this.originalLocation.host = changeURL(value);
}
// 属性:获取和设置 hostname
get hostname() {
console.log("*hostname");
return oriUrl.hostname;
}
set hostname(value) {
console.log("s hostname");
this.originalLocation.hostname = changeURL(value);
}
// 属性:获取和设置 port
get port() {
return oriUrl.port;
}
set port(value) {
this.originalLocation.port = value;
}
// 属性:获取和设置 pathname
get pathname() {
console.log("*pathname");
return oriUrl.pathname;
}
set pathname(value) {
console.log("*pathname");
this.originalLocation.pathname = value;
}
// 属性:获取和设置 search
get search() {
console.log("*search");
console.log(oriUrl.search);
return oriUrl.search;
}
set search(value) {
console.log("*search");
this.originalLocation.search = value;
}
// 属性:获取和设置 hash
get hash() {
return oriUrl.hash;
}
set hash(value) {
this.originalLocation.hash = value;
}
// 属性:获取 origin
get origin() {
return oriUrl.origin;
}
}
function documentLocationInject(){
Object.defineProperty(document, 'URL', {
get: function () {
return oriUrlStr;
},
set: function (url) {
document.URL = changeURL(url);
}
});
Object.defineProperty(document, '${replaceUrlObj}', {
get: function () {
return new ProxyLocation(window.location);
},
set: function (url) {
window.location.href = changeURL(url);
}
});
console.log("LOCATION INJECTED");
}
function windowLocationInject() {
Object.defineProperty(window, '${replaceUrlObj}', {
get: function () {
return new ProxyLocation(window.location);
},
set: function (url) {
window.location.href = changeURL(url);
}
});
console.log("WINDOW LOCATION INJECTED");
}
//---***========================================***---注入历史---***========================================***---
function historyInject(){
const originalPushState = History.prototype.pushState;
const originalReplaceState = History.prototype.replaceState;
History.prototype.pushState = function (state, title, url) {
var u = changeURL(url);
return originalPushState.apply(this, [state, title, u]);
};
History.prototype.replaceState = function (state, title, url) {
var u = changeURL(url);
return originalReplaceState.apply(this, [state, title, u]);
};
History.prototype.back = function () {
return originalBack.apply(this);
};
History.prototype.forward = function () {
return originalForward.apply(this);
};
History.prototype.go = function (delta) {
return originalGo.apply(this, [delta]);
};
console.log("HISTORY INJECTED");
}
//---***========================================***---Hook观察界面---***========================================***---
function obsPage() {
var yProxyObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
traverseAndConvert(mutation);
});
});
var config = { attributes: true, childList: true, subtree: true };
yProxyObserver.observe(document.body, config);
console.log("OBSERVING THE WEBPAGE...");
}
function traverseAndConvert(node) {
if (node instanceof HTMLElement) {
removeIntegrityAttributesFromElement(node);
covToAbs(node);
node.querySelectorAll('*').forEach(function(child) {
removeIntegrityAttributesFromElement(child);
covToAbs(child);
});
}
}
function covToAbs(element) {
var relativePath = "";
var setAttr = "";
if (element instanceof HTMLElement && element.hasAttribute("href")) {
relativePath = element.getAttribute("href");
setAttr = "href";
}
if (element instanceof HTMLElement && element.hasAttribute("src")) {
relativePath = element.getAttribute("src");
setAttr = "src";
}
// Check and update the attribute if necessary
if (setAttr !== "" && relativePath.indexOf(nowlink) != 0) {
if (!relativePath.includes("*")) {
try {
var absolutePath = changeURL(relativePath);
element.setAttribute(setAttr, absolutePath);
} catch (e) {
console.log("Exception occured: " + e.message + path + " " + relativePath);
}
}
}
}
function removeIntegrityAttributesFromElement(element){
if (element.hasAttribute('integrity')) {
element.removeAttribute('integrity');
}
}
//---***========================================***---Hook观察界面里面要用到的func---***========================================***---
function loopAndConvertToAbs(){
for(var ele of document.querySelectorAll('*')){
removeIntegrityAttributesFromElement(ele);
covToAbs(ele);
}
console.log("LOOPED EVERY ELEMENT");
}
function covScript(){ //由于observer经过测试不会hook添加的script标签,也可能是我测试有问题?
var scripts = document.getElementsByTagName('script');
for (var i = 0; i < scripts.length; i++) {
covToAbs(scripts[i]);
}
setTimeout(covScript, 3000);
}
//---***========================================***---操作---***========================================***---
networkInject();
windowOpenInject();
elementPropertyInject();
//appendChildInject(); 经过测试如果放上去将导致maps.google.com无法使用
documentLocationInject();
windowLocationInject();
historyInject();
//---***========================================***---在window.load之后的操作---***========================================***---
window.addEventListener('load', () => {
loopAndConvertToAbs();
console.log("CONVERTING SCRIPT PATH");
obsPage();
covScript();
});
console.log("WINDOW ONLOAD EVENT ADDED");
//---***========================================***---在window.error的时候---***========================================***---
window.addEventListener('error', event => {
var element = event.target || event.srcElement;
if (element.tagName === 'SCRIPT') {
console.log("Found problematic script:", element);
if(element.alreadyChanged){
console.log("this script has already been injected, ignoring this problematic script...");
return;
}
// 调用 covToAbs 函数
removeIntegrityAttributesFromElement(element);
covToAbs(element);
// 创建新的 script 元素
var newScript = document.createElement("script");
newScript.src = element.src;
newScript.async = element.async; // 保留原有的 async 属性
newScript.defer = element.defer; // 保留原有的 defer 属性
newScript.alreadyChanged = true;
// 添加新的 script 元素到 document
document.head.appendChild(newScript);
console.log("New script added:", newScript);
}
}, true);
console.log("WINDOW CORS ERROR EVENT ADDED");
`;
const mainPage = `
<!DOCTYPE html>
<html>
<head>
<style>
body{
background:rgb(150,10,10);
color:rgb(240,240,0);
}
a{
color:rgb(250,250,180);
}
del{
color:rgb(190,190,190);
}
.center{
text-align:center;
}
.important{
font-weight:bold;
font-size:27;
}
/* my style begins*/
form[id=urlForm] {
max-width: 340px;
min-width: 340px;
margin: 0 auto;
}
input[id=targetUrl] {
background-color: rgb(240,240,0);
}
button[id=jumpButton] {
background-color: rgb(240,240,0);
}
</style>
</head>
<body>
<h3 class="center">
I made this project because some extreme annoying network filter software in my school, which is notorious "Goguardian", and now it is open source at <a href="https://github.com/1234567Yang/cf-proxy-ex/">https://github.com/1234567Yang/cf-proxy-ex/</a>.
</h3>
<br><br><br>
<ul style="font-size:25;">
<li class="important">How to use this proxy:<br>
Type the website you want to go to after the website's url, for example: <br>
https://the current url/github.com<br>OR<br>https://the current url/https://github.com</li>
</ul>
<form id="urlForm" onsubmit="redirectToProxy(event)">
<fieldset>
<legend>Proxy Everything</legend>
<label for="targetUrl">TargetUrl: <input type="text" id="targetUrl" placeholder="Enter the target URL here..."></label>
<button type="submit" id="jumpButton">Jump!</button>
</fieldset>
</form>
<script>
function redirectToProxy(event) {
event.preventDefault();
const targetUrl = document.getElementById('targetUrl').value.trim();
const currentOrigin = window.location.origin;
window.open(currentOrigin + '/' + targetUrl, '_blank');
}
</script>
<ul>
<li>If your browser show 400 bad request, please clear your browser cookie<br></li>
<li>Why I make this:<br> Because school blcok every website that I can find math / CS and other subjects' study material and question solutions. In the eyes of the school, China (and some other countries) seems to be outside the scope of this "world". They block access to server IP addresses in China and block access to Chinese search engines and video websites. Of course, some commonly used social software has also been blocked, which once made it impossible for me to send messages to my parents on campus. I don't think that's how it should be, so I'm going to fight it as hard as I can. I believe this will not only benefit myself, but a lot more people can get benefits.</li>
<li>If this website is blocked by your school: <br>Contact me at <a href="mailto:help@lhyang.org">help@lhyang.org</a>, and I will setup a new webpage.</li>
<li>Limitation:<br>Although I tried my best to make every website proxiable, there still might be pages or resources that can not be load, and the most important part is that <span class="important">YOU SHOULD NEVER LOGIN ANY ACCOUNT VIA ONLINE PROXY</span>.</li>
</ul>
<h3>
<br>
<span>Proxies that can bypass the school network blockade:</span>
<br><br>
<span>Traditional VPNs such as <a href="https://hide.me/">hide me</a>.</span>
<br><br>
<a href="https://www.torproject.org/">Tor Browser</a><span>, short for The Onion Router, is free and open-source software for enabling anonymous communication. It directs Internet traffic via a free, worldwide volunteer overlay network that consists of more than seven thousand relays. Using Tor makes it more difficult to trace a user's Internet activity.</span>
<br><br>
<a href="https://v2rayn.org/">v2RayN</a><span> is a GUI client for Windows, support Xray core and v2fly core and others. You must subscribe to an <a href = "https://aijichang.org/6190/">airport</a> to use it. For example, you can subscribe <a href="https://feiniaoyun.xyz/">fly bird cloud</a>.</span>
<br><br>
<span>Bypass <del>Goguardian</del> by proxy: You can buy a domain($1) and setup by yourself: </span><a href="https://github.com/gaboolic/cloudflare-reverse-proxy">how to setup a proxy</a><span>. Unless <del>Goguardian</del> use white list mode, this can always work.</span>
<br>
<span>Too expensive? Never mind! There are a lot of free domains registration companies (for the first year of the domain) that do not need any credit card, search online!</span>
<br><br>
<span>Youtube video unblock: "Thanks" for Russia that they started to invade Ukraine and Google blocked the traffic from Russia, there are a LOT of mirror sites working. You can even <a href="https://github.com/iv-org/invidious">setup</a> one by yourself.</span>
</h3>
<a href="https://goguardian.com" style="visibility:hidden"></a>
<a href="https://blocked.goguardian.com/" style="visibility:hidden"></a>
<a href="https://www.google.com/gen_204" style="visibility:hidden"></a>
<p style="font-size:280px !important;width:100%;" class="center">
☭
</p>
</body>
</html>
`;
const pwdPage = `
<!DOCTYPE html>
<html>
<head>
<script>
function setPassword() {
try {
var cookieDomain = window.location.hostname;
var password = document.getElementById('password').value;
var currentOrigin = window.location.origin;
var oneWeekLater = new Date();
oneWeekLater.setTime(oneWeekLater.getTime() + (7 * 24 * 60 * 60 * 1000)); // 一周的毫秒数
document.cookie = "${passwordCookieName}" + "=" + password + "; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=" + cookieDomain;
document.cookie = "${passwordCookieName}" + "=" + password + "; expires=" + oneWeekLater.toUTCString() + "; path=/; domain=" + cookieDomain;
} catch(e) {
alert(e.message);
}
//window.location.href = currentOrigin + "?" + oneWeekLater.toUTCString();
location.reload();
}
</script>
</head>
<body>
<div>
<input id="password" type="password" placeholder="Password">
<button onclick="setPassword()">
Submit
</button>
</div>
</body>
</html>
`;
const redirectError = `
<html><head></head><body><h2>Error while redirecting: the website you want to access to may contain wrong redirect information, and we can not parse the info</h2></body></html>
`;
//new URL(请求路径, base路径).href;
async function handleRequest(request) {
//获取所有cookie
var siteCookie = request.headers.get('Cookie');
if (password != "") {
if(siteCookie != null && siteCookie != ""){
var pwd = getCook(passwordCookieName, siteCookie);
console.log(pwd);
if (pwd != null && pwd != "") {
if(pwd != password){
return handleWrongPwd();
}
}else{
return handleWrongPwd();
}
}else{
return handleWrongPwd();
}
}
const url = new URL(request.url);
if(request.url.endsWith("favicon.ico")){
return Response.redirect("https://www.baidu.com/favicon.ico", 301);
}
if(request.url.endsWith("robots.txt")){
return getHTMLResponse(`
User-Agent: *
Disallow: /*
Allow: /$
`);
}
//var siteOnly = url.pathname.substring(url.pathname.indexOf(str) + str.length);
var actualUrlStr = url.pathname.substring(url.pathname.indexOf(str) + str.length) + url.search + url.hash;
if (actualUrlStr == "") { //先返回引导界面
return getHTMLResponse(mainPage);
}
try {
var test = actualUrlStr;
if (!test.startsWith("http")) {
test = "https://" + test;
}
var u = new URL(test);
if (!u.host.includes(".")) {
throw new Error();
}
}
catch { //可能是搜素引擎,比如proxy.com/https://www.duckduckgo.com/ 转到 proxy.com/?q=key
var lastVisit;
if (siteCookie != null && siteCookie != "") {
lastVisit = getCook(lastVisitProxyCookie, siteCookie);
console.log(lastVisit);
if (lastVisit != null && lastVisit != "") {
//(!lastVisit.startsWith("http"))?"https://":"" +
//现在的actualUrlStr如果本来不带https:// 的话那么现在也不带,因为判断是否带protocol在后面
return Response.redirect(thisProxyServerUrlHttps + lastVisit + "/" + actualUrlStr, 301);
}
}
return getHTMLResponse("Something is wrong while trying to get your cookie: <br> siteCookie: " + siteCookie + "<br>" + "lastSite: " + lastVisit);
}
if (!actualUrlStr.startsWith("http") && !actualUrlStr.includes("://")) { //从www.xxx.com转到https://www.xxx.com
//actualUrlStr = "https://" + actualUrlStr;
return Response.redirect(thisProxyServerUrlHttps + "https://" + actualUrlStr, 301);
}
//if(!actualUrlStr.endsWith("/")) actualUrlStr += "/";
const actualUrl = new URL(actualUrlStr);
let clientHeaderWithChange = new Headers();
//***代理发送数据的Header:修改部分header防止403 forbidden,要先修改, 因为添加Request之后header是只读的(***ChatGPT,未测试)
for (var pair of request.headers.entries()) {
//console.log(pair[0]+ ': '+ pair[1]);
clientHeaderWithChange.set(pair[0], pair[1].replaceAll(thisProxyServerUrlHttps, actualUrlStr).replaceAll(thisProxyServerUrl_hostOnly, actualUrl.host));
}
let clientRequestBodyWithChange
if (request.body) {
clientRequestBodyWithChange = await request.text();
clientRequestBodyWithChange = clientRequestBodyWithChange
.replaceAll(thisProxyServerUrlHttps, actualUrlStr)
.replaceAll(thisProxyServerUrl_hostOnly, actualUrl.host);
}
const modifiedRequest = new Request(actualUrl, {
headers: clientHeaderWithChange,
method: request.method,
body: (request.body) ? clientRequestBodyWithChange : request.body,
//redirect: 'follow'
redirect: "manual"
//因为有时候会
//https://www.jyshare.com/front-end/61 重定向到
//https://www.jyshare.com/front-end/61/
//但是相对目录就变了
});
//console.log(actualUrl);
const response = await fetch(modifiedRequest);
if (response.status.toString().startsWith("3") && response.headers.get("Location") != null) {
//console.log(base_url + response.headers.get("Location"))
try {
return Response.redirect(thisProxyServerUrlHttps + new URL(response.headers.get("Location"), actualUrlStr).href, 301);
} catch {
getHTMLResponse(redirectError + "<br>the redirect url:" + response.headers.get("Location") + ";the url you are now at:" + actualUrlStr);
}
}
var modifiedResponse;
var bd;
var hasProxyHintCook = (getCook(proxyHintCookieName, siteCookie) != "");
const contentType = response.headers.get("Content-Type");
if (contentType && contentType.startsWith("text/")) {
bd = await response.text();
//ChatGPT
let regex = new RegExp(`(?<!src="|href=")(https?:\\/\\/[^\s'"]+)`, 'g');
bd = bd.replace(regex, (match) => {
if (match.includes("http")) {
return thisProxyServerUrlHttps + match;
} else {
return thisProxyServerUrl_hostOnly + "/" + match;
}
});
console.log(bd); // 输出替换后的文本
if (contentType && (contentType.includes("text/html") || contentType.includes("text/javascript"))){
bd = bd.replace("window.location", "window." + replaceUrlObj);
bd = bd.replace("document.location", "document." + replaceUrlObj);
}
//bd.includes("<html") //不加>因为html标签上可能加属性 这个方法不好用因为一些JS中竟然也会出现这个字符串
//也需要加上这个方法因为有时候server返回json也是html
if (contentType && contentType.includes("text/html") && bd.includes("<html")) {
//console.log("STR" + actualUrlStr)
bd = covToAbs(bd, actualUrlStr);
bd = removeIntegrityAttributes(bd);
bd =
"<script>" +
((!hasProxyHintCook)?proxyHintInjection:"") +
httpRequestInjection +
"</script>" +
bd;
}
//else{
// //const type = response.headers.get('Content-Type');type == null || (type.indexOf("image/") == -1 && type.indexOf("application/") == -1)
// if(actualUrlStr.includes(".css")){ //js不用,因为我已经把网络消息给注入了
// for(var r of CSSReplace){
// bd = bd.replace(r, thisProxyServerUrlHttps + r);
// }
// }
// //问题:在设置css background image 的时候可以使用相对目录
// }
//console.log(bd);
modifiedResponse = new Response(bd, response);
} else {
var blob = await response.blob();
modifiedResponse = new Response(blob, response);
}
let headers = modifiedResponse.headers;
let cookieHeaders = [];
// Collect all 'Set-Cookie' headers regardless of case
for (let [key, value] of headers.entries()) {
if (key.toLowerCase() == 'set-cookie') {
cookieHeaders.push({ headerName: key, headerValue: value });
}
}
if (cookieHeaders.length > 0) {
cookieHeaders.forEach(cookieHeader => {
let cookies = cookieHeader.headerValue.split(',').map(cookie => cookie.trim());
for (let i = 0; i < cookies.length; i++) {
let parts = cookies[i].split(';').map(part => part.trim());
//console.log(parts);
// Modify Path
let pathIndex = parts.findIndex(part => part.toLowerCase().startsWith('path='));
let originalPath;
if (pathIndex !== -1) {
originalPath = parts[pathIndex].substring("path=".length);
}
let absolutePath = "/" + new URL(originalPath, actualUrlStr).href;;
if (pathIndex !== -1) {
parts[pathIndex] = `Path=${absolutePath}`;
} else {
parts.push(`Path=${absolutePath}`);
}
// Modify Domain
let domainIndex = parts.findIndex(part => part.toLowerCase().startsWith('domain='));
if (domainIndex !== -1) {
parts[domainIndex] = `domain=${thisProxyServerUrl_hostOnly}`;
} else {
parts.push(`domain=${thisProxyServerUrl_hostOnly}`);
}
cookies[i] = parts.join('; ');
}
// Re-join cookies and set the header
headers.set(cookieHeader.headerName, cookies.join(', '));
});
}
//bd != null && bd.includes("<html")
if (contentType && contentType.includes("text/html") && response.status == 200 && bd.includes("<html")) { //如果是HTML再加cookie,因为有些网址会通过不同的链接添加CSS等文件
let cookieValue = lastVisitProxyCookie + "=" + actualUrl.origin + "; Path=/; Domain=" + thisProxyServerUrl_hostOnly;
//origin末尾不带/
//例如:console.log(new URL("https://www.baidu.com/w/s?q=2#e"));
//origin: "https://www.baidu.com"
headers.append("Set-Cookie", cookieValue);
if(!hasProxyHintCook){
//添加代理提示
const expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + 24 * 60 * 60 * 1000); // 24小时
var hintCookie = `${proxyHintCookieName}=1; expires=${expiryDate.toUTCString()}; path=/`;
headers.append("Set-Cookie", hintCookie);
}
}
// 添加允许跨域访问的响应头
modifiedResponse.headers.set('Access-Control-Allow-Origin', '*');
//modifiedResponse.headers.set("Content-Security-Policy", "default-src *; script-src * 'unsafe-inline' 'unsafe-eval'; style-src * 'unsafe-inline'; img-src * data:; media-src *; frame-src *; font-src *; connect-src *; base-uri *; form-action *;");
if (modifiedResponse.headers.has("Content-Security-Policy")) {
modifiedResponse.headers.delete("Content-Security-Policy");
}
if (modifiedResponse.headers.has("Permissions-Policy")) {
modifiedResponse.headers.delete("Permissions-Policy");
}
modifiedResponse.headers.set("X-Frame-Options", "ALLOWALL");
if(!hasProxyHintCook){
//设置content立刻过期,防止多次弹代理警告(但是如果是Content-no-change还是会弹出)
modifiedResponse.headers.set("Cache-Control", "max-age=0");
}
return modifiedResponse;
}
function escapeRegExp(string) {
return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& 表示匹配的字符
}
//https://stackoverflow.com/questions/5142337/read-a-javascript-cookie-by-name
function getCook(cookiename, cookies) {
// Get name followed by anything except a semicolon
var cookiestring = RegExp(cookiename + "=[^;]+").exec(cookies);
// Return everything after the equal sign, or an empty string if the cookie name not found
return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./, "") : "");
}
const matchList = [[/href=("|')([^"']*)("|')/g, `href="`], [/src=("|')([^"']*)("|')/g, `src="`]];
function covToAbs(body, requestPathNow) {
var original = [];
var target = [];
for (var match of matchList) {
var setAttr = body.matchAll(match[0]);
if (setAttr != null) {
for (var replace of setAttr) {
if (replace.length == 0) continue;
var strReplace = replace[0];
if (!strReplace.includes(thisProxyServerUrl_hostOnly)) {
if (!isPosEmbed(body, replace.index)) {
var relativePath = strReplace.substring(match[1].toString().length, strReplace.length - 1);
if (!relativePath.startsWith("data:") && !relativePath.startsWith("mailto:") && !relativePath.startsWith("javascript:") && !relativePath.startsWith("chrome") && !relativePath.startsWith("edge")) {
try {
var absolutePath = thisProxyServerUrlHttps + new URL(relativePath, requestPathNow).href;
//body = body.replace(strReplace, match[1].toString() + absolutePath + `"`);
original.push(strReplace);
target.push(match[1].toString() + absolutePath + `"`);
} catch {
// 无视
}
}
}
}
}
}
}
for (var i = 0; i < original.length; i++) {
body = body.replace(original[i], target[i]);
}
return body;
}
function removeIntegrityAttributes(body) {
return body.replace(/integrity=("|')([^"']*)("|')/g, '');
}
// console.log(isPosEmbed("<script src='https://www.google.com/'>uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu</script>",2));
// VM195:1 false
// console.log(isPosEmbed("<script src='https://www.google.com/'>uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu</script>",10));
// VM207:1 false
// console.log(isPosEmbed("<script src='https://www.google.com/'>uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu</script>",50));
// VM222:1 true
function isPosEmbed(html, pos) {
if (pos > html.length || pos < 0) return false;
//取从前面`<`开始后面`>`结束,如果中间有任何`<`或者`>`的话,就是content
//<xx></xx><script>XXXXX[T]XXXXXXX</script><tt>XXXXX</tt>
// |-------------X--------------|
// ! !
// conclusion: in content
// Find the position of the previous '<'
let start = html.lastIndexOf('<', pos);
if (start === -1) start = 0;