├── .gitignore ├── LICENSE ├── README.md ├── config.example.js ├── index.js ├── package.json ├── ui.js └── wrangler.example.toml /.gitignore: -------------------------------------------------------------------------------- 1 | # Special 2 | config.js 3 | package-lock.json 4 | wrangler.toml 5 | worker/ 6 | 7 | # Logs 8 | logs 9 | *.log 10 | npm-debug.log* 11 | yarn-debug.log* 12 | yarn-error.log* 13 | lerna-debug.log* 14 | 15 | # Diagnostic reports (https://nodejs.org/api/report.html) 16 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 17 | 18 | # Runtime data 19 | pids 20 | *.pid 21 | *.seed 22 | *.pid.lock 23 | 24 | # Directory for instrumented libs generated by jscoverage/JSCover 25 | lib-cov 26 | 27 | # Coverage directory used by tools like istanbul 28 | coverage 29 | *.lcov 30 | 31 | # nyc test coverage 32 | .nyc_output 33 | 34 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 35 | .grunt 36 | 37 | # Bower dependency directory (https://bower.io/) 38 | bower_components 39 | 40 | # node-waf configuration 41 | .lock-wscript 42 | 43 | # Compiled binary addons (https://nodejs.org/api/addons.html) 44 | build/Release 45 | 46 | # Dependency directories 47 | node_modules/ 48 | jspm_packages/ 49 | 50 | # TypeScript v1 declaration files 51 | typings/ 52 | 53 | # TypeScript cache 54 | *.tsbuildinfo 55 | 56 | # Optional npm cache directory 57 | .npm 58 | 59 | # Optional eslint cache 60 | .eslintcache 61 | 62 | # Microbundle cache 63 | .rpt2_cache/ 64 | .rts2_cache_cjs/ 65 | .rts2_cache_es/ 66 | .rts2_cache_umd/ 67 | 68 | # Optional REPL history 69 | .node_repl_history 70 | 71 | # Output of 'npm pack' 72 | *.tgz 73 | 74 | # Yarn Integrity file 75 | .yarn-integrity 76 | 77 | # dotenv environment variables file 78 | .env 79 | .env.test 80 | 81 | # parcel-bundler cache (https://parceljs.org/) 82 | .cache 83 | 84 | # Next.js build output 85 | .next 86 | 87 | # Nuxt.js build / generate output 88 | .nuxt 89 | dist 90 | 91 | # Gatsby files 92 | .cache/ 93 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 94 | # https://nextjs.org/blog/next-9-1#public-directory-support 95 | # public 96 | 97 | # vuepress build output 98 | .vuepress/dist 99 | 100 | # Serverless directories 101 | .serverless/ 102 | 103 | # FuseBox cache 104 | .fusebox/ 105 | 106 | # DynamoDB Local files 107 | .dynamodb/ 108 | 109 | # TernJS port file 110 | .tern-port 111 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 iBug ♦ 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cloudflare Worker for GitHub Releases 2 | 3 | Build a serverless download site with GitHub Releases and Cloudflare Workers 4 | 5 | ## Features 6 | 7 | - Based on GitHub Releases, so no total size limit or bandwidth limit. 8 | - GitHub Releases limits size of single files to 2 GB each 9 | - Custom domain with Cloudflare Workers 10 | - One level of directory structure is supported via different release tags. 11 | - Minimalist UI with Bootstrap and Font Awesome 12 | 13 | Preview: 14 | 15 |  16 | 17 | ## Setup 18 | 19 | ### Install Wrangler 20 | 21 | See [Cloudflare's documentation](https://developers.cloudflare.com/workers/wrangler/install-and-update/) for more information. 22 | 23 | ### `wrangler.toml` 24 | 25 | Copy `wrangler.example.toml` to `wrangler.toml` and fill in your own information into the variables. Refer to [Cloudflare's documentation](https://developers.cloudflare.com/workers/wrangler/configuration/) for more information. 26 | 27 | ### `config.js` 28 | 29 | Copy `config.example.js` to `config.js` and fill in your own information as guided. 30 | 31 | ## License 32 | 33 | The MIT License 34 | -------------------------------------------------------------------------------- /config.example.js: -------------------------------------------------------------------------------- 1 | // Your domain, e.g. my.example.com 2 | const DOMAIN = undefined; 3 | 4 | // The repository in which you're providing download files 5 | const REPOSITORY = "octocat/hello-world"; 6 | 7 | // The default tag if not specified 8 | const DEFAULT_TAG = "default"; 9 | 10 | // Give your site a lovely name 11 | const SITE_NAME = "My GitHub bucket"; 12 | 13 | // Any extra
content you want. CSS, favicons are all welcome! 14 | const HEAD = ``; 15 | 16 | // Don't touch this line 17 | export {DOMAIN, REPOSITORY, DEFAULT_TAG, SITE_NAME, HEAD}; 18 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import { DOMAIN, REPOSITORY, DEFAULT_TAG, SITE_NAME } from "./config"; 2 | import { listFilesHTML, listReleasesHTML, createHTMLResponse } from "./ui"; 3 | 4 | async function handleFetch(request) { 5 | let url = new URL(request.url); 6 | if (typeof DOMAIN !== "undefined" && url.hostname !== DOMAIN) { 7 | return createHTMLResponse(400, "Bad Request"); 8 | } 9 | if (url.pathname === "/robots.txt") { 10 | return new Response("User-Agent: *\nDisallow: /\n", { status: 200, headers: { "Content-Type": "text/plain" }}) 11 | } 12 | 13 | let newUrl, tag, filename; 14 | let pathParts = url.pathname.split("/"); 15 | if (pathParts.length === 2) { 16 | if (pathParts[1] === "") { 17 | // Front page - list available releases 18 | let apiUrl = `https://api.github.com/repos/${REPOSITORY}/releases`; 19 | console.log(apiUrl); 20 | let response = await fetch(apiUrl, { headers: { "User-Agent": `Repository ${REPOSITORY}` } }); 21 | if (response.status !== 200) { 22 | console.log(response.status); 23 | console.log(response.body.read()); 24 | return createHTMLResponse(503, "Unavailable"); 25 | } 26 | let data = await response.json(); 27 | let respHeaders = new Headers({ "Content-Type": "text/html" }); 28 | for (let p of response.headers) { 29 | if (p[0].toLowerCase().startsWith("x-ratelimit-")) { 30 | respHeaders.set(p[0], p[1]); 31 | } 32 | } 33 | return new Response(listReleasesHTML(data), { status: 200, headers: respHeaders }); 34 | } 35 | 36 | // One slash - load file from DEFAULT_TAG 37 | tag = DEFAULT_TAG; 38 | filename = pathParts[1]; 39 | } else if (pathParts.length === 3) { 40 | // Two slashes 41 | tag = pathParts[1]; 42 | if (pathParts[2] === "") { 43 | // Fetch GitHub API and list files 44 | let apiUrl = `https://api.github.com/repos/${REPOSITORY}/releases/tags/${tag}`; 45 | console.log(apiUrl); 46 | let response = await fetch(apiUrl, { headers: { "User-Agent": `Repository ${REPOSITORY}` } }); 47 | if (response.status !== 200) { 48 | console.log(response.status); 49 | console.log(response.body.read()); 50 | return createHTMLResponse(503, "Unavailable"); 51 | } 52 | let data = await response.json(); 53 | if (request.method === "POST") { 54 | // Return the upload URL in JSON 55 | response = { upload_url: data["upload_url"].split("{")[0] }; 56 | return new Response(JSON.stringify(response), { 57 | status: 200, 58 | headers: { "Content-Type": "application/json" }, 59 | }); 60 | } 61 | let respHeaders = new Headers({ "Content-Type": "text/html" }); 62 | for (let p of response.headers) { 63 | if (p[0].toLowerCase().startsWith("x-ratelimit-")) { 64 | respHeaders.set(p[0], p[1]); 65 | } 66 | } 67 | return new Response(listFilesHTML(REPOSITORY, data), { status: 200, headers: respHeaders }); 68 | } 69 | filename = pathParts[pathParts.length - 1]; 70 | } else { 71 | return createHTMLResponse(400, "Bad Request"); 72 | } 73 | 74 | // Default action: Download file 75 | newUrl = `https://github.com/${REPOSITORY}/releases/download/${tag}/${filename}`; 76 | let response = await fetch(newUrl, { method: request.method }); 77 | if (response.status !== 200) { 78 | return createHTMLResponse(404, "Not Found"); 79 | } 80 | let { readable, writable } = new TransformStream(); 81 | return new Response(response.body, response); 82 | } 83 | 84 | export default { 85 | fetch: handleFetch, 86 | }; 87 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cf-github-releases", 3 | "version": "1.0.0", 4 | "description": "Serverless download site from GitHub Releases with Cloudflare Workers", 5 | "homepage": "https://github.com/iBug/cf-github-releases", 6 | "repository": "github:iBug/cf-github-releases", 7 | "main": "index.js", 8 | "author": "iBug ", 9 | "license": "MIT", 10 | "scripts": { 11 | "deploy": "wrangler deploy" 12 | }, 13 | "dependencies": { 14 | "wrangler": "^3.80.3" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ui.js: -------------------------------------------------------------------------------- 1 | import { SITE_NAME, HEAD, DEFAULT_TAG } from "./config"; 2 | 3 | function formatDate(timestamp) { 4 | return new Date(timestamp).toISOString().replace("T", " ").split(".")[0]; 5 | } 6 | 7 | // Credits: https://stackoverflow.com/a/14919494/5958455 8 | function humanFileSize(bytes, si = false, dp = 1) { 9 | const thresh = si ? 1000 : 1024; 10 | if (Math.abs(bytes) < thresh) { 11 | return bytes + " B"; 12 | } 13 | const units = si 14 | ? ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] 15 | : ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]; 16 | let u = -1; 17 | const r = 10 ** dp; 18 | do { 19 | bytes /= thresh; 20 | u++; 21 | } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1); 22 | return bytes.toFixed(dp) + " " + units[u]; 23 | } 24 | 25 | function getItemIcon(basename) { 26 | let icon; 27 | if (basename === "$folder") { 28 | icon = "folder-open"; 29 | } else if (basename === "$folderDefault") { 30 | icon = "box-open"; 31 | } else if (/\.(jpe?g|png|bmp|tiff?|gif|webp|tga|cr2|nef|ico)$/i.test(basename)) { 32 | icon = "file-image"; 33 | } else if (/\.(md|markdown|txt|ini|conf|cfg|pub)$/i.test(basename)) { 34 | icon = "file-alt"; 35 | } else if (/\.(mp4|mkv|wmv|flv|hls|ogv|avi)$/i.test(basename)) { 36 | icon = "file-video"; 37 | } else if (/\.(mp3|wav|wma|flac|ogg|aac|m4a)$/i.test(basename)) { 38 | icon = "file-audio"; 39 | } else if (/\.(zip|tgz|gz|tar|7z|rar|xz|bz2)$/i.test(basename)) { 40 | icon = "file-archive"; 41 | } else if (/\.(docx?)$/i.test(basename)) { 42 | icon = "file-word"; 43 | } else if (/\.(xlsx?)$/i.test(basename)) { 44 | icon = "file-excel"; 45 | } else if (/\.(pp[st]x?)$/i.test(basename)) { 46 | icon = "file-powerpoint"; 47 | } else if (/\.(pdf)$/i.test(basename)) { 48 | icon = "file-pdf"; 49 | } else if (/\.([ch](?:pp)?|html|css|js|json)$/i.test(basename)) { 50 | icon = "file-code"; 51 | } else if (/\.(csv)$/i.test(basename)) { 52 | icon = "file-csv"; 53 | } else if (/\.(sig|asc)$/i.test(basename)) { 54 | icon = "file-signature"; 55 | } else if (/\.(exe)$/i.test(basename)) { 56 | icon = "window-maximize"; 57 | } else { 58 | icon = "file"; 59 | } 60 | 61 | return makeIconHTML(`fas fa-lg fa-fw fa-${icon}`); 62 | } 63 | 64 | const makeIconHTML = (classes) => ``; 65 | 66 | export function listFilesHTML(repository, data) { 67 | let description = "", 68 | tbody = "", 69 | tag = data["tag_name"], 70 | displayName = data["name"]; 71 | 72 | if (data["body"]) { 73 | // render Markdown? 74 | description = `${data["body"]}
`; 75 | } 76 | 77 | let assets = data["assets"]; 78 | const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }); 79 | assets.sort((a, b) => collator.compare(a["name"], b["name"])); 80 | 81 | for (let item of assets) { 82 | let name = item["name"]; 83 | let size = item["size"]; 84 | let sizeHuman = humanFileSize(size); 85 | let sizeActual = size.toLocaleString() + (size === 1 ? " byte" : " bytes"); 86 | let updated = formatDate(item["updated_at"]); 87 | let download_count = item["download_count"]; 88 | tbody += `File | Size | Updated | Downloaded |
---|---|---|---|
109 | ${makeIconHTML("fas fa-lg fa-fw fa-level-up-alt")} Parent directory 110 | | 111 | ${makeIconHTML("fas fa-fw fa-edit")} Edit on GitHub 112 | |
Release | Name | Created |
---|