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

GitHubMediaFetch.ts

138 lines5.2 KB

1import * as Mime from "effect/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/http";
14​
15import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
16​
17/**
18 * Everything a redirect leads to — the presigned object stores GitHub hands assets off to —
19 * authorizes with its own signature, and some of them reject a request that also carries a
20 * 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​
36const MAX_REDIRECTS = 3;
37const MANUAL_REDIRECT: RequestInit = { redirect: "manual" };
38const FORWARDED_REQUEST_HEADERS = ["range", "if-range"] as const;
39const FORWARDED_RESPONSE_HEADERS = [
40 "content-type",
41 "content-length",
42 "content-range",
43 "accept-ranges",
44 "etag",
45 "last-modified",
46] as const;
47const MEDIA_CONTENT_TYPE_PATTERN = /^(?:image|video|audio)\/[\w!#$&^.+-]+$/i;
48const SVG_CONTENT_TYPE = "image/svg+xml";
49// An SVG is a document: same policy the asset route gives a workspace SVG, so one embedded in a
50// body cannot run script against this origin.
51const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
52​
53const githubToken = GitHubCredentials.GitHubCredentials.pipe(
54 Effect.flatMap((credentials) => credentials.get("github.com")),
55 Effect.map((credential) => credential.token),
56 Effect.orElseSucceed(() => null),
57);
58​
59const fetchFollowingRedirects = Effect.fn("GitHubMediaFetch.fetchFollowingRedirects")(function* (
60 url: string,
61 headers: Record<string, string>,
62 token: Redacted.Redacted | null,
63) {
64 const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
65 let target = url;
66 for (let hop = 0; ; hop += 1) {
67 const authorization =
68 token !== null && isCredentialedHost(target) ? `Bearer ${Redacted.value(token)}` : null;
69 const response: HttpClientResponse.HttpClientResponse = yield* httpClient
70 .execute(
71 HttpClientRequest.get(target).pipe(
72 HttpClientRequest.setHeaders({
73 ...headers,
74 // The bytes are streamed straight through, so never let an encoding layer in.
75 "accept-encoding": "identity",
76 ...(authorization === null ? {} : { authorization }),
77 }),
78 ),
79 )
80 .pipe(Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT));
81 const location = response.headers.location;
82 if (response.status < 300 || response.status >= 400) return response;
83 if (!location || hop >= MAX_REDIRECTS) return null;
84 const next = new URL(location, target);
85 if (next.protocol !== "https:") return null;
86 target = next.toString();
87 }
88});
89​
90export const githubMediaResponse = Effect.fn("GitHubMediaFetch.githubMediaResponse")(function* (
91 asset: { readonly url: string; readonly cwd: string; readonly expiresAt: number },
92 requestHeaders: Record<string, string | undefined>,
93) {
94 // Both media hosts are served by github.com's account, which is the host `gh` stores it under.
95 const token = yield* githubToken;
96 const forwarded: Record<string, string> = {};
97 for (const name of FORWARDED_REQUEST_HEADERS) {
98 const value = requestHeaders[name];
99 if (value !== undefined) forwarded[name] = value;
100 }
101 const response = yield* fetchFollowingRedirects(asset.url, forwarded, token);
102 const remainingSeconds = Math.floor((asset.expiresAt - (yield* Clock.currentTimeMillis)) / 1000);
103 const headers: Record<string, string> = {
104 "cache-control":
105 remainingSeconds > 0 ? `private, max-age=${remainingSeconds}` : "private, no-store",
106 "x-content-type-options": "nosniff",
107 };
108 if (response === null) return HttpServerResponse.empty({ status: 502, headers });
109 // It carries none of the upstream entity headers: a `content-length` with no body behind it
110 // holds the connection open until the browser gives up on it.
111 if (response.status >= 400) {
112 return HttpServerResponse.empty({
113 status: response.status >= 500 ? 502 : response.status,
114 headers,
115 });
116 }
117 const upstreamType =
118 response.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
119 const contentType = MEDIA_CONTENT_TYPE_PATTERN.test(upstreamType)
120 ? upstreamType
121 : Option.getOrElse(Mime.getType(githubMediaFileName(asset.url)), () => "").toLowerCase();
122 if (!MEDIA_CONTENT_TYPE_PATTERN.test(contentType)) {
123 return HttpServerResponse.empty({ status: 415, headers });
124 }
125 for (const name of FORWARDED_RESPONSE_HEADERS) {
126 const value = response.headers[name];
127 if (value !== undefined) headers[name] = value;
128 }
129 headers["content-type"] = contentType;
130 if (contentType === SVG_CONTENT_TYPE) {
131 headers["content-security-policy"] = SVG_CONTENT_SECURITY_POLICY;
132 }
133 return HttpServerResponse.stream(response.stream, {
134 status: response.status,
135 headers,
136 contentType,
137 });
138});