Forked from vdbelt/cloudflare-hot-link-protection-with-whitelist.js
Last active
October 1, 2019 06:37
-
-
Save judge2020/097c204a04c946d09a2e3f185b1cc961 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' ]; | |
let stub = 'https://i.judge.sh/Rare/5qKPERfA.png'; | |
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. | |
const stubRequest = new Request(stub, { | |
method: 'GET', | |
headers: request.headers | |
}); | |
// create a new request to not return `cache-control: public`. | |
const stubResponse = await fetch(stubRequest); | |
const stubHeaders = new Headers(stubResponse.headers); | |
stubHeaders.set('cache-control', 'private'); | |
return new Response(stubResponse.body, { | |
status: 404, | |
headers: stubHeaders | |
}); | |
} | |
} | |
// 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