-
Notifications
You must be signed in to change notification settings - Fork 311
/
export.js
executable file
·3287 lines (2611 loc) · 119 KB
/
export.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
/**
* Functionality for the Export Link password protection feature
*
* The first implementation will use PBKDF2-HMAC-SHA512 with 100,000 rounds and a 256 bit random salt to derive a 512
* bit key. For folder links the key is 128 bits in length and for file links the actual key is 256 bits in length. The
* first 128 or 256 bits of the derived key will be used to encrypt the actual folder/file key using a simple XOR for
* encryption. The last 256 bits of the derived key will be used as the MAC Key. Using the Encrypt then MAC principle,
* the MAC will be calculated using HMAC-SHA256.
*
* In constructing the protected link, the format is as follows:
* algorithm || file/folder || public handle || salt || encrypted key || MAC tag
*
* algorithm = 1 byte - A byte to identify which algorithm was used (for future upgradability), initially is set to 0
* file/folder = 1 byte - A byte to identify if the link is a file or folder link (0 = folder, 1 = file)
* public handle = 6 bytes - The public folder/file handle
* salt = 32 bytes - A 256 bit randomly generated salt
* encrypted key = 16 or 32 bytes - The encrypted actual folder or file key
* MAC tag = 32 bytes - The MAC of all the previous data to ensure integrity of the link i.e. calculated as:
* HMAC-SHA256(MAC key, (algorithm || file/folder || public handle || salt || encrypted key))
*
* The link data is then Base64 encoded and then URL encoded to remove incompatible characters e.g.:
* https://mega.nz/#P!AAA5TWTcNMs7aYZgtalahVxCffAF0JeZTKxOZQ_s2d...
*
* In receiving a protected link, the program will decode the URL, get the first byte to check which algorithm was used
* to encrypt the data (useful if algorithm changes are made in future). Then it will use the password to derive the
* same key using the same algorithm, provided salt and password. Then a MAC of the data can be calculated, if it's a
* match then the link has not been tampered with or corrupted and the real folder/file key can be decrypted and the
* original link reconstructed. If it doesn't match then an error will be shown which could mean tampering or that the
* user entered an incorrect password.
*/
var exportPassword = {
// List of algorithms
algorithms: [
{
// Algorithm (0) for unit testing with low rounds
name: 'PBKDF2', // Name for the Web Crypto primary PBKDF algorithm
hash: 'SHA-512', // Hash algorithm for the Web Crypto primary PBKDF algorithm
failsafeName: 'PBKDF2_HMAC_SHA512', // Name for the asmCrypto failsafe PBKDF algorithm
macName: 'HMAC_SHA256', // Name for the asmCrypto MAC algorithm
saltLength: 256, // Salt length in bits
macKeyLength: 256, // MAC key length in bits
macLength: 256, // MAC computed digest length in bits
derivedKeyLength: 512, // Desired derived key length in bits
iterations: 1000 // Number of iterations to run
},
{
// Old algorithm (1) which used incorrect parameter order: HMAC(password, data)
name: 'PBKDF2',
hash: 'SHA-512',
failsafeName: 'PBKDF2_HMAC_SHA512',
macName: 'HMAC_SHA256',
saltLength: 256,
macKeyLength: 256,
macLength: 256,
derivedKeyLength: 512,
iterations: 100000
},
{
// Current algorithm (2)
name: 'PBKDF2',
hash: 'SHA-512',
failsafeName: 'PBKDF2_HMAC_SHA512',
macName: 'HMAC_SHA256',
saltLength: 256,
macKeyLength: 256,
macLength: 256,
derivedKeyLength: 512,
iterations: 100000
}
// Future tweaks or changes in algorithms e.g. Argon2
],
// The current algorithm in use for production
currentAlgorithm: 2, // 1 byte (0x02)
/**
* Constants for folder or file type
*/
LINK_TYPE_FOLDER: 0, // 1 byte (0x00)
LINK_TYPE_FILE: 1, // 1 byte (0x01)
/**
* Functions for the encryption
*/
encrypt: {
// The jQuery selector for the Export dialog
$dialog: null,
/**
* Initialise function
*/
init: function() {
"use strict";
// Cache dialog selector
this.$dialog = $('.mega-dialog.export-links-dialog', 'body');
// Update protected/not protected components UI and update links/keys values
this.updatePasswordComponentsUI();
this.updateLinkInputValues();
// If they are a Pro user, enable set password feature
if (u_attr.p) {
this.initPasswordToggleButton();
this.loadPasswordEstimatorLibrary();
this.initPasswordStrengthCheck();
this.initPasswordVisibilityHandler();
this.initConfirmPasswordButton();
}
},
/**
* Update protected/not protected components UI
*/
updatePasswordComponentsUI: function() {
"use strict";
const $items = $('.item', this.$dialog);
const $protectedItems = $items.filter('.password-protect-link');
const $setPasswordBtn = $('.js-confirm-password', this.$dialog);
const $removePasswordBtn = $('.js-reset-password', this.$dialog);
// If password protected links
if ($protectedItems.length) {
// Hide the Confirm password button
$setPasswordBtn.addClass('hidden');
// Show Remove password button
$removePasswordBtn.removeClass('hidden');
}
else {
// Show Confirm password button
$setPasswordBtn.removeClass('hidden');
// Hide Remove password button
$removePasswordBtn.addClass('hidden');
}
},
/**
* Update links/keys values
*/
updateLinkInputValues: function() {
"use strict";
var isSeparateKeys = $('.js-export-keys-switch', this.$dialog).hasClass('toggle-on');
var $items = $('.item:not(.password-protect-link)', this.$dialog);
// Update not password protected Link input values
$items.get().forEach(function(e) {
var $this = $(e);
var $linkInput = $('.item-link.link input', $this);
var $keyInput = $('.item-link.key input', $this);
var linkWithoutKey = $linkInput.data('link');
var key = $linkInput.data('key');
// Set key without # or !
$keyInput.val($keyInput.data('key'));
// Set link
if (isSeparateKeys) {
$linkInput.val(linkWithoutKey);
}
else {
$linkInput.val(linkWithoutKey + key);
}
});
},
/**
* Setup the password toggle
*/
initPasswordToggleButton: function() {
"use strict";
const $exportKeysSwitch = $('.js-export-keys-switch', this.$dialog);
const $linkAccessText = $('.js-link-access-text', this.$dialog);
const $passwordContainer = $('.password-container', this.$dialog);
const $passwordInput = $('.js-password-input', this.$dialog);
const $passwordInputWrapper = $passwordInput.parent();
const $passwordToggleSwitch = $('.js-password-switch', this.$dialog);
const $passwordToggleIcon = $('.mega-feature-switch', $passwordToggleSwitch);
const $passwordVisibilityToggle = $('.js-toggle-password-visible', this.$dialog);
const $passwordStrengthText = $('.js-strength-indicator', this.$dialog);
const $updateSuccessBanner = $('.js-update-success-banner', this.$dialog);
// Init toggle to show/hide password section
$passwordToggleSwitch.rebind('click.changePasswordView', () => {
const passwordToggleIsOn = $passwordToggleSwitch.hasClass('toggle-on');
// If toggle is currently on, we will turn it off
if (passwordToggleIsOn) {
// If no password has been entered, no need to recreate links,
// so just reset the password UI elements to default off state
if ($passwordInput.val() === '') {
exportPassword.encrypt.turnOffPasswordUI();
return;
}
loadingDialog.show();
// Remove the existing links and re-add them
exportPassword.removeLinksAndReAdd($.itemExport)
.then(() => {
const $items = $('.item', this.$dialog);
const linkCount = $.itemExport.length;
// If a password has actually been set
if ($items.first().hasClass('password-protect-link')) {
// Show success banner telling them to re-copy the links
$updateSuccessBanner.text(mega.icu.format(l.links_updated_copy_again, linkCount));
$updateSuccessBanner.removeClass('hidden');
// Hide again after 3 seconds
setTimeout(() => {
$updateSuccessBanner.addClass('hidden');
}, 3000);
}
// Reset the password UI elements to default off state
return exportPassword.encrypt.turnOffPasswordUI();
})
.catch(tell)
.finally(() => {
loadingDialog.hide();
});
}
else {
// The toggle is currently off, so we will turn it on
// First, turn off the separate keys toggle if it's on
if ($exportKeysSwitch.hasClass('toggle-on')) {
$exportKeysSwitch.trigger('click');
}
// Disable the separate keys toggle
$exportKeysSwitch.addClass('disabled');
// Turn on toggle and show the password section
$passwordToggleSwitch.addClass('toggle-on').removeClass('toggle-off');
$passwordToggleIcon.addClass('icon-check-after').removeClass('icon-minimise-after');
$passwordContainer.removeClass('hidden');
// Focus the input so they can immediately enter the password
$passwordInput.focus();
}
});
},
/**
* Turns off the password related UI, used in initialisation of the dialog to reset the password elements,
* also in turning off the toggle switch. It was useful to be able to reset the UI elements to the off state
* without triggering the toggle switch to off (which has a side effect of recreating the password links).
* @returns {undefined}
*/
turnOffPasswordUI: function() {
'use strict';
const $exportKeysSwitch = $('.js-export-keys-switch', this.$dialog);
const $linkAccessText = $('.js-link-access-text', this.$dialog);
const $passwordContainer = $('.password-container', this.$dialog);
const $passwordInput = $('.js-password-input', this.$dialog);
const $passwordInputWrapper = $passwordInput.parent();
const $passwordToggleSwitch = $('.js-password-switch', this.$dialog);
const $passwordToggleIcon = $('.mega-feature-switch', $passwordToggleSwitch);
const $passwordVisibilityToggle = $('.js-toggle-password-visible', this.$dialog);
const $passwordStrengthText = $('.js-strength-indicator', this.$dialog);
const $items = $('.item', this.$dialog);
const linkCount = $.itemExport.length;
// Set links and keys into text boxes
$items.removeClass('password-protect-link');
// Update Password buttons and links UI
exportPassword.encrypt.updatePasswordComponentsUI();
// Update Link input values
exportPassword.encrypt.updateLinkInputValues();
// Turn off toggle and hide the password section
$passwordToggleSwitch.addClass('toggle-off').removeClass('toggle-on');
$passwordToggleIcon.addClass('icon-minimise-after').removeClass('icon-check-after');
$passwordContainer.addClass('hidden');
// Re-enable the separate link/key toggle
$exportKeysSwitch.removeClass('disabled');
// Reset password input to default state
$passwordInput.val('');
$passwordInput.prop('readonly', false);
$passwordStrengthText.text('');
$passwordInputWrapper.removeClass('good1 good2 good3 good4 good5');
// Prepare MegaInput field and hide previous errors
mega.ui.MegaInputs($passwordInput);
$passwordInput.data('MegaInputs').hideError();
// Revert to default state for the password visibility 'eye' icon
if ($passwordVisibilityToggle.hasClass('icon-eye-hidden')) {
$passwordVisibilityToggle.trigger('click');
}
// Change link access description back to 'Anyone with this link can view and download your data'
$linkAccessText.text(mega.icu.format(l.link_access_explainer, linkCount));
},
/**
* Setup Set remove password button
*/
initResetPasswordButton: function() {
"use strict";
const $removePasswordBtn = $('.js-reset-password', this.$dialog);
const $linkAccessText = $('.js-link-access-text', this.$dialog);
const $passwordVisibilityToggle = $('.js-toggle-password-visible', this.$dialog);
const $passwordInput = $('.js-password-input', this.$dialog);
const $passwordInputWrapper = $passwordInput.parent();
const $passwordStrengthText = $('.js-strength-indicator', this.$dialog);
// On Remove password click
$removePasswordBtn.rebind('click.removePass', () => {
loadingDialog.show();
// Remove the existing links and re-add them
exportPassword.removeLinksAndReAdd($.itemExport)
.then(() => {
const $items = $('.item', this.$dialog);
const linkCount = $.itemExport.length;
// Set links and keys into text boxes
$items.removeClass('password-protect-link');
// Update Password buttons and links UI
exportPassword.encrypt.updatePasswordComponentsUI();
// Update Link input values
exportPassword.encrypt.updateLinkInputValues();
// Change link access description back to 'Anyone with this link can view your data'
$linkAccessText.text(mega.icu.format(l.link_access_explainer, linkCount));
// Reset password input to default state
$passwordInput.val('');
$passwordInput.focus();
$passwordInput.prop('readonly', false);
$passwordStrengthText.text('');
$passwordInputWrapper.removeClass('good1 good2 good3 good4 good5');
// Revert to default state for the password visibility 'eye' icon
if ($passwordVisibilityToggle.hasClass('icon-eye-hidden')) {
$passwordVisibilityToggle.trigger('click');
}
})
.catch(tell)
.finally(() => {
loadingDialog.hide();
});
});
},
/**
* Initialise the Confirm password button to set the link/s password
*/
initConfirmPasswordButton: function() {
'use strict';
// Add click handler to the confirm button
$('.js-confirm-password', this.$dialog).rebind('click.setPass', () => {
loadingDialog.show();
// Remove the existing links and re-add them
exportPassword.removeLinksAndReAdd($.itemExport)
.then(() => {
// @todo revamp to get back the crypto promise
return exportPassword.encrypt.startEncryption();
})
.catch(tell)
.finally(() => {
loadingDialog.hide();
});
});
},
/**
* Add click handler on the eye icon inside the password field to toggle the password as text/dots
*/
initPasswordVisibilityHandler: function() {
'use strict';
const $passwordInput = $('.js-password-input', this.$dialog);
const $togglePasswordVisibileIcon = $('.js-toggle-password-visible', this.$dialog);
$togglePasswordVisibileIcon.rebind('click.showPass', () => {
// If the eye icon is showing, reveal the password using text field
if ($togglePasswordVisibileIcon.hasClass('icon-eye-reveal')) {
$togglePasswordVisibileIcon.removeClass('icon-eye-reveal').addClass('icon-eye-hidden');
$passwordInput[0].type = 'text';
}
else {
// Otherwise revert back to dots
$togglePasswordVisibileIcon.removeClass('icon-eye-hidden').addClass('icon-eye-reveal');
$passwordInput[0].type = 'password';
}
});
},
/**
* Load the ZXCVBN password strength estimator library
*/
loadPasswordEstimatorLibrary: function() {
"use strict";
if (typeof zxcvbn === 'undefined') {
// Show loading spinner
const $loader = $('.estimator-loading-icon', this.$dialog).addClass('loading');
// On completion of loading, hide the loading spinner
M.require('zxcvbn_js')
.done(function() {
$loader.removeClass('loading');
});
}
},
/**
* Show what strength the currently entered password is on key up
*/
initPasswordStrengthCheck: function() {
"use strict";
const $passwordStrengthField = $('.js-strength-indicator', this.$dialog);
const $passwordInput = $('.js-password-input', this.$dialog);
const $encryptButton = $('.js-confirm-password', this.$dialog);
const $inputWrapper = $passwordInput.parent();
// Add keyup event to the password text field
$passwordInput.rebind('keyup', function(event) {
// Don't attempt to do add any strength checker text if the field is disabled for typing
if ($passwordInput.prop('readonly')) {
return false;
}
// Make sure the ZXCVBN password strength estimator library is loaded first
if (typeof zxcvbn !== 'undefined') {
// Estimate the password strength
var password = $.trim($passwordInput.val());
var passwordScore = zxcvbn(password).score;
var passwordLength = password.length;
// Remove previous strength classes that were added
$inputWrapper.removeClass('good1 good2 good3 good4 good5');
// Add colour coding and text
if (password.length === 0) {
$passwordStrengthField.text(''); // No password entered, hide text
}
else if (passwordLength < 8) {
$inputWrapper.addClass('good1');
$passwordStrengthField.text(l[18700]); // Too short
}
else if (passwordScore === 4) {
$inputWrapper.addClass('good5');
$passwordStrengthField.text(l[1128]); // Strong
}
else if (passwordScore === 3) {
$inputWrapper.addClass('good4');
$passwordStrengthField.text(l[1127]); // Good
}
else if (passwordScore === 2) {
$inputWrapper.addClass('good3');
$passwordStrengthField.text(l[1126]); // Medium
}
else if (passwordScore === 1) {
$inputWrapper.addClass('good2');
$passwordStrengthField.text(l[1125]); // Weak
}
else {
$inputWrapper.addClass('good1');
$passwordStrengthField.text(l[1124]); // Very Weak
}
}
// If Enter key is pressed, trigger encryption button clicking
if (event.keyCode === 13) {
$encryptButton.trigger('click');
}
});
// Add keyup event to the password field
$passwordInput.rebind('keyup.setPass', (event) => {
// If Enter key is pressed, trigger encryption button clicking
if (event.keyCode === 13) {
$encryptButton.trigger('click');
}
});
},
/**
* Start key derivation of each link in the dialog
*/
startEncryption: function() {
"use strict";
const $linkAccessText = $('.js-link-access-text', this.$dialog);
const $passwordVisibilityToggle = $('.js-toggle-password-visible', this.$dialog);
const $passwordInput = $('.js-password-input', this.$dialog);
const $passwordInputWrapper = $passwordInput.parent();
const $passwordStrengthText = $('.js-strength-indicator', this.$dialog);
const $updateSuccessBanner = $('.js-update-success-banner', this.$dialog);
// Prepare MegaInput field
mega.ui.MegaInputs($passwordInput);
// Hide previous errors
$passwordInput.data('MegaInputs').hideError();
// Get the password
const password = $passwordInput.val();
// Check if TextEncoder function is available for the stringToByteArray function
if (!window.TextEncoder) {
// This feature is not supported in your browser...
$passwordInput.data('MegaInputs').showError(l[9065]);
return false;
}
// Check zxcvbn library is loaded first or we can't check the strength of the password
if (typeof zxcvbn === 'undefined') {
// The password strength verifier is still initializing
$passwordInput.data('MegaInputs').showError(l[1115]);
return false;
}
// Check that the password length is sufficient and exclude very weak passwords
if (password.length < security.minPasswordLength || $passwordInput.parent().hasClass('good1')) {
// Please use a stronger password
$passwordInput.data('MegaInputs').showError(l[9067]);
return false;
}
// Get information for each selected link showing in the dialog and convert the password to bytes
var links = exportPassword.encrypt.getLinkInfo();
// An anonymous function to derive the key and on completion create the password protected link
var processLinkInfo = function(linkInfo, algorithm, saltBytes, password) {
exportPassword.deriveKey(algorithm, saltBytes, password, function(derivedKeyBytes) {
exportPassword.encrypt.encryptAndMakeLink(linkInfo, derivedKeyBytes);
});
};
// For each selected link
for (let i = 0; i < links.length; i++) {
// Get the link information and random salt
const link = links[i];
const linkCount = links.length;
const saltBytes = link.saltBytes;
const algorithm = exportPassword.currentAlgorithm;
// Derive the key and create the password protected link
processLinkInfo(link, algorithm, saltBytes, password);
// If this is the last link
if (i === linkCount - 1) {
// Show a success banner telling them to re-copy the links
$updateSuccessBanner.text(mega.icu.format(l.links_updated_copy_again, linkCount));
$updateSuccessBanner.removeClass('hidden');
// Hide again after 3 seconds
setTimeout(() => {
$updateSuccessBanner.addClass('hidden');
}, 3000);
// Change link access description to 'Only people with the password can open the link/s'
$linkAccessText.text(mega.icu.format(l.password_link_access_explainer, linkCount));
// Set password input to read only and hide the strength display
$passwordInput.prop('readonly', true);
$passwordStrengthText.text('');
$passwordInputWrapper.removeClass('good1 good2 good3 good4 good5');
// Revert to default state for the password visibility 'eye' icon
if ($passwordVisibilityToggle.hasClass('icon-eye-hidden')) {
$passwordVisibilityToggle.trigger('click');
}
}
}
},
/**
* Encrypt the link's key and format the password protected link
* @param {Object} linkInfo The information about the link
* @param {Uint8Array} derivedKeyBytes The derived key in bytes
*/
encryptAndMakeLink: function(linkInfo, derivedKeyBytes) {
"use strict";
var encKeyBytes = null;
var algorithm = exportPassword.currentAlgorithm;
var saltBytes = linkInfo.saltBytes;
// If folder link, use the first 16 bytes (128 bits) of the derived key as the encryption key
if (linkInfo.type === exportPassword.LINK_TYPE_FOLDER) {
encKeyBytes = new Uint8Array(derivedKeyBytes.buffer, 0, 16);
}
else {
// Otherwise if it's a file link use the first 32 bytes (256 bits) as the encryption key
encKeyBytes = new Uint8Array(derivedKeyBytes.buffer, 0, 32);
}
// Use the last 32 bytes (256 bits) of the derived key as the MAC key
var macKeyLengthBytes = exportPassword.algorithms[algorithm].macKeyLength / 8;
var macKeyBytes = new Uint8Array(derivedKeyBytes.buffer, macKeyLengthBytes, macKeyLengthBytes);
// Encrypt the file/folder link key
var encryptedKey = exportPassword.xorByteArrays(encKeyBytes, linkInfo.keyBytes);
// Convert the public handle to bytes
var publicHandleBytes = asmCrypto.base64_to_bytes(linkInfo.publicHandle);
// 1 byte for alg + 1 byte if folder/file + 6 bytes for handle + 32 bytes salt + 16 or 32 bytes for key
var dataToAuthenticateLength = 2 + publicHandleBytes.length + saltBytes.length + encryptedKey.length;
var dataToAuthenticateBytes = new Uint8Array(dataToAuthenticateLength);
// Set the algorithm and set the flag for type of link
dataToAuthenticateBytes[0] = algorithm;
dataToAuthenticateBytes[1] = linkInfo.type;
// Set the handle, salt and encrypted key into the array to be authenticated using different array offsets
dataToAuthenticateBytes.set(publicHandleBytes, 2);
dataToAuthenticateBytes.set(saltBytes, 8);
dataToAuthenticateBytes.set(encryptedKey, 40);
// Create the MAC of the data
var macAlgorithm = exportPassword.algorithms[algorithm].macName;
// If using the old algorithm (1), use parameter order: HMAC(password, data)
if (algorithm === 1) {
var macBytes = asmCrypto[macAlgorithm].bytes(macKeyBytes, dataToAuthenticateBytes);
}
else {
// Otherwise for newer links (algorithm >= 2) use the correct parameter order: HMAC(data, password)
var macBytes = asmCrypto[macAlgorithm].bytes(dataToAuthenticateBytes, macKeyBytes);
}
// Create buffer for the data to be converted to Base64
var numOfBytes = dataToAuthenticateBytes.length + macBytes.length;
var dataToConvert = new Uint8Array(numOfBytes);
// Fill the array using the different offsets
dataToConvert.set(dataToAuthenticateBytes, 0);
dataToConvert.set(macBytes, dataToAuthenticateBytes.length);
// Convert the data to Base64, then make it URL safe
var dataBase64UrlEncoded = exportPassword.base64UrlEncode(dataToConvert);
// Construct URL: #P! for password link + encoded(alg + folder/file + handle + salt + encrypted key + mac)
var protectedUrl = getBaseUrl() + '/#P!' + dataBase64UrlEncoded;
if (is_mobile) {
mobile.linkManagement.pwdProtectedLink = protectedUrl;
}
else {
// Get the HTML block for this link by using the node handle
var $item = $('.item[data-node-handle="' + linkInfo.handle + '"]', this.$dialog);
// Set the password into the text box and add a class for styling this block
$('.item-link.link input', $item).val(protectedUrl);
$('.item-link.key input', $item).val('');
$item.addClass('password-protect-link');
// Update Password buttons and links UI
exportPassword.encrypt.updatePasswordComponentsUI();
exportPassword.encrypt.initResetPasswordButton();
}
// Log to see if encryption feature is used much
eventlog(99618, JSON.stringify([1, linkInfo.type === exportPassword.LINK_TYPE_FOLDER ? 1 : 0]));
},
/**
* Get the information for each selected link
* @returns {Array} Returns an array of objects containing properties 'handle', 'type', 'key', 'keyBytes'
*/
getLinkInfo: function() {
"use strict";
var links = [];
var $links = $('.item', this.$dialog);
var $selectedLink = $links.filter('.selected');
var handles = [];
// Create array of available links handles
if ($selectedLink.length) {
handles.push($selectedLink.data('node-handle'));
}
else {
$links.get().forEach(function(e) {
handles.push($(e).data('node-handle'));
});
}
// Iterate through the selected handles
for (var i in handles) {
if (handles.hasOwnProperty(i)) {
// Get the node information
var node = M.d[handles[i]];
var linkInfo = {};
// Only nodes with public handle
if (node && node.ph) {
// Folder
if (node.t) {
linkInfo.type = exportPassword.LINK_TYPE_FOLDER; // 0 byte for folder link
linkInfo.key = u_sharekeys[node.h][0]; // 128 bit key as array of 32 bit int
}
else {
// File
linkInfo.type = exportPassword.LINK_TYPE_FILE; // 1 byte for file link
linkInfo.key = node.k; // 256 bit key as array of 32 bit int
}
// Convert the key to a byte array (big endian), also add the link's handle and public handle
linkInfo.keyBytes = a32_to_ab(linkInfo.key);
linkInfo.handle = node.h;
linkInfo.publicHandle = node.ph;
// Generate a random salt for encrypting this link
var algorithm = exportPassword.currentAlgorithm;
var saltLengthBytes = exportPassword.algorithms[algorithm].saltLength / 8;
linkInfo.saltBytes = crypto.getRandomValues(new Uint8Array(saltLengthBytes));
// Add object to array
links.push(linkInfo);
}
}
}
return links;
}
}, // Encrypt functions
/**
* Functions for the decryption
*/
decrypt: {
// The jQuery selector for the Export dialog
$dialog: null,
/**
* Initialise function
* @param {String} page The current page's URL hash e.g. #P!AAA5TWTcNMtFlJ5A...
*/
init: function(page) {
"use strict";
// Cache dialog selector
this.$dialog = $('.mega-dialog.password-dialog', 'body');
this.$megaInput = new mega.ui.MegaInputs($('#password-decrypt-input',this.$dialog));
// Show the dialog
this.showDialog(page);
},
/**
* Shows the dialog to let the user decrypt the link using a password
* @param {String} page The current page's URL hash e.g. #P!AAA5TWTcNMtFlJ5A...
*/
showDialog: function(page) {
"use strict";
var $megaInput = this.$megaInput;
var $closeButton = $('button.js-close', this.$dialog);
var $decryptButton = $('.decrypt-link-button', this.$dialog);
var $decryptButtonText = $('.decrypt-text', $decryptButton);
// Show a background overlay
fm_showoverlay();
// Show the dialog
$.dialog = 'passwordlink-dialog';
this.$dialog.removeClass('hidden');
// Reset state of dialog for future password link decryptions
$decryptButtonText.text(l[1027]); // Decrypt
// Add a click handler for the close button to return to the home page (or cloud drive if logged in)
$closeButton.rebind('click', function() {
loadSubPage('');
return false;
});
// Add click handler for Decrypt button
$decryptButton.rebind('click', function() {
exportPassword.decrypt.decryptLink(page);
});
// Listen for Enter key to fire decryption
$megaInput.$input.rebind('keyup', (ev) => {
if (ev.keyCode === 13) {
exportPassword.decrypt.decryptLink(page);
}
});
},
/**
* Decrypts the password protected link and redirects to the real folder/file link
* @param {String} page The current page's URL hash e.g. #P!AAA5TWTcNMtFlJ5A...
*/
decryptLink: function(page) {
"use strict";
var $megaInput = this.$megaInput;
var $decryptButton = $('.decrypt-link-button', this.$dialog);
var $decryptButtonText = $('.decrypt-text', $decryptButton);
var $decryptButtonProgress = $('.decryption-in-progress', $decryptButton);
var $password = $megaInput.$input;
// Get the password and the encoded information in the URL
var password = $password.val();
var urlEncodedInfo = page.replace('P!', '');
var decodedBytes = null;
// If no password given...
if (!password) {
$megaInput.showError(l[970]); // Please enter a valid password...
return false;
}
// Decode the request
try {
decodedBytes = exportPassword.base64UrlDecode(urlEncodedInfo);
}
catch (exception) {
// Show error and abort
$megaInput.showError(l[9068]); // The link could not be decoded...
return false;
}
// Get the algorithm used
var algorithm = decodedBytes[0];
// Check if valid array index or will throw an exception
if (typeof exportPassword.algorithms[algorithm] === 'undefined') {
// Show error and abort
$megaInput.showError(l[9069]); // The algorithm this link was encrypted with is not supported
return false;
}
// Get the salt bytes, start offset at 8 (1 byte for alg + 1 byte for file/folder + 6 for handle)
var saltLength = exportPassword.algorithms[algorithm].saltLength / 8;
var saltStartOffset = 8;
var saltEndOffset = saltStartOffset + saltLength;
var saltBytes = decodedBytes.subarray(saltStartOffset, saltEndOffset);
// Show encryption loading animation and change text to 'Decrypting'
$decryptButtonProgress.removeClass('hidden');
$decryptButtonText.text(l[8579]);
// Compute the PBKDF
exportPassword.deriveKey(algorithm, saltBytes, password, function(derivedKeyBytes) {
// Get the MAC from the decoded bytes
var macLength = exportPassword.algorithms[algorithm].macLength / 8;
var macStartOffset = decodedBytes.length - macLength;
var macEndOffset = decodedBytes.length;
var macToVerifyBytes = decodedBytes.subarray(macStartOffset, macEndOffset);
// Get the data to verify
var dataToVerify = decodedBytes.subarray(0, macStartOffset);
// Get the MAC key
var macKeyLength = exportPassword.algorithms[algorithm].macKeyLength / 8;
var macKeyStartOffset = derivedKeyBytes.length - macKeyLength;
var macKeyEndOffset = derivedKeyBytes.length;
var macKeyBytes = derivedKeyBytes.subarray(macKeyStartOffset, macKeyEndOffset);
// Compute the MAC over the data to verify
var dataToVerifyBytes = decodedBytes.subarray(0, macStartOffset);
var macAlgorithm = exportPassword.algorithms[algorithm].macName;
// If the link was created with an old algorithm (1) which used parameter order: HMAC(password, data)
if (algorithm === 1) {
var macBytes = asmCrypto[macAlgorithm].bytes(macKeyBytes, dataToVerifyBytes);
}
else {
// Otherwise for newer links (algorithm >= 2) use the correct parameter order: HMAC(data, password)
var macBytes = asmCrypto[macAlgorithm].bytes(dataToVerifyBytes, macKeyBytes);
}
// Convert the string to hex for simple string comparison
var macString = asmCrypto.bytes_to_hex(macBytes);
var macToVerifyString = asmCrypto.bytes_to_hex(macToVerifyBytes);
// Compare the MAC in the URL to the computed MAC
if (macString !== macToVerifyString) {
// Show error and abort
$megaInput.showError(l[9076]); // The link could not be decrypted...
$decryptButtonProgress.addClass('hidden');
$decryptButtonText.text(l[1027]);
return false;
}
// Get the link type char code and set the default key length to 32 bytes
var linkTypeByte = decodedBytes[1];
var linkType = linkTypeByte;
var keyLength = 32;
// If folder link, set the key length to 16 bytes
if (linkType === exportPassword.LINK_TYPE_FOLDER) {
keyLength = 16;
}
// Get the encryption key from the derived key
var encKeyBytes = derivedKeyBytes.subarray(0, keyLength);
// Get the encrypted key, start is (2 bytes for alg and type + 6 bytes for handle + salt)
var saltLength = exportPassword.algorithms[algorithm].saltLength / 8;
var startOffset = 2 + 6 + saltLength;
var endOffset = startOffset + keyLength;
var encryptedKeyBytes = dataToVerify.subarray(startOffset, endOffset);
// Decrypt the file/folder link key
var decryptedKey = exportPassword.xorByteArrays(encKeyBytes, encryptedKeyBytes);
// Recreate the original file/folder link
var handleBytes = dataToVerify.subarray(2, 8);
var handleUrlEncoded = exportPassword.base64UrlEncode(handleBytes);
var decryptedKeyUrlEncoded = exportPassword.base64UrlEncode(decryptedKey);
var folderIdentifier = (linkType === exportPassword.LINK_TYPE_FOLDER) ? 'F' : '';
var url = folderIdentifier + '!' + handleUrlEncoded + '!' + decryptedKeyUrlEncoded;
if (mega.flags.nlfe) {
url = (folderIdentifier ? '/folder/' : '/file/') + handleUrlEncoded
+ '#' + decryptedKeyUrlEncoded;
}
// Show completed briefly before redirecting
$decryptButtonProgress.addClass('hidden');
$decryptButtonText.text(l[9077]); // Decrypted
// Clear password field
$password.val('');
// Add a log to see if the feature is used often
api_req({ a: 'log', e: 99633, m: 'Successfully decrypted password protected link on regular web' });
// On success, redirect to actual file/folder link
folderlink = false;
loadSubPage(url);
});
}
}, // Decrypt functions
/**
* Common functions for encryption and decryption
*/