Repository Public
1import "server-only";2import { createReadStream } from "node:fs";3import { stat } from "node:fs/promises";4import { Readable } from "node:stream";5import type { Deck } from "@/modules/content-schema";6import { deckAsset } from "@/server/slides";7import { notFoundResponse } from "./serve";89/**10 * Serves one asset of a deck the caller is entitled to see: `<session>/<hash12>/<file>`. The address must11 * name the deck of the view (not an older or a newer one) and a file that deck lists. The response carries12 * a policy that forbids everything: an SVG opened directly can neither run script nor load anything.13 */14export async function serveDeckAsset(deck: Deck | null, segments: string[], request: Request, cache: string): Promise<Response> {15 if (!deck || segments.length < 3 || `${segments[0]}/${segments[1]}` !== deck.dir) return notFoundResponse();16 const asset = deckAsset(deck, segments.slice(2).join("/"));17 const info = asset ? await stat(asset.path).catch(() => null) : null;18 if (!asset || !info?.isFile()) return notFoundResponse();19 const etag = `"${deck.hash.slice(0, 12)}-${info.size.toString(16)}"`;20 const headers: Record<string, string> = {21 "Content-Type": asset.type, "Cache-Control": cache, ETag: etag, "X-Content-Type-Options": "nosniff",22 "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", "Cross-Origin-Resource-Policy": "same-origin",23 };24 if (request.headers.get("if-none-match") === etag) return new Response(null, { status: 304, headers });25 if (request.method === "HEAD") return new Response(null, { status: 200, headers: { ...headers, "Content-Length": String(info.size) } });26 return new Response(Readable.toWeb(createReadStream(asset.path)) as ReadableStream, { status: 200, headers: { ...headers, "Content-Length": String(info.size) } });27}28