estimateDataURLDecodedBytes.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. /**
  2. * Estimate data: URL byte lengths *without* allocating large buffers.
  3. * - Fetch percent-decodes a base64 body before decoding it.
  4. * - Node's Buffer.from(body, 'base64') sizes its backing allocation from the
  5. * percent-decoded body, including ignored characters and content after padding.
  6. * - Non-base64 data is percent-decoded and then encoded as UTF-8.
  7. */
  8. const isHexDigit = (charCode) =>
  9. (charCode >= 48 && charCode <= 57) ||
  10. (charCode >= 65 && charCode <= 70) ||
  11. (charCode >= 97 && charCode <= 102);
  12. const isPercentEncodedByte = (str, i, len) =>
  13. i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2));
  14. const hexValue = (charCode) => (charCode <= 57 ? charCode - 48 : (charCode & 0xdf) - 55);
  15. const isBase64Char = (charCode) =>
  16. (charCode >= 65 && charCode <= 90) || // A-Z
  17. (charCode >= 97 && charCode <= 122) || // a-z
  18. (charCode >= 48 && charCode <= 57) || // 0-9
  19. charCode === 43 || // +
  20. charCode === 47 || // /
  21. charCode === 45 || // - (base64url)
  22. charCode === 95; // _ (base64url)
  23. const isBase64Whitespace = (charCode) =>
  24. charCode === 9 || charCode === 10 || charCode === 12 || charCode === 13 || charCode === 32;
  25. const base64Bytes = (significant) => {
  26. const groups = Math.floor(significant / 4);
  27. const remainder = significant % 4;
  28. return groups * 3 + (remainder === 2 ? 1 : remainder === 3 ? 2 : 0);
  29. };
  30. // Buffer.byteLength(body, 'base64') uses the raw string length as an allocation
  31. // upper bound even when Buffer.from later ignores characters or stops at '='.
  32. const estimateBase64BufferAllocation = (body) => {
  33. const len = body.length;
  34. let padding = 0;
  35. if (len > 0 && body.charCodeAt(len - 1) === 61 /* '=' */) {
  36. padding++;
  37. if (len > 1 && body.charCodeAt(len - 2) === 61 /* '=' */) {
  38. padding++;
  39. }
  40. }
  41. return Math.floor(((len - padding) * 3) / 4);
  42. };
  43. const estimatePercentDecodedBase64BufferAllocation = (body) => {
  44. // Ordinary Base64 needs only its length and trailing padding.
  45. if (body.indexOf('%') === -1) {
  46. return estimateBase64BufferAllocation(body);
  47. }
  48. let length = 0;
  49. let previous = 0;
  50. let last = 0;
  51. for (let i = 0, len = body.length; i < len; i++) {
  52. let code = body.charCodeAt(i);
  53. if (code === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
  54. code = hexValue(body.charCodeAt(i + 1)) * 16 + hexValue(body.charCodeAt(i + 2));
  55. i += 2;
  56. }
  57. length++;
  58. previous = last;
  59. last = code;
  60. }
  61. const padding = last === 61 ? (previous === 61 ? 2 : 1) : 0;
  62. return Math.floor(((length - padding) * 3) / 4);
  63. };
  64. const estimatePercentDecodedBase64Bytes = (body) => {
  65. const len = body.length;
  66. let significant = 0;
  67. let padding = 0;
  68. let invalid = false;
  69. for (let i = 0; i < len; i++) {
  70. let code = body.charCodeAt(i);
  71. if (code === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
  72. code = hexValue(body.charCodeAt(i + 1)) * 16 + hexValue(body.charCodeAt(i + 2));
  73. i += 2;
  74. }
  75. if (isBase64Whitespace(code)) {
  76. continue;
  77. }
  78. if (code === 61 /* '=' */) {
  79. padding++;
  80. continue;
  81. }
  82. if (!isBase64Char(code) || padding > 0) {
  83. invalid = true;
  84. continue;
  85. }
  86. significant++;
  87. }
  88. // Fetch rejects malformed forgiving-base64 input. Returning the raw-size
  89. // allocation bound keeps that invalid input from becoming a pre-check bypass.
  90. if (
  91. invalid ||
  92. padding > 2 ||
  93. (padding > 0 && (significant + padding) % 4 !== 0) ||
  94. significant % 4 === 1
  95. ) {
  96. return estimateBase64BufferAllocation(body);
  97. }
  98. return base64Bytes(significant);
  99. };
  100. const estimateDataURLBytes = (url, estimateBase64, base64Pattern) => {
  101. if (!url || typeof url !== 'string') return 0;
  102. if (!/^data:/i.test(url)) return 0;
  103. const comma = url.indexOf(',');
  104. if (comma < 0) return 0;
  105. const meta = url.slice(5, comma);
  106. const body = url.slice(comma + 1);
  107. const isBase64 = base64Pattern.test(meta);
  108. if (isBase64) {
  109. return estimateBase64(body);
  110. }
  111. // Compute UTF-8 byte length directly from UTF-16 code units without allocating
  112. // a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies).
  113. // Valid %XX triplets count as one decoded byte; this matches the bytes that
  114. // decodeURIComponent(body) would produce before Buffer re-encodes the string.
  115. let bytes = 0;
  116. for (let i = 0, len = body.length; i < len; i++) {
  117. const c = body.charCodeAt(i);
  118. if (c === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
  119. bytes += 1;
  120. i += 2;
  121. } else if (c < 0x80) {
  122. bytes += 1;
  123. } else if (c < 0x800) {
  124. bytes += 2;
  125. } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) {
  126. const next = body.charCodeAt(i + 1);
  127. if (next >= 0xdc00 && next <= 0xdfff) {
  128. bytes += 4;
  129. i++;
  130. } else {
  131. bytes += 3;
  132. }
  133. } else {
  134. bytes += 3;
  135. }
  136. }
  137. return bytes;
  138. };
  139. /**
  140. * Estimate the percent-decoded payload size used by Fetch data: URLs.
  141. *
  142. * @param {string} url
  143. * @returns {number}
  144. */
  145. export default function estimateDataURLDecodedBytes(url) {
  146. // Fetch removes URL fragments before processing a data: URL.
  147. const fragmentIndex = typeof url === 'string' ? url.indexOf('#') : -1;
  148. return estimateDataURLBytes(
  149. fragmentIndex === -1 ? url : url.slice(0, fragmentIndex),
  150. estimatePercentDecodedBase64Bytes,
  151. /; *base64[\t\n\f\r ]*$/i
  152. );
  153. }
  154. /**
  155. * Estimate the Buffer backing allocation used after Node's percent-decoding step.
  156. *
  157. * @param {string} url
  158. * @returns {number}
  159. */
  160. export function estimateDataURLBufferAllocation(url) {
  161. // Match fromDataURI's case-insensitive protocol and encoding suffix.
  162. return estimateDataURLBytes(url, estimatePercentDecodedBase64BufferAllocation, /;base64$/i);
  163. }