-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
image-proxy.js
105 lines (95 loc) · 2.81 KB
/
image-proxy.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
addEventListener("fetch", async (event) => {
event.respondWith(handleRequest(event.request));
});
const errorResponse = (errorMessage) =>
new Response(errorMessage, {
status: 400,
statusText: "Bad Request",
});
const handleRequest = async (originalRequest) => {
if (originalRequest.headers.get("referrer")) {
return new Response("Forbidden", {
status: 403,
statusText: "Forbidden",
});
}
let originalURL = new URL(originalRequest.url);
if (!originalURL.searchParams.get("url")) {
return errorResponse("Error: Cannot get url from param");
}
let imageURL = null;
try {
imageURL = new URL(originalURL.searchParams.get("url"));
} catch (e) {}
if (!imageURL) {
return errorResponse("Error: Invalid URL string");
}
let imageRequest = new Request(imageURL, {
redirect: "follow",
headers: {
referer: imageURL.origin,
},
});
let response = await fetch(imageRequest, {
cf: {
polish: "lossy",
},
});
if (response.status >= 400) {
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
}
if (
response.headers.get("Content-Type").toLowerCase() !== "application/octet-stream" &&
!["image", "video"].includes(response.headers.get("Content-Type").split("/")[0].toLowerCase())
) {
// retry as bot to get og:image
let webResponse = await fetch(
new Request(imageURL, {
redirect: "follow",
headers: {
referer: imageURL.origin,
"User-Agent": "googlebot",
},
}),
);
if (response.status === 200) {
const ogImageURL = (await webResponse.text())
?.match(/<[^<]+?"og:image".*?>/, "$1")?.[0]
?.match(/content="(.*?)"/, "$1")?.[1];
if (ogImageURL && ogImageURL.match(/^https?:\/\//)) {
response = await fetch(
new Request(ogImageURL, {
redirect: "follow",
headers: {
referer: imageURL.origin,
},
}),
);
if (response.status >= 400) {
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
}
}
}
}
if (
response.headers.get("Content-Type").toLowerCase() !== "application/octet-stream" &&
!["image", "video"].includes(response.headers.get("Content-Type").split("/")[0].toLowerCase())
) {
return errorResponse("Error: Content-Type is not image or video or application/octet-stream");
}
const res = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
res.headers.set("Access-Control-Allow-Origin", "https://trace.moe");
return res;
};