Repository navigation
Expand file tree
/
Copy pathimage-proxy.js
More file actions
197 lines (175 loc) · 5.22 KB
/
Copy pathimage-proxy.js
File metadata and controls
197 lines (175 loc) · 5.22 KB
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
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 {}
if (!imageURL) {
return errorResponse("Error: Invalid URL string");
}
if (imageURL.protocol !== "http:" && imageURL.protocol !== "https:") {
return errorResponse("Error: Protocol must be http or https");
}
if (isPrivateIP(imageURL.hostname)) {
return errorResponse("Error: Forbidden URL");
}
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,
});
}
const contentType = (response.headers.get("Content-Type") || "").toLowerCase();
if (
contentType !== "application/octet-stream" &&
!["image", "video"].includes(contentType.split("/")[0])
) {
// 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 getOgImageFromStream(webResponse);
if (ogImageURL && ogImageURL.match(/^https?:\/\//)) {
let ogParsedURL;
try {
ogParsedURL = new URL(ogImageURL);
} catch {}
if (!ogParsedURL || isPrivateIP(ogParsedURL.hostname)) {
return errorResponse("Error: Forbidden URL in og:image");
}
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,
});
}
}
}
}
const finalContentType = (response.headers.get("Content-Type") || "").toLowerCase();
if (
finalContentType !== "application/octet-stream" &&
!["image", "video"].includes(finalContentType.split("/")[0])
) {
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", "*");
return res;
};
const getOgImageFromStream = async (response) => {
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
let match;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += value;
match = buffer.match(/<(?=[^<]*?"og:image")[^<]*?content="([^"]*?)"[^<]*?>/);
if (match) break;
if (buffer.length > 65536) break;
}
} catch {
} finally {
reader.cancel();
}
return match?.[1];
};
const isPrivateIP = (hostname) => {
if (hostname === "localhost") return true;
// IPv4
// Check for Hex/Octal/Integer formats that are not standard dotted quad
if (hostname.match(/^0x[0-9a-f]+$/i)) return true;
// If it looks like an IPv4 (digits and dots), enforce strictness
if (hostname.match(/^[\d.]+$/)) {
const parts = hostname.split(".");
if (parts.length !== 4) return true; // Block non-4-part IPs (int, short, etc)
// Block leading zeros (octal)
if (parts.some((p) => p.length > 1 && p.startsWith("0"))) return true;
const [a, b] = parts.map(Number);
// 127.0.0.0/8 (Loopback)
// 10.0.0.0/8 (Private)
// 172.16.0.0/12 (Private)
// 192.168.0.0/16 (Private)
// 169.254.0.0/16 (Link-local)
// 0.0.0.0/8 (Current network)
if (
a === 127 ||
a === 10 ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168) ||
(a === 169 && b === 254) ||
a === 0
) {
return true;
}
return false;
}
// IPv6
if (hostname.includes(":")) {
const ipv6 = hostname.replace(/^\[|\]$/g, "").toLowerCase();
// :: (Unspecified)
// ::1 (Loopback)
// fc00::/7 (Unique Local)
// fe80::/10 (Link-local)
if (ipv6 === "::" || ipv6 === "::1" || ipv6.match(/^f[cd]/) || ipv6.match(/^fe[89ab]/))
return true;
// Block IPv4 mapped
if (ipv6.startsWith("::ffff:")) return true;
if (ipv6.includes(".")) return true;
}
return false;
};
export { errorResponse, getOgImageFromStream, handleRequest, isPrivateIP };
export default {
async fetch(request) {
return handleRequest(request);
},
};