SPB Git

Repository Public

media-http.ts 6.8 KB 108 lines typescript

1import type { IncomingMessage, ServerResponse } from "node:http";2import { pipeline } from "node:stream";3import { sql } from "@/lib/db";4import { SESSION_COOKIE, userFromToken } from "@/lib/session-store";5import { keys, storage, THUMB_SIZES } from "./storage";6import { parseRange } from "./range";7import { env } from "@/lib/env";89/**10 * Private media delivery, served by the Node HTTP server itself (server.ts) rather than by a Next route handler:11 * Next strips Content-Length from handler responses, and a media element needs exact Content-Length /12 * Content-Range framing to seek. Same session cookie, same database check as every other route.13 *14 *   GET|HEAD /api/v1/stream/<track uuid>[?v=compat]   audio, HTTP Range supported (206)15 *   GET|HEAD /api/v1/art/<artwork uuid>[?s=96|320|640|orig]16 *17 * A track is addressed by its opaque id only; the file is resolved from media_assets and streamed from disk.18 */19const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;20const SECURITY: Record<string, string> = {21  "X-Content-Type-Options": "nosniff", "Referrer-Policy": "same-origin", "X-Frame-Options": "DENY",22  "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'", "Strict-Transport-Security": "max-age=31536000; includeSubDomains",23  "Cross-Origin-Resource-Policy": "same-origin",24};2526function sessionToken(req: IncomingMessage): string | null {27  for (const part of (req.headers.cookie ?? "").split(";")) {28    const i = part.indexOf("=");29    if (i > 0 && part.slice(0, i).trim() === SESSION_COOKIE) return decodeURIComponent(part.slice(i + 1).trim());30  }31  return null;32}33function end(res: ServerResponse, status: number, code?: string, headers: Record<string, string> = {}) {34  const body = code ? JSON.stringify({ error: { code } }) : "";35  res.writeHead(status, { ...SECURITY, "Cache-Control": "no-store", ...(code ? { "Content-Type": "application/json", "Content-Length": String(Buffer.byteLength(body)) } : { "Content-Length": "0" }), ...headers });36  res.end(res.req.method === "HEAD" ? undefined : body);37}3839/** Returns true when the request was a media request (and has been answered). */40export async function handleMedia(req: IncomingMessage, res: ServerResponse): Promise<boolean> {41  const url = new URL(req.url ?? "/", "http://local");42  if (url.pathname === "/.well-known/apple-app-site-association") return appSiteAssociation(req, res);43  const m = url.pathname.match(/^\/api\/v1\/(stream|art)\/([^/]+)$/);44  if (!m) return false;45  try {46    if (req.method !== "GET" && req.method !== "HEAD") { end(res, 405, "method_not_allowed", { Allow: "GET, HEAD" }); return true; }47    if (!(await userFromToken(sessionToken(req)))) { end(res, 401, "unauthenticated"); return true; }48    if (!UUID.test(m[2])) { end(res, 404, "not_found"); return true; }49    if (m[1] === "stream") await stream(req, res, m[2], url.searchParams.get("v") === "compat");50    else await art(req, res, m[2], url.searchParams.get("s") ?? "320");51  } catch (e) {52    console.error("[media]", e instanceof Error ? `${e.name}: ${e.message}` : String(e));53    if (!res.headersSent) end(res, 500, "internal"); else res.destroy();54  }55  return true;56}5758async function send(req: IncomingMessage, res: ServerResponse, key: string, size: number, status: number, headers: Record<string, string>, range?: { start: number; end: number }) {59  res.writeHead(status, { ...SECURITY, ...headers });60  if (req.method === "HEAD") return void res.end();61  // pipeline() destroys the file stream when the listener seeks away or closes the tab mid-download.62  pipeline(storage().read(key, range), res, () => {});63}6465async function stream(req: IncomingMessage, res: ServerResponse, trackId: string, compat: boolean) {66  const kind = compat ? "rendition" : "original";67  const [a] = await sql<{ id: string; storage_key: string; mime: string }[]>`SELECT id, storage_key, mime FROM media_assets WHERE track_id = ${trackId} AND kind = ${kind}`;68  if (!a) return end(res, 404, compat ? "rendition_missing" : "not_found");69  const size = await storage().size(a.storage_key);70  if (size === null) return end(res, 404, "file_unavailable");            // row present, file missing on the volume71  const etag = `"${a.id}"`;72  const base: Record<string, string> = {73    "Content-Type": a.mime, "Accept-Ranges": "bytes", ETag: etag, "Content-Disposition": "inline", Vary: "Cookie",74    // Private cache only, revalidated against the ETag: a replaced file (new asset id) is never served stale.75    "Cache-Control": "private, no-cache, no-transform",76  };77  const h = req.headers;78  if (h["if-none-match"] === etag && !h.range) { res.writeHead(304, { ...SECURITY, ...base }); return void res.end(); }79  const range = parseRange(h["if-range"] && h["if-range"] !== etag ? null : (h.range ?? null), size);80  if (range === "invalid") { res.writeHead(416, { ...SECURITY, ...base, "Content-Range": `bytes */${size}`, "Content-Length": "0" }); return void res.end(); }81  if (range) return send(req, res, a.storage_key, size, 206, { ...base, "Content-Length": String(range.end - range.start + 1), "Content-Range": `bytes ${range.start}-${range.end}/${size}` }, range);82  return send(req, res, a.storage_key, size, 200, { ...base, "Content-Length": String(size) });83}8485async function art(req: IncomingMessage, res: ServerResponse, artworkId: string, s: string) {86  const [w] = await sql<{ sha256: string; mime: string }[]>`SELECT sha256, mime FROM artworks WHERE id = ${artworkId}`;87  if (!w) return end(res, 404, "not_found");88  const thumb = THUMB_SIZES.find((t) => String(t) === s);89  const key = thumb ? keys.artThumb(w.sha256, thumb) : s === "orig" ? keys.artOriginal(w.sha256, w.mime === "image/jpeg" ? "jpg" : w.mime.slice(6)) : null;90  const size = key ? await storage().size(key) : null;91  if (!key || size === null) return end(res, 404, "not_found");92  // An artwork id names one immutable image (content-addressed), so the private cache may keep it.93  return send(req, res, key, size, 200, { "Content-Type": thumb ? "image/jpeg" : w.mime, "Content-Length": String(size), "Cache-Control": "private, max-age=31536000, immutable", Vary: "Cookie" });94}9596/**97 * Lets the native apps listed in APPLE_APP_IDS use this site's passkeys (AuthenticationServices checks this file,98 * fetched through Apple's CDN, before it offers a credential of this RP ID to the app). Public by design: it holds99 * application identifiers only.100 */101function appSiteAssociation(req: IncomingMessage, res: ServerResponse): true {102  if (req.method !== "GET" && req.method !== "HEAD") { end(res, 405, "method_not_allowed", { Allow: "GET, HEAD" }); return true; }103  const body = JSON.stringify({ webcredentials: { apps: env.appleAppIds } });104  res.writeHead(200, { "Content-Type": "application/json", "Content-Length": String(Buffer.byteLength(body)), "Cache-Control": "public, max-age=3600", "X-Content-Type-Options": "nosniff" });105  res.end(req.method === "HEAD" ? undefined : body);106  return true;107}108
Files main
Menu

Theme