zerobin.js 16 KB

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