-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
92 lines (80 loc) · 2.64 KB
/
index.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
// 验证设置,建议使用CloudFlare的防火墙功能
const allowedIps = ['127.0.0.1']; // 替换为您允许的 IP 地址,建议使用CloudFlare的防火墙功能
const validKey = 'your_secret_key'; // 替换为您允许的密钥,建议使用CloudFlare的防火墙功能
const enableIps = false;
const enableKey = true;
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
if (request.method !== 'POST') {
return new Response(JSON.stringify({
success: false,
error: "Only POST method is allowed"
}), {status: 405});
}
let requestData;
try {
requestData = await request.json();
} catch (error) {
return new Response(JSON.stringify({
success: false,
error: "Invalid JSON"
}), {status: 400});
}
const { key, url: originUrl } = requestData;
if (enableKey) {
if (validKey === 'your_secret_key') {
return new Response(JSON.stringify({
success: false,
error: "Please set a valid key"
}), {status: 403});
}
if (key !== validKey) {
return new Response(JSON.stringify({
success: false,
error: "Unauthorized key"
}), {status: 403});
}
}
if (enableIps) {
// 获取请求 IP 地址
const requestIp = request.headers.get('cf-connecting-ip');
if (!allowedIps.includes(requestIp)) {
return new Response(JSON.stringify({
success: false,
error: "Unauthorized IP"
}), {status: 403});
}
}
if (!originUrl) {
return new Response(JSON.stringify({
success: false,
error: "URL not provided"
}), {status: 400});
}
try {
// 发起请求
const response = await fetch(originUrl);
if (!response.ok) {
return new Response(JSON.stringify({
success: false,
error: "Failed to fetch resource"
}), {status: 502});
}
const newHeaders = new Headers(response.headers);
// 添加 CORS 头部
newHeaders.set('Access-Control-Allow-Origin', '*');
// 返回
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders
});
} catch (error) {
return new Response(JSON.stringify({
success: false,
error: "Error fetching resource"
}), {status: 500});
}
}