forked from Onezyh/Pages-SUB-Convert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_worker.js
241 lines (212 loc) · 9.21 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
// 部署完成后在网址后面输入/,加上下方设置的mytoken=的值,即可获取聚合后的节点
let mytoken = 'auto'; //可根据需要自行设定,或者使用UUID在线生成网站进行生成:https://1024tools.com/uuid
let BotToken =''; //可以为空,或电报@BotFather关注机器人,输入/start,选择:/newbot进行获取
let ChatID =''; //可以为空,或电报@userinfobot中获取,选择:/start进行获取
let TG = 0; //新手勿动, 开发者选项,1 为推送所有的访问信息,0 为不推送订阅转换后端的访问信息与异常访问
let FileName = 'Pages-SUB-Convert';
let SUBUpdateTime = 6; //更改此次设置订阅更新时间,单位小时
//在以下输入您的自建节点链接或订阅链接,请保留双引号
let MainData = `
vless://b7a392e2-4ef0-4496-90bc-1c37bb234904@cf.090227.xyz:443?encryption=none&security=tls&sni=edgetunnel-2z2.pages.dev&fp=random&type=ws&host=edgetunnel-2z2.pages.dev&path=%2F%3Fed%3D2048#%E5%8A%A0%E5%85%A5%E6%88%91%E7%9A%84%E9%A2%91%E9%81%93https%3A%2F%2Ft.me%2FOneZyhCN%E8%8E%B7%E5%8F%96%E6%9B%B4%E5%A4%9A%E8%B5%84%E6%BA%90
https://sub.xf.free.hr/auto
https://hy2sub.pages.dev
`
//请将机场订阅链接填入上方
let urls = [];// https://subs.zeabur.app/clash , https://neko-warp.nloli.xyz/neko_warp.yaml
let subconverter = "apiurl.v1.mk"; //在线订阅转换后端,目前使用肥羊的订阅转换功能。支持自建psub 可自行搭建https://github.com/bulianglin/psub
let subconfig = "https://raw.githubusercontent.com/cmliu/ACL4SSR/main/Clash/config/ACL4SSR_Online_MultiCountry.ini"; //订阅配置文件,可自行更换
export default {
async fetch (request,env) {
const userAgentHeader = request.headers.get('User-Agent');
const userAgent = userAgentHeader ? userAgentHeader.toLowerCase() : "null";
const url = new URL(request.url);
const token = url.searchParams.get('token');
mytoken = env.TOKEN || mytoken;
BotToken = env.TGTOKEN || BotToken;
ChatID = env.TGID || ChatID;
TG = env.TG || TG;
subconverter = env.SUBAPI || subconverter;
subconfig = env.SUBCONFIG || subconfig;
FileName = env.SUBNAME || FileName;
MainData = env.LINK || MainData;
if(env.LINKSUB) urls = await ADD(env.LINKSUB);
let links = await ADD(MainData + '\n' + urls.join('\n'));
let link = "";
let linksub = "";
for (let x of links) {
if (x.toLowerCase().startsWith('http')) {
linksub += x + '\n';
} else {
link += x + '\n';
}
}
MainData = link;
urls = await ADD(linksub);
let sublinks = request.url ;
//console.log(MainData,urls,sublinks);
let warp = env.WARP ;
if(warp && warp != "") sublinks += '|' + (await ADD(warp)).join('|');
if ( !(token == mytoken || url.pathname == ("/"+ mytoken) || url.pathname.includes("/"+ mytoken + "?")) ) {
if ( TG == 1 && url.pathname !== "/" && url.pathname !== "/favicon.ico" ) await sendMessage("#异常访问", request.headers.get('CF-Connecting-IP'), `UA: ${userAgent}</tg-spoiler>\n域名: ${url.hostname}\n<tg-spoiler>入口: ${url.pathname + url.search}</tg-spoiler>`);
//首页改成一个nginx伪装页
return new Response(`
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
`, {
headers: {
'Content-Type': 'text/html; charset=UTF-8',
},
});
} else if ( TG == 1 || !userAgent.includes('subconverter') || !userAgent.includes('null')){
await sendMessage("#获取订阅", request.headers.get('CF-Connecting-IP'), `UA: ${userAgentHeader}</tg-spoiler>\n域名: ${url.hostname}\n<tg-spoiler>入口: ${url.pathname + url.search}</tg-spoiler>`);
}
let req_data = MainData;
// 创建一个AbortController对象,用于控制fetch请求的取消
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort(); // 取消所有请求
}, 1618); // 1.618秒后触发
try {
const responses = await Promise.allSettled(urls.map(url =>
fetch(url, {
method: 'get',
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;',
'User-Agent': `v2rayn/6.42 cmliu/CF-Workers-SUB ${userAgentHeader}`
},
signal: controller.signal // 将AbortController的信号量添加到fetch请求中,以便于需要时可以取消请求
}).then(response => {
if (response.ok) {
return response.text().then(content => {
// 这里可以顺便做内容检查
if (content.includes('dns') && content.includes('proxies') && content.includes('proxy-groups') && content.includes('rules')) {
//console.log("clashsub: " + url);
sublinks += "|" + url;
} else if (content.includes('dns') && content.includes('outbounds') && content.includes('inbounds')){
//console.log("singboxsub: " + url);
sublinks += "|" + url;
} else {
return content; // 保证链式调用中的下一个then可以接收到文本内容
}
});
} else {
return ""; // 如果response.ok为false,返回空字符串
}
})
));
//console.log(responses);
for (const response of responses) {
if (response.status === 'fulfilled') {
const content = await response.value;
req_data += base64Decode(content) + '\n';
}
}
} catch (error) {
//console.error(error);
} finally {
// 无论成功或失败,最后都清除设置的超时定时器
clearTimeout(timeout);
}
//修复中文错误
const utf8Encoder = new TextEncoder();
const encodedData = utf8Encoder.encode(req_data);
const text = String.fromCharCode.apply(null, encodedData);
//去重
const uniqueLines = new Set(text.split('\n'));
const result = [...uniqueLines].join('\n');
//console.log(result);
const base64Data = btoa(result);
//console.log(base64Data);
//console.log("自建节点: " + MainData,"订阅链接: " + urls,"转换链接: " + sublinks);
let target = "v2ray";
if (userAgent.includes('clash') && !userAgent.includes('nekobox')) {
target = "clash";
} else if (userAgent.includes('sing-box') || userAgent.includes('singbox')) {
target = "singbox";
} else {
return new Response(base64Data ,{
headers: {
"content-type": "text/plain; charset=utf-8",
"Profile-Update-Interval": `${SUBUpdateTime}`,
}
});
}
const subconverterUrl = `https://${subconverter}/sub?target=${target}&url=${encodeURIComponent(sublinks)}&insert=false&config=${encodeURIComponent(subconfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`;
try {
const subconverterResponse = await fetch(subconverterUrl);
if (!subconverterResponse.ok) {
throw new Error(`Error fetching subconverterUrl: ${subconverterResponse.status} ${subconverterResponse.statusText}`);
}
const subconverterContent = await subconverterResponse.text();
return new Response(subconverterContent ,{
headers: {
"Content-Disposition": `attachment; filename*=utf-8''${encodeURIComponent(FileName)}; filename=${FileName}`,
"content-type": "text/plain; charset=utf-8",
"Profile-Update-Interval": `${SUBUpdateTime}`,
}
});
} catch (error) {
return new Response(`Error: ${error.message}`, {
status: 500,
headers: { 'content-type': 'text/plain; charset=utf-8' },
});
}
}
};
async function sendMessage(type, ip, add_data = "") {
if ( BotToken !== '' && ChatID !== ''){
let msg = "";
const response = await fetch(`http://ip-api.com/json/${ip}?lang=zh-CN`);
if (response.status == 200) {
const ipInfo = await response.json();
msg = `${type}\nIP: ${ip}\n国家: ${ipInfo.country}\n<tg-spoiler>城市: ${ipInfo.city}\n组织: ${ipInfo.org}\nASN: ${ipInfo.as}\n${add_data}`;
} else {
msg = `${type}\nIP: ${ip}\n<tg-spoiler>${add_data}`;
}
let url = "https://api.telegram.org/bot"+ BotToken +"/sendMessage?chat_id=" + ChatID + "&parse_mode=HTML&text=" + encodeURIComponent(msg);
return fetch(url, {
method: 'get',
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;',
'Accept-Encoding': 'gzip, deflate, br',
'User-Agent': 'Mozilla/5.0 Chrome/90.0.4430.72'
}
});
}
}
// 将 base64 编码的字符串转换为 utf-8 编码的字符
function base64Decode(str) {
const bytes = new Uint8Array(atob(str).split('').map(c => c.charCodeAt(0)));
const decoder = new TextDecoder('utf-8');
return decoder.decode(bytes);
}
async function ADD(envadd) {
var addtext = envadd.replace(/[ "'|\r\n]+/g, ',').replace(/,+/g, ','); // 将空格、双引号、单引号和换行符替换为逗号
//console.log(addtext);
if (addtext.charAt(0) == ',') addtext = addtext.slice(1);
if (addtext.charAt(addtext.length -1) == ',') addtext = addtext.slice(0, addtext.length - 1);
const add = addtext.split(',');
//console.log(add);
return add ;
}