import { createHash } from "crypto"; // cdnOnly means public content is read from jsDelivr, never from the GitHub API. interface TokenContext { quotaKey: string; renew: (force?: boolean) => Promise; publicRepository?: string; cdnOnly?: boolean; } const contexts = new Map(); export function registerGitHubToken(token: string, context: TokenContext) { if (contexts.size >= 2000 && !contexts.has(token)) contexts.delete(contexts.keys().next().value!); contexts.set(token, context); } /** * Used when an owner has no usable GitHub access. It carries no secret and is * recognized by every process, so the API can pass it to the streamer as is. * jsDelivr only mirrors public repositories, so private content is never exposed. */ export const PUBLIC_CDN_TOKEN = "public-cdn"; const publicCdnContext: TokenContext = { quotaKey: "public-cdn", cdnOnly: true, renew: async () => "" }; export function githubTokenContext(token: string) { if (token === PUBLIC_CDN_TOKEN) return publicCdnContext; const context = contexts.get(token); if (!context && token.startsWith("public-read:")) throw new Error("Public repository access context expired"); return context; } // Public handles belong to this process. Revalidate here, then let the // streamer fetch public bytes anonymously without forwarding the owner's token. export async function githubTokenForStreamer(token: string, repository: string | undefined): Promise { const context = githubTokenContext(token); if (!context?.publicRepository) return token; if (!repository || context.publicRepository.toLowerCase() !== repository.toLowerCase()) { throw new Error("Public repository access context mismatch"); } await context.renew(); return ""; } export function githubQuotaKey(token: string) { return contexts.get(token)?.quotaKey || createHash("sha256").update(token).digest("hex").slice(0, 24); }