@voidly/agent-sdk 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -49,11 +49,11 @@ var require_nacl_fast = __commonJS({
49
49
  var _9 = new Uint8Array(32);
50
50
  _9[0] = 9;
51
51
  var gf0 = gf(), gf1 = gf([1]), _121665 = gf([56129, 1]), D = gf([30883, 4953, 19914, 30187, 55467, 16705, 2637, 112, 59544, 30585, 16505, 36039, 65139, 11119, 27886, 20995]), D2 = gf([61785, 9906, 39828, 60374, 45398, 33411, 5274, 224, 53552, 61171, 33010, 6542, 64743, 22239, 55772, 9222]), X = gf([54554, 36645, 11616, 51542, 42930, 38181, 51040, 26924, 56412, 64982, 57905, 49316, 21502, 52590, 14035, 8553]), Y = gf([26200, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214]), I = gf([41136, 18958, 6951, 50414, 58488, 44335, 6150, 12099, 55207, 15867, 153, 11085, 57099, 20417, 9344, 11139]);
52
- function ts64(x, i, h, l) {
53
- x[i] = h >> 24 & 255;
54
- x[i + 1] = h >> 16 & 255;
55
- x[i + 2] = h >> 8 & 255;
56
- x[i + 3] = h & 255;
52
+ function ts64(x, i, h2, l) {
53
+ x[i] = h2 >> 24 & 255;
54
+ x[i + 1] = h2 >> 16 & 255;
55
+ x[i + 2] = h2 >> 8 & 255;
56
+ x[i + 3] = h2 & 255;
57
57
  x[i + 4] = l >> 24 & 255;
58
58
  x[i + 5] = l >> 16 & 255;
59
59
  x[i + 6] = l >> 8 & 255;
@@ -631,7 +631,7 @@ var require_nacl_fast = __commonJS({
631
631
  this.h[9] = h9;
632
632
  };
633
633
  poly1305.prototype.finish = function(mac, macpos) {
634
- var g = new Uint16Array(10);
634
+ var g2 = new Uint16Array(10);
635
635
  var c, mask, f, i;
636
636
  if (this.leftover) {
637
637
  i = this.leftover;
@@ -654,19 +654,19 @@ var require_nacl_fast = __commonJS({
654
654
  c = this.h[1] >>> 13;
655
655
  this.h[1] &= 8191;
656
656
  this.h[2] += c;
657
- g[0] = this.h[0] + 5;
658
- c = g[0] >>> 13;
659
- g[0] &= 8191;
657
+ g2[0] = this.h[0] + 5;
658
+ c = g2[0] >>> 13;
659
+ g2[0] &= 8191;
660
660
  for (i = 1; i < 10; i++) {
661
- g[i] = this.h[i] + c;
662
- c = g[i] >>> 13;
663
- g[i] &= 8191;
661
+ g2[i] = this.h[i] + c;
662
+ c = g2[i] >>> 13;
663
+ g2[i] &= 8191;
664
664
  }
665
- g[9] -= 1 << 13;
665
+ g2[9] -= 1 << 13;
666
666
  mask = (c ^ 1) - 1;
667
- for (i = 0; i < 10; i++) g[i] &= mask;
667
+ for (i = 0; i < 10; i++) g2[i] &= mask;
668
668
  mask = ~mask;
669
- for (i = 0; i < 10; i++) this.h[i] = this.h[i] & mask | g[i];
669
+ for (i = 0; i < 10; i++) this.h[i] = this.h[i] & mask | g2[i];
670
670
  this.h[0] = (this.h[0] | this.h[1] << 13) & 65535;
671
671
  this.h[1] = (this.h[1] >>> 3 | this.h[2] << 10) & 65535;
672
672
  this.h[2] = (this.h[2] >>> 6 | this.h[3] << 7) & 65535;
@@ -732,10 +732,10 @@ var require_nacl_fast = __commonJS({
732
732
  s.finish(out, outpos);
733
733
  return 0;
734
734
  }
735
- function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
735
+ function crypto_onetimeauth_verify(h2, hpos, m, mpos, n, k) {
736
736
  var x = new Uint8Array(16);
737
737
  crypto_onetimeauth(x, 0, m, mpos, n, k);
738
- return crypto_verify_16(h, hpos, x, 0);
738
+ return crypto_verify_16(h2, hpos, x, 0);
739
739
  }
740
740
  function crypto_secretbox(c, m, d, n, k) {
741
741
  var i;
@@ -1488,7 +1488,7 @@ var require_nacl_fast = __commonJS({
1488
1488
  1246189591
1489
1489
  ];
1490
1490
  function crypto_hashblocks_hl(hh, hl, m, n) {
1491
- var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h, l, a, b, c, d;
1491
+ var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h2, l, a, b, c, d;
1492
1492
  var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7];
1493
1493
  var pos = 0;
1494
1494
  while (n >= 128) {
@@ -1514,76 +1514,76 @@ var require_nacl_fast = __commonJS({
1514
1514
  bl5 = al5;
1515
1515
  bl6 = al6;
1516
1516
  bl7 = al7;
1517
- h = ah7;
1517
+ h2 = ah7;
1518
1518
  l = al7;
1519
1519
  a = l & 65535;
1520
1520
  b = l >>> 16;
1521
- c = h & 65535;
1522
- d = h >>> 16;
1523
- h = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32));
1521
+ c = h2 & 65535;
1522
+ d = h2 >>> 16;
1523
+ h2 = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32));
1524
1524
  l = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32));
1525
1525
  a += l & 65535;
1526
1526
  b += l >>> 16;
1527
- c += h & 65535;
1528
- d += h >>> 16;
1529
- h = ah4 & ah5 ^ ~ah4 & ah6;
1527
+ c += h2 & 65535;
1528
+ d += h2 >>> 16;
1529
+ h2 = ah4 & ah5 ^ ~ah4 & ah6;
1530
1530
  l = al4 & al5 ^ ~al4 & al6;
1531
1531
  a += l & 65535;
1532
1532
  b += l >>> 16;
1533
- c += h & 65535;
1534
- d += h >>> 16;
1535
- h = K[i * 2];
1533
+ c += h2 & 65535;
1534
+ d += h2 >>> 16;
1535
+ h2 = K[i * 2];
1536
1536
  l = K[i * 2 + 1];
1537
1537
  a += l & 65535;
1538
1538
  b += l >>> 16;
1539
- c += h & 65535;
1540
- d += h >>> 16;
1541
- h = wh[i % 16];
1539
+ c += h2 & 65535;
1540
+ d += h2 >>> 16;
1541
+ h2 = wh[i % 16];
1542
1542
  l = wl[i % 16];
1543
1543
  a += l & 65535;
1544
1544
  b += l >>> 16;
1545
- c += h & 65535;
1546
- d += h >>> 16;
1545
+ c += h2 & 65535;
1546
+ d += h2 >>> 16;
1547
1547
  b += a >>> 16;
1548
1548
  c += b >>> 16;
1549
1549
  d += c >>> 16;
1550
1550
  th = c & 65535 | d << 16;
1551
1551
  tl = a & 65535 | b << 16;
1552
- h = th;
1552
+ h2 = th;
1553
1553
  l = tl;
1554
1554
  a = l & 65535;
1555
1555
  b = l >>> 16;
1556
- c = h & 65535;
1557
- d = h >>> 16;
1558
- h = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32));
1556
+ c = h2 & 65535;
1557
+ d = h2 >>> 16;
1558
+ h2 = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32));
1559
1559
  l = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32));
1560
1560
  a += l & 65535;
1561
1561
  b += l >>> 16;
1562
- c += h & 65535;
1563
- d += h >>> 16;
1564
- h = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2;
1562
+ c += h2 & 65535;
1563
+ d += h2 >>> 16;
1564
+ h2 = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2;
1565
1565
  l = al0 & al1 ^ al0 & al2 ^ al1 & al2;
1566
1566
  a += l & 65535;
1567
1567
  b += l >>> 16;
1568
- c += h & 65535;
1569
- d += h >>> 16;
1568
+ c += h2 & 65535;
1569
+ d += h2 >>> 16;
1570
1570
  b += a >>> 16;
1571
1571
  c += b >>> 16;
1572
1572
  d += c >>> 16;
1573
1573
  bh7 = c & 65535 | d << 16;
1574
1574
  bl7 = a & 65535 | b << 16;
1575
- h = bh3;
1575
+ h2 = bh3;
1576
1576
  l = bl3;
1577
1577
  a = l & 65535;
1578
1578
  b = l >>> 16;
1579
- c = h & 65535;
1580
- d = h >>> 16;
1581
- h = th;
1579
+ c = h2 & 65535;
1580
+ d = h2 >>> 16;
1581
+ h2 = th;
1582
1582
  l = tl;
1583
1583
  a += l & 65535;
1584
1584
  b += l >>> 16;
1585
- c += h & 65535;
1586
- d += h >>> 16;
1585
+ c += h2 & 65535;
1586
+ d += h2 >>> 16;
1587
1587
  b += a >>> 16;
1588
1588
  c += b >>> 16;
1589
1589
  d += c >>> 16;
@@ -1607,34 +1607,34 @@ var require_nacl_fast = __commonJS({
1607
1607
  al0 = bl7;
1608
1608
  if (i % 16 === 15) {
1609
1609
  for (j = 0; j < 16; j++) {
1610
- h = wh[j];
1610
+ h2 = wh[j];
1611
1611
  l = wl[j];
1612
1612
  a = l & 65535;
1613
1613
  b = l >>> 16;
1614
- c = h & 65535;
1615
- d = h >>> 16;
1616
- h = wh[(j + 9) % 16];
1614
+ c = h2 & 65535;
1615
+ d = h2 >>> 16;
1616
+ h2 = wh[(j + 9) % 16];
1617
1617
  l = wl[(j + 9) % 16];
1618
1618
  a += l & 65535;
1619
1619
  b += l >>> 16;
1620
- c += h & 65535;
1621
- d += h >>> 16;
1620
+ c += h2 & 65535;
1621
+ d += h2 >>> 16;
1622
1622
  th = wh[(j + 1) % 16];
1623
1623
  tl = wl[(j + 1) % 16];
1624
- h = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7;
1624
+ h2 = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7;
1625
1625
  l = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7);
1626
1626
  a += l & 65535;
1627
1627
  b += l >>> 16;
1628
- c += h & 65535;
1629
- d += h >>> 16;
1628
+ c += h2 & 65535;
1629
+ d += h2 >>> 16;
1630
1630
  th = wh[(j + 14) % 16];
1631
1631
  tl = wl[(j + 14) % 16];
1632
- h = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6;
1632
+ h2 = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6;
1633
1633
  l = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6);
1634
1634
  a += l & 65535;
1635
1635
  b += l >>> 16;
1636
- c += h & 65535;
1637
- d += h >>> 16;
1636
+ c += h2 & 65535;
1637
+ d += h2 >>> 16;
1638
1638
  b += a >>> 16;
1639
1639
  c += b >>> 16;
1640
1640
  d += c >>> 16;
@@ -1643,137 +1643,137 @@ var require_nacl_fast = __commonJS({
1643
1643
  }
1644
1644
  }
1645
1645
  }
1646
- h = ah0;
1646
+ h2 = ah0;
1647
1647
  l = al0;
1648
1648
  a = l & 65535;
1649
1649
  b = l >>> 16;
1650
- c = h & 65535;
1651
- d = h >>> 16;
1652
- h = hh[0];
1650
+ c = h2 & 65535;
1651
+ d = h2 >>> 16;
1652
+ h2 = hh[0];
1653
1653
  l = hl[0];
1654
1654
  a += l & 65535;
1655
1655
  b += l >>> 16;
1656
- c += h & 65535;
1657
- d += h >>> 16;
1656
+ c += h2 & 65535;
1657
+ d += h2 >>> 16;
1658
1658
  b += a >>> 16;
1659
1659
  c += b >>> 16;
1660
1660
  d += c >>> 16;
1661
1661
  hh[0] = ah0 = c & 65535 | d << 16;
1662
1662
  hl[0] = al0 = a & 65535 | b << 16;
1663
- h = ah1;
1663
+ h2 = ah1;
1664
1664
  l = al1;
1665
1665
  a = l & 65535;
1666
1666
  b = l >>> 16;
1667
- c = h & 65535;
1668
- d = h >>> 16;
1669
- h = hh[1];
1667
+ c = h2 & 65535;
1668
+ d = h2 >>> 16;
1669
+ h2 = hh[1];
1670
1670
  l = hl[1];
1671
1671
  a += l & 65535;
1672
1672
  b += l >>> 16;
1673
- c += h & 65535;
1674
- d += h >>> 16;
1673
+ c += h2 & 65535;
1674
+ d += h2 >>> 16;
1675
1675
  b += a >>> 16;
1676
1676
  c += b >>> 16;
1677
1677
  d += c >>> 16;
1678
1678
  hh[1] = ah1 = c & 65535 | d << 16;
1679
1679
  hl[1] = al1 = a & 65535 | b << 16;
1680
- h = ah2;
1680
+ h2 = ah2;
1681
1681
  l = al2;
1682
1682
  a = l & 65535;
1683
1683
  b = l >>> 16;
1684
- c = h & 65535;
1685
- d = h >>> 16;
1686
- h = hh[2];
1684
+ c = h2 & 65535;
1685
+ d = h2 >>> 16;
1686
+ h2 = hh[2];
1687
1687
  l = hl[2];
1688
1688
  a += l & 65535;
1689
1689
  b += l >>> 16;
1690
- c += h & 65535;
1691
- d += h >>> 16;
1690
+ c += h2 & 65535;
1691
+ d += h2 >>> 16;
1692
1692
  b += a >>> 16;
1693
1693
  c += b >>> 16;
1694
1694
  d += c >>> 16;
1695
1695
  hh[2] = ah2 = c & 65535 | d << 16;
1696
1696
  hl[2] = al2 = a & 65535 | b << 16;
1697
- h = ah3;
1697
+ h2 = ah3;
1698
1698
  l = al3;
1699
1699
  a = l & 65535;
1700
1700
  b = l >>> 16;
1701
- c = h & 65535;
1702
- d = h >>> 16;
1703
- h = hh[3];
1701
+ c = h2 & 65535;
1702
+ d = h2 >>> 16;
1703
+ h2 = hh[3];
1704
1704
  l = hl[3];
1705
1705
  a += l & 65535;
1706
1706
  b += l >>> 16;
1707
- c += h & 65535;
1708
- d += h >>> 16;
1707
+ c += h2 & 65535;
1708
+ d += h2 >>> 16;
1709
1709
  b += a >>> 16;
1710
1710
  c += b >>> 16;
1711
1711
  d += c >>> 16;
1712
1712
  hh[3] = ah3 = c & 65535 | d << 16;
1713
1713
  hl[3] = al3 = a & 65535 | b << 16;
1714
- h = ah4;
1714
+ h2 = ah4;
1715
1715
  l = al4;
1716
1716
  a = l & 65535;
1717
1717
  b = l >>> 16;
1718
- c = h & 65535;
1719
- d = h >>> 16;
1720
- h = hh[4];
1718
+ c = h2 & 65535;
1719
+ d = h2 >>> 16;
1720
+ h2 = hh[4];
1721
1721
  l = hl[4];
1722
1722
  a += l & 65535;
1723
1723
  b += l >>> 16;
1724
- c += h & 65535;
1725
- d += h >>> 16;
1724
+ c += h2 & 65535;
1725
+ d += h2 >>> 16;
1726
1726
  b += a >>> 16;
1727
1727
  c += b >>> 16;
1728
1728
  d += c >>> 16;
1729
1729
  hh[4] = ah4 = c & 65535 | d << 16;
1730
1730
  hl[4] = al4 = a & 65535 | b << 16;
1731
- h = ah5;
1731
+ h2 = ah5;
1732
1732
  l = al5;
1733
1733
  a = l & 65535;
1734
1734
  b = l >>> 16;
1735
- c = h & 65535;
1736
- d = h >>> 16;
1737
- h = hh[5];
1735
+ c = h2 & 65535;
1736
+ d = h2 >>> 16;
1737
+ h2 = hh[5];
1738
1738
  l = hl[5];
1739
1739
  a += l & 65535;
1740
1740
  b += l >>> 16;
1741
- c += h & 65535;
1742
- d += h >>> 16;
1741
+ c += h2 & 65535;
1742
+ d += h2 >>> 16;
1743
1743
  b += a >>> 16;
1744
1744
  c += b >>> 16;
1745
1745
  d += c >>> 16;
1746
1746
  hh[5] = ah5 = c & 65535 | d << 16;
1747
1747
  hl[5] = al5 = a & 65535 | b << 16;
1748
- h = ah6;
1748
+ h2 = ah6;
1749
1749
  l = al6;
1750
1750
  a = l & 65535;
1751
1751
  b = l >>> 16;
1752
- c = h & 65535;
1753
- d = h >>> 16;
1754
- h = hh[6];
1752
+ c = h2 & 65535;
1753
+ d = h2 >>> 16;
1754
+ h2 = hh[6];
1755
1755
  l = hl[6];
1756
1756
  a += l & 65535;
1757
1757
  b += l >>> 16;
1758
- c += h & 65535;
1759
- d += h >>> 16;
1758
+ c += h2 & 65535;
1759
+ d += h2 >>> 16;
1760
1760
  b += a >>> 16;
1761
1761
  c += b >>> 16;
1762
1762
  d += c >>> 16;
1763
1763
  hh[6] = ah6 = c & 65535 | d << 16;
1764
1764
  hl[6] = al6 = a & 65535 | b << 16;
1765
- h = ah7;
1765
+ h2 = ah7;
1766
1766
  l = al7;
1767
1767
  a = l & 65535;
1768
1768
  b = l >>> 16;
1769
- c = h & 65535;
1770
- d = h >>> 16;
1771
- h = hh[7];
1769
+ c = h2 & 65535;
1770
+ d = h2 >>> 16;
1771
+ h2 = hh[7];
1772
1772
  l = hl[7];
1773
1773
  a += l & 65535;
1774
1774
  b += l >>> 16;
1775
- c += h & 65535;
1776
- d += h >>> 16;
1775
+ c += h2 & 65535;
1776
+ d += h2 >>> 16;
1777
1777
  b += a >>> 16;
1778
1778
  c += b >>> 16;
1779
1779
  d += c >>> 16;
@@ -1813,8 +1813,8 @@ var require_nacl_fast = __commonJS({
1813
1813
  for (i = 0; i < 8; i++) ts64(out, 8 * i, hh[i], hl[i]);
1814
1814
  return 0;
1815
1815
  }
1816
- function add(p, q) {
1817
- var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf();
1816
+ function add2(p, q) {
1817
+ var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g2 = gf(), h2 = gf(), t = gf();
1818
1818
  Z(a, p[1], p[0]);
1819
1819
  Z(t, q[1], q[0]);
1820
1820
  M(a, a, t);
@@ -1827,12 +1827,12 @@ var require_nacl_fast = __commonJS({
1827
1827
  A(d, d, d);
1828
1828
  Z(e, b, a);
1829
1829
  Z(f, d, c);
1830
- A(g, d, c);
1831
- A(h, b, a);
1830
+ A(g2, d, c);
1831
+ A(h2, b, a);
1832
1832
  M(p[0], e, f);
1833
- M(p[1], h, g);
1834
- M(p[2], g, f);
1835
- M(p[3], e, h);
1833
+ M(p[1], h2, g2);
1834
+ M(p[2], g2, f);
1835
+ M(p[3], e, h2);
1836
1836
  }
1837
1837
  function cswap(p, q, b) {
1838
1838
  var i;
@@ -1857,8 +1857,8 @@ var require_nacl_fast = __commonJS({
1857
1857
  for (i = 255; i >= 0; --i) {
1858
1858
  b = s[i / 8 | 0] >> (i & 7) & 1;
1859
1859
  cswap(p, q, b);
1860
- add(q, p);
1861
- add(p, p);
1860
+ add2(q, p);
1861
+ add2(p, p);
1862
1862
  cswap(p, q, b);
1863
1863
  }
1864
1864
  }
@@ -1909,14 +1909,14 @@ var require_nacl_fast = __commonJS({
1909
1909
  r[i] = x[i] & 255;
1910
1910
  }
1911
1911
  }
1912
- function reduce(r) {
1912
+ function reduce2(r) {
1913
1913
  var x = new Float64Array(64), i;
1914
1914
  for (i = 0; i < 64; i++) x[i] = r[i];
1915
1915
  for (i = 0; i < 64; i++) r[i] = 0;
1916
1916
  modL(r, x);
1917
1917
  }
1918
1918
  function crypto_sign(sm, m, n, sk) {
1919
- var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
1919
+ var d = new Uint8Array(64), h2 = new Uint8Array(64), r = new Uint8Array(64);
1920
1920
  var i, j, x = new Float64Array(64);
1921
1921
  var p = [gf(), gf(), gf(), gf()];
1922
1922
  crypto_hash(d, sk, 32);
@@ -1927,17 +1927,17 @@ var require_nacl_fast = __commonJS({
1927
1927
  for (i = 0; i < n; i++) sm[64 + i] = m[i];
1928
1928
  for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
1929
1929
  crypto_hash(r, sm.subarray(32), n + 32);
1930
- reduce(r);
1930
+ reduce2(r);
1931
1931
  scalarbase(p, r);
1932
1932
  pack(sm, p);
1933
1933
  for (i = 32; i < 64; i++) sm[i] = sk[i];
1934
- crypto_hash(h, sm, n + 64);
1935
- reduce(h);
1934
+ crypto_hash(h2, sm, n + 64);
1935
+ reduce2(h2);
1936
1936
  for (i = 0; i < 64; i++) x[i] = 0;
1937
1937
  for (i = 0; i < 32; i++) x[i] = r[i];
1938
1938
  for (i = 0; i < 32; i++) {
1939
1939
  for (j = 0; j < 32; j++) {
1940
- x[i + j] += h[i] * d[j];
1940
+ x[i + j] += h2[i] * d[j];
1941
1941
  }
1942
1942
  }
1943
1943
  modL(sm.subarray(32), x);
@@ -1973,17 +1973,17 @@ var require_nacl_fast = __commonJS({
1973
1973
  }
1974
1974
  function crypto_sign_open(m, sm, n, pk) {
1975
1975
  var i;
1976
- var t = new Uint8Array(32), h = new Uint8Array(64);
1976
+ var t = new Uint8Array(32), h2 = new Uint8Array(64);
1977
1977
  var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()];
1978
1978
  if (n < 64) return -1;
1979
1979
  if (unpackneg(q, pk)) return -1;
1980
1980
  for (i = 0; i < n; i++) m[i] = sm[i];
1981
1981
  for (i = 0; i < 32; i++) m[i + 32] = pk[i];
1982
- crypto_hash(h, m, n);
1983
- reduce(h);
1984
- scalarmult(p, q, h);
1982
+ crypto_hash(h2, m, n);
1983
+ reduce2(h2);
1984
+ scalarmult(p, q, h2);
1985
1985
  scalarbase(q, sm.subarray(32));
1986
- add(p, q);
1986
+ add2(p, q);
1987
1987
  pack(t, p);
1988
1988
  n -= 64;
1989
1989
  if (crypto_verify_32(sm, 0, t, 0)) {
@@ -2044,7 +2044,7 @@ var require_nacl_fast = __commonJS({
2044
2044
  S,
2045
2045
  Z,
2046
2046
  pow2523,
2047
- add,
2047
+ add: add2,
2048
2048
  set25519,
2049
2049
  modL,
2050
2050
  scalarmult,
@@ -2215,9 +2215,9 @@ var require_nacl_fast = __commonJS({
2215
2215
  nacl2.sign.signatureLength = crypto_sign_BYTES;
2216
2216
  nacl2.hash = function(msg) {
2217
2217
  checkArrayTypes(msg);
2218
- var h = new Uint8Array(crypto_hash_BYTES);
2219
- crypto_hash(h, msg, msg.length);
2220
- return h;
2218
+ var h2 = new Uint8Array(crypto_hash_BYTES);
2219
+ crypto_hash(h2, msg, msg.length);
2220
+ return h2;
2221
2221
  };
2222
2222
  nacl2.hash.hashLength = crypto_hash_BYTES;
2223
2223
  nacl2.verify = function(x, y) {
@@ -2230,22 +2230,22 @@ var require_nacl_fast = __commonJS({
2230
2230
  randombytes = fn;
2231
2231
  };
2232
2232
  (function() {
2233
- var crypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null;
2234
- if (crypto && crypto.getRandomValues) {
2233
+ var crypto2 = typeof self !== "undefined" ? self.crypto || self.msCrypto : null;
2234
+ if (crypto2 && crypto2.getRandomValues) {
2235
2235
  var QUOTA = 65536;
2236
2236
  nacl2.setPRNG(function(x, n) {
2237
2237
  var i, v = new Uint8Array(n);
2238
2238
  for (i = 0; i < n; i += QUOTA) {
2239
- crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
2239
+ crypto2.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
2240
2240
  }
2241
2241
  for (i = 0; i < n; i++) x[i] = v[i];
2242
2242
  cleanup(v);
2243
2243
  });
2244
2244
  } else if (typeof require !== "undefined") {
2245
- crypto = require("crypto");
2246
- if (crypto && crypto.randomBytes) {
2245
+ crypto2 = require("crypto");
2246
+ if (crypto2 && crypto2.randomBytes) {
2247
2247
  nacl2.setPRNG(function(x, n) {
2248
- var i, v = crypto.randomBytes(n);
2248
+ var i, v = crypto2.randomBytes(n);
2249
2249
  for (i = 0; i < n; i++) x[i] = v[i];
2250
2250
  cleanup(v);
2251
2251
  });
@@ -2337,6 +2337,1603 @@ __export(index_exports, {
2337
2337
  module.exports = __toCommonJS(index_exports);
2338
2338
  var import_tweetnacl = __toESM(require_nacl_fast());
2339
2339
  var import_tweetnacl_util = __toESM(require_nacl_util());
2340
+
2341
+ // node_modules/mlkem/esm/src/errors.js
2342
+ var MlKemError = class extends Error {
2343
+ constructor(e) {
2344
+ let message;
2345
+ if (e instanceof Error) {
2346
+ message = e.message;
2347
+ } else if (typeof e === "string") {
2348
+ message = e;
2349
+ } else {
2350
+ message = "";
2351
+ }
2352
+ super(message);
2353
+ this.name = this.constructor.name;
2354
+ }
2355
+ };
2356
+
2357
+ // node_modules/mlkem/esm/src/consts.js
2358
+ var N = 256;
2359
+ var Q = 3329;
2360
+ var Q_INV = 62209;
2361
+ var NTT_ZETAS = [
2362
+ 2285,
2363
+ 2571,
2364
+ 2970,
2365
+ 1812,
2366
+ 1493,
2367
+ 1422,
2368
+ 287,
2369
+ 202,
2370
+ 3158,
2371
+ 622,
2372
+ 1577,
2373
+ 182,
2374
+ 962,
2375
+ 2127,
2376
+ 1855,
2377
+ 1468,
2378
+ 573,
2379
+ 2004,
2380
+ 264,
2381
+ 383,
2382
+ 2500,
2383
+ 1458,
2384
+ 1727,
2385
+ 3199,
2386
+ 2648,
2387
+ 1017,
2388
+ 732,
2389
+ 608,
2390
+ 1787,
2391
+ 411,
2392
+ 3124,
2393
+ 1758,
2394
+ 1223,
2395
+ 652,
2396
+ 2777,
2397
+ 1015,
2398
+ 2036,
2399
+ 1491,
2400
+ 3047,
2401
+ 1785,
2402
+ 516,
2403
+ 3321,
2404
+ 3009,
2405
+ 2663,
2406
+ 1711,
2407
+ 2167,
2408
+ 126,
2409
+ 1469,
2410
+ 2476,
2411
+ 3239,
2412
+ 3058,
2413
+ 830,
2414
+ 107,
2415
+ 1908,
2416
+ 3082,
2417
+ 2378,
2418
+ 2931,
2419
+ 961,
2420
+ 1821,
2421
+ 2604,
2422
+ 448,
2423
+ 2264,
2424
+ 677,
2425
+ 2054,
2426
+ 2226,
2427
+ 430,
2428
+ 555,
2429
+ 843,
2430
+ 2078,
2431
+ 871,
2432
+ 1550,
2433
+ 105,
2434
+ 422,
2435
+ 587,
2436
+ 177,
2437
+ 3094,
2438
+ 3038,
2439
+ 2869,
2440
+ 1574,
2441
+ 1653,
2442
+ 3083,
2443
+ 778,
2444
+ 1159,
2445
+ 3182,
2446
+ 2552,
2447
+ 1483,
2448
+ 2727,
2449
+ 1119,
2450
+ 1739,
2451
+ 644,
2452
+ 2457,
2453
+ 349,
2454
+ 418,
2455
+ 329,
2456
+ 3173,
2457
+ 3254,
2458
+ 817,
2459
+ 1097,
2460
+ 603,
2461
+ 610,
2462
+ 1322,
2463
+ 2044,
2464
+ 1864,
2465
+ 384,
2466
+ 2114,
2467
+ 3193,
2468
+ 1218,
2469
+ 1994,
2470
+ 2455,
2471
+ 220,
2472
+ 2142,
2473
+ 1670,
2474
+ 2144,
2475
+ 1799,
2476
+ 2051,
2477
+ 794,
2478
+ 1819,
2479
+ 2475,
2480
+ 2459,
2481
+ 478,
2482
+ 3221,
2483
+ 3021,
2484
+ 996,
2485
+ 991,
2486
+ 958,
2487
+ 1869,
2488
+ 1522,
2489
+ 1628
2490
+ ];
2491
+ var NTT_ZETAS_INV = [
2492
+ 1701,
2493
+ 1807,
2494
+ 1460,
2495
+ 2371,
2496
+ 2338,
2497
+ 2333,
2498
+ 308,
2499
+ 108,
2500
+ 2851,
2501
+ 870,
2502
+ 854,
2503
+ 1510,
2504
+ 2535,
2505
+ 1278,
2506
+ 1530,
2507
+ 1185,
2508
+ 1659,
2509
+ 1187,
2510
+ 3109,
2511
+ 874,
2512
+ 1335,
2513
+ 2111,
2514
+ 136,
2515
+ 1215,
2516
+ 2945,
2517
+ 1465,
2518
+ 1285,
2519
+ 2007,
2520
+ 2719,
2521
+ 2726,
2522
+ 2232,
2523
+ 2512,
2524
+ 75,
2525
+ 156,
2526
+ 3e3,
2527
+ 2911,
2528
+ 2980,
2529
+ 872,
2530
+ 2685,
2531
+ 1590,
2532
+ 2210,
2533
+ 602,
2534
+ 1846,
2535
+ 777,
2536
+ 147,
2537
+ 2170,
2538
+ 2551,
2539
+ 246,
2540
+ 1676,
2541
+ 1755,
2542
+ 460,
2543
+ 291,
2544
+ 235,
2545
+ 3152,
2546
+ 2742,
2547
+ 2907,
2548
+ 3224,
2549
+ 1779,
2550
+ 2458,
2551
+ 1251,
2552
+ 2486,
2553
+ 2774,
2554
+ 2899,
2555
+ 1103,
2556
+ 1275,
2557
+ 2652,
2558
+ 1065,
2559
+ 2881,
2560
+ 725,
2561
+ 1508,
2562
+ 2368,
2563
+ 398,
2564
+ 951,
2565
+ 247,
2566
+ 1421,
2567
+ 3222,
2568
+ 2499,
2569
+ 271,
2570
+ 90,
2571
+ 853,
2572
+ 1860,
2573
+ 3203,
2574
+ 1162,
2575
+ 1618,
2576
+ 666,
2577
+ 320,
2578
+ 8,
2579
+ 2813,
2580
+ 1544,
2581
+ 282,
2582
+ 1838,
2583
+ 1293,
2584
+ 2314,
2585
+ 552,
2586
+ 2677,
2587
+ 2106,
2588
+ 1571,
2589
+ 205,
2590
+ 2918,
2591
+ 1542,
2592
+ 2721,
2593
+ 2597,
2594
+ 2312,
2595
+ 681,
2596
+ 130,
2597
+ 1602,
2598
+ 1871,
2599
+ 829,
2600
+ 2946,
2601
+ 3065,
2602
+ 1325,
2603
+ 2756,
2604
+ 1861,
2605
+ 1474,
2606
+ 1202,
2607
+ 2367,
2608
+ 3147,
2609
+ 1752,
2610
+ 2707,
2611
+ 171,
2612
+ 3127,
2613
+ 3042,
2614
+ 1907,
2615
+ 1836,
2616
+ 1517,
2617
+ 359,
2618
+ 758,
2619
+ 1441
2620
+ ];
2621
+
2622
+ // node_modules/mlkem/esm/src/sha3/_u64.js
2623
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
2624
+ var _32n = /* @__PURE__ */ BigInt(32);
2625
+ function fromBig(n, le = false) {
2626
+ if (le) {
2627
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
2628
+ }
2629
+ return {
2630
+ h: Number(n >> _32n & U32_MASK64) | 0,
2631
+ l: Number(n & U32_MASK64) | 0
2632
+ };
2633
+ }
2634
+ function split(lst, le = false) {
2635
+ const len = lst.length;
2636
+ const Ah = new Uint32Array(len);
2637
+ const Al = new Uint32Array(len);
2638
+ for (let i = 0; i < len; i++) {
2639
+ const { h: h2, l } = fromBig(lst[i], le);
2640
+ [Ah[i], Al[i]] = [h2, l];
2641
+ }
2642
+ return [Ah, Al];
2643
+ }
2644
+ var rotlSH = (h2, l, s) => h2 << s | l >>> 32 - s;
2645
+ var rotlSL = (h2, l, s) => l << s | h2 >>> 32 - s;
2646
+ var rotlBH = (h2, l, s) => l << s - 32 | h2 >>> 64 - s;
2647
+ var rotlBL = (h2, l, s) => h2 << s - 32 | l >>> 64 - s;
2648
+
2649
+ // node_modules/mlkem/esm/src/sha3/utils.js
2650
+ function isBytes(a) {
2651
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
2652
+ }
2653
+ function anumber(n, title = "") {
2654
+ if (!Number.isSafeInteger(n) || n < 0) {
2655
+ const prefix = title && `"${title}" `;
2656
+ throw new Error(`${prefix}expected integer >0, got ${n}`);
2657
+ }
2658
+ }
2659
+ function abytes(value, length, title = "") {
2660
+ const bytes = isBytes(value);
2661
+ const len = value?.length;
2662
+ const needsLen = length !== void 0;
2663
+ if (!bytes || needsLen && len !== length) {
2664
+ const prefix = title && `"${title}" `;
2665
+ const ofLen = needsLen ? ` of length ${length}` : "";
2666
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
2667
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
2668
+ }
2669
+ return value;
2670
+ }
2671
+ function aexists(instance, checkFinished = true) {
2672
+ if (instance.destroyed)
2673
+ throw new Error("Hash instance has been destroyed");
2674
+ if (checkFinished && instance.finished) {
2675
+ throw new Error("Hash#digest() has already been called");
2676
+ }
2677
+ }
2678
+ function aoutput(out, instance) {
2679
+ abytes(out, void 0, "digestInto() output");
2680
+ const min = instance.outputLen;
2681
+ if (out.length < min) {
2682
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
2683
+ }
2684
+ }
2685
+ function u32(arr) {
2686
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
2687
+ }
2688
+ function clean(...arrays) {
2689
+ for (let i = 0; i < arrays.length; i++) {
2690
+ arrays[i].fill(0);
2691
+ }
2692
+ }
2693
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
2694
+ function byteSwap(word) {
2695
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
2696
+ }
2697
+ function byteSwap32(arr) {
2698
+ for (let i = 0; i < arr.length; i++) {
2699
+ arr[i] = byteSwap(arr[i]);
2700
+ }
2701
+ return arr;
2702
+ }
2703
+ var swap32IfBE = isLE ? (u) => u : byteSwap32;
2704
+ function createHasher(hashCons, info = {}) {
2705
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
2706
+ const tmp = hashCons(void 0);
2707
+ hashC.outputLen = tmp.outputLen;
2708
+ hashC.blockLen = tmp.blockLen;
2709
+ hashC.create = (opts) => hashCons(opts);
2710
+ Object.assign(hashC, info);
2711
+ return Object.freeze(hashC);
2712
+ }
2713
+ var oidNist = (suffix) => ({
2714
+ oid: Uint8Array.from([
2715
+ 6,
2716
+ 9,
2717
+ 96,
2718
+ 134,
2719
+ 72,
2720
+ 1,
2721
+ 101,
2722
+ 3,
2723
+ 4,
2724
+ 2,
2725
+ suffix
2726
+ ])
2727
+ });
2728
+
2729
+ // node_modules/mlkem/esm/src/sha3/sha3.js
2730
+ var _0n = BigInt(0);
2731
+ var _1n = BigInt(1);
2732
+ var _2n = BigInt(2);
2733
+ var _7n = BigInt(7);
2734
+ var _256n = BigInt(256);
2735
+ var _0x71n = BigInt(113);
2736
+ var SHA3_PI = [];
2737
+ var SHA3_ROTL = [];
2738
+ var _SHA3_IOTA = [];
2739
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
2740
+ [x, y] = [y, (2 * x + 3 * y) % 5];
2741
+ SHA3_PI.push(2 * (5 * y + x));
2742
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
2743
+ let t = _0n;
2744
+ for (let j = 0; j < 7; j++) {
2745
+ R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
2746
+ if (R & _2n)
2747
+ t ^= _1n << (_1n << BigInt(j)) - _1n;
2748
+ }
2749
+ _SHA3_IOTA.push(t);
2750
+ }
2751
+ var IOTAS = split(_SHA3_IOTA, true);
2752
+ var SHA3_IOTA_H = IOTAS[0];
2753
+ var SHA3_IOTA_L = IOTAS[1];
2754
+ var rotlH = (h2, l, s) => s > 32 ? rotlBH(h2, l, s) : rotlSH(h2, l, s);
2755
+ var rotlL = (h2, l, s) => s > 32 ? rotlBL(h2, l, s) : rotlSL(h2, l, s);
2756
+ function keccakP(s, rounds = 24) {
2757
+ const B = new Uint32Array(5 * 2);
2758
+ for (let round = 24 - rounds; round < 24; round++) {
2759
+ for (let x = 0; x < 10; x++) {
2760
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
2761
+ }
2762
+ for (let x = 0; x < 10; x += 2) {
2763
+ const idx1 = (x + 8) % 10;
2764
+ const idx0 = (x + 2) % 10;
2765
+ const B0 = B[idx0];
2766
+ const B1 = B[idx0 + 1];
2767
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
2768
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
2769
+ for (let y = 0; y < 50; y += 10) {
2770
+ s[x + y] ^= Th;
2771
+ s[x + y + 1] ^= Tl;
2772
+ }
2773
+ }
2774
+ let curH = s[2];
2775
+ let curL = s[3];
2776
+ for (let t = 0; t < 24; t++) {
2777
+ const shift = SHA3_ROTL[t];
2778
+ const Th = rotlH(curH, curL, shift);
2779
+ const Tl = rotlL(curH, curL, shift);
2780
+ const PI = SHA3_PI[t];
2781
+ curH = s[PI];
2782
+ curL = s[PI + 1];
2783
+ s[PI] = Th;
2784
+ s[PI + 1] = Tl;
2785
+ }
2786
+ for (let y = 0; y < 50; y += 10) {
2787
+ for (let x = 0; x < 10; x++)
2788
+ B[x] = s[y + x];
2789
+ for (let x = 0; x < 10; x++) {
2790
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
2791
+ }
2792
+ }
2793
+ s[0] ^= SHA3_IOTA_H[round];
2794
+ s[1] ^= SHA3_IOTA_L[round];
2795
+ }
2796
+ clean(B);
2797
+ }
2798
+ var Keccak = class _Keccak {
2799
+ // NOTE: we accept arguments in bytes instead of bits here.
2800
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
2801
+ Object.defineProperty(this, "state", {
2802
+ enumerable: true,
2803
+ configurable: true,
2804
+ writable: true,
2805
+ value: void 0
2806
+ });
2807
+ Object.defineProperty(this, "pos", {
2808
+ enumerable: true,
2809
+ configurable: true,
2810
+ writable: true,
2811
+ value: 0
2812
+ });
2813
+ Object.defineProperty(this, "posOut", {
2814
+ enumerable: true,
2815
+ configurable: true,
2816
+ writable: true,
2817
+ value: 0
2818
+ });
2819
+ Object.defineProperty(this, "finished", {
2820
+ enumerable: true,
2821
+ configurable: true,
2822
+ writable: true,
2823
+ value: false
2824
+ });
2825
+ Object.defineProperty(this, "state32", {
2826
+ enumerable: true,
2827
+ configurable: true,
2828
+ writable: true,
2829
+ value: void 0
2830
+ });
2831
+ Object.defineProperty(this, "destroyed", {
2832
+ enumerable: true,
2833
+ configurable: true,
2834
+ writable: true,
2835
+ value: false
2836
+ });
2837
+ Object.defineProperty(this, "blockLen", {
2838
+ enumerable: true,
2839
+ configurable: true,
2840
+ writable: true,
2841
+ value: void 0
2842
+ });
2843
+ Object.defineProperty(this, "suffix", {
2844
+ enumerable: true,
2845
+ configurable: true,
2846
+ writable: true,
2847
+ value: void 0
2848
+ });
2849
+ Object.defineProperty(this, "outputLen", {
2850
+ enumerable: true,
2851
+ configurable: true,
2852
+ writable: true,
2853
+ value: void 0
2854
+ });
2855
+ Object.defineProperty(this, "enableXOF", {
2856
+ enumerable: true,
2857
+ configurable: true,
2858
+ writable: true,
2859
+ value: false
2860
+ });
2861
+ Object.defineProperty(this, "rounds", {
2862
+ enumerable: true,
2863
+ configurable: true,
2864
+ writable: true,
2865
+ value: void 0
2866
+ });
2867
+ this.blockLen = blockLen;
2868
+ this.suffix = suffix;
2869
+ this.outputLen = outputLen;
2870
+ this.enableXOF = enableXOF;
2871
+ this.rounds = rounds;
2872
+ anumber(outputLen, "outputLen");
2873
+ if (!(0 < blockLen && blockLen < 200)) {
2874
+ throw new Error("only keccak-f1600 function is supported");
2875
+ }
2876
+ this.state = new Uint8Array(200);
2877
+ this.state32 = u32(this.state);
2878
+ }
2879
+ clone() {
2880
+ return this._cloneInto();
2881
+ }
2882
+ keccak() {
2883
+ swap32IfBE(this.state32);
2884
+ keccakP(this.state32, this.rounds);
2885
+ swap32IfBE(this.state32);
2886
+ this.posOut = 0;
2887
+ this.pos = 0;
2888
+ }
2889
+ update(data) {
2890
+ aexists(this);
2891
+ abytes(data);
2892
+ const { blockLen, state } = this;
2893
+ const len = data.length;
2894
+ for (let pos = 0; pos < len; ) {
2895
+ const take = Math.min(blockLen - this.pos, len - pos);
2896
+ for (let i = 0; i < take; i++)
2897
+ state[this.pos++] ^= data[pos++];
2898
+ if (this.pos === blockLen)
2899
+ this.keccak();
2900
+ }
2901
+ return this;
2902
+ }
2903
+ finish() {
2904
+ if (this.finished)
2905
+ return;
2906
+ this.finished = true;
2907
+ const { state, suffix, pos, blockLen } = this;
2908
+ state[pos] ^= suffix;
2909
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
2910
+ this.keccak();
2911
+ state[blockLen - 1] ^= 128;
2912
+ this.keccak();
2913
+ }
2914
+ writeInto(out) {
2915
+ aexists(this, false);
2916
+ abytes(out);
2917
+ this.finish();
2918
+ const bufferOut = this.state;
2919
+ const { blockLen } = this;
2920
+ for (let pos = 0, len = out.length; pos < len; ) {
2921
+ if (this.posOut >= blockLen)
2922
+ this.keccak();
2923
+ const take = Math.min(blockLen - this.posOut, len - pos);
2924
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
2925
+ this.posOut += take;
2926
+ pos += take;
2927
+ }
2928
+ return out;
2929
+ }
2930
+ xofInto(out) {
2931
+ if (!this.enableXOF) {
2932
+ throw new Error("XOF is not possible for this instance");
2933
+ }
2934
+ return this.writeInto(out);
2935
+ }
2936
+ xof(bytes) {
2937
+ anumber(bytes);
2938
+ return this.xofInto(new Uint8Array(bytes));
2939
+ }
2940
+ digestInto(out) {
2941
+ aoutput(out, this);
2942
+ if (this.finished)
2943
+ throw new Error("digest() was already called");
2944
+ this.writeInto(out);
2945
+ this.destroy();
2946
+ return out;
2947
+ }
2948
+ digest() {
2949
+ return this.digestInto(new Uint8Array(this.outputLen));
2950
+ }
2951
+ destroy() {
2952
+ this.destroyed = true;
2953
+ clean(this.state);
2954
+ }
2955
+ _cloneInto(to) {
2956
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
2957
+ to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
2958
+ to.state32.set(this.state32);
2959
+ to.pos = this.pos;
2960
+ to.posOut = this.posOut;
2961
+ to.finished = this.finished;
2962
+ to.rounds = rounds;
2963
+ to.suffix = suffix;
2964
+ to.outputLen = outputLen;
2965
+ to.enableXOF = enableXOF;
2966
+ to.destroyed = this.destroyed;
2967
+ return to;
2968
+ }
2969
+ };
2970
+ var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
2971
+ var sha3_256 = /* @__PURE__ */ genKeccak(
2972
+ 6,
2973
+ 136,
2974
+ 32,
2975
+ /* @__PURE__ */ oidNist(8)
2976
+ );
2977
+ var sha3_512 = /* @__PURE__ */ genKeccak(
2978
+ 6,
2979
+ 72,
2980
+ 64,
2981
+ /* @__PURE__ */ oidNist(10)
2982
+ );
2983
+ var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true), info);
2984
+ var shake128 = /* @__PURE__ */ genShake(31, 168, 16, /* @__PURE__ */ oidNist(11));
2985
+ var shake256 = /* @__PURE__ */ genShake(31, 136, 32, /* @__PURE__ */ oidNist(12));
2986
+
2987
+ // node_modules/mlkem/esm/_dnt.shims.js
2988
+ var dntGlobals = {};
2989
+ var dntGlobalThis = createMergeProxy(globalThis, dntGlobals);
2990
+ function createMergeProxy(baseObj, extObj) {
2991
+ return new Proxy(baseObj, {
2992
+ get(_target, prop, _receiver) {
2993
+ if (prop in extObj) {
2994
+ return extObj[prop];
2995
+ } else {
2996
+ return baseObj[prop];
2997
+ }
2998
+ },
2999
+ set(_target, prop, value) {
3000
+ if (prop in extObj) {
3001
+ delete extObj[prop];
3002
+ }
3003
+ baseObj[prop] = value;
3004
+ return true;
3005
+ },
3006
+ deleteProperty(_target, prop) {
3007
+ let success = false;
3008
+ if (prop in extObj) {
3009
+ delete extObj[prop];
3010
+ success = true;
3011
+ }
3012
+ if (prop in baseObj) {
3013
+ delete baseObj[prop];
3014
+ success = true;
3015
+ }
3016
+ return success;
3017
+ },
3018
+ ownKeys(_target) {
3019
+ const baseKeys = Reflect.ownKeys(baseObj);
3020
+ const extKeys = Reflect.ownKeys(extObj);
3021
+ const extKeysSet = new Set(extKeys);
3022
+ return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];
3023
+ },
3024
+ defineProperty(_target, prop, desc) {
3025
+ if (prop in extObj) {
3026
+ delete extObj[prop];
3027
+ }
3028
+ Reflect.defineProperty(baseObj, prop, desc);
3029
+ return true;
3030
+ },
3031
+ getOwnPropertyDescriptor(_target, prop) {
3032
+ if (prop in extObj) {
3033
+ return Reflect.getOwnPropertyDescriptor(extObj, prop);
3034
+ } else {
3035
+ return Reflect.getOwnPropertyDescriptor(baseObj, prop);
3036
+ }
3037
+ },
3038
+ has(_target, prop) {
3039
+ return prop in extObj || prop in baseObj;
3040
+ }
3041
+ });
3042
+ }
3043
+
3044
+ // node_modules/mlkem/esm/src/utils.js
3045
+ function byte(n) {
3046
+ return n % 256;
3047
+ }
3048
+ function int16(n) {
3049
+ const end = -32768;
3050
+ const start = 32767;
3051
+ if (n >= end && n <= start) {
3052
+ return n;
3053
+ }
3054
+ if (n < end) {
3055
+ n = n + 32769;
3056
+ n = n % 65536;
3057
+ return start + n;
3058
+ }
3059
+ n = n - 32768;
3060
+ n = n % 65536;
3061
+ return end + n;
3062
+ }
3063
+ function uint16(n) {
3064
+ return n % 65536;
3065
+ }
3066
+ function int32(n) {
3067
+ const end = -2147483648;
3068
+ const start = 2147483647;
3069
+ if (n >= end && n <= start) {
3070
+ return n;
3071
+ }
3072
+ if (n < end) {
3073
+ n = n + 2147483649;
3074
+ n = n % 4294967296;
3075
+ return start + n;
3076
+ }
3077
+ n = n - 2147483648;
3078
+ n = n % 4294967296;
3079
+ return end + n;
3080
+ }
3081
+ function uint32(n) {
3082
+ return n % 4294967296;
3083
+ }
3084
+ function constantTimeCompare(x, y) {
3085
+ if (x.length != y.length) {
3086
+ return 0;
3087
+ }
3088
+ const v = new Uint8Array([0]);
3089
+ for (let i = 0; i < x.length; i++) {
3090
+ v[0] |= x[i] ^ y[i];
3091
+ }
3092
+ const z = new Uint8Array([0]);
3093
+ z[0] = ~(v[0] ^ z[0]);
3094
+ z[0] &= z[0] >> 4;
3095
+ z[0] &= z[0] >> 2;
3096
+ z[0] &= z[0] >> 1;
3097
+ return z[0];
3098
+ }
3099
+ function equalUint8Array(x, y) {
3100
+ if (x.length != y.length) {
3101
+ return false;
3102
+ }
3103
+ for (let i = 0; i < x.length; i++) {
3104
+ if (x[i] !== y[i]) {
3105
+ return false;
3106
+ }
3107
+ }
3108
+ return true;
3109
+ }
3110
+ async function loadCrypto() {
3111
+ if (typeof dntGlobalThis !== "undefined" && globalThis.crypto !== void 0) {
3112
+ return globalThis.crypto;
3113
+ }
3114
+ try {
3115
+ const { webcrypto } = await import("crypto");
3116
+ return webcrypto;
3117
+ } catch (_e) {
3118
+ throw new Error("failed to load Crypto");
3119
+ }
3120
+ }
3121
+ function prf(len, seed, nonce) {
3122
+ return shake256.create({ dkLen: len }).update(seed).update(new Uint8Array([nonce])).digest();
3123
+ }
3124
+ function byteopsLoad32(x) {
3125
+ let r = uint32(x[0]);
3126
+ r |= uint32(x[1]) << 8;
3127
+ r |= uint32(x[2]) << 16;
3128
+ r |= uint32(x[3]) << 24;
3129
+ return uint32(r);
3130
+ }
3131
+
3132
+ // node_modules/mlkem/esm/src/mlKemBase.js
3133
+ var MlKemBase = class {
3134
+ /**
3135
+ * Creates a new instance of the MlKemBase class.
3136
+ */
3137
+ constructor() {
3138
+ Object.defineProperty(this, "_api", {
3139
+ enumerable: true,
3140
+ configurable: true,
3141
+ writable: true,
3142
+ value: void 0
3143
+ });
3144
+ Object.defineProperty(this, "_k", {
3145
+ enumerable: true,
3146
+ configurable: true,
3147
+ writable: true,
3148
+ value: 0
3149
+ });
3150
+ Object.defineProperty(this, "_du", {
3151
+ enumerable: true,
3152
+ configurable: true,
3153
+ writable: true,
3154
+ value: 0
3155
+ });
3156
+ Object.defineProperty(this, "_dv", {
3157
+ enumerable: true,
3158
+ configurable: true,
3159
+ writable: true,
3160
+ value: 0
3161
+ });
3162
+ Object.defineProperty(this, "_eta1", {
3163
+ enumerable: true,
3164
+ configurable: true,
3165
+ writable: true,
3166
+ value: 0
3167
+ });
3168
+ Object.defineProperty(this, "_eta2", {
3169
+ enumerable: true,
3170
+ configurable: true,
3171
+ writable: true,
3172
+ value: 0
3173
+ });
3174
+ Object.defineProperty(this, "_skSize", {
3175
+ enumerable: true,
3176
+ configurable: true,
3177
+ writable: true,
3178
+ value: 0
3179
+ });
3180
+ Object.defineProperty(this, "_pkSize", {
3181
+ enumerable: true,
3182
+ configurable: true,
3183
+ writable: true,
3184
+ value: 0
3185
+ });
3186
+ Object.defineProperty(this, "_compressedUSize", {
3187
+ enumerable: true,
3188
+ configurable: true,
3189
+ writable: true,
3190
+ value: 0
3191
+ });
3192
+ Object.defineProperty(this, "_compressedVSize", {
3193
+ enumerable: true,
3194
+ configurable: true,
3195
+ writable: true,
3196
+ value: 0
3197
+ });
3198
+ }
3199
+ /**
3200
+ * Generates a keypair [publicKey, privateKey].
3201
+ *
3202
+ * If an error occurred, throws {@link MlKemError}.
3203
+ *
3204
+ * @returns A kaypair [publicKey, privateKey].
3205
+ * @throws {@link MlKemError}
3206
+ *
3207
+ * @example Generates a {@link MlKem768} keypair.
3208
+ *
3209
+ * ```ts
3210
+ * // Using jsr:
3211
+ * import { MlKem768 } from "@dajiaji/mlkem";
3212
+ * // Using npm:
3213
+ * // import { MlKem768 } from "mlkem"; // or "crystals-kyber-js"
3214
+ *
3215
+ * const kyber = new MlKem768();
3216
+ * const [pk, sk] = await kyber.generateKeyPair();
3217
+ * ```
3218
+ */
3219
+ async generateKeyPair() {
3220
+ await this._setup();
3221
+ try {
3222
+ const rnd = new Uint8Array(64);
3223
+ this._api.getRandomValues(rnd);
3224
+ return this._deriveKeyPair(rnd);
3225
+ } catch (e) {
3226
+ throw new MlKemError(e);
3227
+ }
3228
+ }
3229
+ /**
3230
+ * Derives a keypair [publicKey, privateKey] deterministically from a 64-octet seed.
3231
+ *
3232
+ * If an error occurred, throws {@link MlKemError}.
3233
+ *
3234
+ * @param seed A 64-octet seed for the deterministic key generation.
3235
+ * @returns A kaypair [publicKey, privateKey].
3236
+ * @throws {@link MlKemError}
3237
+ *
3238
+ * @example Derives a {@link MlKem768} keypair deterministically.
3239
+ *
3240
+ * ```ts
3241
+ * // Using jsr:
3242
+ * import { MlKem768 } from "@dajiaji/mlkem";
3243
+ * // Using npm:
3244
+ * // import { MlKem768 } from "mlkem"; // or "crystals-kyber-js"
3245
+ *
3246
+ * const kyber = new MlKem768();
3247
+ * const seed = new Uint8Array(64);
3248
+ * globalThis.crypto.getRandomValues(seed);
3249
+ * const [pk, sk] = await kyber.deriveKeyPair(seed);
3250
+ * ```
3251
+ */
3252
+ async deriveKeyPair(seed) {
3253
+ await this._setup();
3254
+ try {
3255
+ if (seed.byteLength !== 64) {
3256
+ throw new Error("seed must be 64 bytes in length");
3257
+ }
3258
+ return this._deriveKeyPair(seed);
3259
+ } catch (e) {
3260
+ throw new MlKemError(e);
3261
+ }
3262
+ }
3263
+ /**
3264
+ * Generates a shared secret from the encapsulated ciphertext and the private key.
3265
+ *
3266
+ * If an error occurred, throws {@link MlKemError}.
3267
+ *
3268
+ * @param pk A public key.
3269
+ * @param seed An optional 32-octet seed for the deterministic shared secret generation.
3270
+ * @returns A ciphertext (encapsulated public key) and a shared secret.
3271
+ * @throws {@link MlKemError}
3272
+ *
3273
+ * @example The {@link MlKem768} encapsulation.
3274
+ *
3275
+ * ```ts
3276
+ * // Using jsr:
3277
+ * import { MlKem768 } from "@dajiaji/mlkem";
3278
+ * // Using npm:
3279
+ * // import { MlKem768 } from "mlkem"; // or "crystals-kyber-js"
3280
+ *
3281
+ * const kyber = new MlKem768();
3282
+ * const [pk, sk] = await kyber.generateKeyPair();
3283
+ * const [ct, ss] = await kyber.encap(pk);
3284
+ * ```
3285
+ */
3286
+ async encap(pk, seed) {
3287
+ await this._setup();
3288
+ try {
3289
+ if (pk.length !== 384 * this._k + 32) {
3290
+ throw new Error("invalid encapsulation key");
3291
+ }
3292
+ const m = this._getSeed(seed);
3293
+ const [k, r] = g(m, h(pk));
3294
+ const ct = this._encap(pk, m, r);
3295
+ return [ct, k];
3296
+ } catch (e) {
3297
+ throw new MlKemError(e);
3298
+ }
3299
+ }
3300
+ /**
3301
+ * Generates a ciphertext for the public key and a shared secret.
3302
+ *
3303
+ * If an error occurred, throws {@link MlKemError}.
3304
+ *
3305
+ * @param ct A ciphertext generated by {@link encap}.
3306
+ * @param sk A private key.
3307
+ * @returns A shared secret.
3308
+ * @throws {@link MlKemError}
3309
+ *
3310
+ * @example The {@link MlKem768} decapsulation.
3311
+ *
3312
+ * ```ts
3313
+ * // Using jsr:
3314
+ * import { MlKem768 } from "@dajiaji/mlkem";
3315
+ * // Using npm:
3316
+ * // import { MlKem768 } from "mlkem"; // or "crystals-kyber-js"
3317
+ *
3318
+ * const kyber = new MlKem768();
3319
+ * const [pk, sk] = await kyber.generateKeyPair();
3320
+ * const [ct, ssS] = await kyber.encap(pk);
3321
+ * const ssR = await kyber.decap(ct, sk);
3322
+ * // ssS === ssR
3323
+ * ```
3324
+ */
3325
+ async decap(ct, sk) {
3326
+ await this._setup();
3327
+ try {
3328
+ if (ct.byteLength !== this._compressedUSize + this._compressedVSize) {
3329
+ throw new Error("Invalid ct size");
3330
+ }
3331
+ if (sk.length !== 768 * this._k + 96) {
3332
+ throw new Error("Invalid decapsulation key");
3333
+ }
3334
+ const sk2 = sk.subarray(0, this._skSize);
3335
+ const pk = sk.subarray(this._skSize, this._skSize + this._pkSize);
3336
+ const hpk = sk.subarray(this._skSize + this._pkSize, this._skSize + this._pkSize + 32);
3337
+ const z = sk.subarray(this._skSize + this._pkSize + 32, this._skSize + this._pkSize + 64);
3338
+ const m2 = this._decap(ct, sk2);
3339
+ const [k2, r2] = g(m2, hpk);
3340
+ const kBar = kdf(z, ct);
3341
+ const ct2 = this._encap(pk, m2, r2);
3342
+ return constantTimeCompare(ct, ct2) === 1 ? k2 : kBar;
3343
+ } catch (e) {
3344
+ throw new MlKemError(e);
3345
+ }
3346
+ }
3347
+ /**
3348
+ * Sets up the MlKemBase instance by loading the necessary crypto library.
3349
+ * If the crypto library is already loaded, this method does nothing.
3350
+ * @returns {Promise<void>} A promise that resolves when the setup is complete.
3351
+ */
3352
+ async _setup() {
3353
+ if (this._api !== void 0) {
3354
+ return;
3355
+ }
3356
+ this._api = await loadCrypto();
3357
+ }
3358
+ /**
3359
+ * Returns a Uint8Array seed for cryptographic operations.
3360
+ * If no seed is provided, a random seed of length 32 bytes is generated.
3361
+ * If a seed is provided, it must be exactly 32 bytes in length.
3362
+ *
3363
+ * @param seed - Optional seed for cryptographic operations.
3364
+ * @returns A Uint8Array seed.
3365
+ * @throws Error if the provided seed is not 32 bytes in length.
3366
+ */
3367
+ _getSeed(seed) {
3368
+ if (seed == void 0) {
3369
+ const s = new Uint8Array(32);
3370
+ this._api.getRandomValues(s);
3371
+ return s;
3372
+ }
3373
+ if (seed.byteLength !== 32) {
3374
+ throw new Error("seed must be 32 bytes in length");
3375
+ }
3376
+ return seed;
3377
+ }
3378
+ /**
3379
+ * Derives a key pair from a given seed.
3380
+ *
3381
+ * @param seed - The seed used for key derivation.
3382
+ * @returns An array containing the public key and secret key.
3383
+ */
3384
+ _deriveKeyPair(seed) {
3385
+ const cpaSeed = seed.subarray(0, 32);
3386
+ const z = seed.subarray(32, 64);
3387
+ const [pk, skBody] = this._deriveCpaKeyPair(cpaSeed);
3388
+ const pkh = h(pk);
3389
+ const sk = new Uint8Array(this._skSize + this._pkSize + 64);
3390
+ sk.set(skBody, 0);
3391
+ sk.set(pk, this._skSize);
3392
+ sk.set(pkh, this._skSize + this._pkSize);
3393
+ sk.set(z, this._skSize + this._pkSize + 32);
3394
+ return [pk, sk];
3395
+ }
3396
+ // indcpaKeyGen generates public and private keys for the CPA-secure
3397
+ // public-key encryption scheme underlying ML-KEM.
3398
+ /**
3399
+ * Derives a CPA key pair using the provided CPA seed.
3400
+ *
3401
+ * @param cpaSeed - The CPA seed used for key derivation.
3402
+ * @returns An array containing the public key and private key.
3403
+ */
3404
+ _deriveCpaKeyPair(cpaSeed) {
3405
+ const [publicSeed, noiseSeed] = g(cpaSeed, new Uint8Array([this._k]));
3406
+ const a = this._sampleMatrix(publicSeed, false);
3407
+ const s = this._sampleNoise1(noiseSeed, 0, this._k);
3408
+ const e = this._sampleNoise1(noiseSeed, this._k, this._k);
3409
+ for (let i = 0; i < this._k; i++) {
3410
+ s[i] = ntt(s[i]);
3411
+ s[i] = reduce(s[i]);
3412
+ e[i] = ntt(e[i]);
3413
+ }
3414
+ const pk = new Array(this._k);
3415
+ for (let i = 0; i < this._k; i++) {
3416
+ pk[i] = polyToMont(multiply(a[i], s));
3417
+ pk[i] = add(pk[i], e[i]);
3418
+ pk[i] = reduce(pk[i]);
3419
+ }
3420
+ const pubKey = new Uint8Array(this._pkSize);
3421
+ for (let i = 0; i < this._k; i++) {
3422
+ pubKey.set(polyToBytes(pk[i]), i * 384);
3423
+ }
3424
+ pubKey.set(publicSeed, this._skSize);
3425
+ const privKey = new Uint8Array(this._skSize);
3426
+ for (let i = 0; i < this._k; i++) {
3427
+ privKey.set(polyToBytes(s[i]), i * 384);
3428
+ }
3429
+ return [pubKey, privKey];
3430
+ }
3431
+ // _encap is the encapsulation function of the CPA-secure
3432
+ // public-key encryption scheme underlying ML-KEM.
3433
+ /**
3434
+ * Encapsulates a message using the ML-KEM encryption scheme.
3435
+ *
3436
+ * @param pk - The public key.
3437
+ * @param msg - The message to be encapsulated.
3438
+ * @param seed - The seed used for generating random values.
3439
+ * @returns The encapsulated message as a Uint8Array.
3440
+ */
3441
+ _encap(pk, msg, seed) {
3442
+ const tHat = new Array(this._k);
3443
+ const pkCheck = new Uint8Array(384 * this._k);
3444
+ for (let i = 0; i < this._k; i++) {
3445
+ tHat[i] = polyFromBytes(pk.subarray(i * 384, (i + 1) * 384));
3446
+ pkCheck.set(polyToBytes(tHat[i]), i * 384);
3447
+ }
3448
+ if (!equalUint8Array(pk.subarray(0, pkCheck.length), pkCheck)) {
3449
+ throw new Error("invalid encapsulation key");
3450
+ }
3451
+ const rho = pk.subarray(this._skSize);
3452
+ const a = this._sampleMatrix(rho, true);
3453
+ const r = this._sampleNoise1(seed, 0, this._k);
3454
+ const e1 = this._sampleNoise2(seed, this._k, this._k);
3455
+ const e2 = this._sampleNoise2(seed, this._k * 2, 1)[0];
3456
+ for (let i = 0; i < this._k; i++) {
3457
+ r[i] = ntt(r[i]);
3458
+ r[i] = reduce(r[i]);
3459
+ }
3460
+ const u = new Array(this._k);
3461
+ for (let i = 0; i < this._k; i++) {
3462
+ u[i] = multiply(a[i], r);
3463
+ u[i] = nttInverse(u[i]);
3464
+ u[i] = add(u[i], e1[i]);
3465
+ u[i] = reduce(u[i]);
3466
+ }
3467
+ const m = polyFromMsg(msg);
3468
+ let v = multiply(tHat, r);
3469
+ v = nttInverse(v);
3470
+ v = add(v, e2);
3471
+ v = add(v, m);
3472
+ v = reduce(v);
3473
+ const ret = new Uint8Array(this._compressedUSize + this._compressedVSize);
3474
+ this._compressU(ret.subarray(0, this._compressedUSize), u);
3475
+ this._compressV(ret.subarray(this._compressedUSize), v);
3476
+ return ret;
3477
+ }
3478
+ // indcpaDecrypt is the decryption function of the CPA-secure
3479
+ // public-key encryption scheme underlying ML-KEM.
3480
+ /**
3481
+ * Decapsulates the ciphertext using the provided secret key.
3482
+ *
3483
+ * @param ct - The ciphertext to be decapsulated.
3484
+ * @param sk - The secret key used for decapsulation.
3485
+ * @returns The decapsulated message as a Uint8Array.
3486
+ */
3487
+ _decap(ct, sk) {
3488
+ const u = this._decompressU(ct.subarray(0, this._compressedUSize));
3489
+ const v = this._decompressV(ct.subarray(this._compressedUSize));
3490
+ const privateKeyPolyvec = this._polyvecFromBytes(sk);
3491
+ for (let i = 0; i < this._k; i++) {
3492
+ u[i] = ntt(u[i]);
3493
+ }
3494
+ let mp = multiply(privateKeyPolyvec, u);
3495
+ mp = nttInverse(mp);
3496
+ mp = subtract(v, mp);
3497
+ mp = reduce(mp);
3498
+ return polyToMsg(mp);
3499
+ }
3500
+ // generateMatrixA deterministically generates a matrix `A` (or the transpose of `A`)
3501
+ // from a seed. Entries of the matrix are polynomials that look uniformly random.
3502
+ // Performs rejection sampling on the output of an extendable-output function (XOF).
3503
+ /**
3504
+ * Generates a sample matrix based on the provided seed and transposition flag.
3505
+ *
3506
+ * @param seed - The seed used for generating the matrix.
3507
+ * @param transposed - A flag indicating whether the matrix should be transposed or not.
3508
+ * @returns The generated sample matrix.
3509
+ */
3510
+ _sampleMatrix(seed, transposed) {
3511
+ const a = new Array(this._k);
3512
+ const transpose = new Uint8Array(2);
3513
+ for (let ctr = 0, i = 0; i < this._k; i++) {
3514
+ a[i] = new Array(this._k);
3515
+ for (let j = 0; j < this._k; j++) {
3516
+ if (transposed) {
3517
+ transpose[0] = i;
3518
+ transpose[1] = j;
3519
+ } else {
3520
+ transpose[0] = j;
3521
+ transpose[1] = i;
3522
+ }
3523
+ const output = xof(seed, transpose);
3524
+ const result = indcpaRejUniform(output.subarray(0, 504), 504, N);
3525
+ a[i][j] = result[0];
3526
+ ctr = result[1];
3527
+ while (ctr < N) {
3528
+ const outputn = output.subarray(504, 672);
3529
+ const result1 = indcpaRejUniform(outputn, 168, N - ctr);
3530
+ const missing = result1[0];
3531
+ const ctrn = result1[1];
3532
+ for (let k = ctr; k < N; k++) {
3533
+ a[i][j][k] = missing[k - ctr];
3534
+ }
3535
+ ctr = ctr + ctrn;
3536
+ }
3537
+ }
3538
+ }
3539
+ return a;
3540
+ }
3541
+ /**
3542
+ * Generates a 2D array of noise samples.
3543
+ *
3544
+ * @param sigma - The noise parameter.
3545
+ * @param offset - The offset value.
3546
+ * @param size - The size of the array.
3547
+ * @returns The generated 2D array of noise samples.
3548
+ */
3549
+ _sampleNoise1(sigma, offset, size) {
3550
+ const r = new Array(size);
3551
+ for (let i = 0; i < size; i++) {
3552
+ r[i] = byteopsCbd(prf(this._eta1 * N / 4, sigma, offset), this._eta1);
3553
+ offset++;
3554
+ }
3555
+ return r;
3556
+ }
3557
+ /**
3558
+ * Generates a 2-dimensional array of noise samples.
3559
+ *
3560
+ * @param sigma - The noise parameter.
3561
+ * @param offset - The offset value.
3562
+ * @param size - The size of the array.
3563
+ * @returns The generated 2-dimensional array of noise samples.
3564
+ */
3565
+ _sampleNoise2(sigma, offset, size) {
3566
+ const r = new Array(size);
3567
+ for (let i = 0; i < size; i++) {
3568
+ r[i] = byteopsCbd(prf(this._eta2 * N / 4, sigma, offset), this._eta2);
3569
+ offset++;
3570
+ }
3571
+ return r;
3572
+ }
3573
+ // polyvecFromBytes deserializes a vector of polynomials.
3574
+ /**
3575
+ * Converts a Uint8Array to a 2D array of numbers representing a polynomial vector.
3576
+ * Each element in the resulting array represents a polynomial.
3577
+ * @param a The Uint8Array to convert.
3578
+ * @returns The 2D array of numbers representing the polynomial vector.
3579
+ */
3580
+ _polyvecFromBytes(a) {
3581
+ const r = new Array(this._k);
3582
+ for (let i = 0; i < this._k; i++) {
3583
+ r[i] = polyFromBytes(a.subarray(i * 384, (i + 1) * 384));
3584
+ }
3585
+ return r;
3586
+ }
3587
+ // compressU lossily compresses and serializes a vector of polynomials.
3588
+ /**
3589
+ * Compresses the given array of coefficients into a Uint8Array.
3590
+ *
3591
+ * @param r - The output Uint8Array.
3592
+ * @param u - The array of coefficients.
3593
+ * @returns The compressed Uint8Array.
3594
+ */
3595
+ _compressU(r, u) {
3596
+ const t = new Array(4);
3597
+ for (let rr = 0, i = 0; i < this._k; i++) {
3598
+ for (let j = 0; j < N / 4; j++) {
3599
+ for (let k = 0; k < 4; k++) {
3600
+ t[k] = ((u[i][4 * j + k] << 10) + Q / 2) / Q & 1023;
3601
+ }
3602
+ r[rr++] = byte(t[0] >> 0);
3603
+ r[rr++] = byte(t[0] >> 8 | t[1] << 2);
3604
+ r[rr++] = byte(t[1] >> 6 | t[2] << 4);
3605
+ r[rr++] = byte(t[2] >> 4 | t[3] << 6);
3606
+ r[rr++] = byte(t[3] >> 2);
3607
+ }
3608
+ }
3609
+ return r;
3610
+ }
3611
+ // compressV lossily compresses and subsequently serializes a polynomial.
3612
+ /**
3613
+ * Compresses the given array of numbers into a Uint8Array.
3614
+ *
3615
+ * @param r - The Uint8Array to store the compressed values.
3616
+ * @param v - The array of numbers to compress.
3617
+ * @returns The compressed Uint8Array.
3618
+ */
3619
+ _compressV(r, v) {
3620
+ const t = new Uint8Array(8);
3621
+ for (let rr = 0, i = 0; i < N / 8; i++) {
3622
+ for (let j = 0; j < 8; j++) {
3623
+ t[j] = byte(((v[8 * i + j] << 4) + Q / 2) / Q) & 15;
3624
+ }
3625
+ r[rr++] = t[0] | t[1] << 4;
3626
+ r[rr++] = t[2] | t[3] << 4;
3627
+ r[rr++] = t[4] | t[5] << 4;
3628
+ r[rr++] = t[6] | t[7] << 4;
3629
+ }
3630
+ return r;
3631
+ }
3632
+ // decompressU de-serializes and decompresses a vector of polynomials and
3633
+ // represents the approximate inverse of compress1. Since compression is lossy,
3634
+ // the results of decompression will may not match the original vector of polynomials.
3635
+ /**
3636
+ * Decompresses a Uint8Array into a two-dimensional array of numbers.
3637
+ *
3638
+ * @param a The Uint8Array to decompress.
3639
+ * @returns The decompressed two-dimensional array.
3640
+ */
3641
+ _decompressU(a) {
3642
+ const r = new Array(this._k);
3643
+ for (let i = 0; i < this._k; i++) {
3644
+ r[i] = new Array(384);
3645
+ }
3646
+ const t = new Array(4);
3647
+ for (let aa = 0, i = 0; i < this._k; i++) {
3648
+ for (let j = 0; j < N / 4; j++) {
3649
+ t[0] = uint16(a[aa + 0]) >> 0 | uint16(a[aa + 1]) << 8;
3650
+ t[1] = uint16(a[aa + 1]) >> 2 | uint16(a[aa + 2]) << 6;
3651
+ t[2] = uint16(a[aa + 2]) >> 4 | uint16(a[aa + 3]) << 4;
3652
+ t[3] = uint16(a[aa + 3]) >> 6 | uint16(a[aa + 4]) << 2;
3653
+ aa = aa + 5;
3654
+ for (let k = 0; k < 4; k++) {
3655
+ r[i][4 * j + k] = int16(uint32(t[k] & 1023) * uint32(Q) + 512 >> 10);
3656
+ }
3657
+ }
3658
+ }
3659
+ return r;
3660
+ }
3661
+ // decompressV de-serializes and subsequently decompresses a polynomial,
3662
+ // representing the approximate inverse of compress2.
3663
+ // Note that compression is lossy, and thus decompression will not match the
3664
+ // original input.
3665
+ /**
3666
+ * Decompresses a Uint8Array into an array of numbers.
3667
+ *
3668
+ * @param a - The Uint8Array to decompress.
3669
+ * @returns An array of numbers.
3670
+ */
3671
+ _decompressV(a) {
3672
+ const r = new Array(384);
3673
+ for (let aa = 0, i = 0; i < N / 2; i++, aa++) {
3674
+ r[2 * i + 0] = int16(uint16(a[aa] & 15) * uint16(Q) + 8 >> 4);
3675
+ r[2 * i + 1] = int16(uint16(a[aa] >> 4) * uint16(Q) + 8 >> 4);
3676
+ }
3677
+ return r;
3678
+ }
3679
+ };
3680
+ function g(a, b) {
3681
+ const hash = sha3_512.create().update(a);
3682
+ if (b !== void 0) {
3683
+ hash.update(b);
3684
+ }
3685
+ const res = hash.digest();
3686
+ return [res.subarray(0, 32), res.subarray(32, 64)];
3687
+ }
3688
+ function h(msg) {
3689
+ return sha3_256.create().update(msg).digest();
3690
+ }
3691
+ function kdf(a, b) {
3692
+ const hash = shake256.create({ dkLen: 32 }).update(a);
3693
+ if (b !== void 0) {
3694
+ hash.update(b);
3695
+ }
3696
+ return hash.digest();
3697
+ }
3698
+ function xof(seed, transpose) {
3699
+ return shake128.create({ dkLen: 672 }).update(seed).update(transpose).digest();
3700
+ }
3701
+ function polyToBytes(a) {
3702
+ let t0 = 0;
3703
+ let t1 = 0;
3704
+ const r = new Uint8Array(384);
3705
+ const a2 = subtractQ(a);
3706
+ for (let i = 0; i < N / 2; i++) {
3707
+ t0 = uint16(a2[2 * i]);
3708
+ t1 = uint16(a2[2 * i + 1]);
3709
+ r[3 * i + 0] = byte(t0 >> 0);
3710
+ r[3 * i + 1] = byte(t0 >> 8) | byte(t1 << 4);
3711
+ r[3 * i + 2] = byte(t1 >> 4);
3712
+ }
3713
+ return r;
3714
+ }
3715
+ function polyFromBytes(a) {
3716
+ const r = new Array(384).fill(0);
3717
+ for (let i = 0; i < N / 2; i++) {
3718
+ r[2 * i] = int16((uint16(a[3 * i + 0]) >> 0 | uint16(a[3 * i + 1]) << 8) & 4095);
3719
+ r[2 * i + 1] = int16((uint16(a[3 * i + 1]) >> 4 | uint16(a[3 * i + 2]) << 4) & 4095);
3720
+ }
3721
+ return r;
3722
+ }
3723
+ function polyToMsg(a) {
3724
+ const msg = new Uint8Array(32);
3725
+ let t;
3726
+ const a2 = subtractQ(a);
3727
+ for (let i = 0; i < N / 8; i++) {
3728
+ msg[i] = 0;
3729
+ for (let j = 0; j < 8; j++) {
3730
+ t = ((uint16(a2[8 * i + j]) << 1) + uint16(Q / 2)) / uint16(Q) & 1;
3731
+ msg[i] |= byte(t << j);
3732
+ }
3733
+ }
3734
+ return msg;
3735
+ }
3736
+ function polyFromMsg(msg) {
3737
+ const r = new Array(384).fill(0);
3738
+ let mask;
3739
+ for (let i = 0; i < N / 8; i++) {
3740
+ for (let j = 0; j < 8; j++) {
3741
+ mask = -1 * int16(msg[i] >> j & 1);
3742
+ r[8 * i + j] = mask & int16((Q + 1) / 2);
3743
+ }
3744
+ }
3745
+ return r;
3746
+ }
3747
+ function indcpaRejUniform(buf, bufl, len) {
3748
+ const r = new Array(384).fill(0);
3749
+ let ctr = 0;
3750
+ let val0, val1;
3751
+ for (let pos = 0; ctr < len && pos + 3 <= bufl; ) {
3752
+ val0 = (uint16(buf[pos] >> 0) | uint16(buf[pos + 1]) << 8) & 4095;
3753
+ val1 = (uint16(buf[pos + 1] >> 4) | uint16(buf[pos + 2]) << 4) & 4095;
3754
+ pos = pos + 3;
3755
+ if (val0 < Q) {
3756
+ r[ctr] = val0;
3757
+ ctr = ctr + 1;
3758
+ }
3759
+ if (ctr < len && val1 < Q) {
3760
+ r[ctr] = val1;
3761
+ ctr = ctr + 1;
3762
+ }
3763
+ }
3764
+ return [r, ctr];
3765
+ }
3766
+ function byteopsCbd(buf, eta) {
3767
+ let t, d;
3768
+ let a, b;
3769
+ const r = new Array(384).fill(0);
3770
+ for (let i = 0; i < N / 8; i++) {
3771
+ t = byteopsLoad32(buf.subarray(4 * i, buf.length));
3772
+ d = t & 1431655765;
3773
+ d = d + (t >> 1 & 1431655765);
3774
+ for (let j = 0; j < 8; j++) {
3775
+ a = int16(d >> 4 * j + 0 & 3);
3776
+ b = int16(d >> 4 * j + eta & 3);
3777
+ r[8 * i + j] = a - b;
3778
+ }
3779
+ }
3780
+ return r;
3781
+ }
3782
+ function ntt(r) {
3783
+ for (let j = 0, k = 1, l = 128; l >= 2; l >>= 1) {
3784
+ for (let start = 0; start < 256; start = j + l) {
3785
+ const zeta = NTT_ZETAS[k];
3786
+ k = k + 1;
3787
+ for (j = start; j < start + l; j++) {
3788
+ const t = nttFqMul(zeta, r[j + l]);
3789
+ r[j + l] = r[j] - t;
3790
+ r[j] = r[j] + t;
3791
+ }
3792
+ }
3793
+ }
3794
+ return r;
3795
+ }
3796
+ function nttFqMul(a, b) {
3797
+ return byteopsMontgomeryReduce(a * b);
3798
+ }
3799
+ function reduce(r) {
3800
+ for (let i = 0; i < N; i++) {
3801
+ r[i] = barrett(r[i]);
3802
+ }
3803
+ return r;
3804
+ }
3805
+ function barrett(a) {
3806
+ const v = ((1 << 24) + Q / 2) / Q;
3807
+ let t = v * a >> 24;
3808
+ t = t * Q;
3809
+ return a - t;
3810
+ }
3811
+ function byteopsMontgomeryReduce(a) {
3812
+ const u = int16(int32(a) * Q_INV);
3813
+ let t = u * Q;
3814
+ t = a - t;
3815
+ t >>= 16;
3816
+ return int16(t);
3817
+ }
3818
+ function polyToMont(r) {
3819
+ const f = 1353;
3820
+ for (let i = 0; i < N; i++) {
3821
+ r[i] = byteopsMontgomeryReduce(int32(r[i]) * int32(f));
3822
+ }
3823
+ return r;
3824
+ }
3825
+ function multiply(a, b) {
3826
+ let r = polyBaseMulMontgomery(a[0], b[0]);
3827
+ let t;
3828
+ for (let i = 1; i < a.length; i++) {
3829
+ t = polyBaseMulMontgomery(a[i], b[i]);
3830
+ r = add(r, t);
3831
+ }
3832
+ return reduce(r);
3833
+ }
3834
+ function polyBaseMulMontgomery(a, b) {
3835
+ let rx, ry;
3836
+ for (let i = 0; i < N / 4; i++) {
3837
+ rx = nttBaseMul(a[4 * i + 0], a[4 * i + 1], b[4 * i + 0], b[4 * i + 1], NTT_ZETAS[64 + i]);
3838
+ ry = nttBaseMul(a[4 * i + 2], a[4 * i + 3], b[4 * i + 2], b[4 * i + 3], -NTT_ZETAS[64 + i]);
3839
+ a[4 * i + 0] = rx[0];
3840
+ a[4 * i + 1] = rx[1];
3841
+ a[4 * i + 2] = ry[0];
3842
+ a[4 * i + 3] = ry[1];
3843
+ }
3844
+ return a;
3845
+ }
3846
+ function nttBaseMul(a0, a1, b0, b1, zeta) {
3847
+ const r = new Array(2);
3848
+ r[0] = nttFqMul(a1, b1);
3849
+ r[0] = nttFqMul(r[0], zeta);
3850
+ r[0] += nttFqMul(a0, b0);
3851
+ r[1] = nttFqMul(a0, b1);
3852
+ r[1] += nttFqMul(a1, b0);
3853
+ return r;
3854
+ }
3855
+ function add(a, b) {
3856
+ const c = new Array(384);
3857
+ for (let i = 0; i < N; i++) {
3858
+ c[i] = a[i] + b[i];
3859
+ }
3860
+ return c;
3861
+ }
3862
+ function subtract(a, b) {
3863
+ for (let i = 0; i < N; i++) {
3864
+ a[i] -= b[i];
3865
+ }
3866
+ return a;
3867
+ }
3868
+ function nttInverse(r) {
3869
+ let j = 0;
3870
+ for (let k = 0, l = 2; l <= 128; l <<= 1) {
3871
+ for (let start = 0; start < 256; start = j + l) {
3872
+ const zeta = NTT_ZETAS_INV[k];
3873
+ k = k + 1;
3874
+ for (j = start; j < start + l; j++) {
3875
+ const t = r[j];
3876
+ r[j] = barrett(t + r[j + l]);
3877
+ r[j + l] = t - r[j + l];
3878
+ r[j + l] = nttFqMul(zeta, r[j + l]);
3879
+ }
3880
+ }
3881
+ }
3882
+ for (j = 0; j < 256; j++) {
3883
+ r[j] = nttFqMul(r[j], NTT_ZETAS_INV[127]);
3884
+ }
3885
+ return r;
3886
+ }
3887
+ function subtractQ(r) {
3888
+ for (let i = 0; i < N; i++) {
3889
+ r[i] -= Q;
3890
+ r[i] += r[i] >> 31 & Q;
3891
+ }
3892
+ return r;
3893
+ }
3894
+
3895
+ // node_modules/mlkem/esm/src/mlKem768.js
3896
+ var MlKem768 = class extends MlKemBase {
3897
+ constructor() {
3898
+ super();
3899
+ Object.defineProperty(this, "_k", {
3900
+ enumerable: true,
3901
+ configurable: true,
3902
+ writable: true,
3903
+ value: 3
3904
+ });
3905
+ Object.defineProperty(this, "_du", {
3906
+ enumerable: true,
3907
+ configurable: true,
3908
+ writable: true,
3909
+ value: 10
3910
+ });
3911
+ Object.defineProperty(this, "_dv", {
3912
+ enumerable: true,
3913
+ configurable: true,
3914
+ writable: true,
3915
+ value: 4
3916
+ });
3917
+ Object.defineProperty(this, "_eta1", {
3918
+ enumerable: true,
3919
+ configurable: true,
3920
+ writable: true,
3921
+ value: 2
3922
+ });
3923
+ Object.defineProperty(this, "_eta2", {
3924
+ enumerable: true,
3925
+ configurable: true,
3926
+ writable: true,
3927
+ value: 2
3928
+ });
3929
+ this._skSize = 12 * this._k * N / 8;
3930
+ this._pkSize = this._skSize + 32;
3931
+ this._compressedUSize = this._k * this._du * N / 8;
3932
+ this._compressedVSize = this._dv * N / 8;
3933
+ }
3934
+ };
3935
+
3936
+ // src/index.ts
2340
3937
  async function sha256(data) {
2341
3938
  if (typeof globalThis.crypto?.subtle !== "undefined") {
2342
3939
  const encoder = new TextEncoder();
@@ -2405,6 +4002,39 @@ function unsealEnvelope(plaintext) {
2405
4002
  return null;
2406
4003
  }
2407
4004
  }
4005
+ var PROTO_MARKER = 86;
4006
+ var FLAG_PADDED = 1;
4007
+ var FLAG_SEALED = 2;
4008
+ var FLAG_RATCHET = 4;
4009
+ var FLAG_PQ = 8;
4010
+ function makeProtoHeader(flags, ratchetStep2) {
4011
+ return new Uint8Array([PROTO_MARKER, flags, ratchetStep2 >> 8 & 255, ratchetStep2 & 255]);
4012
+ }
4013
+ function parseProtoHeader(data) {
4014
+ if (data.length < 4 || data[0] !== PROTO_MARKER) return null;
4015
+ return {
4016
+ flags: data[1],
4017
+ ratchetStep: data[2] << 8 | data[3],
4018
+ content: data.slice(4)
4019
+ };
4020
+ }
4021
+ var MAX_SKIP = 200;
4022
+ var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
4023
+ function toBase58(bytes) {
4024
+ if (bytes.length === 0) return "1";
4025
+ let result = "";
4026
+ let num = BigInt("0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""));
4027
+ while (num > 0n) {
4028
+ const remainder = num % 58n;
4029
+ num = num / 58n;
4030
+ result = BASE58_ALPHABET[Number(remainder)] + result;
4031
+ }
4032
+ for (const byte2 of bytes) {
4033
+ if (byte2 === 0) result = "1" + result;
4034
+ else break;
4035
+ }
4036
+ return result || "1";
4037
+ }
2408
4038
  var VoidlyAgent = class _VoidlyAgent {
2409
4039
  constructor(identity, config) {
2410
4040
  this._pinnedDids = /* @__PURE__ */ new Set();
@@ -2412,6 +4042,9 @@ var VoidlyAgent = class _VoidlyAgent {
2412
4042
  this._conversations = /* @__PURE__ */ new Map();
2413
4043
  this._offlineQueue = [];
2414
4044
  this._ratchetStates = /* @__PURE__ */ new Map();
4045
+ this._identityCache = /* @__PURE__ */ new Map();
4046
+ this._seenMessageIds = /* @__PURE__ */ new Set();
4047
+ this._decryptFailCount = 0;
2415
4048
  this.did = identity.did;
2416
4049
  this.apiKey = identity.apiKey;
2417
4050
  this.signingKeyPair = identity.signingKeyPair;
@@ -2422,6 +4055,11 @@ var VoidlyAgent = class _VoidlyAgent {
2422
4055
  this.fallbackRelays = config?.fallbackRelays || [];
2423
4056
  this.paddingEnabled = config?.padding !== false;
2424
4057
  this.sealedSender = config?.sealedSender || false;
4058
+ this.requireSignatures = config?.requireSignatures || false;
4059
+ this.timeout = config?.timeout ?? 3e4;
4060
+ this.postQuantum = config?.postQuantum !== false;
4061
+ this.mlkemPublicKey = identity.mlkemPublicKey || null;
4062
+ this.mlkemSecretKey = identity.mlkemSecretKey || null;
2425
4063
  }
2426
4064
  // ─── Factory Methods ────────────────────────────────────────────────────────
2427
4065
  /**
@@ -2432,15 +4070,26 @@ var VoidlyAgent = class _VoidlyAgent {
2432
4070
  const baseUrl = config?.baseUrl || "https://api.voidly.ai";
2433
4071
  const signingKeyPair = import_tweetnacl.default.sign.keyPair();
2434
4072
  const encryptionKeyPair = import_tweetnacl.default.box.keyPair();
4073
+ const usePQ = config?.postQuantum !== false;
4074
+ let mlkemPk;
4075
+ let mlkemSk;
4076
+ if (usePQ) {
4077
+ const kem = new MlKem768();
4078
+ [mlkemPk, mlkemSk] = await kem.generateKeyPair();
4079
+ }
4080
+ const regBody = {
4081
+ name: options.name,
4082
+ capabilities: options.capabilities,
4083
+ signing_public_key: (0, import_tweetnacl_util.encodeBase64)(signingKeyPair.publicKey),
4084
+ encryption_public_key: (0, import_tweetnacl_util.encodeBase64)(encryptionKeyPair.publicKey)
4085
+ };
4086
+ if (mlkemPk) {
4087
+ regBody.mlkem_public_key = (0, import_tweetnacl_util.encodeBase64)(mlkemPk);
4088
+ }
2435
4089
  const res = await fetch(`${baseUrl}/v1/agent/register`, {
2436
4090
  method: "POST",
2437
4091
  headers: { "Content-Type": "application/json" },
2438
- body: JSON.stringify({
2439
- name: options.name,
2440
- capabilities: options.capabilities,
2441
- signing_public_key: (0, import_tweetnacl_util.encodeBase64)(signingKeyPair.publicKey),
2442
- encryption_public_key: (0, import_tweetnacl_util.encodeBase64)(encryptionKeyPair.publicKey)
2443
- })
4092
+ body: JSON.stringify(regBody)
2444
4093
  });
2445
4094
  if (!res.ok) {
2446
4095
  const err = await res.json().catch(() => ({}));
@@ -2452,7 +4101,9 @@ var VoidlyAgent = class _VoidlyAgent {
2452
4101
  did: data.did,
2453
4102
  apiKey: data.api_key,
2454
4103
  signingKeyPair,
2455
- encryptionKeyPair
4104
+ encryptionKeyPair,
4105
+ mlkemPublicKey: mlkemPk,
4106
+ mlkemSecretKey: mlkemSk
2456
4107
  }, config);
2457
4108
  }
2458
4109
  /**
@@ -2460,32 +4111,117 @@ var VoidlyAgent = class _VoidlyAgent {
2460
4111
  * Use this to resume an agent across sessions.
2461
4112
  */
2462
4113
  static fromCredentials(creds, config) {
2463
- const signingSecret = (0, import_tweetnacl_util.decodeBase64)(creds.signingSecretKey);
2464
- const encryptionSecret = (0, import_tweetnacl_util.decodeBase64)(creds.encryptionSecretKey);
2465
- return new _VoidlyAgent({
4114
+ if (!creds.did || !creds.did.startsWith("did:")) {
4115
+ throw new Error('Invalid credentials: did must start with "did:"');
4116
+ }
4117
+ if (!creds.apiKey || creds.apiKey.length < 8) {
4118
+ throw new Error("Invalid credentials: apiKey is missing or too short");
4119
+ }
4120
+ if (!creds.signingSecretKey || !creds.encryptionSecretKey) {
4121
+ throw new Error("Invalid credentials: secret keys are required");
4122
+ }
4123
+ let signingSecret;
4124
+ let encryptionSecret;
4125
+ try {
4126
+ signingSecret = (0, import_tweetnacl_util.decodeBase64)(creds.signingSecretKey);
4127
+ encryptionSecret = (0, import_tweetnacl_util.decodeBase64)(creds.encryptionSecretKey);
4128
+ } catch {
4129
+ throw new Error("Invalid credentials: secret keys must be valid base64");
4130
+ }
4131
+ if (signingSecret.length !== 64) {
4132
+ throw new Error(`Invalid credentials: signing key must be 64 bytes, got ${signingSecret.length}`);
4133
+ }
4134
+ if (encryptionSecret.length !== 32) {
4135
+ throw new Error(`Invalid credentials: encryption key must be 32 bytes, got ${encryptionSecret.length}`);
4136
+ }
4137
+ let mlkemPk;
4138
+ let mlkemSk;
4139
+ if (creds.mlkemPublicKey && creds.mlkemSecretKey) {
4140
+ try {
4141
+ mlkemPk = (0, import_tweetnacl_util.decodeBase64)(creds.mlkemPublicKey);
4142
+ mlkemSk = (0, import_tweetnacl_util.decodeBase64)(creds.mlkemSecretKey);
4143
+ if (mlkemPk.length !== 1184 || mlkemSk.length !== 2400) {
4144
+ mlkemPk = void 0;
4145
+ mlkemSk = void 0;
4146
+ }
4147
+ } catch {
4148
+ }
4149
+ }
4150
+ const agent = new _VoidlyAgent({
2466
4151
  did: creds.did,
2467
4152
  apiKey: creds.apiKey,
2468
4153
  signingKeyPair: import_tweetnacl.default.sign.keyPair.fromSecretKey(signingSecret),
2469
4154
  encryptionKeyPair: {
2470
4155
  publicKey: import_tweetnacl.default.box.keyPair.fromSecretKey(encryptionSecret).publicKey,
2471
4156
  secretKey: encryptionSecret
2472
- }
4157
+ },
4158
+ mlkemPublicKey: mlkemPk,
4159
+ mlkemSecretKey: mlkemSk
2473
4160
  }, config);
4161
+ if (creds.ratchetStates) {
4162
+ for (const [pairId, rs] of Object.entries(creds.ratchetStates)) {
4163
+ try {
4164
+ const sendChainKey = (0, import_tweetnacl_util.decodeBase64)(rs.sendChainKey);
4165
+ const recvChainKey = (0, import_tweetnacl_util.decodeBase64)(rs.recvChainKey);
4166
+ if (sendChainKey.length !== 32 || recvChainKey.length !== 32) continue;
4167
+ agent._ratchetStates.set(pairId, {
4168
+ sendChainKey,
4169
+ sendStep: rs.sendStep || 0,
4170
+ recvChainKey,
4171
+ recvStep: rs.recvStep || 0,
4172
+ skippedKeys: /* @__PURE__ */ new Map()
4173
+ });
4174
+ } catch {
4175
+ }
4176
+ }
4177
+ }
4178
+ return agent;
2474
4179
  }
2475
4180
  /**
2476
4181
  * Export credentials for persistence.
2477
4182
  * Store these securely — they contain private keys.
2478
4183
  */
2479
4184
  exportCredentials() {
4185
+ const ratchetStates = {};
4186
+ for (const [pairId, state] of this._ratchetStates) {
4187
+ ratchetStates[pairId] = {
4188
+ sendChainKey: (0, import_tweetnacl_util.encodeBase64)(state.sendChainKey),
4189
+ sendStep: state.sendStep,
4190
+ recvChainKey: (0, import_tweetnacl_util.encodeBase64)(state.recvChainKey),
4191
+ recvStep: state.recvStep
4192
+ };
4193
+ }
2480
4194
  return {
2481
4195
  did: this.did,
2482
4196
  apiKey: this.apiKey,
2483
4197
  signingSecretKey: (0, import_tweetnacl_util.encodeBase64)(this.signingKeyPair.secretKey),
2484
4198
  encryptionSecretKey: (0, import_tweetnacl_util.encodeBase64)(this.encryptionKeyPair.secretKey),
2485
4199
  signingPublicKey: (0, import_tweetnacl_util.encodeBase64)(this.signingKeyPair.publicKey),
2486
- encryptionPublicKey: (0, import_tweetnacl_util.encodeBase64)(this.encryptionKeyPair.publicKey)
4200
+ encryptionPublicKey: (0, import_tweetnacl_util.encodeBase64)(this.encryptionKeyPair.publicKey),
4201
+ ...Object.keys(ratchetStates).length > 0 ? { ratchetStates } : {},
4202
+ ...this.mlkemPublicKey ? { mlkemPublicKey: (0, import_tweetnacl_util.encodeBase64)(this.mlkemPublicKey) } : {},
4203
+ ...this.mlkemSecretKey ? { mlkemSecretKey: (0, import_tweetnacl_util.encodeBase64)(this.mlkemSecretKey) } : {}
2487
4204
  };
2488
4205
  }
4206
+ /**
4207
+ * Get the number of messages that failed to decrypt.
4208
+ * Useful for detecting key mismatches, attacks, or corruption.
4209
+ */
4210
+ get decryptFailCount() {
4211
+ return this._decryptFailCount;
4212
+ }
4213
+ /**
4214
+ * Generate a did:key identifier from this agent's Ed25519 signing key.
4215
+ * did:key is a W3C standard — interoperable across systems.
4216
+ * Format: did:key:z6Mk{base58-multicodec-ed25519-pubkey}
4217
+ */
4218
+ get didKey() {
4219
+ const multicodec = new Uint8Array(2 + this.signingKeyPair.publicKey.length);
4220
+ multicodec[0] = 237;
4221
+ multicodec[1] = 1;
4222
+ multicodec.set(this.signingKeyPair.publicKey, 2);
4223
+ return `did:key:z${toBase58(multicodec)}`;
4224
+ }
2489
4225
  // ─── Messaging ──────────────────────────────────────────────────────────────
2490
4226
  /**
2491
4227
  * Send an E2E encrypted message with hardened security.
@@ -2516,39 +4252,73 @@ var VoidlyAgent = class _VoidlyAgent {
2516
4252
  if (useSealed) {
2517
4253
  plaintext = sealEnvelope(this.did, message);
2518
4254
  }
2519
- let messageBytes;
4255
+ let contentBytes;
2520
4256
  if (usePadding) {
2521
- messageBytes = padMessage((0, import_tweetnacl_util.decodeUTF8)(plaintext));
4257
+ contentBytes = padMessage((0, import_tweetnacl_util.decodeUTF8)(plaintext));
2522
4258
  } else {
2523
- messageBytes = (0, import_tweetnacl_util.decodeUTF8)(plaintext);
4259
+ contentBytes = (0, import_tweetnacl_util.decodeUTF8)(plaintext);
2524
4260
  }
2525
4261
  const pairId = `${this.did}:${recipientDid}`;
2526
- const ratchetState = this._ratchetStates.get(pairId);
2527
- let ratchetStep_n = 0;
2528
- if (ratchetState) {
2529
- const { nextChainKey, messageKey } = await ratchetStep(ratchetState.chainKey);
2530
- ratchetState.chainKey = nextChainKey;
2531
- ratchetState.step++;
2532
- ratchetStep_n = ratchetState.step;
2533
- } else {
2534
- const sharedSecret = import_tweetnacl.default.box.before(recipientPubKey, this.encryptionKeyPair.secretKey);
2535
- this._ratchetStates.set(pairId, {
2536
- chainKey: sharedSecret,
2537
- step: 0
2538
- });
4262
+ let state = this._ratchetStates.get(pairId);
4263
+ let pqCiphertext = null;
4264
+ if (!state) {
4265
+ const x25519Shared = import_tweetnacl.default.box.before(recipientPubKey, this.encryptionKeyPair.secretKey);
4266
+ let chainKey;
4267
+ if (this.postQuantum && profile.mlkem_public_key) {
4268
+ try {
4269
+ const recipientPqPk = (0, import_tweetnacl_util.decodeBase64)(profile.mlkem_public_key);
4270
+ const kem = new MlKem768();
4271
+ const [ct, pqShared] = await kem.encap(recipientPqPk);
4272
+ pqCiphertext = ct;
4273
+ const combined = new Uint8Array(x25519Shared.length + pqShared.length);
4274
+ combined.set(x25519Shared, 0);
4275
+ combined.set(pqShared, x25519Shared.length);
4276
+ chainKey = new Uint8Array(await crypto.subtle.digest("SHA-256", combined));
4277
+ } catch {
4278
+ chainKey = x25519Shared;
4279
+ }
4280
+ } else {
4281
+ chainKey = x25519Shared;
4282
+ }
4283
+ state = {
4284
+ sendChainKey: chainKey,
4285
+ sendStep: 0,
4286
+ recvChainKey: chainKey,
4287
+ // Will be synced on first receive
4288
+ recvStep: 0,
4289
+ skippedKeys: /* @__PURE__ */ new Map()
4290
+ };
4291
+ this._ratchetStates.set(pairId, state);
2539
4292
  }
2540
- const nonce = import_tweetnacl.default.randomBytes(import_tweetnacl.default.box.nonceLength);
2541
- const ciphertext = import_tweetnacl.default.box(messageBytes, nonce, recipientPubKey, this.encryptionKeyPair.secretKey);
4293
+ const { nextChainKey, messageKey } = await ratchetStep(state.sendChainKey);
4294
+ state.sendChainKey = nextChainKey;
4295
+ state.sendStep++;
4296
+ const currentStep = state.sendStep;
4297
+ let flags = FLAG_RATCHET;
4298
+ if (usePadding) flags |= FLAG_PADDED;
4299
+ if (useSealed) flags |= FLAG_SEALED;
4300
+ if (pqCiphertext) flags |= FLAG_PQ;
4301
+ const header = makeProtoHeader(flags, currentStep);
4302
+ const messageBytes = new Uint8Array(header.length + contentBytes.length);
4303
+ messageBytes.set(header, 0);
4304
+ messageBytes.set(contentBytes, header.length);
4305
+ const nonce = import_tweetnacl.default.randomBytes(import_tweetnacl.default.secretbox.nonceLength);
4306
+ const ciphertext = import_tweetnacl.default.secretbox(messageBytes, nonce, messageKey);
2542
4307
  if (!ciphertext) {
2543
4308
  throw new Error("Encryption failed");
2544
4309
  }
2545
- const envelopeData = JSON.stringify({
4310
+ const envelopeObj = {
2546
4311
  from: this.did,
2547
4312
  to: recipientDid,
2548
4313
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2549
4314
  nonce: (0, import_tweetnacl_util.encodeBase64)(nonce),
2550
- ciphertext_hash: await sha256((0, import_tweetnacl_util.encodeBase64)(ciphertext))
2551
- });
4315
+ ciphertext_hash: await sha256((0, import_tweetnacl_util.encodeBase64)(ciphertext)),
4316
+ ratchet_step: currentStep
4317
+ };
4318
+ if (pqCiphertext) {
4319
+ envelopeObj.pq_ciphertext = (0, import_tweetnacl_util.encodeBase64)(pqCiphertext);
4320
+ }
4321
+ const envelopeData = JSON.stringify(envelopeObj);
2552
4322
  const signature = import_tweetnacl.default.sign.detached((0, import_tweetnacl_util.decodeUTF8)(envelopeData), this.signingKeyPair.secretKey);
2553
4323
  const payload = {
2554
4324
  to: recipientDid,
@@ -2612,7 +4382,7 @@ var VoidlyAgent = class _VoidlyAgent {
2612
4382
  if (options.contentType) params.set("content_type", options.contentType);
2613
4383
  if (options.messageType) params.set("message_type", options.messageType);
2614
4384
  if (options.unreadOnly) params.set("unread", "true");
2615
- const res = await fetch(`${this.baseUrl}/v1/agent/receive/raw?${params}`, {
4385
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/receive/raw?${params}`, {
2616
4386
  headers: { "X-Agent-Key": this.apiKey }
2617
4387
  });
2618
4388
  if (!res.ok) {
@@ -2623,13 +4393,105 @@ var VoidlyAgent = class _VoidlyAgent {
2623
4393
  const decrypted = [];
2624
4394
  for (const msg of data.messages) {
2625
4395
  try {
4396
+ if (this._seenMessageIds.has(msg.id)) continue;
2626
4397
  const senderEncPub = (0, import_tweetnacl_util.decodeBase64)(msg.sender_encryption_key);
2627
4398
  const ciphertext = (0, import_tweetnacl_util.decodeBase64)(msg.ciphertext);
2628
4399
  const nonce = (0, import_tweetnacl_util.decodeBase64)(msg.nonce);
2629
- const rawPlaintext = import_tweetnacl.default.box.open(ciphertext, nonce, senderEncPub, this.encryptionKeyPair.secretKey);
2630
- if (!rawPlaintext) continue;
4400
+ let rawPlaintext = null;
4401
+ let envelopeRatchetStep = 0;
4402
+ let envelopePqCiphertext = null;
4403
+ if (msg.envelope) {
4404
+ try {
4405
+ const env = JSON.parse(msg.envelope);
4406
+ if (typeof env.ratchet_step === "number") {
4407
+ envelopeRatchetStep = env.ratchet_step;
4408
+ }
4409
+ if (typeof env.pq_ciphertext === "string") {
4410
+ envelopePqCiphertext = env.pq_ciphertext;
4411
+ }
4412
+ } catch {
4413
+ }
4414
+ }
4415
+ if (envelopeRatchetStep > 0) {
4416
+ const pairId = `${msg.from}:${this.did}`;
4417
+ let state = this._ratchetStates.get(pairId);
4418
+ if (!state) {
4419
+ const x25519Shared = import_tweetnacl.default.box.before(senderEncPub, this.encryptionKeyPair.secretKey);
4420
+ let chainKey;
4421
+ if (envelopePqCiphertext && this.mlkemSecretKey) {
4422
+ try {
4423
+ const pqCt = (0, import_tweetnacl_util.decodeBase64)(envelopePqCiphertext);
4424
+ const kem = new MlKem768();
4425
+ const pqShared = await kem.decap(pqCt, this.mlkemSecretKey);
4426
+ const combined = new Uint8Array(x25519Shared.length + pqShared.length);
4427
+ combined.set(x25519Shared, 0);
4428
+ combined.set(pqShared, x25519Shared.length);
4429
+ chainKey = new Uint8Array(await crypto.subtle.digest("SHA-256", combined));
4430
+ } catch {
4431
+ chainKey = x25519Shared;
4432
+ }
4433
+ } else {
4434
+ chainKey = x25519Shared;
4435
+ }
4436
+ state = {
4437
+ sendChainKey: chainKey,
4438
+ // Our sending chain to this peer
4439
+ sendStep: 0,
4440
+ recvChainKey: chainKey,
4441
+ // Their sending chain (our receiving)
4442
+ recvStep: 0,
4443
+ skippedKeys: /* @__PURE__ */ new Map()
4444
+ };
4445
+ this._ratchetStates.set(pairId, state);
4446
+ }
4447
+ const targetStep = envelopeRatchetStep;
4448
+ if (state.skippedKeys.has(targetStep)) {
4449
+ const mk = state.skippedKeys.get(targetStep);
4450
+ rawPlaintext = import_tweetnacl.default.secretbox.open(ciphertext, nonce, mk);
4451
+ state.skippedKeys.delete(targetStep);
4452
+ } else if (targetStep > state.recvStep) {
4453
+ const skip = targetStep - state.recvStep;
4454
+ if (skip > MAX_SKIP) {
4455
+ rawPlaintext = import_tweetnacl.default.box.open(ciphertext, nonce, senderEncPub, this.encryptionKeyPair.secretKey);
4456
+ } else {
4457
+ let ck = state.recvChainKey;
4458
+ for (let i = state.recvStep + 1; i < targetStep; i++) {
4459
+ const { nextChainKey: nextChainKey2, messageKey: skippedMk } = await ratchetStep(ck);
4460
+ state.skippedKeys.set(i, skippedMk);
4461
+ ck = nextChainKey2;
4462
+ if (state.skippedKeys.size > MAX_SKIP) {
4463
+ const oldest = state.skippedKeys.keys().next().value;
4464
+ if (oldest !== void 0) state.skippedKeys.delete(oldest);
4465
+ }
4466
+ }
4467
+ const { nextChainKey, messageKey } = await ratchetStep(ck);
4468
+ state.recvChainKey = nextChainKey;
4469
+ state.recvStep = targetStep;
4470
+ rawPlaintext = import_tweetnacl.default.secretbox.open(ciphertext, nonce, messageKey);
4471
+ }
4472
+ }
4473
+ if (!rawPlaintext) {
4474
+ rawPlaintext = import_tweetnacl.default.box.open(ciphertext, nonce, senderEncPub, this.encryptionKeyPair.secretKey);
4475
+ }
4476
+ } else {
4477
+ rawPlaintext = import_tweetnacl.default.box.open(ciphertext, nonce, senderEncPub, this.encryptionKeyPair.secretKey);
4478
+ }
4479
+ if (!rawPlaintext) {
4480
+ this._decryptFailCount++;
4481
+ continue;
4482
+ }
2631
4483
  let plaintextBytes = rawPlaintext;
2632
- if (rawPlaintext.length >= 256 && (rawPlaintext.length & rawPlaintext.length - 1) === 0) {
4484
+ let wasPadded = false;
4485
+ let wasSealed = false;
4486
+ const proto = parseProtoHeader(rawPlaintext);
4487
+ if (proto) {
4488
+ wasPadded = !!(proto.flags & FLAG_PADDED);
4489
+ wasSealed = !!(proto.flags & FLAG_SEALED);
4490
+ plaintextBytes = proto.content;
4491
+ }
4492
+ if (wasPadded) {
4493
+ plaintextBytes = unpadMessage(plaintextBytes);
4494
+ } else if (!proto && rawPlaintext.length >= 256 && (rawPlaintext.length & rawPlaintext.length - 1) === 0) {
2633
4495
  const unpadded = unpadMessage(rawPlaintext);
2634
4496
  if (unpadded.length < rawPlaintext.length) {
2635
4497
  plaintextBytes = unpadded;
@@ -2637,10 +4499,12 @@ var VoidlyAgent = class _VoidlyAgent {
2637
4499
  }
2638
4500
  let content = (0, import_tweetnacl_util.encodeUTF8)(plaintextBytes);
2639
4501
  let senderDid = msg.from;
2640
- const unsealed = unsealEnvelope(content);
2641
- if (unsealed) {
2642
- content = unsealed.msg;
2643
- senderDid = unsealed.from;
4502
+ if (wasSealed || !proto) {
4503
+ const unsealed = unsealEnvelope(content);
4504
+ if (unsealed) {
4505
+ content = unsealed.msg;
4506
+ senderDid = unsealed.from;
4507
+ }
2644
4508
  }
2645
4509
  let signatureValid = false;
2646
4510
  try {
@@ -2661,6 +4525,15 @@ var VoidlyAgent = class _VoidlyAgent {
2661
4525
  } catch {
2662
4526
  signatureValid = false;
2663
4527
  }
4528
+ if (this.requireSignatures && !signatureValid) {
4529
+ this._decryptFailCount++;
4530
+ continue;
4531
+ }
4532
+ this._seenMessageIds.add(msg.id);
4533
+ if (this._seenMessageIds.size > 1e4) {
4534
+ const first = this._seenMessageIds.values().next().value;
4535
+ if (first !== void 0) this._seenMessageIds.delete(first);
4536
+ }
2664
4537
  decrypted.push({
2665
4538
  id: msg.id,
2666
4539
  from: senderDid,
@@ -2675,6 +4548,7 @@ var VoidlyAgent = class _VoidlyAgent {
2675
4548
  expiresAt: msg.expires_at
2676
4549
  });
2677
4550
  } catch {
4551
+ this._decryptFailCount++;
2678
4552
  }
2679
4553
  }
2680
4554
  return decrypted;
@@ -2684,7 +4558,7 @@ var VoidlyAgent = class _VoidlyAgent {
2684
4558
  * Delete a message by ID (must be sender or recipient).
2685
4559
  */
2686
4560
  async deleteMessage(messageId) {
2687
- const res = await fetch(`${this.baseUrl}/v1/agent/messages/${messageId}`, {
4561
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/messages/${messageId}`, {
2688
4562
  method: "DELETE",
2689
4563
  headers: { "X-Agent-Key": this.apiKey }
2690
4564
  });
@@ -2695,7 +4569,7 @@ var VoidlyAgent = class _VoidlyAgent {
2695
4569
  * Get this agent's own profile.
2696
4570
  */
2697
4571
  async getProfile() {
2698
- const res = await fetch(`${this.baseUrl}/v1/agent/profile`, {
4572
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/profile`, {
2699
4573
  headers: { "X-Agent-Key": this.apiKey }
2700
4574
  });
2701
4575
  if (!res.ok) {
@@ -2707,7 +4581,7 @@ var VoidlyAgent = class _VoidlyAgent {
2707
4581
  * Update this agent's profile (name, capabilities, metadata).
2708
4582
  */
2709
4583
  async updateProfile(updates) {
2710
- const res = await fetch(`${this.baseUrl}/v1/agent/profile`, {
4584
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/profile`, {
2711
4585
  method: "PATCH",
2712
4586
  headers: {
2713
4587
  "Content-Type": "application/json",
@@ -2725,9 +4599,19 @@ var VoidlyAgent = class _VoidlyAgent {
2725
4599
  * Look up an agent's public profile and keys.
2726
4600
  */
2727
4601
  async getIdentity(did) {
2728
- const res = await fetch(`${this.baseUrl}/v1/agent/identity/${did}`);
4602
+ const cached = this._identityCache.get(did);
4603
+ if (cached && Date.now() - cached.cachedAt < 3e5) {
4604
+ return cached.profile;
4605
+ }
4606
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/identity/${did}`);
2729
4607
  if (!res.ok) return null;
2730
- return await res.json();
4608
+ const profile = await res.json();
4609
+ this._identityCache.set(did, { profile, cachedAt: Date.now() });
4610
+ if (this._identityCache.size > 500) {
4611
+ const oldest = this._identityCache.keys().next().value;
4612
+ if (oldest !== void 0) this._identityCache.delete(oldest);
4613
+ }
4614
+ return profile;
2731
4615
  }
2732
4616
  /**
2733
4617
  * Search for agents by name or capability.
@@ -2737,7 +4621,7 @@ var VoidlyAgent = class _VoidlyAgent {
2737
4621
  if (options.query) params.set("query", options.query);
2738
4622
  if (options.capability) params.set("capability", options.capability);
2739
4623
  if (options.limit) params.set("limit", String(options.limit));
2740
- const res = await fetch(`${this.baseUrl}/v1/agent/discover?${params}`);
4624
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/discover?${params}`);
2741
4625
  if (!res.ok) return [];
2742
4626
  const data = await res.json();
2743
4627
  return data.agents;
@@ -2746,7 +4630,7 @@ var VoidlyAgent = class _VoidlyAgent {
2746
4630
  * Get relay network statistics.
2747
4631
  */
2748
4632
  async stats() {
2749
- const res = await fetch(`${this.baseUrl}/v1/agent/stats`);
4633
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/stats`);
2750
4634
  return await res.json();
2751
4635
  }
2752
4636
  // ─── Webhooks ──────────────────────────────────────────────────────────────
@@ -2755,7 +4639,7 @@ var VoidlyAgent = class _VoidlyAgent {
2755
4639
  * Instead of polling receive(), messages are POSTed to your URL with HMAC signatures.
2756
4640
  */
2757
4641
  async registerWebhook(webhookUrl, options = {}) {
2758
- const res = await fetch(`${this.baseUrl}/v1/agent/webhooks`, {
4642
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/webhooks`, {
2759
4643
  method: "POST",
2760
4644
  headers: {
2761
4645
  "Content-Type": "application/json",
@@ -2776,7 +4660,7 @@ var VoidlyAgent = class _VoidlyAgent {
2776
4660
  * List registered webhooks.
2777
4661
  */
2778
4662
  async listWebhooks() {
2779
- const res = await fetch(`${this.baseUrl}/v1/agent/webhooks`, {
4663
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/webhooks`, {
2780
4664
  headers: { "X-Agent-Key": this.apiKey }
2781
4665
  });
2782
4666
  if (!res.ok) return [];
@@ -2787,10 +4671,14 @@ var VoidlyAgent = class _VoidlyAgent {
2787
4671
  * Delete a webhook.
2788
4672
  */
2789
4673
  async deleteWebhook(webhookId) {
2790
- await fetch(`${this.baseUrl}/v1/agent/webhooks/${webhookId}`, {
4674
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/webhooks/${webhookId}`, {
2791
4675
  method: "DELETE",
2792
4676
  headers: { "X-Agent-Key": this.apiKey }
2793
4677
  });
4678
+ if (!res.ok) {
4679
+ const err = await res.json().catch(() => ({}));
4680
+ throw new Error(`Webhook delete failed: ${err.error || res.statusText}`);
4681
+ }
2794
4682
  }
2795
4683
  /**
2796
4684
  * Verify a webhook payload signature (for use in your webhook handler).
@@ -2827,7 +4715,7 @@ var VoidlyAgent = class _VoidlyAgent {
2827
4715
  async rotateKeys() {
2828
4716
  const newSigningKeyPair = import_tweetnacl.default.sign.keyPair();
2829
4717
  const newEncryptionKeyPair = import_tweetnacl.default.box.keyPair();
2830
- const res = await fetch(`${this.baseUrl}/v1/agent/rotate-keys`, {
4718
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/rotate-keys`, {
2831
4719
  method: "POST",
2832
4720
  headers: {
2833
4721
  "Content-Type": "application/json",
@@ -2850,7 +4738,7 @@ var VoidlyAgent = class _VoidlyAgent {
2850
4738
  * Only authenticated agents with did:voidly: identities can join and read.
2851
4739
  */
2852
4740
  async createChannel(options) {
2853
- const res = await fetch(`${this.baseUrl}/v1/agent/channels`, {
4741
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels`, {
2854
4742
  method: "POST",
2855
4743
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
2856
4744
  body: JSON.stringify(options)
@@ -2870,7 +4758,7 @@ var VoidlyAgent = class _VoidlyAgent {
2870
4758
  if (options.query) params.set("q", options.query);
2871
4759
  if (options.mine) params.set("mine", "true");
2872
4760
  if (options.limit) params.set("limit", String(options.limit));
2873
- const res = await fetch(`${this.baseUrl}/v1/agent/channels?${params}`, {
4761
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels?${params}`, {
2874
4762
  headers: options.mine ? { "X-Agent-Key": this.apiKey } : {}
2875
4763
  });
2876
4764
  if (!res.ok) return [];
@@ -2881,7 +4769,7 @@ var VoidlyAgent = class _VoidlyAgent {
2881
4769
  * Join an encrypted channel.
2882
4770
  */
2883
4771
  async joinChannel(channelId) {
2884
- const res = await fetch(`${this.baseUrl}/v1/agent/channels/${channelId}/join`, {
4772
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${channelId}/join`, {
2885
4773
  method: "POST",
2886
4774
  headers: { "X-Agent-Key": this.apiKey }
2887
4775
  });
@@ -2895,7 +4783,7 @@ var VoidlyAgent = class _VoidlyAgent {
2895
4783
  * Leave a channel.
2896
4784
  */
2897
4785
  async leaveChannel(channelId) {
2898
- const res = await fetch(`${this.baseUrl}/v1/agent/channels/${channelId}/leave`, {
4786
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${channelId}/leave`, {
2899
4787
  method: "POST",
2900
4788
  headers: { "X-Agent-Key": this.apiKey }
2901
4789
  });
@@ -2908,7 +4796,7 @@ var VoidlyAgent = class _VoidlyAgent {
2908
4796
  * Post an encrypted message to a channel.
2909
4797
  */
2910
4798
  async postToChannel(channelId, message, replyTo) {
2911
- const res = await fetch(`${this.baseUrl}/v1/agent/channels/${channelId}/messages`, {
4799
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${channelId}/messages`, {
2912
4800
  method: "POST",
2913
4801
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
2914
4802
  body: JSON.stringify({ message, reply_to: replyTo })
@@ -2927,7 +4815,7 @@ var VoidlyAgent = class _VoidlyAgent {
2927
4815
  if (options.since) params.set("since", options.since);
2928
4816
  if (options.before) params.set("before", options.before);
2929
4817
  if (options.limit) params.set("limit", String(options.limit));
2930
- const res = await fetch(`${this.baseUrl}/v1/agent/channels/${channelId}/messages?${params}`, {
4818
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${channelId}/messages?${params}`, {
2931
4819
  headers: { "X-Agent-Key": this.apiKey }
2932
4820
  });
2933
4821
  if (!res.ok) {
@@ -2941,7 +4829,7 @@ var VoidlyAgent = class _VoidlyAgent {
2941
4829
  * This is a soft delete — messages expire per TTL. Re-register for a new identity.
2942
4830
  */
2943
4831
  async deactivate() {
2944
- const res = await fetch(`${this.baseUrl}/v1/agent/deactivate`, {
4832
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/deactivate`, {
2945
4833
  method: "DELETE",
2946
4834
  headers: { "X-Agent-Key": this.apiKey }
2947
4835
  });
@@ -2964,7 +4852,7 @@ var VoidlyAgent = class _VoidlyAgent {
2964
4852
  * ```
2965
4853
  */
2966
4854
  async registerCapability(options) {
2967
- const res = await fetch(`${this.baseUrl}/v1/agent/capabilities`, {
4855
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities`, {
2968
4856
  method: "POST",
2969
4857
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
2970
4858
  body: JSON.stringify({
@@ -2985,7 +4873,7 @@ var VoidlyAgent = class _VoidlyAgent {
2985
4873
  * List this agent's registered capabilities.
2986
4874
  */
2987
4875
  async listCapabilities() {
2988
- const res = await fetch(`${this.baseUrl}/v1/agent/capabilities`, {
4876
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities`, {
2989
4877
  headers: { "X-Agent-Key": this.apiKey }
2990
4878
  });
2991
4879
  if (!res.ok) return [];
@@ -3007,7 +4895,7 @@ var VoidlyAgent = class _VoidlyAgent {
3007
4895
  if (options.query) params.set("q", options.query);
3008
4896
  if (options.name) params.set("name", options.name);
3009
4897
  if (options.limit) params.set("limit", String(options.limit));
3010
- const res = await fetch(`${this.baseUrl}/v1/agent/capabilities/search?${params}`);
4898
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities/search?${params}`);
3011
4899
  if (!res.ok) return [];
3012
4900
  const data = await res.json();
3013
4901
  return data.results;
@@ -3016,7 +4904,7 @@ var VoidlyAgent = class _VoidlyAgent {
3016
4904
  * Remove a capability.
3017
4905
  */
3018
4906
  async deleteCapability(capabilityId) {
3019
- const res = await fetch(`${this.baseUrl}/v1/agent/capabilities/${capabilityId}`, {
4907
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities/${capabilityId}`, {
3020
4908
  method: "DELETE",
3021
4909
  headers: { "X-Agent-Key": this.apiKey }
3022
4910
  });
@@ -3041,14 +4929,14 @@ var VoidlyAgent = class _VoidlyAgent {
3041
4929
  * ```
3042
4930
  */
3043
4931
  async createTask(options) {
3044
- const identityRes = await fetch(`${this.baseUrl}/v1/agent/identity/${options.to}`);
4932
+ const identityRes = await this._timedFetch(`${this.baseUrl}/v1/agent/identity/${options.to}`);
3045
4933
  if (!identityRes.ok) throw new Error("Recipient agent not found");
3046
4934
  const identity = await identityRes.json();
3047
4935
  const recipientPubKey = (0, import_tweetnacl_util.decodeBase64)(identity.encryption_public_key);
3048
4936
  const plaintext = (0, import_tweetnacl_util.decodeUTF8)(JSON.stringify(options.input));
3049
4937
  const nonce = import_tweetnacl.default.randomBytes(import_tweetnacl.default.box.nonceLength);
3050
4938
  const encrypted = import_tweetnacl.default.box(plaintext, nonce, recipientPubKey, this.encryptionKeyPair.secretKey);
3051
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks`, {
4939
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks`, {
3052
4940
  method: "POST",
3053
4941
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3054
4942
  body: JSON.stringify({
@@ -3075,7 +4963,7 @@ var VoidlyAgent = class _VoidlyAgent {
3075
4963
  if (options.status) params.set("status", options.status);
3076
4964
  if (options.capability) params.set("capability", options.capability);
3077
4965
  if (options.limit) params.set("limit", String(options.limit));
3078
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks?${params}`, {
4966
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks?${params}`, {
3079
4967
  headers: { "X-Agent-Key": this.apiKey }
3080
4968
  });
3081
4969
  if (!res.ok) return [];
@@ -3086,7 +4974,7 @@ var VoidlyAgent = class _VoidlyAgent {
3086
4974
  * Get task detail. Includes encrypted input/output (only visible to participants).
3087
4975
  */
3088
4976
  async getTask(taskId) {
3089
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks/${taskId}`, {
4977
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/${taskId}`, {
3090
4978
  headers: { "X-Agent-Key": this.apiKey }
3091
4979
  });
3092
4980
  if (!res.ok) {
@@ -3118,7 +5006,7 @@ var VoidlyAgent = class _VoidlyAgent {
3118
5006
  if (update.output && (update.status === "completed" || update.status === "failed")) {
3119
5007
  const task = await this.getTask(taskId);
3120
5008
  const requesterDid = task.from;
3121
- const identityRes = await fetch(`${this.baseUrl}/v1/agent/identity/${requesterDid}`);
5009
+ const identityRes = await this._timedFetch(`${this.baseUrl}/v1/agent/identity/${requesterDid}`);
3122
5010
  if (identityRes.ok) {
3123
5011
  const identity = await identityRes.json();
3124
5012
  const requesterPubKey = (0, import_tweetnacl_util.decodeBase64)(identity.encryption_public_key);
@@ -3131,7 +5019,7 @@ var VoidlyAgent = class _VoidlyAgent {
3131
5019
  body.output_signature = (0, import_tweetnacl_util.encodeBase64)(signature);
3132
5020
  }
3133
5021
  }
3134
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks/${taskId}`, {
5022
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/${taskId}`, {
3135
5023
  method: "PATCH",
3136
5024
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3137
5025
  body: JSON.stringify(body)
@@ -3198,7 +5086,7 @@ var VoidlyAgent = class _VoidlyAgent {
3198
5086
  const payload = options.claimType + JSON.stringify(options.claimData) + timestamp;
3199
5087
  const payloadBytes = (0, import_tweetnacl_util.decodeUTF8)(payload);
3200
5088
  const signature = import_tweetnacl.default.sign.detached(payloadBytes, this.signingKeyPair.secretKey);
3201
- const res = await fetch(`${this.baseUrl}/v1/agent/attestations`, {
5089
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/attestations`, {
3202
5090
  method: "POST",
3203
5091
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3204
5092
  body: JSON.stringify({
@@ -3235,7 +5123,7 @@ var VoidlyAgent = class _VoidlyAgent {
3235
5123
  const payload = attestationId + vote;
3236
5124
  const payloadBytes = (0, import_tweetnacl_util.decodeUTF8)(payload);
3237
5125
  const signature = import_tweetnacl.default.sign.detached(payloadBytes, this.signingKeyPair.secretKey);
3238
- const res = await fetch(`${this.baseUrl}/v1/agent/attestations/${attestationId}/corroborate`, {
5126
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/attestations/${attestationId}/corroborate`, {
3239
5127
  method: "POST",
3240
5128
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3241
5129
  body: JSON.stringify({ vote, signature: (0, import_tweetnacl_util.encodeBase64)(signature), comment })
@@ -3258,7 +5146,7 @@ var VoidlyAgent = class _VoidlyAgent {
3258
5146
  if (options.minConsensus !== void 0) params.set("min_consensus", String(options.minConsensus));
3259
5147
  if (options.since) params.set("since", options.since);
3260
5148
  if (options.limit) params.set("limit", String(options.limit));
3261
- const res = await fetch(`${this.baseUrl}/v1/agent/attestations?${params}`);
5149
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/attestations?${params}`);
3262
5150
  if (!res.ok) return [];
3263
5151
  const data = await res.json();
3264
5152
  return data.attestations;
@@ -3267,7 +5155,7 @@ var VoidlyAgent = class _VoidlyAgent {
3267
5155
  * Get attestation detail including all corroborations.
3268
5156
  */
3269
5157
  async getAttestation(attestationId) {
3270
- const res = await fetch(`${this.baseUrl}/v1/agent/attestations/${attestationId}`);
5158
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/attestations/${attestationId}`);
3271
5159
  if (!res.ok) {
3272
5160
  const err = await res.json().catch(() => ({}));
3273
5161
  throw new Error(`Get attestation failed: ${err.error || res.statusText}`);
@@ -3282,7 +5170,7 @@ var VoidlyAgent = class _VoidlyAgent {
3282
5170
  if (options.country) params.set("country", options.country);
3283
5171
  if (options.domain) params.set("domain", options.domain);
3284
5172
  if (options.type) params.set("type", options.type);
3285
- const res = await fetch(`${this.baseUrl}/v1/agent/attestations/consensus?${params}`);
5173
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/attestations/consensus?${params}`);
3286
5174
  if (!res.ok) return [];
3287
5175
  const data = await res.json();
3288
5176
  return data.consensus;
@@ -3295,7 +5183,7 @@ var VoidlyAgent = class _VoidlyAgent {
3295
5183
  * Only channel members can invite.
3296
5184
  */
3297
5185
  async inviteToChannel(channelId, inviteeDid, options) {
3298
- const res = await fetch(`${this.baseUrl}/v1/agent/channels/${channelId}/invite`, {
5186
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${channelId}/invite`, {
3299
5187
  method: "POST",
3300
5188
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3301
5189
  body: JSON.stringify({
@@ -3314,7 +5202,7 @@ var VoidlyAgent = class _VoidlyAgent {
3314
5202
  * List pending channel invites for this agent.
3315
5203
  */
3316
5204
  async listInvites(status = "pending") {
3317
- const res = await fetch(`${this.baseUrl}/v1/agent/invites?status=${status}`, {
5205
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/invites?status=${status}`, {
3318
5206
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey }
3319
5207
  });
3320
5208
  if (!res.ok) return [];
@@ -3325,7 +5213,7 @@ var VoidlyAgent = class _VoidlyAgent {
3325
5213
  * Accept or decline a channel invite.
3326
5214
  */
3327
5215
  async respondToInvite(inviteId, action) {
3328
- const res = await fetch(`${this.baseUrl}/v1/agent/invites/${inviteId}/respond`, {
5216
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/invites/${inviteId}/respond`, {
3329
5217
  method: "POST",
3330
5218
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3331
5219
  body: JSON.stringify({ action })
@@ -3343,7 +5231,7 @@ var VoidlyAgent = class _VoidlyAgent {
3343
5231
  * Get an agent's trust score and reputation breakdown.
3344
5232
  */
3345
5233
  async getTrustScore(did) {
3346
- const res = await fetch(`${this.baseUrl}/v1/agent/trust/${did}`);
5234
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/trust/${did}`);
3347
5235
  if (!res.ok) {
3348
5236
  const err = await res.json().catch(() => ({}));
3349
5237
  throw new Error(`Trust score failed: ${err.error || res.statusText}`);
@@ -3357,7 +5245,7 @@ var VoidlyAgent = class _VoidlyAgent {
3357
5245
  const params = new URLSearchParams();
3358
5246
  if (options?.limit) params.set("limit", options.limit.toString());
3359
5247
  if (options?.minLevel) params.set("min_level", options.minLevel);
3360
- const res = await fetch(`${this.baseUrl}/v1/agent/trust/leaderboard?${params}`);
5248
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/trust/leaderboard?${params}`);
3361
5249
  if (!res.ok) return [];
3362
5250
  const data = await res.json();
3363
5251
  return data.leaderboard;
@@ -3369,7 +5257,7 @@ var VoidlyAgent = class _VoidlyAgent {
3369
5257
  * Mark a message as read.
3370
5258
  */
3371
5259
  async markRead(messageId) {
3372
- const res = await fetch(`${this.baseUrl}/v1/agent/messages/${messageId}/read`, {
5260
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/messages/${messageId}/read`, {
3373
5261
  method: "POST",
3374
5262
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey }
3375
5263
  });
@@ -3380,7 +5268,7 @@ var VoidlyAgent = class _VoidlyAgent {
3380
5268
  * Mark multiple messages as read in one call.
3381
5269
  */
3382
5270
  async markReadBatch(messageIds) {
3383
- const res = await fetch(`${this.baseUrl}/v1/agent/messages/read-batch`, {
5271
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/messages/read-batch`, {
3384
5272
  method: "POST",
3385
5273
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3386
5274
  body: JSON.stringify({ message_ids: messageIds })
@@ -3394,7 +5282,7 @@ var VoidlyAgent = class _VoidlyAgent {
3394
5282
  async getUnreadCount(fromDid) {
3395
5283
  const params = new URLSearchParams();
3396
5284
  if (fromDid) params.set("from", fromDid);
3397
- const res = await fetch(`${this.baseUrl}/v1/agent/messages/unread-count?${params}`, {
5285
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/messages/unread-count?${params}`, {
3398
5286
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey }
3399
5287
  });
3400
5288
  if (!res.ok) throw new Error(`Failed to get unread count: ${res.status}`);
@@ -3408,13 +5296,21 @@ var VoidlyAgent = class _VoidlyAgent {
3408
5296
  * The relay finds matching agents and creates individual tasks for each.
3409
5297
  */
3410
5298
  async broadcastTask(options) {
3411
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks/broadcast`, {
5299
+ const inputBytes = (0, import_tweetnacl_util.decodeUTF8)(options.input);
5300
+ const broadcastNonce = import_tweetnacl.default.randomBytes(import_tweetnacl.default.secretbox.nonceLength);
5301
+ const broadcastEncrypted = import_tweetnacl.default.secretbox(inputBytes, broadcastNonce, import_tweetnacl.default.box.before(
5302
+ this.encryptionKeyPair.publicKey,
5303
+ this.encryptionKeyPair.secretKey
5304
+ ));
5305
+ const broadcastSig = import_tweetnacl.default.sign.detached(inputBytes, this.signingKeyPair.secretKey);
5306
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/broadcast`, {
3412
5307
  method: "POST",
3413
5308
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3414
5309
  body: JSON.stringify({
3415
5310
  capability: options.capability,
3416
- encrypted_input: (0, import_tweetnacl_util.encodeBase64)((0, import_tweetnacl_util.decodeUTF8)(options.input)),
3417
- input_nonce: (0, import_tweetnacl_util.encodeBase64)(import_tweetnacl.default.randomBytes(24)),
5311
+ encrypted_input: (0, import_tweetnacl_util.encodeBase64)(broadcastEncrypted),
5312
+ input_nonce: (0, import_tweetnacl_util.encodeBase64)(broadcastNonce),
5313
+ input_signature: (0, import_tweetnacl_util.encodeBase64)(broadcastSig),
3418
5314
  priority: options.priority,
3419
5315
  max_agents: options.maxAgents,
3420
5316
  min_trust_level: options.minTrustLevel,
@@ -3433,7 +5329,7 @@ var VoidlyAgent = class _VoidlyAgent {
3433
5329
  async listBroadcasts(status) {
3434
5330
  const params = new URLSearchParams();
3435
5331
  if (status) params.set("status", status);
3436
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks/broadcasts?${params}`, {
5332
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/broadcasts?${params}`, {
3437
5333
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey }
3438
5334
  });
3439
5335
  if (!res.ok) return [];
@@ -3444,7 +5340,7 @@ var VoidlyAgent = class _VoidlyAgent {
3444
5340
  * Get broadcast detail with individual task statuses.
3445
5341
  */
3446
5342
  async getBroadcast(broadcastId) {
3447
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks/broadcasts/${broadcastId}`, {
5343
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/broadcasts/${broadcastId}`, {
3448
5344
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey }
3449
5345
  });
3450
5346
  if (!res.ok) throw new Error(`Failed to get broadcast: ${res.status}`);
@@ -3460,7 +5356,7 @@ var VoidlyAgent = class _VoidlyAgent {
3460
5356
  async getAnalytics(period) {
3461
5357
  const params = new URLSearchParams();
3462
5358
  if (period) params.set("period", period);
3463
- const res = await fetch(`${this.baseUrl}/v1/agent/analytics?${params}`, {
5359
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/analytics?${params}`, {
3464
5360
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey }
3465
5361
  });
3466
5362
  if (!res.ok) throw new Error(`Failed to get analytics: ${res.status}`);
@@ -3484,16 +5380,30 @@ var VoidlyAgent = class _VoidlyAgent {
3484
5380
  // ─── Memory Store ──────────────────────────────────────────────────────────
3485
5381
  /**
3486
5382
  * Store an encrypted key-value pair in persistent memory.
3487
- * Values are encrypted with a key derived from your API key — only you can read them.
5383
+ * Values are encrypted CLIENT-SIDE with nacl.secretbox before sending to relay.
5384
+ * The relay never sees plaintext values — true E2E encrypted storage.
3488
5385
  */
3489
5386
  async memorySet(namespace, key, value, options) {
3490
- const res = await fetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {
5387
+ const valueStr = JSON.stringify(value);
5388
+ const valueBytes = (0, import_tweetnacl_util.decodeUTF8)(valueStr);
5389
+ const memNonce = import_tweetnacl.default.randomBytes(import_tweetnacl.default.secretbox.nonceLength);
5390
+ const memKeyInput = new Uint8Array([...this.encryptionKeyPair.secretKey, 77, 69, 77]);
5391
+ let memKey;
5392
+ if (typeof globalThis.crypto?.subtle !== "undefined") {
5393
+ memKey = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", memKeyInput));
5394
+ } else {
5395
+ const { createHash } = await import("crypto");
5396
+ memKey = new Uint8Array(createHash("sha256").update(Buffer.from(memKeyInput)).digest());
5397
+ }
5398
+ const encryptedValue = import_tweetnacl.default.secretbox(valueBytes, memNonce, memKey);
5399
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {
3491
5400
  method: "PUT",
3492
5401
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3493
5402
  body: JSON.stringify({
3494
- value,
3495
- value_type: options?.valueType || (typeof value === "object" ? "json" : typeof value),
3496
- ttl: options?.ttl
5403
+ value: (0, import_tweetnacl_util.encodeBase64)(encryptedValue),
5404
+ value_type: `encrypted:${options?.valueType || (typeof value === "object" ? "json" : typeof value)}`,
5405
+ ttl: options?.ttl,
5406
+ client_nonce: (0, import_tweetnacl_util.encodeBase64)(memNonce)
3497
5407
  })
3498
5408
  });
3499
5409
  if (!res.ok) throw new Error(`Memory set failed: ${res.status} ${await res.text()}`);
@@ -3501,21 +5411,42 @@ var VoidlyAgent = class _VoidlyAgent {
3501
5411
  }
3502
5412
  /**
3503
5413
  * Retrieve a value from persistent memory.
3504
- * Decrypted server-side using your API key derivation.
5414
+ * Decrypted CLIENT-SIDE relay never sees plaintext.
3505
5415
  */
3506
5416
  async memoryGet(namespace, key) {
3507
- const res = await fetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {
5417
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {
3508
5418
  headers: { "X-Agent-Key": this.apiKey }
3509
5419
  });
3510
5420
  if (res.status === 404) return null;
3511
5421
  if (!res.ok) throw new Error(`Memory get failed: ${res.status} ${await res.text()}`);
3512
- return res.json();
5422
+ const data = await res.json();
5423
+ if (data.value_type?.startsWith("encrypted:") && data.client_nonce) {
5424
+ try {
5425
+ const memKeyInput = new Uint8Array([...this.encryptionKeyPair.secretKey, 77, 69, 77]);
5426
+ let memKey;
5427
+ if (typeof globalThis.crypto?.subtle !== "undefined") {
5428
+ memKey = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", memKeyInput));
5429
+ } else {
5430
+ const { createHash } = await import("crypto");
5431
+ memKey = new Uint8Array(createHash("sha256").update(Buffer.from(memKeyInput)).digest());
5432
+ }
5433
+ const encBytes = (0, import_tweetnacl_util.decodeBase64)(data.value);
5434
+ const memNonce = (0, import_tweetnacl_util.decodeBase64)(data.client_nonce);
5435
+ const plain = import_tweetnacl.default.secretbox.open(encBytes, memNonce, memKey);
5436
+ if (plain) {
5437
+ data.value = JSON.parse((0, import_tweetnacl_util.encodeUTF8)(plain));
5438
+ data.value_type = data.value_type.replace("encrypted:", "");
5439
+ }
5440
+ } catch {
5441
+ }
5442
+ }
5443
+ return data;
3513
5444
  }
3514
5445
  /**
3515
5446
  * Delete a key from persistent memory.
3516
5447
  */
3517
5448
  async memoryDelete(namespace, key) {
3518
- const res = await fetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {
5449
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {
3519
5450
  method: "DELETE",
3520
5451
  headers: { "X-Agent-Key": this.apiKey }
3521
5452
  });
@@ -3531,7 +5462,7 @@ var VoidlyAgent = class _VoidlyAgent {
3531
5462
  if (options?.prefix) params.set("prefix", options.prefix);
3532
5463
  if (options?.limit) params.set("limit", String(options.limit));
3533
5464
  const qs = params.toString() ? `?${params.toString()}` : "";
3534
- const res = await fetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(ns)}${qs}`, {
5465
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(ns)}${qs}`, {
3535
5466
  headers: { "X-Agent-Key": this.apiKey }
3536
5467
  });
3537
5468
  if (!res.ok) throw new Error(`Memory list failed: ${res.status} ${await res.text()}`);
@@ -3541,7 +5472,7 @@ var VoidlyAgent = class _VoidlyAgent {
3541
5472
  * List all memory namespaces and quota usage.
3542
5473
  */
3543
5474
  async memoryNamespaces() {
3544
- const res = await fetch(`${this.baseUrl}/v1/agent/memory`, {
5475
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/memory`, {
3545
5476
  headers: { "X-Agent-Key": this.apiKey }
3546
5477
  });
3547
5478
  if (!res.ok) throw new Error(`Memory namespaces failed: ${res.status} ${await res.text()}`);
@@ -3554,7 +5485,7 @@ var VoidlyAgent = class _VoidlyAgent {
3554
5485
  * Memory values remain encrypted — portable to another relay.
3555
5486
  */
3556
5487
  async exportData(options) {
3557
- const res = await fetch(`${this.baseUrl}/v1/agent/export`, {
5488
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/export`, {
3558
5489
  method: "POST",
3559
5490
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3560
5491
  body: JSON.stringify({
@@ -3573,7 +5504,7 @@ var VoidlyAgent = class _VoidlyAgent {
3573
5504
  * List past data export records.
3574
5505
  */
3575
5506
  async listExports() {
3576
- const res = await fetch(`${this.baseUrl}/v1/agent/exports`, {
5507
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/exports`, {
3577
5508
  headers: { "X-Agent-Key": this.apiKey }
3578
5509
  });
3579
5510
  if (!res.ok) throw new Error(`List exports failed: ${res.status} ${await res.text()}`);
@@ -3585,7 +5516,7 @@ var VoidlyAgent = class _VoidlyAgent {
3585
5516
  * Includes federation capabilities and known peers.
3586
5517
  */
3587
5518
  async getRelayInfo() {
3588
- const res = await fetch(`${this.baseUrl}/v1/relay/info`);
5519
+ const res = await this._timedFetch(`${this.baseUrl}/v1/relay/info`);
3589
5520
  if (!res.ok) throw new Error(`Relay info failed: ${res.status} ${await res.text()}`);
3590
5521
  return res.json();
3591
5522
  }
@@ -3593,7 +5524,7 @@ var VoidlyAgent = class _VoidlyAgent {
3593
5524
  * List known federated relay peers.
3594
5525
  */
3595
5526
  async getRelayPeers() {
3596
- const res = await fetch(`${this.baseUrl}/v1/relay/peers`);
5527
+ const res = await this._timedFetch(`${this.baseUrl}/v1/relay/peers`);
3597
5528
  if (!res.ok) throw new Error(`Relay peers failed: ${res.status} ${await res.text()}`);
3598
5529
  return res.json();
3599
5530
  }
@@ -3615,7 +5546,7 @@ var VoidlyAgent = class _VoidlyAgent {
3615
5546
  ciphertext_hash: await sha256((0, import_tweetnacl_util.encodeBase64)(encrypted))
3616
5547
  }));
3617
5548
  const signature = import_tweetnacl.default.sign.detached(signaturePayload, this.signingKeyPair.secretKey);
3618
- const res = await fetch(`${this.baseUrl}/v1/relay/route`, {
5549
+ const res = await this._timedFetch(`${this.baseUrl}/v1/relay/route`, {
3619
5550
  method: "POST",
3620
5551
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3621
5552
  body: JSON.stringify({
@@ -3633,7 +5564,7 @@ var VoidlyAgent = class _VoidlyAgent {
3633
5564
  // ── Heartbeat ──────────────────────────────────────────────────────────────
3634
5565
  /** Send heartbeat — signals agent is alive, updates last_seen */
3635
5566
  async ping() {
3636
- const res = await fetch(`${this.baseUrl}/v1/agent/ping`, {
5567
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/ping`, {
3637
5568
  method: "POST",
3638
5569
  headers: { "X-Agent-Key": this.apiKey }
3639
5570
  });
@@ -3642,14 +5573,14 @@ var VoidlyAgent = class _VoidlyAgent {
3642
5573
  }
3643
5574
  /** Check if another agent is online (public) */
3644
5575
  async checkOnline(did) {
3645
- const res = await fetch(`${this.baseUrl}/v1/agent/ping/${encodeURIComponent(did)}`);
5576
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/ping/${encodeURIComponent(did)}`);
3646
5577
  if (!res.ok) throw new Error(`Ping check failed: ${res.status}`);
3647
5578
  return res.json();
3648
5579
  }
3649
5580
  // ── Key Pinning (TOFU) ────────────────────────────────────────────────────
3650
5581
  /** Pin another agent's public keys (Trust On First Use). Returns warning if keys changed since last pin. */
3651
5582
  async pinKeys(did) {
3652
- const res = await fetch(`${this.baseUrl}/v1/agent/keys/pin`, {
5583
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/keys/pin`, {
3653
5584
  method: "POST",
3654
5585
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3655
5586
  body: JSON.stringify({ did })
@@ -3662,7 +5593,7 @@ var VoidlyAgent = class _VoidlyAgent {
3662
5593
  const params = new URLSearchParams();
3663
5594
  if (options?.status) params.set("status", options.status);
3664
5595
  const qs = params.toString() ? `?${params.toString()}` : "";
3665
- const res = await fetch(`${this.baseUrl}/v1/agent/keys/pins${qs}`, {
5596
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/keys/pins${qs}`, {
3666
5597
  headers: { "X-Agent-Key": this.apiKey }
3667
5598
  });
3668
5599
  if (!res.ok) throw new Error(`List pins failed: ${res.status}`);
@@ -3670,7 +5601,7 @@ var VoidlyAgent = class _VoidlyAgent {
3670
5601
  }
3671
5602
  /** Verify an agent's keys against your pinned copy. Detects key changes (potential MitM). */
3672
5603
  async verifyKeys(did) {
3673
- const res = await fetch(`${this.baseUrl}/v1/agent/keys/verify/${encodeURIComponent(did)}`, {
5604
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/keys/verify/${encodeURIComponent(did)}`, {
3674
5605
  headers: { "X-Agent-Key": this.apiKey }
3675
5606
  });
3676
5607
  if (!res.ok) throw new Error(`Key verify failed: ${res.status}`);
@@ -3881,6 +5812,21 @@ var VoidlyAgent = class _VoidlyAgent {
3881
5812
  // ═══════════════════════════════════════════════════════════════════════════
3882
5813
  // INTERNAL — Retry, Auto-Pin
3883
5814
  // ═══════════════════════════════════════════════════════════════════════════
5815
+ /** @internal Fetch with timeout via AbortController */
5816
+ async _timedFetch(url, init) {
5817
+ const controller = new AbortController();
5818
+ const timer = setTimeout(() => controller.abort(), this.timeout);
5819
+ try {
5820
+ return await fetch(url, { ...init, signal: controller.signal });
5821
+ } catch (err) {
5822
+ if (err instanceof Error && err.name === "AbortError") {
5823
+ throw new Error(`Request timed out after ${this.timeout}ms: ${url.replace(this.baseUrl, "")}`);
5824
+ }
5825
+ throw err;
5826
+ } finally {
5827
+ clearTimeout(timer);
5828
+ }
5829
+ }
3884
5830
  /** @internal Auto-pin keys on first contact (TOFU) */
3885
5831
  async _autoPinKeys(did) {
3886
5832
  if (this._pinnedDids.has(did)) return;
@@ -3901,7 +5847,7 @@ var VoidlyAgent = class _VoidlyAgent {
3901
5847
  let lastError = null;
3902
5848
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
3903
5849
  try {
3904
- const res = await fetch(url, init);
5850
+ const res = await this._timedFetch(url, init);
3905
5851
  if (res.ok) {
3906
5852
  return await res.json();
3907
5853
  }
@@ -3978,31 +5924,42 @@ var VoidlyAgent = class _VoidlyAgent {
3978
5924
  "Approximate message size (even with padding, bounded to power-of-2)"
3979
5925
  ],
3980
5926
  relayCannotSee: [
3981
- "Message content (E2E encrypted with NaCl box)",
5927
+ "Message content (E2E encrypted \u2014 nacl.secretbox with ratchet-derived per-message keys)",
3982
5928
  "Private keys (generated and stored client-side only)",
3983
- "Memory values (encrypted with key derived from your API key)",
3984
- "Attestation content (signed but readable by anyone with the attestation)",
5929
+ "Memory values (encrypted CLIENT-SIDE with nacl.secretbox before relay storage)",
5930
+ "Past message keys (hash ratchet provides forward secrecy \u2014 old keys are deleted)",
3985
5931
  ...this.sealedSender ? ["Sender identity (sealed inside ciphertext)"] : []
3986
5932
  ],
3987
5933
  protections: [
5934
+ "Hash ratchet forward secrecy \u2014 per-message key derivation, old keys deleted",
5935
+ ...this.postQuantum && this.mlkemPublicKey ? ["ML-KEM-768 + X25519 hybrid key exchange (NIST FIPS 203 post-quantum, harvest-now-decrypt-later resistant)"] : [],
3988
5936
  "X25519 key exchange + XSalsa20-Poly1305 authenticated encryption",
3989
- "Ed25519 signatures on every message",
5937
+ "Ed25519 signatures on every message (envelope + ciphertext hash)",
3990
5938
  "TOFU key pinning (MitM detection on key change)",
5939
+ "Client-side memory encryption (relay never sees plaintext values)",
5940
+ "Protocol version header (deterministic padding/sealing detection, no heuristics)",
5941
+ "Identity cache (reduced key lookups, 5-min TTL)",
5942
+ "Message deduplication (track seen message IDs)",
5943
+ "Request timeouts (AbortController on all HTTP, configurable)",
5944
+ "Request validation (fromCredentials validates key sizes and format)",
3991
5945
  ...this.paddingEnabled ? ["Message padding to power-of-2 boundary (traffic analysis resistance)"] : [],
3992
5946
  ...this.sealedSender ? ["Sealed sender (relay cannot see who sent a message)"] : [],
5947
+ ...this.requireSignatures ? ["Strict signature enforcement (reject unsigned/invalid messages)"] : [],
3993
5948
  ...this.fallbackRelays.length > 0 ? [`Multi-relay fallback (${this.fallbackRelays.length} backup relays)`] : [],
3994
5949
  "Auto-retry with exponential backoff",
3995
- "Offline message queue"
5950
+ "Offline message queue",
5951
+ "did:key interoperability (W3C standard DID format)"
3996
5952
  ],
3997
5953
  gaps: [
3998
- "No forward secrecy \u2014 same keypair for all messages (compromise exposes ALL history)",
3999
- "No post-quantum protection \u2014 vulnerable to harvest-now-decrypt-later",
5954
+ "No DH ratchet yet \u2014 hash ratchet only (no post-compromise recovery, planned for v3)",
5955
+ ...!this.postQuantum || !this.mlkemPublicKey ? ["No post-quantum protection \u2014 enable postQuantum option and re-register"] : [],
4000
5956
  "Channel encryption is server-side (relay holds channel keys, NOT true E2E)",
4001
5957
  "Metadata (who, when, thread structure) visible to relay operator",
4002
5958
  "Single relay architecture (no onion routing, no mix network)",
4003
5959
  "Ed25519 signatures are non-repudiable (no deniable messaging)",
4004
5960
  "No async key agreement (no X3DH prekeys)",
4005
- "Polling-based (no WebSocket real-time transport)"
5961
+ "Polling-based (no WebSocket real-time transport)",
5962
+ "Ratchet state is in-memory (lost on process restart \u2014 export credentials to persist)"
4006
5963
  ]
4007
5964
  };
4008
5965
  }
@@ -4028,6 +5985,9 @@ var Conversation = class {
4028
5985
  replyTo: this._lastMessageId || void 0
4029
5986
  });
4030
5987
  this._lastMessageId = result.id;
5988
+ if (this._messageHistory.length >= 1e3) {
5989
+ this._messageHistory.splice(0, this._messageHistory.length - 999);
5990
+ }
4031
5991
  this._messageHistory.push({
4032
5992
  id: result.id,
4033
5993
  from: this.agent.did,
@@ -4082,9 +6042,9 @@ var Conversation = class {
4082
6042
  messageType: msg.messageType
4083
6043
  });
4084
6044
  this._lastMessageId = msg.id;
4085
- for (const h of this._replyHandlers) {
6045
+ for (const h2 of this._replyHandlers) {
4086
6046
  try {
4087
- await h(msg);
6047
+ await h2(msg);
4088
6048
  } catch {
4089
6049
  }
4090
6050
  }
@@ -4102,14 +6062,23 @@ var Conversation = class {
4102
6062
  async waitForReply(timeoutMs = 3e4) {
4103
6063
  return new Promise((resolve, reject) => {
4104
6064
  let resolved = false;
6065
+ let pollTimer = null;
6066
+ const cleanup = () => {
6067
+ resolved = true;
6068
+ if (pollTimer) {
6069
+ clearTimeout(pollTimer);
6070
+ pollTimer = null;
6071
+ }
6072
+ };
4105
6073
  const timeout = setTimeout(() => {
4106
6074
  if (!resolved) {
4107
- resolved = true;
6075
+ cleanup();
4108
6076
  reject(new Error(`No reply received within ${timeoutMs}ms`));
4109
6077
  }
4110
6078
  }, timeoutMs);
4111
6079
  const check = async () => {
4112
- while (!resolved) {
6080
+ if (resolved) return;
6081
+ try {
4113
6082
  const messages = await this.agent.receive({
4114
6083
  from: this.peerDid,
4115
6084
  threadId: this.threadId,
@@ -4117,9 +6086,12 @@ var Conversation = class {
4117
6086
  limit: 1
4118
6087
  });
4119
6088
  if (messages.length > 0 && !resolved) {
4120
- resolved = true;
4121
6089
  clearTimeout(timeout);
6090
+ cleanup();
4122
6091
  const msg = messages[0];
6092
+ if (this._messageHistory.length >= 1e3) {
6093
+ this._messageHistory.splice(0, this._messageHistory.length - 999);
6094
+ }
4123
6095
  this._messageHistory.push({
4124
6096
  id: msg.id,
4125
6097
  from: msg.from,
@@ -4134,16 +6106,19 @@ var Conversation = class {
4134
6106
  resolve(msg);
4135
6107
  return;
4136
6108
  }
4137
- await new Promise((r) => setTimeout(r, 1500));
6109
+ } catch (err) {
6110
+ if (!resolved) {
6111
+ clearTimeout(timeout);
6112
+ cleanup();
6113
+ reject(err instanceof Error ? err : new Error(String(err)));
6114
+ return;
6115
+ }
4138
6116
  }
4139
- };
4140
- check().catch((err) => {
4141
6117
  if (!resolved) {
4142
- resolved = true;
4143
- clearTimeout(timeout);
4144
- reject(err);
6118
+ pollTimer = setTimeout(check, 1500);
4145
6119
  }
4146
- });
6120
+ };
6121
+ check();
4147
6122
  });
4148
6123
  }
4149
6124
  /**
@@ -4175,3 +6150,8 @@ var Conversation = class {
4175
6150
  encodeUTF8,
4176
6151
  nacl
4177
6152
  });
6153
+ /*! Bundled license information:
6154
+
6155
+ mlkem/esm/src/sha3/utils.js:
6156
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
6157
+ */