-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprivatebin.js
5495 lines (4962 loc) · 172 KB
/
privatebin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* PrivateBin
*
* a zero-knowledge paste bin
*
* @see {@link https://github.com/PrivateBin/PrivateBin}
* @copyright 2012 Sébastien SAUVAGE ({@link http://sebsauvage.net})
* @license {@link https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License}
* @version 1.3.5
* @name PrivateBin
* @namespace
*/
// global Base64, DOMPurify, FileReader, RawDeflate, history, navigator, prettyPrint, prettyPrintOne, showdown, kjua
jQuery.fn.draghover = function() {
'use strict';
return this.each(function() {
let collection = $(),
self = $(this);
self.on('dragenter', function(e) {
if (collection.length === 0) {
self.trigger('draghoverstart');
}
collection = collection.add(e.target);
});
self.on('dragleave drop', function(e) {
collection = collection.not(e.target);
if (collection.length === 0) {
self.trigger('draghoverend');
}
});
});
};
// main application start, called when DOM is fully loaded
jQuery(document).ready(function() {
'use strict';
// run main controller
$.PrivateBin.Controller.init();
});
jQuery.PrivateBin = (function($, RawDeflate) {
'use strict';
/**
* zlib library interface
*
* @private
*/
let z;
/**
* CryptoData class
*
* bundles helper fuctions used in both paste and comment formats
*
* @name CryptoData
* @class
*/
function CryptoData(data) {
this.v = 1;
// store all keys in the default locations for drop-in replacement
for (let key in data) {
this[key] = data[key];
}
/**
* gets the cipher data (cipher text + adata)
*
* @name Paste.getCipherData
* @function
* @return {Array}|{string}
*/
this.getCipherData = function()
{
return this.v === 1 ? this.data : [this.ct, this.adata];
}
}
/**
* Paste class
*
* bundles helper fuctions around the paste formats
*
* @name Paste
* @class
*/
function Paste(data) {
// inherit constructor and methods of CryptoData
CryptoData.call(this, data);
/**
* gets the used formatter
*
* @name Paste.getFormat
* @function
* @return {string}
*/
this.getFormat = function()
{
return this.v === 1 ? this.meta.formatter : this.adata[1];
}
/**
* gets the remaining seconds before the paste expires
*
* returns 0 if there is no expiration
*
* @name Paste.getTimeToLive
* @function
* @return {string}
*/
this.getTimeToLive = function()
{
return (this.v === 1 ? this.meta.remaining_time : this.meta.time_to_live) || 0;
}
/**
* is burn-after-reading enabled
*
* @name Paste.isBurnAfterReadingEnabled
* @function
* @return {bool}
*/
this.isBurnAfterReadingEnabled = function()
{
return (this.v === 1 ? this.meta.burnafterreading : this.adata[3]);
}
/**
* are discussions enabled
*
* @name Paste.isDiscussionEnabled
* @function
* @return {bool}
*/
this.isDiscussionEnabled = function()
{
return (this.v === 1 ? this.meta.opendiscussion : this.adata[2]);
}
}
/**
* Comment class
*
* bundles helper fuctions around the comment formats
*
* @name Comment
* @class
*/
function Comment(data) {
// inherit constructor and methods of CryptoData
CryptoData.call(this, data);
/**
* gets the UNIX timestamp of the comment creation
*
* @name Paste.getCreated
* @function
* @return {int}
*/
this.getCreated = function()
{
return this.meta[this.v === 1 ? 'postdate' : 'created'];
}
/**
* gets the icon of the comment submitter
*
* @name Paste.getIcon
* @function
* @return {string}
*/
this.getIcon = function()
{
return this.meta[this.v === 1 ? 'vizhash' : 'icon'] || '';
}
}
/**
* static Helper methods
*
* @name Helper
* @class
*/
const Helper = (function () {
const me = {};
/**
* character to HTML entity lookup table
*
* @see {@link https://github.com/janl/mustache.js/blob/master/mustache.js#L60}
* @name Helper.entityMap
* @private
* @enum {Object}
* @readonly
*/
const entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
/**
* number of seconds in a minute
*
* @name Helper.minute
* @private
* @enum {number}
* @readonly
*/
const minute = 60;
/**
* number of seconds in an hour
*
* = 60 * 60 seconds
*
* @name Helper.minute
* @private
* @enum {number}
* @readonly
*/
const hour = 3600;
/**
* number of seconds in a day
*
* = 60 * 60 * 24 seconds
*
* @name Helper.day
* @private
* @enum {number}
* @readonly
*/
const day = 86400;
/**
* number of seconds in a week
*
* = 60 * 60 * 24 * 7 seconds
*
* @name Helper.week
* @private
* @enum {number}
* @readonly
*/
const week = 604800;
/**
* number of seconds in a month (30 days, an approximation)
*
* = 60 * 60 * 24 * 30 seconds
*
* @name Helper.month
* @private
* @enum {number}
* @readonly
*/
const month = 2592000;
/**
* number of seconds in a non-leap year
*
* = 60 * 60 * 24 * 365 seconds
*
* @name Helper.year
* @private
* @enum {number}
* @readonly
*/
const year = 31536000;
/**
* cache for script location
*
* @name Helper.baseUri
* @private
* @enum {string|null}
*/
let baseUri = null;
/**
* converts a duration (in seconds) into human friendly approximation
*
* @name Helper.secondsToHuman
* @function
* @param {number} seconds
* @return {Array}
*/
me.secondsToHuman = function(seconds)
{
let v;
if (seconds < minute)
{
v = Math.floor(seconds);
return [v, 'second'];
}
if (seconds < hour)
{
v = Math.floor(seconds / minute);
return [v, 'minute'];
}
if (seconds < day)
{
v = Math.floor(seconds / hour);
return [v, 'hour'];
}
// If less than 2 months, display in days:
if (seconds < (2 * month))
{
v = Math.floor(seconds / day);
return [v, 'day'];
}
v = Math.floor(seconds / month);
return [v, 'month'];
};
/**
* converts a duration string into seconds
*
* The string is expected to be optional digits, followed by a time.
* Supported times are: min, hour, day, month, year, never
* Examples: 5min, 13hour, never
*
* @name Helper.durationToSeconds
* @function
* @param {String} duration
* @return {number}
*/
me.durationToSeconds = function(duration)
{
let pieces = duration.split(/(\D+)/),
factor = pieces[0] || 0,
timespan = pieces[1] || pieces[0];
switch (timespan)
{
case 'min':
return factor * minute;
case 'hour':
return factor * hour;
case 'day':
return factor * day;
case 'week':
return factor * week;
case 'month':
return factor * month;
case 'year':
return factor * year;
case 'never':
return 0;
default:
return factor;
}
};
/**
* text range selection
*
* @see {@link https://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse}
* @name Helper.selectText
* @function
* @param {HTMLElement} element
*/
me.selectText = function(element)
{
let range, selection;
// MS
if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
/**
* convert URLs to clickable links in the provided element.
*
* URLs to handle:
* <pre>
* magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
* https://example.com:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
* http://user:example.com@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
* </pre>
*
* @name Helper.urls2links
* @function
* @param {HTMLElement} element
*/
me.urls2links = function(element)
{
element.html(
DOMPurify.sanitize(
element.html().replace(
/(((https?|ftp):\/\/[\w?!=&.\/-;#@~%+*-]+(?![\w\s?!&.\/;#~%"=-]>))|((magnet):[\w?=&.\/-;#@~%+*-]+))/ig,
'<a href="$1" rel="nofollow noopener noreferrer">$1</a>'
)
)
);
};
/**
* minimal sprintf emulation for %s and %d formats
*
* Note that this function needs the parameters in the same order as the
* format strings appear in the string, contrary to the original.
*
* @see {@link https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914}
* @name Helper.sprintf
* @function
* @param {string} format
* @param {...*} args - one or multiple parameters injected into format string
* @return {string}
*/
me.sprintf = function()
{
const args = Array.prototype.slice.call(arguments);
let format = args[0],
i = 1;
return format.replace(/%(s|d)/g, function (m) {
let val = args[i];
if (m === '%d') {
val = parseFloat(val);
if (isNaN(val)) {
val = 0;
}
}
++i;
return val;
});
};
/**
* get value of cookie, if it was set, empty string otherwise
*
* @see {@link http://www.w3schools.com/js/js_cookies.asp}
* @name Helper.getCookie
* @function
* @param {string} cname - may not be empty
* @return {string}
*/
me.getCookie = function(cname) {
const name = cname + '=',
ca = document.cookie.split(';');
for (let i = 0; i < ca.length; ++i) {
let c = ca[i];
while (c.charAt(0) === ' ')
{
c = c.substring(1);
}
if (c.indexOf(name) === 0)
{
return c.substring(name.length, c.length);
}
}
return '';
};
/**
* get the current location (without search or hash part of the URL),
* eg. https://example.com/path/?aaaa#bbbb --> https://example.com/path/
*
* @name Helper.baseUri
* @function
* @return {string}
*/
me.baseUri = function()
{
// check for cached version
if (baseUri !== null) {
return baseUri;
}
baseUri = window.location.origin + window.location.pathname;
return baseUri;
};
/**
* wrap an object into a Paste, used for mocking in the unit tests
*
* @name Helper.PasteFactory
* @function
* @param {object} data
* @return {Paste}
*/
me.PasteFactory = function(data)
{
return new Paste(data);
};
/**
* wrap an object into a Comment, used for mocking in the unit tests
*
* @name Helper.CommentFactory
* @function
* @param {object} data
* @return {Comment}
*/
me.CommentFactory = function(data)
{
return new Comment(data);
};
/**
* convert all applicable characters to HTML entities
*
* @see {@link https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html}
* @name Helper.htmlEntities
* @function
* @param {string} str
* @return {string} escaped HTML
*/
me.htmlEntities = function(str) {
return String(str).replace(
/[&<>"'`=\/]/g, function(s) {
return entityMap[s];
}
);
}
/**
* calculate expiration date given initial date and expiration period
*
* @name Helper.calculateExpirationDate
* @function
* @param {Date} initialDate - may not be empty
* @param {string|number} expirationDisplayStringOrSecondsToExpire - may not be empty
* @return {Date}
*/
me.calculateExpirationDate = function(initialDate, expirationDisplayStringOrSecondsToExpire) {
let expirationDate = new Date(initialDate),
secondsToExpiration = expirationDisplayStringOrSecondsToExpire;
if (typeof expirationDisplayStringOrSecondsToExpire === 'string') {
secondsToExpiration = me.durationToSeconds(expirationDisplayStringOrSecondsToExpire);
}
if (typeof secondsToExpiration !== 'number') {
throw new Error('Cannot calculate expiration date.');
}
if (secondsToExpiration === 0) {
return null;
}
expirationDate = expirationDate.setUTCSeconds(expirationDate.getUTCSeconds() + secondsToExpiration);
return expirationDate;
};
/**
* resets state, used for unit testing
*
* @name Helper.reset
* @function
*/
me.reset = function()
{
baseUri = null;
};
return me;
})();
/**
* internationalization module
*
* @name I18n
* @class
*/
const I18n = (function () {
const me = {};
/**
* const for string of loaded language
*
* @name I18n.languageLoadedEvent
* @private
* @prop {string}
* @readonly
*/
const languageLoadedEvent = 'languageLoaded';
/**
* supported languages, minus the built in 'en'
*
* @name I18n.supportedLanguages
* @private
* @prop {string[]}
* @readonly
*/
const supportedLanguages = ['bg', 'ca', 'co', 'cs', 'de', 'es', 'et', 'fr', 'he', 'hu', 'id', 'it', 'jbo', 'lt', 'no', 'nl', 'pl', 'pt', 'oc', 'ru', 'sl', 'uk', 'zh'];
/**
* built in language
*
* @name I18n.language
* @private
* @prop {string|null}
*/
let language = null;
/**
* translation cache
*
* @name I18n.translations
* @private
* @enum {Object}
*/
let translations = {};
/**
* translate a string, alias for I18n.translate
*
* @name I18n._
* @function
* @param {jQuery} $element - optional
* @param {string} messageId
* @param {...*} args - one or multiple parameters injected into placeholders
* @return {string}
*/
me._ = function()
{
return me.translate.apply(this, arguments);
};
/**
* translate a string
*
* Optionally pass a jQuery element as the first parameter, to automatically
* let the text of this element be replaced. In case the (asynchronously
* loaded) language is not downloaded yet, this will make sure the string
* is replaced when it eventually gets loaded. Using this is both simpler
* and more secure, as it avoids potential XSS when inserting text.
* The next parameter is the message ID, matching the ones found in
* the translation files under the i18n directory.
* Any additional parameters will get inserted into the message ID in
* place of %s (strings) or %d (digits), applying the appropriate plural
* in case of digits. See also Helper.sprintf().
*
* @name I18n.translate
* @function
* @param {jQuery} $element - optional
* @param {string} messageId
* @param {...*} args - one or multiple parameters injected into placeholders
* @return {string}
*/
me.translate = function()
{
// convert parameters to array
let args = Array.prototype.slice.call(arguments),
messageId,
$element = null;
// parse arguments
if (args[0] instanceof jQuery) {
// optional jQuery element as first parameter
$element = args[0];
args.shift();
}
// extract messageId from arguments
let usesPlurals = $.isArray(args[0]);
if (usesPlurals) {
// use the first plural form as messageId, otherwise the singular
messageId = args[0].length > 1 ? args[0][1] : args[0][0];
} else {
messageId = args[0];
}
if (messageId.length === 0) {
return messageId;
}
// if no translation string cannot be found (in translations object)
if (!translations.hasOwnProperty(messageId) || language === null) {
// if language is still loading and we have an elemt assigned
if (language === null && $element !== null) {
// handle the error by attaching the language loaded event
let orgArguments = arguments;
$(document).on(languageLoadedEvent, function () {
// re-execute this function
me.translate.apply(this, orgArguments);
});
// and fall back to English for now until the real language
// file is loaded
}
// for all other languages than English for which this behaviour
// is expected as it is built-in, log error
if (language !== null && language !== 'en') {
console.error('Missing translation for: \'' + messageId + '\' in language ' + language);
// fallback to English
}
// save English translation (should be the same on both sides)
translations[messageId] = args[0];
}
// lookup plural translation
if (usesPlurals && $.isArray(translations[messageId])) {
let n = parseInt(args[1] || 1, 10),
key = me.getPluralForm(n),
maxKey = translations[messageId].length - 1;
if (key > maxKey) {
key = maxKey;
}
args[0] = translations[messageId][key];
args[1] = n;
} else {
// lookup singular translation
args[0] = translations[messageId];
}
// messageID may contain links, but should be from a trusted source (code or translation JSON files)
let containsLinks = args[0].indexOf('<a') !== -1;
// prevent double encoding, when we insert into a text node
if (containsLinks || $element === null) {
for (let i = 0; i < args.length; ++i) {
// parameters (i > 0) may never contain HTML as they may come from untrusted parties
if ((containsLinks ? i > 1 : i > 0) || !containsLinks) {
args[i] = Helper.htmlEntities(args[i]);
}
}
}
// format string
let output = Helper.sprintf.apply(this, args);
if (containsLinks) {
// only allow tags/attributes we actually use in translations
output = DOMPurify.sanitize(
output, {
ALLOWED_TAGS: ['a', 'i', 'span'],
ALLOWED_ATTR: ['href', 'id']
}
);
}
// if $element is given, insert translation
if ($element !== null) {
if (containsLinks) {
$element.html(output);
} else {
// text node takes care of entity encoding
$element.text(output);
}
return '';
}
return output;
};
/**
* per language functions to use to determine the plural form
*
* @see {@link https://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html}
* @name I18n.getPluralForm
* @function
* @param {int} n
* @return {int} array key
*/
me.getPluralForm = function(n) {
switch (language)
{
case 'cs':
return n === 1 ? 0 : (n >= 2 && n <=4 ? 1 : 2);
case 'co':
case 'fr':
case 'oc':
case 'zh':
return n > 1 ? 1 : 0;
case 'he':
return n === 1 ? 0 : (n === 2 ? 1 : ((n < 0 || n > 10) && (n % 10 === 0) ? 2 : 3));
case 'id':
case 'jbo':
return 0;
case 'lt':
return n % 10 === 1 && n % 100 !== 11 ? 0 : ((n % 10 >= 2 && n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
case 'pl':
return n === 1 ? 0 : (n % 10 >= 2 && n %10 <=4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
case 'ru':
case 'uk':
return n % 10 === 1 && n % 100 !== 11 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
case 'sl':
return n % 100 === 1 ? 1 : (n % 100 === 2 ? 2 : (n % 100 === 3 || n % 100 === 4 ? 3 : 0));
// bg, ca, de, en, es, et, hu, it, nl, no, pt
default:
return n !== 1 ? 1 : 0;
}
};
/**
* load translations into cache
*
* @name I18n.loadTranslations
* @function
*/
me.loadTranslations = function()
{
let newLanguage = Helper.getCookie('lang');
// auto-select language based on browser settings
if (newLanguage.length === 0) {
newLanguage = (navigator.language || navigator.userLanguage || 'en').substring(0, 2);
}
// if language is already used skip update
if (newLanguage === language) {
return;
}
// if language is built-in (English) skip update
if (newLanguage === 'en') {
language = 'en';
return;
}
// if language is not supported, show error
if (supportedLanguages.indexOf(newLanguage) === -1) {
console.error('Language \'%s\' is not supported. Translation failed, fallback to English.', newLanguage);
language = 'en';
return;
}
// load strings from JSON
$.getJSON('i18n/' + newLanguage + '.json', function(data) {
language = newLanguage;
translations = data;
$(document).triggerHandler(languageLoadedEvent);
}).fail(function (data, textStatus, errorMsg) {
console.error('Language \'%s\' could not be loaded (%s: %s). Translation failed, fallback to English.', newLanguage, textStatus, errorMsg);
language = 'en';
});
};
/**
* resets state, used for unit testing
*
* @name I18n.reset
* @function
*/
me.reset = function(mockLanguage, mockTranslations)
{
language = mockLanguage || null;
translations = mockTranslations || {};
};
return me;
})();
/**
* handles everything related to en/decryption
*
* @name CryptTool
* @class
*/
const CryptTool = (function () {
const me = {};
/**
* base58 encoder & decoder
*
* @private
*/
let base58 = new baseX('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
/**
* convert UTF-8 string stored in a DOMString to a standard UTF-16 DOMString
*
* Iterates over the bytes of the message, converting them all hexadecimal
* percent encoded representations, then URI decodes them all
*
* @name CryptTool.utf8To16
* @function
* @private
* @param {string} message UTF-8 string
* @return {string} UTF-16 string
*/
function utf8To16(message)
{
return decodeURIComponent(
message.split('').map(
function(character)
{
return '%' + ('00' + character.charCodeAt(0).toString(16)).slice(-2);
}
).join('')
);
}
/**
* convert DOMString (UTF-16) to a UTF-8 string stored in a DOMString
*
* URI encodes the message, then finds the percent encoded characters
* and transforms these hexadecimal representation back into bytes
*
* @name CryptTool.utf16To8
* @function
* @private
* @param {string} message UTF-16 string
* @return {string} UTF-8 string
*/
function utf16To8(message)
{
return encodeURIComponent(message).replace(
/%([0-9A-F]{2})/g,
function (match, hexCharacter)
{
return String.fromCharCode('0x' + hexCharacter);
}
);
}
/**
* convert ArrayBuffer into a UTF-8 string
*
* Iterates over the bytes of the array, catenating them into a string
*
* @name CryptTool.arraybufferToString
* @function
* @private
* @param {ArrayBuffer} messageArray
* @return {string} message
*/
function arraybufferToString(messageArray)
{
const array = new Uint8Array(messageArray);
let message = '',
i = 0;
while(i < array.length) {
message += String.fromCharCode(array[i++]);
}
return message;
}
/**
* convert UTF-8 string into a Uint8Array
*
* Iterates over the bytes of the message, writing them to the array
*
* @name CryptTool.stringToArraybuffer
* @function
* @private
* @param {string} message UTF-8 string
* @return {Uint8Array} array
*/
function stringToArraybuffer(message)
{
const messageArray = new Uint8Array(message.length);
for (let i = 0; i < message.length; ++i) {
messageArray[i] = message.charCodeAt(i);
}
return messageArray;
}
/**
* compress a string (deflate compression), returns buffer
*
* @name CryptTool.compress
* @async
* @function
* @private
* @param {string} message
* @param {string} mode
* @param {object} zlib
* @throws {string}
* @return {ArrayBuffer} data
*/
async function compress(message, mode, zlib)
{
message = stringToArraybuffer(
utf16To8(message)
);
if (mode === 'zlib') {
if (typeof zlib === 'undefined') {
throw 'Error compressing paste, due to missing WebAssembly support.'
}
return zlib.deflate(message).buffer;
}
return message;
}
/**
* decompress potentially base64 encoded, deflate compressed buffer, returns string
*
* @name CryptTool.decompress