Skip to content
Snippets Groups Projects
viamapi-iframe.js 84.9 KiB
Newer Older
const libmime = require('libmime');
const QRCode = require('qrcode');
const pkijs = require('pkijs');
const asn1js = require('asn1js');
const pvutils = require('pvutils');
const Penpal = require('penpal').default;
window.axios = require('axios');
//*********************************************************************************

const CERTIFIATE_Version_1 = 0;
const CERTIFIATE_Version_3 = 2;

//these bit fields are reversed, WTF!
const KEY_USAGE_DigitalSignature	= 0x80;//01;
const KEY_USAGE_NonRepudiation		= 0x40;//02;
const KEY_USAGE_KeyEncipherment		= 0x20;//04;
const KEY_USAGE_DataEncipherment	= 0x10;//08;
const KEY_USAGE_KeyAgreement		= 0x08;//10;
const KEY_USAGE_KeyCertSign			= 0x04;//20;
const KEY_USAGE_CRLSign				= 0x02;//40;
//const KEY_USAGE_EncipherOnly		= 0x01;//80; // Not used for now. Must be used together with KEY_USAGE_KeyAgreement (maybe should be ORed as a constant directly?)
//const KEY_USAGE_DecipherOnly		= 0x80;//0100; // If used, modify "KeyUsage" extension array buffer size and appropriate bit operators to accomodate for extra byte

const KEY_USAGE_LeafCertificate		= KEY_USAGE_DigitalSignature | KEY_USAGE_NonRepudiation | KEY_USAGE_KeyEncipherment | KEY_USAGE_DataEncipherment;
const KEY_USAGE_CertificateAuthority= KEY_USAGE_DigitalSignature | KEY_USAGE_KeyCertSign | KEY_USAGE_CRLSign;


const OID_EXT_KEY_USAGE_Any     	= "2.5.29.37.0";
const OID_ID_PKIX_ServerAuth		= "1.3.6.1.5.5.7.3.1";
const OID_ID_PKIX_ClientAuth		= "1.3.6.1.5.5.7.3.2";
const OID_ID_PKIX_CodeSigning		= "1.3.6.1.5.5.7.3.3";
const OID_ID_PKIX_EmailProtection	= "1.3.6.1.5.5.7.3.4";
const OID_ID_PKIX_TimeStamping	    = "1.3.6.1.5.5.7.3.8";
const OID_ID_PKIX_OCSPSigning		= "1.3.6.1.5.5.7.3.9";
// const OID_EXT_KEY_USAGE_MS...	= "1.3.6.1.4.1.311.10.3.1"; // Microsoft Certificate Trust List signing
// const OID_EXT_KEY_USAGE_MS...	= "1.3.6.1.4.1.311.10.3.4";  // Microsoft Encrypted File System
const OID_PKCS7_Data                = "1.2.840.113549.1.7.1";
const OID_PKCS7_SignedData          = "1.2.840.113549.1.7.2";
const OID_PKCS7_EnvelopedData       = "1.2.840.113549.1.7.3";
const OID_PKCS9_EmailAddress        = "1.2.840.113549.1.9.1";
const OID_PKCS9_ContentType         = "1.2.840.113549.1.9.3";
const OID_PKCS9_MessageDigest       = "1.2.840.113549.1.9.4";
const OID_PKCS9_SigningTime         = "1.2.840.113549.1.9.5"

const defaultAlgorithms = {
  hashAlg: "SHA-256",
  signAlg: "RSASSA-PKCS1-v1_5",
  keyLength: 2048
}

const AES_encryptionVariant_Password  = 2;
const encryptionAlgorithm = {
  name: "AES-CBC",
  length: 128
};

//*********************************************************************************
// Returns promise, resolved to keyPair object {publicKey, privateKey}
//*********************************************************************************
function generateKeys(algorithms) {
  //region Get a "crypto" extension
  const crypto = pkijs.getCrypto();
  if (typeof crypto === "undefined") {
    return Promise.reject("No WebCrypto extension found");
  }
  //endregion Get a "crypto" extension

  if (!algorithms) {
    algorithms = defaultAlgorithms;
  } else {
    if (!algorithms.hashAlg) {
      algorithms.hashAlg = defaultAlgorithms.hashAlg;
    }
    if (!algorithms.signAlg) {
      algorithms.signAlg = defaultAlgorithms.signAlg;
    }
    if (!algorithms.keyLength) {
      algorithms.keyLength = defaultAlgorithms.keyLength;
    }
  }

  //region Get default algorithm parameters for key generation
  const algorithm = pkijs.getAlgorithmParameters(algorithms.signAlg, "generatekey");
  if("hash" in algorithm.algorithm) {
    algorithm.algorithm.hash.name = algorithms.hashAlg;
  }
  algorithm.algorithm.modulusLength = algorithms.keyLength;
  //endregion

  return crypto.generateKey(algorithm.algorithm, true, algorithm.usages);
}

//*********************************************************************************
function createCertificate(certData, issuerData = null)
{

  if (typeof certData === "undefined") {
    return Promise.reject("No Certificate data provided");
  }

  if (typeof certData.subject === "undefined") {
    return Promise.reject("No Certificate subject data provided");
  }


  //region Get a "crypto" extension
  const crypto = pkijs.getCrypto();

  if (typeof crypto === "undefined") {
    return Promise.reject("No WebCrypto extension found");
  }
  //endregion Get a "crypto" extension

  //region Initial variables
  let sequence = Promise.resolve();

  const certificate = new pkijs.Certificate();
  let publicKey;
  let privateKey;

  let certificateBuffer;// = new ArrayBuffer(0); // ArrayBuffer with loaded or created CERT
  let privateKeyBuffer;// = new ArrayBuffer(0);
  let publicKeyBuffer;// = new ArrayBuffer(0);

  //endregion Initial variables

  if (certData.keyPair) {
    //region Create a new key pair
    sequence = sequence.then(() =>
    {
      return certData.keyPair;
    });
    //endregion Create a new key pair

  } else {
    //region Create a new key pair
    sequence = sequence.then(() =>
    {
      return generateKeys(certData.algorithms);
    });
    //endregion Create a new key pair
  }

  //region Store new key in an interim variables
  sequence = sequence.then(keyPair =>
  {
    publicKey = keyPair.publicKey;
    privateKey = keyPair.privateKey;
  }, error => Promise.reject(`Error during key generation: ${error}`));
  //endregion Store new key in an interim variables

  //region Exporting public key into "subjectPublicKeyInfo" value of certificate
  sequence = sequence.then(() =>
    certificate.subjectPublicKeyInfo.importKey(publicKey)
  );
  //endregion Exporting public key into "subjectPublicKeyInfo" value of certificate

  sequence = sequence.then(
    () => crypto.digest({ name: "SHA-1" }, certificate.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHex),
    error => Promise.reject(`Error during importing public key: ${error}`)
  );

  //region Fill in cert data
  sequence = sequence.then(subjKeyIdBuffer =>
  {

    //region Put a static values
    certificate.version = CERTIFIATE_Version_3;

    const serialNumberBuffer = new ArrayBuffer(20);
    const serialNumberView = new Uint8Array(serialNumberBuffer);
    pkijs.getRandomValues(serialNumberView)
    // noinspection JSUnresolvedFunction
    certificate.serialNumber = new asn1js.Integer({ valueHex: serialNumberView });
    //endregion Put a static values

    //region Subject
    // For reference http://oidref.com/2.5.4.3
    if (certData.subject.commonName) {
      // noinspection JSUnresolvedFunction
      certificate.subject.typesAndValues.push(new pkijs.AttributeTypeAndValue({
        type: "2.5.4.3", // Common name
        value: new asn1js.PrintableString({ value: certData.subject.commonName })
      }));
    }

    if (certData.subject.country) {
      // noinspection JSUnresolvedFunction
      certificate.subject.typesAndValues.push(new pkijs.AttributeTypeAndValue({
        type: "2.5.4.6", // Country name
        value: new asn1js.PrintableString({ value: certData.subject.country })
      }));
    }

    if (certData.subject.locality) {
      // noinspection JSUnresolvedFunction
      certificate.subject.typesAndValues.push(new pkijs.AttributeTypeAndValue({
        type: "2.5.4.7", // Locality Name
        value: new asn1js.PrintableString({ value: certData.subject.locality })
      }));
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 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
    }

    if (certData.subject.state) {
      // noinspection JSUnresolvedFunction
      certificate.subject.typesAndValues.push(new pkijs.AttributeTypeAndValue({
        type: "2.5.4.8", // State or Province name
        value: new asn1js.PrintableString({ value: certData.subject.state })
      }));
    }

    if (certData.subject.organization) {
      // noinspection JSUnresolvedFunction
      certificate.subject.typesAndValues.push(new pkijs.AttributeTypeAndValue({
        type: "2.5.4.10", // Organization name
        value: new asn1js.PrintableString({ value: certData.subject.organization })
      }));
    }

    if (certData.subject.organizationUnit) {
      // noinspection JSUnresolvedFunction
      certificate.subject.typesAndValues.push(new pkijs.AttributeTypeAndValue({
        type: "2.5.4.11", // Organization unit name
        value: new asn1js.PrintableString({ value: certData.subject.organizationUnit })
      }));
    }

    if (certData.subject.email) {
      // noinspection JSUnresolvedFunction
      certificate.subject.typesAndValues.push(new pkijs.AttributeTypeAndValue({
        type: OID_PKCS9_EmailAddress, // Email, deprecated but still widely used
        value: new asn1js.IA5String({ value: certData.subject.email })
      }));
    }
    //endregion Subject


    //region Issuer
    if (issuerData && issuerData.certificate) {
      certificate.issuer = issuerData.certificate.subject;
    } else {
      certificate.issuer = certificate.subject;
    }
    //endregion Issuer

    //region Validity
    if (!certData.validity) {
      certData.validity = {}
    }

    if (certData.validity.notBefore) {
      certificate.notBefore.value = certData.validity.notBefore; //date
    } else {
      const tmp = new Date();
      certificate.notBefore.value = new Date(tmp.getFullYear(), tmp.getMonth(), tmp.getDate(), 0, 0, 0);
    }

    if (certData.validity.notAfter) {
      certificate.notAfter.value = certData.validity.notAfter; //date
    } else {
      const tmp = certificate.notBefore.value;
      const validYears = certData.validity.validYears || 1;
      certificate.notAfter.value = new Date(tmp.getFullYear() + validYears, tmp.getMonth(), tmp.getDate(), 23, 59, 59);
    }
    //endregion Validity

    //region Extensions
    certificate.extensions = []; // Extensions are not a part of certificate by default, it's an optional array

    //region "BasicConstraints" extension
    const basicConstr = new pkijs.BasicConstraints({
      cA: !!certData.isCA,
      //pathLenConstraint: 0 //TODO add logic for leaf CA
    });

    certificate.extensions.push(new pkijs.Extension({
      extnID: "2.5.29.19",
      critical: true,
      extnValue: basicConstr.toSchema().toBER(false),
      parsedValue: basicConstr // Parsed value for well-known extensions
    }));
    //endregion "BasicConstraints" extension

    //region "KeyUsage" extension
    const keyUsageBuffer = new ArrayBuffer(1);
    const keyUsageBitView = new Uint8Array(keyUsageBuffer);

    keyUsageBitView[0] = !!certData.isCA ? KEY_USAGE_CertificateAuthority : KEY_USAGE_LeafCertificate;

    // noinspection JSUnresolvedFunction
    const keyUsage = new asn1js.BitString({ valueHex: keyUsageBuffer });

    certificate.extensions.push(new pkijs.Extension({
      extnID: "2.5.29.15",
      critical: true,
      extnValue: keyUsage.toBER(false),
      parsedValue: keyUsage // Parsed value for well-known extensions
    }));
    //endregion "KeyUsage" extension

    //region "ExtKeyUsage" extension
    if (!certData.isCA && certData.subject.email) {
      const extKeyUsage = new pkijs.ExtKeyUsage({
        keyPurposes: [
          OID_ID_PKIX_EmailProtection
        ]
      });

      certificate.extensions.push(new pkijs.Extension({
        extnID: "2.5.29.37",
        critical: false,
        extnValue: extKeyUsage.toSchema().toBER(false),
        parsedValue: extKeyUsage // Parsed value for well-known extensions
      }));
    }
    //endregion "ExtKeyUsage" extension

    //region "SubjAltName" extension
    if (certData.subject.email || certData.subject.url) {

      const names = [];

      if (certData.subject.email) {
        names.push(new pkijs.GeneralName({
          type: 1, // rfc822Name
          value: certData.subject.email
        }));
      }

      if (certData.subject.url) {
        names.push(new pkijs.GeneralName({
          type: 2, // dNSName
          value: certData.subject.url
        }));
      }

      const subjAltNames = new pkijs.GeneralNames({
        names: names
      });

      certificate.extensions.push(new pkijs.Extension({
        extnID: "2.5.29.17",
        critical: false,
        extnValue: subjAltNames.toSchema().toBER(false),
        parsedValue: subjAltNames // Parsed value for well-known extensions
      }));
    }
    //endregion "SubjAltName" extension


    //region "SubjectKeyIdentifier" extension
    const subjKeyId = new asn1js.OctetString({ valueHex: subjKeyIdBuffer });

    certificate.extensions.push(new pkijs.Extension({
      extnID: "2.5.29.14",
      critical: false,
      extnValue: subjKeyId.toBER(false),
      parsedValue: subjKeyId // Parsed value for well-known extensions
    }));
    //endregion "SubjectKeyIdentifier" extension

    /* COULD NOT GET IT WORKING
        //region "AuthorityKeyIdentifier" extension
        if (issuerData && issuerData.certificate) {

          let issuerSubjKeyExt = null;

          let extLength = issuerData.certificate.extensions.length;
          for (var i = 0; i < extLength; i++) {
            let ext = issuerData.certificate.extensions[i];
            if (ext.extnID == "2.5.29.14") {
              issuerSubjKeyExt = ext;
              break;
            }
          }

          if (issuerSubjKeyExt) {

            const asn1 = asn1js.fromBER(issuerSubjKeyExt.extnValue);

            const authKeyIdentifier = new AuthorityKeyIdentifier({
              keyIdentifier: new asn1js.OctetString({
                //isHexOnly: true,
                //valueHex: issuerSubjKeyExt.parsedValue.valueBlock.valueHex
                value: new asn1js.OctetString({ valueHex: subjKeyIdBuffer })
              })
            });
            // const authKeyIdentifier = new AuthorityKeyIdentifier({
            // 	//keyIdentifier: new asn1js.OctetString({ valueHex: subjKeyIdBuffer })

            // });

            certificate.extensions.push(new Extension({
              extnID: "2.5.29.35",
              critical: false,
              extnValue: authKeyIdentifier.toSchema().toBER(false),
              parsedValue: authKeyIdentifier // Parsed value for well-known extensions
            }));
          }
        }
        //endregion "AuthorityKeyIdentifier" extension
    */
    //endregion Extensions
  });
  //region Fill in cert data


  //region Signing final certificate
  sequence = sequence.then(() => {
      let signerKey = (issuerData && issuerData.privateKey) ? issuerData.privateKey : privateKey;
      //console.log(signerKey)
      return certificate.sign(signerKey, (certData.algorithms && certData.algorithms.hashAlg) ? certData.algorithms.hashAlg : defaultAlgorithms.hashAlg)
    },
    error => Promise.reject(`Error during exporting public key: ${error}`));
  //endregion

  //region Encode and store certificate
  sequence = sequence.then(() =>
  {
    //console.log(certificate)
    certificateBuffer = certificate.toSchema(true).toBER(false);
  }, error => Promise.reject(`Error during signing: ${error}`));
  //endregion

  //region Exporting public key
  sequence = sequence.then(() =>
    crypto.exportKey("spki", publicKey)
  );
  //endregion

  //region Store exported public key on Web page
  sequence = sequence.then(result =>
  {
    publicKeyBuffer = result;
  }, error => Promise.reject(`Error during exporting of public key: ${error}`));
  //endregion

  //region Exporting private key
  sequence = sequence.then(() =>
    crypto.exportKey("pkcs8", privateKey)
  );
  //endregion

  //region Store exported key on Web page
  sequence = sequence.then(result =>
  {
    privateKeyBuffer = result;
  }, error => Promise.reject(`Error during exporting of private key: ${error}`));
  //endregion

  return sequence.then(() => {

    const result = {
      certificate: certificate,
      certificatePEM: encodePEM(certificateBuffer, "CERTIFICATE"),
      publicKey: publicKey,
      publicKeyPEM: encodePEM(publicKeyBuffer, "PUBLIC KEY"),
      privateKey: privateKey,
      privateKeyPEM: encodePEM(privateKeyBuffer, "PRIVATE KEY")
    }
    return result;
  });
}

function formatPEM(pemString) {
  const lineWidth = 64;
  let resultString = "";
  let start = 0;
  let piece = "";
  while ( (piece = pemString.substring(start, start + lineWidth)).length > 0 ) {
    start += lineWidth;
    resultString += piece + '\r\n'
  }
  return resultString;
}

function encodePEM(buffer, label) {
  const bufferString = String.fromCharCode.apply(null, new Uint8Array(buffer));

  const header = `-----BEGIN ${label}-----\r\n`;
  const base64formatted = formatPEM(window.btoa(bufferString));
  const footer = `-----END ${label}-----\r\n`;
  const resultString = header + base64formatted + footer;

  return resultString;
}

function decodePEM(pemString) {
  const pemStripped = pemString.replace(/(-----(BEGIN|END) [a-zA-Z ]*-----|\r|\n)/g, '');
  const pemDecoded = window.atob(pemStripped);
  const buffer = pvutils.stringToArrayBuffer(pemDecoded);
  return buffer;
}

//*********************************************************************************
function parseCertificate(certificatePEM) {
  const certificateBuffer = decodePEM(certificatePEM);
  const asn1 = asn1js.fromBER(certificateBuffer);
  const certificate = new pkijs.Certificate({ schema: asn1.result });
  return certificate;
}

//*********************************************************************************
function parsePublicKey(publicKeyPEM) {
  const publicKeyBuffer = decodePEM(publicKeyPEM);
  const crypto = pkijs.getCrypto();
  const publicKeyPromise = crypto.importKey(
    "spki",
    publicKeyBuffer,
    {   //these are the algorithm options
      name: "RSASSA-PKCS1-v1_5",
      hash: {name: "SHA-256"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
    },
    true,
    ["verify"]
  );
  return publicKeyPromise;
}

//*********************************************************************************
function encryptMessage(message, password, label) {
  const buffer = pvutils.stringToArrayBuffer(message);
  const secret = pvutils.stringToArrayBuffer(password);

  const enveloped = new pkijs.EnvelopedData();
  enveloped.addRecipientByPreDefinedData(secret, {}, AES_encryptionVariant_Password);
  return enveloped.encrypt(encryptionAlgorithm, buffer).
  then(
    () => {
      const content = new pkijs.ContentInfo();
      content.contentType = OID_PKCS7_EnvelopedData;
      content.content = enveloped.toSchema();
      const ber = content.toSchema().toBER(false);
      return encodePEM(ber, label)
    },
    error => Promise.reject(`encryption error: ${error}`)
  )
}

//*********************************************************************************
function decryptMessage(message, password) {
  const secret = pvutils.stringToArrayBuffer(password);
  const buffer = decodePEM(message);

  const asn1 = asn1js.fromBER(buffer);
  const content = new pkijs.ContentInfo({schema: asn1.result});
  const enveloped = new pkijs.EnvelopedData({schema: content.content});
  return enveloped.decrypt(0, {preDefinedData: secret}).then(result => {
    return pvutils.arrayBufferToString(result);
  }).catch(() => {
    throw("Wrong pincode")
  })
}

//*********************************************************************************
function parsePrivateKey(privateKeyPEM) {
  const privateKeyBuffer = decodePEM(privateKeyPEM);
  const crypto = pkijs.getCrypto();
  const privateKeyPromise = crypto.importKey(
    "pkcs8",
    privateKeyBuffer,
    {   //these are the algorithm options
      name: "RSASSA-PKCS1-v1_5",
      hash: {name: "SHA-256"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
    },
    true,
    ["sign"]
  );
  return privateKeyPromise;
}


function createPassportCertificate(commonNameArg) {
  const certData = {
    algorithms: {
      hashAlg: "SHA-256",
      signAlg: "RSASSA-PKCS1-v1_5",
      keyLength: 2048
    },
    //keyPair: generateKeys(), //optional , if provided must be object or promise that resolves to object {publicKey, prvateKey}. If it is not provided, new ones are generated automatically
    subject: {
      commonName: commonNameArg + "-userdevice", //optional for leaf, recommended for CA
      country: "CH", //optional for leaf, recommended for CA
      locality: "Zug", //optional for leaf, recommended for CA
      state: "Zug", //optional for leaf, recommended for CA
      organization: "Vereign AG", //optional for leaf, recommended for CA
      organizationUnit:"Business Dep", //optional for leaf, recommended for CA
      //email: "damyan.mitev@vereign.com", // added to DN and Subject Alternative Name extension. Optional for CA. Mandatory for leaf certificate, used for email protection
      //url: "www.vereign.com" // optional url, recommended for CA, added to Subject Alternative Name extension
    },
    validity: {
      //notBefore: new Date() // optional, defaults to today at 00:00:00
      //notAfter: new Date()  // optional, defaults to notBefore + validYears at 23:59:59
      validYears: 5 //optional, defaults to 1
    },
    isCA: true // optional flag denoting if this is CA certificate or leaf certificate, defaults to false
  }

  return createCertificate(certData, null)
}

function createOneTimePassportCertificate(commonNameArg, emailArg, privateKeyIssuerArg, certicateIssuerArg) {
  var certData = null
  if(emailArg != null && emailArg != "") {
    certData = {
      algorithms: {
        hashAlg: "SHA-256",
        signAlg: "RSASSA-PKCS1-v1_5",
        keyLength: 2048
      },
      //keyPair: generateKeys(), //optional , if provided must be object or promise that resolves to object {publicKey, prvateKey}. If it is not provided, new ones are generated automatically
      subject: {
        commonName: commonNameArg + "-onetime", //optional for leaf, recommended for CA
        country: "CH", //optional for leaf, recommended for CA
        locality: "Zug", //optional for leaf, recommended for CA
        state: "Zug", //optional for leaf, recommended for CA
        organization: "Vereign AG", //optional for leaf, recommended for CA
        organizationUnit:"Business Dep", //optional for leaf, recommended for CA
        email: emailArg, // added to DN and Subject Alternative Name extension. Optional for CA. Mandatory for leaf certificate, used for email protection
        //url: "www.vereign.com" // optional url, recommended for CA, added to Subject Alternative Name extension
      },
      validity: {
        //notBefore: new Date() // optional, defaults to today at 00:00:00
        //notAfter: new Date()  // optional, defaults to notBefore + validYears at 23:59:59
        validYears: 5 //optional, defaults to 1
      },
      isCA: false // optional flag denoting if this is CA certificate or leaf certificate, defaults to false
    }
  } else {
    certData = {
      algorithms: {
        hashAlg: "SHA-256",
        signAlg: "RSASSA-PKCS1-v1_5",
        keyLength: 2048
      },
      //keyPair: generateKeys(), //optional , if provided must be object or promise that resolves to object {publicKey, prvateKey}. If it is not provided, new ones are generated automatically
      subject: {
        commonName: commonNameArg + "-onetime", //optional for leaf, recommended for CA
        country: "CH", //optional for leaf, recommended for CA
        locality: "Zug", //optional for leaf, recommended for CA
        state: "Zug", //optional for leaf, recommended for CA
        organization: "Vereign AG", //optional for leaf, recommended for CA
        organizationUnit:"Business Dep", //optional for leaf, recommended for CA
        //email: emailArg, // added to DN and Subject Alternative Name extension. Optional for CA. Mandatory for leaf certificate, used for email protection
        //url: "www.vereign.com" // optional url, recommended for CA, added to Subject Alternative Name extension
      },
      validity: {
        //notBefore: new Date() // optional, defaults to today at 00:00:00
        //notAfter: new Date()  // optional, defaults to notBefore + validYears at 23:59:59
        validYears: 5 //optional, defaults to 1
      },
      isCA: false // optional flag denoting if this is CA certificate or leaf certificate, defaults to false
    }
  }

  return parsePrivateKey(privateKeyIssuerArg).then(privateKeyDecoded => {
    const issuerData = {
      certificate: parseCertificate(certicateIssuerArg),// vereignCACertPEM),
      privateKey: privateKeyDecoded
    }
    return createCertificate(certData, issuerData);
    //console.log(vereignIntermediateKey)
  });
}

function download(filename, contentType, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:' + contentType + ';charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

function arrayBufferToBase64Formatted(buffer) {
  const bufferString = String.fromCharCode.apply(null, new Uint8Array(buffer));
  const base64formatted = formatPEM(window.btoa(bufferString));
  return base64formatted;
}

function arrayBufferToBase64(buffer) {
  const bufferString = String.fromCharCode.apply(null, new Uint8Array(buffer));
  const base64 = window.btoa(bufferString);
  return base64;
}

const newline = /\r\n|\r|\n/g;

function capitalizeFirstLetter(string) {
  if(string == "id") {
    return "ID"
  }

  if(string == "mime") {
    return "MIME";
  }

  return string.charAt(0).toUpperCase() + string.slice(1);
}

function capitalizeHeader(string) {
  result = ""
  tokens = string.split("-")
  for(var i = 0; i < tokens.length; i++) {
    result += capitalizeFirstLetter(tokens[i])
    if(i != tokens.length - 1) {
      result += "-"
    }
  }

  return result
}

function signEmail(mime, signingCert, certificateChain, privateKey) {
  signingCertObj = parseCertificate(signingCert)
  certificateChainObj = []
  certificateChainObj[0] = parseCertificate(signingCert)
  for(var i = 0; i < certificateChain.length; i++) {
    certificateChainObj[i + 1] = parseCertificate(certificateChain[i])
  }
  //console.log(certificateChainObj)

  return parsePrivateKey(privateKey).then(privateKeyDecoded => {

    return signEmailObjects(mime, signingCertObj, certificateChainObj, privateKeyDecoded);
    //console.log(vereignIntermediateKey)
  });
}

function signEmailObjects(mime, signingCert, certificateChain, privateKey) {

  //region Get a "crypto" extension
  const crypto = pkijs.getCrypto();
  if (typeof crypto === "undefined") {
    return Promise.reject("No WebCrypto extension found");
  }
  //endregion Get a "crypto" extension

  let template =
    `{{headers}}Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg=sha-256; boundary="{{boundary}}"
MIME-Version: 1.0

This is a cryptographically signed message in MIME format.

--{{boundary}}
{{mime}}
--{{boundary}}
Content-Type: application/pkcs7-signature; name="smime.p7s"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="smime.p7s"
Content-Description: S/MIME Cryptographic Signature

{{signature}}
--{{boundary}}--

Vereign - Authentic Communication
`.replace(newline, '\r\n');

  const detachedSignature = true;
  const addExt = true;
  const hashAlg = "SHA-256";
  let cmsSignedSimpl;

  var mimeHeadersTitles = [
    "Content-Type",
    "Content-Transfer-Encoding",
    "Content-ID",
    "Content-Description",
    "Content-Disposition",
    "Content-Language",
    "Content-Location"
  ]

  mime = mime.replace(newline, '\r\n');

  let newHeaderLines = ""
  let headersEnd = mime.indexOf('\r\n\r\n') //the first empty line

  if (headersEnd < 0 && mime.startsWith('\r\n')) {

    mime = mime.substring(2) //should not happen

  } else
  if (headersEnd >= 0) {

    let mimeHeaders = {}
    let mimeBody = mime.substring(headersEnd + 4)

    let mimeHeadersStr = mime.substring(0, headersEnd)

    let headers = libmime.decodeHeaders(mimeHeadersStr)
    for (var i = 0; i < mimeHeadersTitles.length; i++) {
      let key = mimeHeadersTitles[i].toLowerCase()
      if(key in headers) {
        mimeHeaders[key] = headers[key]
        delete headers[key]
      }
    }

    for(let key in headers) {
      if(!(key === "" || key === "MIME-Version".toLowerCase())) { //we have MIME-Version in the template
        newHeaderLines += capitalizeHeader(key) + ": " + headers[key] + '\r\n';
      }
    }

    let newMimeHeaderLines = ""
    for(let key in mimeHeaders) {
      if(!(key === "")) {
        newMimeHeaderLines += capitalizeHeader(key) + ": " + mimeHeaders[key] + '\r\n';
      }
    }

    if (newMimeHeaderLines === "") {
      newMimeHeaderLines = 'Content-Type: text/plain\r\n' //should not happen
    }

    mime = newMimeHeaderLines + '\r\n' + mimeBody
  }

  let dataBuffer = pvutils.stringToArrayBuffer(mime);

  let sequence = Promise.resolve();

  //region Check if user wants us to include signed extensions
  if(addExt)
  {
    //region Create a message digest
    sequence = sequence.then(
      () => crypto.digest({ name: hashAlg }, new Uint8Array(dataBuffer))
    );
    //endregion

    //region Combine all signed extensions
    sequence = sequence.then(
      messageHash =>
      {
        const signedAttr = [];
        /*
                1.2.840.113549.1.9.1 - e-mailAddress
                1.2.840.113549.1.9.2 - PKCS-9 unstructuredName
                1.2.840.113549.1.9.3 - contentType
                1.2.840.113549.1.9.4 - messageDigest
                1.2.840.113549.1.9.5 - Signing Time
                1.2.840.113549.1.9.6 - counterSignature
        */
        signedAttr.push(new pkijs.Attribute({
          type: OID_PKCS9_ContentType, //contentType
          values: [
            new asn1js.ObjectIdentifier({ value: OID_PKCS7_Data}) //data
          ]
          /*
                      1.2.840.113549.1.7.1 - data
                      1.2.840.113549.1.7.2 - signedData
                      1.2.840.113549.1.7.3 - envelopedData
                      1.2.840.113549.1.7.4 - signedAndEnvelopedData
                      1.2.840.113549.1.7.5 - digestedData
                      1.2.840.113549.1.7.6 - encryptedData
          */
        })); // contentType

        signedAttr.push(new pkijs.Attribute({
          type: OID_PKCS9_SigningTime, //Signing Time
          values: [
            new asn1js.UTCTime({ valueDate: new Date() })
          ]
        })); // signingTime

        signedAttr.push(new pkijs.Attribute({
          type: OID_PKCS9_MessageDigest, //messageDigest
          values: [
            new asn1js.OctetString({ valueHex: messageHash })
          ]
        })); // messageDigest

        return signedAttr;
      }
    );
    //endregion
  }
  //endregion

  //region Initialize CMS Signed Data structures and sign it
  sequence = sequence.then(
    signedAttr =>
    {
      cmsSignedSimpl = new pkijs.SignedData({
        version: 1,
        encapContentInfo: new pkijs.EncapsulatedContentInfo({
          eContentType: OID_PKCS7_Data // "data" content type
        }),
        signerInfos: [
          new pkijs.SignerInfo({
            version: 1,
            sid: new pkijs.IssuerAndSerialNumber({
              issuer: signingCert.issuer,
              serialNumber: signingCert.serialNumber
            })
          })
        ],
        certificates: certificateChain //array
      });

      if(addExt)
      {
        cmsSignedSimpl.signerInfos[0].signedAttrs = new pkijs.SignedAndUnsignedAttributes({
          type: 0,
          attributes: signedAttr
        });
      }

      if(detachedSignature === false)
      {
        const contentInfo = new pkijs.EncapsulatedContentInfo({
          eContent: new asn1js.OctetString({ valueHex: dataBuffer })
        });

        cmsSignedSimpl.encapContentInfo.eContent = contentInfo.eContent;

        return cmsSignedSimpl.sign(privateKey, 0, hashAlg);
      }

      return cmsSignedSimpl.sign(privateKey, 0, hashAlg, dataBuffer);
    }
  );
  //endregion

  //region Create final result
  sequence = sequence.then(
    (result) =>
    {
      const cmsSignedSchema = cmsSignedSimpl.toSchema(true);

      const cmsContentSimp = new pkijs.ContentInfo({
        contentType: OID_PKCS7_SignedData, //signedData
        content: cmsSignedSchema
      });

      const _cmsSignedSchema = cmsContentSimp.toSchema();

      //region Make length of some elements in "indefinite form"
      _cmsSignedSchema.lenBlock.isIndefiniteForm = true;

      const block1 = _cmsSignedSchema.valueBlock.value[1];
      block1.lenBlock.isIndefiniteForm = true;

      const block2 = block1.valueBlock.value[0];
      block2.lenBlock.isIndefiniteForm = true;

      if(detachedSignature === false)
      {
        const block3 = block2.valueBlock.value[2];
        block3.lenBlock.isIndefiniteForm = true;
        block3.valueBlock.value[1].lenBlock.isIndefiniteForm = true;
        block3.valueBlock.value[1].valueBlock.value[0].lenBlock.isIndefiniteForm = true;
      }
      //endregion

      const cmsSignedBuffer = _cmsSignedSchema.toBER(false);
      return cmsSignedBuffer;
    },
    error => Promise.reject(`Erorr during signing of CMS Signed Data: ${error}`)
  );
  //endregion

  sequence = sequence.then(
    (cmsSignedBuffer) =>
    {
      let signature = arrayBufferToBase64Formatted(cmsSignedBuffer);
      let boundary = makeBoundary()

      template = template.replace(/{{boundary}}/g, boundary)
      template = template.replace("{{signature}}", signature)
      template = template.replace("{{headers}}", newHeaderLines)
      template = template.replace("{{mime}}", mime)

      //template = template.replace(newline, '\r\n')
      return template
    }
  );

  return sequence;
}

function makeBoundary() {
  let len = 20 + Math.random() * 20
  return 'W0RyLiBEYW15YW4gTWl0ZXZd--' + makeid(len)
}

function makeid(len) {
  if (typeof len === 'undefined') {
    len = 10
  }
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < len; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

function CryptoData() {
}

CryptoData.prototype.set = function(obj) {
  for(var member in obj) {
    this[member] = JSON.parse(JSON.stringify(obj[member]))
  }
}

CryptoData.prototype.serialize = function() {
  return JSON.stringify(this)
}

CryptoData.prototype.deserialize = function(serialized) {
  var obj = JSON.parse(serialized)
  this.set(obj)
}

CryptoData.prototype.setPublicKey = function(publicKey) {
  this["publicKey"] = publicKey
}

CryptoData.prototype.getPublicKey = function() {
  return this["publicKey"]
}

CryptoData.prototype.setPrivateKey = function(privateKey) {
  this["privateKey"] = privateKey
}

CryptoData.prototype.getPrivateKey = function() {
  return this["privateKey"]
}

CryptoData.prototype.setx509Certificate = function(x509Certificate) {
  this["x509Certificate"] = x509Certificate
}

CryptoData.prototype.getx509Certificate = function() {
  return this["x509Certificate"]
}

CryptoData.prototype.setKeyUUID = function(keyUUID) {
  this["keyUUID"] = keyUUID
}

CryptoData.prototype.getKeyUUID = function() {
  return this["keyUUID"]
}

CryptoData.prototype.setChain = function(chain) {
  this["chain"] = chain
}

CryptoData.prototype.getChain = function() {
  return this["chain"]
}

function Identity() {
}

Identity.prototype.set = function(obj) {
  for(var member in obj) {
    this[member] = JSON.parse(JSON.stringify(obj[member]))
  }
}

Identity.prototype.serialize = function() {
  return JSON.stringify(this)
}

Identity.prototype.deserialize = function(serialized) {
  var obj = JSON.parse(serialized)
  this.set(obj)
}

Identity.prototype.setAuthentication = function(cryptoData) {
  this["authentication"] = cryptoData
}

Identity.prototype.getAuthentication = function() {
  return this["authentication"]
}

Identity.prototype.setPinCode = function(pinCode) {
  this["pinCode"] = pinCode
}

Identity.prototype.getPinCode = function() {
  return this["pinCode"]
}

Identity.prototype.setPassport = function(passportUUID, cryptoData) {
  if(this["passports"] === undefined || this["passports"] === null) {
    this["passports"] = {}
  }

  this["passports"][passportUUID] = cryptoData
}

Identity.prototype.getPassport = function(passportUUID) {
  if(this["passports"] === undefined || this["passports"] === null) {
    this["passports"] = {}
  }

  return this["passports"][passportUUID]
}

var identityColors = ["#994392", "#cb0767", "#e51d31", "#ec671b", "#fab610"]

function getNextColor() {
  var colorIndex = localStorage.getItem("colorIndex");
  if (colorIndex == null || colorIndex == "") {
    colorIndex = 0
  }

  var color = identityColors[colorIndex]

  colorIndex++;

  colorIndex = colorIndex % identityColors.length

  localStorage.setItem("colorIndex", colorIndex)

  return color
}

function setKeyForUUID(uuid, key) {
  var storedIdentityForUuid = localStorage.getItem("keyperuuid/" + uuid)
  if(storedIdentityForUuid != key && storedIdentityForUuid != null && storedIdentityForUuid != "") {
    destroyIdentityFromLocalStorage(storedIdentityForUuid)
  }

  localStorage.setItem("keyperuuid/" + uuid, key)
}

function getColorForIdentity(key) {
  var storedColor = localStorage.getItem("colors/" + key)

  if(storedColor == null || storedColor == "") {
    storedColor = getNextColor()
    console.log("Setting new color: " + storedColor)
    localStorage.setItem("colors/" + key, storedColor)
  }

  return storedColor
}

function setIdentityInLocalStorage(identityToStore, extendKey = true) {
  //console.log(getStack())
  var pinCode = identityToStore.pinCode;
  const serializedIdentity = JSON.stringify(identityToStore);
  const key = identityToStore.authentication.publicKey;

  if(pinCode == null || pinCode == "") {
    pinCode = getPincode(key)
  }

  if(pinCode == null || pinCode == "") {
    console.log("Can not set identity")
    return null;
  }

  return encryptMessage(serializedIdentity, pinCode, "identity").then((encryptedIdentity) => {
    var success = true
    if(extendKey === true) {
      success = extendPinCodeTtl(key, pinCode)
    }
    if (success == true) {
      localStorage.setItem(key, encryptedIdentity);
      let serializedIdentitiesList = localStorage.getItem("identities");
      let identities = JSON.parse(serializedIdentitiesList);
      identities[key] = true;

      localStorage.setItem("identities", JSON.stringify(identities))
    } else {
      console.log("Can not extend pincode ttl")
    }
  });
}

function getProfileData(identity) {
  return new Penpal.Promise(executeResultUpper => {
    executeRestfulFunction("private", viamApi,
      viamApi.identityGetIdentityProfileData).then(executeResult => {
      if(executeResult.code == "200") {
        console.log("In promise")
        console.log(executeResult)
        var listItem = {};

        console.log(identity)
        listItem.identityColor = getColorForIdentity(identity.authentication.publicKey)
        listItem.initials = executeResult.data.initials

        if(listItem.initials === null || listItem.initials === "") {
          listItem.initials = "JD";
        }
        console.log("Item")
        console.log(listItem)
        localStorage.setItem("profiles/" + identity.authentication.publicKey, JSON.stringify(listItem))
        executeResultUpper(listItem)
      } else {
        executeResultUpper({})
      }
    });
  });
}

function getIdentityFromLocalStorage(key, pinCode, extendTtl = true) {
  const encryptedIdentity = localStorage.getItem(key);
  if (encryptedIdentity == null) {
    console.log("No such identity for public key")
    return Promise.resolve(null)
  }
  return decryptMessage(encryptedIdentity, pinCode).then((serializedIdentity) => {
    var parsedIdentity = JSON.parse(serializedIdentity);
    parsedIdentity["pinCode"] = ""
    //console.log(parsedIdentity)
    if(extendTtl === true) {
      var success = extendPinCodeTtl(key, pinCode)
      if (success == true) {
        return parsedIdentity
      } else {
        console.log("Can not extend pincode ttl")
        return null
      }
    } else {
      return parsedIdentity
    }
  });

}

function listIdentitiesFromLocalStorage() {
  var serializedIdentitiesList = localStorage.getItem("identities")
  var identities = JSON.parse(serializedIdentitiesList)
  var identitiesResult = {}

  for(var key in identities) {
    var profile = JSON.parse(JSON.stringify(localStorage.getItem("profiles/" + key)))
    console.log("Getting profile")
    console.log(profile)
    if(profile != null && profile != "") {
      console.log("Setting profile for key: " + key)
      //console.log(profile)
      identitiesResult[key] = JSON.parse(profile)
      //console.log(identitiesResult)
    } else {
      console.log("Setting empty key for profile: " + key)
      identitiesResult[key] = {}
      //console.log(identitiesResult)
    }
  }

  console.log("In list identities from local storage")
  console.log(identitiesResult)
  return identitiesResult
}

function getStack() {
  try {
    throw new Error();
  } catch(e) {
    return e.stack;
  }
}

function extendPinCodeTtl(key, pinCode) {
  //console.log("Extending pincode ttl")
  //console.log(getStack())
  //console.log("Extending pincode ttl for key: " + key)
  //console.log(pinCode)
  if(pinCode == null || pinCode == "") {
    var now = new Date();
    var nowMillis = now.getTime();
    var ttl = window.sessionStorage.getItem("pincodettls/" + key);
    if (ttl == null || ttl == "" || nowMillis >= parseInt(ttl)) {
      clearPinCodeTtl(key)
      return false
    } else {
      var ttl = now.getTime() + 10 * 60 * 1000;
      window.sessionStorage.setItem("pincodettls/" + key, ttl);
    }
  } else {
    var now = new Date();
    var ttl = now.getTime() + 10 * 60 * 1000;
    window.sessionStorage.setItem("pincodettls/" + key, ttl);
    window.sessionStorage.setItem("pincodes/" + key, pinCode);
  }

  return true;
}

function clearPinCodeTtl(key) {
  //console.log("Clearing ttl for key: " + key)
  window.sessionStorage.removeItem("pincodettls/" + key)
  window.sessionStorage.removeItem("pincodes/" + key)
}

function getPincode(key) {
  var now = new Date();
  var nowMillis = now.getTime();
  var ttl = window.sessionStorage.getItem("pincodettls/" + key);
  if (ttl == null || ttl == "") {
    return null
  } else {
    if(nowMillis >= parseInt(ttl)) {
      clearPinCodeTtl(key)
      return null
    } else {
      return window.sessionStorage.getItem("pincodes/" + key);
    }
  }
}

function createEvent(actionId, type, payloads) {
  return {
    "actionID": actionId,
    "type": type,
    "stamp": new Date().getTime(),
    "payloads" : payloads
  }
}

function destroyIdentityFromLocalStorage(key) {
  localStorage.removeItem(key)
  localStorage.removeItem("profiles/" + key)
  localStorage.removeItem("colors/" + key)

  var serializedIdentitiesList = localStorage.getItem("identities")

  var identities = JSON.parse(serializedIdentitiesList)

  identities[key] = null

  delete identities[key]

  localStorage.setItem("identities", JSON.stringify(identities))
}

window.loadedIdentities = {}
window.viamApi = new ViamAPI();
window.viamAnonymousApi = new ViamAPI();
window.currentlyAuthenticatedIdentity = null
window.currentlyLoadedIdentity = null
window.lastTimeGetProfile = 0

function executeRestfulFunction(type, that, fn, ...args) {
  if(type == "private") {
    return new Penpal.Promise(executeResult => {
      fn.apply(that, args).then((response) => {
        if (response.data.code == "400" && response.data.status == "Bad session") {
          console.log("Trying to login again")
          if(currentlyAuthenticatedIdentity != "" && currentlyAuthenticatedIdentity != null) {
            viamApi.identityLogin("previousaddeddevice").then((response1) => {
              if (response1.data.code == "200") {
                //console.log(response.data.data)
                var uuid = response1.data.data["Uuid"]
                var token = response1.data.data["Session"]
                //console.log(uuid + " " + token)
                viamApi.setSessionData(uuid, token)
                localStorage.setItem("uuid", uuid)
                localStorage.setItem("token", token)
                localStorage.setItem("authenticatedIdentity", currentlyAuthenticatedIdentity.authentication.publicKey)
                currentlyAuthenticatedIdentity = loadedIdentities[currentlyAuthenticatedIdentity.authentication.publicKey]
                setKeyForUUID(uuid, currentlyAuthenticatedIdentity.authentication.publicKey)
                lastTimeGetProfile = 0;
                fn.apply(null, args).then((response2) => {
                  executeResult(response2.data)
                });
              } else {
                executeResult(response1.data)
              }
            });
          } else {
            if(currentlyLoadedIdentity != "" && currentlyLoadedIdentity != null) {
              viamApi.identityLogin("previousaddeddevice").then((response1) => {
                if (response1.data.code == "200") {
                  //console.log(response.data.data)
                  var uuid = response1.data.data["Uuid"]
                  var token = response1.data.data["Session"]
                  //console.log(uuid + " " + token)
                  viamApi.setSessionData(uuid, token)
                  localStorage.setItem("uuid", uuid)
                  localStorage.setItem("token", token)
                  localStorage.setItem("authenticatedIdentity", currentlyLoadedIdentity.authentication.publicKey)
                  currentlyAuthenticatedIdentity = loadedIdentities[currentlyLoadedIdentity.authentication.publicKey]
                  setKeyForUUID(uuid, currentlyLoadedIdentity.authentication.publicKey)
                  lastTimeGetProfile = 0;
                  fn.apply(null, args).then((response2) => {
                    executeResult(response2.data)
                  });
                } else {
                  executeResult(response1.data)
                }
              });
            } else {
              executeResult(response.data)
            }
          }
        } else {
          executeResult(response.data)
        }
      });
    });
  } else {
    return new Penpal.Promise(executeResult => {
      fn.apply(that, args).then((response) => {
        executeResult(response.data)
      });
    });
  }
}

function loadIdentityInternal(identityKey, pinCode) {
  return new Penpal.Promise(result => {
    console.log("Loading identity with pincode: " + pinCode)
    getIdentityFromLocalStorage(identityKey, pinCode).then((loadedIdentity) => {
      if (loadedIdentity == null) {
        result({
          "data": "",
          "code": "400",
          "status": "Can not load identity"
        })
      }
      var copiedIdentity = JSON.parse(JSON.stringify(loadedIdentity))
      loadedIdentities[identityKey] = loadedIdentity

      if (identityKey === localStorage.getItem("authenticatedIdentity")) {
        currentlyAuthenticatedIdentity = copiedIdentity
        viamApi.setIdentity(identityKey)
        var uuid = localStorage.getItem("uuid")
        var token = localStorage.getItem("token")
        //console.log("Loading " + uuid + " " + token)
        viamApi.setSessionData(uuid, token)
      }

      //console.log("Set loaded identity in load identity")
      currentlyLoadedIdentity = copiedIdentity
      viamAnonymousApi.setIdentity(currentlyLoadedIdentity.authentication.publicKey)

      copiedIdentity.pinCode = ""
      copiedIdentity.authentication.privateKey = ""

      result({
        "data": copiedIdentity,
        "code": "200",
        "status": "Identity loaded"
      })
    }).catch((e) => {
      result({
        "data": "",
        "code": "400",
        "status": "Can not load entity:" + e
      })
    })
  });
}

function changeIdentityPinCodeInternal(key, oldPinCode, newPinCode) {

  return new Penpal.Promise(result => {
    getIdentityFromLocalStorage(key, oldPinCode, false).then((identity) => {

      identity.pinCode = newPinCode;

      console.log("Storing identity with pincode: " + identity.pinCode)
      setIdentityInLocalStorage(identity).then(() => {
      }).catch((e) => {
        result({
          "data": "",
          "code": "400",
          "status": "Cannot store identity " + e
        });
      });
    });
  });
}

function getCertificateForPassport(passportUUID, internal) {

  return new Penpal.Promise(certificateResult => {
    if (currentlyAuthenticatedIdentity === null) {
      return {"data" : "",
        "code" : "400",
        "status" : "Identity not authenticated"
      }
    }

    var passportIdentity = new Identity()
    passportIdentity.set(currentlyAuthenticatedIdentity)
    //console.log("Getting: " + passportUUID)
    //console.log(identity)
    var passport = passportIdentity.getPassport(passportUUID)
    if(passport === undefined || passport === null) {
      createPassportCertificate(passportUUID).then(function(keys){
        var cryptoData = new CryptoData()
        //console.log(keys)
        cryptoData.setPublicKey(keys["publicKeyPEM"])
        cryptoData.setPrivateKey(keys["privateKeyPEM"])
        var certificate = keys["certificatePEM"]
        //download("passportCertificateBeforeSigning.crt", "text/plain", certificate)
        //console.log(certificate)
        //cryptoData.setx509Certificate(keys["certificate"])
        executeRestfulFunction("private", viamApi, viamApi.signSignCertificate, btoa(certificate), passportUUID).then(executeResult => {
          if(executeResult.code == "200") {
            var signedCertificate = atob(executeResult.data["SignedCertificate"])
            //download("passportCertificateAfterSigning.crt", "text/plain", signedCertificate)
            var keyUUID = executeResult.data["CertificateUUID"]
            var encodedChain = executeResult.data["Chain"]
            //download("rootCertificate.crt", "text/plain", atob(encodedChain[0]))

            var chain = []

            for(var i = 0; i < encodedChain.length; i++) {
              chain.push(atob(encodedChain[i]))
            }

            //console.log("Chain from server")
            //console.log(chain)
            //console.log(signedCertificate)
            //console.log(certificate)
            //console.log(keyUUID)
            cryptoData.setx509Certificate(signedCertificate)
            cryptoData.setKeyUUID(keyUUID)
            cryptoData.setChain(chain)

            passportIdentity.setPassport(passportUUID, cryptoData)

            getProfileData(passportIdentity).then(executeResult1 => {
              console.log("Profile updated in set identity")
              setIdentityInLocalStorage(passportIdentity).then(() => {
                currentlyAuthenticatedIdentity = passportIdentity
                lastTimeGetProfile = 0;
                //console.log("Set loaded identity in passport");
                currentlyLoadedIdentity = passportIdentity
                var copyOfCryptoData = JSON.parse(JSON.stringify(cryptoData))

                if (internal === false) {
                  copyOfCryptoData["privateKey"] = ""
                }

                certificateResult({
                  "data": copyOfCryptoData,
                  "code": "200",
                  "status": "Certificate got"
                });
              }).catch((e) => {
                certificateResult({
                  "data": "",
                  "code": "400",
                  "status": "Can not store certificate " + e
                });
              });
            });
          } else {
            certificateResult(executeResult)
          }
        });
      });
    } else {
      //console.log(passport)
      var copyOfCryptoData = JSON.parse(JSON.stringify(passport))

      if(internal === false) {
        copyOfCryptoData["privateKey"] = ""
      }

      certificateResult({"data" : copyOfCryptoData,
        "code" : "200",
        "status" : "Certificate got"
      });
    }
  });
}

const connection = Penpal.connectToParent({
  // Methods child is exposing to parent
  methods: {
    createIdentity(pinCode) {
      return new Penpal.Promise(result => {
        createPassportCertificate(makeid()).then(function(keys){
          var newIdentity = new Identity()
          var cryptoData = new CryptoData()
          cryptoData.setPublicKey(keys["publicKeyPEM"])
          cryptoData.setPrivateKey(keys["privateKeyPEM"])
          cryptoData.setx509Certificate(keys["certificatePEM"])
          newIdentity.setAuthentication(cryptoData)
          newIdentity.setPinCode(pinCode)

          //console.log("Set loaded identity in createIdentity")
          currentlyLoadedIdentity = newIdentity
          loadedIdentities[newIdentity.authentication.publicKey] = newIdentity
          extendPinCodeTtl(newIdentity.authentication.publicKey, pinCode)


          viamAnonymousApi.setIdentity(newIdentity.authentication.publicKey)

          result({"data" : newIdentity,
            "code" : "200",
            "status" : "Identity created"
          })
        });
      })
    },
    listIdentities() {
      return new Penpal.Promise(result => {
        var identities = listIdentitiesFromLocalStorage()
        console.log("Before return of identities")
        console.log(identities)
        result({"data" : identities,
          "code" : "200",
          "status" : "Identities listed"
        })
      });
    },
    loadIdentity(identityKey, pinCode) {
      return loadIdentityInternal(identityKey, pinCode)
    },
    changeIdentityPinCode(key, oldPinCode, newPinCode) {
      return changeIdentityPinCodeInternal(key, oldPinCode, newPinCode)
    },
    getIdentityProfile(identityKey) {
      return new Penpal.Promise(result => {
        serializedProfile = localStorage.getItem("profiles/" + identityKey)
        if(serializedProfile == null || serializedProfile == "") {
          result({"data" : "",
            "code" : "400",
            "status" : "Profile is empty"
          });
        } else {
          result({"data" : JSON.parse(serializedProfile),
            "code" : "200",
            "status" : "Identities cleared"
          })
        }
      });
    },
    clearIdentities() {
      return new Penpal.Promise(result => {
        var identitiesTemp = listIdentitiesFromLocalStorage()
        //console.log(identitiesTemp.length)
        for(var i in identitiesTemp) {
          destroyIdentityFromLocalStorage(i)
        }
        result({"data" : "",
          "code" : "200",
          "status" : "Identities cleared"
        })
      });
    },
    register(registerIdentity, email, name, surname, family, phoneNumber) {
      return new Penpal.Promise(result => {
        viamApi.setIdentity(registerIdentity.authentication.publicKey)

        executeRestfulFunction("public", viamApi, viamApi.identityRegister, email, name,surname, family, phoneNumber).then(executeResult => {
          console.log("Profile updated in set identity")

          let sequence = Promise.resolve()
          if (executeResult.code === "200") {
            sequence = sequence.then(() => {
                setIdentityInLocalStorage(registerIdentity)
              }
            )
          }
          sequence.then(() => {
            result(executeResult);
          }).catch((e) => {
            result({
              "data": "",
              "code": "400",
              "status": "Can not store identity: " + e
            })
          })
        });
      });
    },
    resendConfirmationCode(identity, identificatorArg) {
      return new Penpal.Promise(result => {
        viamApi.setIdentity(identity.authentication.publicKey)

        executeRestfulFunction("public", viamApi, viamApi.identityResendConfirmationCode,identificatorArg).then(executeResult => {
          result(executeResult);
        });
      });
    },
    login(loginIdentity, mode, code, actionID) {
      return new Penpal.Promise(result => {
        if (loadedIdentities[loginIdentity.authentication.publicKey] === null) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not loaded"
          })
        }

        //console.log("After loaded check")

        viamApi.setIdentity(loginIdentity.authentication.publicKey)

        executeRestfulFunction("public", viamApi, viamApi.identityLogin, mode, code, actionID).then(executeResult => {
          // console.log(executeResult)
          //console.log(mode)
          switch(mode) {
            case "sms" : {
              if (executeResult.code === "200") {
                //console.log("In if")
                var uuid = executeResult.data["Uuid"]
                var token = executeResult.data["Session"]
                viamApi.setSessionData(uuid, token)
                localStorage.setItem("uuid", uuid)
                localStorage.setItem("token", token)
                localStorage.setItem("authenticatedIdentity",
                  loginIdentity.authentication.publicKey)
                setKeyForUUID(uuid, loginIdentity.authentication.publicKey)
                currentlyAuthenticatedIdentity = loadedIdentities[loginIdentity.authentication.publicKey]
                lastTimeGetProfile = 0;
                delete executeResult.data["Uuid"]
                delete executeResult.data["Session"]
                getProfileData(loginIdentity).then(executeResult1 => {
                  result(executeResult);
                });
              } else {
                //console.log("In else")
                result(executeResult);
              }

              break;
            }

            case "previousaddeddevice" : {
              if (executeResult.code === "200") {
                //console.log(response.data.data)
                var uuid = executeResult.data["Uuid"]
                var token = executeResult.data["Session"]
                //console.log(uuid + " " + token)
                viamApi.setSessionData(uuid, token)
                localStorage.setItem("uuid", uuid)
                localStorage.setItem("token", token)
                localStorage.setItem("authenticatedIdentity",
                  loginIdentity.authentication.publicKey)
                setKeyForUUID(uuid, loginIdentity.authentication.publicKey)
                currentlyAuthenticatedIdentity = loadedIdentities[loginIdentity.authentication.publicKey]
                lastTimeGetProfile = 0;
                delete executeResult.data["Uuid"]
                delete executeResult.data["Session"]
                getProfileData(loginIdentity).then(executeResult1 => {
                  result(executeResult);
                });
              } else {
                result(executeResult);
              }

              break;
            }

            case "newdevice" : {
              if (executeResult.code === "200") {
                //console.log(executeResult)
                var actionID = executeResult.data["ActionID"]
                var QrCode = executeResult.data["QrCode"]
                //console.log(uuid + " " + token)
                QRCode.toDataURL(actionID + "," + QrCode, function (err, url) {
                  executeResult.data["image"] = url
                  //console.log(executeResult)
                  result(executeResult);
                })
              } else {
                //console.log(executeResult)
                result(executeResult);
              }
              break;
            }

            default : {
              result(executeResult);
              break;
            }
          }
        });
      });
    },
    identityAddNewDevice() {
      return new Penpal.Promise(result => {
        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")

        if (authenticationPublicKey === null) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          })
        }

        if (loadedIdentities[authenticationPublicKey] === null) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          })
        }

        var success = extendPinCodeTtl(authenticationPublicKey)

        if(success == false) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          })
        }

        executeRestfulFunction("private", viamApi, viamApi.identityAddNewDevice).then(executeResult => {
          if (executeResult.code == "200") {
            //console.log(response.data.data)
            var actionID = executeResult.data["ActionID"]
            var QrCode = executeResult.data["QrCode"]
            //console.log(uuid + " " + token)
            QRCode.toDataURL(actionID + "," + QrCode, function (err, url) {
              executeResult.data["image"] = url
              result(executeResult);
            })
          } else {
            result(executeResult);
          }
        });
      });
    },
    identityDestroyKeysForDevice(authenticationPublicKeyArg) {
      return new Penpal.Promise(result => {
        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
        if (authenticationPublicKey === null) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          })
        }
        if (loadedIdentities[authenticationPublicKey] === null) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          })
        }

        var success = extendPinCodeTtl(authenticationPublicKey)

        if(success == false) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          })
        }

        executeRestfulFunction("private", viamApi, viamApi.identityDestroyKeysForDevice, btoa(authenticationPublicKeyArg)).then(executeResult => {
          result(executeResult);
        });
      });
    },
    logout() {
      authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
      if (authenticationPublicKey === null) {
        return {"data" : "",
          "code" : "400",
          "status" : "Identity not loaded"
        }
      }
      if (loadedIdentities[authenticationPublicKey] === null) {
        return {"data" : "",
          "code" : "400",
          "status" : "Identity not loaded"
        }
      }

      return new Penpal.Promise(result => {
        executeRestfulFunction("private", viamApi, viamApi.identityLogout).then(executeResult => {
          viamApi.setIdentity("")
          viamApi.setSessionData("", "")
          clearPinCodeTtl(authenticationPublicKey)

          authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
          localStorage.removeItem("uuid")
          localStorage.removeItem("token")
          localStorage.removeItem("authenticatedIdentity")
          delete loadedIdentities[authenticationPublicKey]
          //console.log("Set loaded identity in logout")
          currentlyLoadedIdentity = null
          currentlyAuthenticatedIdentity = null
          lastTimeGetProfile = 0;

          result(executeResult);
        });
      });
    },
    identityRestoreAccess(restoreAccessIdentity, identificator) {
      return new Penpal.Promise(result => {
        viamApi.setIdentity(restoreAccessIdentity.authentication.publicKey)

        executeRestfulFunction("public", viamApi, viamApi.identityRestoreAccess, identificator).then(executeResult => {
          if (executeResult.code === "200") {
            setIdentityInLocalStorage(restoreAccessIdentity)
            result(executeResult);
          } else {
            result(executeResult);
          }
        });
      });
    },
    getCurrentlyLoggedInUUID() {
      return new Penpal.Promise(result => {
        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
        if (authenticationPublicKey === null) {
          return {"data" : "",
            "code" : "400",
            "status" : "Identity not loaded"
          }
        }
        if (loadedIdentities[authenticationPublicKey] === null) {
          return {"data" : "",
            "code" : "400",
            "status" : "Identity not loaded"
          }
        }

        var success = extendPinCodeTtl(authenticationPublicKey)

        if(success == false) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          })
        }

        if(localStorage.getItem("uuid") === null) {
          result({"data" : "",
            "code" : "400",
            "status" : "Not logged in UUID"
          })
        }
        result({"data" : localStorage.getItem("uuid"),
          "code" : "200",
          "status" : "UUID loaded"
        })
      });
    },
    getCertificateByPassport(passportUUID) {
      return new Penpal.Promise(result => {
        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
        if (authenticationPublicKey === null) {
          return {"data" : "",
            "code" : "400",
            "status" : "Identity not loaded"
          }
        }
        if (loadedIdentities[authenticationPublicKey] === null) {
          return {"data" : "",
            "code" : "400",
            "status" : "Identity not loaded"
          }
        }

        var success = extendPinCodeTtl(authenticationPublicKey)

        if(success == false) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          })
        }

        getCertificateForPassport(passportUUID, false).then(certificateResult => {
          //console.log(certificateResult)
          result(certificateResult)
        })
      });
    },
    getOneTimeCertificateByPassport(passportUUID, emailArg) {
      return new Penpal.Promise(result => {
        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
        if (authenticationPublicKey === null) {
          return {"data" : "",
            "code" : "400",
            "status" : "Identity not loaded"
          }
        }
        if (loadedIdentities[authenticationPublicKey] === null) {
          return {"data" : "",
            "code" : "400",
            "status" : "Identity not loaded"
          }
        }

        var success = extendPinCodeTtl(authenticationPublicKey)

        if(success == false) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          })
        }

        getCertificateForPassport(passportUUID, true).then(certificateResult => {
          //console.log(certificateResult)
          if(certificateResult.code == "200") {
            var passportCertificate = certificateResult.data["x509Certificate"]
            var passportPrivateKey = certificateResult.data["privateKey"]
            var passportChain = certificateResult.data["chain"]

            createOneTimePassportCertificate(makeid() + "-" + passportUUID, emailArg, passportPrivateKey, passportCertificate).then(function(keys){
              var publicKeyOneTime = keys["publicKeyPEM"]
              var privateKeyOneTime = keys["privateKeyPEM"]
              var certificateOneTime = keys["certificatePEM"]
              passportChain.push(passportCertificate)

              var oneTimeCryptoData = new CryptoData();
              oneTimeCryptoData.setx509Certificate(certificateOneTime)
              oneTimeCryptoData.setPrivateKey(privateKeyOneTime)
              oneTimeCryptoData.setPublicKey(publicKeyOneTime)
              oneTimeCryptoData.setChain(passportChain)

              result({"data" : oneTimeCryptoData,
                "code" : "200",
                "status" : "One time certificate generated"
              })
              // Prints PEM formatted signed certificate
              // -----BEGIN CERTIFICATE-----MIID....7Hyg==-----END CERTIFICATE-----

            });
          } else {
            result({"data" : "",
              "code" : "400",
              "status" : "Can not generate one time certificate"
            })
          }
        })
      });
    },
    signEmail(passportUUID, emailArg, emailMessage) {
      return new Penpal.Promise(result => {
        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
        if (authenticationPublicKey === null) {
          return {"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          }
        }
        if (loadedIdentities[authenticationPublicKey] === null) {
          return {"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          }
        }

        var success = extendPinCodeTtl(authenticationPublicKey)

        if(success == false) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          })
        }

        getCertificateForPassport(passportUUID, true).then(certificateResult => {
          console.log("Certificate for passport")
          console.log(certificateResult)
          if(certificateResult.code == "200") {
            var passportCertificate = certificateResult.data["x509Certificate"]
            var passportPrivateKey = certificateResult.data["privateKey"]
            var passportChain = certificateResult.data["chain"]

            createOneTimePassportCertificate(makeid() + "-" + passportUUID, emailArg, passportPrivateKey, passportCertificate).then(function(keys){
              var publicKeyOneTime = keys["publicKeyPEM"]
              var privateKeyOneTime = keys["privateKeyPEM"]
              var certificateOneTime = keys["certificatePEM"]
              //download("certificateOneTime.crt", "text/plain", certificateOneTime)

              passportChain.push(passportCertificate)

              //console.log("Before sign email")
              //console.log(certificateOneTime)
              //console.log(passportChain)
              //console.log(privateKeyOneTime)

              executeRestfulFunction("private", viamApi, viamApi.passportGetEmailWithHeaderByPassport,
                passportUUID, window.btoa(emailMessage)).then(executeResult2 => {
                var emailWithHeader = window.atob(executeResult2.data)
                //console.log(emailWithHeader)
                //download("withheader.eml", "message/rfc822", emailWithHeader)
                var signedEmailPromise = signEmail(emailWithHeader,
                  certificateOneTime,
                  passportChain,
                  privateKeyOneTime)

                signedEmailPromise.then(signedEmail => {
                  executeRestfulFunction("private", viamApi, viamApi.signResignEmail,
                    passportUUID, window.btoa(signedEmail)).then(executeResult => {
                    result({"data" : window.atob(executeResult.data),
                      "code" : "200",
                      "status" : "Email signed"
                    })
                  });
                  /*result({"data" : signedEmail,
                      "code" : "200",
                      "status" : "Email signed"
                  })*/
                });
              });
              // Prints PEM formatted signed certificate
              // -----BEGIN CERTIFICATE-----MIID....7Hyg==-----END CERTIFICATE-----

            });
          } else {
            result({"data" : "",
              "code" : "400",
              "status" : "Can not sign email"
            })
          }
        })
      });
    },
    hasSession() {
      return new Penpal.Promise(result => {
        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
        if (authenticationPublicKey === null) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          });
        }
        if (loadedIdentities[authenticationPublicKey] === null) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          });
        }

        var success = extendPinCodeTtl(authenticationPublicKey)

        if(success == false) {
          result({"data" : "",
            "code" : "400",
            "status" : "Identity not authenticated"
          })
        }

        executeRestfulFunction("private", viamApi, viamApi.identityHasSession).then(executeResult => {
          result(executeResult);
        });
      });
    },
    marketingSignUpIdentificator(identificator, reference) {
      return new Penpal.Promise(result => {
        viamApi.setIdentity("marketingapppublickey")

        executeRestfulFunction("public", viamApi, viamApi.marketingSignUpIdentificator, identificator, reference).then(executeResult => {
          viamApi.setIdentity("")
          viamApi.setSessionData("", "")
          result(executeResult);
        });
      });
    },
    marketingGetIdentificatorProfile(identificator, pincode) {
      return new Penpal.Promise(result => {
        viamApi.setIdentity("marketingapppublickey")

        executeRestfulFunction("public", viamApi, viamApi.marketingGetIdentificatorProfile, identificator, pincode).then(executeResult => {
          viamApi.setIdentity("")
          viamApi.setSessionData("", "")
          result(executeResult);
        });
      });
    },
    marketingЕxecuteEventForIdentificator(identificator, pincode, event) {
      return new Penpal.Promise(result => {
        viamApi.setIdentity("marketingapppublickey")

        executeRestfulFunction("public", viamApi, viamApi.marketingExecuteEventForIdentificator, identificator, pincode, event).then(executeResult => {
          viamApi.setIdentity("")
          viamApi.setSessionData("", "")
          result(executeResult);
        });
      });
    },
    getCurrentlyAuthenticatedIdentity() {
      return new Penpal.Promise(result => {
        result({"data" : currentlyAuthenticatedIdentity,
          "code" : "200",
          "status" : "Currently authenticated identity"
        })
      });
    },
    //{{methods}}
  }
});

connection.promise.then(parent => {
  var identities = localStorage.getItem("identities")

  console.log("Library loaded at: " + new Date().toISOString())

  if (identities === "" || identities === null) {
Loading
Loading full blame...