manicanldes-backend/src/b2b/artwork-file.ts

53 lines
1.8 KiB
TypeScript

import { AppError } from '../common/errors/app-error';
import { fileDigest } from '../common/file-digest';
import type { UploadedDocument } from '../procurement/supplier-document-file';
export const MAX_ARTWORK_BYTES = 2 * 1024 * 1024;
const TYPES = {
pdf: 'application/pdf',
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
} as const;
export function inspectArtwork(file?: UploadedDocument) {
if (!file) throw new AppError('B2B_ARTWORK_FILE_REQUIRED');
if (file.buffer.length > MAX_ARTWORK_BYTES)
throw new AppError('B2B_ARTWORK_FILE_TOO_LARGE');
const name = file.originalname;
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,115}\.(pdf|png|jpg|jpeg)$/.test(name))
throw new AppError('B2B_ARTWORK_FILENAME_INVALID');
const extension = name.split('.').at(-1) as keyof typeof TYPES;
const bytes = file.buffer;
const valid =
extension === 'pdf'
? bytes.subarray(0, 5).equals(Buffer.from('%PDF-')) &&
bytes.subarray(-1024).includes(Buffer.from('%%EOF'))
: extension === 'png'
? bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')) &&
bytes.subarray(-8, -4).equals(Buffer.from('IEND'))
: bytes.subarray(0, 3).equals(Buffer.from('ffd8ff', 'hex')) &&
bytes.subarray(-2).equals(Buffer.from('ffd9', 'hex'));
if (
file.size !== bytes.length ||
!bytes.length ||
file.mimetype !== TYPES[extension] ||
!valid
)
throw new AppError('B2B_ARTWORK_FILE_INVALID');
return {
filename: name,
mimeType: TYPES[extension],
sha256: fileDigest(bytes),
size: bytes.length,
content: Uint8Array.from(bytes),
};
}
export function verifiedArtwork(content: Uint8Array, expectedHash: string) {
const bytes = Buffer.from(content);
if (fileDigest(bytes) !== expectedHash)
throw new AppError('B2B_ARTWORK_INTEGRITY_FAILURE');
return bytes;
}