validation.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. 'use strict';
  2. /**
  3. * Checks if a status code is allowed in a close frame.
  4. *
  5. * @param {Number} code The status code
  6. * @return {Boolean} `true` if the status code is valid, else `false`
  7. * @public
  8. */
  9. function isValidStatusCode(code) {
  10. return (
  11. (code >= 1000 &&
  12. code <= 1014 &&
  13. code !== 1004 &&
  14. code !== 1005 &&
  15. code !== 1006) ||
  16. (code >= 3000 && code <= 4999)
  17. );
  18. }
  19. /**
  20. * Checks if a given buffer contains only correct UTF-8.
  21. * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
  22. * Markus Kuhn.
  23. *
  24. * @param {Buffer} buf The buffer to check
  25. * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
  26. * @public
  27. */
  28. function _isValidUTF8(buf) {
  29. const len = buf.length;
  30. let i = 0;
  31. while (i < len) {
  32. if ((buf[i] & 0x80) === 0) {
  33. // 0xxxxxxx
  34. i++;
  35. } else if ((buf[i] & 0xe0) === 0xc0) {
  36. // 110xxxxx 10xxxxxx
  37. if (
  38. i + 1 === len ||
  39. (buf[i + 1] & 0xc0) !== 0x80 ||
  40. (buf[i] & 0xfe) === 0xc0 // Overlong
  41. ) {
  42. return false;
  43. }
  44. i += 2;
  45. } else if ((buf[i] & 0xf0) === 0xe0) {
  46. // 1110xxxx 10xxxxxx 10xxxxxx
  47. if (
  48. i + 2 >= len ||
  49. (buf[i + 1] & 0xc0) !== 0x80 ||
  50. (buf[i + 2] & 0xc0) !== 0x80 ||
  51. (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
  52. (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
  53. ) {
  54. return false;
  55. }
  56. i += 3;
  57. } else if ((buf[i] & 0xf8) === 0xf0) {
  58. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  59. if (
  60. i + 3 >= len ||
  61. (buf[i + 1] & 0xc0) !== 0x80 ||
  62. (buf[i + 2] & 0xc0) !== 0x80 ||
  63. (buf[i + 3] & 0xc0) !== 0x80 ||
  64. (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
  65. (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
  66. buf[i] > 0xf4 // > U+10FFFF
  67. ) {
  68. return false;
  69. }
  70. i += 4;
  71. } else {
  72. return false;
  73. }
  74. }
  75. return true;
  76. }
  77. try {
  78. let isValidUTF8 = require('utf-8-validate');
  79. /* istanbul ignore if */
  80. if (typeof isValidUTF8 === 'object') {
  81. isValidUTF8 = isValidUTF8.Validation.isValidUTF8; // utf-8-validate@<3.0.0
  82. }
  83. module.exports = {
  84. isValidStatusCode,
  85. isValidUTF8(buf) {
  86. return buf.length < 150 ? _isValidUTF8(buf) : isValidUTF8(buf);
  87. }
  88. };
  89. } catch (e) /* istanbul ignore next */ {
  90. module.exports = {
  91. isValidStatusCode,
  92. isValidUTF8: _isValidUTF8
  93. };
  94. }