-
Notifications
You must be signed in to change notification settings - Fork 82
/
Rewrite-Parser.beta.js
3058 lines (2755 loc) · 107 KB
/
Rewrite-Parser.beta.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
/***************************
支持将 QX重写 Surge模块 Loon插件 解析至Surge Shadowrocket Loon Stash
远程重写支持多链接输入,链接间用😂连接 可以 重写 模块 插件 混合传入
说明
原脚本作者@小白脸 脚本修改@chengkongyiban
感谢@xream 提供的replace-Header.js
echo-response.js
感谢@mieqq 提供的replace-body.js
插件图标用的 @Keikinn 的 StickerOnScreen项目 以及 @Toperlock 的图标库项目,感谢
项目地址:
https://github.com/Script-Hub-Org/Script-Hub
***************************/
const script_start = Date.now()
const JS_NAME = 'Script Hub: 重写转换'
const $ = new Env(JS_NAME)
let arg
if (typeof $argument != 'undefined') {
arg = Object.fromEntries($argument.split('&').map(item => item.split('=')))
} else {
arg = {}
}
// 超时设置 与 script-converter.js 相同
const HTTP_TIMEOUT = ($.getval('Parser_http_timeout') ?? 20) * 1000
const url = $request.url
const req = url.split(/file\/_start_\//)[1].split(/\/_end_\//)[0]
const reqArr = req.match('%F0%9F%98%82') ? req.split('%F0%9F%98%82') : [req]
//$.log("原始链接:" + req);
const urlArg = url.split(/\/_end_\//)[1]
//获取参数
const queryObject = parseQueryString(urlArg)
//$.log("参数:" + $.toStr(queryObject));
// 来源
const fromType = queryObject.type
//目标app
const targetApp = queryObject.target
const app = targetApp.split('-')[0]
const isSurgeiOS = targetApp == 'surge-module'
const isStashiOS = targetApp == 'stash-stoverride'
const isLooniOS = targetApp == 'loon-plugin'
const isShadowrocket = targetApp == 'shadowrocket-module'
const evJsori = queryObject.evalScriptori
const evJsmodi = queryObject.evalScriptmodi
const evUrlori = queryObject.evalUrlori
const evUrlmodi = queryObject.evalUrlmodi
const prepend = queryObject.prepend
const scEvJsori = queryObject.evJsori
const scEvJsmodi = queryObject.evJsmodi
const scEvUrlori = queryObject.evUrlori
const scEvUrlmodi = queryObject.evUrlmodi
let noNtf = queryObject.noNtf ? istrue(queryObject.noNtf) : false //默认开启通知
let localsetNtf = $.lodash_get(arg, 'Notify') || $.getval('ScriptHub通知') || ''
noNtf = localsetNtf == '开启通知' ? false : localsetNtf == '关闭通知' ? true : noNtf
let jqEnabled = istrue(queryObject.jqEnabled)
let openMsgHtml = istrue(queryObject.openMsgHtml)
noNtf = openMsgHtml ? true : noNtf
let nName = queryObject.n != undefined ? getArgArr(queryObject.n) : null //名字简介
let category = queryObject.category ?? null
let icon = queryObject.icon ?? null
let Pin0 = queryObject.y != undefined ? getArgArr(queryObject.y) : null //保留
let Pout0 = queryObject.x != undefined ? getArgArr(queryObject.x) : null //排除
let hnAdd = queryObject.hnadd != undefined ? queryObject.hnadd.split(/\s*,\s*/) : null //加
let hnDel = queryObject.hndel != undefined ? queryObject.hndel.split(/\s*,\s*/) : null //减
let hnRegDel = queryObject.hnregdel != undefined ? new RegExp(queryObject.hnregdel) : null //正则删除hostname
let synMitm = istrue(queryObject.synMitm) //将force与mitm同步
let delNoteSc = istrue(queryObject.del)
let nCron = queryObject.cron != undefined ? getArgArr(queryObject.cron) : null //替换cron目标
let ncronexp = queryObject.cronexp != undefined ? queryObject.cronexp.replace(/\./g, ' ').split('+') : null //新cronexp
let nArgTarget = queryObject.arg != undefined ? getArgArr(queryObject.arg) : null //arg目标
let nArg = queryObject.argv != undefined ? getArgArr(queryObject.argv) : null //arg参数
let nTilesTarget = queryObject.tiles != undefined ? getArgArr(queryObject.tiles) : null
let ntilescolor = queryObject.tcolor != undefined ? getArgArr(queryObject.tcolor) : null
let nPolicy = queryObject.policy != undefined ? queryObject.policy : null
let njsnametarget = queryObject.njsnametarget != undefined ? getArgArr(queryObject.njsnametarget) : null //修改脚本名目标
let njsname = queryObject.njsname != undefined ? getArgArr(queryObject.njsname) : null //修改脚本名
let timeoutt = queryObject.timeoutt != undefined ? getArgArr(queryObject.timeoutt) : null //修改超时目标
let timeoutv = queryObject.timeoutv != undefined ? getArgArr(queryObject.timeoutv) : null //修改超时的值
let enginet = queryObject.enginet != undefined ? getArgArr(queryObject.enginet) : null //修改引擎目标
let enginev = queryObject.enginev != undefined ? getArgArr(queryObject.enginev) : null //修改引擎的值
let jsConverter = queryObject.jsc != undefined ? getArgArr(queryObject.jsc) : null //脚本转换1
let jsConverter2 = queryObject.jsc2 != undefined ? getArgArr(queryObject.jsc2) : null //脚本转换2
let compatibilityOnly = istrue(queryObject.compatibilityOnly) //兼容转换
let keepHeader = istrue(queryObject.keepHeader) //保留mock header
let jsDelivr = istrue(queryObject.jsDelivr) //开启jsDelivr
let localText = queryObject.localtext != undefined ? '\n' + queryObject.localtext : '' //纯文本输入
let ipNoResolve = istrue(queryObject.nore) //ip规则不解析域名
let sni = queryObject.sni != undefined ? getArgArr(queryObject.sni) : null //sni嗅探
let pm = queryObject.pm != undefined ? getArgArr(queryObject.pm) : null // pre-matching
let sufkeepHeader = keepHeader == true ? '&keepHeader=true' : '' //用于保留header的后缀
let sufjsDelivr = jsDelivr == true ? '&jsDelivr=true' : '' //用于开启jsDeliver的后缀
//用于自定义发送请求的请求头
const reqHeaders = {
headers: {
'User-Agent': 'script-hub/1.0.0',
},
}
if (queryObject.headers) {
decodeURIComponent(queryObject.headers)
.split(/\r?\n/)
.map(i => {
if (/.+:.+/.test(i)) {
const [_, key, value] = i.match(/^(.*?):(.*)$/)
if (key?.length > 0 && value?.length > 0) {
reqHeaders.headers[key] = value
}
}
})
}
//插件图标区域
const iconStatus = $.getval('启用插件随机图标') ?? '启用'
const iconReplace = $.getval('替换原始插件图标') ?? '禁用'
const iconLibrary1 = $.getval('插件随机图标合集') ?? 'Doraemon(100P)'
const iconLibrary2 = iconLibrary1.split('(')[0]
const iconFormat = /gif/i.test(iconLibrary2) ? '.gif' : '.png'
//统一前置声明变量
let name,
desc,
randomicon,
body,
jscStatus,
jsc2Status,
jsPre,
jsSuf,
mark,
noteK,
ruletype,
rulenore,
rulesni,
rulepm,
rulePandV,
rulepolicy,
rulevalue,
modistatus,
hostdomain,
hostvalue,
panelname,
title,
content,
style,
scriptname,
jsurl,
jsname,
img,
jsfrom,
jstype,
eventname,
size,
proto,
engine,
jsptn,
jsarg,
rebody,
wakesys,
cronexp,
ability,
updatetime,
timeout,
tilesicon,
tilescolor,
urlInNum,
noteK2,
noteK4,
noteKn4,
noteKn6,
noteKn8,
rwtype,
rwptn,
rwvalue,
ori,
MITM,
force,
result
let Rewrite = isLooniOS ? '[Rewrite]' : '[URL Rewrite]'
//随机插件图标
if ((isStashiOS || isLooniOS) && iconStatus == '启用') {
const stickerStartNum = 1001
const stickerSum = iconLibrary1.split('(')[1].split('P')[0]
let randomStickerNum = parseInt(stickerStartNum + Math.random() * stickerSum).toString()
randomicon =
'https://github.com/Toperlock/Quantumult/raw/main/icon/' +
iconLibrary2 +
'/' +
iconLibrary2 +
'-' +
randomStickerNum +
iconFormat
}
//通知名区域
let rewriteName = req.substring(req.lastIndexOf('/') + 1).split('.')[0]
let resFile = urlArg.split('?')[0]
let resFileName = resFile.substring(0, resFile.lastIndexOf('.'))
let notifyName
if (nName != null && nName[0] != '') {
notifyName = nName[0]
} else {
notifyName = resFileName
}
//修改名字和简介
if (nName === null) {
name = rewriteName
desc = name
} else {
name = nName[0] != '' ? nName[0] : rewriteName
desc = nName[1] != undefined ? nName[1] : name
}
let modInfoObj = {
name: name,
desc: desc,
author: '',
icon: randomicon,
category: '',
}
//信息中转站
let bodyBox = [] //存储待转换的内容
let otherRule = [] //不支持的规则&脚本
let notBuildInPolicy = [] //不是内置策略的规则
let inBox = [] //被释放的重写或规则
let outBox = [] //被排除的重写或规则
let modInfoBox = [] //模块简介等信息
let modInputBox = [] //loon插件的可交互按钮
let hostBox = [] //host
let ruleBox = [] //规则
let rwBox = [] //重写
let rwhdBox = [] //HeaderRewrite
let rwbodyBox = [] // Body Rewrite
let panelBox = [] //Panel信息
let jsBox = [] //脚本
let mockBox = [] //MapLocal或echo-response
let hnBox = [] //MITM主机名
let fheBox = [] //force-http-engine
let skipBox = [] //skip-ip
let realBox = [] //real-ip
let hndelBox = [] //正则剔除的主机名
let sgArg = [] //surge模块参数
let hnaddMethod = '%APPEND%'
let fheaddMethod = '%APPEND%'
let skipaddMethod = '%APPEND%'
let realaddMethod = '%APPEND%'
//待输出
let modInfo = [] //模块简介
let httpFrame = '' //Stash的http:父框架
let tiles = [] //磁贴覆写
let General = []
let Panel = []
let host = []
let rules = []
let URLRewrite = []
let HeaderRewrite = []
let BodyRewrite = []
let MapLocal = []
let script = []
let cron = []
let providers = []
hnBox = hnAdd != null ? hnAdd : []
const jsRegex =
/\s*[=,]\s*(?:script-path|pattern|timeout|argument|script-update-interval|requires-body|max-size|ability|binary-body-mode|cronexpr?|wake-system|enabled?|engine|tag|type|img-url|debug|event-name|desc)\s*=\s*/
const panelRegex = /\s*[=,]\s*(?:title|content|style|script-name|update-interval)\s*=\s*/
const policyRegex = /^(direct|reject-?(img|video|dict|array|drop|200|tinygif)?(-no-drop)?|\{\{\{[^,]+\}\}\})$/i
const mockRegex = /\s+(?:data-type|status-code|header|data|data-path|mock-data-is-base64)\s*=/
//查询js binarymode相关
let binaryInfo = $.getval('Parser_binary_info')
if (binaryInfo != null && binaryInfo.length > 0) {
binaryInfo = $.toObj(binaryInfo)
} else {
binaryInfo = []
}
!(async () => {
if (evUrlori) {
evUrlori = (await $.http.get(evUrlori)).body
}
if (evUrlmodi) {
evUrlmodi = (await $.http.get(evUrlmodi)).body
}
if (req == 'http://local.text') {
body = localText
} else {
for (let i = 0; i < reqArr.length; i++) {
let res = await http(reqArr[i], reqHeaders)
let reStatus = res.status
body = reStatus == 200 ? res.body : reStatus == 404 ? '#!error=404: Not Found' : ''
reStatus == 404 && $.msg(JS_NAME, '来源链接已失效', '404: Not Found ---> ' + reqArr[i], '')
if (body.match(/^(?:\s)*\/\*[\s\S]*?(?:\r|\n)\s*\*+\//)) {
body = body.match(/^(?:\n|\r)*\/\*([\s\S]*?)(?:\r|\n)\s*\*+\//)[1]
bodyBox.push(body)
} else {
bodyBox.push(body)
}
} //for
body = bodyBox.join('\n\n') + localText
}
eval(evJsori)
eval(evUrlori)
// [Body Rewrite] 部分 rwbodyBox
let bodyRewrite = body.match(/(^|\n)\[Body Rewrite\]\n([\s\S]*?)\s*(\n\[|$)/)?.[2]
if (bodyRewrite) {
for await (let [y, x] of bodyRewrite.match(/[^\r\n]+/g).entries()) {
if (/^(#|;|\/\/)\s*/.test(x)) continue
const [_, type, regex, value] = x.match(/^((?:http-request|http-response)(?:-jq)?)\s+?(.*?)\s+?(.*?)$/)
rwbodyBox.push({ type, regex, value })
}
}
body = body.match(/[^\r\n]+/g)
for await (let [y, x] of body.entries()) {
//简单处理方便后续操作
x = x
.trim()
.replace(/^(#|;|\/\/)\s*/, '#')
.replace(/\s+[^\s]+\s+url-and-header\s+/, ' url ')
.replace(/(^[^#].+)\x20+\/\/.+/, '$1')
.replace(/^#!PROFILE-VERSION-REQUIRED\s+[0-9]+\s+/i, '')
.replace(/^(#)?host(-suffix|-keyword|-wildcard)?\s*,\s*/i, '$1DOMAIN$2,')
.replace(/^(#)?ip6-cidr\s*,\s*/i, '$1IP-CIDR6,')
if (!/^(#|\/\/|;)/.test(x)) {
x = x.replace(/\s+?(?:#|\/\/|;).*?$/, '')
}
//去掉注释
if (Pin0 != null) {
for (let i = 0; i < Pin0.length; i++) {
const elem = Pin0[i].trim()
if (x.indexOf(elem) != -1 && /^#/.test(x)) {
x = x.replace(/^#/, '')
inBox.push(x)
break
}
} //循环结束
} //去掉注释结束
//增加注释
if (Pout0 != null) {
for (let i = 0; i < Pout0.length; i++) {
const elem = Pout0[i].trim()
if (
x.indexOf(elem) != -1 &&
!/^(hostname|force-http-engine-hosts|skip-proxy|always-real-ip|real-ip)\s*=/.test(x) &&
!/^#/.test(x)
) {
x = '#' + x
outBox.push(x)
break
}
} //循环结束
} //增加注释结束
//剔除被注释的重写
if (delNoteSc == true && /^#/.test(x) && !/^#!/.test(x)) {
x = ''
}
let flags = {}
//sni嗅探
if (sni != null) {
for (let i = 0; i < sni.length; i++) {
const elem = sni[i].trim()
// 加入对逻辑规则的判断
if (isSurgeiOS && x.indexOf(elem) != -1) {
if (/^(DOMAIN(-\w+)?|RULE-SET|URL-REGEX)/i.test(x) && !/,\s*?extended-matching/i.test(x)) {
x = x + ',extended-matching'
break
} else if (/^(AND|OR|NOT)\s*?,/i.test(x)) {
// x = x.replace(
// /(\(\s*?(?:DOMAIN(?:-\w+)?|RULE-SET|URL-REGEX)\s*?,\s*?(?:(?!,\s*?extended-matching\s*?(?:,|\))).)+?\s*?)((\)\s*?)+?,)/g,
// '$1,extended-matching$2'
// )
// x = modifyRule(x, 'surge', { extendedMatching: true })
flags.extendedMatching = true
break
}
}
} //循环结束
} //启用sni嗅探结束
// pre-matching
if (pm != null) {
for (let i = 0; i < pm.length; i++) {
const elem = pm[i].trim()
// 加入对逻辑规则的判断
const _rulepolicy = x.match(/,\s*([^,]+?)\s*(\s*,\s*(pre-matching|no-resolve|extended-matching)\s*)*?\s*$/)?.[1]
if (
isSurgeiOS &&
x.indexOf(elem) != -1 &&
!/,\s*pre-matching/i.test(x) &&
/^REJECT(-[A-Z]+)*$/i.test(_rulepolicy)
) {
if (
/^(DOMAIN|DOMAIN|DOMAIN-SUFFIX|DOMAIN-KEYWORD|DOMAIN-SET|DOMAIN-WILDCARD|IP-CIDR|IP-CIDR6|GEOIP|IP-ASN|SUBNET|DEST-PORT|SRC-PORT|SRC-IP|RULE-SET)\s*?,/i.test(
x
)
) {
x = x + ',pre-matching'
break
} else if (/^(AND|OR|NOT)\s*?,/i.test(x)) {
// const pre_matching_regex = /\(\s*?(((?!(AND|NOT|OR))(\w|-))+?)\s*?,\s*?.+?\s*?((\)\s*?)+?,)/g
// let not_matched = false
// while ((matched = pre_matching_regex.exec(x))) {
// if (
// !/^(DOMAIN|DOMAIN|DOMAIN-SUFFIX|DOMAIN-KEYWORD|DOMAIN-SET|DOMAIN-WILDCARD|IP-CIDR|IP-CIDR6|GEOIP|IP-ASN|SUBNET|DEST-PORT|SRC-PORT|SRC-IP|RULE-SET)$/i.test(
// matched?.[1]
// )
// ) {
// not_matched = true
// break
// }
// }
// if (!not_matched) {
// x = x + ',pre-matching'
// break
// }
// x = modifyRule(x, 'surge', { preMatching: true })
flags.preMatching = true
}
}
} //循环结束
} //启用 pre-matching 结束
//ip规则不解析域名
if (ipNoResolve == true) {
if (/^(IP(-\w+)?|RULE-SET|GEOIP)/i.test(x) && !/,\s*?no-resolve/i.test(x)) {
x = x + ',no-resolve'
} else if (/^(AND|OR|NOT)\s*?,/i.test(x)) {
// x = x.replace(
// /(\(\s*?(?:IP(?:-\w+)?|RULE-SET|GEOIP)\s*?,\s*?(?:(?!,\s*?no-resolve\s*?(?:,|\))).)+?\s*?)((\)\s*?)+?,)/g,
// '$1,no-resolve$2'
// )
// x = modifyRule(x, 'surge', { noResolve: true })
flags.noResolve = true
}
} //增加ip规则不解析域名结束
if (/^(AND|OR|NOT)\s*?,/i.test(x)) {
x = modifyRule(x, 'surge', flags)
}
if (jsConverter != null) {
jscStatus = isJsCon(x, jsConverter)
}
if (jsConverter2 != null) {
jsc2Status = isJsCon(x, jsConverter2)
}
if (jsc2Status == true) {
jscStatus = false
}
jsPre = ''
jsSuf = ''
if (jscStatus == true || jsc2Status == true) {
jsPre = 'http://script.hub/convert/_start_/'
}
if (jscStatus == true) {
jsSuf = `/_end_/_yuliu_.js?type=_js_from_-script&target=${app}-script`
} else if (jsc2Status == true) {
jsSuf = `/_end_/_yuliu_.js?type=_js_from_-script&target=${app}-script&wrap_response=true`
}
if (compatibilityOnly == true && (jscStatus == true || jsc2Status == true)) {
jsSuf = jsSuf + '&compatibilityOnly=true'
}
if (prepend && (jscStatus == true || jsc2Status == true)) {
jsSuf = jsSuf + `&prepend=${encodeURIComponent(prepend)}`
}
if (scEvJsori && (jscStatus == true || jsc2Status == true)) {
jsSuf = jsSuf + `&evalScriptori=${encodeURIComponent(scEvJsori)}`
}
if (scEvJsmodi && (jscStatus == true || jsc2Status == true)) {
jsSuf = jsSuf + `&evalScriptmodi=${encodeURIComponent(scEvJsmodi)}`
}
if (scEvUrlori && (jscStatus == true || jsc2Status == true)) {
jsSuf = jsSuf + `&evalUrlori=${encodeURIComponent(scEvUrlori)}`
}
if (scEvUrlmodi && (jscStatus == true || jsc2Status == true)) {
jsSuf = jsSuf + `&evalUrlmodi=${encodeURIComponent(scEvUrlmodi)}`
}
//模块信息
if (/^#!.+?=\s*$/.test(x)) {
} else if (isLooniOS && /^#!(?:select|input)\s*=\s*.+/.test(x)) {
getInputInfo(x, modInputBox)
} else if (/^#!.+?=.+/.test(x) && !/^#!(?:select|input)\s*=\s*.+/.test(x)) {
getModInfo(x)
}
//#!arguments参数
if (!isSurgeiOS && /^#!arguments\s*=\s*.+/.test(x)) {
parseArguments(x)
}
//hostname
if (/^hostname\s*=.+/.test(x)) hnaddMethod = getHn(x, hnBox, hnaddMethod)
if (/^force-http-engine-hosts\s*=.+/.test(x)) fheaddMethod = getHn(x, fheBox, fheaddMethod)
if (/^skip-proxy\s*=.+/.test(x)) skipaddMethod = getHn(x, skipBox, skipaddMethod)
if (/^(?:always-)?real-ip\s*=.+/.test(x)) realaddMethod = getHn(x, realBox, realaddMethod)
//reject 解析
if (
/.+reject(?:-\w+)?$/i.test(x) &&
!/^#?(DOMAIN.*?\s*,|IP-CIDR6?\s*,|IP-ASN\s*,|OR\s*,|AND\s*,|NOT\s*,|USER-AGENT\s*,|URL-REGEX\s*,|RULE-SET\s*,|DE?ST-PORT\s*,|PROTOCOL\s*,)/i.test(
x
) &&
!/^#!/.test(x)
) {
mark = getMark(y, body)
rw_reject(x, mark)
}
//重定向 解析
if (/(?:\s(?:302|307|header)(?:$|\s)|url\s+30(?:2|7)\s)/.test(x)) {
mark = getMark(y, body)
rw_redirect(x, mark)
}
if (/\s((request|response)-body-json-jq)\s/.test(x)) {
let [_, regex, type, value] = x.match(/^(.*?)\s+?(?:(request|response)-body-json-jq)\s+?(.*?)\s*$/)
if (jqEnabled && isSurgeiOS) {
const jqPath = value.match(/jq-path="(.+?)"/)?.[1]
if (jqPath) {
if (/^https?:\/\//.test(jqPath)) {
value = `'${(await $.http.get(jqPath)).body.replace(/^#.*$/gm, '').replace(/$\r?\n/gm, ' ')}'`
} else {
value = undefined
const e = `暂不支持本地 JQ 文件:\n${x}`
console.log(e)
shNotify(e)
}
}
if (value) {
rwbodyBox.push({ type: `http-${type}-jq`, regex, value })
}
} else if (isLooniOS) {
URLRewrite.push(x)
}
}
if (/\s((request|response)-body-(json-(add|del|replace)|replace-regex))\s/.test(x)) {
let [_, regex, __, httpType, action, ___, suffix] = x.match(
/^(.*?)\s+?((request|response)-body-(json-(add|del|replace)|replace-regex))\s+?(.*?)\s*$/
)
const suffixArray = suffix.split(/\s+/)
let newSuffixArray = []
if (action === 'json-del') {
if (suffix) {
newSuffixArray = suffixArray.map(item => {
return parseLoonKey(item)
})
}
} else {
for (let index = 0; index < suffixArray.length; index += 2) {
const key = suffixArray[index]
let value = suffixArray[index + 1]
if (value != null) {
newSuffixArray.push([
parseLoonKey(key),
['json-add', 'json-replace'].includes(action) ? parseLoonValue(value) : parseLoonKey(value),
])
}
}
}
const jsurl = 'https://raw.githubusercontent.com/Script-Hub-Org/Script-Hub/main/scripts/body-rewrite.js'
let jstype = `http-${httpType}`
const jsptn = regex
let args = [[action, newSuffixArray]]
if (jqEnabled && isSurgeiOS) {
if (action === 'json-add') {
newSuffixArray.forEach(item => {
const paths = parseJsonPath(item[0])
rwbodyBox.push({
type: `${jstype}-jq`,
regex: jsptn,
value: `'setpath(${JSON.stringify(paths)}; ${JSON.stringify(item[1])})'`,
})
})
} else if (action === 'json-del') {
newSuffixArray.forEach(item => {
const paths = parseJsonPath(item)
rwbodyBox.push({ type: `${jstype}-jq`, regex: jsptn, value: `'delpaths([${JSON.stringify(paths)}])'` })
})
} else if (action === 'json-replace') {
newSuffixArray.forEach(item => {
const paths = parseJsonPath(item[0])
const parant = [...paths]
const last = parant.pop()
rwbodyBox.push({
type: `${jstype}-jq`,
regex: jsptn,
value: `'if (getpath(${JSON.stringify(parant)}) | has(${
/^\d+$/.test(last) ? last : `"${last}"`
})) then (setpath(${JSON.stringify(paths)}; ${JSON.stringify(item[1])})) else . end'`,
})
})
} else {
newSuffixArray = newSuffixArray.map(item => item.join(' '))
rwbodyBox.push({ type: jstype, regex: jsptn, value: newSuffixArray.join(' ') })
}
} else {
// console.log(JSON.stringify(args, null, 2))
const index = jsBox.findIndex(i => i.jsurl === jsurl && i.jstype === jstype && i.jsptn === jsptn)
if (index === -1) {
jsBox.push({
jsname: `body_rewrite_${y}`,
jstype,
jsptn,
jsurl,
rebody: true,
size: -1,
timeout: '30',
jsarg: encodeURIComponent(JSON.stringify(args)),
ori: x,
num: y,
})
} else {
let jsargs = JSON.parse(decodeURIComponent(jsBox[index].jsarg))
jsBox[index].jsarg = encodeURIComponent(JSON.stringify([...jsargs, args[0]]))
}
}
}
//header rewrite 解析
if (/\s(response-)?header-(?:del|add|replace|replace-regex)\s/.test(x)) {
mark = getMark(y, body)
noteK = isNoteK(x)
x = x.replace(/^#/, '')
if (fromType === 'loon-plugin') {
let [_, __, prefix, isResponseHeaderRewrite, action, suffix] = x.match(
/^((.*?\s)(response-)?(header-(?:del|add|replace|replace-regex)\s))\s*(.*?)\s*$/
)
prefix = `${isResponseHeaderRewrite ? 'http-response' : 'http-request'} ${prefix}${action}`
const suffixArray = suffix.split(/\s+/)
const newSuffixArray = []
if (/\s(response-)?header-del\s/.test(prefix)) {
for (let index = 0; index < suffixArray.length; index++) {
const key = suffixArray[index]
newSuffixArray.push(`'${parseLoonKey(key)}'`)
}
} else if (/\s(response-)?header-replace-regex\s/.test(prefix)) {
for (let index = 0; index < suffixArray.length; index += 3) {
const key = suffixArray[index]
const value = `${`'${parseLoonKey(suffixArray[index + 1])}'`} ${`'${parseLoonKey(
suffixArray[index + 2]
)}'`}`
if (value != null) {
newSuffixArray.push(`'${parseLoonKey(key)}' ${value}`)
}
}
} else {
for (let index = 0; index < suffixArray.length; index += 2) {
const key = suffixArray[index]
const value = suffixArray[index + 1]
if (value != null) {
newSuffixArray.push(`'${parseLoonKey(key)}' '${parseLoonKey(value)}'`)
}
}
}
// console.log({ mark, noteK, x })
for (let index = 0; index < newSuffixArray.length; index++) {
let i = newSuffixArray[index]
rwhdBox.push({ mark, noteK, x: `${prefix}${i}` })
}
} else {
rwhdBox.push({ mark, noteK, x })
}
}
//(request|response)-(header|body) 解析
if (/\surl\s+(?:request|response)-(?:header|body)\s/i.test(x)) {
mark = getMark(y, body)
getQxReInfo(x, y, mark)
}
//rule解析
if (
/^(#|\/\/|;)?\s*?(domain|domain-suffix|domain-keyword|domain-set|domain-wildcard|ip-cidr|ip-cidr6|geoip|ip-asn|rule-set|url-regex|user-agent|process-name|subnet|dest-port|dst-port|in-port|src-port|src-ip|protocol|network|script|hostname-type|cellular-radio|device-name|domain-regex|geosite|ip-suffix|src-geoip|src-ip-asn|src-ip-cidr|src-ip-suffix|in-type|in-user|in-name|process-path|process-path-regex|process-name-regex|uid|dscp|sub-rule|match|and|or|not)\s*?,.+/i.test(
x
)
) {
mark = getMark(y, body)
noteK = isNoteK(x)
ruletype = x.split(/\s*,\s*/)[0].replace(/^#/, '')
rulenore = /,\s*no-resolve/.test(x) ? ',no-resolve' : ''
rulesni = /,\s*extended-matching/.test(x) ? ',extended-matching' : ''
rulepm = /,\s*pre-matching/.test(x) ? ',pre-matching' : ''
rulePandV = x
.replace(/^#/, '')
.replace(ruletype, '')
.replace(/\s*,\s*no-resolve/, '')
.replace(/\s*,\s*extended-matching/, '')
.replace(/\s*,\s*pre-matching/, '')
.replace(/^\s*,\s*/, '')
rulepolicy = getPolicy(rulePandV)
rulevalue = rulePandV
.replace(rulepolicy, '')
.replace(/\s*,\s*$/, '')
.replace(/"/g, '')
if (nPolicy != null && !policyRegex.test(rulepolicy)) {
rulepolicy = nPolicy
modistatus = 'yes'
} else {
modistatus = 'no'
}
ruleBox.push({ mark, noteK, ruletype, rulevalue, rulepolicy, rulenore, rulesni, rulepm, ori: x, modistatus })
} //rule解析结束
//host解析
if (
/^#?(?:\*|localhost|[-*?0-9a-z]+\.[-*.?0-9a-z]+)\s*=\s*(?:sever\s*:\s*|script\s*:\s*)?[\s0-9a-z:/,.]+$/g.test(x)
) {
noteK = isNoteK(x)
mark = getMark(y, body)
hostdomain = x.split(/\s*=\s*/)[0]
hostvalue = x.split(/\s*=\s*/)[1]
hostBox.push({ mark, noteK, hostdomain, hostvalue, ori: x })
}
//Panel信息
if (/[=,]\s*script-name\s*=.+/.test(x)) {
mark = getMark(y, body)
noteK = isNoteK(x)
panelname = x.split(/\s*=/)[0].replace(/^#/, '')
title = getJsInfo(x, /[=,\s]\s*title\s*=\s*/)
content = getJsInfo(x, /[=,\s]\s*content\s*=\s*/)
style = getJsInfo(x, /[=,\s]\s*style\s*=\s*/)
scriptname = getJsInfo(x, /[=,\s]\s*script-name\s*=\s*/)
updatetime = getJsInfo(x, /[=,\s]\s*update-interval\s*=\s*/)
panelBox.push({
mark,
noteK,
panelname,
title,
content,
style,
scriptname,
updatetime,
ori: x,
num: y,
})
} //Panel信息解析结束
//脚本解析
if (/script-path\s*=.+/.test(x)) {
mark = getMark(y, body)
noteK = isNoteK(x)
jsurl = getJsInfo(x, /script-path\s*=\s*/)
jsname = /[=,]\s*type\s*=\s*/.test(x)
? x.split(/\s*=/)[0].replace(/^#/, '')
: /,\s*tag\s*=\s*/.test(x)
? getJsInfo(x, /,\s*tag\s*=\s*/)
: jsurl.substring(jsurl.lastIndexOf('/') + 1, jsurl.lastIndexOf('.'))
img = getJsInfo(x, /[,\s]\s*img-url\s*=\s*/)
jsfrom = 'surge'
jsurl = toJsc(jsurl, jscStatus, jsc2Status, jsfrom)
jstype = /[=,]\s*type\s*=\s*/.test(x) ? getJsInfo(x, /[=,]\s*type\s*=\s*/) : x.split(/\s+/)[0].replace(/^#/, '')
eventname = getJsInfo(x, /[=,\s]\s*event-name\s*=\s*/)
size = getJsInfo(x, /[=,\s]\s*max-size\s*=\s*/)
proto = getJsInfo(x, /[=,\s]\s*binary-body-mode\s*=\s*/)
jsptn = /[=,]\s*pattern\s*=\s*/.test(x)
? getJsInfo(x, /[=,]\s*pattern\s*=\s*/).replace(/"/g, '')
: x.split(/\s+/)[1]
jsptn = /cron|event|network-changed|generic|dns|rule/i.test(jstype) ? '' : jsptn
jsarg = getJsInfo(x, /[=,\s]\s*argument\s*=\s*/)
rebody = getJsInfo(x, /[=,\s]\s*requires-body\s*=\s*/)
wakesys = getJsInfo(x, /[=,\s]\s*wake-system\s*=\s*/)
cronexp = /cronexpr?\s*=\s*/.test(x)
? getJsInfo(x, /[=,\s]\s*cronexpr?\s*=\s*/)
: /cron\s+"/.test(x)
? x.split('"')[1]
: ''
ability = getJsInfo(x, /[=,\s]\s*ability\s*=\s*/)
engine = getJsInfo(x, /[=,\s]\s*engine\s*=\s*/)
updatetime = getJsInfo(x, /[=,\s]\s*script-update-interval\s*=\s*/)
timeout = getJsInfo(x, /[=,\s]\s*timeout\s*=\s*/)
tilesicon = jstype == 'generic' && /icon=/.test(x) ? x.split('icon=')[1].split('&')[0] : ''
tilescolor = jstype == 'generic' && /icon-color=/.test(x) ? x.split('icon-color=')[1].split('&')[0] : ''
if (nCron != null && jstype != 'cron') {
for (let i = 0; i < nCron.length; i++) {
let elem = nCron[i].trim()
if (x.indexOf(elem) != -1) {
let jsname = jsurl.substring(jsurl.lastIndexOf('/') + 1, jsurl.lastIndexOf('.')) + '-cron'
jsBox.push({
mark,
noteK,
jsname,
img,
jstype: 'cron',
jsptn: '',
jsurl,
updatetime,
wakesys: '1',
timeout: '120',
ori: x,
num: y,
})
}
} //for
}
// 注释不加
if (!/^(#|;|\/\/)\s*/.test(x)) {
jsBox.push({
mark,
noteK,
jsname,
img,
jstype,
jsptn,
jsurl,
rebody,
proto,
size,
ability,
updatetime,
timeout,
jsarg,
cronexp,
wakesys,
tilesicon,
tilescolor,
eventname,
engine,
ori: x,
num: y,
})
}
} //脚本解析结束
//qx脚本解析
if (/\surl\s+script-/.test(x)) {
x = x.replace(/\s{2,}/g, ' ')
mark = getMark(y, body)
noteK = isNoteK(x)
jstype = x.match(' url script-response') ? 'http-response' : 'http-request'
urlInNum = x.split(/\s/).indexOf('url')
jsptn = x.split(/\s/)[urlInNum - 1].replace(/^#/, '')
jsurl = x.split(/\s/)[urlInNum + 2]
jsfrom = 'qx'
jsname = jsurl.substring(jsurl.lastIndexOf('/') + 1, jsurl.lastIndexOf('.'))
jsarg = ''
proto = await isBinaryMode(jsurl, jsname)
jsurl = toJsc(jsurl, jscStatus, jsc2Status, jsfrom)
rebody = /\sscript[^\s]*(-body|-analyze)/.test(x) ? 'true' : ''
size = rebody == 'true' ? '-1' : ''
if (nCron != null) {
for (let i = 0; i < nCron.length; i++) {
let elem = nCron[i].trim()
if (x.indexOf(elem) != -1) {
let jsname = jsurl.substring(jsurl.lastIndexOf('/') + 1, jsurl.lastIndexOf('.')) + '-cron'
jsBox.push({
mark,
noteK,
jsname,
jstype: 'cron',
jsptn: '',
jsurl,
wakesys: '1',
timeout: '120',
ori: x,
num: y,
})
}
} //for
}
jsBox.push({
mark,
noteK,
jsname,
jstype,
jsptn,
jsurl,
rebody,
proto,
size,
timeout: '60',
ori: x,
num: y,
})
} //qx脚本解析结束
//qx cron脚本解析
if (
/^(?!^(?:#!arguments-desc\s*=|#!desc\s*=))[^\s]+\s+[^u\s]+\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+([^\s]+\s+)?(https?|ftp|file):\/\//.test(
x
)
) {
mark = getMark(y, body)
noteK = isNoteK(x)
cronexp = x
.replace(/\s{2,}/g, ' ')
.split(/\s(https?|ftp|file)/)[0]
.replace(/^#/, '')
jsurl = x
.replace(/^#/, '')
.replace(/\x20{2,}/g, ' ')
.replace(cronexp, '')
.split(/\s*,\s*/)[0]
.trim()
jsname = /,\s*tag\s*=/.test(x)
? getJsInfo(x, /[,\s]\s*tag\s*=\s*/, jsRegex)
: jsurl.substring(jsurl.lastIndexOf('/') + 1, jsurl.lastIndexOf('.'))
img = getJsInfo(x, /[,\s]\s*img-url\s*=\s*/, jsRegex)
jsfrom = 'qx'
jsurl = toJsc(jsurl, jscStatus, jsc2Status, jsfrom)
jsBox.push({
mark,
noteK,
jsname,
img,
jstype: 'cron',
jsptn: '',
cronexp,
jsurl,
wakesys: '1',
timeout: '120',
ori: x,
num: y,
})
} //qx cron 脚本解析结束
//mock 解析
if (/url\s+echo-response\s|\sdata\s*=\s*"|\sdata-type\s*=/.test(x)) {
mark = getMark(y, body)
getMockInfo(x, mark, y)
}
} //for await循环结束
//去重
let obj = {}
inBox = [...new Set(inBox)]
outBox = [...new Set(outBox)]
hnBox = [...new Set(hnBox)]
fheBox = [...new Set(fheBox)]
skipBox = [...new Set(skipBox)]
realBox = [...new Set(realBox)]
ruleBox = [...new Set(ruleBox)]
modInputBox = modInputBox.reduce((curr, next) => {
/*判断对象中是否已经有该属性 没有的话 push 到 curr数组*/
obj[next.a + next.b] ? '' : (obj[next.a + next.b] = curr.push(next))
return curr
}, [])
hostBox = hostBox.reduce((curr, next) => {
/*判断对象中是否已经有该属性 没有的话 push 到 curr数组*/
obj[next.hostdomain] ? '' : (obj[next.hostdomain] = curr.push(next))
return curr
}, [])
rwBox = rwBox.reduce((curr, next) => {
/*判断对象中是否已经有该属性 没有的话 push 到 curr数组*/
obj[next.rwptn] ? '' : (obj[next.rwptn] = curr.push(next))
return curr
}, [])