Dough Git

clove/cdn

src/files.ts

back to src

// Everything backed by the R2 bucket: serving files, listing them for the
// browser, and uploads, new folders and deletes.

import { FOLDER_MARKER } from "../shared/folders";
import { rawBase, type AppContext } from "./env";

/** Browser cache for served files. URLs can change any time, so nothing longer. */
const FILE_CACHE = "public, max-age=86400";
const MAX_KEY_BYTES = 1024;

// Paths the viewer itself answers, so a folder there could never be browsed.
const RESERVED = ["_app/", "api/", "auth/", "login", "logout", "upload", "licence", "LICENCE.md", ".well-known/", "favicon.svg", "favicon.png", "style.css", "sfx.js"];

// Known extensions always get these, since browsers often send nothing useful
// (.glb, fonts, .mov and friends). Anything else keeps what the uploader sent.
const TYPES: Record<string, string> = {
  avif: "image/avif",
  gif: "image/gif",
  glb: "model/gltf-binary",
  gltf: "model/gltf+json",
  ico: "image/x-icon",
  jpeg: "image/jpeg",
  jpg: "image/jpeg",
  js: "text/javascript; charset=utf-8",
  json: "application/json",
  md: "text/plain; charset=utf-8",
  mov: "video/quicktime",
  mp3: "audio/mpeg",
  mp4: "video/mp4",
  ogg: "audio/ogg",
  otf: "font/otf",
  pdf: "application/pdf",
  png: "image/png",
  ps1: "text/plain; charset=utf-8",
  sh: "text/plain; charset=utf-8",
  svg: "image/svg+xml",
  ttf: "font/ttf",
  txt: "text/plain; charset=utf-8",
  wav: "audio/wav",
  webm: "video/webm",
  webp: "image/webp",
  woff: "font/woff",
  woff2: "font/woff2",
};

export function fmtSize(n: number): string {
  if (n < 1024) return `${n} B`;
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
  return `${(n / (1024 * 1024)).toFixed(1)} MB`;
}

function knownType(key: string): string | undefined {
  const dot = key.lastIndexOf(".");
  return dot > key.lastIndexOf("/") ? TYPES[key.slice(dot + 1).toLowerCase()] : undefined;
}

/** Returns an error message, or null if the key is fine to store. */
export function checkKey(key: string): string | null {
  if (!key) return "No file path given.";
  if (new TextEncoder().encode(key).length > MAX_KEY_BYTES) return "That path is too long.";
  if (/[\u0000-\u001f\u007f\\]/.test(key)) return "That path has characters that aren't allowed.";
  const segs = key.split("/");
  if (segs.some((s) => s === "" || s === "." || s === ".." || s.startsWith("."))) {
    return "Path segments can't be empty or start with a dot.";
  }
  if (RESERVED.some((r) => (r.endsWith("/") ? key.startsWith(r) : key === r))) {
    return "That path is used by the site itself.";
  }
  return null;
}

/** True if any object lives under `<prefix>/`. */
export async function isFolder(c: AppContext, prefix: string): Promise<boolean> {
  const page = await c.env.BUCKET.list({ prefix: `${prefix}/`, limit: 1 });
  return page.objects.length > 0;
}

/** GET/HEAD /api/files/<key> straight out of R2, with conditional and range support. */
export async function serveFile(c: AppContext, key: string): Promise<Response | null> {
  const bucket = c.env.BUCKET;
  const req = c.req.raw;

  if (req.method === "HEAD") {
    const head = await bucket.head(key);
    if (!head) return null;
    const headers = fileHeaders(head);
    headers.set("Content-Length", String(head.size));
    return new Response(null, { headers });
  }

  const obj = await bucket.get(key, { onlyIf: req.headers, range: req.headers });
  if (!obj) return null;
  const headers = fileHeaders(obj);

  // A failed precondition comes back as an object without a body.
  if (!("body" in obj)) {
    const conditionalGet = req.headers.has("If-None-Match") || req.headers.has("If-Modified-Since");
    return new Response(null, { status: conditionalGet ? 304 : 412, headers });
  }

  if (req.headers.has("Range") && obj.range) {
    const r = obj.range as { offset?: number; length?: number; suffix?: number };
    const offset = r.suffix !== undefined ? obj.size - r.suffix : (r.offset ?? 0);
    const length = r.suffix !== undefined ? r.suffix : (r.length ?? obj.size - offset);
    headers.set("Content-Range", `bytes ${offset}-${offset + length - 1}/${obj.size}`);
    headers.set("Content-Length", String(length));
    return new Response(obj.body, { status: 206, headers });
  }

  headers.set("Content-Length", String(obj.size));
  return new Response(obj.body, { headers });
}

function fileHeaders(obj: R2Object): Headers {
  const headers = new Headers();
  obj.writeHttpMetadata(headers);
  if (!headers.has("Content-Type")) headers.set("Content-Type", knownType(obj.key) ?? "application/octet-stream");
  headers.set("ETag", obj.httpEtag);
  headers.set("Last-Modified", obj.uploaded.toUTCString());
  headers.set("Accept-Ranges", "bytes");
  headers.set("Cache-Control", FILE_CACHE);
  return headers;
}

// Seconds the listing stays in the edge cache. Writes purge it in their own
// data centre; the others catch up when this runs out.
const LIST_TTL = 60;

function listCacheKey(c: AppContext): Request {
  return new Request(new URL("/api/list", c.req.url).href);
}

/** Drops the cached listing. Called after every upload, new folder and delete. */
async function purgeList(c: AppContext): Promise<void> {
  await caches.default.delete(listCacheKey(c));
}

async function etagOf(body: string): Promise<string> {
  const digest = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(body));
  const hex = [...new Uint8Array(digest)]
    .map((byte) => byte.toString(16).padStart(2, "0"))
    .join("");
  return `"${hex}"`;
}

/** True if the browser's If-None-Match names this ETag (weak or strong). */
function etagMatches(header: string | undefined, etag: string | null): boolean {
  if (!header || !etag) return false;
  return header
    .split(",")
    .map((value) => value.trim().replace(/^W\//, ""))
    .includes(etag);
}

/** Scans the whole bucket and builds the listing response. */
async function buildList(c: AppContext): Promise<Response> {
  const files: { path: string; size: number }[] = [];
  let cursor: string | undefined;
  do {
    const page = await c.env.BUCKET.list({ cursor, limit: 1000 });
    for (const o of page.objects) files.push({ path: o.key, size: o.size });
    cursor = page.truncated ? page.cursor : undefined;
  } while (cursor);

  const body = JSON.stringify({
    count: files.length,
    raw: rawBase(c.env),
    files,
  });

  return new Response(body, {
    headers: {
      "Content-Type": "application/json",
      // Browsers revalidate (a 304 when nothing changed); the edge keeps it for LIST_TTL
      "Cache-Control": `public, max-age=0, s-maxage=${LIST_TTL}`,
      ETag: await etagOf(body),
    },
  });
}

/**
 * GET /api/list — flat list of every object, for the browser. Served from the
 * edge cache when it can be; ?fresh=1 skips the cache and refills it.
 */
export async function listFiles(c: AppContext): Promise<Response> {
  const cacheKey = listCacheKey(c);
  const fresh = c.req.query("fresh") === "1";

  let response = fresh ? undefined : await caches.default.match(cacheKey);
  if (!response) {
    response = await buildList(c);
    c.executionCtx.waitUntil(caches.default.put(cacheKey, response.clone()));
  }

  if (etagMatches(c.req.header("If-None-Match"), response.headers.get("ETag"))) {
    return new Response(null, { status: 304, headers: response.headers });
  }
  return response;
}

/** PUT /api/files/<key> — raw request body becomes the object. */
export async function uploadFile(c: AppContext, key: string, uploader: string): Promise<Response> {
  const bad = checkKey(key);
  if (bad) return c.json({ error: bad }, 400);

  const length = Number(c.req.header("Content-Length"));
  const body = c.req.raw.body;
  if (!body || !Number.isFinite(length)) return c.json({ error: "Send the file as the request body." }, 411);

  if (c.req.query("overwrite") !== "1" && (await c.env.BUCKET.head(key))) {
    return c.json({ error: "A file already exists at that path." }, 409);
  }

  const sent = c.req.header("Content-Type")?.trim();
  const contentType = knownType(key) ?? (sent && !sent.startsWith("application/x-www-form-urlencoded") ? sent : "application/octet-stream");

  const obj = await c.env.BUCKET.put(key, body, {
    httpMetadata: { contentType },
    customMetadata: { uploadedBy: uploader },
  });
  await purgeList(c);
  return c.json({ path: obj.key, size: obj.size, url: `${rawBase(c.env)}/${encodeKey(obj.key)}` }, 201);
}

/** POST /api/folders/<key> — an empty folder, held open by its marker. */
export async function createFolder(c: AppContext, key: string, uploader: string): Promise<Response> {
  const bad = checkKey(key);
  if (bad) return c.json({ error: bad }, 400);
  if (await c.env.BUCKET.head(key)) return c.json({ error: "A file already exists at that path." }, 409);
  if (await isFolder(c, key)) return c.json({ error: "That folder already exists." }, 409);

  await c.env.BUCKET.put(`${key}/${FOLDER_MARKER}`, "", { customMetadata: { uploadedBy: uploader } });
  await purgeList(c);
  return c.json({ path: key }, 201);
}

/**
 * DELETE /api/files/<key> — one file, or a folder's marker (which deletes that
 * empty folder). Whatever folder the viewer goes back to afterwards keeps
 * existing, with a marker if nothing else is left in it.
 */
export async function deleteFile(c: AppContext, key: string, uploader: string): Promise<Response> {
  if (!(await c.env.BUCKET.head(key))) return c.json({ error: "No file at that path." }, 404);
  await c.env.BUCKET.delete(key);

  const deleted = key.endsWith(`/${FOLDER_MARKER}`) ? parentOf(key) : key;
  const keep = parentOf(deleted);
  if (keep && !(await isFolder(c, keep))) {
    await c.env.BUCKET.put(`${keep}/${FOLDER_MARKER}`, "", { customMetadata: { uploadedBy: uploader } });
  }
  await purgeList(c);
  return c.body(null, 204);
}

/** "img/avatars/x.png" → "img/avatars"; "" at the top level. */
function parentOf(key: string): string {
  return key.slice(0, Math.max(0, key.lastIndexOf("/")));
}

export function encodeKey(key: string): string {
  return key.split("/").map(encodeURIComponent).join("/");
}