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

sourceControlMediaResponse.ts

139 lines5.4 KB

1import * as Mime from "effect/http/Mime";
2import * as Clock from "effect/Clock";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import { HttpServerResponse } from "effect/http";
6​
7import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
8import * as BuiltInDrivers from "../sourceControl/builtInDrivers.ts";
9import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
10​
11const FORWARDED_REQUEST_HEADERS = ["range", "if-range"] as const;
12const FORWARDED_RESPONSE_HEADERS = [
13 "content-type",
14 "content-length",
15 "content-range",
16 "accept-ranges",
17 "etag",
18 "last-modified",
19] as const;
20const MEDIA_CONTENT_TYPE_PATTERN = /^(?:image|video|audio)\/[\w!#$&^.+-]+$/i;
21const SVG_CONTENT_TYPE = "image/svg+xml";
22// An SVG is a document: same policy the asset route gives a workspace SVG, so one embedded in a
23// body cannot run script against this origin.
24const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
25​
26const NO_STORE = "private, no-store";
27​
28/**
29 * How long the upstream still lets its bytes be reused. Bytes that can never change may be kept
30 * for the signed URL's whole life unless the upstream forbids storing them; anything else is kept
31 * no longer than the upstream's `max-age` less the age the bytes already had when they arrived,
32 * and not at all when it says nothing.
33 */
34function upstreamFreshSeconds(
35 responseHeaders: Readonly<Record<string, string | undefined>>,
36 immutable: boolean,
37 elapsedSeconds: number,
38): number {
39 const directives = (responseHeaders["cache-control"] ?? "")
40 .toLowerCase()
41 .split(",")
42 .map((part) => part.trim());
43 if (directives.some((part) => part === "no-store" || part === "no-cache")) return 0;
44 if (immutable) return Number.POSITIVE_INFINITY;
45 const maxAge = directives
46 .map((part) => /^max-age=(\d+)$/u.exec(part)?.[1])
47 .find((value) => value !== undefined);
48 if (maxAge === undefined) return 0;
49 const age = Number(responseHeaders.age ?? 0);
50 // An unreadable Age means the age is unknown, so nothing is fresh.
51 return Number.isFinite(age) && age >= 0 ? Number(maxAge) - age - elapsedSeconds : 0;
53​
54export const sourceControlMediaResponse = Effect.fn(
55 "SourceControlMediaResponse.sourceControlMediaResponse",
56)(function* (
57 asset: {
58 readonly url: string;
59 readonly cwd: string;
60 readonly repository?: string;
61 readonly expiresAt: number;
62 },
63 requestHeaders: Record<string, string | undefined>,
64) {
65 const requestedAt = yield* Clock.currentTimeMillis;
66 const headers: Record<string, string> = {
67 "cache-control": NO_STORE,
68 "x-content-type-options": "nosniff",
69 };
70 const media = sourceControlDefinitions.mediaUrl(asset.url);
71 const drivers = yield* BuiltInDrivers.SourceControlDrivers;
72 const fetchMedia = drivers.find(({ driver }) => driver.kind === media?.definition.kind)?.instance
73 .fetchMedia;
74 if (media === null || fetchMedia === undefined) {
75 return HttpServerResponse.empty({ status: 404, headers });
76 }
77 const forwarded: Record<string, string> = {};
78 for (const name of FORWARDED_REQUEST_HEADERS) {
79 const value = requestHeaders[name];
80 if (value !== undefined) forwarded[name] = value;
81 }
82 // Clients that predate `repository` fall back to the repository checked out at `cwd`.
83 let repository = asset.repository;
84 if (repository === undefined) {
85 const identities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
86 const identity = yield* identities.resolve(asset.cwd);
87 if (identity?.provider === media.definition.kind && identity.owner && identity.name) {
88 repository = `${identity.owner}/${identity.name}`;
89 }
90 }
91 const response = yield* fetchMedia({
92 url: asset.url,
93 headers: forwarded,
94 ...(repository === undefined ? {} : { repository }),
95 });
96 if (response === null) return HttpServerResponse.empty({ status: 502, headers });
97 // It carries none of the upstream entity headers: a `content-length` with no body behind it
98 // holds the connection open until the browser gives up on it.
99 if (response.status >= 400) {
100 return HttpServerResponse.empty({
101 status: response.status >= 500 ? 502 : response.status,
102 headers,
103 });
104 }
105 const upstreamType =
106 response.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
107 const contentType = MEDIA_CONTENT_TYPE_PATTERN.test(upstreamType)
108 ? upstreamType
109 : Option.getOrElse(Mime.getType(media.fileName), () => "").toLowerCase();
110 if (!MEDIA_CONTENT_TYPE_PATTERN.test(contentType)) {
111 return HttpServerResponse.empty({ status: 415, headers });
112 }
113 for (const name of FORWARDED_RESPONSE_HEADERS) {
114 const value = response.headers[name];
115 if (value !== undefined) headers[name] = value;
116 }
117 headers["content-type"] = contentType;
118 // Measured after the upstream answered: a slow upstream uses up both lifetimes.
119 const receivedAt = yield* Clock.currentTimeMillis;
120 const maxAge = Math.floor(
121 Math.min(
122 (asset.expiresAt - receivedAt) / 1000,
123 upstreamFreshSeconds(
124 response.headers,
125 media.immutable === true,
126 Math.ceil((receivedAt - requestedAt) / 1000),
127 ),
128 ),
129 );
130 if (maxAge > 0) headers["cache-control"] = `private, max-age=${maxAge}`;
131 if (contentType === SVG_CONTENT_TYPE) {
132 headers["content-security-policy"] = SVG_CONTENT_SECURITY_POLICY;
133 }
134 return HttpServerResponse.stream(response.stream, {
135 status: response.status,
136 headers,
137 contentType,
138 });
139});