Skip to content
116 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, 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/** The only types identity stores, having checked each image's bytes. */
16const AVATAR_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
17
18function plain(status: number, message: string, cache = "no-store"): Response {
19 return new Response(`${message}\n`, {
20 status,
21 headers: {
22 "content-type": "text/plain; charset=utf-8",
23 "cache-control": cache,
24 "x-content-type-options": "nosniff",
25 "content-security-policy": "default-src 'none'; sandbox",
26 },
27 });
28}
29
30/** Answers a request for `path`, the part of its address under the usercontent origin. */
31export async function serveUsercontent(env: Env, ctx: ExecutionContext, request: Request, path: string): Promise<Response> {
32 const method = request.method;
33 if (method !== "GET" && method !== "HEAD") {
34 return new Response("Method not allowed\n", { status: 405, headers: { allow: "GET, HEAD" } });
35 }
36 if (path === "/robots.txt") {
37 return new Response("User-agent: *\nDisallow: /\n", { headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "public, max-age=86400" } });
38 }
39 const avatar = AVATAR_PATH.exec(path);
40 if (avatar) return serveAvatar(env, ctx, method, avatar[1]!, new URL(request.url).origin);
41 const emoji = EMOJI_PATH.exec(path);
42 if (emoji) return serveAvatar(env, ctx, method, `emoji/${emoji[1]!}`, new URL(request.url).origin);
43 const file = parseRawPath(path);
44 if (file) return serveRaw(env, request, method, file);
45 return plain(404, "Not found", "public, max-age=300");
46}
47
48/**
49 * A repository's file. A public repository's to anyone; a private one's
50 * only with a token for this very file (routes/repo/raw.ts makes them).
51 */
52async function serveRaw(env: Env, request: Request, method: string, file: NonNullable<ReturnType<typeof parseRawPath>>): Promise<Response> {
53 const repos = reposClient(env.REPOS);
54 const token = new URL(request.url).searchParams.get("token");
55 let repoId: string | null = null;
56 let isPublic = false;
57 if (token) {
58 if (!env.USERCONTENT_KEY) return plain(404, "Not found");
59 repoId = await verifyRaw(env.USERCONTENT_KEY, file, token);
60 if (!repoId) return plain(403, "This address has expired. Open the file on g1t again for a new one.");
61 } else {
62 // No viewer: only a public repository answers.
63 const found = await repos.get({ namespace: file.owner, name: file.repo }, null).catch(() => null);
64 if (!found?.ok) return plain(404, "There is no such file, or it is not public.", "public, max-age=60");
65 repoId = found.value.id;
66 isPublic = true;
67 }
68 const raw = await repos.rawFile(repoId, file.ref, file.path, MAX_RAW_BYTES).catch(() => null);
69 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");
70 const bytes = Uint8Array.from(atob(raw.data), (c) => c.charCodeAt(0));
71 const headers = rawHeaders(file.path, bytes);
72 // A commit's files never change; a branch's or tag's may.
73 const lasting = isCommit(file.ref);
74 headers.set(
75 "cache-control",
76 isPublic ? (lasting ? "public, max-age=31536000, immutable" : "public, max-age=60") : lasting ? "private, max-age=3600" : "private, max-age=60",
77 );
78 if (lasting) headers.set("etag", `"${file.ref}"`);
79 return new Response(method === "HEAD" ? null : bytes, { headers });
80}
81
82/**
83 * An uploaded avatar, or a custom emoji (`key` is then `emoji/<hash>`). Its
84 * address is its hash, so it never changes and is
85 * kept for good: each data centre keeps it in its cache after the first
86 * view, and storage is read about once per place, not once per visitor.
87 * It is served as nothing but an image: the stored type, no sniffing, and
88 * a policy that lets nothing in it run.
89 */
90async function serveAvatar(env: Env, ctx: ExecutionContext, method: string, key: string, origin: string): Promise<Response> {
91 // The Workers runtime's own cache, which the DOM types do not know.
92 const cache = (caches as unknown as { default: Cache }).default;
93 const cacheKey = new Request(`${origin}/${key.startsWith("emoji/") ? key : `avatars/${key}`}`, { method: "GET" });
94 const cached = await cache.match(cacheKey);
95 if (cached) {
96 return method === "HEAD" ? new Response(null, { headers: cached.headers }) : cached;
97 }
98 const { value, metadata } = await env.AVATARS.getWithMetadata<{ contentType?: string }>(key, {
99 type: "arrayBuffer",
100 cacheTtl: 86400,
101 });
102 const contentType = metadata?.contentType;
103 if (!value || !contentType || !AVATAR_TYPES.has(contentType)) {
104 return plain(404, "Not found", "public, max-age=60");
105 }
106 const headers = {
107 "content-type": contentType,
108 "content-length": String(value.byteLength),
109 "cache-control": "public, max-age=31536000, immutable",
110 "x-content-type-options": "nosniff",
111 "content-security-policy": "default-src 'none'; sandbox",
112 "cross-origin-resource-policy": "cross-origin",
113 };
114 ctx.waitUntil(cache.put(cacheKey, new Response(value, { headers })));
115 return new Response(method === "HEAD" ? null : value, { headers });
116}