Skip to content

Instantly share code, notes, and snippets.

@insanity54
Created January 28, 2024 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save insanity54/360a9df30943f554e8d040beaf6f0e37 to your computer and use it in GitHub Desktop.
Save insanity54/360a9df30943f554e8d040beaf6f0e37 to your computer and use it in GitHub Desktop.
A method for signing BunnyCDN URLS using Token Authentication
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