surl.js 929 B

12345678910111213141516171819202122232425262728293031323334
  1. 'use strict';
  2. const escapeMap = {
  3. '"': '"',
  4. '<': '&lt;',
  5. '>': '&gt;',
  6. '\'': '&#x27;',
  7. };
  8. module.exports = function surl(val) {
  9. // Just get the converted the protocalWhiteList in `Set` mode,
  10. // Avoid conversions in `foreach`
  11. const protocolWhiteListSet = this.app.config.security._protocolWhiteListSet;
  12. if (typeof val !== 'string') return val;
  13. // only test on absolute path
  14. if (val[0] !== '/') {
  15. const arr = val.split('://', 2);
  16. const protocol = arr.length > 1 ? arr[0].toLowerCase() : '';
  17. if (protocol === '' || !protocolWhiteListSet.has(protocol)) {
  18. if (this.app.config.env === 'local') {
  19. this.ctx.coreLogger.warn('[egg-security:surl] url: %j, protocol: %j, ' +
  20. 'protocol is empty or not in white list, convert to empty string', val, protocol);
  21. }
  22. return '';
  23. }
  24. }
  25. return val.replace(/["'<>]/g, function(ch) {
  26. return escapeMap[ch];
  27. });
  28. };