Created
January 28, 2024 08:45
-
-
Save insanity54/360a9df30943f554e8d040beaf6f0e37 to your computer and use it in GitHub Desktop.
A method for signing BunnyCDN URLS using Token Authentication
This file contains hidden or 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
import { add } from "npm:date-fns"; | |
/** | |
* references | |
* - https://write.corbpie.com/how-to-do-token-authentication-urls-with-bunnycdn/ | |
* - https://git.sr.ht/~jamesponddotco/bunnysign | |
* - https://bunny.net/blog/were-bringing-token-authentication-to-the-next-level/ | |
* | |
*/ | |
async function signUrl(url: string, securityKey: string): string { | |
const parsedUrl = new URL(url); | |
const expirationDate = add(new Date(), { weeks: 1 }) | |
const hashBase = securityKey + parsedUrl.pathname + expirationDate.getTime(); | |
const data = new TextEncoder().encode(hashBase); | |
const hashBuffer = await crypto.subtle.digest('SHA-256', data); | |
const hashArray = Array.from(new Uint8Array(hashBuffer)); | |
const hash = hashArray.map(byte => String.fromCharCode(byte)).join(''); | |
const b64 = btoa(hash); | |
const formattedToken = b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); | |
return `${url}?token=${formattedToken}&expires=${expirationDate.getTime()}`; | |
} | |
export async function main( | |
url: string, | |
securityKey: string | |
) { | |
if (!url) throw new Error('url arg missing'); | |
if (!securityKey) throw new Error('securityKey arg missing'); | |
return await signUrl(url, securityKey); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment