File size: 1,336 Bytes
4d27410
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const HttpError = require('./httpError');

const MAX_PROFILE_IMAGE_BYTES = 2 * 1024 * 1024;
const PROFILE_IMAGE_PATTERN =
  /^data:image\/(png|jpe?g|webp);base64,([A-Za-z0-9+/=]+)$/i;

function normalizeProfileImageDataUrl(rawValue) {
  if (rawValue === undefined) {
    return undefined;
  }

  if (rawValue === null || String(rawValue).trim() === '') {
    return null;
  }

  const normalizedValue = String(rawValue).trim();
  const match = normalizedValue.match(PROFILE_IMAGE_PATTERN);

  if (!match) {
    throw new HttpError(
      400,
      'profileImageUrl must be a valid base64 data URL (png, jpg, jpeg, webp).',
      'INVALID_PROFILE_IMAGE',
    );
  }

  const fileFormat = String(match[1] || '').toLowerCase();
  const canonicalFormat = fileFormat === 'jpg' ? 'jpeg' : fileFormat;

  const imageBuffer = Buffer.from(match[2], 'base64');

  if (!imageBuffer.length) {
    throw new HttpError(
      400,
      'profileImageUrl contains empty image data.',
      'INVALID_PROFILE_IMAGE',
    );
  }

  if (imageBuffer.length > MAX_PROFILE_IMAGE_BYTES) {
    throw new HttpError(
      413,
      'Profile image must be 2 MB or smaller.',
      'PROFILE_IMAGE_TOO_LARGE',
    );
  }

  return `data:image/${canonicalFormat};base64,${imageBuffer.toString('base64')}`;
}

module.exports = {
  normalizeProfileImageDataUrl,
};