|
| 1 | +/** |
| 2 | + * Public media hosting for Public/Open spaces. Serves the PLAINTEXT bytes of a file at a stable, |
| 3 | + * unauthenticated URL — /p/<slug> (an optional trailing /<name> is cosmetic, so consumers that |
| 4 | + * sniff the extension are happy). Built for embedding raw images/videos on other sites: |
| 5 | + * |
| 6 | + * - no auth, no decryption → fast; |
| 7 | + * - HTTP range requests (206) so <video>/<audio> seeking works; |
| 8 | + * - long immutable caching (each slug maps to one, never-rewritten blob) + ETag revalidation; |
| 9 | + * - permissive CORS (Access-Control-Allow-Origin: *) so cross-origin fetch/canvas use works too. |
| 10 | + * |
| 11 | + * Mounted OUTSIDE the browser CORS scope (like WebDAV) so the wildcard CORS here isn't overridden. |
| 12 | + */ |
| 13 | +import type { FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify'; |
| 14 | +import { prisma } from '../db.js'; |
| 15 | + |
| 16 | +const ONE_YEAR = 31_536_000; |
| 17 | + |
| 18 | +/** Parse a single-range `Range: bytes=…` header against a known size. Returns null if absent, |
| 19 | + * or 'invalid' if present but unsatisfiable. */ |
| 20 | +function parseRange(header: string | undefined, size: number): { start: number; end: number } | null | 'invalid' { |
| 21 | + if (!header) return null; |
| 22 | + const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim()); |
| 23 | + if (!m) return 'invalid'; |
| 24 | + const [, rawStart, rawEnd] = m; |
| 25 | + let start: number; |
| 26 | + let end: number; |
| 27 | + if (rawStart === '') { |
| 28 | + // Suffix range: last N bytes. |
| 29 | + const n = Number(rawEnd); |
| 30 | + if (!n) return 'invalid'; |
| 31 | + start = Math.max(0, size - n); |
| 32 | + end = size - 1; |
| 33 | + } else { |
| 34 | + start = Number(rawStart); |
| 35 | + end = rawEnd === '' ? size - 1 : Math.min(Number(rawEnd), size - 1); |
| 36 | + } |
| 37 | + if (Number.isNaN(start) || Number.isNaN(end) || start > end || start >= size) return 'invalid'; |
| 38 | + return { start, end }; |
| 39 | +} |
| 40 | + |
| 41 | +export const publicMediaRoutes: FastifyPluginAsync = async (app) => { |
| 42 | + async function serve(req: FastifyRequest, reply: FastifyReply) { |
| 43 | + const { slug } = req.params as { slug: string }; |
| 44 | + const file = await prisma.fileObject.findFirst({ |
| 45 | + where: { publicSlug: slug, encMode: 'PUBLIC', deletedAt: null }, |
| 46 | + }); |
| 47 | + |
| 48 | + // Common headers (also on 404 so cross-origin callers get a clean answer). CORP must be |
| 49 | + // overridden to cross-origin, otherwise Helmet's global same-origin value blocks other sites |
| 50 | + // from embedding the media in <img>/<video>. |
| 51 | + reply.header('Access-Control-Allow-Origin', '*').header('Cross-Origin-Resource-Policy', 'cross-origin'); |
| 52 | + if (!file) return reply.code(404).header('Cache-Control', 'no-store').send('Not found'); |
| 53 | + |
| 54 | + const size = Number(file.sizeBytes); |
| 55 | + const etag = file.sha256 ? `"${file.sha256}"` : undefined; |
| 56 | + |
| 57 | + reply |
| 58 | + .header('Content-Type', file.mimeType) |
| 59 | + .header('Accept-Ranges', 'bytes') |
| 60 | + .header('Cache-Control', `public, max-age=${ONE_YEAR}, immutable`) |
| 61 | + .header('Content-Disposition', `inline; filename="${encodeURIComponent(file.name)}"`); |
| 62 | + if (etag) reply.header('ETag', etag); |
| 63 | + |
| 64 | + // Conditional request: unchanged → 304 (no body). |
| 65 | + if (etag && req.headers['if-none-match'] === etag) { |
| 66 | + return reply.code(304).send(); |
| 67 | + } |
| 68 | + |
| 69 | + const range = parseRange(req.headers.range, size); |
| 70 | + if (range === 'invalid') { |
| 71 | + return reply.code(416).header('Content-Range', `bytes */${size}`).send('Range Not Satisfiable'); |
| 72 | + } |
| 73 | + |
| 74 | + if (range) { |
| 75 | + const length = range.end - range.start + 1; |
| 76 | + reply |
| 77 | + .code(206) |
| 78 | + .header('Content-Range', `bytes ${range.start}-${range.end}/${size}`) |
| 79 | + .header('Content-Length', length); |
| 80 | + if (req.method === 'HEAD') return reply.send(); |
| 81 | + return reply.send(app.ctx.storage.createReadStream(file.storageKey, { start: range.start, end: range.end })); |
| 82 | + } |
| 83 | + |
| 84 | + reply.header('Content-Length', size); |
| 85 | + if (req.method === 'HEAD') return reply.send(); |
| 86 | + return reply.send(app.ctx.storage.createReadStream(file.storageKey)); |
| 87 | + } |
| 88 | + |
| 89 | + // Preflight for cross-origin fetch/XHR use (plain <img>/<video> loads need no preflight). |
| 90 | + const preflight = (_req: FastifyRequest, reply: FastifyReply) => |
| 91 | + reply |
| 92 | + .header('Access-Control-Allow-Origin', '*') |
| 93 | + .header('Cross-Origin-Resource-Policy', 'cross-origin') |
| 94 | + .header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS') |
| 95 | + .header('Access-Control-Max-Age', '86400') |
| 96 | + .code(204) |
| 97 | + .send(); |
| 98 | + |
| 99 | + app.get('/:slug', serve); |
| 100 | + app.get('/:slug/:name', serve); // cosmetic filename (nice extension in the URL) |
| 101 | + app.options('/:slug', preflight); |
| 102 | + app.options('/:slug/:name', preflight); |
| 103 | +}; |
0 commit comments