Skip to content

Instantly share code, notes, and snippets.

@BruceZhang1993
Created January 4, 2025 02:05
Show Gist options
  • Save BruceZhang1993/ce1e5409764bb1a0d3c51a699e6f719d to your computer and use it in GitHub Desktop.
Save BruceZhang1993/ce1e5409764bb1a0d3c51a699e6f719d to your computer and use it in GitHub Desktop.
Cloudflare Worker to access private repo assets
import welcome from "welcome.html";
/**
* @typedef {Object} Env
*/
export default {
/**
* @param {Request} request
* @param {Env} env
* @param {ExecutionContext} ctx
* @returns {Promise<Response>}
*/
async fetch(request, env, ctx) {
let url = new URL(request.url)
let token = url.searchParams.get("token")
if (token == null || token == '') {
return new Response("missing token");
}
const releaseApi = "https://api.github.com/repos/BruceZhang1993/MihomoConfigGenerator/releases/tags/pre-release"
let response = await fetch(releaseApi, { headers: { 'Authorization': 'token ' + token, "User-Agent": "Cloudflare" } })
const { _, result } = await gatherResponse(response);
if (result.assets == null || result.assets.length == 0) {
return new Response("missing assets");
}
let assetId = result.assets[0].id
let assetApi = "https://api.github.com/repos/BruceZhang1993/MihomoConfigGenerator/releases/assets/" + assetId
let assetResp = await fetch(assetApi, { headers: { 'Authorization': 'token ' + token, "User-Agent": "Cloudflare", "Accept": "application/octet-stream" } })
return new Response(await assetResp.text(), { 'headers': { 'Content-Type': 'text/yaml' } });
},
};
async function gatherResponse(response) {
const { headers } = response;
const contentType = headers.get("content-type") || "";
if (contentType.includes("application/json")) {
return { contentType, result: await response.json() };
}
return { contentType, result: await response.text() };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment