Branchwell

Lumen & Gesso / website · lumengesso.com / app / lib / studio-media.ts

1import 'server-only';
2import { encodeReviewPhoto, imageDimensions } from './image-processing';
3
4export const MAX_UPLOAD_BYTES = 6 * 1024 * 1024;
5export const MAX_REQUEST_BYTES = MAX_UPLOAD_BYTES + 32 * 1024;
6export const MAX_PIXELS = 24_000_000;
7export const MAX_PROMPT = 1200;
8export const STUDIO_OUTPUT_LIMIT = 6 * 1024 * 1024;
9
10export type RasterMime = 'image/png' | 'image/jpeg' | 'image/webp';
11export type StudioImage = { bytes: Buffer; mime: RasterMime };
12
13export class StudioError extends Error {
14 constructor(public code: string, public status: number, message: string) { super(message); }
15}
16
17export async function boundedBody(
18 body: ReadableStream<Uint8Array> | null,
19 limit: number,
20 tooLarge: StudioError,
21): Promise<Uint8Array<ArrayBuffer>> {
22 if (!body) return new Uint8Array(0);
23 const reader = body.getReader();
24 const chunks: Uint8Array[] = [];
25 let size = 0;
26 try {
27 while (true) {
28 const { done, value } = await reader.read();
29 if (done) break;
30 size += value.length;
31 if (size > limit) {
32 // Do not wait on the producer to honor cancellation.
33 void reader.cancel().catch(() => {});
34 throw tooLarge;
35 }
36 chunks.push(value);
37 }
38 } finally { reader.releaseLock(); }
39 const data = new Uint8Array(size);
40 let offset = 0;
41 for (const chunk of chunks) {
42 data.set(chunk, offset);
43 offset += chunk.length;
44 }
45 return data;
46}
47
48export function imageMime(bytes: Buffer): RasterMime | null {
49 if (bytes.length >= 24 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return 'image/png';
50 if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
51 if (bytes.length >= 16 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP') return 'image/webp';
52 return null;
53}
54
55function badImage() {
56 return new StudioError('invalid_image', 400, 'Choose a valid JPG, PNG or WebP image, up to 6 MB and 24 megapixels.');
57}
58
59async function acceptableDimensions(bytes: Buffer) {
60 const { width, height } = await imageDimensions(bytes);
61 return (width ?? 0) > 0 && (height ?? 0) > 0
62 && (width ?? 0) <= 10000 && (height ?? 0) <= 10000
63 && (width ?? 0) * (height ?? 0) <= MAX_PIXELS;
64}
65
66export async function rawUpload(file: File): Promise<Buffer> {
67 if (!file.size || file.size > MAX_UPLOAD_BYTES) throw badImage();
68 const raw = Buffer.from(await file.arrayBuffer());
69 const mime = imageMime(raw);
70 if (!mime || (file.type && file.type !== 'application/octet-stream' && file.type !== mime)) throw badImage();
71 return raw;
72}
73
74export async function cleanUpload(raw: Buffer): Promise<StudioImage> {
75 try {
76 if (!await acceptableDimensions(raw)) throw badImage();
77 // Reuse the application's trusted image decoder to normalize the input;
78 // strip location/EXIF, flatten animation and bound the provider token load.
79 const bytes = await encodeReviewPhoto(raw);
80 if (!bytes || !bytes.length || bytes.length > MAX_UPLOAD_BYTES) throw badImage();
81 return { bytes, mime: 'image/jpeg' };
82 } catch { throw badImage(); }
83}
84
85export async function providerRaster(base64: string): Promise<StudioImage> {
86 const failed = () => new StudioError('provider_unavailable', 502, 'The image model didn’t return a usable image. Try again later.');
87 if (!base64 || base64.length > Math.ceil(STUDIO_OUTPUT_LIMIT / 3) * 4
88 || !/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) throw failed();
89 const bytes = Buffer.from(base64, 'base64');
90 const mime = imageMime(bytes);
91 if (!mime || bytes.length > STUDIO_OUTPUT_LIMIT) throw failed();
92 try {
93 if (!await acceptableDimensions(bytes)) throw failed();
94 } catch { throw failed(); }
95 // Leave the provider image untouched. Lumen adds no watermark and does
96 // not remove any provider provenance or other information.
97 return { bytes, mime };
98}
99
100export async function readStudioForm(req: Request) {
101 const type = req.headers.get('content-type') ?? '';
102 if (!/^multipart\/form-data;\s*boundary=/i.test(type)) {
103 throw new StudioError('invalid_request', 415, 'Send the studio request as a multipart form.');
104 }
105 const huge = new StudioError('upload_too_large', 413, 'Choose an image under 6 MB.');
106 const length = req.headers.get('content-length');
107 if (length && (!/^\d+$/.test(length) || Number(length) > MAX_REQUEST_BYTES)) throw huge;
108 const bytes = await boundedBody(req.body, MAX_REQUEST_BYTES, huge);
109 let form: FormData;
110 try { form = await new Response(bytes, { headers: { 'content-type': type } }).formData(); }
111 catch { throw new StudioError('invalid_request', 400, 'The studio form could not be read.'); }
112 if ([...form.keys()].some(key => !['action', 'prompt', 'model', 'image'].includes(key)
113 || form.getAll(key).length !== 1)) {
114 throw new StudioError('invalid_request', 400, 'The studio form contains unsupported fields.');
115 }
116 return form;
117}