Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubMediaFetch.ts

196 lines8.4 KB

1import Mime from "@effect/platform-node/Mime";
2import { githubMediaFileName } from "@t3tools/shared/githubMedia";
3import * as Clock from "effect/Clock";
4import * as Effect from "effect/Effect";
5import * as Redacted from "effect/Redacted";
6import {
7 FetchHttpClient,
8 HttpClient,
9 HttpClientRequest,
10 HttpServerResponse,
11 type HttpClientResponse,
12} from "effect/unstable/http";
13​
14import * as GitHubCli from "../sourceControl/GitHubCli.ts";
15​
16/**
17 * Exactly the hosts the credential is for. Everything a redirect leads to — the presigned
18 * object stores GitHub hands assets off to — authorizes with its own signature, and some of
19 * them reject a request that also carries a bearer token.
20 */
21const CREDENTIALED_HOSTS = new Set([
22 "github.com",
23 "www.github.com",
24 "raw.githubusercontent.com",
25 "media.githubusercontent.com",
26]);
27const isCredentialedHost = (url: string) => {
28 try {
29 return CREDENTIALED_HOSTS.has(new URL(url).hostname.toLowerCase());
30 } catch {
31 return false;
32 }
33};
34​
35/** GitHub answers an asset request with a 302 to a signed object URL that needs no credential. */
36const MAX_REDIRECTS = 3;
37/** Following the redirect here, rather than in `fetch`, is what keeps the token on GitHub. */
38const MANUAL_REDIRECT: RequestInit = { redirect: "manual" };
39const TOKEN_CACHE_TTL_MS = 5 * 60_000;
40const TOKEN_CACHE_MAX_ENTRIES = 32;
41/** Passed through so a seek in a long video costs one upstream range request, not a full download. */
42const FORWARDED_REQUEST_HEADERS = ["range", "if-range"] as const;
43const FORWARDED_RESPONSE_HEADERS = [
44 "content-type",
45 "content-length",
46 "content-range",
47 "accept-ranges",
48 "etag",
49 "last-modified",
50] as const;
51/** A pull request embeds pictures and recordings. Anything else is not served from our origin. */
52const MEDIA_CONTENT_TYPE_PATTERN = /^(?:image|video|audio)\/[\w!#$&^.+-]+$/i;
53const SVG_CONTENT_TYPE = "image/svg+xml";
54// An SVG is a document: same policy the asset route gives a workspace SVG, so one embedded in a
55// body cannot run script against this origin.
56const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
57​
58/**
59 * A media request per image and one per video seek, each of which would otherwise spawn `gh`.
60 * The token is what `gh auth token` would print again on the next call, and it is held no longer
61 * than a signed asset URL lives.
62 */
63const tokenCache = new Map<string, { readonly at: number; readonly token: Redacted.Redacted }>();
64​
65const githubToken = Effect.fn("GitHubMediaFetch.githubToken")(function* (input: {
66 readonly cwd: string;
67 readonly host: string;
68}) {
69 // `gh` stores a token per host, not per repository, so the directory it runs in is not part
70 // of the answer and must not fragment the cache a client could otherwise churn. This route
71 // pins no credential; if it ever does, the pin belongs in this key.
72 const key = input.host;
73 const now = yield* Clock.currentTimeMillis;
74 const cached = tokenCache.get(key);
75 if (cached !== undefined && now - cached.at < TOKEN_CACHE_TTL_MS) return cached.token;
76 const github = yield* GitHubCli.GitHubCli;
77 // No credential is a normal state: a public asset still loads, and a private one fails the way
78 // it does in a browser that is not signed in.
79 const token = yield* github
80 .execute({
81 cwd: input.cwd,
82 args: ["auth", "token", "--hostname", input.host],
83 env: { GH_DEBUG: "" },
84 })
85 .pipe(
86 Effect.map((output) => output.stdout.trim()),
87 Effect.orElseSucceed(() => ""),
88 );
89 // A login or recovered CLI failure must take effect on the next media request.
90 if (token.length === 0) return null;
91 if (tokenCache.size >= TOKEN_CACHE_MAX_ENTRIES) {
92 tokenCache.delete(tokenCache.keys().next().value!);
93 }
94 const redacted = Redacted.make(token);
95 tokenCache.set(key, { at: now, token: redacted });
96 return redacted;
97});
98​
99/**
100 * Follows GitHub's redirect to the signed object itself, and never carries the credential off
101 * GitHub: the object URL authorizes with its own signature, and the store it lives in has no
102 * business seeing a token.
103 */
104const fetchFollowingRedirects = Effect.fn("GitHubMediaFetch.fetchFollowingRedirects")(function* (
105 url: string,
106 headers: Record<string, string>,
107 token: Redacted.Redacted | null,
108) {
109 const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
110 let target = url;
111 for (let hop = 0; ; hop += 1) {
112 // The credential rides only on a request to GitHub itself. A redirect leads to a signed
113 // object URL that authorizes on its own, and the store it lives in has no business seeing
114 // a token — deciding that from the target, not from the hop count, is what makes it so.
115 const authorization =
116 token !== null && isCredentialedHost(target) ? `Bearer ${Redacted.value(token)}` : null;
117 const response: HttpClientResponse.HttpClientResponse = yield* httpClient
118 .execute(
119 HttpClientRequest.get(target).pipe(
120 HttpClientRequest.setHeaders({
121 ...headers,
122 // The bytes are streamed straight through, so never let an encoding layer in.
123 "accept-encoding": "identity",
124 ...(authorization === null ? {} : { authorization }),
125 }),
126 ),
127 )
128 .pipe(Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT));
129 const location = response.headers.location;
130 if (response.status < 300 || response.status >= 400) return response;
131 // A chain this long is not GitHub answering with bytes, and its body is not the media.
132 if (!location || hop >= MAX_REDIRECTS) return null;
133 const next = new URL(location, target);
134 if (next.protocol !== "https:") return null;
135 target = next.toString();
136 }
137});
138​
139/**
140 * Serves media a pull request body points at on GitHub through the `gh` credential, which is the
141 * only thing that distinguishes a readable private attachment from a 404.
142 */
143export const githubMediaResponse = Effect.fn("GitHubMediaFetch.githubMediaResponse")(function* (
144 asset: { readonly url: string; readonly cwd: string; readonly expiresAt: number },
145 requestHeaders: Record<string, string | undefined>,
146) {
147 // Both media hosts are served by github.com's account, which is the host `gh` stores it under.
148 const token = yield* githubToken({ cwd: asset.cwd, host: "github.com" });
149 const forwarded: Record<string, string> = {};
150 for (const name of FORWARDED_REQUEST_HEADERS) {
151 const value = requestHeaders[name];
152 if (value !== undefined) forwarded[name] = value;
153 }
154 const response = yield* fetchFollowingRedirects(asset.url, forwarded, token);
155 // An upload GitHub hosts never changes under its URL, so the only thing a cached copy must
156 // not outlive is the signed URL that granted it — which is the same bound the URL itself has.
157 const remainingSeconds = Math.floor((asset.expiresAt - (yield* Clock.currentTimeMillis)) / 1000);
158 const headers: Record<string, string> = {
159 "cache-control":
160 remainingSeconds > 0 ? `private, max-age=${remainingSeconds}` : "private, no-store",
161 "x-content-type-options": "nosniff",
162 };
163 if (response === null) return HttpServerResponse.empty({ status: 502, headers });
164 // An upstream refusal is the client's answer, not this server's fault; only a broken hop is.
165 // It carries none of the upstream entity headers: a `content-length` with no body behind it
166 // holds the connection open until the browser gives up on it.
167 if (response.status >= 400) {
168 return HttpServerResponse.empty({
169 status: response.status >= 500 ? 502 : response.status,
170 headers,
171 });
172 }
173 // Only pictures and recordings leave this origin, and never on GitHub's word alone: the raw
174 // host labels every committed binary `application/octet-stream`, so the name decides those.
175 const upstreamType =
176 response.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
177 const contentType = MEDIA_CONTENT_TYPE_PATTERN.test(upstreamType)
178 ? upstreamType
179 : (Mime.getType(githubMediaFileName(asset.url))?.toLowerCase() ?? "");
180 if (!MEDIA_CONTENT_TYPE_PATTERN.test(contentType)) {
181 return HttpServerResponse.empty({ status: 415, headers });
182 }
183 for (const name of FORWARDED_RESPONSE_HEADERS) {
184 const value = response.headers[name];
185 if (value !== undefined) headers[name] = value;
186 }
187 headers["content-type"] = contentType;
188 if (contentType === SVG_CONTENT_TYPE) {
189 headers["content-security-policy"] = SVG_CONTENT_SECURITY_POLICY;
190 }
191 return HttpServerResponse.stream(response.stream, {
192 status: response.status,
193 headers,
194 contentType,
195 });
196});