SPB Git

Repository Public

serve.ts 3.5 KB 44 lines typescript

1import "server-only";2import { Readable } from "node:stream";3import { mimeOf, parseRange, type MediaStorage } from "@/modules/storage";45const notFound = () => new Response("Introuvable", { status: 404, headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" } });67/**8 * Streams one object with HTTP range support. The caller has already checked that the visitor may see it.9 * Responses are locked down: known media types only, nosniff, and a CSP that forbids everything, so an10 * SVG or any other file opened directly can never run script or load anything.11 */12export async function serveObject(storage: MediaStorage, key: string, request: Request, opts: { cache: string; download?: string; type?: string } = { cache: "public, max-age=3600" }): Promise<Response> {13  // A download is always sent as an attachment, so its recorded type may be used; anything shown inline must be a known media type.14  const type = mimeOf(key) ?? (opts.download && opts.type && /^[a-z]+\/[a-z0-9.+-]+(; charset=utf-8)?$/.test(opts.type) ? opts.type : null);15  if (!type) return notFound();16  const info = await storage.stat(key);17  if (!info) return notFound();18  const etag = `"${info.size.toString(16)}-${Math.floor(info.mtimeMs).toString(16)}"`;19  const headers: Record<string, string> = {20    "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": opts.cache, ETag: etag,21    "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", "Cross-Origin-Resource-Policy": "same-origin",22    ...(opts.download ? { "Content-Disposition": `attachment; filename="${opts.download.replace(/[^A-Za-z0-9._-]/g, "_")}"` } : {}),23  };24  if (request.headers.get("if-none-match") === etag) return new Response(null, { status: 304, headers });25  const range = parseRange(request.headers.get("range"), info.size);26  if (range === "invalid") return new Response(null, { status: 416, headers: { ...headers, "Content-Range": `bytes */${info.size}` } });27  if (request.method === "HEAD") return new Response(null, { status: 200, headers: { ...headers, "Content-Length": String(info.size) } });28  const stream = await storage.read(key, range ?? undefined);29  if (!stream) return notFound();30  const body = Readable.toWeb(stream) as ReadableStream;31  if (range) return new Response(body, { status: 206, headers: { ...headers, "Content-Range": `bytes ${range.start}-${range.end}/${info.size}`, "Content-Length": String(range.end - range.start + 1) } });32  return new Response(body, { status: 200, headers: { ...headers, "Content-Length": String(info.size) } });33}3435/** Serves bytes held in memory (a figure kept in the studio database) with the same locked-down headers. */36export function serveBytes(bytes: Buffer, type: string, request: Request, opts: { cache: string }): Response {37  const etag = `"${bytes.length.toString(16)}-${bytes.subarray(0, 64).reduce((a, b) => (a * 31 + b) >>> 0, 7).toString(16)}"`;38  const headers: Record<string, string> = { "Content-Type": type, "Cache-Control": opts.cache, ETag: etag, "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", "Cross-Origin-Resource-Policy": "same-origin" };39  if (request.headers.get("if-none-match") === etag) return new Response(null, { status: 304, headers });40  return new Response(request.method === "HEAD" ? null : new Uint8Array(bytes), { status: 200, headers: { ...headers, "Content-Length": String(bytes.length) } });41}4243export { notFound as notFoundResponse };44
Files main
Menu

Theme