summaryrefslogtreecommitdiffstats
path: root/comm/mail/extensions/openpgp/content/ui/keyWizard.js
blob: fe699bcc7e170a7c2faa12c54511ea9ba352f21c (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

/* global GetEnigmailSvc */

var { MailServices } = ChromeUtils.import(
  "resource:///modules/MailServices.jsm"
);
var { AppConstants } = ChromeUtils.importESModule(
  "resource://gre/modules/AppConstants.sys.mjs"
);
var { EnigmailCryptoAPI } = ChromeUtils.import(
  "chrome://openpgp/content/modules/cryptoAPI.jsm"
);
var { OpenPGPMasterpass } = ChromeUtils.import(
  "chrome://openpgp/content/modules/masterpass.jsm"
);
var { EnigmailDialog } = ChromeUtils.import(
  "chrome://openpgp/content/modules/dialog.jsm"
);
var { EnigmailKey } = ChromeUtils.import(
  "chrome://openpgp/content/modules/key.jsm"
);
var { EnigmailKeyRing } = ChromeUtils.import(
  "chrome://openpgp/content/modules/keyRing.jsm"
);
var { EnigmailWindows } = ChromeUtils.import(
  "chrome://openpgp/content/modules/windows.jsm"
);
var { PgpSqliteDb2 } = ChromeUtils.import(
  "chrome://openpgp/content/modules/sqliteDb.jsm"
);

ChromeUtils.defineESModuleGetters(this, {
  LoginHelper: "resource://gre/modules/LoginHelper.sys.mjs",
});

// UI variables.
var gIdentity;
var gIdentityList;
var gSubDialog;
var kStartSection;
var kDialog;
var kCurrentSection = "start";
var kGenerating = false;
var kButtonLabel;

// OpenPGP variables.
var gKeygenRequest;
var gAllData = "";
var gGeneratedKey = null;
var gFiles;

const DEFAULT_FILE_PERMS = 0o600;

// The revocation strings are not localization since the revocation certificate
// will be published to others who may not know the native language of the user.
const revocationFilePrefix1 =
  "This is a revocation certificate for the OpenPGP key:";
const revocationFilePrefix2 = `
A revocation certificate is kind of a "kill switch" to publicly
declare that a key shall no longer be used.  It is not possible
to retract such a revocation certificate once it has been published.

Use it to revoke this key in case of a secret key compromise, or loss of
the secret key, or loss of passphrase of the secret key.

To avoid an accidental use of this file, a colon has been inserted
before the 5 dashes below.  Remove this colon with a text editor
before importing and publishing this revocation certificate.

:`;

var syncl10n = new Localization(["messenger/openpgp/keyWizard.ftl"], true);

// Dialog event listeners.
document.addEventListener("dialogaccept", wizardContinue);
document.addEventListener("dialogextra1", goBack);
document.addEventListener("dialogcancel", onClose);

/**
 * Initialize the keyWizard dialog.
 */
async function init() {
  gSubDialog = window.arguments[0].gSubDialog;
  gIdentity = window.arguments[0].identity || null;
  gIdentityList = document.getElementById("userIdentity");

  kStartSection = document.getElementById("wizardStart");
  kDialog = document.querySelector("dialog");

  await initIdentity();

  // Show the GnuPG radio selection if the pref is enabled.
  if (Services.prefs.getBoolPref("mail.openpgp.allow_external_gnupg")) {
    document.getElementById("externalOpenPgp").removeAttribute("hidden");
  }

  // After the dialog is visible, disable the event listeners causing it to
  // close when clicking on the overlay or hitting the Esc key, and remove the
  // close button from the header. This is necessary to control the escape
  // point and prevent the accidental dismiss of the dialog during important
  // processes, like the generation or importing of a key.
  setTimeout(() => {
    // Check if the attribute is not null. This can be removed after the full
    // conversion of the Key Manager into a SubDialog in Bug 1652537.
    if (gSubDialog) {
      gSubDialog._topDialog._removeDialogEventListeners();
      gSubDialog._topDialog._closeButton.remove();
      resizeDialog();
    }
  }, 150);

  // Switch directly to the create screen if requested by the user.
  if (window.arguments[0].isCreate) {
    document.getElementById("openPgpKeyChoices").value = 0;

    switchSection();
  }

  // Switch directly to the import screen if requested by the user.
  if (window.arguments[0].isImport) {
    document.getElementById("openPgpKeyChoices").value = 1;

    // Disable the "Continue" button so the user can't accidentally click on it.
    // See bug 1689980.
    kDialog.getButton("accept").setAttribute("disabled", true);

    switchSection();
  }
}

function onProtectionChange() {
  let pw1Element = document.getElementById("passwordInput");
  let pw2Element = document.getElementById("passwordConfirm");

  let pw1 = pw1Element.value;
  let pw2 = pw2Element.value;

  let inputDisabled = document.getElementById("keygenAutoProtection").selected;
  pw1Element.disabled = inputDisabled;
  pw2Element.disabled = inputDisabled;

  let buttonEnabled = inputDisabled || (!inputDisabled && pw1 == pw2 && pw1);
  let ok = kDialog.getButton("accept");
  ok.disabled = !buttonEnabled;
}

/**
 * Populate the identity menulist with all the valid and available identities
 * and autoselect the current identity if available.
 */
async function initIdentity() {
  let identityListPopup = document.getElementById("userIdentityPopup");

  for (let identity of MailServices.accounts.allIdentities) {
    // Skip invalid and non-email identities.
    if (!identity.valid || !identity.email) {
      continue;
    }

    // Interrupt if no server was defined for this identity.
    let servers = MailServices.accounts.getServersForIdentity(identity);
    if (servers.length == 0) {
      continue;
    }

    let item = document.createXULElement("menuitem");
    item.setAttribute(
      "label",
      `${identity.identityName} - ${servers[0].prettyName}`
    );
    item.setAttribute("class", "identity-popup-item");
    item.setAttribute("accountname", servers[0].prettyName);
    item.setAttribute("identitykey", identity.key);
    item.setAttribute("email", identity.email);

    identityListPopup.appendChild(item);

    if (gIdentity && gIdentity.key == identity.key) {
      gIdentityList.selectedItem = item;
    }
  }

  // If not identity was originally passed during the creation of this dialog,
  // select the first available value.
  if (!gIdentity) {
    gIdentityList.selectedIndex = 0;
  }

  await setIdentity();
}

/**
 * Update the currently used identity to reflect the user selection from the
 * identity menulist.
 */
async function setIdentity() {
  if (gIdentityList.selectedItem) {
    gIdentity = MailServices.accounts.getIdentity(
      gIdentityList.selectedItem.getAttribute("identitykey")
    );

    document.l10n.setAttributes(
      document.documentElement,
      "key-wizard-dialog-window",
      {
        identity: gIdentity.email,
      }
    );
  }
}

/**
 * Intercept the dialogaccept command to implement a wizard like setup workflow.
 *
 * @param {Event} event - The DOM Event.
 */
function wizardContinue(event) {
  event.preventDefault();

  // Pretty impossible scenario but just in case if no radio button is
  // currently selected, bail out.
  if (!document.getElementById("openPgpKeyChoices").value) {
    return;
  }

  // Trigger an action based on the currently visible section.
  if (kCurrentSection != "start") {
    wizardNextStep();
    return;
  }

  // Disable the `Continue` button.
  kDialog.getButton("accept").setAttribute("disabled", true);

  kStartSection.addEventListener("transitionend", switchSection, {
    once: true,
  });
  kStartSection.classList.add("hide");
}

/**
 * Separated method dealing with the section switching to allow the removal of
 * the event listener to prevent stacking.
 */
function switchSection() {
  kStartSection.setAttribute("hidden", true);

  // Save the current label of the accept button in order to restore it later.
  kButtonLabel = kDialog.getButton("accept").label;

  // Update the UI based on the radiogroup selection.
  switch (document.getElementById("openPgpKeyChoices").value) {
    case "0":
      wizardCreateKey();
      break;

    case "1":
      wizardImportKey();
      break;

    case "2":
      wizardExternalKey();
      break;
  }

  // Show the `Go back` button.
  kDialog.getButton("extra1").hidden = false;
  resizeDialog();
}

/**
 * Handle the next step of the wizard based on the currently visible section.
 */
async function wizardNextStep() {
  switch (kCurrentSection) {
    case "create":
      await openPgpKeygenStart();
      break;

    case "import":
      await openPgpImportStart();
      break;

    case "importComplete":
      openPgpImportComplete();
      break;

    case "external":
      openPgpExternalComplete();
      break;
  }
}

/**
 * Go back to the initial view of the wizard.
 */
function goBack() {
  let section = document.querySelector(".wizard-section:not([hidden])");
  section.addEventListener("transitionend", backToStart, { once: true });
  section.classList.add("hide-reverse");
}

/**
 * Hide the currently visible section at the end of the animation, remove the
 * listener to prevent stacking, and trigger the reveal of the first section.
 *
 * @param {Event} event - The DOM Event.
 */
function backToStart(event) {
  // Hide the `Go Back` button.
  kDialog.getButton("extra1").hidden = true;

  // Enable the `Continue` button.
  kDialog.getButton("accept").removeAttribute("disabled");

  kDialog.getButton("accept").label = kButtonLabel;
  kDialog.getButton("accept").classList.remove("primary");

  // Reset the import section.
  clearImportWarningNotifications();
  document.getElementById("importKeyIntro").hidden = false;
  document.getElementById("importKeyListContainer").collapsed = true;

  event.target.setAttribute("hidden", true);

  // Reset section key.
  kCurrentSection = "start";

  revealSection("wizardStart");
}

/**
 * Create a new inline notification to append to the import warning container.
 *
 * @returns {XULElement} - The description element inside the notification.
 */
async function addImportWarningNotification() {
  let notification = document.createXULElement("hbox");
  notification.classList.add(
    "inline-notification-container",
    "error-container"
  );

  let wrapper = document.createXULElement("hbox");
  wrapper.classList.add("inline-notification-wrapper", "align-center");

  let image = document.createElement("img");
  image.classList.add("notification-image");
  image.setAttribute("src", "chrome://global/skin/icons/warning.svg");
  image.setAttribute("alt", "");

  let description = document.createXULElement("description");

  wrapper.appendChild(image);
  wrapper.appendChild(description);

  notification.appendChild(wrapper);

  let container = document.getElementById("openPgpImportWarning");
  container.appendChild(notification);

  // Show the notification container.
  container.removeAttribute("hidden");

  return description;
}

/**
 * Remove all inline errors from the notification area of the import section.
 */
function clearImportWarningNotifications() {
  let container = document.getElementById("openPgpImportWarning");

  // Remove any existing notification.
  for (let notification of container.querySelectorAll(
    ".inline-notification-container"
  )) {
    notification.remove();
  }

  // Hide the entire notification container.
  container.hidden = true;
}

/**
 * Show the Key Creation section.
 */
async function wizardCreateKey() {
  kCurrentSection = "create";
  revealSection("wizardCreateKey");

  kDialog.getButton("accept").label = await document.l10n.formatValue(
    "openpgp-keygen-button"
  );
  kDialog.getButton("accept").classList.add("primary");

  if (!gIdentity.fullName) {
    document.getElementById("openPgpWarning").collapsed = false;
    document.l10n.setAttributes(
      document.getElementById("openPgpWarningDescription"),
      "openpgp-keygen-long-expiry"
    );
    return;
  }

  let sepPassphraseEnabled = Services.prefs.getBoolPref(
    "mail.openpgp.passphrases.enabled"
  );
  document.getElementById("keygenPassphraseSection").hidden =
    !sepPassphraseEnabled;

  if (sepPassphraseEnabled) {
    let usingPP = LoginHelper.isPrimaryPasswordSet();
    let autoProt = document.getElementById("keygenAutoProtection");

    document.l10n.setAttributes(
      autoProt,
      usingPP
        ? "radio-keygen-protect-primary-pass"
        : "radio-keygen-no-protection"
    );

    autoProt.setAttribute("selected", true);
    document
      .getElementById("keygenPassphraseProtection")
      .removeAttribute("selected");
  }

  // This also handles enable/disabling the accept/ok button.
  onProtectionChange();
}

/**
 * Show the Key Import section.
 */
function wizardImportKey() {
  kCurrentSection = "import";
  revealSection("wizardImportKey");

  let sepPassphraseEnabled = Services.prefs.getBoolPref(
    "mail.openpgp.passphrases.enabled"
  );
  let keepPassphrasesItem = document.getElementById(
    "openPgpKeygenKeepPassphrases"
  );
  keepPassphrasesItem.hidden = !sepPassphraseEnabled;
  keepPassphrasesItem.checked = false;
}

/**
 * Show the Key Setup via external smartcard section.
 */
async function wizardExternalKey() {
  kCurrentSection = "external";
  revealSection("wizardExternalKey");

  kDialog.getButton("accept").label = await document.l10n.formatValue(
    "openpgp-save-external-button"
  );
  kDialog.getButton("accept").classList.add("primary");

  // If the user is already using an external GnuPG key, populate the input,
  // show the warning description, and enable the primary button.
  if (gIdentity.getBoolAttribute("is_gnupg_key_id")) {
    document.getElementById("externalKey").value =
      gIdentity.getUnicharAttribute("last_entered_external_gnupg_key_id");
    document.getElementById("openPgpExternalWarning").collapsed = false;
    kDialog.getButton("accept").removeAttribute("disabled");
  } else {
    document.getElementById("openPgpExternalWarning").collapsed = true;
    kDialog.getButton("accept").setAttribute("disabled", true);
  }
}

/**
 * Animate the reveal of a section of the wizard.
 *
 * @param {string} id - The id of the section to reveal.
 */
function revealSection(id) {
  let section = document.getElementById(id);
  section.removeAttribute("hidden");

  // Timeout to animate after the hidden attribute has been removed.
  setTimeout(() => {
    section.classList.remove("hide", "hide-reverse");
  });

  resizeDialog();
}

/**
 * Enable or disable the elements based on the radiogroup selection.
 *
 * @param {Event} event - The DOM event triggered on change.
 */
function onExpirationChange(event) {
  document
    .getElementById("expireInput")
    .toggleAttribute("disabled", event.target.value != 0);
  document.getElementById("timeScale").disabled = event.target.value != 0;

  validateExpiration();
}

/**
 * Enable or disable the #keySize input field based on the current selection of
 * the #keyType radio group.
 *
 * @param {Event} event - The DOM Event.
 */
function onKeyTypeChange(event) {
  document.getElementById("keySize").disabled = event.target.value == "ECC";
}

/**
 * Intercept the cancel event to prevent accidental closing if the generation of
 * a key is currently in progress.
 *
 * @param {Event} event - The DOM event.
 */
function onClose(event) {
  if (kGenerating) {
    event.preventDefault();
  }

  window.arguments[0].cancelCallback();
}

/**
 * Validate the expiration time of a newly generated key when the user changes
 * values. Disable the "Generate Key" button and show an alert if the selected
 * value is less than 1 day or more than 100 years.
 */
async function validateExpiration() {
  // If the key doesn't have an expiration date, hide the warning message and
  // enable the "Generate Key" button.
  if (document.getElementById("openPgpKeygeExpiry").value == 1) {
    document.getElementById("openPgpWarning").collapsed = true;
    kDialog.getButton("accept").removeAttribute("disabled");
    return;
  }

  // Calculate the selected expiration date.
  let expiryTime =
    Number(document.getElementById("expireInput").value) *
    Number(document.getElementById("timeScale").value);

  // If the expiration date exceeds 100 years.
  if (expiryTime > 36500) {
    document.getElementById("openPgpWarning").collapsed = false;
    document.l10n.setAttributes(
      document.getElementById("openPgpWarningDescription"),
      "openpgp-keygen-long-expiry"
    );
    kDialog.getButton("accept").setAttribute("disabled", true);
    resizeDialog();
    return;
  }

  // If the expiration date is shorter than 1 day.
  if (expiryTime <= 0) {
    document.getElementById("openPgpWarning").collapsed = false;
    document.l10n.setAttributes(
      document.getElementById("openPgpWarningDescription"),
      "openpgp-keygen-short-expiry"
    );
    kDialog.getButton("accept").setAttribute("disabled", true);
    resizeDialog();
    return;
  }

  // If the previous conditions are false, hide the warning message and
  // enable the "Generate Key" button since the expiration date is valid.
  document.getElementById("openPgpWarning").collapsed = true;
  kDialog.getButton("accept").removeAttribute("disabled");
}

/**
 * Resize the dialog to account for the newly visible sections.
 */
function resizeDialog() {
  // Check if the attribute is not null. This can be removed after the full
  // conversion of the Key Manager into a SubDialog in Bug 1652537.
  if (gSubDialog && gSubDialog._topDialog) {
    gSubDialog._topDialog.resizeVertically();
  } else {
    window.sizeToContent();
  }
}

/**
 * Start the generation of a new OpenPGP Key.
 */
async function openPgpKeygenStart() {
  let openPgpWarning = document.getElementById("openPgpWarning");
  let openPgpWarningText = document.getElementById("openPgpWarningDescription");
  openPgpWarning.collapsed = true;

  // If a key generation request is already pending, warn the user and
  // don't proceed.
  if (gKeygenRequest) {
    let req = gKeygenRequest.QueryInterface(Ci.nsIRequest);

    if (req.isPending()) {
      openPgpWarning.collapsed = false;
      document.l10n.setAttributes(openPgpWarningText, "openpgp-keygen-ongoing");
      return;
    }
  }

  // Reset global variables to be sure.
  gGeneratedKey = null;
  gAllData = "";

  let enigmailSvc = GetEnigmailSvc();
  if (!enigmailSvc) {
    openPgpWarning.collapsed = false;
    document.l10n.setAttributes(
      openPgpWarningText,
      "openpgp-keygen-error-core"
    );
    closeOverlay();

    throw new Error("GetEnigmailSvc failed");
  }

  // Show wizard overlay before the start of the generation process. This is
  // necessary because the generation happens synchronously and blocks the UI.
  // We need to show the overlay before it, otherwise it would flash and freeze.
  // This should be moved after the Services.prompt.confirmEx() method
  // once Bug 1617444 is implemented.
  let overlay = document.getElementById("wizardOverlay");
  overlay.removeAttribute("hidden");
  overlay.classList.remove("hide");

  // Ask for confirmation before triggering the generation of a new key.
  document.l10n.setAttributes(
    document.getElementById("wizardOverlayQuestion"),
    "openpgp-key-confirm",
    {
      identity: `${gIdentity.fullName} <b>"${gIdentity.email}"</b>`,
    }
  );

  document.l10n.setAttributes(
    document.getElementById("wizardOverlayTitle"),
    "openpgp-keygen-progress-title"
  );
}

async function openPgpKeygenConfirm() {
  document.getElementById("openPgpKeygenConfirm").collapsed = true;
  document.getElementById("openPgpKeygenProcess").removeAttribute("collapsed");

  let openPgpWarning = document.getElementById("openPgpWarning");
  let openPgpWarningText = document.getElementById("openPgpWarningDescription");
  openPgpWarning.collapsed = true;

  kGenerating = true;

  let password;
  let cApi = EnigmailCryptoAPI();
  let newId = null;

  let sepPassphraseEnabled = Services.prefs.getBoolPref(
    "mail.openpgp.passphrases.enabled"
  );

  if (
    !sepPassphraseEnabled ||
    document.getElementById("keygenAutoProtection").selected
  ) {
    password = await OpenPGPMasterpass.retrieveOpenPGPPassword();
  } else {
    password = document.getElementById("passwordInput").value;
  }
  newId = await cApi.genKey(
    `${gIdentity.fullName} <${gIdentity.email}>`,
    document.getElementById("keyType").value,
    Number(document.getElementById("keySize").value),
    document.getElementById("openPgpKeygeExpiry").value == 1
      ? 0
      : Number(document.getElementById("expireInput").value) *
          Number(document.getElementById("timeScale").value),
    password
  );

  gGeneratedKey = newId;

  EnigmailWindows.keyManReloadKeys();

  gKeygenRequest = null;
  kGenerating = false;

  // For wathever reason, the key wasn't generated. Show an error message and
  // hide the processing overlay.
  if (!gGeneratedKey) {
    openPgpWarning.collapsed = false;
    document.l10n.setAttributes(
      openPgpWarningText,
      "openpgp-keygen-error-failed"
    );
    closeOverlay();

    throw new Error("key generation failed");
  }

  console.debug("saving new key id " + gGeneratedKey);
  Services.prefs.savePrefFile(null);

  // Hide wizard overlay at the end of the generation process.
  closeOverlay();
  EnigmailKeyRing.clearCache();

  let rev = await cApi.unlockAndGetNewRevocation(
    `0x${gGeneratedKey}`,
    password
  );
  if (!rev) {
    openPgpWarning.collapsed = false;
    document.l10n.setAttributes(
      openPgpWarningText,
      "openpgp-keygen-error-revocation",
      {
        key: gGeneratedKey,
      }
    );
    closeOverlay();

    throw new Error("failed to obtain revocation for key " + gGeneratedKey);
  }

  let revFull =
    revocationFilePrefix1 +
    "\n\n" +
    gGeneratedKey +
    "\n" +
    revocationFilePrefix2 +
    rev;

  let revFile = Services.dirsvc.get("ProfD", Ci.nsIFile);
  revFile.append(`0x${gGeneratedKey}_rev.asc`);

  // Create a revokation cert in the Thunderbird profile directory.
  await IOUtils.writeUTF8(revFile.path, revFull);

  // Key successfully created. Close the dialog and show a confirmation message.
  // Assigning the key to an identity is the responsibility of the caller,
  // so we pass back what we created.
  window.arguments[0].okCallback(gGeneratedKey);
  window.close();
}

/**
 * Cancel the keygen process, ask for confirmation before proceeding.
 */
async function openPgpKeygenCancel() {
  let [abortTitle, abortText] = await document.l10n.formatValues([
    { id: "openpgp-keygen-abort-title" },
    { id: "openpgp-keygen-abort" },
  ]);

  if (
    kGenerating &&
    Services.prompt.confirmEx(
      window,
      abortTitle,
      abortText,
      Services.prompt.STD_YES_NO_BUTTONS,
      "",
      "",
      "",
      "",
      {}
    ) != 0
  ) {
    return;
  }

  closeOverlay();
  gKeygenRequest.kill(false);
  kGenerating = false;
}

/**
 * Close the processing wizard overlay.
 */
function closeOverlay() {
  document.getElementById("openPgpKeygenConfirm").removeAttribute("collapsed");
  document.getElementById("openPgpKeygenProcess").collapsed = true;

  let overlay = document.getElementById("wizardOverlay");

  overlay.addEventListener("transitionend", hideOverlay, { once: true });
  overlay.classList.add("hide");
}

/**
 * Add the "hidden" attribute tot he processing wizard overlay after the CSS
 * transition ended.
 *
 * @param {Event} event - The DOM Event.
 */
function hideOverlay(event) {
  event.target.setAttribute("hidden", true);
  resizeDialog();
}

async function importSecretKey() {
  let [importTitle, importType] = await document.l10n.formatValues([
    { id: "import-key-file" },
    { id: "gnupg-file" },
  ]);

  // Reset the array of selected files.
  gFiles = [];

  let files = EnigmailDialog.filePicker(
    window,
    importTitle,
    "",
    false,
    true,
    "*.asc",
    "",
    [importType, "*.asc;*.gpg;*.pgp"]
  );

  if (!files.length) {
    return;
  }

  // Clear and hide the warning notification section.
  clearImportWarningNotifications();

  // Clear the key list from any previously listed key.
  let keyList = document.getElementById("importKeyList");
  while (keyList.lastChild) {
    keyList.lastChild.remove();
  }

  let keyCount = 0;
  for (let file of files) {
    // Skip the file and show a warning message if larger than 5MB.
    if (file.fileSize > 5000000) {
      document.l10n.setAttributes(
        await addImportWarningNotification(),
        "import-error-file-size"
      );
      continue;
    }

    let errorMsgObj = {};
    // Fetch the list of all the available keys inside the selected file.
    let importKeys = await EnigmailKey.getKeyListFromKeyFile(
      file,
      errorMsgObj,
      false,
      true
    );

    // Skip the file and show a warning message if the import failed.
    if (!importKeys || !importKeys.length || errorMsgObj.value) {
      document.l10n.setAttributes(
        await addImportWarningNotification(),
        "import-error-failed",
        {
          error: errorMsgObj.value,
        }
      );
      continue;
    }

    await appendFetchedKeys(importKeys);
    keyCount += importKeys.length;

    // Add the current file to the list of valid files to import.
    gFiles.push(file);
  }

  // Update the list count recap and show the container.
  document.l10n.setAttributes(
    document.getElementById("keyListCount"),
    "openpgp-import-key-list-amount-2",
    {
      count: keyCount,
    }
  );

  document.getElementById("importKeyListContainer").collapsed = !keyCount;

  // Hide the intro section and enable the import of keys only if we have valid
  // keys currently listed.
  if (keyCount) {
    document.getElementById("importKeyIntro").hidden = true;
    kDialog.getButton("accept").removeAttribute("disabled");
    kDialog.getButton("accept").classList.add("primary");
  }

  resizeDialog();
}

/**
 * Populate the key list in the import dialog with all the valid keys fetched
 * from a single file.
 *
 * @param {string[]} importKeys - The array of keys fetched from a single file.
 */
async function appendFetchedKeys(importKeys) {
  let keyList = document.getElementById("importKeyList");

  // List all the keys fetched from the file.
  for (let key of importKeys) {
    let container = document.createXULElement("hbox");
    container.classList.add("key-import-row", "selected");

    let titleContainer = document.createXULElement("vbox");

    let id = document.createXULElement("label");
    id.classList.add("openpgp-key-id");
    id.value = `0x${key.id}`;

    let name = document.createXULElement("label");
    name.classList.add("openpgp-key-name");
    name.value = key.name;

    titleContainer.appendChild(id);
    titleContainer.appendChild(name);

    // Allow users to treat imported keys as "Personal".
    let checkbox = document.createXULElement("checkbox");
    checkbox.setAttribute("id", `${key.id}-set-personal`);
    document.l10n.setAttributes(checkbox, "import-key-personal-checkbox");
    checkbox.checked = true;

    container.appendChild(titleContainer);
    container.appendChild(checkbox);

    keyList.appendChild(container);
  }
}

async function openPgpImportStart() {
  if (!gFiles.length) {
    return;
  }

  kGenerating = true;

  // Show the overlay.
  let overlay = document.getElementById("wizardImportOverlay");
  overlay.removeAttribute("hidden");
  overlay.classList.remove("hide");

  // Clear and hide the warning notification section.
  clearImportWarningNotifications();

  // Clear the list of any previously improted keys from the DOM.
  let keyList = document.getElementById("importKeyListRecap");
  while (keyList.lastChild) {
    keyList.lastChild.remove();
  }

  let keyCount = 0;
  for (let file of gFiles) {
    let resultKeys = {};
    let errorMsgObj = {};

    // keepPassphrases false is the classic behavior.
    let keepPassphrases = false;

    // If the pref is on, we allow the user to decide what to do.
    let allowSeparatePassphrases = Services.prefs.getBoolPref(
      "mail.openpgp.passphrases.enabled"
    );
    if (allowSeparatePassphrases) {
      keepPassphrases = document.getElementById(
        "openPgpKeygenKeepPassphrases"
      ).checked;
    }

    let exitCode = await EnigmailKeyRing.importSecKeyFromFile(
      window,
      passphrasePromptCallback,
      keepPassphrases,
      file,
      errorMsgObj,
      resultKeys
    );

    // Skip this file if something went wrong.
    if (exitCode !== 0) {
      document.l10n.setAttributes(
        await addImportWarningNotification(),
        "openpgp-import-keys-failed",
        {
          error: errorMsgObj.value,
        }
      );
      continue;
    }

    await appendImportedKeys(resultKeys);
    keyCount += resultKeys.keys.length;
  }

  // Hide the previous key list container and title.
  document.getElementById("importKeyListContainer").collapsed = keyCount;
  document.getElementById("importKeyTitle").hidden = keyCount;

  // Show the successful final screen only if at least one key was imported.
  if (keyCount) {
    // Update the dialog buttons for the final stage.
    kDialog.getButton("extra1").hidden = true;
    kDialog.getButton("cancel").hidden = true;

    // Update the `Continue` button.
    document.l10n.setAttributes(
      kDialog.getButton("accept"),
      "openpgp-keygen-import-complete"
    );
    kCurrentSection = "importComplete";

    // Show the recently built key list.
    document.getElementById("importKeyListSuccess").collapsed = false;
  }

  // Hide the loading overlay.
  overlay.addEventListener("transitionend", hideOverlay, { once: true });
  overlay.classList.add("hide");

  resizeDialog();
  kGenerating = false;
}

/**
 * Populate the key list in the import dialog with all the valid keys imported
 * from a single file.
 *
 * @param {string[]} resultKeys - The array of keys imported from a single file.
 */
async function appendImportedKeys(resultKeys) {
  let keyList = document.getElementById("importKeyListRecap");

  for (let keyId of resultKeys.keys) {
    if (keyId.search(/^0x/) === 0) {
      keyId = keyId.substr(2).toUpperCase();
    }

    let key = EnigmailKeyRing.getKeyById(keyId);

    if (key && key.fpr) {
      // If the checkbox was checked, update the acceptance of the key.
      if (document.getElementById(`${key.keyId}-set-personal`).checked) {
        PgpSqliteDb2.acceptAsPersonalKey(key.fpr);
      }

      let container = document.createXULElement("hbox");
      container.classList.add("key-import-row");

      // Start key info section.
      let grid = document.createXULElement("hbox");
      grid.classList.add("extra-information-label");

      // Key identity.
      let identityLabel = document.createXULElement("label");
      identityLabel.classList.add("extra-information-label-type");
      document.l10n.setAttributes(
        identityLabel,
        "openpgp-import-identity-label"
      );

      let identityValue = document.createXULElement("label");
      identityValue.value = key.userId;

      grid.appendChild(identityLabel);
      grid.appendChild(identityValue);

      // Key fingerprint.
      let fingerprintLabel = document.createXULElement("label");
      document.l10n.setAttributes(
        fingerprintLabel,
        "openpgp-import-fingerprint-label"
      );
      fingerprintLabel.classList.add("extra-information-label-type");

      let fingerprintInput = document.createXULElement("label");
      fingerprintInput.value = EnigmailKey.formatFpr(key.fpr);

      grid.appendChild(fingerprintLabel);
      grid.appendChild(fingerprintInput);

      // Key creation date.
      let createdLabel = document.createXULElement("label");
      document.l10n.setAttributes(createdLabel, "openpgp-import-created-label");
      createdLabel.classList.add("extra-information-label-type");

      let createdValue = document.createXULElement("label");
      createdValue.value = key.created;

      grid.appendChild(createdLabel);
      grid.appendChild(createdValue);

      // Key bits.
      let bitsLabel = document.createXULElement("label");
      bitsLabel.classList.add("extra-information-label-type");
      document.l10n.setAttributes(bitsLabel, "openpgp-import-bits-label");

      let bitsValue = document.createXULElement("label");
      bitsValue.value = key.keySize;

      grid.appendChild(bitsLabel);
      grid.appendChild(bitsValue);
      // End key info section.

      let info = document.createXULElement("button");
      info.classList.add("openpgp-image-btn", "openpgp-props-btn");
      document.l10n.setAttributes(info, "openpgp-import-key-props");
      info.addEventListener("command", () => {
        window.arguments[0].keyDetailsDialog(key.keyId);
      });

      container.appendChild(grid);
      container.appendChild(info);

      keyList.appendChild(container);
    }
  }
}

function openPgpImportComplete() {
  window.arguments[0].okImportCallback();
  window.close();
}

/**
 * Opens a prompt asking the user to enter the passphrase for a given key id.
 *
 * @param {object} win - The current window.
 * @param {string} keyId - The ID of the imported key.
 * @param {object} resultFlags - Keep track of the cancelled action.
 *
 * @returns {string} - The entered passphrase or empty.
 */
function passphrasePromptCallback(win, promptString, resultFlags) {
  let passphrase = { value: "" };

  // We need to fetch these strings synchronously in order to properly work with
  // the RNP key import method, which is not async.
  let title = syncl10n.formatValueSync("openpgp-passphrase-prompt-title");

  let prompt = Services.prompt.promptPassword(
    win,
    title,
    promptString,
    passphrase,
    null,
    {}
  );

  if (!prompt) {
    let overlay = document.getElementById("wizardImportOverlay");
    overlay.addEventListener("transitionend", hideOverlay, { once: true });
    overlay.classList.add("hide");
    kGenerating = false;
  }

  resultFlags.canceled = !prompt;
  return !prompt ? "" : passphrase.value;
}

function toggleSaveButton(event) {
  kDialog
    .getButton("accept")
    .toggleAttribute("disabled", !event.target.value.trim());
}

/**
 * Save the GnuPG Key for the current identity and trigger a callback.
 */
function openPgpExternalComplete() {
  gIdentity.setBoolAttribute("is_gnupg_key_id", true);

  let externalKey = document.getElementById("externalKey").value;
  gIdentity.setUnicharAttribute("openpgp_key_id", externalKey);

  window.arguments[0].okExternalCallback(externalKey);
  window.close();
}