0%

使用 Workers 制作订阅链接并追踪访客 IP

在多个设备使用同一套代理方案时,如果遇到代理配置需要更新,每一个客户端手动修改会非常麻烦,这种情况下,创建订阅链接是很有必要的。
为了方便更新订阅信息,所以选择使用 Cloudflare Workers 来制作订阅链接。

以下代码由 ChatGPT 协助完成:

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
// 默认节点信息
const MainData = `
ss://[email protected]:443#example1
ss://[email protected]:443#example2
`

addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) })

async function handleRequest(request) {
const url_tag = new URL(request.url).searchParams.get('user_tag');
let req_data = "";
if (url_tag) { // 判断 user_tag 参数
switch (url_tag) {
case 'MuxData': // 从其他订阅取得数据,和默认节点合成后返回给客户端
const response = await fetch('https://example.com');
if (response.ok) {
const content = await response.text();
req_data = MainData + atob(content);
break;
}
default: // 如果未匹配选择条件,则只返回默认节点
req_data = MainData;
break;
}
} else { // 如果未找到 user_tag 参数,则随机生成一些无意义数据
const bytes = new Uint8Array(Math.floor(Math.random() * 100));
crypto.getRandomValues(bytes);
req_data = String.fromCharCode.apply(null, bytes);
}
// 传递访问者 IP 到 sendMessage 函数,用于发送通知
await sendMessage("#Update", request.headers.get('CF-Connecting-IP'), `User_Tag: ${url_tag}`);
return new Response(btoa(req_data)); // 将数据 base64 加密后返回给访问者
}

// 代码参考:https://azhuge233.com/cloudflare-workers-%E8%BD%AC%E5%8F%91-telegram-bot-%E6%8E%A8%E9%80%81%E4%BF%A1%E6%81%AF/
async function sendMessage(type, ip, add_data = "") {
const OPT = {
BotToken: '', // Telegram Bot API
ChatID: '', // User ChatID
}

let msg = "";

const response = await fetch(`http://ip-api.com/json/${ip}`);
if (response.status == 200) { // 查询 IP 来源信息,使用方法参考:https://ip-api.com/docs/api:json
const ipInfo = await response.json();
msg = `${type}\nIP: ${ip}\nCountry: ${ipInfo.country}\nCity: ${ipInfo.city}\n${add_data}`;
} else {
msg = `${type}\nIP: ${ip}\n${add_data}`;
}

let url = "https://api.telegram.org/";
url += "bot" + OPT.BotToken + "/sendMessage?";
url += "chat_id=" + OPT.ChatID + "&";
url += "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'
}
});
}

修改必要的信息后将代码粘贴到 Workers,在客户端把订阅地址设置为 https://Workers_address/?user_tag=MuxData,将会取得 MainDatahttps://example.com 内的节点信息,并通过 tgbot 给指定用户发送一条消息。

关联文章:在订阅中显示 Lightsail 流量使用情况