Last active
October 29, 2023 12:41
-
-
Save vdbelt/d0b6c1e2e48b21ead5acd079b8a92ccd to your computer and use it in GitHub Desktop.
Cloudflare service worker hot link protection with whitelist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
addEventListener('fetch', event => { | |
event.respondWith(fetchAndApply(event.request)) | |
}) | |
/** | |
* If the browser is requesting an image and | |
* the referer does not match your host | |
* we redirect the request to your page | |
*/ | |
async function fetchAndApply(request) { | |
// Fetch the response. | |
let response = await fetch(request) | |
// If it's an image, engage hotlink protection based on the | |
// Referer header. | |
let referer = request.headers.get('Referer') | |
let contentType = response.headers.get('Content-Type') || '' | |
let whitelist = [ 'domain1.com', 'domain2.com' ]; | |
if (referer && contentType.startsWith('image/')) { | |
// It's an image and there's a Referer. Verify that the | |
// hostnames match. | |
if ( | |
new URL(referer).hostname !== new URL(request.url).hostname | |
&& !whitelist.includes(new URL(referer).hostname) | |
) { | |
// Hosts don't match. This is a hotlink. Redirect the | |
// user to our homepage. | |
return new Response('', { | |
status: 302, | |
headers: { | |
'Location': '/' | |
} | |
}) | |
} | |
} | |
// Everything is fine, return the response normally. | |
return response | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment