Skip to content
147 linesCodeBlameRaw
1/**
2 * The usercontent origin (app/lib/usercontent.ts): repository files and
3 * uploaded avatars, on g1tusercontent.com for g1t.sh. This answers before
4 * anything of the site's runs, and reads no cookie and sets none: nothing
5 * here knows who is asking, only what the address and its token say.
6 */
7import { reposClient } from "@g1t/contracts";
8
9import { MAX_RAW_BYTES, PDF_POLICY, USERCONTENT_POLICY, isCommit, parseRawPath, rawHeaders, verifyRaw } from "../app/lib/usercontent";
10
11/** An uploaded avatar, by the SHA-256 of its bytes. */
12export const AVATAR_PATH = /^\/avatars\/([0-9a-f]{64})$/;
13/** A workspace's custom emoji, by the SHA-256 of its bytes: kept by chat under `emoji/<hash>` in the same namespace. */
14export const EMOJI_PATH = /^\/emoji\/([0-9a-f]{64})$/;
15/** A project's uploaded production image, by the SHA-256 of its bytes: kept by projects under `production/<hash>` in the same namespace. */
16export const PRODUCTION_IMAGE_PATH = /^\/production-images\/([0-9a-f]{64})$/;
17/** A file put in a Docs page, by its random key: kept by the artifacts service (services/artifacts). */
18export const DOCS_FILE_PATH = /^\/docs-files\/([0-9a-f]{64})$/;
19/** The only types identity stores, having checked each image's bytes. */
20const AVATAR_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
21
22function plain(status: number, message: string, cache = "no-store"): Response {
23 return new Response(`${message}\n`, {
24 status,
25 headers: {
26 "content-type": "text/plain; charset=utf-8",
27 "cache-control": cache,
28 "x-content-type-options": "nosniff",
29 "content-security-policy": "default-src 'none'; sandbox",
30 },
31 });
32}
33
34/** Answers a request for `path`, the part of its address under the usercontent origin. */
35export async function serveUsercontent(env: Env, ctx: ExecutionContext, request: Request, path: string): Promise<Response> {
36 const method = request.method;
37 if (method !== "GET" && method !== "HEAD") {
38 return new Response("Method not allowed\n", { status: 405, headers: { allow: "GET, HEAD" } });
39 }
40 if (path === "/robots.txt") {
41 return new Response("User-agent: *\nDisallow: /\n", { headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "public, max-age=86400" } });
42 }
43 const avatar = AVATAR_PATH.exec(path);
44 if (avatar) return serveAvatar(env, ctx, method, avatar[1]!, new URL(request.url).origin);
45 const emoji = EMOJI_PATH.exec(path);
46 if (emoji) return serveAvatar(env, ctx, method, `emoji/${emoji[1]!}`, new URL(request.url).origin);
47 const production = PRODUCTION_IMAGE_PATH.exec(path);
48 if (production) return serveAvatar(env, ctx, method, `production/${production[1]!}`, new URL(request.url).origin);
49 const docsFile = DOCS_FILE_PATH.exec(path);
50 if (docsFile) return serveDocsFile(env, method, docsFile[1]!);
51 const file = parseRawPath(path);
52 if (file) return serveRaw(env, request, method, file);
53 return plain(404, "Not found", "public, max-age=300");
54}
55
56/**
57 * A repository's file. A public repository's to anyone; a private one's
58 * only with a token for this very file (routes/repo/raw.ts makes them).
59 */
60async function serveRaw(env: Env, request: Request, method: string, file: NonNullable<ReturnType<typeof parseRawPath>>): Promise<Response> {
61 const repos = reposClient(env.REPOS);
62 const token = new URL(request.url).searchParams.get("token");
63 let repoId: string | null = null;
64 let isPublic = false;
65 if (token) {
66 if (!env.USERCONTENT_KEY) return plain(404, "Not found");
67 repoId = await verifyRaw(env.USERCONTENT_KEY, file, token);
68 if (!repoId) return plain(403, "This address has expired. Open the file on g1t again for a new one.");
69 } else {
70 // No viewer: only a public repository answers.
71 const found = await repos.get({ namespace: file.owner, name: file.repo }, null).catch(() => null);
72 if (!found?.ok) return plain(404, "There is no such file, or it is not public.", "public, max-age=60");
73 repoId = found.value.id;
74 isPublic = true;
75 }
76 const raw = await repos.rawFile(repoId, file.ref, file.path, MAX_RAW_BYTES).catch(() => null);
77 if (!raw) return plain(404, `There is no such file, or it is over ${MAX_RAW_BYTES / 1024 / 1024} MB. Clone the repository for it.`, "public, max-age=60");
78 const bytes = Uint8Array.from(atob(raw.data), (c) => c.charCodeAt(0));
79 const headers = rawHeaders(file.path, bytes);
80 // A commit's files never change; a branch's or tag's may.
81 const lasting = isCommit(file.ref);
82 headers.set(
83 "cache-control",
84 isPublic ? (lasting ? "public, max-age=31536000, immutable" : "public, max-age=60") : lasting ? "private, max-age=3600" : "private, max-age=60",
85 );
86 if (lasting) headers.set("etag", `"${file.ref}"`);
87 return new Response(method === "HEAD" ? null : bytes, { headers });
88}
89
90/**
91 * An uploaded avatar, a custom emoji (`key` is then `emoji/<hash>`) or a
92 * production image (`production/<hash>`). Its
93 * address is its hash, so it never changes and is
94 * kept for good: each data centre keeps it in its cache after the first
95 * view, and storage is read about once per place, not once per visitor.
96 * It is served as nothing but an image: the stored type, no sniffing, and
97 * a policy that lets nothing in it run.
98 */
99async function serveAvatar(env: Env, ctx: ExecutionContext, method: string, key: string, origin: string): Promise<Response> {
100 // The Workers runtime's own cache, which the DOM types do not know.
101 const cache = (caches as unknown as { default: Cache }).default;
102 const path = key.startsWith("emoji/") ? key : key.startsWith("production/") ? `production-images/${key.slice("production/".length)}` : `avatars/${key}`;
103 const cacheKey = new Request(`${origin}/${path}`, { method: "GET" });
104 const cached = await cache.match(cacheKey);
105 if (cached) {
106 return method === "HEAD" ? new Response(null, { headers: cached.headers }) : cached;
107 }
108 const { value, metadata } = await env.AVATARS.getWithMetadata<{ contentType?: string }>(key, {
109 type: "arrayBuffer",
110 cacheTtl: 86400,
111 });
112 const contentType = metadata?.contentType;
113 if (!value || !contentType || !AVATAR_TYPES.has(contentType)) {
114 return plain(404, "Not found", "public, max-age=60");
115 }
116 const headers = {
117 "content-type": contentType,
118 "content-length": String(value.byteLength),
119 "cache-control": "public, max-age=31536000, immutable",
120 "x-content-type-options": "nosniff",
121 "content-security-policy": "default-src 'none'; sandbox",
122 "cross-origin-resource-policy": "cross-origin",
123 };
124 ctx.waitUntil(cache.put(cacheKey, new Response(value, { headers })));
125 return new Response(method === "HEAD" ? null : value, { headers });
126}
127
128/**
129 * A file put in a Docs page. Its key is 256 random bits the artifacts service
130 * made, so the address is the permission, as a shared link is; the docs
131 * service serves images, media and PDFs as themselves and everything else
132 * as a download, and nothing here can run script.
133 */
134async function serveDocsFile(env: Env, method: string, key: string): Promise<Response> {
135 let answer: Response;
136 try {
137 answer = await env.ARTIFACTS.fetch(`https://docs/files/${key}`, { method });
138 } catch {
139 return plain(503, "Docs didn't answer");
140 }
141 if (!answer.ok) return plain(answer.status === 404 ? 404 : 502, "Not found", "public, max-age=60");
142 const headers = new Headers(answer.headers);
143 headers.set("x-content-type-options", "nosniff");
144 headers.set("content-security-policy", headers.get("content-type") === "application/pdf" ? PDF_POLICY : USERCONTENT_POLICY);
145 headers.set("cross-origin-resource-policy", "cross-origin");
146 return new Response(method === "HEAD" ? null : answer.body, { status: 200, headers });
147}