Files
anonymous_github/src/core/github-token-context.ts
T
Thomas DurieuxandClaude Opus 5.5 4e10e6662d feat: serve public files through jsDelivr when the owner has no GitHub access
Instead of failing, repositories whose owners have no usable credential read
files from jsDelivr at the pinned commit, and archives from codeload. Neither
needs a token or spends GitHub API quota, and neither serves private content.
The shared cache still verifies every file against its Git blob SHA. Calls that
need the GitHub API (tree listing, refresh, metadata) still return
token_expired, and a jsDelivr read does not clear the owner's access alert.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 20:14:07 +00:00

37 lines
1.9 KiB
TypeScript

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<string>; publicRepository?: string; cdnOnly?: boolean; }
const contexts = new Map<string, TokenContext>();
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<string> {
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);
}