Last active
January 27, 2023 03:43
-
-
Save LostLuma/c8b9f3804fe5e1b7f7dc3c9b5155450c to your computer and use it in GitHub Desktop.
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
/* | |
MIT License | |
Copyright (c) 2020 - 2023 Lilly Rose Berner | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
*/ | |
// Cloudflare Worker acting as a reverse proxy to a B2 Cloud Storage Bucket | |
// In order to use this worker copy the file and change the constants below | |
// Name of the B2 bucket to proxy | |
const BUCKET = "lostluma-public"; | |
// If you're not sure what your cluster ID is follow these steps: | |
// - Upload a file to your bucket | |
// - Click on it in the browse files menu | |
// - Look for the friendly URL in the displayed information, copy the subdomain | |
const CLUSTER_ID = "f002"; | |
// When using a private B2 bucket create a new application key and set it here | |
// For better performance add a daily cron trigger, it will refresh download token | |
const KEY_ID = "002f18dda8a3068000000001b"; | |
const APPLICATION_KEY = "K002gD12ar1t7Kx7623tJggw1NwaFXAa"; | |
// Image location to use as a favicon | |
const FAVICON = "https://files.lostluma.net/RTAhCG.svg"; | |
// Default Cache-Control header to set, unless overridden by file info | |
const CACHE_CONTROL = "public, max-age=31536000, immutable"; | |
class HTTPError extends Error { | |
constructor(status, message) { | |
super(message); | |
this.status = status; | |
} | |
} | |
async function getFile(path, event) { | |
// Empty filenames are not valid | |
if (path === "/") { | |
throw new HTTPError(404, "File not found."); | |
} | |
const headers = { | |
"Authorization": await getAuthorizationToken(event), | |
} | |
const url = `https://${CLUSTER_ID}.backblazeb2.com/file/${BUCKET}${path}`; | |
for (let x = 0; x <= 5; x++) { | |
let resp = await fetch(url, { headers }); | |
if (resp.ok) { | |
return resp; | |
} | |
if (resp.status === 404) { | |
throw new HTTPError(404, "File not found."); | |
} | |
} | |
throw new HTTPError(502, "Service unavailable."); | |
} | |
function keepHeader(name, placeholder = null) { | |
function passthrough(value) { | |
if (value) { | |
return [name, value]; | |
} else if (placeholder) { | |
return [name, placeholder]; | |
} | |
} | |
return passthrough; | |
} | |
function lastModified(value) { | |
if (value) { | |
const ms = Number(value); | |
return ["last-modified", new Date(ms).toUTCString()]; | |
} | |
} | |
const HEADERS = { | |
// Passthrough | |
"content-type": keepHeader("content-type"), | |
"content-length": keepHeader("content-length"), | |
"content-disposition": keepHeader("content-disposition"), | |
// Passthrough or default | |
"cache-control": keepHeader("cache-control", CACHE_CONTROL), | |
// Alter header format conditionally | |
"x-bz-info-src_last_modified_millis": lastModified, | |
}; | |
function transformHeaders(response) { | |
const headers = new Headers(); | |
for (const [name, value] of response.headers.entries()) { | |
if (!Object.hasOwn(HEADERS, name) && name.startsWith("x-bz-info")) { | |
headers.set(name.slice(10), value); // Custom value set during upload | |
} | |
} | |
for (const [source, transform] of Object.entries(HEADERS)) { | |
const result = transform(response.headers.get(source)); | |
if (result) { | |
headers.set(...result); // Generic header or transformed custom value | |
} | |
} | |
return new Response(response.body, { headers, status: response.status }); | |
} | |
function shouldCache(response) { | |
const contentLength = response.headers.get("Content-Length"); | |
if (contentLength) { | |
// Cache responses with less than 64MiB of content | |
return Number(contentLength) < 1024 ** 2 * 64; | |
} | |
} | |
async function handleRequest(event) { | |
let cache = caches.default; | |
const request = event.request; | |
let response = await cache.match(request); | |
if (!response) { | |
const { method, url } = request; | |
const path = new URL(url).pathname; | |
if (method !== "GET") { | |
throw new HTTPError(405, "Method not supported."); | |
} | |
if (path === "/favicon.ico") { | |
response = Response.redirect(FAVICON, 301); | |
} else { | |
response = await getFile(path, event); | |
response = transformHeaders(response); | |
response.headers.set("CF-Cache-Status", "MISS"); | |
} | |
if (shouldCache(response)) { | |
event.waitUntil(cache.put(request, response.clone())); | |
} | |
} | |
return response; | |
} | |
async function handleFetch(event) { | |
try { | |
return await handleRequest(event); | |
} catch (e) { | |
if (!(e instanceof HTTPError)) { | |
throw e; | |
} | |
const headers = { | |
"Cache-Control": "no-cache", | |
"Content-Type": "text/plain; charset=UTF-8", | |
}; | |
return new Response(e.message, { headers, status: e.status }); | |
} | |
} | |
addEventListener("fetch", (event) => { | |
event.respondWith(handleFetch(event)); | |
}); | |
async function handleScheduled(event) { | |
await getAuthorizationToken(event, true); // Refresh auth token to ensure it exists once a request comes in | |
} | |
async function getAuthorizationToken(event, force) { | |
// TODO: POP local cache | |
let token = await STORAGE.get("authorization-token"); | |
if (!token || force) { | |
token = await fetchAuthorizationToken(); | |
event.waitUntil(STORAGE.put("authorization-token", token, { expirationTtl: 86400 })); | |
} | |
return token | |
} | |
async function fetchAuthorizationToken() { | |
const headers = { | |
"Authorization": "Basic " + btoa(`${KEY_ID}:${APPLICATION_KEY}`), | |
} | |
let resp; | |
for (let x = 0; x <= 5; x++) { | |
resp = await fetch("https://api.backblazeb2.com/b2api/v2/b2_authorize_account", { headers }); | |
if (resp.ok) { | |
break; | |
} | |
if (resp.status == 401) { | |
throw new HTTPError(401, "Invalid B2 credentials provided."); | |
} | |
} | |
if (!resp || !resp.ok) { | |
throw new HTTPError(502, "Service unavailable."); | |
} | |
const data = await resp.json(); | |
return data["authorizationToken"]; | |
} | |
addEventListener("scheduled", (event) => { | |
event.waitUntil(handleScheduled(event)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment