privatebin.js 152 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978
  1. /**
  2. * PrivateBin
  3. *
  4. * a zero-knowledge paste bin
  5. *
  6. * @see {@link https://github.com/PrivateBin/PrivateBin}
  7. * @copyright 2012 Sébastien SAUVAGE ({@link http://sebsauvage.net})
  8. * @license {@link https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License}
  9. * @version 1.2.1
  10. * @name PrivateBin
  11. * @namespace
  12. */
  13. /** global: Base64 */
  14. /** global: DOMPurify */
  15. /** global: FileReader */
  16. /** global: RawDeflate */
  17. /** global: history */
  18. /** global: navigator */
  19. /** global: prettyPrint */
  20. /** global: prettyPrintOne */
  21. /** global: showdown */
  22. /** global: kjua */
  23. // main application start, called when DOM is fully loaded
  24. jQuery(document).ready(function() {
  25. 'use strict';
  26. // run main controller
  27. $.PrivateBin.Controller.init();
  28. });
  29. jQuery.PrivateBin = (function($, RawDeflate) {
  30. 'use strict';
  31. /**
  32. * zlib library interface
  33. *
  34. * @private
  35. */
  36. let z;
  37. /**
  38. * CryptoData class
  39. *
  40. * bundles helper fuctions used in both paste and comment formats
  41. *
  42. * @name CryptoData
  43. * @class
  44. */
  45. function CryptoData(data) {
  46. this.v = 1;
  47. // store all keys in the default locations for drop-in replacement
  48. for (let key in data) {
  49. this[key] = data[key];
  50. }
  51. /**
  52. * gets the cipher data (cipher text + adata)
  53. *
  54. * @name Paste.getCipherData
  55. * @function
  56. * @return {Array}|{string}
  57. */
  58. this.getCipherData = function()
  59. {
  60. return this.v === 1 ? this.data : [this.ct, this.adata];
  61. }
  62. }
  63. /**
  64. * Paste class
  65. *
  66. * bundles helper fuctions around the paste formats
  67. *
  68. * @name Paste
  69. * @class
  70. */
  71. function Paste(data) {
  72. // inherit constructor and methods of CryptoData
  73. CryptoData.call(this, data);
  74. /**
  75. * gets the used formatter
  76. *
  77. * @name Paste.getFormat
  78. * @function
  79. * @return {string}
  80. */
  81. this.getFormat = function()
  82. {
  83. return this.v === 1 ? this.meta.formatter : this.adata[1];
  84. }
  85. /**
  86. * gets the remaining seconds before the paste expires
  87. *
  88. * returns 0 if there is no expiration
  89. *
  90. * @name Paste.getTimeToLive
  91. * @function
  92. * @return {string}
  93. */
  94. this.getTimeToLive = function()
  95. {
  96. return (this.v === 1 ? this.meta.remaining_time : this.meta.time_to_live) || 0;
  97. }
  98. /**
  99. * is burn-after-reading enabled
  100. *
  101. * @name Paste.isBurnAfterReadingEnabled
  102. * @function
  103. * @return {bool}
  104. */
  105. this.isBurnAfterReadingEnabled = function()
  106. {
  107. return (this.v === 1 ? this.meta.burnafterreading : this.adata[3]);
  108. }
  109. /**
  110. * are discussions enabled
  111. *
  112. * @name Paste.isDiscussionEnabled
  113. * @function
  114. * @return {bool}
  115. */
  116. this.isDiscussionEnabled = function()
  117. {
  118. return (this.v === 1 ? this.meta.opendiscussion : this.adata[2]);
  119. }
  120. }
  121. /**
  122. * Comment class
  123. *
  124. * bundles helper fuctions around the comment formats
  125. *
  126. * @name Comment
  127. * @class
  128. */
  129. function Comment(data) {
  130. // inherit constructor and methods of CryptoData
  131. CryptoData.call(this, data);
  132. /**
  133. * gets the UNIX timestamp of the comment creation
  134. *
  135. * @name Paste.getCreated
  136. * @function
  137. * @return {int}
  138. */
  139. this.getCreated = function()
  140. {
  141. return this.meta[this.v === 1 ? 'postdate' : 'created'];
  142. }
  143. /**
  144. * gets the icon of the comment submitter
  145. *
  146. * @name Paste.getIcon
  147. * @function
  148. * @return {string}
  149. */
  150. this.getIcon = function()
  151. {
  152. return this.meta[this.v === 1 ? 'vizhash' : 'icon'] || '';
  153. }
  154. }
  155. /**
  156. * static Helper methods
  157. *
  158. * @name Helper
  159. * @class
  160. */
  161. const Helper = (function () {
  162. const me = {};
  163. /**
  164. * cache for script location
  165. *
  166. * @name Helper.baseUri
  167. * @private
  168. * @enum {string|null}
  169. */
  170. let baseUri = null;
  171. /**
  172. * converts a duration (in seconds) into human friendly approximation
  173. *
  174. * @name Helper.secondsToHuman
  175. * @function
  176. * @param {number} seconds
  177. * @return {Array}
  178. */
  179. me.secondsToHuman = function(seconds)
  180. {
  181. let v;
  182. if (seconds < 60)
  183. {
  184. v = Math.floor(seconds);
  185. return [v, 'second'];
  186. }
  187. if (seconds < 60 * 60)
  188. {
  189. v = Math.floor(seconds / 60);
  190. return [v, 'minute'];
  191. }
  192. if (seconds < 60 * 60 * 24)
  193. {
  194. v = Math.floor(seconds / (60 * 60));
  195. return [v, 'hour'];
  196. }
  197. // If less than 2 months, display in days:
  198. if (seconds < 60 * 60 * 24 * 60)
  199. {
  200. v = Math.floor(seconds / (60 * 60 * 24));
  201. return [v, 'day'];
  202. }
  203. v = Math.floor(seconds / (60 * 60 * 24 * 30));
  204. return [v, 'month'];
  205. };
  206. /**
  207. * text range selection
  208. *
  209. * @see {@link https://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse}
  210. * @name Helper.selectText
  211. * @function
  212. * @param {HTMLElement} element
  213. */
  214. me.selectText = function(element)
  215. {
  216. let range, selection;
  217. // MS
  218. if (document.body.createTextRange) {
  219. range = document.body.createTextRange();
  220. range.moveToElementText(element);
  221. range.select();
  222. } else if (window.getSelection) {
  223. selection = window.getSelection();
  224. range = document.createRange();
  225. range.selectNodeContents(element);
  226. selection.removeAllRanges();
  227. selection.addRange(range);
  228. }
  229. };
  230. /**
  231. * convert URLs to clickable links.
  232. *
  233. * URLs to handle:
  234. * <pre>
  235. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  236. * https://example.com:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  237. * http://user:example.com@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  238. * </pre>
  239. *
  240. * @name Helper.urls2links
  241. * @function
  242. * @param {string} html
  243. * @return {string}
  244. */
  245. me.urls2links = function(html)
  246. {
  247. return html.replace(
  248. /(((https?|ftp):\/\/[\w?!=&.\/-;#@~%+*-]+(?![\w\s?!&.\/;#~%"=-]*>))|((magnet):[\w?=&.\/-;#@~%+*-]+))/ig,
  249. '<a href="$1" rel="nofollow">$1</a>'
  250. );
  251. };
  252. /**
  253. * minimal sprintf emulation for %s and %d formats
  254. *
  255. * Note that this function needs the parameters in the same order as the
  256. * format strings appear in the string, contrary to the original.
  257. *
  258. * @see {@link https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914}
  259. * @name Helper.sprintf
  260. * @function
  261. * @param {string} format
  262. * @param {...*} args - one or multiple parameters injected into format string
  263. * @return {string}
  264. */
  265. me.sprintf = function()
  266. {
  267. const args = Array.prototype.slice.call(arguments);
  268. let format = args[0],
  269. i = 1;
  270. return format.replace(/%(s|d)/g, function (m) {
  271. // m is the matched format, e.g. %s, %d
  272. let val = args[i];
  273. // A switch statement so that the formatter can be extended.
  274. switch (m)
  275. {
  276. case '%d':
  277. val = parseFloat(val);
  278. if (isNaN(val)) {
  279. val = 0;
  280. }
  281. break;
  282. default:
  283. // Default is %s
  284. }
  285. ++i;
  286. return val;
  287. });
  288. };
  289. /**
  290. * get value of cookie, if it was set, empty string otherwise
  291. *
  292. * @see {@link http://www.w3schools.com/js/js_cookies.asp}
  293. * @name Helper.getCookie
  294. * @function
  295. * @param {string} cname - may not be empty
  296. * @return {string}
  297. */
  298. me.getCookie = function(cname) {
  299. const name = cname + '=',
  300. ca = document.cookie.split(';');
  301. for (let i = 0; i < ca.length; ++i) {
  302. let c = ca[i];
  303. while (c.charAt(0) === ' ')
  304. {
  305. c = c.substring(1);
  306. }
  307. if (c.indexOf(name) === 0)
  308. {
  309. return c.substring(name.length, c.length);
  310. }
  311. }
  312. return '';
  313. };
  314. /**
  315. * get the current location (without search or hash part of the URL),
  316. * eg. https://example.com/path/?aaaa#bbbb --> https://example.com/path/
  317. *
  318. * @name Helper.baseUri
  319. * @function
  320. * @return {string}
  321. */
  322. me.baseUri = function()
  323. {
  324. // check for cached version
  325. if (baseUri !== null) {
  326. return baseUri;
  327. }
  328. baseUri = window.location.origin + window.location.pathname;
  329. return baseUri;
  330. };
  331. /**
  332. * wrap an object into a Paste, used for mocking in the unit tests
  333. *
  334. * @name Helper.PasteFactory
  335. * @function
  336. * @param {object} data
  337. * @return {Paste}
  338. */
  339. me.PasteFactory = function(data)
  340. {
  341. return new Paste(data);
  342. };
  343. /**
  344. * wrap an object into a Comment, used for mocking in the unit tests
  345. *
  346. * @name Helper.CommentFactory
  347. * @function
  348. * @param {object} data
  349. * @return {Comment}
  350. */
  351. me.CommentFactory = function(data)
  352. {
  353. return new Comment(data);
  354. };
  355. /**
  356. * resets state, used for unit testing
  357. *
  358. * @name Helper.reset
  359. * @function
  360. */
  361. me.reset = function()
  362. {
  363. baseUri = null;
  364. };
  365. return me;
  366. })();
  367. /**
  368. * internationalization module
  369. *
  370. * @name I18n
  371. * @class
  372. */
  373. const I18n = (function () {
  374. const me = {};
  375. /**
  376. * const for string of loaded language
  377. *
  378. * @name I18n.languageLoadedEvent
  379. * @private
  380. * @prop {string}
  381. * @readonly
  382. */
  383. const languageLoadedEvent = 'languageLoaded';
  384. /**
  385. * supported languages, minus the built in 'en'
  386. *
  387. * @name I18n.supportedLanguages
  388. * @private
  389. * @prop {string[]}
  390. * @readonly
  391. */
  392. const supportedLanguages = ['cs', 'de', 'es', 'fr', 'it', 'hu', 'no', 'nl', 'pl', 'pt', 'oc', 'ru', 'sl', 'zh'];
  393. /**
  394. * built in language
  395. *
  396. * @name I18n.language
  397. * @private
  398. * @prop {string|null}
  399. */
  400. let language = null;
  401. /**
  402. * translation cache
  403. *
  404. * @name I18n.translations
  405. * @private
  406. * @enum {Object}
  407. */
  408. let translations = {};
  409. /**
  410. * translate a string, alias for I18n.translate
  411. *
  412. * @name I18n._
  413. * @function
  414. * @param {jQuery} $element - optional
  415. * @param {string} messageId
  416. * @param {...*} args - one or multiple parameters injected into placeholders
  417. * @return {string}
  418. */
  419. me._ = function()
  420. {
  421. return me.translate.apply(this, arguments);
  422. };
  423. /**
  424. * translate a string
  425. *
  426. * Optionally pass a jQuery element as the first parameter, to automatically
  427. * let the text of this element be replaced. In case the (asynchronously
  428. * loaded) language is not downloadet yet, this will make sure the string
  429. * is replaced when it is actually loaded.
  430. * So for easy translations passing the jQuery object to apply it to is
  431. * more save, especially when they are loaded in the beginning.
  432. *
  433. * @name I18n.translate
  434. * @function
  435. * @param {jQuery} $element - optional
  436. * @param {string} messageId
  437. * @param {...*} args - one or multiple parameters injected into placeholders
  438. * @return {string}
  439. */
  440. me.translate = function()
  441. {
  442. // convert parameters to array
  443. let args = Array.prototype.slice.call(arguments),
  444. messageId,
  445. $element = null;
  446. // parse arguments
  447. if (args[0] instanceof jQuery) {
  448. // optional jQuery element as first parameter
  449. $element = args[0];
  450. args.shift();
  451. }
  452. // extract messageId from arguments
  453. let usesPlurals = $.isArray(args[0]);
  454. if (usesPlurals) {
  455. // use the first plural form as messageId, otherwise the singular
  456. messageId = args[0].length > 1 ? args[0][1] : args[0][0];
  457. } else {
  458. messageId = args[0];
  459. }
  460. if (messageId.length === 0) {
  461. return messageId;
  462. }
  463. // if no translation string cannot be found (in translations object)
  464. if (!translations.hasOwnProperty(messageId) || language === null) {
  465. // if language is still loading and we have an elemt assigned
  466. if (language === null && $element !== null) {
  467. // handle the error by attaching the language loaded event
  468. let orgArguments = arguments;
  469. $(document).on(languageLoadedEvent, function () {
  470. // log to show that the previous error could be mitigated
  471. console.warn('Fix missing translation of \'' + messageId + '\' with now loaded language ' + language);
  472. // re-execute this function
  473. me.translate.apply(this, orgArguments);
  474. });
  475. // and fall back to English for now until the real language
  476. // file is loaded
  477. }
  478. // for all other languages than English for which this behaviour
  479. // is expected as it is built-in, log error
  480. if (language !== null && language !== 'en') {
  481. console.error('Missing translation for: \'' + messageId + '\' in language ' + language);
  482. // fallback to English
  483. }
  484. // save English translation (should be the same on both sides)
  485. translations[messageId] = args[0];
  486. }
  487. // lookup plural translation
  488. if (usesPlurals && $.isArray(translations[messageId])) {
  489. let n = parseInt(args[1] || 1, 10),
  490. key = me.getPluralForm(n),
  491. maxKey = translations[messageId].length - 1;
  492. if (key > maxKey) {
  493. key = maxKey;
  494. }
  495. args[0] = translations[messageId][key];
  496. args[1] = n;
  497. } else {
  498. // lookup singular translation
  499. args[0] = translations[messageId];
  500. }
  501. // format string
  502. let output = Helper.sprintf.apply(this, args);
  503. // if $element is given, apply text to element
  504. if ($element !== null) {
  505. // get last text node of element
  506. let content = $element.contents();
  507. if (content.length > 1) {
  508. content[content.length - 1].nodeValue = ' ' + output;
  509. } else {
  510. $element.text(output);
  511. }
  512. }
  513. return output;
  514. };
  515. /**
  516. * per language functions to use to determine the plural form
  517. *
  518. * @see {@link http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html}
  519. * @name I18n.getPluralForm
  520. * @function
  521. * @param {int} n
  522. * @return {int} array key
  523. */
  524. me.getPluralForm = function(n) {
  525. switch (language)
  526. {
  527. case 'cs':
  528. return n === 1 ? 0 : (n >= 2 && n <=4 ? 1 : 2);
  529. case 'fr':
  530. case 'oc':
  531. case 'zh':
  532. return n > 1 ? 1 : 0;
  533. case 'pl':
  534. return n === 1 ? 0 : (n % 10 >= 2 && n %10 <=4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  535. case 'ru':
  536. return n % 10 === 1 && n % 100 !== 11 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  537. case 'sl':
  538. return n % 100 === 1 ? 1 : (n % 100 === 2 ? 2 : (n % 100 === 3 || n % 100 === 4 ? 3 : 0));
  539. // de, en, es, hu, it, nl, no, pt
  540. default:
  541. return n !== 1 ? 1 : 0;
  542. }
  543. };
  544. /**
  545. * load translations into cache
  546. *
  547. * @name I18n.loadTranslations
  548. * @function
  549. */
  550. me.loadTranslations = function()
  551. {
  552. let newLanguage = Helper.getCookie('lang');
  553. // auto-select language based on browser settings
  554. if (newLanguage.length === 0) {
  555. newLanguage = (navigator.language || navigator.userLanguage || 'en').substring(0, 2);
  556. }
  557. // if language is already used skip update
  558. if (newLanguage === language) {
  559. return;
  560. }
  561. // if language is built-in (English) skip update
  562. if (newLanguage === 'en') {
  563. language = 'en';
  564. return;
  565. }
  566. // if language is not supported, show error
  567. if (supportedLanguages.indexOf(newLanguage) === -1) {
  568. console.error('Language \'%s\' is not supported. Translation failed, fallback to English.', newLanguage);
  569. language = 'en';
  570. return;
  571. }
  572. // load strings from JSON
  573. $.getJSON('i18n/' + newLanguage + '.json', function(data) {
  574. language = newLanguage;
  575. translations = data;
  576. $(document).triggerHandler(languageLoadedEvent);
  577. }).fail(function (data, textStatus, errorMsg) {
  578. console.error('Language \'%s\' could not be loaded (%s: %s). Translation failed, fallback to English.', newLanguage, textStatus, errorMsg);
  579. language = 'en';
  580. });
  581. };
  582. /**
  583. * resets state, used for unit testing
  584. *
  585. * @name I18n.reset
  586. * @function
  587. */
  588. me.reset = function(mockLanguage, mockTranslations)
  589. {
  590. language = mockLanguage || null;
  591. translations = mockTranslations || {};
  592. };
  593. return me;
  594. })();
  595. /**
  596. * handles everything related to en/decryption
  597. *
  598. * @name CryptTool
  599. * @class
  600. */
  601. const CryptTool = (function () {
  602. const me = {};
  603. /**
  604. * base58 encoder & decoder
  605. *
  606. * @private
  607. */
  608. let base58 = new baseX('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
  609. /**
  610. * convert hexadecimal string to binary representation
  611. *
  612. * @name CryptTool.hex2bin
  613. * @function
  614. * @private
  615. * @param {string} message hex string
  616. * @return {string} binary representation as a DOMString
  617. */
  618. function hex2bin(message) {
  619. let result = [];
  620. for (let i = 0, l = message.length; i < l; i += 2) {
  621. result.push(parseInt(message.substr(i, 2), 16));
  622. }
  623. return String.fromCharCode.apply(String, result);
  624. }
  625. /**
  626. * convert UTF-8 string stored in a DOMString to a standard UTF-16 DOMString
  627. *
  628. * Iterates over the bytes of the message, converting them all hexadecimal
  629. * percent encoded representations, then URI decodes them all
  630. *
  631. * @name CryptTool.utf8To16
  632. * @function
  633. * @private
  634. * @param {string} message UTF-8 string
  635. * @return {string} UTF-16 string
  636. */
  637. function utf8To16(message)
  638. {
  639. return decodeURIComponent(
  640. message.split('').map(
  641. function(character)
  642. {
  643. return '%' + ('00' + character.charCodeAt(0).toString(16)).slice(-2);
  644. }
  645. ).join('')
  646. );
  647. }
  648. /**
  649. * convert DOMString (UTF-16) to a UTF-8 string stored in a DOMString
  650. *
  651. * URI encodes the message, then finds the percent encoded characters
  652. * and transforms these hexadecimal representation back into bytes
  653. *
  654. * @name CryptTool.utf16To8
  655. * @function
  656. * @private
  657. * @param {string} message UTF-16 string
  658. * @return {string} UTF-8 string
  659. */
  660. function utf16To8(message)
  661. {
  662. return encodeURIComponent(message).replace(
  663. /%([0-9A-F]{2})/g,
  664. function (match, hexCharacter)
  665. {
  666. return String.fromCharCode('0x' + hexCharacter);
  667. }
  668. );
  669. }
  670. /**
  671. * convert ArrayBuffer into a UTF-8 string
  672. *
  673. * Iterates over the bytes of the array, catenating them into a string
  674. *
  675. * @name CryptTool.arraybufferToString
  676. * @function
  677. * @private
  678. * @param {ArrayBuffer} messageArray
  679. * @return {string} message
  680. */
  681. function arraybufferToString(messageArray)
  682. {
  683. const array = new Uint8Array(messageArray);
  684. let message = '',
  685. i = 0;
  686. while(i < array.length) {
  687. message += String.fromCharCode(array[i++]);
  688. }
  689. return message;
  690. }
  691. /**
  692. * convert UTF-8 string into a Uint8Array
  693. *
  694. * Iterates over the bytes of the message, writing them to the array
  695. *
  696. * @name CryptTool.stringToArraybuffer
  697. * @function
  698. * @private
  699. * @param {string} message UTF-8 string
  700. * @return {Uint8Array} array
  701. */
  702. function stringToArraybuffer(message)
  703. {
  704. const messageArray = new Uint8Array(message.length);
  705. for (let i = 0; i < message.length; ++i) {
  706. messageArray[i] = message.charCodeAt(i);
  707. }
  708. return messageArray;
  709. }
  710. /**
  711. * compress a string (deflate compression), returns buffer
  712. *
  713. * @name CryptTool.compress
  714. * @async
  715. * @function
  716. * @private
  717. * @param {string} message
  718. * @param {string} mode
  719. * @return {ArrayBuffer} data
  720. */
  721. async function compress(message, mode)
  722. {
  723. message = stringToArraybuffer(
  724. utf16To8(message)
  725. );
  726. if (mode === 'zlib') {
  727. return z.deflate(message).buffer;
  728. }
  729. return message;
  730. }
  731. /**
  732. * decompress potentially base64 encoded, deflate compressed buffer, returns string
  733. *
  734. * @name CryptTool.decompress
  735. * @async
  736. * @function
  737. * @private
  738. * @param {ArrayBuffer} data
  739. * @param {string} mode
  740. * @return {string} message
  741. */
  742. async function decompress(data, mode)
  743. {
  744. if (mode === 'zlib' || mode === 'none') {
  745. if (mode === 'zlib') {
  746. data = z.inflate(
  747. new Uint8Array(data)
  748. ).buffer;
  749. }
  750. return utf8To16(
  751. arraybufferToString(data)
  752. );
  753. }
  754. // detect presence of Base64.js, indicating legacy ZeroBin paste
  755. if (typeof Base64 === 'undefined') {
  756. return utf8To16(
  757. RawDeflate.inflate(
  758. utf8To16(
  759. atob(
  760. arraybufferToString(data)
  761. )
  762. )
  763. )
  764. );
  765. } else {
  766. return Base64.btou(
  767. RawDeflate.inflate(
  768. Base64.fromBase64(
  769. arraybufferToString(data)
  770. )
  771. )
  772. );
  773. }
  774. }
  775. /**
  776. * returns specified number of random bytes
  777. *
  778. * @name CryptTool.getRandomBytes
  779. * @function
  780. * @private
  781. * @param {int} length number of random bytes to fetch
  782. * @throws {string}
  783. * @return {string} random bytes
  784. */
  785. function getRandomBytes(length)
  786. {
  787. let bytes = '';
  788. const byteArray = new Uint8Array(length);
  789. window.crypto.getRandomValues(byteArray);
  790. for (let i = 0; i < length; ++i) {
  791. bytes += String.fromCharCode(byteArray[i]);
  792. }
  793. return bytes;
  794. }
  795. /**
  796. * derive cryptographic key from key string and password
  797. *
  798. * @name CryptTool.deriveKey
  799. * @async
  800. * @function
  801. * @private
  802. * @param {string} key
  803. * @param {string} password
  804. * @param {array} spec cryptographic specification
  805. * @param {bool} exportKey
  806. * @return {CryptoKey} derived key
  807. */
  808. async function deriveKey(key, password, spec, exportKey)
  809. {
  810. exportKey = exportKey || false;
  811. let keyArray = stringToArraybuffer(key);
  812. if (password.length > 0) {
  813. // version 1 pastes did append the passwords SHA-256 hash in hex
  814. if (spec[7] === 'rawdeflate') {
  815. let passwordBuffer = await window.crypto.subtle.digest(
  816. {name: 'SHA-256'},
  817. stringToArraybuffer(
  818. utf16To8(password)
  819. )
  820. );
  821. password = Array.prototype.map.call(
  822. new Uint8Array(passwordBuffer),
  823. x => ('00' + x.toString(16)).slice(-2)
  824. ).join('');
  825. }
  826. let passwordArray = stringToArraybuffer(password),
  827. newKeyArray = new Uint8Array(keyArray.length + passwordArray.length);
  828. newKeyArray.set(keyArray, 0);
  829. newKeyArray.set(passwordArray, keyArray.length);
  830. keyArray = newKeyArray;
  831. }
  832. // import raw key
  833. const importedKey = await window.crypto.subtle.importKey(
  834. 'raw', // only 'raw' is allowed
  835. keyArray,
  836. {name: 'PBKDF2'}, // we use PBKDF2 for key derivation
  837. false, // the key may not be exported
  838. ['deriveKey'] // we may only use it for key derivation
  839. );
  840. // derive a stronger key for use with AES
  841. return window.crypto.subtle.deriveKey(
  842. {
  843. name: 'PBKDF2', // we use PBKDF2 for key derivation
  844. salt: stringToArraybuffer(spec[1]), // salt used in HMAC
  845. iterations: spec[2], // amount of iterations to apply
  846. hash: {name: 'SHA-256'} // can be "SHA-1", "SHA-256", "SHA-384" or "SHA-512"
  847. },
  848. importedKey,
  849. {
  850. name: 'AES-' + spec[6].toUpperCase(), // can be any supported AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH" or "HMAC")
  851. length: spec[3] // can be 128, 192 or 256
  852. },
  853. exportKey, // may the key get exported, false by default
  854. ['encrypt', 'decrypt'] // we may only use it for en- and decryption
  855. );
  856. }
  857. /**
  858. * derive PBKDF2 protected credentials for server to validate password
  859. *
  860. * @name CryptTool.deriveCredentials
  861. * @function
  862. * @private
  863. * @param {string} key
  864. * @param {string} password
  865. * @return {string} derived key
  866. */
  867. async function deriveCredentials(key, password)
  868. {
  869. const spec = [
  870. null, // initialization vector
  871. key.slice(0, 16), // salt
  872. 100000, // iterations
  873. 256, // key size
  874. null, // tag size
  875. null, // algorithm
  876. 'gcm', // algorithm mode
  877. 'none' // compression
  878. ];
  879. return window.crypto.subtle.exportKey(
  880. 'raw', await deriveKey(key.slice(16), password, spec, true)
  881. );
  882. }
  883. /**
  884. * gets crypto settings from specification and authenticated data
  885. *
  886. * @name CryptTool.cryptoSettings
  887. * @function
  888. * @private
  889. * @param {string} adata authenticated data
  890. * @param {array} spec cryptographic specification
  891. * @return {object} crypto settings
  892. */
  893. function cryptoSettings(adata, spec)
  894. {
  895. return {
  896. name: 'AES-' + spec[6].toUpperCase(), // can be any supported AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH" or "HMAC")
  897. iv: stringToArraybuffer(spec[0]), // the initialization vector you used to encrypt
  898. additionalData: stringToArraybuffer(adata), // the addtional data you used during encryption (if any)
  899. tagLength: spec[4] // the length of the tag you used to encrypt (if any)
  900. };
  901. }
  902. /**
  903. * get PBKDF2 protected credentials for server to validate password
  904. *
  905. * @name CryptTool.getCredentials
  906. * @function
  907. * @param {string} key
  908. * @param {string} password
  909. * @return {string} derived key
  910. */
  911. me.getCredentials = async function(key, password)
  912. {
  913. return btoa(
  914. arraybufferToString(
  915. await deriveCredentials(key, password)
  916. )
  917. );
  918. }
  919. /**
  920. * get HMAC of paste ID and PBKDF2 protected credentials for server to validate
  921. *
  922. * @name CryptTool.getToken
  923. * @function
  924. * @param {string} id
  925. * @param {string} key
  926. * @param {string} password
  927. * @return {string} decrypted message, empty if decryption failed
  928. */
  929. me.getToken = async function(id, key, password)
  930. {
  931. return btoa(
  932. arraybufferToString(
  933. await window.crypto.subtle.sign(
  934. {name: 'HMAC'},
  935. await window.crypto.subtle.importKey(
  936. 'raw',
  937. await deriveCredentials(key, password),
  938. {
  939. name: 'HMAC',
  940. hash: {name: 'SHA-256'} // can be "SHA-1", "SHA-256", "SHA-384" or "SHA-512"
  941. },
  942. false, // may not export this
  943. ['sign']
  944. ),
  945. stringToArraybuffer(
  946. hex2bin(id)
  947. )
  948. )
  949. )
  950. );
  951. }
  952. /**
  953. * compress, then encrypt message with given key and password
  954. *
  955. * @name CryptTool.cipher
  956. * @async
  957. * @function
  958. * @param {string} key
  959. * @param {string} password
  960. * @param {string} message
  961. * @param {array} adata
  962. * @return {array} encrypted message in base64 encoding & adata containing encryption spec
  963. */
  964. me.cipher = async function(key, password, message, adata)
  965. {
  966. // AES in Galois Counter Mode, keysize 256 bit,
  967. // authentication tag 128 bit, 10000 iterations in key derivation
  968. const spec = [
  969. getRandomBytes(16), // initialization vector
  970. getRandomBytes(8), // salt
  971. 100000, // iterations
  972. 256, // key size
  973. 128, // tag size
  974. 'aes', // algorithm
  975. 'gcm', // algorithm mode
  976. $('body').data('compression') || 'zlib' // compression
  977. ], encodedSpec = [];
  978. for (let i = 0; i < spec.length; ++i) {
  979. encodedSpec[i] = i < 2 ? btoa(spec[i]) : spec[i];
  980. }
  981. if (adata.length === 0) {
  982. // comment
  983. adata = encodedSpec;
  984. } else if (adata[0] === null) {
  985. // paste
  986. adata[0] = encodedSpec;
  987. }
  988. // finally, encrypt message
  989. return [
  990. btoa(
  991. arraybufferToString(
  992. await window.crypto.subtle.encrypt(
  993. cryptoSettings(JSON.stringify(adata), spec),
  994. await deriveKey(key, password, spec),
  995. await compress(message, spec[7])
  996. )
  997. )
  998. ),
  999. adata
  1000. ];
  1001. };
  1002. /**
  1003. * decrypt message with key, then decompress
  1004. *
  1005. * @name CryptTool.decipher
  1006. * @async
  1007. * @function
  1008. * @param {string} key
  1009. * @param {string} password
  1010. * @param {string|object} data encrypted message
  1011. * @return {string} decrypted message, empty if decryption failed
  1012. */
  1013. me.decipher = async function(key, password, data)
  1014. {
  1015. let adataString, spec, cipherMessage;
  1016. if (data instanceof Array) {
  1017. // version 2
  1018. adataString = JSON.stringify(data[1]);
  1019. // clone the array instead of passing the reference
  1020. spec = (data[1][0] instanceof Array ? data[1][0] : data[1]).slice();
  1021. cipherMessage = data[0];
  1022. } else if (typeof data === 'string') {
  1023. // version 1
  1024. let object = JSON.parse(data);
  1025. adataString = atob(object.adata);
  1026. spec = [
  1027. object.iv,
  1028. object.salt,
  1029. object.iter,
  1030. object.ks,
  1031. object.ts,
  1032. object.cipher,
  1033. object.mode,
  1034. 'rawdeflate'
  1035. ];
  1036. cipherMessage = object.ct;
  1037. } else {
  1038. throw 'unsupported message format';
  1039. }
  1040. spec[0] = atob(spec[0]);
  1041. spec[1] = atob(spec[1]);
  1042. try {
  1043. return await decompress(
  1044. await window.crypto.subtle.decrypt(
  1045. cryptoSettings(adataString, spec),
  1046. await deriveKey(key, password, spec),
  1047. stringToArraybuffer(
  1048. atob(cipherMessage)
  1049. )
  1050. ),
  1051. spec[7]
  1052. );
  1053. } catch(err) {
  1054. return '';
  1055. }
  1056. };
  1057. /**
  1058. * returns a random symmetric key
  1059. *
  1060. * generates 256 bit long keys (8 Bits * 32) for AES with 256 bit long blocks
  1061. *
  1062. * @name CryptTool.getSymmetricKey
  1063. * @function
  1064. * @throws {string}
  1065. * @return {string} raw bytes
  1066. */
  1067. me.getSymmetricKey = function()
  1068. {
  1069. return getRandomBytes(32);
  1070. };
  1071. /**
  1072. * base58 encode a DOMString (UTF-16)
  1073. *
  1074. * @name CryptTool.base58encode
  1075. * @function
  1076. * @param {string} input
  1077. * @return {string} output
  1078. */
  1079. me.base58encode = function(input)
  1080. {
  1081. return base58.encode(
  1082. stringToArraybuffer(input)
  1083. );
  1084. }
  1085. /**
  1086. * base58 decode a DOMString (UTF-16)
  1087. *
  1088. * @name CryptTool.base58decode
  1089. * @function
  1090. * @param {string} input
  1091. * @return {string} output
  1092. */
  1093. me.base58decode = function(input)
  1094. {
  1095. return arraybufferToString(
  1096. base58.decode(input)
  1097. );
  1098. }
  1099. return me;
  1100. })();
  1101. /**
  1102. * (Model) Data source (aka MVC)
  1103. *
  1104. * @name Model
  1105. * @class
  1106. */
  1107. const Model = (function () {
  1108. const me = {};
  1109. let id = null,
  1110. pasteData = null,
  1111. symmetricKey = null,
  1112. $templates;
  1113. /**
  1114. * returns the expiration set in the HTML
  1115. *
  1116. * @name Model.getExpirationDefault
  1117. * @function
  1118. * @return string
  1119. */
  1120. me.getExpirationDefault = function()
  1121. {
  1122. return $('#pasteExpiration').val();
  1123. };
  1124. /**
  1125. * returns the format set in the HTML
  1126. *
  1127. * @name Model.getFormatDefault
  1128. * @function
  1129. * @return string
  1130. */
  1131. me.getFormatDefault = function()
  1132. {
  1133. return $('#pasteFormatter').val();
  1134. };
  1135. /**
  1136. * returns the paste data (including the cipher data)
  1137. *
  1138. * @name Model.getPasteData
  1139. * @function
  1140. * @param {function} callback (optional) Called when data is available
  1141. * @param {function} useCache (optional) Whether to use the cache or
  1142. * force a data reload. Default: true
  1143. * @return string
  1144. */
  1145. me.getPasteData = async function(callback, useCache)
  1146. {
  1147. // use cache if possible/allowed
  1148. if (useCache !== false && pasteData !== null) {
  1149. //execute callback
  1150. if (typeof callback === 'function') {
  1151. return callback(pasteData);
  1152. }
  1153. // alternatively just using inline
  1154. return pasteData;
  1155. }
  1156. // load data
  1157. ServerInteraction.prepare();
  1158. ServerInteraction.setUrl(
  1159. Helper.baseUri() + '?' + $.param({
  1160. pasteid: me.getPasteId(),
  1161. token: await CryptTool.getToken(
  1162. me.getPasteId(), me.getPasteKey(), Prompt.getPassword()
  1163. )
  1164. })
  1165. );
  1166. ServerInteraction.setFailure(function (status, data) {
  1167. // revert loading status…
  1168. Alert.hideLoading();
  1169. TopNav.showViewButtons();
  1170. // might be a missing password, try one more time after getting one
  1171. if (Prompt.getPassword().length === 0) {
  1172. Prompt.requestPassword(function () {
  1173. me.getPasteData(callback, useCache);
  1174. });
  1175. } else {
  1176. // show error message
  1177. Alert.showError(ServerInteraction.parseUploadError(status, data, 'get paste data'));
  1178. }
  1179. });
  1180. ServerInteraction.setSuccess(function (status, data) {
  1181. pasteData = new Paste(data);
  1182. if (typeof callback === 'function') {
  1183. return callback(pasteData);
  1184. }
  1185. });
  1186. ServerInteraction.run();
  1187. };
  1188. /**
  1189. * get the pastes unique identifier from the URL,
  1190. * eg. https://example.com/path/?c05354954c49a487#dfdsdgdgdfgdf returns c05354954c49a487
  1191. *
  1192. * @name Model.getPasteId
  1193. * @function
  1194. * @return {string} unique identifier
  1195. * @throws {string}
  1196. */
  1197. me.getPasteId = function()
  1198. {
  1199. const idRegEx = /^[a-z0-9]{16}$/;
  1200. const idRegExFind = /[a-z0-9]{16}/;
  1201. // return cached value
  1202. if (id !== null) {
  1203. return id;
  1204. }
  1205. // do use URL interface, if possible
  1206. const url = new URL(window.location);
  1207. for (const param of url.searchParams) {
  1208. const key = param[0];
  1209. const value = param[1];
  1210. if (value === '' && idRegEx.test(key)) {
  1211. // safe, as the whole regex is matched
  1212. id = key;
  1213. return key;
  1214. }
  1215. }
  1216. if (id === null) {
  1217. throw 'no paste id given';
  1218. }
  1219. return id;
  1220. }
  1221. /**
  1222. * returns true, when the URL has a delete token and the current call was used for deleting a paste.
  1223. *
  1224. * @name Model.hasDeleteToken
  1225. * @function
  1226. * @return {bool}
  1227. */
  1228. me.hasDeleteToken = function()
  1229. {
  1230. return window.location.search.indexOf('deletetoken') !== -1;
  1231. }
  1232. /**
  1233. * return the deciphering key stored in anchor part of the URL
  1234. *
  1235. * @name Model.getPasteKey
  1236. * @function
  1237. * @return {string|null} key
  1238. * @throws {string}
  1239. */
  1240. me.getPasteKey = function()
  1241. {
  1242. if (symmetricKey === null) {
  1243. let newKey = window.location.hash.substring(1);
  1244. if (newKey === '') {
  1245. throw 'no encryption key given';
  1246. }
  1247. // Some web 2.0 services and redirectors add data AFTER the anchor
  1248. // (such as &utm_source=...). We will strip any additional data.
  1249. let ampersandPos = newKey.indexOf('&');
  1250. if (ampersandPos > -1)
  1251. {
  1252. newKey = newKey.substring(0, ampersandPos);
  1253. }
  1254. // version 2 uses base58, version 1 uses base64 without decoding
  1255. try {
  1256. // base58 encode strips NULL bytes at the beginning of the
  1257. // string, so we re-add them if necessary
  1258. symmetricKey = CryptTool.base58decode(newKey).padStart(32, '\u0000');
  1259. } catch(e) {
  1260. symmetricKey = newKey;
  1261. }
  1262. }
  1263. return symmetricKey;
  1264. };
  1265. /**
  1266. * returns a jQuery copy of the HTML template
  1267. *
  1268. * @name Model.getTemplate
  1269. * @function
  1270. * @param {string} name - the name of the template
  1271. * @return {jQuery}
  1272. */
  1273. me.getTemplate = function(name)
  1274. {
  1275. // find template
  1276. let $element = $templates.find('#' + name + 'template').clone(true);
  1277. // change ID to avoid collisions (one ID should really be unique)
  1278. return $element.prop('id', name);
  1279. };
  1280. /**
  1281. * resets state, used for unit testing
  1282. *
  1283. * @name Model.reset
  1284. * @function
  1285. */
  1286. me.reset = function()
  1287. {
  1288. pasteData = $templates = id = symmetricKey = null;
  1289. };
  1290. /**
  1291. * init navigation manager
  1292. *
  1293. * preloads jQuery elements
  1294. *
  1295. * @name Model.init
  1296. * @function
  1297. */
  1298. me.init = function()
  1299. {
  1300. $templates = $('#templates');
  1301. };
  1302. return me;
  1303. })();
  1304. /**
  1305. * Helper functions for user interface
  1306. *
  1307. * everything directly UI-related, which fits nowhere else
  1308. *
  1309. * @name UiHelper
  1310. * @class
  1311. */
  1312. const UiHelper = (function () {
  1313. const me = {};
  1314. /**
  1315. * handle history (pop) state changes
  1316. *
  1317. * currently this does only handle redirects to the home page.
  1318. *
  1319. * @name UiHelper.historyChange
  1320. * @private
  1321. * @function
  1322. * @param {Event} event
  1323. */
  1324. function historyChange(event)
  1325. {
  1326. let currentLocation = Helper.baseUri();
  1327. if (event.originalEvent.state === null && // no state object passed
  1328. event.target.location.href === currentLocation && // target location is home page
  1329. window.location.href === currentLocation // and we are not already on the home page
  1330. ) {
  1331. // redirect to home page
  1332. window.location.href = currentLocation;
  1333. }
  1334. }
  1335. /**
  1336. * reload the page
  1337. *
  1338. * This takes the user to the PrivateBin homepage.
  1339. *
  1340. * @name UiHelper.reloadHome
  1341. * @function
  1342. */
  1343. me.reloadHome = function()
  1344. {
  1345. window.location.href = Helper.baseUri();
  1346. };
  1347. /**
  1348. * checks whether the element is currently visible in the viewport (so
  1349. * the user can actually see it)
  1350. *
  1351. * @see {@link https://stackoverflow.com/a/40658647}
  1352. * @name UiHelper.isVisible
  1353. * @function
  1354. * @param {jQuery} $element The link hash to move to.
  1355. */
  1356. me.isVisible = function($element)
  1357. {
  1358. let elementTop = $element.offset().top,
  1359. viewportTop = $(window).scrollTop(),
  1360. viewportBottom = viewportTop + $(window).height();
  1361. return elementTop > viewportTop && elementTop < viewportBottom;
  1362. };
  1363. /**
  1364. * scrolls to a specific element
  1365. *
  1366. * @see {@link https://stackoverflow.com/questions/4198041/jquery-smooth-scroll-to-an-anchor#answer-12714767}
  1367. * @name UiHelper.scrollTo
  1368. * @function
  1369. * @param {jQuery} $element The link hash to move to.
  1370. * @param {(number|string)} animationDuration passed to jQuery .animate, when set to 0 the animation is skipped
  1371. * @param {string} animationEffect passed to jQuery .animate
  1372. * @param {function} finishedCallback function to call after animation finished
  1373. */
  1374. me.scrollTo = function($element, animationDuration, animationEffect, finishedCallback)
  1375. {
  1376. let $body = $('html, body'),
  1377. margin = 50,
  1378. callbackCalled = false,
  1379. dest = 0;
  1380. // calculate destination place
  1381. // if it would scroll out of the screen at the bottom only scroll it as
  1382. // far as the screen can go
  1383. if ($element.offset().top > $(document).height() - $(window).height()) {
  1384. dest = $(document).height() - $(window).height();
  1385. } else {
  1386. dest = $element.offset().top - margin;
  1387. }
  1388. // skip animation if duration is set to 0
  1389. if (animationDuration === 0) {
  1390. window.scrollTo(0, dest);
  1391. } else {
  1392. // stop previous animation
  1393. $body.stop();
  1394. // scroll to destination
  1395. $body.animate({
  1396. scrollTop: dest
  1397. }, animationDuration, animationEffect);
  1398. }
  1399. // as we have finished we can enable scrolling again
  1400. $body.queue(function (next) {
  1401. if (!callbackCalled) {
  1402. // call user function if needed
  1403. if (typeof finishedCallback !== 'undefined') {
  1404. finishedCallback();
  1405. }
  1406. // prevent calling this function twice
  1407. callbackCalled = true;
  1408. }
  1409. next();
  1410. });
  1411. };
  1412. /**
  1413. * trigger a history (pop) state change
  1414. *
  1415. * used to test the UiHelper.historyChange private function
  1416. *
  1417. * @name UiHelper.mockHistoryChange
  1418. * @function
  1419. * @param {string} state (optional) state to mock
  1420. */
  1421. me.mockHistoryChange = function(state)
  1422. {
  1423. if (typeof state === 'undefined') {
  1424. state = null;
  1425. }
  1426. historyChange($.Event('popstate', {originalEvent: new PopStateEvent('popstate', {state: state}), target: window}));
  1427. };
  1428. /**
  1429. * initialize
  1430. *
  1431. * @name UiHelper.init
  1432. * @function
  1433. */
  1434. me.init = function()
  1435. {
  1436. // update link to home page
  1437. $('.reloadlink').prop('href', Helper.baseUri());
  1438. $(window).on('popstate', historyChange);
  1439. };
  1440. return me;
  1441. })();
  1442. /**
  1443. * Alert/error manager
  1444. *
  1445. * @name Alert
  1446. * @class
  1447. */
  1448. const Alert = (function () {
  1449. const me = {};
  1450. let $errorMessage,
  1451. $loadingIndicator,
  1452. $statusMessage,
  1453. $remainingTime,
  1454. currentIcon,
  1455. customHandler;
  1456. const alertType = [
  1457. 'loading', // not in bootstrap CSS, but using a plausible value here
  1458. 'info', // status icon
  1459. 'warning', // not used yet
  1460. 'danger' // error icon
  1461. ];
  1462. /**
  1463. * forwards a request to the i18n module and shows the element
  1464. *
  1465. * @name Alert.handleNotification
  1466. * @private
  1467. * @function
  1468. * @param {int} id - id of notification
  1469. * @param {jQuery} $element - jQuery object
  1470. * @param {string|array} args
  1471. * @param {string|null} icon - optional, icon
  1472. */
  1473. function handleNotification(id, $element, args, icon)
  1474. {
  1475. // basic parsing/conversion of parameters
  1476. if (typeof icon === 'undefined') {
  1477. icon = null;
  1478. }
  1479. if (typeof args === 'undefined') {
  1480. args = null;
  1481. } else if (typeof args === 'string') {
  1482. // convert string to array if needed
  1483. args = [args];
  1484. } else if (args instanceof Error) {
  1485. // extract message into array if needed
  1486. args = [args.message];
  1487. }
  1488. // pass to custom handler if defined
  1489. if (typeof customHandler === 'function') {
  1490. let handlerResult = customHandler(alertType[id], $element, args, icon);
  1491. if (handlerResult === true) {
  1492. // if it returns true, skip own handler
  1493. return;
  1494. }
  1495. if (handlerResult instanceof jQuery) {
  1496. // continue processing with new element
  1497. $element = handlerResult;
  1498. icon = null; // icons not supported in this case
  1499. }
  1500. }
  1501. // handle icon
  1502. if (icon !== null && // icon was passed
  1503. icon !== currentIcon[id] // and it differs from current icon
  1504. ) {
  1505. let $glyphIcon = $element.find(':first');
  1506. // remove (previous) icon
  1507. $glyphIcon.removeClass(currentIcon[id]);
  1508. // any other thing as a string (e.g. 'null') (only) removes the icon
  1509. if (typeof icon === 'string') {
  1510. // set new icon
  1511. currentIcon[id] = 'glyphicon-' + icon;
  1512. $glyphIcon.addClass(currentIcon[id]);
  1513. }
  1514. }
  1515. // show text
  1516. if (args !== null) {
  1517. // add jQuery object to it as first parameter
  1518. args.unshift($element);
  1519. // pass it to I18n
  1520. I18n._.apply(this, args);
  1521. }
  1522. // show notification
  1523. $element.removeClass('hidden');
  1524. }
  1525. /**
  1526. * display a status message
  1527. *
  1528. * This automatically passes the text to I18n for translation.
  1529. *
  1530. * @name Alert.showStatus
  1531. * @function
  1532. * @param {string|array} message string, use an array for %s/%d options
  1533. * @param {string|null} icon optional, the icon to show,
  1534. * default: leave previous icon
  1535. */
  1536. me.showStatus = function(message, icon)
  1537. {
  1538. handleNotification(1, $statusMessage, message, icon);
  1539. };
  1540. /**
  1541. * display an error message
  1542. *
  1543. * This automatically passes the text to I18n for translation.
  1544. *
  1545. * @name Alert.showError
  1546. * @function
  1547. * @param {string|array} message string, use an array for %s/%d options
  1548. * @param {string|null} icon optional, the icon to show, default:
  1549. * leave previous icon
  1550. */
  1551. me.showError = function(message, icon)
  1552. {
  1553. handleNotification(3, $errorMessage, message, icon);
  1554. };
  1555. /**
  1556. * display remaining message
  1557. *
  1558. * This automatically passes the text to I18n for translation.
  1559. *
  1560. * @name Alert.showRemaining
  1561. * @function
  1562. * @param {string|array} message string, use an array for %s/%d options
  1563. */
  1564. me.showRemaining = function(message)
  1565. {
  1566. handleNotification(1, $remainingTime, message);
  1567. };
  1568. /**
  1569. * shows a loading message, optionally with a percentage
  1570. *
  1571. * This automatically passes all texts to the i10s module.
  1572. *
  1573. * @name Alert.showLoading
  1574. * @function
  1575. * @param {string|array|null} message optional, use an array for %s/%d options, default: 'Loading…'
  1576. * @param {string|null} icon optional, the icon to show, default: leave previous icon
  1577. */
  1578. me.showLoading = function(message, icon)
  1579. {
  1580. // default message text
  1581. if (typeof message === 'undefined') {
  1582. message = 'Loading…';
  1583. }
  1584. handleNotification(0, $loadingIndicator, message, icon);
  1585. // show loading status (cursor)
  1586. $('body').addClass('loading');
  1587. };
  1588. /**
  1589. * hides the loading message
  1590. *
  1591. * @name Alert.hideLoading
  1592. * @function
  1593. */
  1594. me.hideLoading = function()
  1595. {
  1596. $loadingIndicator.addClass('hidden');
  1597. // hide loading cursor
  1598. $('body').removeClass('loading');
  1599. };
  1600. /**
  1601. * hides any status/error messages
  1602. *
  1603. * This does not include the loading message.
  1604. *
  1605. * @name Alert.hideMessages
  1606. * @function
  1607. */
  1608. me.hideMessages = function()
  1609. {
  1610. $statusMessage.addClass('hidden');
  1611. $errorMessage.addClass('hidden');
  1612. };
  1613. /**
  1614. * set a custom handler, which gets all notifications.
  1615. *
  1616. * This handler gets the following arguments:
  1617. * alertType (see array), $element, args, icon
  1618. * If it returns true, the own processing will be stopped so the message
  1619. * will not be displayed. Otherwise it will continue.
  1620. * As an aditional feature it can return q jQuery element, which will
  1621. * then be used to add the message there. Icons are not supported in
  1622. * that case and will be ignored.
  1623. * Pass 'null' to reset/delete the custom handler.
  1624. * Note that there is no notification when a message is supposed to get
  1625. * hidden.
  1626. *
  1627. * @name Alert.setCustomHandler
  1628. * @function
  1629. * @param {function|null} newHandler
  1630. */
  1631. me.setCustomHandler = function(newHandler)
  1632. {
  1633. customHandler = newHandler;
  1634. };
  1635. /**
  1636. * init status manager
  1637. *
  1638. * preloads jQuery elements
  1639. *
  1640. * @name Alert.init
  1641. * @function
  1642. */
  1643. me.init = function()
  1644. {
  1645. // hide "no javascript" error message
  1646. $('#noscript').hide();
  1647. // not a reset, but first set of the elements
  1648. $errorMessage = $('#errormessage');
  1649. $loadingIndicator = $('#loadingindicator');
  1650. $statusMessage = $('#status');
  1651. $remainingTime = $('#remainingtime');
  1652. currentIcon = [
  1653. 'glyphicon-time', // loading icon
  1654. 'glyphicon-info-sign', // status icon
  1655. '', // reserved for warning, not used yet
  1656. 'glyphicon-alert' // error icon
  1657. ];
  1658. };
  1659. return me;
  1660. })();
  1661. /**
  1662. * handles paste status/result
  1663. *
  1664. * @name PasteStatus
  1665. * @class
  1666. */
  1667. const PasteStatus = (function () {
  1668. const me = {};
  1669. let $pasteSuccess,
  1670. $pasteUrl,
  1671. $remainingTime,
  1672. $shortenButton;
  1673. /**
  1674. * forward to URL shortener
  1675. *
  1676. * @name PasteStatus.sendToShortener
  1677. * @private
  1678. * @function
  1679. */
  1680. function sendToShortener()
  1681. {
  1682. window.location.href = $shortenButton.data('shortener') +
  1683. encodeURIComponent($pasteUrl.attr('href'));
  1684. }
  1685. /**
  1686. * Forces opening the paste if the link does not do this automatically.
  1687. *
  1688. * This is necessary as browsers will not reload the page when it is
  1689. * already loaded (which is fake as it is set via history.pushState()).
  1690. *
  1691. * @name PasteStatus.pasteLinkClick
  1692. * @function
  1693. */
  1694. function pasteLinkClick()
  1695. {
  1696. // check if location is (already) shown in URL bar
  1697. if (window.location.href === $pasteUrl.attr('href')) {
  1698. // if so we need to load link by reloading the current site
  1699. window.location.reload(true);
  1700. }
  1701. }
  1702. /**
  1703. * creates a notification after a successfull paste upload
  1704. *
  1705. * @name PasteStatus.createPasteNotification
  1706. * @function
  1707. * @param {string} url
  1708. * @param {string} deleteUrl
  1709. */
  1710. me.createPasteNotification = function(url, deleteUrl)
  1711. {
  1712. $('#pastelink').html(
  1713. I18n._(
  1714. 'Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>',
  1715. url, url
  1716. )
  1717. );
  1718. // save newly created element
  1719. $pasteUrl = $('#pasteurl');
  1720. // and add click event
  1721. $pasteUrl.click(pasteLinkClick);
  1722. // shorten button
  1723. $('#deletelink').html('<a href="' + deleteUrl + '">' + I18n._('Delete data') + '</a>');
  1724. // show result
  1725. $pasteSuccess.removeClass('hidden');
  1726. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1727. Helper.selectText($pasteUrl[0]);
  1728. };
  1729. /**
  1730. * shows the remaining time
  1731. *
  1732. * @name PasteStatus.showRemainingTime
  1733. * @function
  1734. * @param {Paste} paste
  1735. */
  1736. me.showRemainingTime = function(paste)
  1737. {
  1738. if (paste.isBurnAfterReadingEnabled()) {
  1739. // display paste "for your eyes only" if it is deleted
  1740. // the paste has been deleted when the JSON with the ciphertext
  1741. // has been downloaded
  1742. Alert.showRemaining('FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.');
  1743. $remainingTime.addClass('foryoureyesonly');
  1744. // discourage cloning (it cannot really be prevented)
  1745. TopNav.hideCloneButton();
  1746. } else if (paste.getTimeToLive() > 0) {
  1747. // display paste expiration
  1748. let expiration = Helper.secondsToHuman(paste.getTimeToLive()),
  1749. expirationLabel = [
  1750. 'This document will expire in %d ' + expiration[1] + '.',
  1751. 'This document will expire in %d ' + expiration[1] + 's.'
  1752. ];
  1753. Alert.showRemaining([expirationLabel, expiration[0]]);
  1754. $remainingTime.removeClass('foryoureyesonly');
  1755. } else {
  1756. // never expires
  1757. return;
  1758. }
  1759. // in the end, display notification
  1760. $remainingTime.removeClass('hidden');
  1761. };
  1762. /**
  1763. * hides the remaining time and successful upload notification
  1764. *
  1765. * @name PasteStatus.hideMessages
  1766. * @function
  1767. */
  1768. me.hideMessages = function()
  1769. {
  1770. $remainingTime.addClass('hidden');
  1771. $pasteSuccess.addClass('hidden');
  1772. };
  1773. /**
  1774. * init status manager
  1775. *
  1776. * preloads jQuery elements
  1777. *
  1778. * @name PasteStatus.init
  1779. * @function
  1780. */
  1781. me.init = function()
  1782. {
  1783. $pasteSuccess = $('#pastesuccess');
  1784. // $pasteUrl is saved in me.createPasteNotification() after creation
  1785. $remainingTime = $('#remainingtime');
  1786. $shortenButton = $('#shortenbutton');
  1787. // bind elements
  1788. $shortenButton.click(sendToShortener);
  1789. };
  1790. return me;
  1791. })();
  1792. /**
  1793. * password prompt
  1794. *
  1795. * @name Prompt
  1796. * @class
  1797. */
  1798. const Prompt = (function () {
  1799. const me = {};
  1800. let $passwordDecrypt,
  1801. $passwordForm,
  1802. $passwordModal,
  1803. password = '';
  1804. /**
  1805. * submit a password in the modal dialog
  1806. *
  1807. * @name Prompt.submitPasswordModal
  1808. * @private
  1809. * @function
  1810. * @param {Event} event
  1811. */
  1812. function submitPasswordModal(event)
  1813. {
  1814. event.preventDefault();
  1815. // get input
  1816. password = $passwordDecrypt.val();
  1817. // hide modal
  1818. $passwordModal.modal('hide');
  1819. PasteDecrypter.run();
  1820. }
  1821. /**
  1822. * ask the user for the password and set it
  1823. *
  1824. * @name Prompt.requestPassword
  1825. * @function
  1826. * @param {function} callback
  1827. */
  1828. me.requestPassword = function(callback)
  1829. {
  1830. // show new bootstrap method (if available)
  1831. if ($passwordModal.length !== 0) {
  1832. $passwordModal.modal({
  1833. backdrop: 'static',
  1834. keyboard: false
  1835. });
  1836. return;
  1837. }
  1838. // fallback to old method for page template
  1839. password = prompt(I18n._('Please enter the password for this paste:'), '');
  1840. if (password === null) {
  1841. throw 'password prompt canceled';
  1842. }
  1843. if (password.length === 0) {
  1844. // recurse…
  1845. return me.requestPassword(callback);
  1846. }
  1847. callback();
  1848. };
  1849. /**
  1850. * get the cached password
  1851. *
  1852. * If you do not get a password with this function
  1853. * (returns an empty string), use requestPassword.
  1854. *
  1855. * @name Prompt.getPassword
  1856. * @function
  1857. * @return {string}
  1858. */
  1859. me.getPassword = function()
  1860. {
  1861. return password;
  1862. };
  1863. /**
  1864. * resets the password to an empty string
  1865. *
  1866. * @name Prompt.reset
  1867. * @function
  1868. */
  1869. me.reset = function()
  1870. {
  1871. // reset internal
  1872. password = '';
  1873. // and also reset UI
  1874. $passwordDecrypt.val('');
  1875. }
  1876. /**
  1877. * init status manager
  1878. *
  1879. * preloads jQuery elements
  1880. *
  1881. * @name Prompt.init
  1882. * @function
  1883. */
  1884. me.init = function()
  1885. {
  1886. $passwordDecrypt = $('#passworddecrypt');
  1887. $passwordForm = $('#passwordform');
  1888. $passwordModal = $('#passwordmodal');
  1889. // bind events
  1890. // focus password input when it is shown
  1891. $passwordModal.on('shown.bs.Model', function () {
  1892. $passwordDecrypt.focus();
  1893. });
  1894. // handle Model password submission
  1895. $passwordForm.submit(submitPasswordModal);
  1896. };
  1897. return me;
  1898. })();
  1899. /**
  1900. * Manage paste/message input, and preview tab
  1901. *
  1902. * Note that the actual preview is handled by PasteViewer.
  1903. *
  1904. * @name Editor
  1905. * @class
  1906. */
  1907. const Editor = (function () {
  1908. const me = {};
  1909. let $editorTabs,
  1910. $messageEdit,
  1911. $messagePreview,
  1912. $message,
  1913. isPreview = false;
  1914. /**
  1915. * support input of tab character
  1916. *
  1917. * @name Editor.supportTabs
  1918. * @function
  1919. * @param {Event} event
  1920. * @this $message (but not used, so it is jQuery-free, possibly faster)
  1921. */
  1922. function supportTabs(event)
  1923. {
  1924. const keyCode = event.keyCode || event.which;
  1925. // tab was pressed
  1926. if (keyCode === 9) {
  1927. // get caret position & selection
  1928. const val = this.value,
  1929. start = this.selectionStart,
  1930. end = this.selectionEnd;
  1931. // set textarea value to: text before caret + tab + text after caret
  1932. this.value = val.substring(0, start) + '\t' + val.substring(end);
  1933. // put caret at right position again
  1934. this.selectionStart = this.selectionEnd = start + 1;
  1935. // prevent the textarea to lose focus
  1936. event.preventDefault();
  1937. }
  1938. }
  1939. /**
  1940. * view the Editor tab
  1941. *
  1942. * @name Editor.viewEditor
  1943. * @function
  1944. * @param {Event} event - optional
  1945. */
  1946. function viewEditor(event)
  1947. {
  1948. // toggle buttons
  1949. $messageEdit.addClass('active');
  1950. $messagePreview.removeClass('active');
  1951. PasteViewer.hide();
  1952. // reshow input
  1953. $message.removeClass('hidden');
  1954. me.focusInput();
  1955. // finish
  1956. isPreview = false;
  1957. // prevent jumping of page to top
  1958. if (typeof event !== 'undefined') {
  1959. event.preventDefault();
  1960. }
  1961. }
  1962. /**
  1963. * view the preview tab
  1964. *
  1965. * @name Editor.viewPreview
  1966. * @function
  1967. * @param {Event} event
  1968. */
  1969. function viewPreview(event)
  1970. {
  1971. // toggle buttons
  1972. $messageEdit.removeClass('active');
  1973. $messagePreview.addClass('active');
  1974. // hide input as now preview is shown
  1975. $message.addClass('hidden');
  1976. // show preview
  1977. PasteViewer.setText($message.val());
  1978. if (AttachmentViewer.hasAttachmentData()) {
  1979. const attachment = AttachmentViewer.getAttachment();
  1980. AttachmentViewer.handleBlobAttachmentPreview(
  1981. AttachmentViewer.getAttachmentPreview(),
  1982. attachment[0], attachment[1]
  1983. );
  1984. }
  1985. PasteViewer.run();
  1986. // finish
  1987. isPreview = true;
  1988. // prevent jumping of page to top
  1989. if (typeof event !== 'undefined') {
  1990. event.preventDefault();
  1991. }
  1992. }
  1993. /**
  1994. * get the state of the preview
  1995. *
  1996. * @name Editor.isPreview
  1997. * @function
  1998. */
  1999. me.isPreview = function()
  2000. {
  2001. return isPreview;
  2002. };
  2003. /**
  2004. * reset the Editor view
  2005. *
  2006. * @name Editor.resetInput
  2007. * @function
  2008. */
  2009. me.resetInput = function()
  2010. {
  2011. // go back to input
  2012. if (isPreview) {
  2013. viewEditor();
  2014. }
  2015. // clear content
  2016. $message.val('');
  2017. };
  2018. /**
  2019. * shows the Editor
  2020. *
  2021. * @name Editor.show
  2022. * @function
  2023. */
  2024. me.show = function()
  2025. {
  2026. $message.removeClass('hidden');
  2027. $editorTabs.removeClass('hidden');
  2028. };
  2029. /**
  2030. * hides the Editor
  2031. *
  2032. * @name Editor.reset
  2033. * @function
  2034. */
  2035. me.hide = function()
  2036. {
  2037. $message.addClass('hidden');
  2038. $editorTabs.addClass('hidden');
  2039. };
  2040. /**
  2041. * focuses the message input
  2042. *
  2043. * @name Editor.focusInput
  2044. * @function
  2045. */
  2046. me.focusInput = function()
  2047. {
  2048. $message.focus();
  2049. };
  2050. /**
  2051. * sets a new text
  2052. *
  2053. * @name Editor.setText
  2054. * @function
  2055. * @param {string} newText
  2056. */
  2057. me.setText = function(newText)
  2058. {
  2059. $message.val(newText);
  2060. };
  2061. /**
  2062. * returns the current text
  2063. *
  2064. * @name Editor.getText
  2065. * @function
  2066. * @return {string}
  2067. */
  2068. me.getText = function()
  2069. {
  2070. return $message.val();
  2071. };
  2072. /**
  2073. * init status manager
  2074. *
  2075. * preloads jQuery elements
  2076. *
  2077. * @name Editor.init
  2078. * @function
  2079. */
  2080. me.init = function()
  2081. {
  2082. $editorTabs = $('#editorTabs');
  2083. $message = $('#message');
  2084. // bind events
  2085. $message.keydown(supportTabs);
  2086. // bind click events to tab switchers (a), but save parent of them
  2087. // (li)
  2088. $messageEdit = $('#messageedit').click(viewEditor).parent();
  2089. $messagePreview = $('#messagepreview').click(viewPreview).parent();
  2090. };
  2091. return me;
  2092. })();
  2093. /**
  2094. * (view) Parse and show paste.
  2095. *
  2096. * @name PasteViewer
  2097. * @class
  2098. */
  2099. const PasteViewer = (function () {
  2100. const me = {};
  2101. let $placeholder,
  2102. $prettyMessage,
  2103. $prettyPrint,
  2104. $plainText,
  2105. text,
  2106. format = 'plaintext',
  2107. isDisplayed = false,
  2108. isChanged = true; // by default true as nothing was parsed yet
  2109. /**
  2110. * apply the set format on paste and displays it
  2111. *
  2112. * @name PasteViewer.parsePaste
  2113. * @private
  2114. * @function
  2115. */
  2116. function parsePaste()
  2117. {
  2118. // skip parsing if no text is given
  2119. if (text === '') {
  2120. return;
  2121. }
  2122. // escape HTML entities, link URLs, sanitize
  2123. const escapedLinkedText = Helper.urls2links(
  2124. $('<div />').text(text).html()
  2125. ),
  2126. sanitizedLinkedText = DOMPurify.sanitize(escapedLinkedText);
  2127. $plainText.html(sanitizedLinkedText);
  2128. $prettyPrint.html(sanitizedLinkedText);
  2129. switch (format) {
  2130. case 'markdown':
  2131. const converter = new showdown.Converter({
  2132. strikethrough: true,
  2133. tables: true,
  2134. tablesHeaderId: true,
  2135. simplifiedAutoLink: true,
  2136. excludeTrailingPunctuationFromURLs: true
  2137. });
  2138. // let showdown convert the HTML and sanitize HTML *afterwards*!
  2139. $plainText.html(
  2140. DOMPurify.sanitize(
  2141. converter.makeHtml(text)
  2142. )
  2143. );
  2144. // add table classes from bootstrap css
  2145. $plainText.find('table').addClass('table-condensed table-bordered');
  2146. break;
  2147. case 'syntaxhighlighting':
  2148. // yes, this is really needed to initialize the environment
  2149. if (typeof prettyPrint === 'function')
  2150. {
  2151. prettyPrint();
  2152. }
  2153. $prettyPrint.html(
  2154. DOMPurify.sanitize(
  2155. prettyPrintOne(escapedLinkedText, null, true)
  2156. )
  2157. );
  2158. // fall through, as the rest is the same
  2159. default: // = 'plaintext'
  2160. $prettyPrint.css('white-space', 'pre-wrap');
  2161. $prettyPrint.css('word-break', 'normal');
  2162. $prettyPrint.removeClass('prettyprint');
  2163. }
  2164. }
  2165. /**
  2166. * displays the paste
  2167. *
  2168. * @name PasteViewer.showPaste
  2169. * @private
  2170. * @function
  2171. */
  2172. function showPaste()
  2173. {
  2174. // instead of "nothing" better display a placeholder
  2175. if (text === '') {
  2176. $placeholder.removeClass('hidden');
  2177. return;
  2178. }
  2179. // otherwise hide the placeholder
  2180. $placeholder.addClass('hidden');
  2181. switch (format) {
  2182. case 'markdown':
  2183. $plainText.removeClass('hidden');
  2184. $prettyMessage.addClass('hidden');
  2185. break;
  2186. default:
  2187. $plainText.addClass('hidden');
  2188. $prettyMessage.removeClass('hidden');
  2189. break;
  2190. }
  2191. }
  2192. /**
  2193. * sets the format in which the text is shown
  2194. *
  2195. * @name PasteViewer.setFormat
  2196. * @function
  2197. * @param {string} newFormat the new format
  2198. */
  2199. me.setFormat = function(newFormat)
  2200. {
  2201. // skip if there is no update
  2202. if (format === newFormat) {
  2203. return;
  2204. }
  2205. // needs to update display too, if we switch from or to Markdown
  2206. if (format === 'markdown' || newFormat === 'markdown') {
  2207. isDisplayed = false;
  2208. }
  2209. format = newFormat;
  2210. isChanged = true;
  2211. };
  2212. /**
  2213. * returns the current format
  2214. *
  2215. * @name PasteViewer.getFormat
  2216. * @function
  2217. * @return {string}
  2218. */
  2219. me.getFormat = function()
  2220. {
  2221. return format;
  2222. };
  2223. /**
  2224. * returns whether the current view is pretty printed
  2225. *
  2226. * @name PasteViewer.isPrettyPrinted
  2227. * @function
  2228. * @return {bool}
  2229. */
  2230. me.isPrettyPrinted = function()
  2231. {
  2232. return $prettyPrint.hasClass('prettyprinted');
  2233. };
  2234. /**
  2235. * sets the text to show
  2236. *
  2237. * @name PasteViewer.setText
  2238. * @function
  2239. * @param {string} newText the text to show
  2240. */
  2241. me.setText = function(newText)
  2242. {
  2243. if (text !== newText) {
  2244. text = newText;
  2245. isChanged = true;
  2246. }
  2247. };
  2248. /**
  2249. * gets the current cached text
  2250. *
  2251. * @name PasteViewer.getText
  2252. * @function
  2253. * @return {string}
  2254. */
  2255. me.getText = function()
  2256. {
  2257. return text;
  2258. };
  2259. /**
  2260. * show/update the parsed text (preview)
  2261. *
  2262. * @name PasteViewer.run
  2263. * @function
  2264. */
  2265. me.run = function()
  2266. {
  2267. if (isChanged) {
  2268. parsePaste();
  2269. isChanged = false;
  2270. }
  2271. if (!isDisplayed) {
  2272. showPaste();
  2273. isDisplayed = true;
  2274. }
  2275. };
  2276. /**
  2277. * hide parsed text (preview)
  2278. *
  2279. * @name PasteViewer.hide
  2280. * @function
  2281. */
  2282. me.hide = function()
  2283. {
  2284. if (!isDisplayed) {
  2285. return;
  2286. }
  2287. $plainText.addClass('hidden');
  2288. $prettyMessage.addClass('hidden');
  2289. $placeholder.addClass('hidden');
  2290. AttachmentViewer.hideAttachmentPreview();
  2291. isDisplayed = false;
  2292. };
  2293. /**
  2294. * init status manager
  2295. *
  2296. * preloads jQuery elements
  2297. *
  2298. * @name PasteViewer.init
  2299. * @function
  2300. */
  2301. me.init = function()
  2302. {
  2303. $placeholder = $('#placeholder');
  2304. $plainText = $('#plaintext');
  2305. $prettyMessage = $('#prettymessage');
  2306. $prettyPrint = $('#prettyprint');
  2307. // get default option from template/HTML or fall back to set value
  2308. format = Model.getFormatDefault() || format;
  2309. text = '';
  2310. isDisplayed = false;
  2311. isChanged = true;
  2312. };
  2313. return me;
  2314. })();
  2315. /**
  2316. * (view) Show attachment and preview if possible
  2317. *
  2318. * @name AttachmentViewer
  2319. * @class
  2320. */
  2321. const AttachmentViewer = (function () {
  2322. const me = {};
  2323. let $attachmentLink,
  2324. $attachmentPreview,
  2325. $attachment,
  2326. attachmentData,
  2327. file,
  2328. $fileInput,
  2329. $dragAndDropFileName,
  2330. attachmentHasPreview = false;
  2331. /**
  2332. * sets the attachment but does not yet show it
  2333. *
  2334. * @name AttachmentViewer.setAttachment
  2335. * @function
  2336. * @param {string} attachmentData - base64-encoded data of file
  2337. * @param {string} fileName - optional, file name
  2338. */
  2339. me.setAttachment = function(attachmentData, fileName)
  2340. {
  2341. // data URI format: data:[<mediaType>][;base64],<data>
  2342. // position in data URI string of where data begins
  2343. const base64Start = attachmentData.indexOf(',') + 1;
  2344. // position in data URI string of where mediaType ends
  2345. const mediaTypeEnd = attachmentData.indexOf(';');
  2346. // extract mediaType
  2347. const mediaType = attachmentData.substring(5, mediaTypeEnd);
  2348. // extract data and convert to binary
  2349. const decodedData = atob(attachmentData.substring(base64Start));
  2350. // Transform into a Blob
  2351. const buf = new Uint8Array(decodedData.length);
  2352. for (let i = 0; i < decodedData.length; ++i) {
  2353. buf[i] = decodedData.charCodeAt(i);
  2354. }
  2355. const blob = new window.Blob([ buf ], { type: mediaType });
  2356. // Get Blob URL
  2357. const blobUrl = window.URL.createObjectURL(blob);
  2358. // IE does not support setting a data URI on an a element
  2359. // Using msSaveBlob to download
  2360. if (window.Blob && navigator.msSaveBlob) {
  2361. $attachmentLink.off('click').on('click', function () {
  2362. navigator.msSaveBlob(blob, fileName);
  2363. });
  2364. } else {
  2365. $attachmentLink.attr('href', blobUrl);
  2366. }
  2367. if (typeof fileName !== 'undefined') {
  2368. $attachmentLink.attr('download', fileName);
  2369. }
  2370. me.handleBlobAttachmentPreview($attachmentPreview, blobUrl, mediaType);
  2371. };
  2372. /**
  2373. * displays the attachment
  2374. *
  2375. * @name AttachmentViewer.showAttachment
  2376. * @function
  2377. */
  2378. me.showAttachment = function()
  2379. {
  2380. $attachment.removeClass('hidden');
  2381. if (attachmentHasPreview) {
  2382. $attachmentPreview.removeClass('hidden');
  2383. }
  2384. };
  2385. /**
  2386. * removes the attachment
  2387. *
  2388. * This automatically hides the attachment containers too, to
  2389. * prevent an inconsistent display.
  2390. *
  2391. * @name AttachmentViewer.removeAttachment
  2392. * @function
  2393. */
  2394. me.removeAttachment = function()
  2395. {
  2396. if (!$attachment.length) {
  2397. return;
  2398. }
  2399. me.hideAttachment();
  2400. me.hideAttachmentPreview();
  2401. $attachmentLink.removeAttr('href');
  2402. $attachmentLink.removeAttr('download');
  2403. $attachmentLink.off('click');
  2404. $attachmentPreview.html('');
  2405. AttachmentViewer.removeAttachmentData();
  2406. };
  2407. /**
  2408. * removes the attachment data
  2409. *
  2410. * This removes the data, which would be uploaded otherwise.
  2411. *
  2412. * @name AttachmentViewer.removeAttachmentData
  2413. * @function
  2414. */
  2415. me.removeAttachmentData = function()
  2416. {
  2417. file = undefined;
  2418. attachmentData = undefined;
  2419. };
  2420. /**
  2421. * Cleares the drag & drop data.
  2422. *
  2423. * @name AttachmentViewer.clearDragAndDrop
  2424. * @function
  2425. */
  2426. me.clearDragAndDrop = function()
  2427. {
  2428. $dragAndDropFileName.text('');
  2429. };
  2430. /**
  2431. * hides the attachment
  2432. *
  2433. * This will not hide the preview (see AttachmentViewer.hideAttachmentPreview
  2434. * for that) nor will it hide the attachment link if it was moved somewhere
  2435. * else (see AttachmentViewer.moveAttachmentTo).
  2436. *
  2437. * @name AttachmentViewer.hideAttachment
  2438. * @function
  2439. */
  2440. me.hideAttachment = function()
  2441. {
  2442. $attachment.addClass('hidden');
  2443. };
  2444. /**
  2445. * hides the attachment preview
  2446. *
  2447. * @name AttachmentViewer.hideAttachmentPreview
  2448. * @function
  2449. */
  2450. me.hideAttachmentPreview = function()
  2451. {
  2452. if ($attachmentPreview) {
  2453. $attachmentPreview.addClass('hidden');
  2454. }
  2455. };
  2456. /**
  2457. * checks if there is an attachment displayed
  2458. *
  2459. * @name AttachmentViewer.hasAttachment
  2460. * @function
  2461. */
  2462. me.hasAttachment = function()
  2463. {
  2464. if (!$attachment.length) {
  2465. return false;
  2466. }
  2467. const link = $attachmentLink.prop('href');
  2468. return (typeof link !== 'undefined' && link !== '');
  2469. };
  2470. /**
  2471. * checks if there is attachment data (for preview!) available
  2472. *
  2473. * It returns true, when there is data that needs to be encrypted.
  2474. *
  2475. * @name AttachmentViewer.hasAttachmentData
  2476. * @function
  2477. */
  2478. me.hasAttachmentData = function()
  2479. {
  2480. if ($attachment.length) {
  2481. return true;
  2482. }
  2483. return false;
  2484. };
  2485. /**
  2486. * return the attachment
  2487. *
  2488. * @name AttachmentViewer.getAttachment
  2489. * @function
  2490. * @returns {array}
  2491. */
  2492. me.getAttachment = function()
  2493. {
  2494. return [
  2495. $attachmentLink.prop('href'),
  2496. $attachmentLink.prop('download')
  2497. ];
  2498. };
  2499. /**
  2500. * moves the attachment link to another element
  2501. *
  2502. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  2503. *
  2504. * @name AttachmentViewer.moveAttachmentTo
  2505. * @function
  2506. * @param {jQuery} $element - the wrapper/container element where this should be moved to
  2507. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  2508. */
  2509. me.moveAttachmentTo = function($element, label)
  2510. {
  2511. // move elemement to new place
  2512. $attachmentLink.appendTo($element);
  2513. // update text
  2514. I18n._($attachmentLink, label, $attachmentLink.attr('download'));
  2515. };
  2516. /**
  2517. * read file data as data URL using the FileReader API
  2518. *
  2519. * @name AttachmentViewer.readFileData
  2520. * @private
  2521. * @function
  2522. * @param {object} loadedFile (optional) loaded file object
  2523. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsDataURL()}
  2524. */
  2525. function readFileData(loadedFile) {
  2526. if (typeof FileReader === 'undefined') {
  2527. // revert loading status…
  2528. me.hideAttachment();
  2529. me.hideAttachmentPreview();
  2530. Alert.showError('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2531. return;
  2532. }
  2533. const fileReader = new FileReader();
  2534. if (loadedFile === undefined) {
  2535. loadedFile = $fileInput[0].files[0];
  2536. $dragAndDropFileName.text('');
  2537. } else {
  2538. $dragAndDropFileName.text(loadedFile.name);
  2539. }
  2540. file = loadedFile;
  2541. fileReader.onload = function (event) {
  2542. const dataURL = event.target.result;
  2543. attachmentData = dataURL;
  2544. if (Editor.isPreview()) {
  2545. me.setAttachment(dataURL, loadedFile.name || '');
  2546. $attachmentPreview.removeClass('hidden');
  2547. }
  2548. };
  2549. fileReader.readAsDataURL(loadedFile);
  2550. }
  2551. /**
  2552. * handle the preview of files decoded to blob that can either be an image, video, audio or pdf element
  2553. *
  2554. * @name AttachmentViewer.handleBlobAttachmentPreview
  2555. * @function
  2556. * @argument {jQuery} $targetElement element where the preview should be appended
  2557. * @argument {string} file as a blob URL
  2558. * @argument {string} mime type
  2559. */
  2560. me.handleBlobAttachmentPreview = function ($targetElement, blobUrl, mimeType) {
  2561. if (blobUrl) {
  2562. attachmentHasPreview = true;
  2563. if (mimeType.match(/image\//i)) {
  2564. $targetElement.html(
  2565. $(document.createElement('img'))
  2566. .attr('src', blobUrl)
  2567. .attr('class', 'img-thumbnail')
  2568. );
  2569. } else if (mimeType.match(/video\//i)) {
  2570. $targetElement.html(
  2571. $(document.createElement('video'))
  2572. .attr('controls', 'true')
  2573. .attr('autoplay', 'true')
  2574. .attr('class', 'img-thumbnail')
  2575. .append($(document.createElement('source'))
  2576. .attr('type', mimeType)
  2577. .attr('src', blobUrl))
  2578. );
  2579. } else if (mimeType.match(/audio\//i)) {
  2580. $targetElement.html(
  2581. $(document.createElement('audio'))
  2582. .attr('controls', 'true')
  2583. .attr('autoplay', 'true')
  2584. .append($(document.createElement('source'))
  2585. .attr('type', mimeType)
  2586. .attr('src', blobUrl))
  2587. );
  2588. } else if (mimeType.match(/\/pdf/i)) {
  2589. // Fallback for browsers, that don't support the vh unit
  2590. var clientHeight = $(window).height();
  2591. $targetElement.html(
  2592. $(document.createElement('embed'))
  2593. .attr('src', blobUrl)
  2594. .attr('type', 'application/pdf')
  2595. .attr('class', 'pdfPreview')
  2596. .css('height', clientHeight)
  2597. );
  2598. } else {
  2599. attachmentHasPreview = false;
  2600. }
  2601. }
  2602. };
  2603. /**
  2604. * attaches the file attachment drag & drop handler to the page
  2605. *
  2606. * @name AttachmentViewer.addDragDropHandler
  2607. * @private
  2608. * @function
  2609. */
  2610. function addDragDropHandler() {
  2611. if (typeof $fileInput === 'undefined' || $fileInput.length === 0) {
  2612. return;
  2613. }
  2614. const ignoreDragDrop = function(event) {
  2615. event.stopPropagation();
  2616. event.preventDefault();
  2617. };
  2618. const drop = function(event) {
  2619. const evt = event.originalEvent;
  2620. evt.stopPropagation();
  2621. evt.preventDefault();
  2622. if ($fileInput) {
  2623. const file = evt.dataTransfer.files[0];
  2624. //Clear the file input:
  2625. $fileInput.wrap('<form>').closest('form').get(0).reset();
  2626. $fileInput.unwrap();
  2627. //Only works in Chrome:
  2628. //fileInput[0].files = e.dataTransfer.files;
  2629. readFileData(file);
  2630. }
  2631. };
  2632. $(document).on('drop', drop);
  2633. $(document).on('dragenter', ignoreDragDrop);
  2634. $(document).on('dragover', ignoreDragDrop);
  2635. $fileInput.on('change', function () {
  2636. readFileData();
  2637. });
  2638. }
  2639. /**
  2640. * attaches the clipboard attachment handler to the page
  2641. *
  2642. * @name AttachmentViewer.addClipboardEventHandler
  2643. * @private
  2644. * @function
  2645. */
  2646. function addClipboardEventHandler() {
  2647. $(document).on('paste', function (event) {
  2648. const items = (event.clipboardData || event.originalEvent.clipboardData).items;
  2649. for (let i = 0; i < items.length; ++i) {
  2650. if (items[i].kind === 'file') {
  2651. //Clear the file input:
  2652. $fileInput.wrap('<form>').closest('form').get(0).reset();
  2653. $fileInput.unwrap();
  2654. readFileData(items[i].getAsFile());
  2655. }
  2656. }
  2657. });
  2658. }
  2659. /**
  2660. * getter for attachment data
  2661. *
  2662. * @name AttachmentViewer.getAttachmentData
  2663. * @function
  2664. * @return {jQuery}
  2665. */
  2666. me.getAttachmentData = function () {
  2667. return attachmentData;
  2668. };
  2669. /**
  2670. * getter for attachment link
  2671. *
  2672. * @name AttachmentViewer.getAttachmentLink
  2673. * @function
  2674. * @return {jQuery}
  2675. */
  2676. me.getAttachmentLink = function () {
  2677. return $attachmentLink;
  2678. };
  2679. /**
  2680. * getter for attachment preview
  2681. *
  2682. * @name AttachmentViewer.getAttachmentPreview
  2683. * @function
  2684. * @return {jQuery}
  2685. */
  2686. me.getAttachmentPreview = function () {
  2687. return $attachmentPreview;
  2688. };
  2689. /**
  2690. * getter for file data, returns the file contents
  2691. *
  2692. * @name AttachmentViewer.getFile
  2693. * @function
  2694. * @return {string}
  2695. */
  2696. me.getFile = function () {
  2697. return file;
  2698. };
  2699. /**
  2700. * initiate
  2701. *
  2702. * preloads jQuery elements
  2703. *
  2704. * @name AttachmentViewer.init
  2705. * @function
  2706. */
  2707. me.init = function()
  2708. {
  2709. $attachment = $('#attachment');
  2710. if($attachment.length){
  2711. $attachmentLink = $('#attachment a');
  2712. $attachmentPreview = $('#attachmentPreview');
  2713. $dragAndDropFileName = $('#dragAndDropFileName');
  2714. $fileInput = $('#file');
  2715. addDragDropHandler();
  2716. addClipboardEventHandler();
  2717. }
  2718. }
  2719. return me;
  2720. })();
  2721. /**
  2722. * (view) Shows discussion thread and handles replies
  2723. *
  2724. * @name DiscussionViewer
  2725. * @class
  2726. */
  2727. const DiscussionViewer = (function () {
  2728. const me = {};
  2729. let $commentTail,
  2730. $discussion,
  2731. $reply,
  2732. $replyMessage,
  2733. $replyNickname,
  2734. $replyStatus,
  2735. $commentContainer,
  2736. replyCommentId;
  2737. /**
  2738. * initializes the templates
  2739. *
  2740. * @name DiscussionViewer.initTemplates
  2741. * @private
  2742. * @function
  2743. */
  2744. function initTemplates()
  2745. {
  2746. $reply = Model.getTemplate('reply');
  2747. $replyMessage = $reply.find('#replymessage');
  2748. $replyNickname = $reply.find('#nickname');
  2749. $replyStatus = $reply.find('#replystatus');
  2750. // cache jQuery elements
  2751. $commentTail = Model.getTemplate('commenttail');
  2752. }
  2753. /**
  2754. * open the comment entry when clicking the "Reply" button of a comment
  2755. *
  2756. * @name DiscussionViewer.openReply
  2757. * @private
  2758. * @function
  2759. * @param {Event} event
  2760. */
  2761. function openReply(event)
  2762. {
  2763. const $source = $(event.target);
  2764. // clear input
  2765. $replyMessage.val('');
  2766. $replyNickname.val('');
  2767. // get comment id from source element
  2768. replyCommentId = $source.parent().prop('id').split('_')[1];
  2769. // move to correct position
  2770. $source.after($reply);
  2771. // show
  2772. $reply.removeClass('hidden');
  2773. $replyMessage.focus();
  2774. event.preventDefault();
  2775. }
  2776. /**
  2777. * custom handler for displaying notifications in own status message area
  2778. *
  2779. * @name DiscussionViewer.handleNotification
  2780. * @function
  2781. * @param {string} alertType
  2782. * @return {bool|jQuery}
  2783. */
  2784. me.handleNotification = function(alertType)
  2785. {
  2786. // ignore loading messages
  2787. if (alertType === 'loading') {
  2788. return false;
  2789. }
  2790. if (alertType === 'danger') {
  2791. $replyStatus.removeClass('alert-info');
  2792. $replyStatus.addClass('alert-danger');
  2793. $replyStatus.find(':first').removeClass('glyphicon-alert');
  2794. $replyStatus.find(':first').addClass('glyphicon-info-sign');
  2795. } else {
  2796. $replyStatus.removeClass('alert-danger');
  2797. $replyStatus.addClass('alert-info');
  2798. $replyStatus.find(':first').removeClass('glyphicon-info-sign');
  2799. $replyStatus.find(':first').addClass('glyphicon-alert');
  2800. }
  2801. return $replyStatus;
  2802. };
  2803. /**
  2804. * adds another comment
  2805. *
  2806. * @name DiscussionViewer.addComment
  2807. * @function
  2808. * @param {Comment} comment
  2809. * @param {string} commentText
  2810. * @param {string} nickname
  2811. */
  2812. me.addComment = function(comment, commentText, nickname)
  2813. {
  2814. if (commentText === '') {
  2815. commentText = 'comment decryption failed';
  2816. }
  2817. // create new comment based on template
  2818. const $commentEntry = Model.getTemplate('comment');
  2819. $commentEntry.prop('id', 'comment_' + comment.id);
  2820. const $commentEntryData = $commentEntry.find('div.commentdata');
  2821. // set & parse text
  2822. $commentEntryData.html(
  2823. DOMPurify.sanitize(
  2824. Helper.urls2links(commentText)
  2825. )
  2826. );
  2827. // set nickname
  2828. if (nickname.length > 0) {
  2829. $commentEntry.find('span.nickname').text(nickname);
  2830. } else {
  2831. $commentEntry.find('span.nickname').html('<i></i>');
  2832. I18n._($commentEntry.find('span.nickname i'), 'Anonymous');
  2833. }
  2834. // set date
  2835. $commentEntry.find('span.commentdate')
  2836. .text(' (' + (new Date(comment.getCreated() * 1000).toLocaleString()) + ')')
  2837. .attr('title', 'CommentID: ' + comment.id);
  2838. // if an avatar is available, display it
  2839. const icon = comment.getIcon();
  2840. if (icon) {
  2841. $commentEntry.find('span.nickname')
  2842. .before(
  2843. '<img src="' + icon + '" class="vizhash" /> '
  2844. );
  2845. $(document).on('languageLoaded', function () {
  2846. $commentEntry.find('img.vizhash')
  2847. .prop('title', I18n._('Avatar generated from IP address'));
  2848. });
  2849. }
  2850. // starting point (default value/fallback)
  2851. let $place = $commentContainer;
  2852. // if parent comment exists
  2853. const $parentComment = $('#comment_' + comment.parentid);
  2854. if ($parentComment.length) {
  2855. // use parent as position for new comment, so it is shifted
  2856. // to the right
  2857. $place = $parentComment;
  2858. }
  2859. // finally append comment
  2860. $place.append($commentEntry);
  2861. };
  2862. /**
  2863. * finishes the discussion area after last comment
  2864. *
  2865. * @name DiscussionViewer.finishDiscussion
  2866. * @function
  2867. */
  2868. me.finishDiscussion = function()
  2869. {
  2870. // add 'add new comment' area
  2871. $commentContainer.append($commentTail);
  2872. // show discussions
  2873. $discussion.removeClass('hidden');
  2874. };
  2875. /**
  2876. * removes the old discussion and prepares everything for creating a new
  2877. * one.
  2878. *
  2879. * @name DiscussionViewer.prepareNewDiscussion
  2880. * @function
  2881. */
  2882. me.prepareNewDiscussion = function()
  2883. {
  2884. $commentContainer.html('');
  2885. $discussion.addClass('hidden');
  2886. // (re-)init templates
  2887. initTemplates();
  2888. };
  2889. /**
  2890. * returns the users message from the reply form
  2891. *
  2892. * @name DiscussionViewer.getReplyMessage
  2893. * @function
  2894. * @return {String}
  2895. */
  2896. me.getReplyMessage = function()
  2897. {
  2898. return $replyMessage.val();
  2899. };
  2900. /**
  2901. * returns the users nickname (if any) from the reply form
  2902. *
  2903. * @name DiscussionViewer.getReplyNickname
  2904. * @function
  2905. * @return {String}
  2906. */
  2907. me.getReplyNickname = function()
  2908. {
  2909. return $replyNickname.val();
  2910. };
  2911. /**
  2912. * returns the id of the parent comment the user is replying to
  2913. *
  2914. * @name DiscussionViewer.getReplyCommentId
  2915. * @function
  2916. * @return {int|undefined}
  2917. */
  2918. me.getReplyCommentId = function()
  2919. {
  2920. return replyCommentId;
  2921. };
  2922. /**
  2923. * highlights a specific comment and scrolls to it if necessary
  2924. *
  2925. * @name DiscussionViewer.highlightComment
  2926. * @function
  2927. * @param {string} commentId
  2928. * @param {bool} fadeOut - whether to fade out the comment
  2929. */
  2930. me.highlightComment = function(commentId, fadeOut)
  2931. {
  2932. const $comment = $('#comment_' + commentId);
  2933. // in case comment does not exist, cancel
  2934. if ($comment.length === 0) {
  2935. return;
  2936. }
  2937. $comment.addClass('highlight');
  2938. const highlightComment = function () {
  2939. if (fadeOut === true) {
  2940. setTimeout(function () {
  2941. $comment.removeClass('highlight');
  2942. }, 300);
  2943. }
  2944. };
  2945. if (UiHelper.isVisible($comment)) {
  2946. return highlightComment();
  2947. }
  2948. UiHelper.scrollTo($comment, 100, 'swing', highlightComment);
  2949. };
  2950. /**
  2951. * initiate
  2952. *
  2953. * preloads jQuery elements
  2954. *
  2955. * @name DiscussionViewer.init
  2956. * @function
  2957. */
  2958. me.init = function()
  2959. {
  2960. // bind events to templates (so they are later cloned)
  2961. $('#commenttailtemplate, #commenttemplate').find('button').on('click', openReply);
  2962. $('#replytemplate').find('button').on('click', PasteEncrypter.sendComment);
  2963. $commentContainer = $('#commentcontainer');
  2964. $discussion = $('#discussion');
  2965. };
  2966. return me;
  2967. })();
  2968. /**
  2969. * Manage top (navigation) bar
  2970. *
  2971. * @name TopNav
  2972. * @param {object} window
  2973. * @param {object} document
  2974. * @class
  2975. */
  2976. const TopNav = (function (window, document) {
  2977. const me = {};
  2978. let createButtonsDisplayed = false,
  2979. viewButtonsDisplayed = false,
  2980. $attach,
  2981. $burnAfterReading,
  2982. $burnAfterReadingOption,
  2983. $cloneButton,
  2984. $customAttachment,
  2985. $expiration,
  2986. $fileRemoveButton,
  2987. $fileWrap,
  2988. $formatter,
  2989. $newButton,
  2990. $openDiscussion,
  2991. $openDiscussionOption,
  2992. $password,
  2993. $passwordInput,
  2994. $rawTextButton,
  2995. $qrCodeLink,
  2996. $sendButton,
  2997. $retryButton,
  2998. pasteExpiration = '1week',
  2999. retryButtonCallback;
  3000. /**
  3001. * set the expiration on bootstrap templates in dropdown
  3002. *
  3003. * @name TopNav.updateExpiration
  3004. * @private
  3005. * @function
  3006. * @param {Event} event
  3007. */
  3008. function updateExpiration(event)
  3009. {
  3010. // get selected option
  3011. const target = $(event.target);
  3012. // update dropdown display and save new expiration time
  3013. $('#pasteExpirationDisplay').text(target.text());
  3014. pasteExpiration = target.data('expiration');
  3015. event.preventDefault();
  3016. }
  3017. /**
  3018. * set the format on bootstrap templates in dropdown
  3019. *
  3020. * @name TopNav.updateFormat
  3021. * @private
  3022. * @function
  3023. * @param {Event} event
  3024. */
  3025. function updateFormat(event)
  3026. {
  3027. // get selected option
  3028. const $target = $(event.target);
  3029. // update dropdown display and save new format
  3030. const newFormat = $target.data('format');
  3031. $('#pasteFormatterDisplay').text($target.text());
  3032. PasteViewer.setFormat(newFormat);
  3033. // update preview
  3034. if (Editor.isPreview()) {
  3035. PasteViewer.run();
  3036. }
  3037. event.preventDefault();
  3038. }
  3039. /**
  3040. * when "burn after reading" is checked, disable discussion
  3041. *
  3042. * @name TopNav.changeBurnAfterReading
  3043. * @private
  3044. * @function
  3045. */
  3046. function changeBurnAfterReading()
  3047. {
  3048. if ($burnAfterReading.is(':checked')) {
  3049. $openDiscussionOption.addClass('buttondisabled');
  3050. $openDiscussion.prop('checked', false);
  3051. // if button is actually disabled, force-enable it and uncheck other button
  3052. $burnAfterReadingOption.removeClass('buttondisabled');
  3053. } else {
  3054. $openDiscussionOption.removeClass('buttondisabled');
  3055. }
  3056. }
  3057. /**
  3058. * when discussion is checked, disable "burn after reading"
  3059. *
  3060. * @name TopNav.changeOpenDiscussion
  3061. * @private
  3062. * @function
  3063. */
  3064. function changeOpenDiscussion()
  3065. {
  3066. if ($openDiscussion.is(':checked')) {
  3067. $burnAfterReadingOption.addClass('buttondisabled');
  3068. $burnAfterReading.prop('checked', false);
  3069. // if button is actually disabled, force-enable it and uncheck other button
  3070. $openDiscussionOption.removeClass('buttondisabled');
  3071. } else {
  3072. $burnAfterReadingOption.removeClass('buttondisabled');
  3073. }
  3074. }
  3075. /**
  3076. * return raw text
  3077. *
  3078. * @name TopNav.rawText
  3079. * @private
  3080. * @function
  3081. */
  3082. function rawText()
  3083. {
  3084. TopNav.hideAllButtons();
  3085. Alert.showLoading('Showing raw text…', 'time');
  3086. let paste = PasteViewer.getText();
  3087. // push a new state to allow back navigation with browser back button
  3088. history.pushState(
  3089. {type: 'raw'},
  3090. document.title,
  3091. // recreate paste URL
  3092. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  3093. CryptTool.base58encode(Model.getPasteKey())
  3094. );
  3095. // we use text/html instead of text/plain to avoid a bug when
  3096. // reloading the raw text view (it reverts to type text/html)
  3097. const $head = $('head').children().not('noscript, script, link[type="text/css"]'),
  3098. newDoc = document.open('text/html', 'replace');
  3099. newDoc.write('<!DOCTYPE html><html><head>');
  3100. for (let i = 0; i < $head.length; ++i) {
  3101. newDoc.write($head[i].outerHTML);
  3102. }
  3103. newDoc.write('</head><body><pre>' + DOMPurify.sanitize($('<div />').text(paste).html()) + '</pre></body></html>');
  3104. newDoc.close();
  3105. }
  3106. /**
  3107. * saves the language in a cookie and reloads the page
  3108. *
  3109. * @name TopNav.setLanguage
  3110. * @private
  3111. * @function
  3112. * @param {Event} event
  3113. */
  3114. function setLanguage(event)
  3115. {
  3116. document.cookie = 'lang=' + $(event.target).data('lang');
  3117. UiHelper.reloadHome();
  3118. }
  3119. /**
  3120. * hides all messages and creates a new paste
  3121. *
  3122. * @name TopNav.clickNewPaste
  3123. * @private
  3124. * @function
  3125. */
  3126. function clickNewPaste()
  3127. {
  3128. Controller.hideStatusMessages();
  3129. Controller.newPaste();
  3130. }
  3131. /**
  3132. * retrys some callback registered before
  3133. *
  3134. * @name TopNav.clickRetryButton
  3135. * @private
  3136. * @function
  3137. * @param {Event} event
  3138. */
  3139. function clickRetryButton(event)
  3140. {
  3141. retryButtonCallback(event);
  3142. }
  3143. /**
  3144. * removes the existing attachment
  3145. *
  3146. * @name TopNav.removeAttachment
  3147. * @private
  3148. * @function
  3149. * @param {Event} event
  3150. */
  3151. function removeAttachment(event)
  3152. {
  3153. // if custom attachment is used, remove it first
  3154. if (!$customAttachment.hasClass('hidden')) {
  3155. AttachmentViewer.removeAttachment();
  3156. $customAttachment.addClass('hidden');
  3157. $fileWrap.removeClass('hidden');
  3158. }
  3159. // in any case, remove saved attachment data
  3160. AttachmentViewer.removeAttachmentData();
  3161. // hide UI for selected files
  3162. // our up-to-date jQuery can handle it :)
  3163. $fileWrap.find('input').val('');
  3164. AttachmentViewer.clearDragAndDrop();
  3165. // pevent '#' from appearing in the URL
  3166. event.preventDefault();
  3167. }
  3168. /**
  3169. * Shows the QR code of the current paste (URL).
  3170. *
  3171. * @name TopNav.displayQrCode
  3172. * @private
  3173. * @function
  3174. */
  3175. function displayQrCode()
  3176. {
  3177. const qrCanvas = kjua({
  3178. render: 'canvas',
  3179. text: window.location.href
  3180. });
  3181. $('#qrcode-display').html(qrCanvas);
  3182. }
  3183. /**
  3184. * Shows all navigation elements for viewing an existing paste
  3185. *
  3186. * @name TopNav.showViewButtons
  3187. * @function
  3188. */
  3189. me.showViewButtons = function()
  3190. {
  3191. if (viewButtonsDisplayed) {
  3192. return;
  3193. }
  3194. $newButton.removeClass('hidden');
  3195. $cloneButton.removeClass('hidden');
  3196. $rawTextButton.removeClass('hidden');
  3197. $qrCodeLink.removeClass('hidden');
  3198. viewButtonsDisplayed = true;
  3199. };
  3200. /**
  3201. * Hides all navigation elements for viewing an existing paste
  3202. *
  3203. * @name TopNav.hideViewButtons
  3204. * @function
  3205. */
  3206. me.hideViewButtons = function()
  3207. {
  3208. if (!viewButtonsDisplayed) {
  3209. return;
  3210. }
  3211. $cloneButton.addClass('hidden');
  3212. $newButton.addClass('hidden');
  3213. $rawTextButton.addClass('hidden');
  3214. $qrCodeLink.addClass('hidden');
  3215. viewButtonsDisplayed = false;
  3216. };
  3217. /**
  3218. * Hides all elements belonging to existing pastes
  3219. *
  3220. * @name TopNav.hideAllButtons
  3221. * @function
  3222. */
  3223. me.hideAllButtons = function()
  3224. {
  3225. me.hideViewButtons();
  3226. me.hideCreateButtons();
  3227. };
  3228. /**
  3229. * shows all elements needed when creating a new paste
  3230. *
  3231. * @name TopNav.showCreateButtons
  3232. * @function
  3233. */
  3234. me.showCreateButtons = function()
  3235. {
  3236. if (createButtonsDisplayed) {
  3237. return;
  3238. }
  3239. $attach.removeClass('hidden');
  3240. $burnAfterReadingOption.removeClass('hidden');
  3241. $expiration.removeClass('hidden');
  3242. $formatter.removeClass('hidden');
  3243. $newButton.removeClass('hidden');
  3244. $openDiscussionOption.removeClass('hidden');
  3245. $password.removeClass('hidden');
  3246. $sendButton.removeClass('hidden');
  3247. createButtonsDisplayed = true;
  3248. };
  3249. /**
  3250. * shows all elements needed when creating a new paste
  3251. *
  3252. * @name TopNav.hideCreateButtons
  3253. * @function
  3254. */
  3255. me.hideCreateButtons = function()
  3256. {
  3257. if (!createButtonsDisplayed) {
  3258. return;
  3259. }
  3260. $newButton.addClass('hidden');
  3261. $sendButton.addClass('hidden');
  3262. $expiration.addClass('hidden');
  3263. $formatter.addClass('hidden');
  3264. $burnAfterReadingOption.addClass('hidden');
  3265. $openDiscussionOption.addClass('hidden');
  3266. $password.addClass('hidden');
  3267. $attach.addClass('hidden');
  3268. createButtonsDisplayed = false;
  3269. };
  3270. /**
  3271. * only shows the "new paste" button
  3272. *
  3273. * @name TopNav.showNewPasteButton
  3274. * @function
  3275. */
  3276. me.showNewPasteButton = function()
  3277. {
  3278. $newButton.removeClass('hidden');
  3279. };
  3280. /**
  3281. * only shows the "retry" button
  3282. *
  3283. * @name TopNav.showRetryButton
  3284. * @function
  3285. */
  3286. me.showRetryButton = function()
  3287. {
  3288. $retryButton.removeClass('hidden');
  3289. }
  3290. /**
  3291. * hides the "retry" button
  3292. *
  3293. * @name TopNav.hideRetryButton
  3294. * @function
  3295. */
  3296. me.hideRetryButton = function()
  3297. {
  3298. $retryButton.addClass('hidden');
  3299. }
  3300. /**
  3301. * only hides the clone button
  3302. *
  3303. * @name TopNav.hideCloneButton
  3304. * @function
  3305. */
  3306. me.hideCloneButton = function()
  3307. {
  3308. $cloneButton.addClass('hidden');
  3309. };
  3310. /**
  3311. * only hides the raw text button
  3312. *
  3313. * @name TopNav.hideRawButton
  3314. * @function
  3315. */
  3316. me.hideRawButton = function()
  3317. {
  3318. $rawTextButton.addClass('hidden');
  3319. };
  3320. /**
  3321. * hides the file selector in attachment
  3322. *
  3323. * @name TopNav.hideFileSelector
  3324. * @function
  3325. */
  3326. me.hideFileSelector = function()
  3327. {
  3328. $fileWrap.addClass('hidden');
  3329. };
  3330. /**
  3331. * shows the custom attachment
  3332. *
  3333. * @name TopNav.showCustomAttachment
  3334. * @function
  3335. */
  3336. me.showCustomAttachment = function()
  3337. {
  3338. $customAttachment.removeClass('hidden');
  3339. };
  3340. /**
  3341. * collapses the navigation bar, only if expanded
  3342. *
  3343. * @name TopNav.collapseBar
  3344. * @function
  3345. */
  3346. me.collapseBar = function()
  3347. {
  3348. if ($('#navbar').attr('aria-expanded') === 'true') {
  3349. $('.navbar-toggle').click();
  3350. }
  3351. };
  3352. /**
  3353. * returns the currently set expiration time
  3354. *
  3355. * @name TopNav.getExpiration
  3356. * @function
  3357. * @return {int}
  3358. */
  3359. me.getExpiration = function()
  3360. {
  3361. return pasteExpiration;
  3362. };
  3363. /**
  3364. * returns the currently selected file(s)
  3365. *
  3366. * @name TopNav.getFileList
  3367. * @function
  3368. * @return {FileList|null}
  3369. */
  3370. me.getFileList = function()
  3371. {
  3372. const $file = $('#file');
  3373. // if no file given, return null
  3374. if (!$file.length || !$file[0].files.length) {
  3375. return null;
  3376. }
  3377. // ensure the selected file is still accessible
  3378. if (!($file[0].files && $file[0].files[0])) {
  3379. return null;
  3380. }
  3381. return $file[0].files;
  3382. };
  3383. /**
  3384. * returns the state of the burn after reading checkbox
  3385. *
  3386. * @name TopNav.getExpiration
  3387. * @function
  3388. * @return {bool}
  3389. */
  3390. me.getBurnAfterReading = function()
  3391. {
  3392. return $burnAfterReading.is(':checked');
  3393. };
  3394. /**
  3395. * returns the state of the discussion checkbox
  3396. *
  3397. * @name TopNav.getOpenDiscussion
  3398. * @function
  3399. * @return {bool}
  3400. */
  3401. me.getOpenDiscussion = function()
  3402. {
  3403. return $openDiscussion.is(':checked');
  3404. };
  3405. /**
  3406. * returns the entered password
  3407. *
  3408. * @name TopNav.getPassword
  3409. * @function
  3410. * @return {string}
  3411. */
  3412. me.getPassword = function()
  3413. {
  3414. return $passwordInput.val();
  3415. };
  3416. /**
  3417. * returns the element where custom attachments can be placed
  3418. *
  3419. * Used by AttachmentViewer when an attachment is cloned here.
  3420. *
  3421. * @name TopNav.getCustomAttachment
  3422. * @function
  3423. * @return {jQuery}
  3424. */
  3425. me.getCustomAttachment = function()
  3426. {
  3427. return $customAttachment;
  3428. };
  3429. /**
  3430. * Set a function to call when the retry button is clicked.
  3431. *
  3432. * @name TopNav.setRetryCallback
  3433. * @function
  3434. * @param {function} callback
  3435. */
  3436. me.setRetryCallback = function(callback)
  3437. {
  3438. retryButtonCallback = callback;
  3439. }
  3440. /**
  3441. * init navigation manager
  3442. *
  3443. * preloads jQuery elements
  3444. *
  3445. * @name TopNav.init
  3446. * @function
  3447. */
  3448. me.init = function()
  3449. {
  3450. $attach = $('#attach');
  3451. $burnAfterReading = $('#burnafterreading');
  3452. $burnAfterReadingOption = $('#burnafterreadingoption');
  3453. $cloneButton = $('#clonebutton');
  3454. $customAttachment = $('#customattachment');
  3455. $expiration = $('#expiration');
  3456. $fileRemoveButton = $('#fileremovebutton');
  3457. $fileWrap = $('#filewrap');
  3458. $formatter = $('#formatter');
  3459. $newButton = $('#newbutton');
  3460. $openDiscussion = $('#opendiscussion');
  3461. $openDiscussionOption = $('#opendiscussionoption');
  3462. $password = $('#password');
  3463. $passwordInput = $('#passwordinput');
  3464. $rawTextButton = $('#rawtextbutton');
  3465. $retryButton = $('#retrybutton');
  3466. $sendButton = $('#sendbutton');
  3467. $qrCodeLink = $('#qrcodelink');
  3468. // bootstrap template drop down
  3469. $('#language ul.dropdown-menu li a').click(setLanguage);
  3470. // page template drop down
  3471. $('#language select option').click(setLanguage);
  3472. // bind events
  3473. $burnAfterReading.change(changeBurnAfterReading);
  3474. $openDiscussionOption.change(changeOpenDiscussion);
  3475. $newButton.click(clickNewPaste);
  3476. $sendButton.click(PasteEncrypter.sendPaste);
  3477. $cloneButton.click(Controller.clonePaste);
  3478. $rawTextButton.click(rawText);
  3479. $retryButton.click(clickRetryButton);
  3480. $fileRemoveButton.click(removeAttachment);
  3481. $qrCodeLink.click(displayQrCode);
  3482. // bootstrap template drop downs
  3483. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  3484. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  3485. // initiate default state of checkboxes
  3486. changeBurnAfterReading();
  3487. changeOpenDiscussion();
  3488. // get default value from template or fall back to set value
  3489. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  3490. createButtonsDisplayed = false;
  3491. viewButtonsDisplayed = false;
  3492. };
  3493. return me;
  3494. })(window, document);
  3495. /**
  3496. * Responsible for AJAX requests, transparently handles encryption…
  3497. *
  3498. * @name ServerInteraction
  3499. * @class
  3500. */
  3501. const ServerInteraction = (function () {
  3502. const me = {};
  3503. let successFunc = null,
  3504. failureFunc = null,
  3505. symmetricKey = null,
  3506. url,
  3507. data,
  3508. password;
  3509. /**
  3510. * public variable ('constant') for errors to prevent magic numbers
  3511. *
  3512. * @name ServerInteraction.error
  3513. * @readonly
  3514. * @enum {Object}
  3515. */
  3516. me.error = {
  3517. okay: 0,
  3518. custom: 1,
  3519. unknown: 2,
  3520. serverError: 3
  3521. };
  3522. /**
  3523. * ajaxHeaders to send in AJAX requests
  3524. *
  3525. * @name ServerInteraction.ajaxHeaders
  3526. * @private
  3527. * @readonly
  3528. * @enum {Object}
  3529. */
  3530. const ajaxHeaders = {'X-Requested-With': 'JSONHttpRequest'};
  3531. /**
  3532. * called after successful upload
  3533. *
  3534. * @name ServerInteraction.success
  3535. * @private
  3536. * @function
  3537. * @param {int} status
  3538. * @param {int} result - optional
  3539. */
  3540. function success(status, result)
  3541. {
  3542. if (successFunc !== null) {
  3543. // add useful data to result
  3544. result.encryptionKey = symmetricKey;
  3545. successFunc(status, result);
  3546. }
  3547. }
  3548. /**
  3549. * called after a upload failure
  3550. *
  3551. * @name ServerInteraction.fail
  3552. * @private
  3553. * @function
  3554. * @param {int} status - internal code
  3555. * @param {int} result - original error code
  3556. */
  3557. function fail(status, result)
  3558. {
  3559. if (failureFunc !== null) {
  3560. failureFunc(status, result);
  3561. }
  3562. }
  3563. /**
  3564. * actually uploads the data
  3565. *
  3566. * @name ServerInteraction.run
  3567. * @function
  3568. */
  3569. me.run = function()
  3570. {
  3571. let isPost = Object.keys(data).length > 0,
  3572. ajaxParams = {
  3573. type: isPost ? 'POST' : 'GET',
  3574. url: url,
  3575. headers: ajaxHeaders,
  3576. dataType: 'json',
  3577. success: function(result) {
  3578. if (result.status === 0) {
  3579. success(0, result);
  3580. } else if (result.status === 1) {
  3581. fail(1, result);
  3582. } else {
  3583. fail(2, result);
  3584. }
  3585. }
  3586. };
  3587. if (isPost) {
  3588. ajaxParams.data = JSON.stringify(data);
  3589. }
  3590. $.ajax(ajaxParams).fail(function(jqXHR, textStatus, errorThrown) {
  3591. console.error(textStatus, errorThrown);
  3592. fail(3, jqXHR);
  3593. });
  3594. };
  3595. /**
  3596. * return currently set data, used in unit testing
  3597. *
  3598. * @name ServerInteraction.getData
  3599. * @function
  3600. */
  3601. me.getData = function()
  3602. {
  3603. return data;
  3604. };
  3605. /**
  3606. * set success function
  3607. *
  3608. * @name ServerInteraction.setUrl
  3609. * @function
  3610. * @param {function} newUrl
  3611. */
  3612. me.setUrl = function(newUrl)
  3613. {
  3614. url = newUrl;
  3615. };
  3616. /**
  3617. * sets the password to use (first value) and optionally also the
  3618. * encryption key (not recommended, it is automatically generated).
  3619. *
  3620. * Note: Call this after prepare() as prepare() resets these values.
  3621. *
  3622. * @name ServerInteraction.setCryptValues
  3623. * @function
  3624. * @param {string} newPassword
  3625. * @param {string} newKey - optional
  3626. */
  3627. me.setCryptParameters = function(newPassword, newKey)
  3628. {
  3629. password = newPassword;
  3630. if (typeof newKey !== 'undefined') {
  3631. symmetricKey = newKey;
  3632. }
  3633. };
  3634. /**
  3635. * set success function
  3636. *
  3637. * @name ServerInteraction.setSuccess
  3638. * @function
  3639. * @param {function} func
  3640. */
  3641. me.setSuccess = function(func)
  3642. {
  3643. successFunc = func;
  3644. };
  3645. /**
  3646. * set failure function
  3647. *
  3648. * @name ServerInteraction.setFailure
  3649. * @function
  3650. * @param {function} func
  3651. */
  3652. me.setFailure = function(func)
  3653. {
  3654. failureFunc = func;
  3655. };
  3656. /**
  3657. * prepares a new upload
  3658. *
  3659. * Call this when doing a new upload to reset any data from potential
  3660. * previous uploads. Must be called before any other method of this
  3661. * module.
  3662. *
  3663. * @name ServerInteraction.prepare
  3664. * @function
  3665. * @return {object}
  3666. */
  3667. me.prepare = function()
  3668. {
  3669. // entropy should already be checked!
  3670. // reset password
  3671. password = '';
  3672. // reset key, so it a new one is generated when it is used
  3673. symmetricKey = null;
  3674. // reset data
  3675. successFunc = null;
  3676. failureFunc = null;
  3677. url = Helper.baseUri();
  3678. data = {};
  3679. };
  3680. /**
  3681. * encrypts and sets the data
  3682. *
  3683. * @name ServerInteraction.setCipherMessage
  3684. * @async
  3685. * @function
  3686. * @param {object} cipherMessage
  3687. */
  3688. me.setCipherMessage = async function(cipherMessage)
  3689. {
  3690. if (
  3691. symmetricKey === null ||
  3692. (typeof symmetricKey === 'string' && symmetricKey === '')
  3693. ) {
  3694. symmetricKey = CryptTool.getSymmetricKey();
  3695. }
  3696. if (!data.hasOwnProperty('adata')) {
  3697. data['adata'] = [];
  3698. }
  3699. let cipherResult = await CryptTool.cipher(symmetricKey, password, JSON.stringify(cipherMessage), data['adata']);
  3700. data['v'] = 2;
  3701. data['ct'] = cipherResult[0];
  3702. data['adata'] = cipherResult[1];
  3703. };
  3704. /**
  3705. * set the additional metadata to send unencrypted
  3706. *
  3707. * @name ServerInteraction.setUnencryptedData
  3708. * @function
  3709. * @param {string} index
  3710. * @param {mixed} element
  3711. */
  3712. me.setUnencryptedData = function(index, element)
  3713. {
  3714. data[index] = element;
  3715. };
  3716. /**
  3717. * Helper, which parses shows a general error message based on the result of the ServerInteraction
  3718. *
  3719. * @name ServerInteraction.parseUploadError
  3720. * @function
  3721. * @param {int} status
  3722. * @param {object} data
  3723. * @param {string} doThisThing - a human description of the action, which was tried
  3724. * @return {array}
  3725. */
  3726. me.parseUploadError = function(status, data, doThisThing) {
  3727. let errorArray;
  3728. switch (status) {
  3729. case me.error.custom:
  3730. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  3731. break;
  3732. case me.error.unknown:
  3733. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  3734. break;
  3735. case me.error.serverError:
  3736. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  3737. break;
  3738. default:
  3739. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  3740. break;
  3741. }
  3742. return errorArray;
  3743. };
  3744. return me;
  3745. })();
  3746. /**
  3747. * (controller) Responsible for encrypting paste and sending it to server.
  3748. *
  3749. * Does upload, encryption is done transparently by ServerInteraction.
  3750. *
  3751. * @name PasteEncrypter
  3752. * @class
  3753. */
  3754. const PasteEncrypter = (function () {
  3755. const me = {};
  3756. let requirementsChecked = false;
  3757. /**
  3758. * called after successful paste upload
  3759. *
  3760. * @name PasteEncrypter.showCreatedPaste
  3761. * @private
  3762. * @function
  3763. * @param {int} status
  3764. * @param {object} data
  3765. */
  3766. function showCreatedPaste(status, data) {
  3767. Alert.hideLoading();
  3768. Alert.hideMessages();
  3769. // show notification
  3770. const baseUri = Helper.baseUri() + '?',
  3771. url = baseUri + data.id + '#' + CryptTool.base58encode(data.encryptionKey),
  3772. deleteUrl = baseUri + $.param({pasteid: data.id, deletetoken: data.deletetoken});
  3773. PasteStatus.createPasteNotification(url, deleteUrl);
  3774. // show new URL in browser bar
  3775. history.pushState({type: 'newpaste'}, document.title, url);
  3776. TopNav.showViewButtons();
  3777. TopNav.hideRawButton();
  3778. Editor.hide();
  3779. // parse and show text
  3780. // (preparation already done in me.sendPaste())
  3781. PasteViewer.run();
  3782. }
  3783. /**
  3784. * called after successful comment upload
  3785. *
  3786. * @name PasteEncrypter.showUploadedComment
  3787. * @private
  3788. * @function
  3789. * @param {int} status
  3790. * @param {object} data
  3791. */
  3792. function showUploadedComment(status, data) {
  3793. // show success message
  3794. Alert.showStatus('Comment posted.');
  3795. // reload paste
  3796. Controller.refreshPaste(function () {
  3797. // highlight sent comment
  3798. DiscussionViewer.highlightComment(data.id, true);
  3799. // reset error handler
  3800. Alert.setCustomHandler(null);
  3801. });
  3802. }
  3803. /**
  3804. * send a reply in a discussion
  3805. *
  3806. * @name PasteEncrypter.sendComment
  3807. * @async
  3808. * @function
  3809. */
  3810. me.sendComment = async function()
  3811. {
  3812. Alert.hideMessages();
  3813. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  3814. // UI loading state
  3815. TopNav.hideAllButtons();
  3816. Alert.showLoading('Sending comment…', 'cloud-upload');
  3817. // get data
  3818. const plainText = DiscussionViewer.getReplyMessage(),
  3819. nickname = DiscussionViewer.getReplyNickname(),
  3820. parentid = DiscussionViewer.getReplyCommentId();
  3821. // do not send if there is no data
  3822. if (plainText.length === 0) {
  3823. // revert loading status…
  3824. Alert.hideLoading();
  3825. Alert.setCustomHandler(null);
  3826. TopNav.showViewButtons();
  3827. return;
  3828. }
  3829. // prepare server interaction
  3830. ServerInteraction.prepare();
  3831. ServerInteraction.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  3832. // set success/fail functions
  3833. ServerInteraction.setSuccess(showUploadedComment);
  3834. ServerInteraction.setFailure(function (status, data) {
  3835. // revert loading status…
  3836. Alert.hideLoading();
  3837. TopNav.showViewButtons();
  3838. // …show error message…
  3839. Alert.showError(
  3840. ServerInteraction.parseUploadError(status, data, 'post comment')
  3841. );
  3842. // …and reset error handler
  3843. Alert.setCustomHandler(null);
  3844. });
  3845. // fill it with unencrypted params
  3846. ServerInteraction.setUnencryptedData('pasteid', Model.getPasteId());
  3847. if (typeof parentid === 'undefined') {
  3848. // if parent id is not set, this is the top-most comment, so use
  3849. // paste id as parent, as the root element of the discussion tree
  3850. ServerInteraction.setUnencryptedData('parentid', Model.getPasteId());
  3851. } else {
  3852. ServerInteraction.setUnencryptedData('parentid', parentid);
  3853. }
  3854. // prepare cypher message
  3855. let cipherMessage = {
  3856. 'comment': plainText
  3857. };
  3858. if (nickname.length > 0) {
  3859. cipherMessage['nickname'] = nickname;
  3860. }
  3861. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  3862. ServerInteraction.run();
  3863. };
  3864. /**
  3865. * sends a new paste to server
  3866. *
  3867. * @name PasteEncrypter.sendPaste
  3868. * @async
  3869. * @function
  3870. */
  3871. me.sendPaste = async function()
  3872. {
  3873. // hide previous (error) messages
  3874. Controller.hideStatusMessages();
  3875. // UI loading state
  3876. TopNav.hideAllButtons();
  3877. Alert.showLoading('Sending paste…', 'cloud-upload');
  3878. TopNav.collapseBar();
  3879. // get data
  3880. const plainText = Editor.getText(),
  3881. format = PasteViewer.getFormat(),
  3882. // the methods may return different values if no files are attached (null, undefined or false)
  3883. files = TopNav.getFileList() || AttachmentViewer.getFile() || AttachmentViewer.hasAttachment();
  3884. // do not send if there is no data
  3885. if (plainText.length === 0 && !files) {
  3886. // revert loading status…
  3887. Alert.hideLoading();
  3888. TopNav.showCreateButtons();
  3889. return;
  3890. }
  3891. // prepare server interaction
  3892. ServerInteraction.prepare();
  3893. const key = CryptTool.getSymmetricKey(),
  3894. password = TopNav.getPassword();
  3895. ServerInteraction.setCryptParameters(password, key);
  3896. // set success/fail functions
  3897. ServerInteraction.setSuccess(showCreatedPaste);
  3898. ServerInteraction.setFailure(function (status, data) {
  3899. // revert loading status…
  3900. Alert.hideLoading();
  3901. TopNav.showCreateButtons();
  3902. // show error message
  3903. Alert.showError(
  3904. ServerInteraction.parseUploadError(status, data, 'create paste')
  3905. );
  3906. });
  3907. // fill it with unencrypted submitted options
  3908. ServerInteraction.setUnencryptedData('adata', [
  3909. null, format,
  3910. TopNav.getOpenDiscussion() ? 1 : 0,
  3911. TopNav.getBurnAfterReading() ? 1 : 0
  3912. ]);
  3913. ServerInteraction.setUnencryptedData('meta', {
  3914. 'expire': TopNav.getExpiration(),
  3915. 'challenge': await CryptTool.getCredentials(key, password)
  3916. });
  3917. // prepare PasteViewer for later preview
  3918. PasteViewer.setText(plainText);
  3919. PasteViewer.setFormat(format);
  3920. // prepare cypher message
  3921. let file = AttachmentViewer.getAttachmentData(),
  3922. cipherMessage = {
  3923. 'paste': plainText
  3924. };
  3925. if (typeof file !== 'undefined' && file !== null) {
  3926. cipherMessage['attachment'] = file;
  3927. cipherMessage['attachment_name'] = AttachmentViewer.getFile().name;
  3928. } else if (AttachmentViewer.hasAttachment()) {
  3929. // fall back to cloned part
  3930. let attachment = AttachmentViewer.getAttachment();
  3931. cipherMessage['attachment'] = attachment[0];
  3932. cipherMessage['attachment_name'] = attachment[1];
  3933. }
  3934. // encrypt message
  3935. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  3936. // send data
  3937. ServerInteraction.run();
  3938. };
  3939. return me;
  3940. })();
  3941. /**
  3942. * (controller) Responsible for decrypting cipherdata and passing data to view.
  3943. *
  3944. * Only decryption, no download.
  3945. *
  3946. * @name PasteDecrypter
  3947. * @class
  3948. */
  3949. const PasteDecrypter = (function () {
  3950. const me = {};
  3951. /**
  3952. * decrypt data or prompts for password in case of failure
  3953. *
  3954. * @name PasteDecrypter.decryptOrPromptPassword
  3955. * @private
  3956. * @async
  3957. * @function
  3958. * @param {string} key
  3959. * @param {string} password - optional, may be an empty string
  3960. * @param {string} cipherdata
  3961. * @throws {string}
  3962. * @return {false|string} false, when unsuccessful or string (decrypted data)
  3963. */
  3964. async function decryptOrPromptPassword(key, password, cipherdata)
  3965. {
  3966. // try decryption without password
  3967. const plaindata = await CryptTool.decipher(key, password, cipherdata);
  3968. // if it fails, request password
  3969. if (plaindata.length === 0 && password.length === 0) {
  3970. // show prompt
  3971. Prompt.requestPassword(me.run);
  3972. // Thus, we cannot do anything yet, we need to wait for the user
  3973. // input.
  3974. return false;
  3975. }
  3976. // if all tries failed, we can only return an error
  3977. if (plaindata.length === 0) {
  3978. throw 'failed to decipher data';
  3979. }
  3980. return plaindata;
  3981. }
  3982. /**
  3983. * decrypt the actual paste text
  3984. *
  3985. * @name PasteDecrypter.decryptPaste
  3986. * @private
  3987. * @async
  3988. * @function
  3989. * @param {Paste} paste - paste data in object form
  3990. * @param {string} key
  3991. * @param {string} password
  3992. * @throws {string}
  3993. * @return {Promise}
  3994. */
  3995. async function decryptPaste(paste, key, password)
  3996. {
  3997. let pastePlain = await decryptOrPromptPassword(
  3998. key, password,
  3999. paste.getCipherData()
  4000. );
  4001. if (pastePlain === false) {
  4002. if (password.length === 0) {
  4003. throw 'waiting on user to provide a password';
  4004. } else {
  4005. displayDecryptionError('failed to decipher paste text: Incorrect password?');
  4006. throw 'waiting on user to provide correct password';
  4007. }
  4008. }
  4009. let format = '',
  4010. text = '';
  4011. if (paste.v > 1) {
  4012. // version 2 paste
  4013. const pasteMessage = JSON.parse(pastePlain);
  4014. if (pasteMessage.hasOwnProperty('attachment') && pasteMessage.hasOwnProperty('attachment_name')) {
  4015. AttachmentViewer.setAttachment(pasteMessage.attachment, pasteMessage.attachment_name);
  4016. AttachmentViewer.showAttachment();
  4017. }
  4018. pastePlain = pasteMessage.paste;
  4019. } else {
  4020. // version 1 paste
  4021. if (paste.hasOwnProperty('attachment') && paste.hasOwnProperty('attachmentname')) {
  4022. Promise.all([
  4023. CryptTool.decipher(key, password, paste.attachment),
  4024. CryptTool.decipher(key, password, paste.attachmentname)
  4025. ]).then((attachment) => {
  4026. AttachmentViewer.setAttachment(attachment[0], attachment[1]);
  4027. AttachmentViewer.showAttachment();
  4028. });
  4029. }
  4030. }
  4031. PasteViewer.setFormat(paste.getFormat());
  4032. PasteViewer.setText(pastePlain);
  4033. PasteViewer.run();
  4034. }
  4035. /**
  4036. * decrypts all comments and shows them
  4037. *
  4038. * @name PasteDecrypter.decryptComments
  4039. * @private
  4040. * @async
  4041. * @function
  4042. * @param {Paste} paste - paste data in object form
  4043. * @param {string} key
  4044. * @param {string} password
  4045. * @return {Promise}
  4046. */
  4047. async function decryptComments(paste, key, password)
  4048. {
  4049. // remove potential previous discussion
  4050. DiscussionViewer.prepareNewDiscussion();
  4051. const commentDecryptionPromises = [];
  4052. // iterate over comments
  4053. for (let i = 0; i < paste.comments.length; ++i) {
  4054. const comment = new Comment(paste.comments[i]),
  4055. commentPromise = CryptTool.decipher(key, password, comment.getCipherData());
  4056. paste.comments[i] = comment;
  4057. if (comment.v > 1) {
  4058. // version 2 comment
  4059. commentDecryptionPromises.push(
  4060. commentPromise.then(function (commentJson) {
  4061. const commentMessage = JSON.parse(commentJson);
  4062. return [
  4063. commentMessage.comment || '',
  4064. commentMessage.nickname || ''
  4065. ];
  4066. })
  4067. );
  4068. } else {
  4069. // version 1 comment
  4070. commentDecryptionPromises.push(
  4071. Promise.all([
  4072. commentPromise,
  4073. paste.comments[i].meta.hasOwnProperty('nickname') ?
  4074. CryptTool.decipher(key, password, paste.comments[i].meta.nickname) :
  4075. Promise.resolve('')
  4076. ])
  4077. );
  4078. }
  4079. }
  4080. return Promise.all(commentDecryptionPromises).then(function (plaintexts) {
  4081. for (let i = 0; i < paste.comments.length; ++i) {
  4082. if (plaintexts[i][0].length === 0) {
  4083. continue;
  4084. }
  4085. DiscussionViewer.addComment(
  4086. paste.comments[i],
  4087. plaintexts[i][0],
  4088. plaintexts[i][1]
  4089. );
  4090. }
  4091. DiscussionViewer.finishDiscussion();
  4092. });
  4093. }
  4094. /**
  4095. * displays and logs decryption errors
  4096. *
  4097. * @name PasteDecrypter.displayDecryptionError
  4098. * @private
  4099. * @function
  4100. * @param {string} message
  4101. */
  4102. function displayDecryptionError(message)
  4103. {
  4104. Alert.hideLoading();
  4105. // log detailed error, but display generic translation
  4106. console.error(message);
  4107. Alert.showError('Could not decrypt data. Did you enter a wrong password? Retry with the button at the top.');
  4108. // reset password, so it can be re-entered
  4109. Prompt.reset();
  4110. TopNav.showRetryButton();
  4111. }
  4112. /**
  4113. * show decrypted text in the display area, including discussion (if open)
  4114. *
  4115. * @name PasteDecrypter.run
  4116. * @function
  4117. * @param {Paste} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  4118. */
  4119. me.run = function(paste)
  4120. {
  4121. Alert.hideMessages();
  4122. Alert.showLoading('Decrypting paste…', 'cloud-download');
  4123. if (typeof paste === 'undefined') {
  4124. // get cipher data and wait until it is available
  4125. Model.getPasteData(me.run);
  4126. return;
  4127. }
  4128. let key = Model.getPasteKey(),
  4129. password = Prompt.getPassword(),
  4130. decryptionPromises = [];
  4131. TopNav.setRetryCallback(function () {
  4132. TopNav.hideRetryButton();
  4133. me.run(paste);
  4134. });
  4135. // decrypt paste & attachments
  4136. decryptionPromises.push(decryptPaste(paste, key, password));
  4137. // if the discussion is opened on this paste, display it
  4138. if (paste.isDiscussionEnabled()) {
  4139. decryptionPromises.push(decryptComments(paste, key, password));
  4140. }
  4141. // shows the remaining time (until) deletion
  4142. PasteStatus.showRemainingTime(paste);
  4143. Promise.all(decryptionPromises)
  4144. .then(() => {
  4145. Alert.hideLoading();
  4146. TopNav.showViewButtons();
  4147. })
  4148. .catch((err) => {
  4149. // wait for the user to type in the password,
  4150. // then PasteDecrypter.run will be called again
  4151. console.error(err);
  4152. });
  4153. };
  4154. return me;
  4155. })();
  4156. /**
  4157. * initial (security) check
  4158. *
  4159. * @name InitialCheck
  4160. * @param {object} window
  4161. * @param {object} document
  4162. * @class
  4163. */
  4164. var InitialCheck = (function () {
  4165. var me = {};
  4166. /**
  4167. * blacklist of UserAgents (parts) known to belong to a bot
  4168. *
  4169. * @private
  4170. * @enum {Array}
  4171. * @readonly
  4172. */
  4173. const badBotUA = [
  4174. 'Bot',
  4175. 'bot'
  4176. ];
  4177. /**
  4178. * check if the connection is insecure
  4179. *
  4180. * @private
  4181. * @name InitialCheck.isInsecureConnection
  4182. * @function
  4183. * @return {bool}
  4184. */
  4185. function isInsecureConnection()
  4186. {
  4187. // use .isSecureContext if available
  4188. if (window.isSecureContext === true || window.isSecureContext === false) {
  4189. return !window.isSecureContext;
  4190. }
  4191. const url = new URL(window.location);
  4192. // HTTP is obviously insecure
  4193. if (url.protocol !== 'http:') {
  4194. return false;
  4195. }
  4196. // filter out actually secure connections over HTTP
  4197. for (const tld of ['.onion', '.i2p']) {
  4198. if (url.hostname.endsWith(tld)) {
  4199. return false;
  4200. }
  4201. }
  4202. // whitelist localhost for development
  4203. for (const hostname of ['localhost', '127.0.0.1', '[::1]']) {
  4204. if (url.hostname === hostname) {
  4205. return false;
  4206. }
  4207. }
  4208. // totally INSECURE http protocol!
  4209. return true;
  4210. }
  4211. /**
  4212. * checks whether this is a bot we dislike
  4213. *
  4214. * @private
  4215. * @name InitialCheck.isBadBot
  4216. * @function
  4217. * @return {bool}
  4218. */
  4219. function isBadBot() {
  4220. // check whether a bot user agent part can be found in the current
  4221. // user agent
  4222. for (const UAfragment of badBotUA) {
  4223. if (navigator.userAgent.indexOf(UAfragment) >= 0) {
  4224. return true;
  4225. }
  4226. }
  4227. return false;
  4228. }
  4229. /**
  4230. * checks whether this is an unsupported browser, via feature detection
  4231. *
  4232. * @private
  4233. * @name InitialCheck.isOldBrowser
  4234. * @function
  4235. * @return {bool}
  4236. */
  4237. function isOldBrowser() {
  4238. // webcrypto support
  4239. if (typeof window.crypto !== 'object') {
  4240. return true;
  4241. }
  4242. if (typeof WebAssembly !== 'object' && typeof WebAssembly.instantiate !== 'function') {
  4243. return true;
  4244. }
  4245. try {
  4246. // [\0, 'a', 's', 'm', (uint_32) 1] - smallest valid wasm module
  4247. const module = new WebAssembly.Module(Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00));
  4248. if (
  4249. !(
  4250. module instanceof WebAssembly.Module &&
  4251. new WebAssembly.Instance(module) instanceof WebAssembly.Instance
  4252. )
  4253. ) {
  4254. return true;
  4255. }
  4256. } catch (e) {
  4257. return true;
  4258. }
  4259. // not checking for async/await, ES6, Promise or Uint8Array support,
  4260. // as most browsers introduced these earlier then webassembly and webcrypto:
  4261. // https://github.com/PrivateBin/PrivateBin/pull/431#issuecomment-493129359
  4262. return false;
  4263. }
  4264. /**
  4265. * init on application start, returns an all-clear signal
  4266. *
  4267. * @name InitialCheck.init
  4268. * @function
  4269. * @return {bool}
  4270. */
  4271. me.init = function()
  4272. {
  4273. // prevent bots from viewing a paste and potentially deleting data
  4274. // when burn-after-reading is set
  4275. if (isBadBot()) {
  4276. Alert.showError('I love you too, bot…');
  4277. return false;
  4278. }
  4279. if (isOldBrowser()) {
  4280. // some browsers (Chrome based ones) would have webcrypto support if using HTTPS
  4281. if (isInsecureConnection()) {
  4282. Alert.showError(['Your browser may require an HTTPS connection to support the WebCrypto API. Try <a href="%s">switching to HTTPS</a>.', 'https' + window.location.href.slice(4)]);
  4283. }
  4284. $('#oldnotice').removeClass('hidden');
  4285. return false;
  4286. }
  4287. if (isInsecureConnection()) {
  4288. $('#httpnotice').removeClass('hidden');
  4289. }
  4290. return true;
  4291. }
  4292. return me;
  4293. })();
  4294. /**
  4295. * (controller) main PrivateBin logic
  4296. *
  4297. * @name Controller
  4298. * @param {object} window
  4299. * @param {object} document
  4300. * @class
  4301. */
  4302. const Controller = (function (window, document) {
  4303. const me = {};
  4304. /**
  4305. * hides all status messages no matter which module showed them
  4306. *
  4307. * @name Controller.hideStatusMessages
  4308. * @function
  4309. */
  4310. me.hideStatusMessages = function()
  4311. {
  4312. PasteStatus.hideMessages();
  4313. Alert.hideMessages();
  4314. };
  4315. /**
  4316. * creates a new paste
  4317. *
  4318. * @name Controller.newPaste
  4319. * @function
  4320. */
  4321. me.newPaste = function()
  4322. {
  4323. // Important: This *must not* run Alert.hideMessages() as previous
  4324. // errors from viewing a paste should be shown.
  4325. TopNav.hideAllButtons();
  4326. Alert.showLoading('Preparing new paste…', 'time');
  4327. PasteStatus.hideMessages();
  4328. PasteViewer.hide();
  4329. Editor.resetInput();
  4330. Editor.show();
  4331. Editor.focusInput();
  4332. AttachmentViewer.removeAttachment();
  4333. TopNav.showCreateButtons();
  4334. Alert.hideLoading();
  4335. };
  4336. /**
  4337. * shows the loaded paste
  4338. *
  4339. * @name Controller.showPaste
  4340. * @function
  4341. */
  4342. me.showPaste = function()
  4343. {
  4344. try {
  4345. Model.getPasteKey();
  4346. } catch (err) {
  4347. console.error(err);
  4348. // missing decryption key (or paste ID) in URL?
  4349. if (window.location.hash.length === 0) {
  4350. Alert.showError('Cannot decrypt paste: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL?)');
  4351. return;
  4352. }
  4353. }
  4354. // show proper elements on screen
  4355. PasteDecrypter.run();
  4356. };
  4357. /**
  4358. * refreshes the loaded paste to show potential new data
  4359. *
  4360. * @name Controller.refreshPaste
  4361. * @function
  4362. * @param {function} callback
  4363. */
  4364. me.refreshPaste = function(callback)
  4365. {
  4366. // save window position to restore it later
  4367. const orgPosition = $(window).scrollTop();
  4368. Model.getPasteData(function (data) {
  4369. PasteDecrypter.run(new Paste(data));
  4370. // restore position
  4371. window.scrollTo(0, orgPosition);
  4372. // NOTE: could create problems as callback may be called
  4373. // asyncronously if PasteDecrypter e.g. needs to wait for a
  4374. // password being entered
  4375. callback();
  4376. }, false); // this false is important as it circumvents the cache
  4377. }
  4378. /**
  4379. * clone the current paste
  4380. *
  4381. * @name Controller.clonePaste
  4382. * @function
  4383. */
  4384. me.clonePaste = function()
  4385. {
  4386. TopNav.collapseBar();
  4387. TopNav.hideAllButtons();
  4388. // hide messages from previous paste
  4389. me.hideStatusMessages();
  4390. // erase the id and the key in url
  4391. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  4392. if (AttachmentViewer.hasAttachment()) {
  4393. AttachmentViewer.moveAttachmentTo(
  4394. TopNav.getCustomAttachment(),
  4395. 'Cloned: \'%s\''
  4396. );
  4397. TopNav.hideFileSelector();
  4398. AttachmentViewer.hideAttachment();
  4399. // NOTE: it also looks nice without removing the attachment
  4400. // but for a consistent display we remove it…
  4401. AttachmentViewer.hideAttachmentPreview();
  4402. TopNav.showCustomAttachment();
  4403. // show another status message to make the user aware that the
  4404. // file was cloned too!
  4405. Alert.showStatus(
  4406. [
  4407. 'The cloned file \'%s\' was attached to this paste.',
  4408. AttachmentViewer.getAttachment()[1]
  4409. ],
  4410. 'copy'
  4411. );
  4412. }
  4413. Editor.setText(PasteViewer.getText());
  4414. PasteViewer.hide();
  4415. Editor.show();
  4416. TopNav.showCreateButtons();
  4417. };
  4418. /**
  4419. * application start
  4420. *
  4421. * @name Controller.init
  4422. * @function
  4423. */
  4424. me.init = async function()
  4425. {
  4426. // first load translations
  4427. I18n.loadTranslations();
  4428. DOMPurify.setConfig({SAFE_FOR_JQUERY: true});
  4429. // initialize other modules/"classes"
  4430. Alert.init();
  4431. Model.init();
  4432. AttachmentViewer.init();
  4433. DiscussionViewer.init();
  4434. Editor.init();
  4435. PasteStatus.init();
  4436. PasteViewer.init();
  4437. Prompt.init();
  4438. TopNav.init();
  4439. UiHelper.init();
  4440. z = (await zlib);
  4441. if (!InitialCheck.init()) {
  4442. // something major is wrong, stop right away
  4443. return;
  4444. }
  4445. // check whether existing paste needs to be shown
  4446. try {
  4447. Model.getPasteId();
  4448. } catch (e) {
  4449. // otherwise create a new paste
  4450. return me.newPaste();
  4451. }
  4452. // if delete token is passed (i.e. paste has been deleted by this
  4453. // access), there is nothing more to do
  4454. if (Model.hasDeleteToken()) {
  4455. return;
  4456. }
  4457. // display an existing paste
  4458. return me.showPaste();
  4459. }
  4460. return me;
  4461. })(window, document);
  4462. return {
  4463. Helper: Helper,
  4464. I18n: I18n,
  4465. CryptTool: CryptTool,
  4466. Model: Model,
  4467. UiHelper: UiHelper,
  4468. Alert: Alert,
  4469. PasteStatus: PasteStatus,
  4470. Prompt: Prompt,
  4471. Editor: Editor,
  4472. PasteViewer: PasteViewer,
  4473. AttachmentViewer: AttachmentViewer,
  4474. DiscussionViewer: DiscussionViewer,
  4475. TopNav: TopNav,
  4476. ServerInteraction: ServerInteraction,
  4477. PasteEncrypter: PasteEncrypter,
  4478. PasteDecrypter: PasteDecrypter,
  4479. InitialCheck: InitialCheck,
  4480. Controller: Controller
  4481. };
  4482. })(jQuery, RawDeflate);