@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.mjs 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
  });
@@ -2326,6 +2326,1603 @@ var require_nacl_util = __commonJS({
2326
2326
  // src/index.ts
2327
2327
  var import_tweetnacl = __toESM(require_nacl_fast());
2328
2328
  var import_tweetnacl_util = __toESM(require_nacl_util());
2329
+
2330
+ // node_modules/mlkem/esm/src/errors.js
2331
+ var MlKemError = class extends Error {
2332
+ constructor(e) {
2333
+ let message;
2334
+ if (e instanceof Error) {
2335
+ message = e.message;
2336
+ } else if (typeof e === "string") {
2337
+ message = e;
2338
+ } else {
2339
+ message = "";
2340
+ }
2341
+ super(message);
2342
+ this.name = this.constructor.name;
2343
+ }
2344
+ };
2345
+
2346
+ // node_modules/mlkem/esm/src/consts.js
2347
+ var N = 256;
2348
+ var Q = 3329;
2349
+ var Q_INV = 62209;
2350
+ var NTT_ZETAS = [
2351
+ 2285,
2352
+ 2571,
2353
+ 2970,
2354
+ 1812,
2355
+ 1493,
2356
+ 1422,
2357
+ 287,
2358
+ 202,
2359
+ 3158,
2360
+ 622,
2361
+ 1577,
2362
+ 182,
2363
+ 962,
2364
+ 2127,
2365
+ 1855,
2366
+ 1468,
2367
+ 573,
2368
+ 2004,
2369
+ 264,
2370
+ 383,
2371
+ 2500,
2372
+ 1458,
2373
+ 1727,
2374
+ 3199,
2375
+ 2648,
2376
+ 1017,
2377
+ 732,
2378
+ 608,
2379
+ 1787,
2380
+ 411,
2381
+ 3124,
2382
+ 1758,
2383
+ 1223,
2384
+ 652,
2385
+ 2777,
2386
+ 1015,
2387
+ 2036,
2388
+ 1491,
2389
+ 3047,
2390
+ 1785,
2391
+ 516,
2392
+ 3321,
2393
+ 3009,
2394
+ 2663,
2395
+ 1711,
2396
+ 2167,
2397
+ 126,
2398
+ 1469,
2399
+ 2476,
2400
+ 3239,
2401
+ 3058,
2402
+ 830,
2403
+ 107,
2404
+ 1908,
2405
+ 3082,
2406
+ 2378,
2407
+ 2931,
2408
+ 961,
2409
+ 1821,
2410
+ 2604,
2411
+ 448,
2412
+ 2264,
2413
+ 677,
2414
+ 2054,
2415
+ 2226,
2416
+ 430,
2417
+ 555,
2418
+ 843,
2419
+ 2078,
2420
+ 871,
2421
+ 1550,
2422
+ 105,
2423
+ 422,
2424
+ 587,
2425
+ 177,
2426
+ 3094,
2427
+ 3038,
2428
+ 2869,
2429
+ 1574,
2430
+ 1653,
2431
+ 3083,
2432
+ 778,
2433
+ 1159,
2434
+ 3182,
2435
+ 2552,
2436
+ 1483,
2437
+ 2727,
2438
+ 1119,
2439
+ 1739,
2440
+ 644,
2441
+ 2457,
2442
+ 349,
2443
+ 418,
2444
+ 329,
2445
+ 3173,
2446
+ 3254,
2447
+ 817,
2448
+ 1097,
2449
+ 603,
2450
+ 610,
2451
+ 1322,
2452
+ 2044,
2453
+ 1864,
2454
+ 384,
2455
+ 2114,
2456
+ 3193,
2457
+ 1218,
2458
+ 1994,
2459
+ 2455,
2460
+ 220,
2461
+ 2142,
2462
+ 1670,
2463
+ 2144,
2464
+ 1799,
2465
+ 2051,
2466
+ 794,
2467
+ 1819,
2468
+ 2475,
2469
+ 2459,
2470
+ 478,
2471
+ 3221,
2472
+ 3021,
2473
+ 996,
2474
+ 991,
2475
+ 958,
2476
+ 1869,
2477
+ 1522,
2478
+ 1628
2479
+ ];
2480
+ var NTT_ZETAS_INV = [
2481
+ 1701,
2482
+ 1807,
2483
+ 1460,
2484
+ 2371,
2485
+ 2338,
2486
+ 2333,
2487
+ 308,
2488
+ 108,
2489
+ 2851,
2490
+ 870,
2491
+ 854,
2492
+ 1510,
2493
+ 2535,
2494
+ 1278,
2495
+ 1530,
2496
+ 1185,
2497
+ 1659,
2498
+ 1187,
2499
+ 3109,
2500
+ 874,
2501
+ 1335,
2502
+ 2111,
2503
+ 136,
2504
+ 1215,
2505
+ 2945,
2506
+ 1465,
2507
+ 1285,
2508
+ 2007,
2509
+ 2719,
2510
+ 2726,
2511
+ 2232,
2512
+ 2512,
2513
+ 75,
2514
+ 156,
2515
+ 3e3,
2516
+ 2911,
2517
+ 2980,
2518
+ 872,
2519
+ 2685,
2520
+ 1590,
2521
+ 2210,
2522
+ 602,
2523
+ 1846,
2524
+ 777,
2525
+ 147,
2526
+ 2170,
2527
+ 2551,
2528
+ 246,
2529
+ 1676,
2530
+ 1755,
2531
+ 460,
2532
+ 291,
2533
+ 235,
2534
+ 3152,
2535
+ 2742,
2536
+ 2907,
2537
+ 3224,
2538
+ 1779,
2539
+ 2458,
2540
+ 1251,
2541
+ 2486,
2542
+ 2774,
2543
+ 2899,
2544
+ 1103,
2545
+ 1275,
2546
+ 2652,
2547
+ 1065,
2548
+ 2881,
2549
+ 725,
2550
+ 1508,
2551
+ 2368,
2552
+ 398,
2553
+ 951,
2554
+ 247,
2555
+ 1421,
2556
+ 3222,
2557
+ 2499,
2558
+ 271,
2559
+ 90,
2560
+ 853,
2561
+ 1860,
2562
+ 3203,
2563
+ 1162,
2564
+ 1618,
2565
+ 666,
2566
+ 320,
2567
+ 8,
2568
+ 2813,
2569
+ 1544,
2570
+ 282,
2571
+ 1838,
2572
+ 1293,
2573
+ 2314,
2574
+ 552,
2575
+ 2677,
2576
+ 2106,
2577
+ 1571,
2578
+ 205,
2579
+ 2918,
2580
+ 1542,
2581
+ 2721,
2582
+ 2597,
2583
+ 2312,
2584
+ 681,
2585
+ 130,
2586
+ 1602,
2587
+ 1871,
2588
+ 829,
2589
+ 2946,
2590
+ 3065,
2591
+ 1325,
2592
+ 2756,
2593
+ 1861,
2594
+ 1474,
2595
+ 1202,
2596
+ 2367,
2597
+ 3147,
2598
+ 1752,
2599
+ 2707,
2600
+ 171,
2601
+ 3127,
2602
+ 3042,
2603
+ 1907,
2604
+ 1836,
2605
+ 1517,
2606
+ 359,
2607
+ 758,
2608
+ 1441
2609
+ ];
2610
+
2611
+ // node_modules/mlkem/esm/src/sha3/_u64.js
2612
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
2613
+ var _32n = /* @__PURE__ */ BigInt(32);
2614
+ function fromBig(n, le = false) {
2615
+ if (le) {
2616
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
2617
+ }
2618
+ return {
2619
+ h: Number(n >> _32n & U32_MASK64) | 0,
2620
+ l: Number(n & U32_MASK64) | 0
2621
+ };
2622
+ }
2623
+ function split(lst, le = false) {
2624
+ const len = lst.length;
2625
+ const Ah = new Uint32Array(len);
2626
+ const Al = new Uint32Array(len);
2627
+ for (let i = 0; i < len; i++) {
2628
+ const { h: h2, l } = fromBig(lst[i], le);
2629
+ [Ah[i], Al[i]] = [h2, l];
2630
+ }
2631
+ return [Ah, Al];
2632
+ }
2633
+ var rotlSH = (h2, l, s) => h2 << s | l >>> 32 - s;
2634
+ var rotlSL = (h2, l, s) => l << s | h2 >>> 32 - s;
2635
+ var rotlBH = (h2, l, s) => l << s - 32 | h2 >>> 64 - s;
2636
+ var rotlBL = (h2, l, s) => h2 << s - 32 | l >>> 64 - s;
2637
+
2638
+ // node_modules/mlkem/esm/src/sha3/utils.js
2639
+ function isBytes(a) {
2640
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
2641
+ }
2642
+ function anumber(n, title = "") {
2643
+ if (!Number.isSafeInteger(n) || n < 0) {
2644
+ const prefix = title && `"${title}" `;
2645
+ throw new Error(`${prefix}expected integer >0, got ${n}`);
2646
+ }
2647
+ }
2648
+ function abytes(value, length, title = "") {
2649
+ const bytes = isBytes(value);
2650
+ const len = value?.length;
2651
+ const needsLen = length !== void 0;
2652
+ if (!bytes || needsLen && len !== length) {
2653
+ const prefix = title && `"${title}" `;
2654
+ const ofLen = needsLen ? ` of length ${length}` : "";
2655
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
2656
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
2657
+ }
2658
+ return value;
2659
+ }
2660
+ function aexists(instance, checkFinished = true) {
2661
+ if (instance.destroyed)
2662
+ throw new Error("Hash instance has been destroyed");
2663
+ if (checkFinished && instance.finished) {
2664
+ throw new Error("Hash#digest() has already been called");
2665
+ }
2666
+ }
2667
+ function aoutput(out, instance) {
2668
+ abytes(out, void 0, "digestInto() output");
2669
+ const min = instance.outputLen;
2670
+ if (out.length < min) {
2671
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
2672
+ }
2673
+ }
2674
+ function u32(arr) {
2675
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
2676
+ }
2677
+ function clean(...arrays) {
2678
+ for (let i = 0; i < arrays.length; i++) {
2679
+ arrays[i].fill(0);
2680
+ }
2681
+ }
2682
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
2683
+ function byteSwap(word) {
2684
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
2685
+ }
2686
+ function byteSwap32(arr) {
2687
+ for (let i = 0; i < arr.length; i++) {
2688
+ arr[i] = byteSwap(arr[i]);
2689
+ }
2690
+ return arr;
2691
+ }
2692
+ var swap32IfBE = isLE ? (u) => u : byteSwap32;
2693
+ function createHasher(hashCons, info = {}) {
2694
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
2695
+ const tmp = hashCons(void 0);
2696
+ hashC.outputLen = tmp.outputLen;
2697
+ hashC.blockLen = tmp.blockLen;
2698
+ hashC.create = (opts) => hashCons(opts);
2699
+ Object.assign(hashC, info);
2700
+ return Object.freeze(hashC);
2701
+ }
2702
+ var oidNist = (suffix) => ({
2703
+ oid: Uint8Array.from([
2704
+ 6,
2705
+ 9,
2706
+ 96,
2707
+ 134,
2708
+ 72,
2709
+ 1,
2710
+ 101,
2711
+ 3,
2712
+ 4,
2713
+ 2,
2714
+ suffix
2715
+ ])
2716
+ });
2717
+
2718
+ // node_modules/mlkem/esm/src/sha3/sha3.js
2719
+ var _0n = BigInt(0);
2720
+ var _1n = BigInt(1);
2721
+ var _2n = BigInt(2);
2722
+ var _7n = BigInt(7);
2723
+ var _256n = BigInt(256);
2724
+ var _0x71n = BigInt(113);
2725
+ var SHA3_PI = [];
2726
+ var SHA3_ROTL = [];
2727
+ var _SHA3_IOTA = [];
2728
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
2729
+ [x, y] = [y, (2 * x + 3 * y) % 5];
2730
+ SHA3_PI.push(2 * (5 * y + x));
2731
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
2732
+ let t = _0n;
2733
+ for (let j = 0; j < 7; j++) {
2734
+ R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
2735
+ if (R & _2n)
2736
+ t ^= _1n << (_1n << BigInt(j)) - _1n;
2737
+ }
2738
+ _SHA3_IOTA.push(t);
2739
+ }
2740
+ var IOTAS = split(_SHA3_IOTA, true);
2741
+ var SHA3_IOTA_H = IOTAS[0];
2742
+ var SHA3_IOTA_L = IOTAS[1];
2743
+ var rotlH = (h2, l, s) => s > 32 ? rotlBH(h2, l, s) : rotlSH(h2, l, s);
2744
+ var rotlL = (h2, l, s) => s > 32 ? rotlBL(h2, l, s) : rotlSL(h2, l, s);
2745
+ function keccakP(s, rounds = 24) {
2746
+ const B = new Uint32Array(5 * 2);
2747
+ for (let round = 24 - rounds; round < 24; round++) {
2748
+ for (let x = 0; x < 10; x++) {
2749
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
2750
+ }
2751
+ for (let x = 0; x < 10; x += 2) {
2752
+ const idx1 = (x + 8) % 10;
2753
+ const idx0 = (x + 2) % 10;
2754
+ const B0 = B[idx0];
2755
+ const B1 = B[idx0 + 1];
2756
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
2757
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
2758
+ for (let y = 0; y < 50; y += 10) {
2759
+ s[x + y] ^= Th;
2760
+ s[x + y + 1] ^= Tl;
2761
+ }
2762
+ }
2763
+ let curH = s[2];
2764
+ let curL = s[3];
2765
+ for (let t = 0; t < 24; t++) {
2766
+ const shift = SHA3_ROTL[t];
2767
+ const Th = rotlH(curH, curL, shift);
2768
+ const Tl = rotlL(curH, curL, shift);
2769
+ const PI = SHA3_PI[t];
2770
+ curH = s[PI];
2771
+ curL = s[PI + 1];
2772
+ s[PI] = Th;
2773
+ s[PI + 1] = Tl;
2774
+ }
2775
+ for (let y = 0; y < 50; y += 10) {
2776
+ for (let x = 0; x < 10; x++)
2777
+ B[x] = s[y + x];
2778
+ for (let x = 0; x < 10; x++) {
2779
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
2780
+ }
2781
+ }
2782
+ s[0] ^= SHA3_IOTA_H[round];
2783
+ s[1] ^= SHA3_IOTA_L[round];
2784
+ }
2785
+ clean(B);
2786
+ }
2787
+ var Keccak = class _Keccak {
2788
+ // NOTE: we accept arguments in bytes instead of bits here.
2789
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
2790
+ Object.defineProperty(this, "state", {
2791
+ enumerable: true,
2792
+ configurable: true,
2793
+ writable: true,
2794
+ value: void 0
2795
+ });
2796
+ Object.defineProperty(this, "pos", {
2797
+ enumerable: true,
2798
+ configurable: true,
2799
+ writable: true,
2800
+ value: 0
2801
+ });
2802
+ Object.defineProperty(this, "posOut", {
2803
+ enumerable: true,
2804
+ configurable: true,
2805
+ writable: true,
2806
+ value: 0
2807
+ });
2808
+ Object.defineProperty(this, "finished", {
2809
+ enumerable: true,
2810
+ configurable: true,
2811
+ writable: true,
2812
+ value: false
2813
+ });
2814
+ Object.defineProperty(this, "state32", {
2815
+ enumerable: true,
2816
+ configurable: true,
2817
+ writable: true,
2818
+ value: void 0
2819
+ });
2820
+ Object.defineProperty(this, "destroyed", {
2821
+ enumerable: true,
2822
+ configurable: true,
2823
+ writable: true,
2824
+ value: false
2825
+ });
2826
+ Object.defineProperty(this, "blockLen", {
2827
+ enumerable: true,
2828
+ configurable: true,
2829
+ writable: true,
2830
+ value: void 0
2831
+ });
2832
+ Object.defineProperty(this, "suffix", {
2833
+ enumerable: true,
2834
+ configurable: true,
2835
+ writable: true,
2836
+ value: void 0
2837
+ });
2838
+ Object.defineProperty(this, "outputLen", {
2839
+ enumerable: true,
2840
+ configurable: true,
2841
+ writable: true,
2842
+ value: void 0
2843
+ });
2844
+ Object.defineProperty(this, "enableXOF", {
2845
+ enumerable: true,
2846
+ configurable: true,
2847
+ writable: true,
2848
+ value: false
2849
+ });
2850
+ Object.defineProperty(this, "rounds", {
2851
+ enumerable: true,
2852
+ configurable: true,
2853
+ writable: true,
2854
+ value: void 0
2855
+ });
2856
+ this.blockLen = blockLen;
2857
+ this.suffix = suffix;
2858
+ this.outputLen = outputLen;
2859
+ this.enableXOF = enableXOF;
2860
+ this.rounds = rounds;
2861
+ anumber(outputLen, "outputLen");
2862
+ if (!(0 < blockLen && blockLen < 200)) {
2863
+ throw new Error("only keccak-f1600 function is supported");
2864
+ }
2865
+ this.state = new Uint8Array(200);
2866
+ this.state32 = u32(this.state);
2867
+ }
2868
+ clone() {
2869
+ return this._cloneInto();
2870
+ }
2871
+ keccak() {
2872
+ swap32IfBE(this.state32);
2873
+ keccakP(this.state32, this.rounds);
2874
+ swap32IfBE(this.state32);
2875
+ this.posOut = 0;
2876
+ this.pos = 0;
2877
+ }
2878
+ update(data) {
2879
+ aexists(this);
2880
+ abytes(data);
2881
+ const { blockLen, state } = this;
2882
+ const len = data.length;
2883
+ for (let pos = 0; pos < len; ) {
2884
+ const take = Math.min(blockLen - this.pos, len - pos);
2885
+ for (let i = 0; i < take; i++)
2886
+ state[this.pos++] ^= data[pos++];
2887
+ if (this.pos === blockLen)
2888
+ this.keccak();
2889
+ }
2890
+ return this;
2891
+ }
2892
+ finish() {
2893
+ if (this.finished)
2894
+ return;
2895
+ this.finished = true;
2896
+ const { state, suffix, pos, blockLen } = this;
2897
+ state[pos] ^= suffix;
2898
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
2899
+ this.keccak();
2900
+ state[blockLen - 1] ^= 128;
2901
+ this.keccak();
2902
+ }
2903
+ writeInto(out) {
2904
+ aexists(this, false);
2905
+ abytes(out);
2906
+ this.finish();
2907
+ const bufferOut = this.state;
2908
+ const { blockLen } = this;
2909
+ for (let pos = 0, len = out.length; pos < len; ) {
2910
+ if (this.posOut >= blockLen)
2911
+ this.keccak();
2912
+ const take = Math.min(blockLen - this.posOut, len - pos);
2913
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
2914
+ this.posOut += take;
2915
+ pos += take;
2916
+ }
2917
+ return out;
2918
+ }
2919
+ xofInto(out) {
2920
+ if (!this.enableXOF) {
2921
+ throw new Error("XOF is not possible for this instance");
2922
+ }
2923
+ return this.writeInto(out);
2924
+ }
2925
+ xof(bytes) {
2926
+ anumber(bytes);
2927
+ return this.xofInto(new Uint8Array(bytes));
2928
+ }
2929
+ digestInto(out) {
2930
+ aoutput(out, this);
2931
+ if (this.finished)
2932
+ throw new Error("digest() was already called");
2933
+ this.writeInto(out);
2934
+ this.destroy();
2935
+ return out;
2936
+ }
2937
+ digest() {
2938
+ return this.digestInto(new Uint8Array(this.outputLen));
2939
+ }
2940
+ destroy() {
2941
+ this.destroyed = true;
2942
+ clean(this.state);
2943
+ }
2944
+ _cloneInto(to) {
2945
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
2946
+ to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
2947
+ to.state32.set(this.state32);
2948
+ to.pos = this.pos;
2949
+ to.posOut = this.posOut;
2950
+ to.finished = this.finished;
2951
+ to.rounds = rounds;
2952
+ to.suffix = suffix;
2953
+ to.outputLen = outputLen;
2954
+ to.enableXOF = enableXOF;
2955
+ to.destroyed = this.destroyed;
2956
+ return to;
2957
+ }
2958
+ };
2959
+ var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
2960
+ var sha3_256 = /* @__PURE__ */ genKeccak(
2961
+ 6,
2962
+ 136,
2963
+ 32,
2964
+ /* @__PURE__ */ oidNist(8)
2965
+ );
2966
+ var sha3_512 = /* @__PURE__ */ genKeccak(
2967
+ 6,
2968
+ 72,
2969
+ 64,
2970
+ /* @__PURE__ */ oidNist(10)
2971
+ );
2972
+ var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true), info);
2973
+ var shake128 = /* @__PURE__ */ genShake(31, 168, 16, /* @__PURE__ */ oidNist(11));
2974
+ var shake256 = /* @__PURE__ */ genShake(31, 136, 32, /* @__PURE__ */ oidNist(12));
2975
+
2976
+ // node_modules/mlkem/esm/_dnt.shims.js
2977
+ var dntGlobals = {};
2978
+ var dntGlobalThis = createMergeProxy(globalThis, dntGlobals);
2979
+ function createMergeProxy(baseObj, extObj) {
2980
+ return new Proxy(baseObj, {
2981
+ get(_target, prop, _receiver) {
2982
+ if (prop in extObj) {
2983
+ return extObj[prop];
2984
+ } else {
2985
+ return baseObj[prop];
2986
+ }
2987
+ },
2988
+ set(_target, prop, value) {
2989
+ if (prop in extObj) {
2990
+ delete extObj[prop];
2991
+ }
2992
+ baseObj[prop] = value;
2993
+ return true;
2994
+ },
2995
+ deleteProperty(_target, prop) {
2996
+ let success = false;
2997
+ if (prop in extObj) {
2998
+ delete extObj[prop];
2999
+ success = true;
3000
+ }
3001
+ if (prop in baseObj) {
3002
+ delete baseObj[prop];
3003
+ success = true;
3004
+ }
3005
+ return success;
3006
+ },
3007
+ ownKeys(_target) {
3008
+ const baseKeys = Reflect.ownKeys(baseObj);
3009
+ const extKeys = Reflect.ownKeys(extObj);
3010
+ const extKeysSet = new Set(extKeys);
3011
+ return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];
3012
+ },
3013
+ defineProperty(_target, prop, desc) {
3014
+ if (prop in extObj) {
3015
+ delete extObj[prop];
3016
+ }
3017
+ Reflect.defineProperty(baseObj, prop, desc);
3018
+ return true;
3019
+ },
3020
+ getOwnPropertyDescriptor(_target, prop) {
3021
+ if (prop in extObj) {
3022
+ return Reflect.getOwnPropertyDescriptor(extObj, prop);
3023
+ } else {
3024
+ return Reflect.getOwnPropertyDescriptor(baseObj, prop);
3025
+ }
3026
+ },
3027
+ has(_target, prop) {
3028
+ return prop in extObj || prop in baseObj;
3029
+ }
3030
+ });
3031
+ }
3032
+
3033
+ // node_modules/mlkem/esm/src/utils.js
3034
+ function byte(n) {
3035
+ return n % 256;
3036
+ }
3037
+ function int16(n) {
3038
+ const end = -32768;
3039
+ const start = 32767;
3040
+ if (n >= end && n <= start) {
3041
+ return n;
3042
+ }
3043
+ if (n < end) {
3044
+ n = n + 32769;
3045
+ n = n % 65536;
3046
+ return start + n;
3047
+ }
3048
+ n = n - 32768;
3049
+ n = n % 65536;
3050
+ return end + n;
3051
+ }
3052
+ function uint16(n) {
3053
+ return n % 65536;
3054
+ }
3055
+ function int32(n) {
3056
+ const end = -2147483648;
3057
+ const start = 2147483647;
3058
+ if (n >= end && n <= start) {
3059
+ return n;
3060
+ }
3061
+ if (n < end) {
3062
+ n = n + 2147483649;
3063
+ n = n % 4294967296;
3064
+ return start + n;
3065
+ }
3066
+ n = n - 2147483648;
3067
+ n = n % 4294967296;
3068
+ return end + n;
3069
+ }
3070
+ function uint32(n) {
3071
+ return n % 4294967296;
3072
+ }
3073
+ function constantTimeCompare(x, y) {
3074
+ if (x.length != y.length) {
3075
+ return 0;
3076
+ }
3077
+ const v = new Uint8Array([0]);
3078
+ for (let i = 0; i < x.length; i++) {
3079
+ v[0] |= x[i] ^ y[i];
3080
+ }
3081
+ const z = new Uint8Array([0]);
3082
+ z[0] = ~(v[0] ^ z[0]);
3083
+ z[0] &= z[0] >> 4;
3084
+ z[0] &= z[0] >> 2;
3085
+ z[0] &= z[0] >> 1;
3086
+ return z[0];
3087
+ }
3088
+ function equalUint8Array(x, y) {
3089
+ if (x.length != y.length) {
3090
+ return false;
3091
+ }
3092
+ for (let i = 0; i < x.length; i++) {
3093
+ if (x[i] !== y[i]) {
3094
+ return false;
3095
+ }
3096
+ }
3097
+ return true;
3098
+ }
3099
+ async function loadCrypto() {
3100
+ if (typeof dntGlobalThis !== "undefined" && globalThis.crypto !== void 0) {
3101
+ return globalThis.crypto;
3102
+ }
3103
+ try {
3104
+ const { webcrypto } = await import("crypto");
3105
+ return webcrypto;
3106
+ } catch (_e) {
3107
+ throw new Error("failed to load Crypto");
3108
+ }
3109
+ }
3110
+ function prf(len, seed, nonce) {
3111
+ return shake256.create({ dkLen: len }).update(seed).update(new Uint8Array([nonce])).digest();
3112
+ }
3113
+ function byteopsLoad32(x) {
3114
+ let r = uint32(x[0]);
3115
+ r |= uint32(x[1]) << 8;
3116
+ r |= uint32(x[2]) << 16;
3117
+ r |= uint32(x[3]) << 24;
3118
+ return uint32(r);
3119
+ }
3120
+
3121
+ // node_modules/mlkem/esm/src/mlKemBase.js
3122
+ var MlKemBase = class {
3123
+ /**
3124
+ * Creates a new instance of the MlKemBase class.
3125
+ */
3126
+ constructor() {
3127
+ Object.defineProperty(this, "_api", {
3128
+ enumerable: true,
3129
+ configurable: true,
3130
+ writable: true,
3131
+ value: void 0
3132
+ });
3133
+ Object.defineProperty(this, "_k", {
3134
+ enumerable: true,
3135
+ configurable: true,
3136
+ writable: true,
3137
+ value: 0
3138
+ });
3139
+ Object.defineProperty(this, "_du", {
3140
+ enumerable: true,
3141
+ configurable: true,
3142
+ writable: true,
3143
+ value: 0
3144
+ });
3145
+ Object.defineProperty(this, "_dv", {
3146
+ enumerable: true,
3147
+ configurable: true,
3148
+ writable: true,
3149
+ value: 0
3150
+ });
3151
+ Object.defineProperty(this, "_eta1", {
3152
+ enumerable: true,
3153
+ configurable: true,
3154
+ writable: true,
3155
+ value: 0
3156
+ });
3157
+ Object.defineProperty(this, "_eta2", {
3158
+ enumerable: true,
3159
+ configurable: true,
3160
+ writable: true,
3161
+ value: 0
3162
+ });
3163
+ Object.defineProperty(this, "_skSize", {
3164
+ enumerable: true,
3165
+ configurable: true,
3166
+ writable: true,
3167
+ value: 0
3168
+ });
3169
+ Object.defineProperty(this, "_pkSize", {
3170
+ enumerable: true,
3171
+ configurable: true,
3172
+ writable: true,
3173
+ value: 0
3174
+ });
3175
+ Object.defineProperty(this, "_compressedUSize", {
3176
+ enumerable: true,
3177
+ configurable: true,
3178
+ writable: true,
3179
+ value: 0
3180
+ });
3181
+ Object.defineProperty(this, "_compressedVSize", {
3182
+ enumerable: true,
3183
+ configurable: true,
3184
+ writable: true,
3185
+ value: 0
3186
+ });
3187
+ }
3188
+ /**
3189
+ * Generates a keypair [publicKey, privateKey].
3190
+ *
3191
+ * If an error occurred, throws {@link MlKemError}.
3192
+ *
3193
+ * @returns A kaypair [publicKey, privateKey].
3194
+ * @throws {@link MlKemError}
3195
+ *
3196
+ * @example Generates a {@link MlKem768} keypair.
3197
+ *
3198
+ * ```ts
3199
+ * // Using jsr:
3200
+ * import { MlKem768 } from "@dajiaji/mlkem";
3201
+ * // Using npm:
3202
+ * // import { MlKem768 } from "mlkem"; // or "crystals-kyber-js"
3203
+ *
3204
+ * const kyber = new MlKem768();
3205
+ * const [pk, sk] = await kyber.generateKeyPair();
3206
+ * ```
3207
+ */
3208
+ async generateKeyPair() {
3209
+ await this._setup();
3210
+ try {
3211
+ const rnd = new Uint8Array(64);
3212
+ this._api.getRandomValues(rnd);
3213
+ return this._deriveKeyPair(rnd);
3214
+ } catch (e) {
3215
+ throw new MlKemError(e);
3216
+ }
3217
+ }
3218
+ /**
3219
+ * Derives a keypair [publicKey, privateKey] deterministically from a 64-octet seed.
3220
+ *
3221
+ * If an error occurred, throws {@link MlKemError}.
3222
+ *
3223
+ * @param seed A 64-octet seed for the deterministic key generation.
3224
+ * @returns A kaypair [publicKey, privateKey].
3225
+ * @throws {@link MlKemError}
3226
+ *
3227
+ * @example Derives a {@link MlKem768} keypair deterministically.
3228
+ *
3229
+ * ```ts
3230
+ * // Using jsr:
3231
+ * import { MlKem768 } from "@dajiaji/mlkem";
3232
+ * // Using npm:
3233
+ * // import { MlKem768 } from "mlkem"; // or "crystals-kyber-js"
3234
+ *
3235
+ * const kyber = new MlKem768();
3236
+ * const seed = new Uint8Array(64);
3237
+ * globalThis.crypto.getRandomValues(seed);
3238
+ * const [pk, sk] = await kyber.deriveKeyPair(seed);
3239
+ * ```
3240
+ */
3241
+ async deriveKeyPair(seed) {
3242
+ await this._setup();
3243
+ try {
3244
+ if (seed.byteLength !== 64) {
3245
+ throw new Error("seed must be 64 bytes in length");
3246
+ }
3247
+ return this._deriveKeyPair(seed);
3248
+ } catch (e) {
3249
+ throw new MlKemError(e);
3250
+ }
3251
+ }
3252
+ /**
3253
+ * Generates a shared secret from the encapsulated ciphertext and the private key.
3254
+ *
3255
+ * If an error occurred, throws {@link MlKemError}.
3256
+ *
3257
+ * @param pk A public key.
3258
+ * @param seed An optional 32-octet seed for the deterministic shared secret generation.
3259
+ * @returns A ciphertext (encapsulated public key) and a shared secret.
3260
+ * @throws {@link MlKemError}
3261
+ *
3262
+ * @example The {@link MlKem768} encapsulation.
3263
+ *
3264
+ * ```ts
3265
+ * // Using jsr:
3266
+ * import { MlKem768 } from "@dajiaji/mlkem";
3267
+ * // Using npm:
3268
+ * // import { MlKem768 } from "mlkem"; // or "crystals-kyber-js"
3269
+ *
3270
+ * const kyber = new MlKem768();
3271
+ * const [pk, sk] = await kyber.generateKeyPair();
3272
+ * const [ct, ss] = await kyber.encap(pk);
3273
+ * ```
3274
+ */
3275
+ async encap(pk, seed) {
3276
+ await this._setup();
3277
+ try {
3278
+ if (pk.length !== 384 * this._k + 32) {
3279
+ throw new Error("invalid encapsulation key");
3280
+ }
3281
+ const m = this._getSeed(seed);
3282
+ const [k, r] = g(m, h(pk));
3283
+ const ct = this._encap(pk, m, r);
3284
+ return [ct, k];
3285
+ } catch (e) {
3286
+ throw new MlKemError(e);
3287
+ }
3288
+ }
3289
+ /**
3290
+ * Generates a ciphertext for the public key and a shared secret.
3291
+ *
3292
+ * If an error occurred, throws {@link MlKemError}.
3293
+ *
3294
+ * @param ct A ciphertext generated by {@link encap}.
3295
+ * @param sk A private key.
3296
+ * @returns A shared secret.
3297
+ * @throws {@link MlKemError}
3298
+ *
3299
+ * @example The {@link MlKem768} decapsulation.
3300
+ *
3301
+ * ```ts
3302
+ * // Using jsr:
3303
+ * import { MlKem768 } from "@dajiaji/mlkem";
3304
+ * // Using npm:
3305
+ * // import { MlKem768 } from "mlkem"; // or "crystals-kyber-js"
3306
+ *
3307
+ * const kyber = new MlKem768();
3308
+ * const [pk, sk] = await kyber.generateKeyPair();
3309
+ * const [ct, ssS] = await kyber.encap(pk);
3310
+ * const ssR = await kyber.decap(ct, sk);
3311
+ * // ssS === ssR
3312
+ * ```
3313
+ */
3314
+ async decap(ct, sk) {
3315
+ await this._setup();
3316
+ try {
3317
+ if (ct.byteLength !== this._compressedUSize + this._compressedVSize) {
3318
+ throw new Error("Invalid ct size");
3319
+ }
3320
+ if (sk.length !== 768 * this._k + 96) {
3321
+ throw new Error("Invalid decapsulation key");
3322
+ }
3323
+ const sk2 = sk.subarray(0, this._skSize);
3324
+ const pk = sk.subarray(this._skSize, this._skSize + this._pkSize);
3325
+ const hpk = sk.subarray(this._skSize + this._pkSize, this._skSize + this._pkSize + 32);
3326
+ const z = sk.subarray(this._skSize + this._pkSize + 32, this._skSize + this._pkSize + 64);
3327
+ const m2 = this._decap(ct, sk2);
3328
+ const [k2, r2] = g(m2, hpk);
3329
+ const kBar = kdf(z, ct);
3330
+ const ct2 = this._encap(pk, m2, r2);
3331
+ return constantTimeCompare(ct, ct2) === 1 ? k2 : kBar;
3332
+ } catch (e) {
3333
+ throw new MlKemError(e);
3334
+ }
3335
+ }
3336
+ /**
3337
+ * Sets up the MlKemBase instance by loading the necessary crypto library.
3338
+ * If the crypto library is already loaded, this method does nothing.
3339
+ * @returns {Promise<void>} A promise that resolves when the setup is complete.
3340
+ */
3341
+ async _setup() {
3342
+ if (this._api !== void 0) {
3343
+ return;
3344
+ }
3345
+ this._api = await loadCrypto();
3346
+ }
3347
+ /**
3348
+ * Returns a Uint8Array seed for cryptographic operations.
3349
+ * If no seed is provided, a random seed of length 32 bytes is generated.
3350
+ * If a seed is provided, it must be exactly 32 bytes in length.
3351
+ *
3352
+ * @param seed - Optional seed for cryptographic operations.
3353
+ * @returns A Uint8Array seed.
3354
+ * @throws Error if the provided seed is not 32 bytes in length.
3355
+ */
3356
+ _getSeed(seed) {
3357
+ if (seed == void 0) {
3358
+ const s = new Uint8Array(32);
3359
+ this._api.getRandomValues(s);
3360
+ return s;
3361
+ }
3362
+ if (seed.byteLength !== 32) {
3363
+ throw new Error("seed must be 32 bytes in length");
3364
+ }
3365
+ return seed;
3366
+ }
3367
+ /**
3368
+ * Derives a key pair from a given seed.
3369
+ *
3370
+ * @param seed - The seed used for key derivation.
3371
+ * @returns An array containing the public key and secret key.
3372
+ */
3373
+ _deriveKeyPair(seed) {
3374
+ const cpaSeed = seed.subarray(0, 32);
3375
+ const z = seed.subarray(32, 64);
3376
+ const [pk, skBody] = this._deriveCpaKeyPair(cpaSeed);
3377
+ const pkh = h(pk);
3378
+ const sk = new Uint8Array(this._skSize + this._pkSize + 64);
3379
+ sk.set(skBody, 0);
3380
+ sk.set(pk, this._skSize);
3381
+ sk.set(pkh, this._skSize + this._pkSize);
3382
+ sk.set(z, this._skSize + this._pkSize + 32);
3383
+ return [pk, sk];
3384
+ }
3385
+ // indcpaKeyGen generates public and private keys for the CPA-secure
3386
+ // public-key encryption scheme underlying ML-KEM.
3387
+ /**
3388
+ * Derives a CPA key pair using the provided CPA seed.
3389
+ *
3390
+ * @param cpaSeed - The CPA seed used for key derivation.
3391
+ * @returns An array containing the public key and private key.
3392
+ */
3393
+ _deriveCpaKeyPair(cpaSeed) {
3394
+ const [publicSeed, noiseSeed] = g(cpaSeed, new Uint8Array([this._k]));
3395
+ const a = this._sampleMatrix(publicSeed, false);
3396
+ const s = this._sampleNoise1(noiseSeed, 0, this._k);
3397
+ const e = this._sampleNoise1(noiseSeed, this._k, this._k);
3398
+ for (let i = 0; i < this._k; i++) {
3399
+ s[i] = ntt(s[i]);
3400
+ s[i] = reduce(s[i]);
3401
+ e[i] = ntt(e[i]);
3402
+ }
3403
+ const pk = new Array(this._k);
3404
+ for (let i = 0; i < this._k; i++) {
3405
+ pk[i] = polyToMont(multiply(a[i], s));
3406
+ pk[i] = add(pk[i], e[i]);
3407
+ pk[i] = reduce(pk[i]);
3408
+ }
3409
+ const pubKey = new Uint8Array(this._pkSize);
3410
+ for (let i = 0; i < this._k; i++) {
3411
+ pubKey.set(polyToBytes(pk[i]), i * 384);
3412
+ }
3413
+ pubKey.set(publicSeed, this._skSize);
3414
+ const privKey = new Uint8Array(this._skSize);
3415
+ for (let i = 0; i < this._k; i++) {
3416
+ privKey.set(polyToBytes(s[i]), i * 384);
3417
+ }
3418
+ return [pubKey, privKey];
3419
+ }
3420
+ // _encap is the encapsulation function of the CPA-secure
3421
+ // public-key encryption scheme underlying ML-KEM.
3422
+ /**
3423
+ * Encapsulates a message using the ML-KEM encryption scheme.
3424
+ *
3425
+ * @param pk - The public key.
3426
+ * @param msg - The message to be encapsulated.
3427
+ * @param seed - The seed used for generating random values.
3428
+ * @returns The encapsulated message as a Uint8Array.
3429
+ */
3430
+ _encap(pk, msg, seed) {
3431
+ const tHat = new Array(this._k);
3432
+ const pkCheck = new Uint8Array(384 * this._k);
3433
+ for (let i = 0; i < this._k; i++) {
3434
+ tHat[i] = polyFromBytes(pk.subarray(i * 384, (i + 1) * 384));
3435
+ pkCheck.set(polyToBytes(tHat[i]), i * 384);
3436
+ }
3437
+ if (!equalUint8Array(pk.subarray(0, pkCheck.length), pkCheck)) {
3438
+ throw new Error("invalid encapsulation key");
3439
+ }
3440
+ const rho = pk.subarray(this._skSize);
3441
+ const a = this._sampleMatrix(rho, true);
3442
+ const r = this._sampleNoise1(seed, 0, this._k);
3443
+ const e1 = this._sampleNoise2(seed, this._k, this._k);
3444
+ const e2 = this._sampleNoise2(seed, this._k * 2, 1)[0];
3445
+ for (let i = 0; i < this._k; i++) {
3446
+ r[i] = ntt(r[i]);
3447
+ r[i] = reduce(r[i]);
3448
+ }
3449
+ const u = new Array(this._k);
3450
+ for (let i = 0; i < this._k; i++) {
3451
+ u[i] = multiply(a[i], r);
3452
+ u[i] = nttInverse(u[i]);
3453
+ u[i] = add(u[i], e1[i]);
3454
+ u[i] = reduce(u[i]);
3455
+ }
3456
+ const m = polyFromMsg(msg);
3457
+ let v = multiply(tHat, r);
3458
+ v = nttInverse(v);
3459
+ v = add(v, e2);
3460
+ v = add(v, m);
3461
+ v = reduce(v);
3462
+ const ret = new Uint8Array(this._compressedUSize + this._compressedVSize);
3463
+ this._compressU(ret.subarray(0, this._compressedUSize), u);
3464
+ this._compressV(ret.subarray(this._compressedUSize), v);
3465
+ return ret;
3466
+ }
3467
+ // indcpaDecrypt is the decryption function of the CPA-secure
3468
+ // public-key encryption scheme underlying ML-KEM.
3469
+ /**
3470
+ * Decapsulates the ciphertext using the provided secret key.
3471
+ *
3472
+ * @param ct - The ciphertext to be decapsulated.
3473
+ * @param sk - The secret key used for decapsulation.
3474
+ * @returns The decapsulated message as a Uint8Array.
3475
+ */
3476
+ _decap(ct, sk) {
3477
+ const u = this._decompressU(ct.subarray(0, this._compressedUSize));
3478
+ const v = this._decompressV(ct.subarray(this._compressedUSize));
3479
+ const privateKeyPolyvec = this._polyvecFromBytes(sk);
3480
+ for (let i = 0; i < this._k; i++) {
3481
+ u[i] = ntt(u[i]);
3482
+ }
3483
+ let mp = multiply(privateKeyPolyvec, u);
3484
+ mp = nttInverse(mp);
3485
+ mp = subtract(v, mp);
3486
+ mp = reduce(mp);
3487
+ return polyToMsg(mp);
3488
+ }
3489
+ // generateMatrixA deterministically generates a matrix `A` (or the transpose of `A`)
3490
+ // from a seed. Entries of the matrix are polynomials that look uniformly random.
3491
+ // Performs rejection sampling on the output of an extendable-output function (XOF).
3492
+ /**
3493
+ * Generates a sample matrix based on the provided seed and transposition flag.
3494
+ *
3495
+ * @param seed - The seed used for generating the matrix.
3496
+ * @param transposed - A flag indicating whether the matrix should be transposed or not.
3497
+ * @returns The generated sample matrix.
3498
+ */
3499
+ _sampleMatrix(seed, transposed) {
3500
+ const a = new Array(this._k);
3501
+ const transpose = new Uint8Array(2);
3502
+ for (let ctr = 0, i = 0; i < this._k; i++) {
3503
+ a[i] = new Array(this._k);
3504
+ for (let j = 0; j < this._k; j++) {
3505
+ if (transposed) {
3506
+ transpose[0] = i;
3507
+ transpose[1] = j;
3508
+ } else {
3509
+ transpose[0] = j;
3510
+ transpose[1] = i;
3511
+ }
3512
+ const output = xof(seed, transpose);
3513
+ const result = indcpaRejUniform(output.subarray(0, 504), 504, N);
3514
+ a[i][j] = result[0];
3515
+ ctr = result[1];
3516
+ while (ctr < N) {
3517
+ const outputn = output.subarray(504, 672);
3518
+ const result1 = indcpaRejUniform(outputn, 168, N - ctr);
3519
+ const missing = result1[0];
3520
+ const ctrn = result1[1];
3521
+ for (let k = ctr; k < N; k++) {
3522
+ a[i][j][k] = missing[k - ctr];
3523
+ }
3524
+ ctr = ctr + ctrn;
3525
+ }
3526
+ }
3527
+ }
3528
+ return a;
3529
+ }
3530
+ /**
3531
+ * Generates a 2D array of noise samples.
3532
+ *
3533
+ * @param sigma - The noise parameter.
3534
+ * @param offset - The offset value.
3535
+ * @param size - The size of the array.
3536
+ * @returns The generated 2D array of noise samples.
3537
+ */
3538
+ _sampleNoise1(sigma, offset, size) {
3539
+ const r = new Array(size);
3540
+ for (let i = 0; i < size; i++) {
3541
+ r[i] = byteopsCbd(prf(this._eta1 * N / 4, sigma, offset), this._eta1);
3542
+ offset++;
3543
+ }
3544
+ return r;
3545
+ }
3546
+ /**
3547
+ * Generates a 2-dimensional array of noise samples.
3548
+ *
3549
+ * @param sigma - The noise parameter.
3550
+ * @param offset - The offset value.
3551
+ * @param size - The size of the array.
3552
+ * @returns The generated 2-dimensional array of noise samples.
3553
+ */
3554
+ _sampleNoise2(sigma, offset, size) {
3555
+ const r = new Array(size);
3556
+ for (let i = 0; i < size; i++) {
3557
+ r[i] = byteopsCbd(prf(this._eta2 * N / 4, sigma, offset), this._eta2);
3558
+ offset++;
3559
+ }
3560
+ return r;
3561
+ }
3562
+ // polyvecFromBytes deserializes a vector of polynomials.
3563
+ /**
3564
+ * Converts a Uint8Array to a 2D array of numbers representing a polynomial vector.
3565
+ * Each element in the resulting array represents a polynomial.
3566
+ * @param a The Uint8Array to convert.
3567
+ * @returns The 2D array of numbers representing the polynomial vector.
3568
+ */
3569
+ _polyvecFromBytes(a) {
3570
+ const r = new Array(this._k);
3571
+ for (let i = 0; i < this._k; i++) {
3572
+ r[i] = polyFromBytes(a.subarray(i * 384, (i + 1) * 384));
3573
+ }
3574
+ return r;
3575
+ }
3576
+ // compressU lossily compresses and serializes a vector of polynomials.
3577
+ /**
3578
+ * Compresses the given array of coefficients into a Uint8Array.
3579
+ *
3580
+ * @param r - The output Uint8Array.
3581
+ * @param u - The array of coefficients.
3582
+ * @returns The compressed Uint8Array.
3583
+ */
3584
+ _compressU(r, u) {
3585
+ const t = new Array(4);
3586
+ for (let rr = 0, i = 0; i < this._k; i++) {
3587
+ for (let j = 0; j < N / 4; j++) {
3588
+ for (let k = 0; k < 4; k++) {
3589
+ t[k] = ((u[i][4 * j + k] << 10) + Q / 2) / Q & 1023;
3590
+ }
3591
+ r[rr++] = byte(t[0] >> 0);
3592
+ r[rr++] = byte(t[0] >> 8 | t[1] << 2);
3593
+ r[rr++] = byte(t[1] >> 6 | t[2] << 4);
3594
+ r[rr++] = byte(t[2] >> 4 | t[3] << 6);
3595
+ r[rr++] = byte(t[3] >> 2);
3596
+ }
3597
+ }
3598
+ return r;
3599
+ }
3600
+ // compressV lossily compresses and subsequently serializes a polynomial.
3601
+ /**
3602
+ * Compresses the given array of numbers into a Uint8Array.
3603
+ *
3604
+ * @param r - The Uint8Array to store the compressed values.
3605
+ * @param v - The array of numbers to compress.
3606
+ * @returns The compressed Uint8Array.
3607
+ */
3608
+ _compressV(r, v) {
3609
+ const t = new Uint8Array(8);
3610
+ for (let rr = 0, i = 0; i < N / 8; i++) {
3611
+ for (let j = 0; j < 8; j++) {
3612
+ t[j] = byte(((v[8 * i + j] << 4) + Q / 2) / Q) & 15;
3613
+ }
3614
+ r[rr++] = t[0] | t[1] << 4;
3615
+ r[rr++] = t[2] | t[3] << 4;
3616
+ r[rr++] = t[4] | t[5] << 4;
3617
+ r[rr++] = t[6] | t[7] << 4;
3618
+ }
3619
+ return r;
3620
+ }
3621
+ // decompressU de-serializes and decompresses a vector of polynomials and
3622
+ // represents the approximate inverse of compress1. Since compression is lossy,
3623
+ // the results of decompression will may not match the original vector of polynomials.
3624
+ /**
3625
+ * Decompresses a Uint8Array into a two-dimensional array of numbers.
3626
+ *
3627
+ * @param a The Uint8Array to decompress.
3628
+ * @returns The decompressed two-dimensional array.
3629
+ */
3630
+ _decompressU(a) {
3631
+ const r = new Array(this._k);
3632
+ for (let i = 0; i < this._k; i++) {
3633
+ r[i] = new Array(384);
3634
+ }
3635
+ const t = new Array(4);
3636
+ for (let aa = 0, i = 0; i < this._k; i++) {
3637
+ for (let j = 0; j < N / 4; j++) {
3638
+ t[0] = uint16(a[aa + 0]) >> 0 | uint16(a[aa + 1]) << 8;
3639
+ t[1] = uint16(a[aa + 1]) >> 2 | uint16(a[aa + 2]) << 6;
3640
+ t[2] = uint16(a[aa + 2]) >> 4 | uint16(a[aa + 3]) << 4;
3641
+ t[3] = uint16(a[aa + 3]) >> 6 | uint16(a[aa + 4]) << 2;
3642
+ aa = aa + 5;
3643
+ for (let k = 0; k < 4; k++) {
3644
+ r[i][4 * j + k] = int16(uint32(t[k] & 1023) * uint32(Q) + 512 >> 10);
3645
+ }
3646
+ }
3647
+ }
3648
+ return r;
3649
+ }
3650
+ // decompressV de-serializes and subsequently decompresses a polynomial,
3651
+ // representing the approximate inverse of compress2.
3652
+ // Note that compression is lossy, and thus decompression will not match the
3653
+ // original input.
3654
+ /**
3655
+ * Decompresses a Uint8Array into an array of numbers.
3656
+ *
3657
+ * @param a - The Uint8Array to decompress.
3658
+ * @returns An array of numbers.
3659
+ */
3660
+ _decompressV(a) {
3661
+ const r = new Array(384);
3662
+ for (let aa = 0, i = 0; i < N / 2; i++, aa++) {
3663
+ r[2 * i + 0] = int16(uint16(a[aa] & 15) * uint16(Q) + 8 >> 4);
3664
+ r[2 * i + 1] = int16(uint16(a[aa] >> 4) * uint16(Q) + 8 >> 4);
3665
+ }
3666
+ return r;
3667
+ }
3668
+ };
3669
+ function g(a, b) {
3670
+ const hash = sha3_512.create().update(a);
3671
+ if (b !== void 0) {
3672
+ hash.update(b);
3673
+ }
3674
+ const res = hash.digest();
3675
+ return [res.subarray(0, 32), res.subarray(32, 64)];
3676
+ }
3677
+ function h(msg) {
3678
+ return sha3_256.create().update(msg).digest();
3679
+ }
3680
+ function kdf(a, b) {
3681
+ const hash = shake256.create({ dkLen: 32 }).update(a);
3682
+ if (b !== void 0) {
3683
+ hash.update(b);
3684
+ }
3685
+ return hash.digest();
3686
+ }
3687
+ function xof(seed, transpose) {
3688
+ return shake128.create({ dkLen: 672 }).update(seed).update(transpose).digest();
3689
+ }
3690
+ function polyToBytes(a) {
3691
+ let t0 = 0;
3692
+ let t1 = 0;
3693
+ const r = new Uint8Array(384);
3694
+ const a2 = subtractQ(a);
3695
+ for (let i = 0; i < N / 2; i++) {
3696
+ t0 = uint16(a2[2 * i]);
3697
+ t1 = uint16(a2[2 * i + 1]);
3698
+ r[3 * i + 0] = byte(t0 >> 0);
3699
+ r[3 * i + 1] = byte(t0 >> 8) | byte(t1 << 4);
3700
+ r[3 * i + 2] = byte(t1 >> 4);
3701
+ }
3702
+ return r;
3703
+ }
3704
+ function polyFromBytes(a) {
3705
+ const r = new Array(384).fill(0);
3706
+ for (let i = 0; i < N / 2; i++) {
3707
+ r[2 * i] = int16((uint16(a[3 * i + 0]) >> 0 | uint16(a[3 * i + 1]) << 8) & 4095);
3708
+ r[2 * i + 1] = int16((uint16(a[3 * i + 1]) >> 4 | uint16(a[3 * i + 2]) << 4) & 4095);
3709
+ }
3710
+ return r;
3711
+ }
3712
+ function polyToMsg(a) {
3713
+ const msg = new Uint8Array(32);
3714
+ let t;
3715
+ const a2 = subtractQ(a);
3716
+ for (let i = 0; i < N / 8; i++) {
3717
+ msg[i] = 0;
3718
+ for (let j = 0; j < 8; j++) {
3719
+ t = ((uint16(a2[8 * i + j]) << 1) + uint16(Q / 2)) / uint16(Q) & 1;
3720
+ msg[i] |= byte(t << j);
3721
+ }
3722
+ }
3723
+ return msg;
3724
+ }
3725
+ function polyFromMsg(msg) {
3726
+ const r = new Array(384).fill(0);
3727
+ let mask;
3728
+ for (let i = 0; i < N / 8; i++) {
3729
+ for (let j = 0; j < 8; j++) {
3730
+ mask = -1 * int16(msg[i] >> j & 1);
3731
+ r[8 * i + j] = mask & int16((Q + 1) / 2);
3732
+ }
3733
+ }
3734
+ return r;
3735
+ }
3736
+ function indcpaRejUniform(buf, bufl, len) {
3737
+ const r = new Array(384).fill(0);
3738
+ let ctr = 0;
3739
+ let val0, val1;
3740
+ for (let pos = 0; ctr < len && pos + 3 <= bufl; ) {
3741
+ val0 = (uint16(buf[pos] >> 0) | uint16(buf[pos + 1]) << 8) & 4095;
3742
+ val1 = (uint16(buf[pos + 1] >> 4) | uint16(buf[pos + 2]) << 4) & 4095;
3743
+ pos = pos + 3;
3744
+ if (val0 < Q) {
3745
+ r[ctr] = val0;
3746
+ ctr = ctr + 1;
3747
+ }
3748
+ if (ctr < len && val1 < Q) {
3749
+ r[ctr] = val1;
3750
+ ctr = ctr + 1;
3751
+ }
3752
+ }
3753
+ return [r, ctr];
3754
+ }
3755
+ function byteopsCbd(buf, eta) {
3756
+ let t, d;
3757
+ let a, b;
3758
+ const r = new Array(384).fill(0);
3759
+ for (let i = 0; i < N / 8; i++) {
3760
+ t = byteopsLoad32(buf.subarray(4 * i, buf.length));
3761
+ d = t & 1431655765;
3762
+ d = d + (t >> 1 & 1431655765);
3763
+ for (let j = 0; j < 8; j++) {
3764
+ a = int16(d >> 4 * j + 0 & 3);
3765
+ b = int16(d >> 4 * j + eta & 3);
3766
+ r[8 * i + j] = a - b;
3767
+ }
3768
+ }
3769
+ return r;
3770
+ }
3771
+ function ntt(r) {
3772
+ for (let j = 0, k = 1, l = 128; l >= 2; l >>= 1) {
3773
+ for (let start = 0; start < 256; start = j + l) {
3774
+ const zeta = NTT_ZETAS[k];
3775
+ k = k + 1;
3776
+ for (j = start; j < start + l; j++) {
3777
+ const t = nttFqMul(zeta, r[j + l]);
3778
+ r[j + l] = r[j] - t;
3779
+ r[j] = r[j] + t;
3780
+ }
3781
+ }
3782
+ }
3783
+ return r;
3784
+ }
3785
+ function nttFqMul(a, b) {
3786
+ return byteopsMontgomeryReduce(a * b);
3787
+ }
3788
+ function reduce(r) {
3789
+ for (let i = 0; i < N; i++) {
3790
+ r[i] = barrett(r[i]);
3791
+ }
3792
+ return r;
3793
+ }
3794
+ function barrett(a) {
3795
+ const v = ((1 << 24) + Q / 2) / Q;
3796
+ let t = v * a >> 24;
3797
+ t = t * Q;
3798
+ return a - t;
3799
+ }
3800
+ function byteopsMontgomeryReduce(a) {
3801
+ const u = int16(int32(a) * Q_INV);
3802
+ let t = u * Q;
3803
+ t = a - t;
3804
+ t >>= 16;
3805
+ return int16(t);
3806
+ }
3807
+ function polyToMont(r) {
3808
+ const f = 1353;
3809
+ for (let i = 0; i < N; i++) {
3810
+ r[i] = byteopsMontgomeryReduce(int32(r[i]) * int32(f));
3811
+ }
3812
+ return r;
3813
+ }
3814
+ function multiply(a, b) {
3815
+ let r = polyBaseMulMontgomery(a[0], b[0]);
3816
+ let t;
3817
+ for (let i = 1; i < a.length; i++) {
3818
+ t = polyBaseMulMontgomery(a[i], b[i]);
3819
+ r = add(r, t);
3820
+ }
3821
+ return reduce(r);
3822
+ }
3823
+ function polyBaseMulMontgomery(a, b) {
3824
+ let rx, ry;
3825
+ for (let i = 0; i < N / 4; i++) {
3826
+ rx = nttBaseMul(a[4 * i + 0], a[4 * i + 1], b[4 * i + 0], b[4 * i + 1], NTT_ZETAS[64 + i]);
3827
+ ry = nttBaseMul(a[4 * i + 2], a[4 * i + 3], b[4 * i + 2], b[4 * i + 3], -NTT_ZETAS[64 + i]);
3828
+ a[4 * i + 0] = rx[0];
3829
+ a[4 * i + 1] = rx[1];
3830
+ a[4 * i + 2] = ry[0];
3831
+ a[4 * i + 3] = ry[1];
3832
+ }
3833
+ return a;
3834
+ }
3835
+ function nttBaseMul(a0, a1, b0, b1, zeta) {
3836
+ const r = new Array(2);
3837
+ r[0] = nttFqMul(a1, b1);
3838
+ r[0] = nttFqMul(r[0], zeta);
3839
+ r[0] += nttFqMul(a0, b0);
3840
+ r[1] = nttFqMul(a0, b1);
3841
+ r[1] += nttFqMul(a1, b0);
3842
+ return r;
3843
+ }
3844
+ function add(a, b) {
3845
+ const c = new Array(384);
3846
+ for (let i = 0; i < N; i++) {
3847
+ c[i] = a[i] + b[i];
3848
+ }
3849
+ return c;
3850
+ }
3851
+ function subtract(a, b) {
3852
+ for (let i = 0; i < N; i++) {
3853
+ a[i] -= b[i];
3854
+ }
3855
+ return a;
3856
+ }
3857
+ function nttInverse(r) {
3858
+ let j = 0;
3859
+ for (let k = 0, l = 2; l <= 128; l <<= 1) {
3860
+ for (let start = 0; start < 256; start = j + l) {
3861
+ const zeta = NTT_ZETAS_INV[k];
3862
+ k = k + 1;
3863
+ for (j = start; j < start + l; j++) {
3864
+ const t = r[j];
3865
+ r[j] = barrett(t + r[j + l]);
3866
+ r[j + l] = t - r[j + l];
3867
+ r[j + l] = nttFqMul(zeta, r[j + l]);
3868
+ }
3869
+ }
3870
+ }
3871
+ for (j = 0; j < 256; j++) {
3872
+ r[j] = nttFqMul(r[j], NTT_ZETAS_INV[127]);
3873
+ }
3874
+ return r;
3875
+ }
3876
+ function subtractQ(r) {
3877
+ for (let i = 0; i < N; i++) {
3878
+ r[i] -= Q;
3879
+ r[i] += r[i] >> 31 & Q;
3880
+ }
3881
+ return r;
3882
+ }
3883
+
3884
+ // node_modules/mlkem/esm/src/mlKem768.js
3885
+ var MlKem768 = class extends MlKemBase {
3886
+ constructor() {
3887
+ super();
3888
+ Object.defineProperty(this, "_k", {
3889
+ enumerable: true,
3890
+ configurable: true,
3891
+ writable: true,
3892
+ value: 3
3893
+ });
3894
+ Object.defineProperty(this, "_du", {
3895
+ enumerable: true,
3896
+ configurable: true,
3897
+ writable: true,
3898
+ value: 10
3899
+ });
3900
+ Object.defineProperty(this, "_dv", {
3901
+ enumerable: true,
3902
+ configurable: true,
3903
+ writable: true,
3904
+ value: 4
3905
+ });
3906
+ Object.defineProperty(this, "_eta1", {
3907
+ enumerable: true,
3908
+ configurable: true,
3909
+ writable: true,
3910
+ value: 2
3911
+ });
3912
+ Object.defineProperty(this, "_eta2", {
3913
+ enumerable: true,
3914
+ configurable: true,
3915
+ writable: true,
3916
+ value: 2
3917
+ });
3918
+ this._skSize = 12 * this._k * N / 8;
3919
+ this._pkSize = this._skSize + 32;
3920
+ this._compressedUSize = this._k * this._du * N / 8;
3921
+ this._compressedVSize = this._dv * N / 8;
3922
+ }
3923
+ };
3924
+
3925
+ // src/index.ts
2329
3926
  async function sha256(data) {
2330
3927
  if (typeof globalThis.crypto?.subtle !== "undefined") {
2331
3928
  const encoder = new TextEncoder();
@@ -2394,6 +3991,39 @@ function unsealEnvelope(plaintext) {
2394
3991
  return null;
2395
3992
  }
2396
3993
  }
3994
+ var PROTO_MARKER = 86;
3995
+ var FLAG_PADDED = 1;
3996
+ var FLAG_SEALED = 2;
3997
+ var FLAG_RATCHET = 4;
3998
+ var FLAG_PQ = 8;
3999
+ function makeProtoHeader(flags, ratchetStep2) {
4000
+ return new Uint8Array([PROTO_MARKER, flags, ratchetStep2 >> 8 & 255, ratchetStep2 & 255]);
4001
+ }
4002
+ function parseProtoHeader(data) {
4003
+ if (data.length < 4 || data[0] !== PROTO_MARKER) return null;
4004
+ return {
4005
+ flags: data[1],
4006
+ ratchetStep: data[2] << 8 | data[3],
4007
+ content: data.slice(4)
4008
+ };
4009
+ }
4010
+ var MAX_SKIP = 200;
4011
+ var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
4012
+ function toBase58(bytes) {
4013
+ if (bytes.length === 0) return "1";
4014
+ let result = "";
4015
+ let num = BigInt("0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""));
4016
+ while (num > 0n) {
4017
+ const remainder = num % 58n;
4018
+ num = num / 58n;
4019
+ result = BASE58_ALPHABET[Number(remainder)] + result;
4020
+ }
4021
+ for (const byte2 of bytes) {
4022
+ if (byte2 === 0) result = "1" + result;
4023
+ else break;
4024
+ }
4025
+ return result || "1";
4026
+ }
2397
4027
  var VoidlyAgent = class _VoidlyAgent {
2398
4028
  constructor(identity, config) {
2399
4029
  this._pinnedDids = /* @__PURE__ */ new Set();
@@ -2401,6 +4031,9 @@ var VoidlyAgent = class _VoidlyAgent {
2401
4031
  this._conversations = /* @__PURE__ */ new Map();
2402
4032
  this._offlineQueue = [];
2403
4033
  this._ratchetStates = /* @__PURE__ */ new Map();
4034
+ this._identityCache = /* @__PURE__ */ new Map();
4035
+ this._seenMessageIds = /* @__PURE__ */ new Set();
4036
+ this._decryptFailCount = 0;
2404
4037
  this.did = identity.did;
2405
4038
  this.apiKey = identity.apiKey;
2406
4039
  this.signingKeyPair = identity.signingKeyPair;
@@ -2411,6 +4044,11 @@ var VoidlyAgent = class _VoidlyAgent {
2411
4044
  this.fallbackRelays = config?.fallbackRelays || [];
2412
4045
  this.paddingEnabled = config?.padding !== false;
2413
4046
  this.sealedSender = config?.sealedSender || false;
4047
+ this.requireSignatures = config?.requireSignatures || false;
4048
+ this.timeout = config?.timeout ?? 3e4;
4049
+ this.postQuantum = config?.postQuantum !== false;
4050
+ this.mlkemPublicKey = identity.mlkemPublicKey || null;
4051
+ this.mlkemSecretKey = identity.mlkemSecretKey || null;
2414
4052
  }
2415
4053
  // ─── Factory Methods ────────────────────────────────────────────────────────
2416
4054
  /**
@@ -2421,15 +4059,26 @@ var VoidlyAgent = class _VoidlyAgent {
2421
4059
  const baseUrl = config?.baseUrl || "https://api.voidly.ai";
2422
4060
  const signingKeyPair = import_tweetnacl.default.sign.keyPair();
2423
4061
  const encryptionKeyPair = import_tweetnacl.default.box.keyPair();
4062
+ const usePQ = config?.postQuantum !== false;
4063
+ let mlkemPk;
4064
+ let mlkemSk;
4065
+ if (usePQ) {
4066
+ const kem = new MlKem768();
4067
+ [mlkemPk, mlkemSk] = await kem.generateKeyPair();
4068
+ }
4069
+ const regBody = {
4070
+ name: options.name,
4071
+ capabilities: options.capabilities,
4072
+ signing_public_key: (0, import_tweetnacl_util.encodeBase64)(signingKeyPair.publicKey),
4073
+ encryption_public_key: (0, import_tweetnacl_util.encodeBase64)(encryptionKeyPair.publicKey)
4074
+ };
4075
+ if (mlkemPk) {
4076
+ regBody.mlkem_public_key = (0, import_tweetnacl_util.encodeBase64)(mlkemPk);
4077
+ }
2424
4078
  const res = await fetch(`${baseUrl}/v1/agent/register`, {
2425
4079
  method: "POST",
2426
4080
  headers: { "Content-Type": "application/json" },
2427
- body: JSON.stringify({
2428
- name: options.name,
2429
- capabilities: options.capabilities,
2430
- signing_public_key: (0, import_tweetnacl_util.encodeBase64)(signingKeyPair.publicKey),
2431
- encryption_public_key: (0, import_tweetnacl_util.encodeBase64)(encryptionKeyPair.publicKey)
2432
- })
4081
+ body: JSON.stringify(regBody)
2433
4082
  });
2434
4083
  if (!res.ok) {
2435
4084
  const err = await res.json().catch(() => ({}));
@@ -2441,7 +4090,9 @@ var VoidlyAgent = class _VoidlyAgent {
2441
4090
  did: data.did,
2442
4091
  apiKey: data.api_key,
2443
4092
  signingKeyPair,
2444
- encryptionKeyPair
4093
+ encryptionKeyPair,
4094
+ mlkemPublicKey: mlkemPk,
4095
+ mlkemSecretKey: mlkemSk
2445
4096
  }, config);
2446
4097
  }
2447
4098
  /**
@@ -2449,32 +4100,117 @@ var VoidlyAgent = class _VoidlyAgent {
2449
4100
  * Use this to resume an agent across sessions.
2450
4101
  */
2451
4102
  static fromCredentials(creds, config) {
2452
- const signingSecret = (0, import_tweetnacl_util.decodeBase64)(creds.signingSecretKey);
2453
- const encryptionSecret = (0, import_tweetnacl_util.decodeBase64)(creds.encryptionSecretKey);
2454
- return new _VoidlyAgent({
4103
+ if (!creds.did || !creds.did.startsWith("did:")) {
4104
+ throw new Error('Invalid credentials: did must start with "did:"');
4105
+ }
4106
+ if (!creds.apiKey || creds.apiKey.length < 8) {
4107
+ throw new Error("Invalid credentials: apiKey is missing or too short");
4108
+ }
4109
+ if (!creds.signingSecretKey || !creds.encryptionSecretKey) {
4110
+ throw new Error("Invalid credentials: secret keys are required");
4111
+ }
4112
+ let signingSecret;
4113
+ let encryptionSecret;
4114
+ try {
4115
+ signingSecret = (0, import_tweetnacl_util.decodeBase64)(creds.signingSecretKey);
4116
+ encryptionSecret = (0, import_tweetnacl_util.decodeBase64)(creds.encryptionSecretKey);
4117
+ } catch {
4118
+ throw new Error("Invalid credentials: secret keys must be valid base64");
4119
+ }
4120
+ if (signingSecret.length !== 64) {
4121
+ throw new Error(`Invalid credentials: signing key must be 64 bytes, got ${signingSecret.length}`);
4122
+ }
4123
+ if (encryptionSecret.length !== 32) {
4124
+ throw new Error(`Invalid credentials: encryption key must be 32 bytes, got ${encryptionSecret.length}`);
4125
+ }
4126
+ let mlkemPk;
4127
+ let mlkemSk;
4128
+ if (creds.mlkemPublicKey && creds.mlkemSecretKey) {
4129
+ try {
4130
+ mlkemPk = (0, import_tweetnacl_util.decodeBase64)(creds.mlkemPublicKey);
4131
+ mlkemSk = (0, import_tweetnacl_util.decodeBase64)(creds.mlkemSecretKey);
4132
+ if (mlkemPk.length !== 1184 || mlkemSk.length !== 2400) {
4133
+ mlkemPk = void 0;
4134
+ mlkemSk = void 0;
4135
+ }
4136
+ } catch {
4137
+ }
4138
+ }
4139
+ const agent = new _VoidlyAgent({
2455
4140
  did: creds.did,
2456
4141
  apiKey: creds.apiKey,
2457
4142
  signingKeyPair: import_tweetnacl.default.sign.keyPair.fromSecretKey(signingSecret),
2458
4143
  encryptionKeyPair: {
2459
4144
  publicKey: import_tweetnacl.default.box.keyPair.fromSecretKey(encryptionSecret).publicKey,
2460
4145
  secretKey: encryptionSecret
2461
- }
4146
+ },
4147
+ mlkemPublicKey: mlkemPk,
4148
+ mlkemSecretKey: mlkemSk
2462
4149
  }, config);
4150
+ if (creds.ratchetStates) {
4151
+ for (const [pairId, rs] of Object.entries(creds.ratchetStates)) {
4152
+ try {
4153
+ const sendChainKey = (0, import_tweetnacl_util.decodeBase64)(rs.sendChainKey);
4154
+ const recvChainKey = (0, import_tweetnacl_util.decodeBase64)(rs.recvChainKey);
4155
+ if (sendChainKey.length !== 32 || recvChainKey.length !== 32) continue;
4156
+ agent._ratchetStates.set(pairId, {
4157
+ sendChainKey,
4158
+ sendStep: rs.sendStep || 0,
4159
+ recvChainKey,
4160
+ recvStep: rs.recvStep || 0,
4161
+ skippedKeys: /* @__PURE__ */ new Map()
4162
+ });
4163
+ } catch {
4164
+ }
4165
+ }
4166
+ }
4167
+ return agent;
2463
4168
  }
2464
4169
  /**
2465
4170
  * Export credentials for persistence.
2466
4171
  * Store these securely — they contain private keys.
2467
4172
  */
2468
4173
  exportCredentials() {
4174
+ const ratchetStates = {};
4175
+ for (const [pairId, state] of this._ratchetStates) {
4176
+ ratchetStates[pairId] = {
4177
+ sendChainKey: (0, import_tweetnacl_util.encodeBase64)(state.sendChainKey),
4178
+ sendStep: state.sendStep,
4179
+ recvChainKey: (0, import_tweetnacl_util.encodeBase64)(state.recvChainKey),
4180
+ recvStep: state.recvStep
4181
+ };
4182
+ }
2469
4183
  return {
2470
4184
  did: this.did,
2471
4185
  apiKey: this.apiKey,
2472
4186
  signingSecretKey: (0, import_tweetnacl_util.encodeBase64)(this.signingKeyPair.secretKey),
2473
4187
  encryptionSecretKey: (0, import_tweetnacl_util.encodeBase64)(this.encryptionKeyPair.secretKey),
2474
4188
  signingPublicKey: (0, import_tweetnacl_util.encodeBase64)(this.signingKeyPair.publicKey),
2475
- encryptionPublicKey: (0, import_tweetnacl_util.encodeBase64)(this.encryptionKeyPair.publicKey)
4189
+ encryptionPublicKey: (0, import_tweetnacl_util.encodeBase64)(this.encryptionKeyPair.publicKey),
4190
+ ...Object.keys(ratchetStates).length > 0 ? { ratchetStates } : {},
4191
+ ...this.mlkemPublicKey ? { mlkemPublicKey: (0, import_tweetnacl_util.encodeBase64)(this.mlkemPublicKey) } : {},
4192
+ ...this.mlkemSecretKey ? { mlkemSecretKey: (0, import_tweetnacl_util.encodeBase64)(this.mlkemSecretKey) } : {}
2476
4193
  };
2477
4194
  }
4195
+ /**
4196
+ * Get the number of messages that failed to decrypt.
4197
+ * Useful for detecting key mismatches, attacks, or corruption.
4198
+ */
4199
+ get decryptFailCount() {
4200
+ return this._decryptFailCount;
4201
+ }
4202
+ /**
4203
+ * Generate a did:key identifier from this agent's Ed25519 signing key.
4204
+ * did:key is a W3C standard — interoperable across systems.
4205
+ * Format: did:key:z6Mk{base58-multicodec-ed25519-pubkey}
4206
+ */
4207
+ get didKey() {
4208
+ const multicodec = new Uint8Array(2 + this.signingKeyPair.publicKey.length);
4209
+ multicodec[0] = 237;
4210
+ multicodec[1] = 1;
4211
+ multicodec.set(this.signingKeyPair.publicKey, 2);
4212
+ return `did:key:z${toBase58(multicodec)}`;
4213
+ }
2478
4214
  // ─── Messaging ──────────────────────────────────────────────────────────────
2479
4215
  /**
2480
4216
  * Send an E2E encrypted message with hardened security.
@@ -2505,39 +4241,73 @@ var VoidlyAgent = class _VoidlyAgent {
2505
4241
  if (useSealed) {
2506
4242
  plaintext = sealEnvelope(this.did, message);
2507
4243
  }
2508
- let messageBytes;
4244
+ let contentBytes;
2509
4245
  if (usePadding) {
2510
- messageBytes = padMessage((0, import_tweetnacl_util.decodeUTF8)(plaintext));
4246
+ contentBytes = padMessage((0, import_tweetnacl_util.decodeUTF8)(plaintext));
2511
4247
  } else {
2512
- messageBytes = (0, import_tweetnacl_util.decodeUTF8)(plaintext);
4248
+ contentBytes = (0, import_tweetnacl_util.decodeUTF8)(plaintext);
2513
4249
  }
2514
4250
  const pairId = `${this.did}:${recipientDid}`;
2515
- const ratchetState = this._ratchetStates.get(pairId);
2516
- let ratchetStep_n = 0;
2517
- if (ratchetState) {
2518
- const { nextChainKey, messageKey } = await ratchetStep(ratchetState.chainKey);
2519
- ratchetState.chainKey = nextChainKey;
2520
- ratchetState.step++;
2521
- ratchetStep_n = ratchetState.step;
2522
- } else {
2523
- const sharedSecret = import_tweetnacl.default.box.before(recipientPubKey, this.encryptionKeyPair.secretKey);
2524
- this._ratchetStates.set(pairId, {
2525
- chainKey: sharedSecret,
2526
- step: 0
2527
- });
4251
+ let state = this._ratchetStates.get(pairId);
4252
+ let pqCiphertext = null;
4253
+ if (!state) {
4254
+ const x25519Shared = import_tweetnacl.default.box.before(recipientPubKey, this.encryptionKeyPair.secretKey);
4255
+ let chainKey;
4256
+ if (this.postQuantum && profile.mlkem_public_key) {
4257
+ try {
4258
+ const recipientPqPk = (0, import_tweetnacl_util.decodeBase64)(profile.mlkem_public_key);
4259
+ const kem = new MlKem768();
4260
+ const [ct, pqShared] = await kem.encap(recipientPqPk);
4261
+ pqCiphertext = ct;
4262
+ const combined = new Uint8Array(x25519Shared.length + pqShared.length);
4263
+ combined.set(x25519Shared, 0);
4264
+ combined.set(pqShared, x25519Shared.length);
4265
+ chainKey = new Uint8Array(await crypto.subtle.digest("SHA-256", combined));
4266
+ } catch {
4267
+ chainKey = x25519Shared;
4268
+ }
4269
+ } else {
4270
+ chainKey = x25519Shared;
4271
+ }
4272
+ state = {
4273
+ sendChainKey: chainKey,
4274
+ sendStep: 0,
4275
+ recvChainKey: chainKey,
4276
+ // Will be synced on first receive
4277
+ recvStep: 0,
4278
+ skippedKeys: /* @__PURE__ */ new Map()
4279
+ };
4280
+ this._ratchetStates.set(pairId, state);
2528
4281
  }
2529
- const nonce = import_tweetnacl.default.randomBytes(import_tweetnacl.default.box.nonceLength);
2530
- const ciphertext = import_tweetnacl.default.box(messageBytes, nonce, recipientPubKey, this.encryptionKeyPair.secretKey);
4282
+ const { nextChainKey, messageKey } = await ratchetStep(state.sendChainKey);
4283
+ state.sendChainKey = nextChainKey;
4284
+ state.sendStep++;
4285
+ const currentStep = state.sendStep;
4286
+ let flags = FLAG_RATCHET;
4287
+ if (usePadding) flags |= FLAG_PADDED;
4288
+ if (useSealed) flags |= FLAG_SEALED;
4289
+ if (pqCiphertext) flags |= FLAG_PQ;
4290
+ const header = makeProtoHeader(flags, currentStep);
4291
+ const messageBytes = new Uint8Array(header.length + contentBytes.length);
4292
+ messageBytes.set(header, 0);
4293
+ messageBytes.set(contentBytes, header.length);
4294
+ const nonce = import_tweetnacl.default.randomBytes(import_tweetnacl.default.secretbox.nonceLength);
4295
+ const ciphertext = import_tweetnacl.default.secretbox(messageBytes, nonce, messageKey);
2531
4296
  if (!ciphertext) {
2532
4297
  throw new Error("Encryption failed");
2533
4298
  }
2534
- const envelopeData = JSON.stringify({
4299
+ const envelopeObj = {
2535
4300
  from: this.did,
2536
4301
  to: recipientDid,
2537
4302
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2538
4303
  nonce: (0, import_tweetnacl_util.encodeBase64)(nonce),
2539
- ciphertext_hash: await sha256((0, import_tweetnacl_util.encodeBase64)(ciphertext))
2540
- });
4304
+ ciphertext_hash: await sha256((0, import_tweetnacl_util.encodeBase64)(ciphertext)),
4305
+ ratchet_step: currentStep
4306
+ };
4307
+ if (pqCiphertext) {
4308
+ envelopeObj.pq_ciphertext = (0, import_tweetnacl_util.encodeBase64)(pqCiphertext);
4309
+ }
4310
+ const envelopeData = JSON.stringify(envelopeObj);
2541
4311
  const signature = import_tweetnacl.default.sign.detached((0, import_tweetnacl_util.decodeUTF8)(envelopeData), this.signingKeyPair.secretKey);
2542
4312
  const payload = {
2543
4313
  to: recipientDid,
@@ -2601,7 +4371,7 @@ var VoidlyAgent = class _VoidlyAgent {
2601
4371
  if (options.contentType) params.set("content_type", options.contentType);
2602
4372
  if (options.messageType) params.set("message_type", options.messageType);
2603
4373
  if (options.unreadOnly) params.set("unread", "true");
2604
- const res = await fetch(`${this.baseUrl}/v1/agent/receive/raw?${params}`, {
4374
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/receive/raw?${params}`, {
2605
4375
  headers: { "X-Agent-Key": this.apiKey }
2606
4376
  });
2607
4377
  if (!res.ok) {
@@ -2612,13 +4382,105 @@ var VoidlyAgent = class _VoidlyAgent {
2612
4382
  const decrypted = [];
2613
4383
  for (const msg of data.messages) {
2614
4384
  try {
4385
+ if (this._seenMessageIds.has(msg.id)) continue;
2615
4386
  const senderEncPub = (0, import_tweetnacl_util.decodeBase64)(msg.sender_encryption_key);
2616
4387
  const ciphertext = (0, import_tweetnacl_util.decodeBase64)(msg.ciphertext);
2617
4388
  const nonce = (0, import_tweetnacl_util.decodeBase64)(msg.nonce);
2618
- const rawPlaintext = import_tweetnacl.default.box.open(ciphertext, nonce, senderEncPub, this.encryptionKeyPair.secretKey);
2619
- if (!rawPlaintext) continue;
4389
+ let rawPlaintext = null;
4390
+ let envelopeRatchetStep = 0;
4391
+ let envelopePqCiphertext = null;
4392
+ if (msg.envelope) {
4393
+ try {
4394
+ const env = JSON.parse(msg.envelope);
4395
+ if (typeof env.ratchet_step === "number") {
4396
+ envelopeRatchetStep = env.ratchet_step;
4397
+ }
4398
+ if (typeof env.pq_ciphertext === "string") {
4399
+ envelopePqCiphertext = env.pq_ciphertext;
4400
+ }
4401
+ } catch {
4402
+ }
4403
+ }
4404
+ if (envelopeRatchetStep > 0) {
4405
+ const pairId = `${msg.from}:${this.did}`;
4406
+ let state = this._ratchetStates.get(pairId);
4407
+ if (!state) {
4408
+ const x25519Shared = import_tweetnacl.default.box.before(senderEncPub, this.encryptionKeyPair.secretKey);
4409
+ let chainKey;
4410
+ if (envelopePqCiphertext && this.mlkemSecretKey) {
4411
+ try {
4412
+ const pqCt = (0, import_tweetnacl_util.decodeBase64)(envelopePqCiphertext);
4413
+ const kem = new MlKem768();
4414
+ const pqShared = await kem.decap(pqCt, this.mlkemSecretKey);
4415
+ const combined = new Uint8Array(x25519Shared.length + pqShared.length);
4416
+ combined.set(x25519Shared, 0);
4417
+ combined.set(pqShared, x25519Shared.length);
4418
+ chainKey = new Uint8Array(await crypto.subtle.digest("SHA-256", combined));
4419
+ } catch {
4420
+ chainKey = x25519Shared;
4421
+ }
4422
+ } else {
4423
+ chainKey = x25519Shared;
4424
+ }
4425
+ state = {
4426
+ sendChainKey: chainKey,
4427
+ // Our sending chain to this peer
4428
+ sendStep: 0,
4429
+ recvChainKey: chainKey,
4430
+ // Their sending chain (our receiving)
4431
+ recvStep: 0,
4432
+ skippedKeys: /* @__PURE__ */ new Map()
4433
+ };
4434
+ this._ratchetStates.set(pairId, state);
4435
+ }
4436
+ const targetStep = envelopeRatchetStep;
4437
+ if (state.skippedKeys.has(targetStep)) {
4438
+ const mk = state.skippedKeys.get(targetStep);
4439
+ rawPlaintext = import_tweetnacl.default.secretbox.open(ciphertext, nonce, mk);
4440
+ state.skippedKeys.delete(targetStep);
4441
+ } else if (targetStep > state.recvStep) {
4442
+ const skip = targetStep - state.recvStep;
4443
+ if (skip > MAX_SKIP) {
4444
+ rawPlaintext = import_tweetnacl.default.box.open(ciphertext, nonce, senderEncPub, this.encryptionKeyPair.secretKey);
4445
+ } else {
4446
+ let ck = state.recvChainKey;
4447
+ for (let i = state.recvStep + 1; i < targetStep; i++) {
4448
+ const { nextChainKey: nextChainKey2, messageKey: skippedMk } = await ratchetStep(ck);
4449
+ state.skippedKeys.set(i, skippedMk);
4450
+ ck = nextChainKey2;
4451
+ if (state.skippedKeys.size > MAX_SKIP) {
4452
+ const oldest = state.skippedKeys.keys().next().value;
4453
+ if (oldest !== void 0) state.skippedKeys.delete(oldest);
4454
+ }
4455
+ }
4456
+ const { nextChainKey, messageKey } = await ratchetStep(ck);
4457
+ state.recvChainKey = nextChainKey;
4458
+ state.recvStep = targetStep;
4459
+ rawPlaintext = import_tweetnacl.default.secretbox.open(ciphertext, nonce, messageKey);
4460
+ }
4461
+ }
4462
+ if (!rawPlaintext) {
4463
+ rawPlaintext = import_tweetnacl.default.box.open(ciphertext, nonce, senderEncPub, this.encryptionKeyPair.secretKey);
4464
+ }
4465
+ } else {
4466
+ rawPlaintext = import_tweetnacl.default.box.open(ciphertext, nonce, senderEncPub, this.encryptionKeyPair.secretKey);
4467
+ }
4468
+ if (!rawPlaintext) {
4469
+ this._decryptFailCount++;
4470
+ continue;
4471
+ }
2620
4472
  let plaintextBytes = rawPlaintext;
2621
- if (rawPlaintext.length >= 256 && (rawPlaintext.length & rawPlaintext.length - 1) === 0) {
4473
+ let wasPadded = false;
4474
+ let wasSealed = false;
4475
+ const proto = parseProtoHeader(rawPlaintext);
4476
+ if (proto) {
4477
+ wasPadded = !!(proto.flags & FLAG_PADDED);
4478
+ wasSealed = !!(proto.flags & FLAG_SEALED);
4479
+ plaintextBytes = proto.content;
4480
+ }
4481
+ if (wasPadded) {
4482
+ plaintextBytes = unpadMessage(plaintextBytes);
4483
+ } else if (!proto && rawPlaintext.length >= 256 && (rawPlaintext.length & rawPlaintext.length - 1) === 0) {
2622
4484
  const unpadded = unpadMessage(rawPlaintext);
2623
4485
  if (unpadded.length < rawPlaintext.length) {
2624
4486
  plaintextBytes = unpadded;
@@ -2626,10 +4488,12 @@ var VoidlyAgent = class _VoidlyAgent {
2626
4488
  }
2627
4489
  let content = (0, import_tweetnacl_util.encodeUTF8)(plaintextBytes);
2628
4490
  let senderDid = msg.from;
2629
- const unsealed = unsealEnvelope(content);
2630
- if (unsealed) {
2631
- content = unsealed.msg;
2632
- senderDid = unsealed.from;
4491
+ if (wasSealed || !proto) {
4492
+ const unsealed = unsealEnvelope(content);
4493
+ if (unsealed) {
4494
+ content = unsealed.msg;
4495
+ senderDid = unsealed.from;
4496
+ }
2633
4497
  }
2634
4498
  let signatureValid = false;
2635
4499
  try {
@@ -2650,6 +4514,15 @@ var VoidlyAgent = class _VoidlyAgent {
2650
4514
  } catch {
2651
4515
  signatureValid = false;
2652
4516
  }
4517
+ if (this.requireSignatures && !signatureValid) {
4518
+ this._decryptFailCount++;
4519
+ continue;
4520
+ }
4521
+ this._seenMessageIds.add(msg.id);
4522
+ if (this._seenMessageIds.size > 1e4) {
4523
+ const first = this._seenMessageIds.values().next().value;
4524
+ if (first !== void 0) this._seenMessageIds.delete(first);
4525
+ }
2653
4526
  decrypted.push({
2654
4527
  id: msg.id,
2655
4528
  from: senderDid,
@@ -2664,6 +4537,7 @@ var VoidlyAgent = class _VoidlyAgent {
2664
4537
  expiresAt: msg.expires_at
2665
4538
  });
2666
4539
  } catch {
4540
+ this._decryptFailCount++;
2667
4541
  }
2668
4542
  }
2669
4543
  return decrypted;
@@ -2673,7 +4547,7 @@ var VoidlyAgent = class _VoidlyAgent {
2673
4547
  * Delete a message by ID (must be sender or recipient).
2674
4548
  */
2675
4549
  async deleteMessage(messageId) {
2676
- const res = await fetch(`${this.baseUrl}/v1/agent/messages/${messageId}`, {
4550
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/messages/${messageId}`, {
2677
4551
  method: "DELETE",
2678
4552
  headers: { "X-Agent-Key": this.apiKey }
2679
4553
  });
@@ -2684,7 +4558,7 @@ var VoidlyAgent = class _VoidlyAgent {
2684
4558
  * Get this agent's own profile.
2685
4559
  */
2686
4560
  async getProfile() {
2687
- const res = await fetch(`${this.baseUrl}/v1/agent/profile`, {
4561
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/profile`, {
2688
4562
  headers: { "X-Agent-Key": this.apiKey }
2689
4563
  });
2690
4564
  if (!res.ok) {
@@ -2696,7 +4570,7 @@ var VoidlyAgent = class _VoidlyAgent {
2696
4570
  * Update this agent's profile (name, capabilities, metadata).
2697
4571
  */
2698
4572
  async updateProfile(updates) {
2699
- const res = await fetch(`${this.baseUrl}/v1/agent/profile`, {
4573
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/profile`, {
2700
4574
  method: "PATCH",
2701
4575
  headers: {
2702
4576
  "Content-Type": "application/json",
@@ -2714,9 +4588,19 @@ var VoidlyAgent = class _VoidlyAgent {
2714
4588
  * Look up an agent's public profile and keys.
2715
4589
  */
2716
4590
  async getIdentity(did) {
2717
- const res = await fetch(`${this.baseUrl}/v1/agent/identity/${did}`);
4591
+ const cached = this._identityCache.get(did);
4592
+ if (cached && Date.now() - cached.cachedAt < 3e5) {
4593
+ return cached.profile;
4594
+ }
4595
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/identity/${did}`);
2718
4596
  if (!res.ok) return null;
2719
- return await res.json();
4597
+ const profile = await res.json();
4598
+ this._identityCache.set(did, { profile, cachedAt: Date.now() });
4599
+ if (this._identityCache.size > 500) {
4600
+ const oldest = this._identityCache.keys().next().value;
4601
+ if (oldest !== void 0) this._identityCache.delete(oldest);
4602
+ }
4603
+ return profile;
2720
4604
  }
2721
4605
  /**
2722
4606
  * Search for agents by name or capability.
@@ -2726,7 +4610,7 @@ var VoidlyAgent = class _VoidlyAgent {
2726
4610
  if (options.query) params.set("query", options.query);
2727
4611
  if (options.capability) params.set("capability", options.capability);
2728
4612
  if (options.limit) params.set("limit", String(options.limit));
2729
- const res = await fetch(`${this.baseUrl}/v1/agent/discover?${params}`);
4613
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/discover?${params}`);
2730
4614
  if (!res.ok) return [];
2731
4615
  const data = await res.json();
2732
4616
  return data.agents;
@@ -2735,7 +4619,7 @@ var VoidlyAgent = class _VoidlyAgent {
2735
4619
  * Get relay network statistics.
2736
4620
  */
2737
4621
  async stats() {
2738
- const res = await fetch(`${this.baseUrl}/v1/agent/stats`);
4622
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/stats`);
2739
4623
  return await res.json();
2740
4624
  }
2741
4625
  // ─── Webhooks ──────────────────────────────────────────────────────────────
@@ -2744,7 +4628,7 @@ var VoidlyAgent = class _VoidlyAgent {
2744
4628
  * Instead of polling receive(), messages are POSTed to your URL with HMAC signatures.
2745
4629
  */
2746
4630
  async registerWebhook(webhookUrl, options = {}) {
2747
- const res = await fetch(`${this.baseUrl}/v1/agent/webhooks`, {
4631
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/webhooks`, {
2748
4632
  method: "POST",
2749
4633
  headers: {
2750
4634
  "Content-Type": "application/json",
@@ -2765,7 +4649,7 @@ var VoidlyAgent = class _VoidlyAgent {
2765
4649
  * List registered webhooks.
2766
4650
  */
2767
4651
  async listWebhooks() {
2768
- const res = await fetch(`${this.baseUrl}/v1/agent/webhooks`, {
4652
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/webhooks`, {
2769
4653
  headers: { "X-Agent-Key": this.apiKey }
2770
4654
  });
2771
4655
  if (!res.ok) return [];
@@ -2776,10 +4660,14 @@ var VoidlyAgent = class _VoidlyAgent {
2776
4660
  * Delete a webhook.
2777
4661
  */
2778
4662
  async deleteWebhook(webhookId) {
2779
- await fetch(`${this.baseUrl}/v1/agent/webhooks/${webhookId}`, {
4663
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/webhooks/${webhookId}`, {
2780
4664
  method: "DELETE",
2781
4665
  headers: { "X-Agent-Key": this.apiKey }
2782
4666
  });
4667
+ if (!res.ok) {
4668
+ const err = await res.json().catch(() => ({}));
4669
+ throw new Error(`Webhook delete failed: ${err.error || res.statusText}`);
4670
+ }
2783
4671
  }
2784
4672
  /**
2785
4673
  * Verify a webhook payload signature (for use in your webhook handler).
@@ -2816,7 +4704,7 @@ var VoidlyAgent = class _VoidlyAgent {
2816
4704
  async rotateKeys() {
2817
4705
  const newSigningKeyPair = import_tweetnacl.default.sign.keyPair();
2818
4706
  const newEncryptionKeyPair = import_tweetnacl.default.box.keyPair();
2819
- const res = await fetch(`${this.baseUrl}/v1/agent/rotate-keys`, {
4707
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/rotate-keys`, {
2820
4708
  method: "POST",
2821
4709
  headers: {
2822
4710
  "Content-Type": "application/json",
@@ -2839,7 +4727,7 @@ var VoidlyAgent = class _VoidlyAgent {
2839
4727
  * Only authenticated agents with did:voidly: identities can join and read.
2840
4728
  */
2841
4729
  async createChannel(options) {
2842
- const res = await fetch(`${this.baseUrl}/v1/agent/channels`, {
4730
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels`, {
2843
4731
  method: "POST",
2844
4732
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
2845
4733
  body: JSON.stringify(options)
@@ -2859,7 +4747,7 @@ var VoidlyAgent = class _VoidlyAgent {
2859
4747
  if (options.query) params.set("q", options.query);
2860
4748
  if (options.mine) params.set("mine", "true");
2861
4749
  if (options.limit) params.set("limit", String(options.limit));
2862
- const res = await fetch(`${this.baseUrl}/v1/agent/channels?${params}`, {
4750
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels?${params}`, {
2863
4751
  headers: options.mine ? { "X-Agent-Key": this.apiKey } : {}
2864
4752
  });
2865
4753
  if (!res.ok) return [];
@@ -2870,7 +4758,7 @@ var VoidlyAgent = class _VoidlyAgent {
2870
4758
  * Join an encrypted channel.
2871
4759
  */
2872
4760
  async joinChannel(channelId) {
2873
- const res = await fetch(`${this.baseUrl}/v1/agent/channels/${channelId}/join`, {
4761
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${channelId}/join`, {
2874
4762
  method: "POST",
2875
4763
  headers: { "X-Agent-Key": this.apiKey }
2876
4764
  });
@@ -2884,7 +4772,7 @@ var VoidlyAgent = class _VoidlyAgent {
2884
4772
  * Leave a channel.
2885
4773
  */
2886
4774
  async leaveChannel(channelId) {
2887
- const res = await fetch(`${this.baseUrl}/v1/agent/channels/${channelId}/leave`, {
4775
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${channelId}/leave`, {
2888
4776
  method: "POST",
2889
4777
  headers: { "X-Agent-Key": this.apiKey }
2890
4778
  });
@@ -2897,7 +4785,7 @@ var VoidlyAgent = class _VoidlyAgent {
2897
4785
  * Post an encrypted message to a channel.
2898
4786
  */
2899
4787
  async postToChannel(channelId, message, replyTo) {
2900
- const res = await fetch(`${this.baseUrl}/v1/agent/channels/${channelId}/messages`, {
4788
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${channelId}/messages`, {
2901
4789
  method: "POST",
2902
4790
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
2903
4791
  body: JSON.stringify({ message, reply_to: replyTo })
@@ -2916,7 +4804,7 @@ var VoidlyAgent = class _VoidlyAgent {
2916
4804
  if (options.since) params.set("since", options.since);
2917
4805
  if (options.before) params.set("before", options.before);
2918
4806
  if (options.limit) params.set("limit", String(options.limit));
2919
- const res = await fetch(`${this.baseUrl}/v1/agent/channels/${channelId}/messages?${params}`, {
4807
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${channelId}/messages?${params}`, {
2920
4808
  headers: { "X-Agent-Key": this.apiKey }
2921
4809
  });
2922
4810
  if (!res.ok) {
@@ -2930,7 +4818,7 @@ var VoidlyAgent = class _VoidlyAgent {
2930
4818
  * This is a soft delete — messages expire per TTL. Re-register for a new identity.
2931
4819
  */
2932
4820
  async deactivate() {
2933
- const res = await fetch(`${this.baseUrl}/v1/agent/deactivate`, {
4821
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/deactivate`, {
2934
4822
  method: "DELETE",
2935
4823
  headers: { "X-Agent-Key": this.apiKey }
2936
4824
  });
@@ -2953,7 +4841,7 @@ var VoidlyAgent = class _VoidlyAgent {
2953
4841
  * ```
2954
4842
  */
2955
4843
  async registerCapability(options) {
2956
- const res = await fetch(`${this.baseUrl}/v1/agent/capabilities`, {
4844
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities`, {
2957
4845
  method: "POST",
2958
4846
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
2959
4847
  body: JSON.stringify({
@@ -2974,7 +4862,7 @@ var VoidlyAgent = class _VoidlyAgent {
2974
4862
  * List this agent's registered capabilities.
2975
4863
  */
2976
4864
  async listCapabilities() {
2977
- const res = await fetch(`${this.baseUrl}/v1/agent/capabilities`, {
4865
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities`, {
2978
4866
  headers: { "X-Agent-Key": this.apiKey }
2979
4867
  });
2980
4868
  if (!res.ok) return [];
@@ -2996,7 +4884,7 @@ var VoidlyAgent = class _VoidlyAgent {
2996
4884
  if (options.query) params.set("q", options.query);
2997
4885
  if (options.name) params.set("name", options.name);
2998
4886
  if (options.limit) params.set("limit", String(options.limit));
2999
- const res = await fetch(`${this.baseUrl}/v1/agent/capabilities/search?${params}`);
4887
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities/search?${params}`);
3000
4888
  if (!res.ok) return [];
3001
4889
  const data = await res.json();
3002
4890
  return data.results;
@@ -3005,7 +4893,7 @@ var VoidlyAgent = class _VoidlyAgent {
3005
4893
  * Remove a capability.
3006
4894
  */
3007
4895
  async deleteCapability(capabilityId) {
3008
- const res = await fetch(`${this.baseUrl}/v1/agent/capabilities/${capabilityId}`, {
4896
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities/${capabilityId}`, {
3009
4897
  method: "DELETE",
3010
4898
  headers: { "X-Agent-Key": this.apiKey }
3011
4899
  });
@@ -3030,14 +4918,14 @@ var VoidlyAgent = class _VoidlyAgent {
3030
4918
  * ```
3031
4919
  */
3032
4920
  async createTask(options) {
3033
- const identityRes = await fetch(`${this.baseUrl}/v1/agent/identity/${options.to}`);
4921
+ const identityRes = await this._timedFetch(`${this.baseUrl}/v1/agent/identity/${options.to}`);
3034
4922
  if (!identityRes.ok) throw new Error("Recipient agent not found");
3035
4923
  const identity = await identityRes.json();
3036
4924
  const recipientPubKey = (0, import_tweetnacl_util.decodeBase64)(identity.encryption_public_key);
3037
4925
  const plaintext = (0, import_tweetnacl_util.decodeUTF8)(JSON.stringify(options.input));
3038
4926
  const nonce = import_tweetnacl.default.randomBytes(import_tweetnacl.default.box.nonceLength);
3039
4927
  const encrypted = import_tweetnacl.default.box(plaintext, nonce, recipientPubKey, this.encryptionKeyPair.secretKey);
3040
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks`, {
4928
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks`, {
3041
4929
  method: "POST",
3042
4930
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3043
4931
  body: JSON.stringify({
@@ -3064,7 +4952,7 @@ var VoidlyAgent = class _VoidlyAgent {
3064
4952
  if (options.status) params.set("status", options.status);
3065
4953
  if (options.capability) params.set("capability", options.capability);
3066
4954
  if (options.limit) params.set("limit", String(options.limit));
3067
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks?${params}`, {
4955
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks?${params}`, {
3068
4956
  headers: { "X-Agent-Key": this.apiKey }
3069
4957
  });
3070
4958
  if (!res.ok) return [];
@@ -3075,7 +4963,7 @@ var VoidlyAgent = class _VoidlyAgent {
3075
4963
  * Get task detail. Includes encrypted input/output (only visible to participants).
3076
4964
  */
3077
4965
  async getTask(taskId) {
3078
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks/${taskId}`, {
4966
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/${taskId}`, {
3079
4967
  headers: { "X-Agent-Key": this.apiKey }
3080
4968
  });
3081
4969
  if (!res.ok) {
@@ -3107,7 +4995,7 @@ var VoidlyAgent = class _VoidlyAgent {
3107
4995
  if (update.output && (update.status === "completed" || update.status === "failed")) {
3108
4996
  const task = await this.getTask(taskId);
3109
4997
  const requesterDid = task.from;
3110
- const identityRes = await fetch(`${this.baseUrl}/v1/agent/identity/${requesterDid}`);
4998
+ const identityRes = await this._timedFetch(`${this.baseUrl}/v1/agent/identity/${requesterDid}`);
3111
4999
  if (identityRes.ok) {
3112
5000
  const identity = await identityRes.json();
3113
5001
  const requesterPubKey = (0, import_tweetnacl_util.decodeBase64)(identity.encryption_public_key);
@@ -3120,7 +5008,7 @@ var VoidlyAgent = class _VoidlyAgent {
3120
5008
  body.output_signature = (0, import_tweetnacl_util.encodeBase64)(signature);
3121
5009
  }
3122
5010
  }
3123
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks/${taskId}`, {
5011
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/${taskId}`, {
3124
5012
  method: "PATCH",
3125
5013
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3126
5014
  body: JSON.stringify(body)
@@ -3187,7 +5075,7 @@ var VoidlyAgent = class _VoidlyAgent {
3187
5075
  const payload = options.claimType + JSON.stringify(options.claimData) + timestamp;
3188
5076
  const payloadBytes = (0, import_tweetnacl_util.decodeUTF8)(payload);
3189
5077
  const signature = import_tweetnacl.default.sign.detached(payloadBytes, this.signingKeyPair.secretKey);
3190
- const res = await fetch(`${this.baseUrl}/v1/agent/attestations`, {
5078
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/attestations`, {
3191
5079
  method: "POST",
3192
5080
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3193
5081
  body: JSON.stringify({
@@ -3224,7 +5112,7 @@ var VoidlyAgent = class _VoidlyAgent {
3224
5112
  const payload = attestationId + vote;
3225
5113
  const payloadBytes = (0, import_tweetnacl_util.decodeUTF8)(payload);
3226
5114
  const signature = import_tweetnacl.default.sign.detached(payloadBytes, this.signingKeyPair.secretKey);
3227
- const res = await fetch(`${this.baseUrl}/v1/agent/attestations/${attestationId}/corroborate`, {
5115
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/attestations/${attestationId}/corroborate`, {
3228
5116
  method: "POST",
3229
5117
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3230
5118
  body: JSON.stringify({ vote, signature: (0, import_tweetnacl_util.encodeBase64)(signature), comment })
@@ -3247,7 +5135,7 @@ var VoidlyAgent = class _VoidlyAgent {
3247
5135
  if (options.minConsensus !== void 0) params.set("min_consensus", String(options.minConsensus));
3248
5136
  if (options.since) params.set("since", options.since);
3249
5137
  if (options.limit) params.set("limit", String(options.limit));
3250
- const res = await fetch(`${this.baseUrl}/v1/agent/attestations?${params}`);
5138
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/attestations?${params}`);
3251
5139
  if (!res.ok) return [];
3252
5140
  const data = await res.json();
3253
5141
  return data.attestations;
@@ -3256,7 +5144,7 @@ var VoidlyAgent = class _VoidlyAgent {
3256
5144
  * Get attestation detail including all corroborations.
3257
5145
  */
3258
5146
  async getAttestation(attestationId) {
3259
- const res = await fetch(`${this.baseUrl}/v1/agent/attestations/${attestationId}`);
5147
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/attestations/${attestationId}`);
3260
5148
  if (!res.ok) {
3261
5149
  const err = await res.json().catch(() => ({}));
3262
5150
  throw new Error(`Get attestation failed: ${err.error || res.statusText}`);
@@ -3271,7 +5159,7 @@ var VoidlyAgent = class _VoidlyAgent {
3271
5159
  if (options.country) params.set("country", options.country);
3272
5160
  if (options.domain) params.set("domain", options.domain);
3273
5161
  if (options.type) params.set("type", options.type);
3274
- const res = await fetch(`${this.baseUrl}/v1/agent/attestations/consensus?${params}`);
5162
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/attestations/consensus?${params}`);
3275
5163
  if (!res.ok) return [];
3276
5164
  const data = await res.json();
3277
5165
  return data.consensus;
@@ -3284,7 +5172,7 @@ var VoidlyAgent = class _VoidlyAgent {
3284
5172
  * Only channel members can invite.
3285
5173
  */
3286
5174
  async inviteToChannel(channelId, inviteeDid, options) {
3287
- const res = await fetch(`${this.baseUrl}/v1/agent/channels/${channelId}/invite`, {
5175
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${channelId}/invite`, {
3288
5176
  method: "POST",
3289
5177
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3290
5178
  body: JSON.stringify({
@@ -3303,7 +5191,7 @@ var VoidlyAgent = class _VoidlyAgent {
3303
5191
  * List pending channel invites for this agent.
3304
5192
  */
3305
5193
  async listInvites(status = "pending") {
3306
- const res = await fetch(`${this.baseUrl}/v1/agent/invites?status=${status}`, {
5194
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/invites?status=${status}`, {
3307
5195
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey }
3308
5196
  });
3309
5197
  if (!res.ok) return [];
@@ -3314,7 +5202,7 @@ var VoidlyAgent = class _VoidlyAgent {
3314
5202
  * Accept or decline a channel invite.
3315
5203
  */
3316
5204
  async respondToInvite(inviteId, action) {
3317
- const res = await fetch(`${this.baseUrl}/v1/agent/invites/${inviteId}/respond`, {
5205
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/invites/${inviteId}/respond`, {
3318
5206
  method: "POST",
3319
5207
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3320
5208
  body: JSON.stringify({ action })
@@ -3332,7 +5220,7 @@ var VoidlyAgent = class _VoidlyAgent {
3332
5220
  * Get an agent's trust score and reputation breakdown.
3333
5221
  */
3334
5222
  async getTrustScore(did) {
3335
- const res = await fetch(`${this.baseUrl}/v1/agent/trust/${did}`);
5223
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/trust/${did}`);
3336
5224
  if (!res.ok) {
3337
5225
  const err = await res.json().catch(() => ({}));
3338
5226
  throw new Error(`Trust score failed: ${err.error || res.statusText}`);
@@ -3346,7 +5234,7 @@ var VoidlyAgent = class _VoidlyAgent {
3346
5234
  const params = new URLSearchParams();
3347
5235
  if (options?.limit) params.set("limit", options.limit.toString());
3348
5236
  if (options?.minLevel) params.set("min_level", options.minLevel);
3349
- const res = await fetch(`${this.baseUrl}/v1/agent/trust/leaderboard?${params}`);
5237
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/trust/leaderboard?${params}`);
3350
5238
  if (!res.ok) return [];
3351
5239
  const data = await res.json();
3352
5240
  return data.leaderboard;
@@ -3358,7 +5246,7 @@ var VoidlyAgent = class _VoidlyAgent {
3358
5246
  * Mark a message as read.
3359
5247
  */
3360
5248
  async markRead(messageId) {
3361
- const res = await fetch(`${this.baseUrl}/v1/agent/messages/${messageId}/read`, {
5249
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/messages/${messageId}/read`, {
3362
5250
  method: "POST",
3363
5251
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey }
3364
5252
  });
@@ -3369,7 +5257,7 @@ var VoidlyAgent = class _VoidlyAgent {
3369
5257
  * Mark multiple messages as read in one call.
3370
5258
  */
3371
5259
  async markReadBatch(messageIds) {
3372
- const res = await fetch(`${this.baseUrl}/v1/agent/messages/read-batch`, {
5260
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/messages/read-batch`, {
3373
5261
  method: "POST",
3374
5262
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3375
5263
  body: JSON.stringify({ message_ids: messageIds })
@@ -3383,7 +5271,7 @@ var VoidlyAgent = class _VoidlyAgent {
3383
5271
  async getUnreadCount(fromDid) {
3384
5272
  const params = new URLSearchParams();
3385
5273
  if (fromDid) params.set("from", fromDid);
3386
- const res = await fetch(`${this.baseUrl}/v1/agent/messages/unread-count?${params}`, {
5274
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/messages/unread-count?${params}`, {
3387
5275
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey }
3388
5276
  });
3389
5277
  if (!res.ok) throw new Error(`Failed to get unread count: ${res.status}`);
@@ -3397,13 +5285,21 @@ var VoidlyAgent = class _VoidlyAgent {
3397
5285
  * The relay finds matching agents and creates individual tasks for each.
3398
5286
  */
3399
5287
  async broadcastTask(options) {
3400
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks/broadcast`, {
5288
+ const inputBytes = (0, import_tweetnacl_util.decodeUTF8)(options.input);
5289
+ const broadcastNonce = import_tweetnacl.default.randomBytes(import_tweetnacl.default.secretbox.nonceLength);
5290
+ const broadcastEncrypted = import_tweetnacl.default.secretbox(inputBytes, broadcastNonce, import_tweetnacl.default.box.before(
5291
+ this.encryptionKeyPair.publicKey,
5292
+ this.encryptionKeyPair.secretKey
5293
+ ));
5294
+ const broadcastSig = import_tweetnacl.default.sign.detached(inputBytes, this.signingKeyPair.secretKey);
5295
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/broadcast`, {
3401
5296
  method: "POST",
3402
5297
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3403
5298
  body: JSON.stringify({
3404
5299
  capability: options.capability,
3405
- encrypted_input: (0, import_tweetnacl_util.encodeBase64)((0, import_tweetnacl_util.decodeUTF8)(options.input)),
3406
- input_nonce: (0, import_tweetnacl_util.encodeBase64)(import_tweetnacl.default.randomBytes(24)),
5300
+ encrypted_input: (0, import_tweetnacl_util.encodeBase64)(broadcastEncrypted),
5301
+ input_nonce: (0, import_tweetnacl_util.encodeBase64)(broadcastNonce),
5302
+ input_signature: (0, import_tweetnacl_util.encodeBase64)(broadcastSig),
3407
5303
  priority: options.priority,
3408
5304
  max_agents: options.maxAgents,
3409
5305
  min_trust_level: options.minTrustLevel,
@@ -3422,7 +5318,7 @@ var VoidlyAgent = class _VoidlyAgent {
3422
5318
  async listBroadcasts(status) {
3423
5319
  const params = new URLSearchParams();
3424
5320
  if (status) params.set("status", status);
3425
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks/broadcasts?${params}`, {
5321
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/broadcasts?${params}`, {
3426
5322
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey }
3427
5323
  });
3428
5324
  if (!res.ok) return [];
@@ -3433,7 +5329,7 @@ var VoidlyAgent = class _VoidlyAgent {
3433
5329
  * Get broadcast detail with individual task statuses.
3434
5330
  */
3435
5331
  async getBroadcast(broadcastId) {
3436
- const res = await fetch(`${this.baseUrl}/v1/agent/tasks/broadcasts/${broadcastId}`, {
5332
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/broadcasts/${broadcastId}`, {
3437
5333
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey }
3438
5334
  });
3439
5335
  if (!res.ok) throw new Error(`Failed to get broadcast: ${res.status}`);
@@ -3449,7 +5345,7 @@ var VoidlyAgent = class _VoidlyAgent {
3449
5345
  async getAnalytics(period) {
3450
5346
  const params = new URLSearchParams();
3451
5347
  if (period) params.set("period", period);
3452
- const res = await fetch(`${this.baseUrl}/v1/agent/analytics?${params}`, {
5348
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/analytics?${params}`, {
3453
5349
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey }
3454
5350
  });
3455
5351
  if (!res.ok) throw new Error(`Failed to get analytics: ${res.status}`);
@@ -3473,16 +5369,30 @@ var VoidlyAgent = class _VoidlyAgent {
3473
5369
  // ─── Memory Store ──────────────────────────────────────────────────────────
3474
5370
  /**
3475
5371
  * Store an encrypted key-value pair in persistent memory.
3476
- * Values are encrypted with a key derived from your API key — only you can read them.
5372
+ * Values are encrypted CLIENT-SIDE with nacl.secretbox before sending to relay.
5373
+ * The relay never sees plaintext values — true E2E encrypted storage.
3477
5374
  */
3478
5375
  async memorySet(namespace, key, value, options) {
3479
- const res = await fetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {
5376
+ const valueStr = JSON.stringify(value);
5377
+ const valueBytes = (0, import_tweetnacl_util.decodeUTF8)(valueStr);
5378
+ const memNonce = import_tweetnacl.default.randomBytes(import_tweetnacl.default.secretbox.nonceLength);
5379
+ const memKeyInput = new Uint8Array([...this.encryptionKeyPair.secretKey, 77, 69, 77]);
5380
+ let memKey;
5381
+ if (typeof globalThis.crypto?.subtle !== "undefined") {
5382
+ memKey = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", memKeyInput));
5383
+ } else {
5384
+ const { createHash } = await import("crypto");
5385
+ memKey = new Uint8Array(createHash("sha256").update(Buffer.from(memKeyInput)).digest());
5386
+ }
5387
+ const encryptedValue = import_tweetnacl.default.secretbox(valueBytes, memNonce, memKey);
5388
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {
3480
5389
  method: "PUT",
3481
5390
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3482
5391
  body: JSON.stringify({
3483
- value,
3484
- value_type: options?.valueType || (typeof value === "object" ? "json" : typeof value),
3485
- ttl: options?.ttl
5392
+ value: (0, import_tweetnacl_util.encodeBase64)(encryptedValue),
5393
+ value_type: `encrypted:${options?.valueType || (typeof value === "object" ? "json" : typeof value)}`,
5394
+ ttl: options?.ttl,
5395
+ client_nonce: (0, import_tweetnacl_util.encodeBase64)(memNonce)
3486
5396
  })
3487
5397
  });
3488
5398
  if (!res.ok) throw new Error(`Memory set failed: ${res.status} ${await res.text()}`);
@@ -3490,21 +5400,42 @@ var VoidlyAgent = class _VoidlyAgent {
3490
5400
  }
3491
5401
  /**
3492
5402
  * Retrieve a value from persistent memory.
3493
- * Decrypted server-side using your API key derivation.
5403
+ * Decrypted CLIENT-SIDE relay never sees plaintext.
3494
5404
  */
3495
5405
  async memoryGet(namespace, key) {
3496
- const res = await fetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {
5406
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {
3497
5407
  headers: { "X-Agent-Key": this.apiKey }
3498
5408
  });
3499
5409
  if (res.status === 404) return null;
3500
5410
  if (!res.ok) throw new Error(`Memory get failed: ${res.status} ${await res.text()}`);
3501
- return res.json();
5411
+ const data = await res.json();
5412
+ if (data.value_type?.startsWith("encrypted:") && data.client_nonce) {
5413
+ try {
5414
+ const memKeyInput = new Uint8Array([...this.encryptionKeyPair.secretKey, 77, 69, 77]);
5415
+ let memKey;
5416
+ if (typeof globalThis.crypto?.subtle !== "undefined") {
5417
+ memKey = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", memKeyInput));
5418
+ } else {
5419
+ const { createHash } = await import("crypto");
5420
+ memKey = new Uint8Array(createHash("sha256").update(Buffer.from(memKeyInput)).digest());
5421
+ }
5422
+ const encBytes = (0, import_tweetnacl_util.decodeBase64)(data.value);
5423
+ const memNonce = (0, import_tweetnacl_util.decodeBase64)(data.client_nonce);
5424
+ const plain = import_tweetnacl.default.secretbox.open(encBytes, memNonce, memKey);
5425
+ if (plain) {
5426
+ data.value = JSON.parse((0, import_tweetnacl_util.encodeUTF8)(plain));
5427
+ data.value_type = data.value_type.replace("encrypted:", "");
5428
+ }
5429
+ } catch {
5430
+ }
5431
+ }
5432
+ return data;
3502
5433
  }
3503
5434
  /**
3504
5435
  * Delete a key from persistent memory.
3505
5436
  */
3506
5437
  async memoryDelete(namespace, key) {
3507
- const res = await fetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {
5438
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`, {
3508
5439
  method: "DELETE",
3509
5440
  headers: { "X-Agent-Key": this.apiKey }
3510
5441
  });
@@ -3520,7 +5451,7 @@ var VoidlyAgent = class _VoidlyAgent {
3520
5451
  if (options?.prefix) params.set("prefix", options.prefix);
3521
5452
  if (options?.limit) params.set("limit", String(options.limit));
3522
5453
  const qs = params.toString() ? `?${params.toString()}` : "";
3523
- const res = await fetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(ns)}${qs}`, {
5454
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(ns)}${qs}`, {
3524
5455
  headers: { "X-Agent-Key": this.apiKey }
3525
5456
  });
3526
5457
  if (!res.ok) throw new Error(`Memory list failed: ${res.status} ${await res.text()}`);
@@ -3530,7 +5461,7 @@ var VoidlyAgent = class _VoidlyAgent {
3530
5461
  * List all memory namespaces and quota usage.
3531
5462
  */
3532
5463
  async memoryNamespaces() {
3533
- const res = await fetch(`${this.baseUrl}/v1/agent/memory`, {
5464
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/memory`, {
3534
5465
  headers: { "X-Agent-Key": this.apiKey }
3535
5466
  });
3536
5467
  if (!res.ok) throw new Error(`Memory namespaces failed: ${res.status} ${await res.text()}`);
@@ -3543,7 +5474,7 @@ var VoidlyAgent = class _VoidlyAgent {
3543
5474
  * Memory values remain encrypted — portable to another relay.
3544
5475
  */
3545
5476
  async exportData(options) {
3546
- const res = await fetch(`${this.baseUrl}/v1/agent/export`, {
5477
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/export`, {
3547
5478
  method: "POST",
3548
5479
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3549
5480
  body: JSON.stringify({
@@ -3562,7 +5493,7 @@ var VoidlyAgent = class _VoidlyAgent {
3562
5493
  * List past data export records.
3563
5494
  */
3564
5495
  async listExports() {
3565
- const res = await fetch(`${this.baseUrl}/v1/agent/exports`, {
5496
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/exports`, {
3566
5497
  headers: { "X-Agent-Key": this.apiKey }
3567
5498
  });
3568
5499
  if (!res.ok) throw new Error(`List exports failed: ${res.status} ${await res.text()}`);
@@ -3574,7 +5505,7 @@ var VoidlyAgent = class _VoidlyAgent {
3574
5505
  * Includes federation capabilities and known peers.
3575
5506
  */
3576
5507
  async getRelayInfo() {
3577
- const res = await fetch(`${this.baseUrl}/v1/relay/info`);
5508
+ const res = await this._timedFetch(`${this.baseUrl}/v1/relay/info`);
3578
5509
  if (!res.ok) throw new Error(`Relay info failed: ${res.status} ${await res.text()}`);
3579
5510
  return res.json();
3580
5511
  }
@@ -3582,7 +5513,7 @@ var VoidlyAgent = class _VoidlyAgent {
3582
5513
  * List known federated relay peers.
3583
5514
  */
3584
5515
  async getRelayPeers() {
3585
- const res = await fetch(`${this.baseUrl}/v1/relay/peers`);
5516
+ const res = await this._timedFetch(`${this.baseUrl}/v1/relay/peers`);
3586
5517
  if (!res.ok) throw new Error(`Relay peers failed: ${res.status} ${await res.text()}`);
3587
5518
  return res.json();
3588
5519
  }
@@ -3604,7 +5535,7 @@ var VoidlyAgent = class _VoidlyAgent {
3604
5535
  ciphertext_hash: await sha256((0, import_tweetnacl_util.encodeBase64)(encrypted))
3605
5536
  }));
3606
5537
  const signature = import_tweetnacl.default.sign.detached(signaturePayload, this.signingKeyPair.secretKey);
3607
- const res = await fetch(`${this.baseUrl}/v1/relay/route`, {
5538
+ const res = await this._timedFetch(`${this.baseUrl}/v1/relay/route`, {
3608
5539
  method: "POST",
3609
5540
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3610
5541
  body: JSON.stringify({
@@ -3622,7 +5553,7 @@ var VoidlyAgent = class _VoidlyAgent {
3622
5553
  // ── Heartbeat ──────────────────────────────────────────────────────────────
3623
5554
  /** Send heartbeat — signals agent is alive, updates last_seen */
3624
5555
  async ping() {
3625
- const res = await fetch(`${this.baseUrl}/v1/agent/ping`, {
5556
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/ping`, {
3626
5557
  method: "POST",
3627
5558
  headers: { "X-Agent-Key": this.apiKey }
3628
5559
  });
@@ -3631,14 +5562,14 @@ var VoidlyAgent = class _VoidlyAgent {
3631
5562
  }
3632
5563
  /** Check if another agent is online (public) */
3633
5564
  async checkOnline(did) {
3634
- const res = await fetch(`${this.baseUrl}/v1/agent/ping/${encodeURIComponent(did)}`);
5565
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/ping/${encodeURIComponent(did)}`);
3635
5566
  if (!res.ok) throw new Error(`Ping check failed: ${res.status}`);
3636
5567
  return res.json();
3637
5568
  }
3638
5569
  // ── Key Pinning (TOFU) ────────────────────────────────────────────────────
3639
5570
  /** Pin another agent's public keys (Trust On First Use). Returns warning if keys changed since last pin. */
3640
5571
  async pinKeys(did) {
3641
- const res = await fetch(`${this.baseUrl}/v1/agent/keys/pin`, {
5572
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/keys/pin`, {
3642
5573
  method: "POST",
3643
5574
  headers: { "Content-Type": "application/json", "X-Agent-Key": this.apiKey },
3644
5575
  body: JSON.stringify({ did })
@@ -3651,7 +5582,7 @@ var VoidlyAgent = class _VoidlyAgent {
3651
5582
  const params = new URLSearchParams();
3652
5583
  if (options?.status) params.set("status", options.status);
3653
5584
  const qs = params.toString() ? `?${params.toString()}` : "";
3654
- const res = await fetch(`${this.baseUrl}/v1/agent/keys/pins${qs}`, {
5585
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/keys/pins${qs}`, {
3655
5586
  headers: { "X-Agent-Key": this.apiKey }
3656
5587
  });
3657
5588
  if (!res.ok) throw new Error(`List pins failed: ${res.status}`);
@@ -3659,7 +5590,7 @@ var VoidlyAgent = class _VoidlyAgent {
3659
5590
  }
3660
5591
  /** Verify an agent's keys against your pinned copy. Detects key changes (potential MitM). */
3661
5592
  async verifyKeys(did) {
3662
- const res = await fetch(`${this.baseUrl}/v1/agent/keys/verify/${encodeURIComponent(did)}`, {
5593
+ const res = await this._timedFetch(`${this.baseUrl}/v1/agent/keys/verify/${encodeURIComponent(did)}`, {
3663
5594
  headers: { "X-Agent-Key": this.apiKey }
3664
5595
  });
3665
5596
  if (!res.ok) throw new Error(`Key verify failed: ${res.status}`);
@@ -3870,6 +5801,21 @@ var VoidlyAgent = class _VoidlyAgent {
3870
5801
  // ═══════════════════════════════════════════════════════════════════════════
3871
5802
  // INTERNAL — Retry, Auto-Pin
3872
5803
  // ═══════════════════════════════════════════════════════════════════════════
5804
+ /** @internal Fetch with timeout via AbortController */
5805
+ async _timedFetch(url, init) {
5806
+ const controller = new AbortController();
5807
+ const timer = setTimeout(() => controller.abort(), this.timeout);
5808
+ try {
5809
+ return await fetch(url, { ...init, signal: controller.signal });
5810
+ } catch (err) {
5811
+ if (err instanceof Error && err.name === "AbortError") {
5812
+ throw new Error(`Request timed out after ${this.timeout}ms: ${url.replace(this.baseUrl, "")}`);
5813
+ }
5814
+ throw err;
5815
+ } finally {
5816
+ clearTimeout(timer);
5817
+ }
5818
+ }
3873
5819
  /** @internal Auto-pin keys on first contact (TOFU) */
3874
5820
  async _autoPinKeys(did) {
3875
5821
  if (this._pinnedDids.has(did)) return;
@@ -3890,7 +5836,7 @@ var VoidlyAgent = class _VoidlyAgent {
3890
5836
  let lastError = null;
3891
5837
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
3892
5838
  try {
3893
- const res = await fetch(url, init);
5839
+ const res = await this._timedFetch(url, init);
3894
5840
  if (res.ok) {
3895
5841
  return await res.json();
3896
5842
  }
@@ -3967,31 +5913,42 @@ var VoidlyAgent = class _VoidlyAgent {
3967
5913
  "Approximate message size (even with padding, bounded to power-of-2)"
3968
5914
  ],
3969
5915
  relayCannotSee: [
3970
- "Message content (E2E encrypted with NaCl box)",
5916
+ "Message content (E2E encrypted \u2014 nacl.secretbox with ratchet-derived per-message keys)",
3971
5917
  "Private keys (generated and stored client-side only)",
3972
- "Memory values (encrypted with key derived from your API key)",
3973
- "Attestation content (signed but readable by anyone with the attestation)",
5918
+ "Memory values (encrypted CLIENT-SIDE with nacl.secretbox before relay storage)",
5919
+ "Past message keys (hash ratchet provides forward secrecy \u2014 old keys are deleted)",
3974
5920
  ...this.sealedSender ? ["Sender identity (sealed inside ciphertext)"] : []
3975
5921
  ],
3976
5922
  protections: [
5923
+ "Hash ratchet forward secrecy \u2014 per-message key derivation, old keys deleted",
5924
+ ...this.postQuantum && this.mlkemPublicKey ? ["ML-KEM-768 + X25519 hybrid key exchange (NIST FIPS 203 post-quantum, harvest-now-decrypt-later resistant)"] : [],
3977
5925
  "X25519 key exchange + XSalsa20-Poly1305 authenticated encryption",
3978
- "Ed25519 signatures on every message",
5926
+ "Ed25519 signatures on every message (envelope + ciphertext hash)",
3979
5927
  "TOFU key pinning (MitM detection on key change)",
5928
+ "Client-side memory encryption (relay never sees plaintext values)",
5929
+ "Protocol version header (deterministic padding/sealing detection, no heuristics)",
5930
+ "Identity cache (reduced key lookups, 5-min TTL)",
5931
+ "Message deduplication (track seen message IDs)",
5932
+ "Request timeouts (AbortController on all HTTP, configurable)",
5933
+ "Request validation (fromCredentials validates key sizes and format)",
3980
5934
  ...this.paddingEnabled ? ["Message padding to power-of-2 boundary (traffic analysis resistance)"] : [],
3981
5935
  ...this.sealedSender ? ["Sealed sender (relay cannot see who sent a message)"] : [],
5936
+ ...this.requireSignatures ? ["Strict signature enforcement (reject unsigned/invalid messages)"] : [],
3982
5937
  ...this.fallbackRelays.length > 0 ? [`Multi-relay fallback (${this.fallbackRelays.length} backup relays)`] : [],
3983
5938
  "Auto-retry with exponential backoff",
3984
- "Offline message queue"
5939
+ "Offline message queue",
5940
+ "did:key interoperability (W3C standard DID format)"
3985
5941
  ],
3986
5942
  gaps: [
3987
- "No forward secrecy \u2014 same keypair for all messages (compromise exposes ALL history)",
3988
- "No post-quantum protection \u2014 vulnerable to harvest-now-decrypt-later",
5943
+ "No DH ratchet yet \u2014 hash ratchet only (no post-compromise recovery, planned for v3)",
5944
+ ...!this.postQuantum || !this.mlkemPublicKey ? ["No post-quantum protection \u2014 enable postQuantum option and re-register"] : [],
3989
5945
  "Channel encryption is server-side (relay holds channel keys, NOT true E2E)",
3990
5946
  "Metadata (who, when, thread structure) visible to relay operator",
3991
5947
  "Single relay architecture (no onion routing, no mix network)",
3992
5948
  "Ed25519 signatures are non-repudiable (no deniable messaging)",
3993
5949
  "No async key agreement (no X3DH prekeys)",
3994
- "Polling-based (no WebSocket real-time transport)"
5950
+ "Polling-based (no WebSocket real-time transport)",
5951
+ "Ratchet state is in-memory (lost on process restart \u2014 export credentials to persist)"
3995
5952
  ]
3996
5953
  };
3997
5954
  }
@@ -4017,6 +5974,9 @@ var Conversation = class {
4017
5974
  replyTo: this._lastMessageId || void 0
4018
5975
  });
4019
5976
  this._lastMessageId = result.id;
5977
+ if (this._messageHistory.length >= 1e3) {
5978
+ this._messageHistory.splice(0, this._messageHistory.length - 999);
5979
+ }
4020
5980
  this._messageHistory.push({
4021
5981
  id: result.id,
4022
5982
  from: this.agent.did,
@@ -4071,9 +6031,9 @@ var Conversation = class {
4071
6031
  messageType: msg.messageType
4072
6032
  });
4073
6033
  this._lastMessageId = msg.id;
4074
- for (const h of this._replyHandlers) {
6034
+ for (const h2 of this._replyHandlers) {
4075
6035
  try {
4076
- await h(msg);
6036
+ await h2(msg);
4077
6037
  } catch {
4078
6038
  }
4079
6039
  }
@@ -4091,14 +6051,23 @@ var Conversation = class {
4091
6051
  async waitForReply(timeoutMs = 3e4) {
4092
6052
  return new Promise((resolve, reject) => {
4093
6053
  let resolved = false;
6054
+ let pollTimer = null;
6055
+ const cleanup = () => {
6056
+ resolved = true;
6057
+ if (pollTimer) {
6058
+ clearTimeout(pollTimer);
6059
+ pollTimer = null;
6060
+ }
6061
+ };
4094
6062
  const timeout = setTimeout(() => {
4095
6063
  if (!resolved) {
4096
- resolved = true;
6064
+ cleanup();
4097
6065
  reject(new Error(`No reply received within ${timeoutMs}ms`));
4098
6066
  }
4099
6067
  }, timeoutMs);
4100
6068
  const check = async () => {
4101
- while (!resolved) {
6069
+ if (resolved) return;
6070
+ try {
4102
6071
  const messages = await this.agent.receive({
4103
6072
  from: this.peerDid,
4104
6073
  threadId: this.threadId,
@@ -4106,9 +6075,12 @@ var Conversation = class {
4106
6075
  limit: 1
4107
6076
  });
4108
6077
  if (messages.length > 0 && !resolved) {
4109
- resolved = true;
4110
6078
  clearTimeout(timeout);
6079
+ cleanup();
4111
6080
  const msg = messages[0];
6081
+ if (this._messageHistory.length >= 1e3) {
6082
+ this._messageHistory.splice(0, this._messageHistory.length - 999);
6083
+ }
4112
6084
  this._messageHistory.push({
4113
6085
  id: msg.id,
4114
6086
  from: msg.from,
@@ -4123,16 +6095,19 @@ var Conversation = class {
4123
6095
  resolve(msg);
4124
6096
  return;
4125
6097
  }
4126
- await new Promise((r) => setTimeout(r, 1500));
6098
+ } catch (err) {
6099
+ if (!resolved) {
6100
+ clearTimeout(timeout);
6101
+ cleanup();
6102
+ reject(err instanceof Error ? err : new Error(String(err)));
6103
+ return;
6104
+ }
4127
6105
  }
4128
- };
4129
- check().catch((err) => {
4130
6106
  if (!resolved) {
4131
- resolved = true;
4132
- clearTimeout(timeout);
4133
- reject(err);
6107
+ pollTimer = setTimeout(check, 1500);
4134
6108
  }
4135
- });
6109
+ };
6110
+ check();
4136
6111
  });
4137
6112
  }
4138
6113
  /**
@@ -4168,3 +6143,8 @@ export {
4168
6143
  export_encodeUTF8 as encodeUTF8,
4169
6144
  export_nacl as nacl
4170
6145
  };
6146
+ /*! Bundled license information:
6147
+
6148
+ mlkem/esm/src/sha3/utils.js:
6149
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
6150
+ */