zerobin.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. /**
  2. * ZeroBin
  3. *
  4. * a zero-knowledge paste bin
  5. *
  6. * @link http://sebsauvage.net/wiki/doku.php?id=php:zerobin
  7. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  8. * @license http://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  9. * @version 0.15
  10. */
  11. // Immediately start random number generator collector.
  12. sjcl.random.startCollectors();
  13. /**
  14. * Converts a duration (in seconds) into human readable format.
  15. *
  16. * @param int seconds
  17. * @return string
  18. */
  19. function secondsToHuman(seconds)
  20. {
  21. if (seconds<60) { var v=Math.floor(seconds); return v+' second'+((v>1)?'s':''); }
  22. if (seconds<60*60) { var v=Math.floor(seconds/60); return v+' minute'+((v>1)?'s':''); }
  23. if (seconds<60*60*24) { var v=Math.floor(seconds/(60*60)); return v+' hour'+((v>1)?'s':''); }
  24. // If less than 2 months, display in days:
  25. if (seconds<60*60*24*60) { var v=Math.floor(seconds/(60*60*24)); return v+' day'+((v>1)?'s':''); }
  26. var v=Math.floor(seconds/(60*60*24*30)); return v+' month'+((v>1)?'s':'');
  27. }
  28. /**
  29. * Converts an associative array to an encoded string
  30. * for appending to the anchor.
  31. *
  32. * @param object associative_array Object to be serialized
  33. * @return string
  34. */
  35. function hashToParameterString(associativeArray)
  36. {
  37. var parameterString = ""
  38. for (key in associativeArray)
  39. {
  40. if( parameterString === "" )
  41. {
  42. parameterString = encodeURIComponent(key);
  43. parameterString += "=" + encodeURIComponent(associativeArray[key]);
  44. } else {
  45. parameterString += "&" + encodeURIComponent(key);
  46. parameterString += "=" + encodeURIComponent(associativeArray[key]);
  47. }
  48. }
  49. //padding for URL shorteners
  50. parameterString += "&p=p";
  51. return parameterString;
  52. }
  53. /**
  54. * Converts a string to an associative array.
  55. *
  56. * @param string parameter_string String containing parameters
  57. * @return object
  58. */
  59. function parameterStringToHash(parameterString)
  60. {
  61. var parameterHash = {};
  62. var parameterArray = parameterString.split("&");
  63. for (var i = 0; i < parameterArray.length; i++) {
  64. //var currentParamterString = decodeURIComponent(parameterArray[i]);
  65. var pair = parameterArray[i].split("=");
  66. var key = decodeURIComponent(pair[0]);
  67. var value = decodeURIComponent(pair[1]);
  68. parameterHash[key] = value;
  69. }
  70. return parameterHash;
  71. }
  72. /**
  73. * Get an associative array of the parameters found in the anchor
  74. *
  75. * @return object
  76. **/
  77. function getParameterHash()
  78. {
  79. var hashIndex = window.location.href.indexOf("#");
  80. if (hashIndex >= 0) {
  81. return parameterStringToHash(window.location.href.substring(hashIndex + 1));
  82. } else {
  83. return {};
  84. }
  85. }
  86. /**
  87. * Compress a message (deflate compression). Returns base64 encoded data.
  88. *
  89. * @param string message
  90. * @return base64 string data
  91. */
  92. function compress(message) {
  93. return Base64.toBase64( RawDeflate.deflate( Base64.utob(message) ) );
  94. }
  95. /**
  96. * Decompress a message compressed with compress().
  97. */
  98. function decompress(data) {
  99. return Base64.btou( RawDeflate.inflate( Base64.fromBase64(data) ) );
  100. }
  101. /**
  102. * Compress, then encrypt message with key.
  103. *
  104. * @param string key
  105. * @param string message
  106. * @return encrypted string data
  107. */
  108. function zeroCipher(key, message) {
  109. return sjcl.encrypt(key,compress(message));
  110. }
  111. /**
  112. * Decrypt message with key, then decompress.
  113. *
  114. * @param key
  115. * @param encrypted string data
  116. * @return string readable message
  117. */
  118. function zeroDecipher(key, data) {
  119. return decompress(sjcl.decrypt(key,data));
  120. }
  121. /**
  122. * @return the current script location (without search or hash part of the URL).
  123. * eg. http://server.com/zero/?aaaa#bbbb --> http://server.com/zero/
  124. */
  125. function scriptLocation() {
  126. var scriptLocation = window.location.href.substring(0,window.location.href.length
  127. - window.location.search.length - window.location.hash.length);
  128. var hashIndex = scriptLocation.indexOf("#");
  129. if (hashIndex !== -1) {
  130. scriptLocation = scriptLocation.substring(0, hashIndex)
  131. }
  132. return scriptLocation
  133. }
  134. /**
  135. * @return the paste unique identifier from the URL
  136. * eg. 'c05354954c49a487'
  137. */
  138. function pasteID() {
  139. return window.location.search.substring(1);
  140. }
  141. /**
  142. * Set text of a DOM element (required for IE)
  143. * This is equivalent to element.text(text)
  144. * @param object element : a DOM element.
  145. * @param string text : the text to enter.
  146. */
  147. function setElementText(element, text) {
  148. // For IE<10.
  149. if ($('div#oldienotice').is(":visible")) {
  150. // IE<10 do not support white-space:pre-wrap; so we have to do this BIG UGLY STINKING THING.
  151. element.text(text.replace(/\n/ig,'{BIG_UGLY_STINKING_THING__OH_GOD_I_HATE_IE}'));
  152. element.html(element.text().replace(/{BIG_UGLY_STINKING_THING__OH_GOD_I_HATE_IE}/ig,"\n<br />"));
  153. }
  154. // for other (sane) browsers:
  155. else {
  156. element.text(text);
  157. }
  158. }
  159. /**
  160. * Show decrypted text in the display area, including discussion (if open)
  161. *
  162. * @param string key : decryption key
  163. * @param array comments : Array of messages to display (items = array with keys ('data','meta')
  164. */
  165. function displayMessages(key, comments) {
  166. try { // Try to decrypt the paste.
  167. var cleartext = zeroDecipher(key, comments[0].data);
  168. } catch(err) {
  169. $('div#cleartext').addClass('hidden');
  170. $('div#prettymessage').addClass('hidden');
  171. $('button#clonebutton').addClass('hidden');
  172. showError('Could not decrypt data (Wrong key ?)');
  173. return;
  174. }
  175. setElementText($('div#cleartext'), cleartext);
  176. setElementText($('pre#prettyprint'), cleartext);
  177. urls2links($('div#cleartext')); // Convert URLs to clickable links.
  178. prettyPrint();
  179. // Display paste expiration.
  180. if (comments[0].meta.expire_date) $('div#remainingtime').removeClass('foryoureyesonly').text('This document will expire in '+secondsToHuman(comments[0].meta.remaining_time)+'.').removeClass('hidden');
  181. if (comments[0].meta.burnafterreading) {
  182. $('div#remainingtime').addClass('foryoureyesonly').text('FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.').removeClass('hidden');
  183. $('button#clonebutton').addClass('hidden'); // Discourage cloning (as it can't really be prevented).
  184. }
  185. // If the discussion is opened on this paste, display it.
  186. if (comments[0].meta.opendiscussion) {
  187. $('div#comments').html('');
  188. // For each comment.
  189. for (var i = 1; i < comments.length; i++) {
  190. var comment=comments[i];
  191. var cleartext="[Could not decrypt comment ; Wrong key ?]";
  192. try {
  193. cleartext = zeroDecipher(key, comment.data);
  194. } catch(err) { }
  195. var place = $('div#comments');
  196. // If parent comment exists, display below (CSS will automatically shift it right.)
  197. var cname = 'div#comment_'+comment.meta.parentid
  198. // If the element exists in page
  199. if ($(cname).length) {
  200. place = $(cname);
  201. }
  202. var divComment = $('<article><div class="comment" id="comment_' + comment.meta.commentid+'">'
  203. + '<div class="commentmeta"><span class="nickname"></span><span class="commentdate"></span></div><div class="commentdata"></div>'
  204. + '<button onclick="open_reply($(this),\'' + comment.meta.commentid + '\');return false;">Reply</button>'
  205. + '</div></article>');
  206. setElementText(divComment.find('div.commentdata'), cleartext);
  207. // Convert URLs to clickable links in comment.
  208. urls2links(divComment.find('div.commentdata'));
  209. divComment.find('span.nickname').html('<i>(Anonymous)</i>');
  210. // Try to get optional nickname:
  211. try {
  212. divComment.find('span.nickname').text(zeroDecipher(key, comment.meta.nickname));
  213. } catch(err) { }
  214. divComment.find('span.commentdate').text(' ('+(new Date(comment.meta.postdate*1000).toString())+')').attr('title','CommentID: ' + comment.meta.commentid);
  215. // If an avatar is available, display it.
  216. if (comment.meta.vizhash) {
  217. divComment.find('span.nickname').before('<img src="' + comment.meta.vizhash + '" class="vizhash" title="Anonymous avatar (Vizhash of the IP address)" />');
  218. }
  219. place.append(divComment);
  220. }
  221. $('div#comments').append('<div class="comment"><button onclick="open_reply($(this),\'' + pasteID() + '\');return false;">Add comment</button></div>');
  222. $('div#discussion').removeClass('hidden');
  223. }
  224. }
  225. /**
  226. * Open the comment entry when clicking the "Reply" button of a comment.
  227. * @param object source : element which emitted the event.
  228. * @param string commentid = identifier of the comment we want to reply to.
  229. */
  230. function open_reply(source, commentid) {
  231. $('div.reply').remove(); // Remove any other reply area.
  232. source.after('<div class="reply">'
  233. + '<input type="text" id="nickname" title="Optional nickname..." value="Optional nickname..." />'
  234. + '<textarea id="replymessage" class="replymessage" cols="80" rows="7"></textarea>'
  235. + '<br /><button id="replybutton" onclick="send_comment(\'' + commentid + '\');return false;">Post comment</button>'
  236. + '<div id="replystatus"> </div>'
  237. + '</div>');
  238. $('input#nickname').focus(function() {
  239. if ($(this).val() == $(this).attr('title')) {
  240. $(this).val('');
  241. }
  242. });
  243. $('textarea#replymessage').focus();
  244. }
  245. /**
  246. * Send a reply in a discussion.
  247. * @param string parentid : the comment identifier we want to send a reply to.
  248. */
  249. function send_comment(parentid) {
  250. // Do not send if no data.
  251. if ($('textarea#replymessage').val().length==0) {
  252. return;
  253. }
  254. showStatus('Sending comment...', spin=true);
  255. var cipherdata = zeroCipher(pageKey(), $('textarea#replymessage').val());
  256. var ciphernickname = '';
  257. var nick=$('input#nickname').val();
  258. if (nick != '' && nick != 'Optional nickname...') {
  259. ciphernickname = zeroCipher(pageKey(), nick);
  260. }
  261. var data_to_send = { data:cipherdata,
  262. parentid: parentid,
  263. pasteid: pasteID(),
  264. nickname: ciphernickname
  265. };
  266. $.post(scriptLocation(), data_to_send, 'json')
  267. .error(function() {
  268. showError('Comment could not be sent (serveur error or not responding).');
  269. })
  270. .success(function(data) {
  271. if (data.status == 0) {
  272. showStatus('Comment posted.');
  273. location.reload();
  274. }
  275. else if (data.status==1) {
  276. showError('Could not post comment: '+data.message);
  277. }
  278. else {
  279. showError('Could not post comment.');
  280. }
  281. });
  282. }
  283. /**
  284. * Send a new paste to server
  285. */
  286. function send_data() {
  287. // Do not send if no data.
  288. if ($('textarea#message').val().length == 0) {
  289. return;
  290. }
  291. showStatus('Sending paste...', spin=true);
  292. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  293. var cipherdata = zeroCipher(randomkey, $('textarea#message').val());
  294. var data_to_send = { data: cipherdata,
  295. expire: $('select#pasteExpiration').val(),
  296. opendiscussion: $('input#opendiscussion').is(':checked') ? 1 : 0
  297. };
  298. $.post(scriptLocation(), data_to_send, 'json')
  299. .error(function() {
  300. showError('Data could not be sent (serveur error or not responding).');
  301. })
  302. .success(function(data) {
  303. if (data.status == 0) {
  304. stateExistingPaste();
  305. var url = scriptLocation() + "?" + data.id + '#' + randomkey;
  306. showStatus('');
  307. $('div#pastelink').html('Your paste is <a href="' + url + '">' + url + '</a>').removeClass('hidden');
  308. setElementText($('div#cleartext'), $('textarea#message').val());
  309. setElementText($('pre#prettyprint'), $('textarea#message').val());
  310. urls2links($('div#cleartext'));
  311. showStatus('');
  312. prettyPrint();
  313. }
  314. else if (data.status==1) {
  315. showError('Could not create paste: '+data.message);
  316. }
  317. else {
  318. showError('Could not create paste.');
  319. }
  320. });
  321. }
  322. /**
  323. * Put the screen in "New paste" mode.
  324. */
  325. function stateNewPaste() {
  326. $('button#sendbutton').removeClass('hidden');
  327. $('button#clonebutton').addClass('hidden');
  328. $('div#expiration').removeClass('hidden');
  329. $('div#remainingtime').addClass('hidden');
  330. $('div#language').addClass('hidden'); // $('#language').removeClass('hidden');
  331. $('input#password').addClass('hidden'); //$('#password').removeClass('hidden');
  332. $('div#opendisc').removeClass('hidden');
  333. $('button#newbutton').removeClass('hidden');
  334. $('div#pastelink').addClass('hidden');
  335. $('textarea#message').text('');
  336. $('textarea#message').removeClass('hidden');
  337. $('div#cleartext').addClass('hidden');
  338. $('textarea#message').focus();
  339. $('div#discussion').addClass('hidden');
  340. $('div#prettymessage').addClass('hidden');
  341. }
  342. /**
  343. * Put the screen in "Existing paste" mode.
  344. */
  345. function stateExistingPaste() {
  346. $('button#sendbutton').addClass('hidden');
  347. // No "clone" for IE<10.
  348. if ($('div#oldienotice').is(":visible")) {
  349. $('button#clonebutton').addClass('hidden');
  350. }
  351. else {
  352. $('button#clonebutton').removeClass('hidden');
  353. }
  354. $('div#expiration').addClass('hidden');
  355. $('div#language').addClass('hidden');
  356. $('input#password').addClass('hidden');
  357. $('div#opendisc').addClass('hidden');
  358. $('button#newbutton').removeClass('hidden');
  359. $('div#pastelink').addClass('hidden');
  360. $('textarea#message').addClass('hidden');
  361. $('div#cleartext').addClass('hidden');
  362. $('div#prettymessage').removeClass('hidden');
  363. }
  364. /**
  365. * Clone the current paste.
  366. */
  367. function clonePaste() {
  368. stateNewPaste();
  369. //Erase the id and the key in url
  370. history.replaceState(document.title, document.title, scriptLocation());
  371. showStatus('');
  372. $('textarea#message').text($('div#cleartext').text());
  373. }
  374. /**
  375. * Create a new paste.
  376. */
  377. function newPaste() {
  378. stateNewPaste();
  379. showStatus('');
  380. $('textarea#message').text('');
  381. }
  382. /**
  383. * Display an error message
  384. * (We use the same function for paste and reply to comments)
  385. */
  386. function showError(message) {
  387. $('div#status').addClass('errorMessage').text(message);
  388. $('div#replystatus').addClass('errorMessage').text(message);
  389. }
  390. /**
  391. * Display status
  392. * (We use the same function for paste and reply to comments)
  393. *
  394. * @param string message : text to display
  395. * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
  396. */
  397. function showStatus(message, spin) {
  398. $('div#replystatus').removeClass('errorMessage');
  399. $('div#replystatus').text(message);
  400. if (!message) {
  401. $('div#status').html(' ');
  402. return;
  403. }
  404. if (message == '') {
  405. $('div#status').html(' ');
  406. return;
  407. }
  408. $('div#status').removeClass('errorMessage');
  409. $('div#status').text(message);
  410. if (spin) {
  411. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0px 4px 0px 0px;" />';
  412. $('div#status').prepend(img);
  413. $('div#replystatus').prepend(img);
  414. }
  415. }
  416. /**
  417. * Convert URLs to clickable links.
  418. * URLs to handle:
  419. * <code>
  420. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  421. * http://localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  422. * http://user:password@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  423. * </code>
  424. *
  425. * @param object element : a jQuery DOM element.
  426. * @FIXME: add ppa & apt links.
  427. */
  428. function urls2links(element) {
  429. var re = /((http|https|ftp):\/\/[\w?=&.\/-;#@~%+-]+(?![\w\s?&.\/;#~%"=-]*>))/ig;
  430. element.html(element.html().replace(re,'<a href="$1" rel="nofollow">$1</a>'));
  431. var re = /((magnet):[\w?=&.\/-;#@~%+-]+)/ig;
  432. element.html(element.html().replace(re,'<a href="$1">$1</a>'));
  433. }
  434. /**
  435. * Return the deciphering key stored in anchor part of the URL
  436. */
  437. function pageKey() {
  438. var key = window.location.hash.substring(1); // Get key
  439. // Some stupid web 2.0 services and redirectors add data AFTER the anchor
  440. // (such as &utm_source=...).
  441. // We will strip any additional data.
  442. // First, strip everything after the equal sign (=) which signals end of base64 string.
  443. i = key.indexOf('='); if (i>-1) { key = key.substring(0,i+1); }
  444. // If the equal sign was not present, some parameters may remain:
  445. i = key.indexOf('&'); if (i>-1) { key = key.substring(0,i); }
  446. // Then add trailing equal sign if it's missing
  447. if (key.charAt(key.length-1)!=='=') key+='=';
  448. return key;
  449. }
  450. $(function() {
  451. // hide "no javascript" message
  452. $('#noscript').hide();
  453. $('select#pasteExpiration').change(function() {
  454. if ($(this).val() == 'burn') {
  455. $('div#opendisc').addClass('buttondisabled');
  456. $('input#opendiscussion').attr('disabled',true);
  457. }
  458. else {
  459. $('div#opendisc').removeClass('buttondisabled');
  460. $('input#opendiscussion').removeAttr('disabled');
  461. }
  462. });
  463. // Display an existing paste
  464. if ($('div#cipherdata').text().length > 1) {
  465. // Missing decryption key in URL ?
  466. if (window.location.hash.length == 0) {
  467. showError('Cannot decrypt paste: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL ?)');
  468. return;
  469. }
  470. // List of messages to display
  471. var messages = jQuery.parseJSON($('div#cipherdata').text());
  472. // Show proper elements on screen.
  473. stateExistingPaste();
  474. displayMessages(pageKey(), messages);
  475. }
  476. // Display error message from php code.
  477. else if ($('div#errormessage').text().length>1) {
  478. showError($('div#errormessage').text());
  479. }
  480. // Create a new paste.
  481. else {
  482. newPaste();
  483. }
  484. });