-
Notifications
You must be signed in to change notification settings - Fork 1
Adds Backblaze B2 proxy function for Cloudflare workers #11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lukestanley
wants to merge
4
commits into
master
Choose a base branch
from
b2_s3_like_proxy
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
dd8c0b5
Adds Backblaze B2 proxy function for Cloudflare workers
lukestanley 294f6b5
Renames B2 proxy filename, improves comments, provides more clear HTT…
lukestanley 35945c4
B2 proxy: Improve readability of URL construction
lukestanley ac9ec85
B2 proxy: Fetch logic error handling
lukestanley File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| This directory has self contained proxy functions, including a proxy for Backblaze's B2 service. | ||
| They can be ran as isolated Cloudflare Workers. |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| /** | ||
| * Worker script to proxy requests to Backblaze B2 with CORS | ||
| * headers and key from environment variables, to sign URLs. | ||
| * Compatible with Cloudflare Workers. | ||
| * See https://developers.cloudflare.com/workers/ | ||
| */ | ||
|
|
||
| const handleFetchError = (error, message, corsHeaders) => { | ||
| console.error(`${message}: ${error.message}`); | ||
| return new Response(`${message}`, { | ||
| status: 500, | ||
| headers: corsHeaders | ||
| }); | ||
| }; | ||
|
|
||
| const safeFetch = async (url, options, errorMessage, corsHeaders) => { | ||
| try { | ||
| const response = await fetch(url, options); | ||
| if (!response.ok) { | ||
| console.error(`${errorMessage} failed with status: ${response.status}`); | ||
| throw new Error(`HTTP error! status: ${response.status}`); | ||
| } | ||
| return response; | ||
| } catch (error) { | ||
| throw new Error(`${errorMessage}: ${error.message}`); | ||
| } | ||
| }; | ||
|
|
||
| export default { | ||
| async fetch(request, env, ctx) { | ||
| const corsHeaders = { | ||
| 'Access-Control-Allow-Origin': 'https://app.kendra.io', | ||
| 'Access-Control-Allow-Methods': 'GET, OPTIONS', | ||
| 'Access-Control-Allow-Headers': 'Content-Type', | ||
| }; | ||
|
|
||
| // Handle OPTIONS request | ||
| if (request.method === 'OPTIONS') { | ||
| return new Response(null, { headers: corsHeaders }); | ||
| } | ||
|
|
||
| const url = new URL(request.url); | ||
|
|
||
| // Return response if no path is specified | ||
| if (url.pathname === "/" || !url.pathname) { | ||
| return new Response("The proxy server is active. This is the root path. Note: To access a file resource, append the filename to the path.", { | ||
| headers: { | ||
| "content-type": "text/plain", | ||
| ...corsHeaders | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| const fileName = url.pathname.split("/").pop(); | ||
|
|
||
| // Get configuration from environment variables | ||
| const B2_APPLICATION_KEY_ID = env.B2_APPLICATION_KEY_ID; | ||
| const B2_APPLICATION_KEY = env.B2_APPLICATION_KEY; | ||
| const B2_BUCKET_ID = env.B2_BUCKET_ID; | ||
| const B2_BUCKET_NAME = env.B2_BUCKET_NAME; | ||
|
|
||
| console.log(`Processing request for file: ${fileName}`); | ||
| console.log(`Using bucket: ${B2_BUCKET_NAME} (${B2_BUCKET_ID})`); | ||
|
|
||
| try { | ||
| // Step 1: Authorise with Backblaze B2 | ||
| const authResponse = await safeFetch( | ||
| 'https://api.backblazeb2.com/b2api/v2/b2_authorize_account', | ||
| { | ||
| headers: { | ||
| Authorization: 'Basic ' + btoa(B2_APPLICATION_KEY_ID + ':' + B2_APPLICATION_KEY), | ||
| } | ||
| }, | ||
| 'B2 authorization', | ||
| corsHeaders | ||
| ); | ||
| console.log('B2 authorisation successful'); | ||
|
|
||
| const authData = await authResponse.json(); | ||
| const apiUrl = authData.apiUrl; | ||
|
|
||
| // Step 2: Get Download Authorisation | ||
| const downloadAuthorisation = await safeFetch( | ||
| `${apiUrl}/b2api/v2/b2_get_download_authorization`, | ||
| { | ||
| method: 'POST', | ||
| headers: { | ||
| Authorization: authData.authorizationToken, | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| body: JSON.stringify({ | ||
| bucketId: B2_BUCKET_ID, | ||
| fileNamePrefix: fileName, | ||
| validDurationInSeconds: 360000, | ||
| }), | ||
| }, | ||
| 'Download authorization', | ||
| corsHeaders | ||
| ); | ||
| console.log('Download authorisation successful'); | ||
|
|
||
| const signedUrlData = await downloadAuthorisation.json(); | ||
|
|
||
| const b2DownloadEndpoint = authData.downloadUrl; | ||
| const downloadAuthToken = signedUrlData.authorizationToken; | ||
| const downloadUrl = `${b2DownloadEndpoint}/file/${B2_BUCKET_NAME}/${fileName}?Authorization=${downloadAuthToken}`; | ||
|
|
||
| // Step 3: Fetch the content from signed URL | ||
| console.log(`Fetching content from signed URL for: ${fileName}`); | ||
| const fileResponse = await safeFetch( | ||
| downloadUrl, | ||
| {}, | ||
| 'File content fetch', | ||
| corsHeaders | ||
| ); | ||
|
|
||
| // Return the file content with original headers plus CORS | ||
| const responseHeaders = new Headers(fileResponse.headers); | ||
| Object.entries(corsHeaders).forEach(([key, value]) => { | ||
| responseHeaders.set(key, value); | ||
| }); | ||
|
|
||
| return new Response(fileResponse.body, { | ||
| status: 200, | ||
| headers: responseHeaders | ||
| }); | ||
|
|
||
| } catch (error) { | ||
| return handleFetchError(error, error.message || 'Error processing request', corsHeaders); | ||
| } | ||
| } | ||
| }; | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤩