index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**!
  2. * jsonp-body - index.js
  3. *
  4. * Copyright(c) fengmk2 and other contributors.
  5. * MIT Licensed
  6. *
  7. * Authors:
  8. * fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
  9. */
  10. 'use strict';
  11. /**
  12. * Module dependencies.
  13. */
  14. module.exports = jsonp;
  15. function jsonp(obj, callback, options) {
  16. // fixup callback when `this.query.callback` return Array
  17. if (Array.isArray(callback)) {
  18. callback = callback[0];
  19. }
  20. options = options || {};
  21. var limit = options.limit || 512;
  22. // JSON parse vs eval fix. @see https://github.com/rack/rack-contrib/pull/37
  23. var body = JSON.stringify(obj, options.replacer, options.space)
  24. .replace(/\u2028/g, '\\u2028')
  25. .replace(/\u2029/g, '\\u2029');
  26. if (typeof callback !== 'string' || callback.length === 0) {
  27. return body;
  28. }
  29. // limit callback length
  30. if (callback.length > limit) {
  31. callback = callback.substring(0, limit);
  32. }
  33. // Only allow "[","]","a-zA-Z0123456789_", "$" and "." characters.
  34. var cb = callback.replace(/[^\[\]\w$.]/g, '');
  35. // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"
  36. // @see https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-4671
  37. // @see http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
  38. // @see http://drops.wooyun.org/tips/2554
  39. return '/**/ typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';
  40. }