import { randomUUID } from 'node:crypto' import mime from 'mime-types' import { canonicalContentType, contentTypeSpellings } from './contentTypes.js' import { UploadError } from './errors.js' /** * A fresh storage key: a random id plus the extension that matches * `mimeType`, when one is known. Keys never derive from the client's * filename. Aliased types are looked up under every spelling, so the * registered `video/matroska` gets the `.mkv` the database only knows for * `video/x-matroska`. */ export function generateStorageKey(mimeType: string): string { const ext = contentTypeSpellings(canonicalContentType(mimeType)) .map((type) => mime.extension(type)) .find(Boolean) return ext ? `${randomUUID()}.${ext}` : randomUUID() } const SAFE_KEY = /^[A-Za-z0-9][A-Za-z0-9._-]*$/ /** * Rejects keys that could escape a provider's root: path separators, `..`, * leading dots, and anything outside a conservative character set. Providers * that map keys onto a filesystem call this before touching disk. */ export function assertSafeKey(key: string) { if (!SAFE_KEY.test(key) || key.includes('..')) { throw new UploadError('INVALID_KEY', `Invalid storage key '${key}'.`) } } /** * Removes trailing slashes without a regex, which keeps the trim linear on * any input. */ export function trimTrailingSlashes(value: string): string { let end = value.length while (end > 0 && value[end - 1] === '/') { end -= 1 } return value.slice(0, end) }