urlencode_unpacker.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*global unescape */
  2. /*jshint curly: false, scripturl: true */
  3. //
  4. // trivial bookmarklet/escaped script detector for the javascript beautifier
  5. // written by Einar Lielmanis <einar@jsbeautifier.org>
  6. //
  7. // usage:
  8. //
  9. // if (Urlencoded.detect(some_string)) {
  10. // var unpacked = Urlencoded.unpack(some_string);
  11. // }
  12. //
  13. //
  14. var isNode = (typeof module !== 'undefined' && module.exports);
  15. if (isNode) {
  16. var SanityTest = require(__dirname + '/../../test/sanitytest');
  17. }
  18. var Urlencoded = {
  19. detect: function (str) {
  20. // the fact that script doesn't contain any space, but has %20 instead
  21. // should be sufficient check for now.
  22. if (str.indexOf(' ') == -1) {
  23. if (str.indexOf('%2') != -1) return true;
  24. if (str.replace(/[^%]+/g, '').length > 3) return true;
  25. }
  26. return false;
  27. },
  28. unpack: function (str) {
  29. if (Urlencoded.detect(str)) {
  30. if (str.indexOf('%2B') != -1 || str.indexOf('%2b') != -1) {
  31. // "+" escaped as "%2B"
  32. return unescape(str.replace(/\+/g, '%20'));
  33. } else {
  34. return unescape(str);
  35. }
  36. }
  37. return str;
  38. },
  39. run_tests: function (sanity_test) {
  40. var t = sanity_test || new SanityTest();
  41. t.test_function(Urlencoded.detect, "Urlencoded.detect");
  42. t.expect('', false);
  43. t.expect('var a = b', false);
  44. t.expect('var%20a+=+b', true);
  45. t.expect('var%20a=b', true);
  46. t.expect('var%20%21%22', true);
  47. t.expect('javascript:(function(){var%20whatever={init:function(){alert(%22a%22+%22b%22)}};whatever.init()})();', true);
  48. t.test_function(Urlencoded.unpack, 'Urlencoded.unpack');
  49. t.expect('javascript:(function(){var%20whatever={init:function(){alert(%22a%22+%22b%22)}};whatever.init()})();',
  50. 'javascript:(function(){var whatever={init:function(){alert("a"+"b")}};whatever.init()})();'
  51. );
  52. t.expect('', '');
  53. t.expect('abcd', 'abcd');
  54. t.expect('var a = b', 'var a = b');
  55. t.expect('var%20a=b', 'var a=b');
  56. t.expect('var%20a=b+1', 'var a=b+1');
  57. t.expect('var%20a=b%2b1', 'var a=b+1');
  58. return t;
  59. }
  60. };
  61. if (isNode) {
  62. module.exports = Urlencoded;
  63. }