-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathworker.js
More file actions
65 lines (54 loc) · 1.86 KB
/
worker.js
File metadata and controls
65 lines (54 loc) · 1.86 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
/**
* Cloudflare Worker for Proxying Requests to Target URLs
* Author: SeRaMo ( https://github.com/seramo/ )
*/
const ALLOWED_DOMAINS = [
// 'example.com',
// 'api.example.com',
];
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
// Extract the target URL from the path
const targetUrl = url.pathname.slice(1); // Remove the leading "/" from the path
// Validate URL
let parsedTargetUrl;
try {
parsedTargetUrl = new URL(targetUrl);
} catch (e) {
return new Response('Invalid URL provided.', { status: 400 });
}
// Check allowed domains (if list is not empty)
if (ALLOWED_DOMAINS.length > 0) {
const hostname = parsedTargetUrl.hostname.toLowerCase();
const isAllowed = ALLOWED_DOMAINS.some(d => {
const domain = d.toLowerCase().trim();
if (!domain) return false;
return hostname === domain || hostname.endsWith('.' + domain);
});
if (!isAllowed) {
return new Response('Domain not allowed.', { status: 403 });
}
}
// Clone the incoming request and prepare it for the target URL
const modifiedRequest = new Request(targetUrl + url.search, {
method: request.method,
headers: request.headers,
body: request.body,
redirect: 'follow',
});
try {
// Fetch the target URL
const response = await fetch(modifiedRequest);
// Return the response from the target server
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
} catch (error) {
return new Response('Error fetching the target URL.', { status: 500 });
}
}