import pngjs from 'pngjs'; import { SystemError } from './errors.js'; const MAX_ICON_BYTES = 1024 * 1024; export function validateCaseIcon(value) { if (value === null || value === '') return null; if (typeof value !== 'string' || value.length > 22 + 4 * Math.ceil(MAX_ICON_BYTES / 3)) throw new SystemError(400, 'Иконка должна быть PNG до 1 МБ.'); const match = /^data:image\/png;base64,([A-Za-z0-9+/]+={0,2})$/.exec(value); if (!match) throw new SystemError(400, 'Иконка должна быть в формате PNG.'); const buffer = Buffer.from(match[1], 'base64'); const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); if ( buffer.length < 24 || buffer.length > MAX_ICON_BYTES || !buffer.subarray(0, 8).equals(signature) || buffer.toString('ascii', 12, 16) !== 'IHDR' ) throw new SystemError(400, 'Некорректный PNG-файл.'); const width = buffer.readUInt32BE(16), height = buffer.readUInt32BE(20); if (!width || !height || width > 1024 || height > 1024) throw new SystemError(400, 'Размер иконки — не более 1024 × 1024 пикселей.'); try { pngjs.PNG.sync.read(buffer); } catch (error) { throw new SystemError(400, 'Не удалось прочитать PNG-файл.'); } return 'data:image/png;base64,' + buffer.toString('base64'); }