{"version":3,"file":"image-endpoint.mjs","names":[],"sources":["../../src/media/image-endpoint.ts"],"sourcesContent":["/**\n * Portable helpers shared by the platform image-endpoint modules.\n *\n * EmDash wraps Astro's image endpoint (`image.endpoint`) so that source bytes\n * for EmDash media are read straight from the storage adapter instead of being\n * fetched over HTTP. The platform endpoint modules (Node: sharp via\n * `astro:assets`; Cloudflare: the `IMAGES` binding) do the actual transform;\n * this module holds the platform-agnostic bits they share: recognizing an\n * EmDash media URL and validating transform query params.\n *\n * Kept free of `astro:*` / `virtual:emdash/*` imports so it stays in the\n * precompiled package and can be unit-tested directly.\n */\n\nimport { INTERNAL_MEDIA_PREFIX } from \"./normalize.js\";\n\n/** Output formats the wrapped endpoint can produce on Cloudflare. */\nexport const ALLOWED_TRANSFORM_FORMATS = [\"webp\", \"avif\", \"jpeg\", \"png\"] as const;\n\n/** Default output format -- broad support, strong compression. */\nexport const DEFAULT_TRANSFORM_FORMAT: ImageTransformFormat = \"webp\";\n\n/**\n * Default output quality for lossy formats (WebP/AVIF/JPEG) when the request\n * doesn't specify one. Matches the default Cloudflare applies to URL-based\n * image transformations. The Images *binding* applies no default of its own\n * and encodes near-losslessly when quality is omitted (a 2048px WebP comes\n * out ~900 KB instead of ~100 KB), so the endpoint sends an explicit quality\n * for lossy output. PNG is exempt: an explicit PNG quality switches the\n * binding to lossy PNG8, which is not a safe default for a lossless format.\n */\nexport const DEFAULT_TRANSFORM_QUALITY = 85;\n\n/** Upper bound for a requested dimension; caps the work a single request asks for. */\nexport const MAX_TRANSFORM_DIMENSION = 4000;\n\n/** A format string accepted by {@link ImageTransformOptions.format}. */\nexport type ImageTransformFormat = (typeof ALLOWED_TRANSFORM_FORMATS)[number];\n\n/** Validated options for a single transform. */\nexport interface ImageTransformOptions {\n\twidth?: number;\n\theight?: number;\n\tformat: ImageTransformFormat;\n\t/**\n\t * Explicitly-requested quality (1-100), or `undefined` when the request\n\t * carried no `q`. Callers apply their own default per format (see\n\t * {@link DEFAULT_TRANSFORM_QUALITY}); lossless PNG deliberately gets none.\n\t */\n\tquality?: number;\n}\n\n/** Long-lived immutable cache -- transform output is deterministic per key+params. */\nexport const IMMUTABLE_IMAGE_CACHE = \"public, max-age=31536000, immutable\";\n\n/**\n * Raster types safe to render inline. Anything else (SVG, PDF, ...) is served\n * as an attachment so it can't execute as an active document. Mirrors the\n * `/_emdash/api/media/file/{key}` route's allowlist.\n */\nconst SAFE_INLINE_IMAGE_TYPES = new Set([\n\t\"image/jpeg\",\n\t\"image/png\",\n\t\"image/gif\",\n\t\"image/webp\",\n\t\"image/avif\",\n\t\"image/x-icon\",\n]);\n\n/**\n * Headers for streaming **original** stored bytes (the no-transform fallback).\n * Carries the same stored-XSS protections as the media file route: a sandbox\n * CSP, `nosniff`, and `Content-Disposition: attachment` for anything not on the\n * inline raster allowlist (so a stored SVG can't run scripts in the site\n * origin). Transformed output is always generated raster and doesn't need this.\n */\nexport function originalMediaHeaders(contentType: string): Record<string, string> {\n\treturn {\n\t\t\"Content-Type\": contentType,\n\t\t\"Cache-Control\": IMMUTABLE_IMAGE_CACHE,\n\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\"Content-Security-Policy\":\n\t\t\t\"sandbox; default-src 'none'; img-src 'self'; style-src 'unsafe-inline'\",\n\t\t\"Content-Disposition\": SAFE_INLINE_IMAGE_TYPES.has(contentType) ? \"inline\" : \"attachment\",\n\t};\n}\n\n/** Storage keys safe to serve: the flat `{ulid}{ext}` shape, no slashes/traversal. */\nconst SAFE_STORAGE_KEY = /^[A-Za-z0-9._-]+$/;\n\n/** Plain decimal digits only -- rejects \"1e3\", \"0x10\", \"+5\", whitespace. */\nconst DECIMAL_DIGITS = /^\\d+$/;\n\n/** Whether a storage key is safe to resolve against the storage backend. */\nexport function isSafeTransformKey(key: string): boolean {\n\treturn SAFE_STORAGE_KEY.test(key);\n}\n\n/**\n * If `href` points at the internal EmDash media route\n * (`/_emdash/api/media/file/{key}`) with a safe key, return the key; otherwise\n * `null` (the endpoint then delegates to the stock image endpoint for bundled\n * assets, allowed remote, and `publicUrl` media).\n *\n * The component absolutizes same-origin media (Astro only optimizes absolute,\n * remote-allowed URLs), so `href` is typically `https://site/_emdash/...` but\n * may be relative. We match on the **pathname** only and never fetch `href` —\n * the key is read from our own storage — so the host is irrelevant and can't be\n * an SSRF vector. A dummy base resolves both absolute and relative forms and\n * strips any query/fragment.\n */\nexport function matchInternalMediaKey(href: string | null | undefined): string | null {\n\tif (!href) return null;\n\tlet pathname: string;\n\ttry {\n\t\tpathname = new URL(href, \"http://localhost\").pathname;\n\t} catch {\n\t\treturn null;\n\t}\n\tif (!pathname.startsWith(INTERNAL_MEDIA_PREFIX)) return null;\n\tconst key = pathname.slice(INTERNAL_MEDIA_PREFIX.length);\n\tif (!key || !isSafeTransformKey(key)) return null;\n\treturn key;\n}\n\n/** Type guard for {@link ImageTransformFormat}. */\nexport function isTransformFormat(value: string): value is ImageTransformFormat {\n\treturn (ALLOWED_TRANSFORM_FORMATS as readonly string[]).includes(value);\n}\n\n/** Outcome of parsing transform query params: validated options or an error. */\nexport type ParsedTransformParams =\n\t| { ok: true; options: ImageTransformOptions }\n\t| { ok: false; message: string };\n\n/**\n * Resolve the quality to send to the image binding for a transform. An\n * explicitly-requested quality always wins. Otherwise lossy formats\n * (WebP/AVIF/JPEG) get {@link DEFAULT_TRANSFORM_QUALITY} because the Images\n * binding encodes near-losslessly when quality is omitted; lossless PNG gets\n * `undefined` because an explicit PNG quality switches the binding to lossy\n * PNG8, which is not a safe default for a lossless format.\n */\nexport function resolveTransformQuality(\n\tformat: ImageTransformFormat,\n\trequested: number | undefined,\n): number | undefined {\n\tif (requested !== undefined) return requested;\n\treturn format === \"png\" ? undefined : DEFAULT_TRANSFORM_QUALITY;\n}\n\n/**\n * Parse and validate `?w=&h=&f=&q=` query params. Width is required (it sizes\n * the rendition); dimensions are bounded so a request can't ask for an\n * unbounded or nonsensical transform. Format falls back to\n * {@link DEFAULT_TRANSFORM_FORMAT} when not requested. `q` is validated when\n * present but otherwise left `undefined` so the caller can apply a per-format\n * default (lossy formats get one, lossless PNG does not — see\n * {@link DEFAULT_TRANSFORM_QUALITY}).\n */\nexport function parseTransformParams(params: URLSearchParams): ParsedTransformParams {\n\tconst width = parseDimension(params.get(\"w\"));\n\tif (width === null) return { ok: false, message: \"Invalid 'w' (width)\" };\n\tif (width === undefined) return { ok: false, message: \"Missing 'w' (width)\" };\n\n\tconst height = parseDimension(params.get(\"h\"));\n\tif (height === null) return { ok: false, message: \"Invalid 'h' (height)\" };\n\n\tconst formatRaw = params.get(\"f\");\n\tlet format: ImageTransformFormat = DEFAULT_TRANSFORM_FORMAT;\n\tif (formatRaw !== null) {\n\t\tif (!isTransformFormat(formatRaw)) {\n\t\t\treturn { ok: false, message: `Unsupported 'f' (format): ${formatRaw}` };\n\t\t}\n\t\tformat = formatRaw;\n\t}\n\n\tlet quality: number | undefined;\n\tconst qualityRaw = params.get(\"q\");\n\tif (qualityRaw !== null) {\n\t\tconst q = Number(qualityRaw);\n\t\tif (!Number.isInteger(q) || q < 1 || q > 100) {\n\t\t\treturn { ok: false, message: \"Invalid 'q' (quality), expected 1-100\" };\n\t\t}\n\t\tquality = q;\n\t}\n\n\treturn { ok: true, options: { width, height, format, quality } };\n}\n\n/**\n * Parse a dimension query value.\n * - `undefined`: param absent\n * - `null`: present but invalid (non-integer, out of range)\n * - `number`: valid, within [1, MAX_TRANSFORM_DIMENSION]\n */\nfunction parseDimension(raw: string | null): number | undefined | null {\n\tif (raw === null) return undefined;\n\tif (!DECIMAL_DIGITS.test(raw)) return null;\n\tconst n = Number(raw);\n\tif (n < 1 || n > MAX_TRANSFORM_DIMENSION) return null;\n\treturn n;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAa,4BAA4B;CAAC;CAAQ;CAAQ;CAAQ;CAAM;;AAGxE,MAAa,2BAAiD;;;;;;;;;;AAW9D,MAAa,4BAA4B;;AAGzC,MAAa,0BAA0B;;AAmBvC,MAAa,wBAA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