{"version":3,"file":"media-upload-C3YxCdag.mjs","names":["path"],"sources":["../src/api/handlers/media-upload.ts"],"sourcesContent":["/**\n * Programmatic media upload handler (MCP `media_upload` tool).\n *\n * Accepts file bytes as base64 or fetches them from an external URL\n * (SSRF-guarded), then runs the same pipeline as the multipart REST\n * upload route: allowlist + size validation, content-hash deduplication,\n * storage upload, image metadata enrichment, and record creation.\n */\n\nimport * as path from \"node:path\";\n\nimport type { Kysely } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { MediaRepository, type MediaItem } from \"../../database/repositories/media.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { enrichImageMetadata } from \"../../media/enrich.js\";\nimport { matchesMimeAllowlist, normalizeMime } from \"../../media/mime.js\";\nimport { SsrfError, ssrfSafeFetch } from \"../../security/ssrf.js\";\nimport type { Storage } from \"../../storage/types.js\";\nimport { decodeBase64Bytes } from \"../../utils/base64.js\";\nimport { computeContentHash } from \"../../utils/hash.js\";\nimport { CONTENT_TYPE_RE, DEFAULT_MAX_UPLOAD_SIZE, formatFileSize } from \"../schemas/media.js\";\nimport type { ApiResult } from \"../types.js\";\nimport { GLOBAL_UPLOAD_ALLOWLIST } from \"./media-allowlist.js\";\n\nexport interface MediaUploadInput {\n\t/** Original filename (e.g. 'logo.png'); the extension is kept on the storage key. */\n\tfilename: string;\n\t/** Base64-encoded file contents. Exactly one of `base64` / `url` must be set. */\n\tbase64?: string;\n\t/** External http(s) URL to fetch the file from. Exactly one of `base64` / `url` must be set. */\n\turl?: string;\n\t/**\n\t * MIME type. Required with `base64`; optional with `url` (falls back to\n\t * the response's Content-Type header).\n\t */\n\tcontentType?: string;\n\t/** Alt text stored on the media record. */\n\talt?: string;\n\tauthorId?: string;\n\t/** Upload size limit in bytes (defaults to DEFAULT_MAX_UPLOAD_SIZE). */\n\tmaxUploadSize?: number;\n}\n\nexport type MediaUploadResult = ApiResult<{\n\titem: MediaItem & { url: string };\n\tdeduplicated?: boolean;\n}>;\n\nfunction fail(code: string, message: string): MediaUploadResult {\n\treturn { success: false, error: { code, message } };\n}\n\n/** Same relative-URL shape the REST media routes return. */\nfunction withUrl(item: MediaItem): MediaItem & { url: string } {\n\treturn { ...item, url: `/_emdash/api/media/file/${item.storageKey}` };\n}\n\n/** Strip parameters from a Content-Type header value (e.g. '; charset=...'). */\nfunction bareMime(headerValue: string): string {\n\treturn (headerValue.split(\";\")[0] ?? \"\").trim();\n}\n\n/**\n * Acquire the file bytes and MIME type from either the base64 payload or\n * the external URL. Returns an error result on any validation failure.\n */\nasync function acquireBytes(\n\tinput: MediaUploadInput,\n\tmaxUploadSize: number,\n): Promise<{ bytes: Uint8Array; mimeType: string } | MediaUploadResult> {\n\tif (input.base64) {\n\t\tif (!input.contentType) {\n\t\t\treturn fail(\"VALIDATION_ERROR\", \"contentType is required when uploading base64 data\");\n\t\t}\n\t\t// Cheap size precheck on the encoded string (decoded size is ~3/4 of\n\t\t// the base64 length) before allocating the decoded buffer.\n\t\tif ((input.base64.length * 3) / 4 > maxUploadSize) {\n\t\t\treturn fail(\n\t\t\t\t\"PAYLOAD_TOO_LARGE\",\n\t\t\t\t`File exceeds maximum size of ${formatFileSize(maxUploadSize)}`,\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\treturn { bytes: decodeBase64Bytes(input.base64), mimeType: input.contentType };\n\t\t} catch {\n\t\t\treturn fail(\"VALIDATION_ERROR\", \"Invalid base64 data\");\n\t\t}\n\t}\n\n\t// url mode — the caller guarantees exactly one source, so url is set here\n\tconst url = input.url;\n\tif (!url) {\n\t\treturn fail(\"VALIDATION_ERROR\", \"Provide exactly one of 'base64' or 'url'\");\n\t}\n\tlet response: Response;\n\ttry {\n\t\tresponse = await ssrfSafeFetch(url, { headers: { accept: \"*/*\" } });\n\t} catch (error) {\n\t\tif (error instanceof SsrfError) {\n\t\t\treturn fail(\"VALIDATION_ERROR\", `URL not allowed: ${error.message}`);\n\t\t}\n\t\treturn fail(\"FETCH_ERROR\", \"Failed to fetch file from URL\");\n\t}\n\tif (!response.ok) {\n\t\treturn fail(\"FETCH_ERROR\", `Failed to fetch file from URL (HTTP ${response.status})`);\n\t}\n\n\tconst contentLength = response.headers.get(\"Content-Length\");\n\tif (contentLength && parseInt(contentLength, 10) > maxUploadSize) {\n\t\treturn fail(\n\t\t\t\"PAYLOAD_TOO_LARGE\",\n\t\t\t`File exceeds maximum size of ${formatFileSize(maxUploadSize)}`,\n\t\t);\n\t}\n\n\tconst mimeType = input.contentType ?? bareMime(response.headers.get(\"Content-Type\") ?? \"\");\n\tif (!mimeType) {\n\t\treturn fail(\"VALIDATION_ERROR\", \"Could not determine MIME type — pass contentType explicitly\");\n\t}\n\n\tconst bytes = new Uint8Array(await response.arrayBuffer());\n\treturn { bytes, mimeType };\n}\n\n/**\n * Upload a media file from base64 data or an external URL.\n *\n * Mirrors the REST `POST /_emdash/api/media` route: global MIME allowlist,\n * size limit, content-hash dedupe (returns the existing item with\n * `deduplicated: true`), storage upload with cleanup on failure, and\n * image metadata enrichment (dimensions, blurhash, dominant color).\n */\nexport async function handleMediaUpload(\n\tdb: Kysely<Database>,\n\tstorage: Storage,\n\tinput: MediaUploadInput,\n): Promise<MediaUploadResult> {\n\tif (!input.base64 === !input.url) {\n\t\treturn fail(\"VALIDATION_ERROR\", \"Provide exactly one of 'base64' or 'url'\");\n\t}\n\n\tconst rawMax = input.maxUploadSize ?? DEFAULT_MAX_UPLOAD_SIZE;\n\tif (!Number.isFinite(rawMax) || rawMax <= 0) {\n\t\treturn fail(\"CONFIGURATION_ERROR\", \"Invalid maxUploadSize configuration\");\n\t}\n\n\tconst acquired = await acquireBytes(input, rawMax);\n\tif (\"success\" in acquired) return acquired;\n\tconst { bytes } = acquired;\n\n\t// Validate the raw MIME string before normalize/allowlist: normalizeMime\n\t// only strips parameters and matchesMimeAllowlist only checks startsWith,\n\t// so without this a crafted value like \"image/png\\r\\nX-Evil: 1\" would\n\t// reach the storage backend's ContentType header and be echoed by the\n\t// media file serving route.\n\tif (!CONTENT_TYPE_RE.test(acquired.mimeType)) {\n\t\treturn fail(\"VALIDATION_ERROR\", \"Invalid content type\");\n\t}\n\tconst mimeType = normalizeMime(acquired.mimeType);\n\n\tif (!matchesMimeAllowlist(mimeType, GLOBAL_UPLOAD_ALLOWLIST)) {\n\t\treturn fail(\"INVALID_TYPE\", \"File type not allowed\");\n\t}\n\tif (bytes.byteLength > rawMax) {\n\t\treturn fail(\"PAYLOAD_TOO_LARGE\", `File exceeds maximum size of ${formatFileSize(rawMax)}`);\n\t}\n\n\ttry {\n\t\tconst contentHash = await computeContentHash(bytes);\n\t\tconst repo = new MediaRepository(db);\n\n\t\tconst existing = await repo.findByContentHash(contentHash);\n\t\tif (existing) {\n\t\t\treturn { success: true, data: { item: withUrl(existing), deduplicated: true } };\n\t\t}\n\n\t\tconst storageKey = `${ulid()}${path.extname(input.filename)}`;\n\t\tawait storage.upload({ key: storageKey, body: bytes, contentType: mimeType });\n\n\t\ttry {\n\t\t\tconst enriched = await enrichImageMetadata(bytes, mimeType);\n\t\t\tconst item = await repo.create({\n\t\t\t\tfilename: input.filename,\n\t\t\t\tmimeType,\n\t\t\t\tsize: bytes.byteLength,\n\t\t\t\twidth: enriched.width,\n\t\t\t\theight: enriched.height,\n\t\t\t\talt: input.alt,\n\t\t\t\tstorageKey,\n\t\t\t\tcontentHash,\n\t\t\t\tblurhash: enriched.blurhash,\n\t\t\t\tdominantColor: enriched.dominantColor,\n\t\t\t\tauthorId: input.authorId,\n\t\t\t});\n\t\t\treturn { success: true, data: { item: withUrl(item) } };\n\t\t} catch (error) {\n\t\t\t// Don't leave an orphaned object in storage when record creation fails\n\t\t\ttry {\n\t\t\t\tawait storage.delete(storageKey);\n\t\t\t} catch {\n\t\t\t\t// Ignore cleanup errors\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t} catch {\n\t\treturn fail(\"UPLOAD_ERROR\", \"Upload failed\");\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAS,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