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

gitHubMediaFetch.ts

68 lines2.6 KB

1import type { SourceControlMediaRequest } from "@t3tools/source-control-core/server/driver";
2import * as Effect from "effect/Effect";
3import * as Redacted from "effect/Redacted";
4import {
5 FetchHttpClient,
6 HttpClient,
7 HttpClientRequest,
8 type HttpClientResponse,
9} from "effect/http";
10​
11import { GITHUB_CREDENTIALED_MEDIA_HOSTS } from "../shared/gitHubMedia.ts";
12​
13import * as GitHubCredentials from "./GitHubCredentials.ts";
14​
15/**
16 * Everything a redirect leads to — the presigned object stores GitHub hands assets off to —
17 * authorizes with its own signature, and some of them reject a request that also carries a
18 * bearer token.
19 */
20const isCredentialedHost = (url: string) => {
21 try {
22 return GITHUB_CREDENTIALED_MEDIA_HOSTS.has(new URL(url).hostname.toLowerCase());
23 } catch {
24 return false;
25 }
26};
27​
28const MAX_REDIRECTS = 3;
29const MANUAL_REDIRECT: RequestInit = { redirect: "manual" };
30​
31export const make = Effect.gen(function* () {
32 const credentials = yield* GitHubCredentials.GitHubCredentials;
33 const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
34​
35 // Both media hosts are served by github.com's account, which is the host `gh` stores it under.
36 // Read on every fetch, so media loads as soon as the user signs in.
37 const token = Effect.suspend(() => credentials.get("github.com")).pipe(
38 Effect.map((credential) => credential.token),
39 Effect.orElseSucceed(() => null),
40 );
41​
42 return Effect.fn("GitHubMediaFetch.fetchMedia")(function* (request: SourceControlMediaRequest) {
43 const bearer = yield* token;
44 let target = request.url;
45 for (let hop = 0; ; hop += 1) {
46 const authorization =
47 bearer !== null && isCredentialedHost(target) ? `Bearer ${Redacted.value(bearer)}` : null;
48 const response: HttpClientResponse.HttpClientResponse = yield* httpClient
49 .execute(
50 HttpClientRequest.get(target).pipe(
51 HttpClientRequest.setHeaders({
52 ...request.headers,
53 // The bytes are streamed straight through, so never let an encoding layer in.
54 "accept-encoding": "identity",
55 ...(authorization === null ? {} : { authorization }),
56 }),
57 ),
58 )
59 .pipe(Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT));
60 const location = response.headers.location;
61 if (response.status < 300 || response.status >= 400) return response;
62 if (!location || hop >= MAX_REDIRECTS) return null;
63 const next = new URL(location, target);
64 if (next.protocol !== "https:") return null;
65 target = next.toString();
66 }
67 });
68});