import { createHash, randomUUID } from 'node:crypto'; import { Readable } from 'node:stream'; import sharp from 'sharp'; import { env } from '../config/env'; import type { Attachment, ImageType, User } from '../domain/models'; import { notFound, payloadTooLarge, unavailable, unsupportedMediaType } from '../errors/api-error'; import { logger } from '../config/logger'; import { db } from '../repositories/postgres'; import { deleteOriginal, getOriginal, putOriginal } from '../repositories/s3'; import { parseWith } from '../validation/parse'; import { uuidSchema } from '../validation/schemas'; type AttachmentRow = Pick & { object_key: string }; interface UploadTarget { chatId: string; filename: string; contentType: ImageType; } const attachmentFields = ` a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.created_at, a.object_key `; function publicMetadata({ object_key: _key, ...row }: AttachmentRow): Attachment { return { ...row, status: 'ready', variants: [], error_code: null, updated_at: row.created_at }; } async function validateImage(data: Buffer, mediaType: ImageType): Promise { const expected = mediaType === 'image/png' ? 'png' : 'jpeg'; let metadata: sharp.Metadata; try { // Reading metadata probes the header without decompressing the pixel array. metadata = await sharp(data, { limitInputPixels: false, failOn: 'warning' }).metadata(); } catch { throw unsupportedMediaType(); } const { format, width, height } = metadata; if (format !== expected || !width || !height) throw unsupportedMediaType(); if (width > Math.floor(env.MAX_IMAGE_PIXELS / height)) { throw payloadTooLarge('Размер изображения превышает лимит пикселей'); } try { await sharp(data, { limitInputPixels: env.MAX_IMAGE_PIXELS, failOn: 'warning' }).stats(); } catch { throw unsupportedMediaType(); } } export async function saveAttachment(actor: User, target: UploadTarget, bytes: Buffer): Promise { if (bytes.length === 0) throw unsupportedMediaType(); await validateImage(bytes, target.contentType); const sha256 = createHash('sha256').update(bytes).digest('hex'); const key = `originals/${randomUUID()}`; try { await putOriginal(key, bytes, target.contentType); } catch { throw unavailable('Хранилище вложений временно недоступно'); } try { const { rows } = await db.query( `INSERT INTO attachments AS a (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING ${attachmentFields}`, [target.chatId, actor.id, target.filename, target.contentType, bytes.length, sha256, key], ); if (!rows[0]) throw new Error('Attachment not returned'); return publicMetadata(rows[0]); } catch (error) { const sqlState = (error as { code?: string } | undefined)?.code ?? ''; // Keep the object if a lost connection leaves the commit outcome uncertain. if (/^(22...|23...|57014)$/.test(sqlState)) { await deleteOriginal(key).catch(() => logger.warn('attachment compensation failed')); } throw error; } } async function requireAttachment(actor: User, attachmentId: string): Promise { const id = parseWith(uuidSchema, attachmentId); const { rows } = await db.query( `SELECT ${attachmentFields} FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id WHERE a.id = $1 AND m.user_id = $2`, [id, actor.id], ); if (!rows[0]) throw notFound(); return rows[0]; } export async function attachmentMetadata(actor: User, id: string): Promise { return publicMetadata(await requireAttachment(actor, id)); } export async function downloadAttachment(actor: User, id: string, variant: string) { const row = await requireAttachment(actor, id); if (variant !== 'original') throw notFound(); try { const { Body, ContentLength } = await getOriginal(row.object_key); if (!(Body instanceof Readable) || ContentLength !== row.size_bytes) { if (Body instanceof Readable) Body.destroy(); throw new Error('Original missing or storage length mismatch'); } return { content: Body, contentType: row.content_type, size: row.size_bytes }; } catch { throw unavailable('Оригинал вложения временно недоступен'); } }