import 'server-only'; import { encodeReviewPhoto, imageDimensions } from './image-processing'; export const MAX_UPLOAD_BYTES = 6 * 1024 * 1024; export const MAX_REQUEST_BYTES = MAX_UPLOAD_BYTES + 32 * 1024; export const MAX_PIXELS = 24_000_000; export const MAX_PROMPT = 1200; export const STUDIO_OUTPUT_LIMIT = 6 * 1024 * 1024; export type RasterMime = 'image/png' | 'image/jpeg' | 'image/webp'; export type StudioImage = { bytes: Buffer; mime: RasterMime }; export class StudioError extends Error { constructor(public code: string, public status: number, message: string) { super(message); } } export async function boundedBody( body: ReadableStream | null, limit: number, tooLarge: StudioError, ): Promise> { if (!body) return new Uint8Array(0); const reader = body.getReader(); const chunks: Uint8Array[] = []; let size = 0; try { while (true) { const { done, value } = await reader.read(); if (done) break; size += value.length; if (size > limit) { // Do not wait on the producer to honor cancellation. void reader.cancel().catch(() => {}); throw tooLarge; } chunks.push(value); } } finally { reader.releaseLock(); } const data = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { data.set(chunk, offset); offset += chunk.length; } return data; } export function imageMime(bytes: Buffer): RasterMime | null { if (bytes.length >= 24 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return 'image/png'; if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg'; if (bytes.length >= 16 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP') return 'image/webp'; return null; } function badImage() { return new StudioError('invalid_image', 400, 'Choose a valid JPG, PNG or WebP image, up to 6 MB and 24 megapixels.'); } async function acceptableDimensions(bytes: Buffer) { const { width, height } = await imageDimensions(bytes); return (width ?? 0) > 0 && (height ?? 0) > 0 && (width ?? 0) <= 10000 && (height ?? 0) <= 10000 && (width ?? 0) * (height ?? 0) <= MAX_PIXELS; } export async function rawUpload(file: File): Promise { if (!file.size || file.size > MAX_UPLOAD_BYTES) throw badImage(); const raw = Buffer.from(await file.arrayBuffer()); const mime = imageMime(raw); if (!mime || (file.type && file.type !== 'application/octet-stream' && file.type !== mime)) throw badImage(); return raw; } export async function cleanUpload(raw: Buffer): Promise { try { if (!await acceptableDimensions(raw)) throw badImage(); // Reuse the application's trusted image decoder to normalize the input; // strip location/EXIF, flatten animation and bound the provider token load. const bytes = await encodeReviewPhoto(raw); if (!bytes || !bytes.length || bytes.length > MAX_UPLOAD_BYTES) throw badImage(); return { bytes, mime: 'image/jpeg' }; } catch { throw badImage(); } } export async function providerRaster(base64: string): Promise { const failed = () => new StudioError('provider_unavailable', 502, 'The image model didn’t return a usable image. Try again later.'); if (!base64 || base64.length > Math.ceil(STUDIO_OUTPUT_LIMIT / 3) * 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) throw failed(); const bytes = Buffer.from(base64, 'base64'); const mime = imageMime(bytes); if (!mime || bytes.length > STUDIO_OUTPUT_LIMIT) throw failed(); try { if (!await acceptableDimensions(bytes)) throw failed(); } catch { throw failed(); } // Leave the provider image untouched. Lumen adds no watermark and does // not remove any provider provenance or other information. return { bytes, mime }; } export async function readStudioForm(req: Request) { const type = req.headers.get('content-type') ?? ''; if (!/^multipart\/form-data;\s*boundary=/i.test(type)) { throw new StudioError('invalid_request', 415, 'Send the studio request as a multipart form.'); } const huge = new StudioError('upload_too_large', 413, 'Choose an image under 6 MB.'); const length = req.headers.get('content-length'); if (length && (!/^\d+$/.test(length) || Number(length) > MAX_REQUEST_BYTES)) throw huge; const bytes = await boundedBody(req.body, MAX_REQUEST_BYTES, huge); let form: FormData; try { form = await new Response(bytes, { headers: { 'content-type': type } }).formData(); } catch { throw new StudioError('invalid_request', 400, 'The studio form could not be read.'); } if ([...form.keys()].some(key => !['action', 'prompt', 'model', 'image'].includes(key) || form.getAll(key).length !== 1)) { throw new StudioError('invalid_request', 400, 'The studio form contains unsupported fields.'); } return form; }