| 1 | import { env } from "cloudflare:workers"; |
| 2 | |
| 3 | import type { Route } from "./+types/downloads-runner"; |
| 4 | |
| 5 | /** |
| 6 | * Releases: `g1t.sh/downloads/<tool>/<version>/<file>`, served from the |
| 7 | * g1t-downloads R2 bucket. `runner` is the self-hosted runner |
| 8 | * (scripts/runner-release.mjs), `cli` the g1t CLI (scripts/cli-release.mjs). |
| 9 | * `latest/<file>` is the newest release's, as its `latest.json` names it; |
| 10 | * the runner's `latest.json` and `latest.json.sig` are what runners check |
| 11 | * before updating. |
| 12 | */ |
| 13 | const TOOLS = new Set(["runner", "cli"]); |
| 14 | const TYPES: Record<string, string> = { |
| 15 | json: "application/json", |
| 16 | sig: "text/plain; charset=utf-8", |
| 17 | txt: "text/plain; charset=utf-8", |
| 18 | }; |
| 19 | |
| 20 | async function object(key: string): Promise<R2ObjectBody | null> { |
| 21 | const bucket = env.DOWNLOADS; |
| 22 | return bucket ? bucket.get(key) : null; |
| 23 | } |
| 24 | |
| 25 | export async function loader({ params }: Route.LoaderArgs) { |
| 26 | const tool = params.tool ?? ""; |
| 27 | const path = (params["*"] ?? "").replace(/^\/+/, ""); |
| 28 | if (!TOOLS.has(tool) || !path || path.includes("..") || !/^[A-Za-z0-9._/-]+$/.test(path)) { |
| 29 | throw new Response("Not found\n", { status: 404 }); |
| 30 | } |
| 31 | let key = `${tool}/${path}`; |
| 32 | // `latest/<file>`: the file of the newest release. |
| 33 | if (path.startsWith("latest/")) { |
| 34 | const manifest = await object(`${tool}/latest.json`); |
| 35 | if (!manifest) throw new Response("No release yet\n", { status: 404 }); |
| 36 | const { version } = (await manifest.json()) as { version: string }; |
| 37 | key = `${tool}/${version}/${path.slice("latest/".length)}`; |
| 38 | } |
| 39 | const found = await object(key); |
| 40 | if (!found) throw new Response("Not found\n", { status: 404 }); |
| 41 | const name = key.split("/").pop() ?? "g1t-runner"; |
| 42 | const extension = name.includes(".") ? name.split(".").pop()! : ""; |
| 43 | const headers = new Headers({ |
| 44 | "content-type": TYPES[extension] ?? "application/octet-stream", |
| 45 | etag: found.httpEtag, |
| 46 | // A version's files never change; what `latest` points to does. |
| 47 | "cache-control": path.startsWith("latest") ? "public, max-age=300" : "public, max-age=31536000, immutable", |
| 48 | }); |
| 49 | if (!TYPES[extension]) headers.set("content-disposition", `attachment; filename="${name}"`); |
| 50 | return new Response(found.body, { headers }); |
| 51 | } |