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

GitHubMediaFetch.ts

197 lines8.5 KB

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