智慧水务管理系统 - 精河县供水工程综合管理平台

sanitizeHeaderValue.js 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict';
  2. import utils from '../utils.js';
  3. function trimSPorHTAB(str) {
  4. let start = 0;
  5. let end = str.length;
  6. while (start < end) {
  7. const code = str.charCodeAt(start);
  8. if (code !== 0x09 && code !== 0x20) {
  9. break;
  10. }
  11. start += 1;
  12. }
  13. while (end > start) {
  14. const code = str.charCodeAt(end - 1);
  15. if (code !== 0x09 && code !== 0x20) {
  16. break;
  17. }
  18. end -= 1;
  19. }
  20. return start === 0 && end === str.length ? str : str.slice(start, end);
  21. }
  22. // The control-code ranges are intentional: header sanitization strips C0/DEL bytes.
  23. // eslint-disable-next-line no-control-regex
  24. const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+', 'g');
  25. // eslint-disable-next-line no-control-regex
  26. const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+', 'g');
  27. function sanitizeValue(value, invalidChars) {
  28. if (utils.isArray(value)) {
  29. return value.map((item) => sanitizeValue(item, invalidChars));
  30. }
  31. return trimSPorHTAB(String(value).replace(invalidChars, ''));
  32. }
  33. export const sanitizeHeaderValue = (value) =>
  34. sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);
  35. export const sanitizeByteStringHeaderValue = (value) =>
  36. sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);
  37. export function toByteStringHeaderObject(headers) {
  38. const byteStringHeaders = Object.create(null);
  39. utils.forEach(headers.toJSON(), (value, header) => {
  40. byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);
  41. });
  42. return byteStringHeaders;
  43. }