@codemem/core 0.49.0-beta.2 → 0.49.0-beta.3

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.
Files changed (177) hide show
  1. package/dist/better-sqlite-coordinator-store.d.ts +21 -2
  2. package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
  3. package/dist/coordinator-account-change-authority.d.ts +56 -0
  4. package/dist/coordinator-account-change-authority.d.ts.map +1 -0
  5. package/dist/coordinator-account-change-decision.d.ts +141 -0
  6. package/dist/coordinator-account-change-decision.d.ts.map +1 -0
  7. package/dist/coordinator-account-change-http-test-fixtures.d.ts +3 -1
  8. package/dist/coordinator-account-change-http-test-fixtures.d.ts.map +1 -1
  9. package/dist/coordinator-account-change-original-sql-test-fixtures.d.ts +61 -0
  10. package/dist/coordinator-account-change-original-sql-test-fixtures.d.ts.map +1 -0
  11. package/dist/coordinator-account-change.d.ts +7 -1
  12. package/dist/coordinator-account-change.d.ts.map +1 -1
  13. package/dist/coordinator-account-connection-schema.d.ts +31 -0
  14. package/dist/coordinator-account-connection-schema.d.ts.map +1 -1
  15. package/dist/coordinator-account-connection-session.d.ts +9 -0
  16. package/dist/coordinator-account-connection-session.d.ts.map +1 -1
  17. package/dist/coordinator-account-historical-revoke-original-sql-test-fixtures.d.ts +7 -0
  18. package/dist/coordinator-account-historical-revoke-original-sql-test-fixtures.d.ts.map +1 -0
  19. package/dist/coordinator-account-historical-revoke.d.ts +8 -2
  20. package/dist/coordinator-account-historical-revoke.d.ts.map +1 -1
  21. package/dist/coordinator-account-link-status.d.ts.map +1 -1
  22. package/dist/coordinator-account-schema-sqlite-test-fixtures.d.ts +58 -0
  23. package/dist/coordinator-account-schema-sqlite-test-fixtures.d.ts.map +1 -0
  24. package/dist/coordinator-account-schema-test-fixtures.d.ts +20 -0
  25. package/dist/coordinator-account-schema-test-fixtures.d.ts.map +1 -0
  26. package/dist/coordinator-auth-browser-owner-purpose-test-harness.d.ts.map +1 -1
  27. package/dist/coordinator-auth-browser-transaction-test-fixtures.d.ts.map +1 -1
  28. package/dist/coordinator-auth-browser-transaction.d.ts.map +1 -1
  29. package/dist/coordinator-auth-controller-consistency-test-fixtures.d.ts +5 -1
  30. package/dist/coordinator-auth-controller-consistency-test-fixtures.d.ts.map +1 -1
  31. package/dist/coordinator-auth-controller-history.d.ts +0 -1
  32. package/dist/coordinator-auth-controller-history.d.ts.map +1 -1
  33. package/dist/coordinator-auth-controller-original-sql-test-fixtures.d.ts +41 -0
  34. package/dist/coordinator-auth-controller-original-sql-test-fixtures.d.ts.map +1 -0
  35. package/dist/coordinator-auth-controller-owner.d.ts +0 -6
  36. package/dist/coordinator-auth-controller-owner.d.ts.map +1 -1
  37. package/dist/coordinator-auth-controller-race-test-fixtures.d.ts +38 -0
  38. package/dist/coordinator-auth-controller-race-test-fixtures.d.ts.map +1 -0
  39. package/dist/coordinator-auth-controller-read-set.d.ts +47 -0
  40. package/dist/coordinator-auth-controller-read-set.d.ts.map +1 -0
  41. package/dist/coordinator-auth-controller-stages-original-sql-test-fixtures.d.ts +8 -0
  42. package/dist/coordinator-auth-controller-stages-original-sql-test-fixtures.d.ts.map +1 -0
  43. package/dist/coordinator-auth-controller.d.ts +1 -21
  44. package/dist/coordinator-auth-controller.d.ts.map +1 -1
  45. package/dist/coordinator-auth-device-claim-eligibility.d.ts +39 -1
  46. package/dist/coordinator-auth-device-claim-eligibility.d.ts.map +1 -1
  47. package/dist/coordinator-auth-historical-store-test-fixture.d.ts +2 -0
  48. package/dist/coordinator-auth-historical-store-test-fixture.d.ts.map +1 -1
  49. package/dist/coordinator-auth-legacy-assignment.d.ts +4 -2
  50. package/dist/coordinator-auth-legacy-assignment.d.ts.map +1 -1
  51. package/dist/coordinator-auth-link-authority-upgrade.d.ts +5 -0
  52. package/dist/coordinator-auth-link-authority-upgrade.d.ts.map +1 -1
  53. package/dist/coordinator-auth-link-maintenance-fixtures.d.ts +2 -2
  54. package/dist/coordinator-auth-link-maintenance-fixtures.d.ts.map +1 -1
  55. package/dist/coordinator-auth-link-provenance.d.ts.map +1 -1
  56. package/dist/coordinator-auth-link-revocation-test-harness.d.ts.map +1 -1
  57. package/dist/coordinator-auth-link-test-fixtures.d.ts +26 -4
  58. package/dist/coordinator-auth-link-test-fixtures.d.ts.map +1 -1
  59. package/dist/coordinator-auth-link.d.ts +4 -0
  60. package/dist/coordinator-auth-link.d.ts.map +1 -1
  61. package/dist/coordinator-auth-read-set.d.ts +99 -0
  62. package/dist/coordinator-auth-read-set.d.ts.map +1 -0
  63. package/dist/coordinator-auth-schema-stage.d.ts +36 -0
  64. package/dist/coordinator-auth-schema-stage.d.ts.map +1 -0
  65. package/dist/coordinator-auth-schema.d.ts.map +1 -1
  66. package/dist/coordinator-auth-session.d.ts.map +1 -1
  67. package/dist/coordinator-auth-store-test-fixtures.d.ts +12 -0
  68. package/dist/coordinator-auth-store-test-fixtures.d.ts.map +1 -1
  69. package/dist/coordinator-controller-revocation-test-harness.d.ts.map +1 -1
  70. package/dist/coordinator-d1-schema-inventory.d.ts +10 -0
  71. package/dist/coordinator-d1-schema-inventory.d.ts.map +1 -0
  72. package/dist/coordinator-device-claim-binding-reuse.d.ts +2 -0
  73. package/dist/coordinator-device-claim-binding-reuse.d.ts.map +1 -1
  74. package/dist/coordinator-device-claim-binding-sql.d.ts +8 -0
  75. package/dist/coordinator-device-claim-binding-sql.d.ts.map +1 -1
  76. package/dist/coordinator-device-ownership-evidence-original-sql-test-fixtures.d.ts +88 -0
  77. package/dist/coordinator-device-ownership-evidence-original-sql-test-fixtures.d.ts.map +1 -0
  78. package/dist/coordinator-device-ownership-evidence-queries.d.ts +4 -14
  79. package/dist/coordinator-device-ownership-evidence-queries.d.ts.map +1 -1
  80. package/dist/coordinator-device-ownership-evidence-test-fixtures.d.ts +10 -0
  81. package/dist/coordinator-device-ownership-evidence-test-fixtures.d.ts.map +1 -1
  82. package/dist/coordinator-device-ownership-evidence.d.ts +11 -3
  83. package/dist/coordinator-device-ownership-evidence.d.ts.map +1 -1
  84. package/dist/coordinator-device-rebind-browser.d.ts +1 -1
  85. package/dist/coordinator-device-rebind-ceremony.d.ts +2 -1
  86. package/dist/coordinator-device-rebind-ceremony.d.ts.map +1 -1
  87. package/dist/coordinator-device-rebind-commit.d.ts.map +1 -1
  88. package/dist/coordinator-device-rebind-test-fixtures.d.ts.map +1 -1
  89. package/dist/coordinator-device-self-bind-authority.d.ts +11 -2
  90. package/dist/coordinator-device-self-bind-authority.d.ts.map +1 -1
  91. package/dist/coordinator-device-self-bind-decision.d.ts +84 -0
  92. package/dist/coordinator-device-self-bind-decision.d.ts.map +1 -0
  93. package/dist/coordinator-device-self-bind-original-sql-test-fixtures.d.ts +17 -0
  94. package/dist/coordinator-device-self-bind-original-sql-test-fixtures.d.ts.map +1 -0
  95. package/dist/coordinator-device-self-bind-test-fixtures.d.ts +12 -1
  96. package/dist/coordinator-device-self-bind-test-fixtures.d.ts.map +1 -1
  97. package/dist/coordinator-history-sql-equivalence-test-fixtures.d.ts +6 -2
  98. package/dist/coordinator-history-sql-equivalence-test-fixtures.d.ts.map +1 -1
  99. package/dist/coordinator-legacy-completion-owner-proof-original-sql-test-fixtures.d.ts +77 -0
  100. package/dist/coordinator-legacy-completion-owner-proof-original-sql-test-fixtures.d.ts.map +1 -0
  101. package/dist/coordinator-legacy-completion-owner-proof-test-fixtures.d.ts +46 -0
  102. package/dist/coordinator-legacy-completion-owner-proof-test-fixtures.d.ts.map +1 -0
  103. package/dist/coordinator-legacy-completion-owner-proof.d.ts +19 -2
  104. package/dist/coordinator-legacy-completion-owner-proof.d.ts.map +1 -1
  105. package/dist/coordinator-legacy-owner-compatibility.d.ts +23 -0
  106. package/dist/coordinator-legacy-owner-compatibility.d.ts.map +1 -1
  107. package/dist/coordinator-legacy-owner-resolution-commit-original-sql-test-fixtures.d.ts +63 -0
  108. package/dist/coordinator-legacy-owner-resolution-commit-original-sql-test-fixtures.d.ts.map +1 -0
  109. package/dist/coordinator-legacy-owner-resolution-commit-test-fixtures.d.ts +3 -1
  110. package/dist/coordinator-legacy-owner-resolution-commit-test-fixtures.d.ts.map +1 -1
  111. package/dist/coordinator-legacy-owner-resolution-commit.d.ts.map +1 -1
  112. package/dist/coordinator-owner-enrollment-commit.d.ts.map +1 -1
  113. package/dist/coordinator-owner-enrollment-historical-test-fixture.d.ts +2 -0
  114. package/dist/coordinator-owner-enrollment-historical-test-fixture.d.ts.map +1 -1
  115. package/dist/coordinator-owner-enrollment-start-test-fixtures.d.ts.map +1 -1
  116. package/dist/coordinator-owner-negative-consistency.d.ts +11 -17
  117. package/dist/coordinator-owner-negative-consistency.d.ts.map +1 -1
  118. package/dist/coordinator-owner-negative-original-sql-test-fixtures.d.ts +44 -0
  119. package/dist/coordinator-owner-negative-original-sql-test-fixtures.d.ts.map +1 -0
  120. package/dist/coordinator-owner-negative-race-test-fixtures.d.ts +26 -0
  121. package/dist/coordinator-owner-negative-race-test-fixtures.d.ts.map +1 -0
  122. package/dist/coordinator-owner-negative-read-set.d.ts +43 -0
  123. package/dist/coordinator-owner-negative-read-set.d.ts.map +1 -0
  124. package/dist/coordinator-owner-negative-reads.d.ts +32 -0
  125. package/dist/coordinator-owner-negative-reads.d.ts.map +1 -0
  126. package/dist/coordinator-owner-producer-original-sql-test-fixtures.d.ts +26 -0
  127. package/dist/coordinator-owner-producer-original-sql-test-fixtures.d.ts.map +1 -0
  128. package/dist/coordinator-owner-resolution-review-test-fixtures.d.ts +1 -0
  129. package/dist/coordinator-owner-resolution-review-test-fixtures.d.ts.map +1 -1
  130. package/dist/coordinator-owner-resolution-review.d.ts +1 -0
  131. package/dist/coordinator-owner-resolution-review.d.ts.map +1 -1
  132. package/dist/coordinator-producer-negative-owner-test-fixtures.d.ts +8 -2
  133. package/dist/coordinator-producer-negative-owner-test-fixtures.d.ts.map +1 -1
  134. package/dist/coordinator-recipient-negative-race-test-fixtures.d.ts +54 -0
  135. package/dist/coordinator-recipient-negative-race-test-fixtures.d.ts.map +1 -0
  136. package/dist/coordinator-recipient-owner-consistency.d.ts +4 -5
  137. package/dist/coordinator-recipient-owner-consistency.d.ts.map +1 -1
  138. package/dist/coordinator-recipient-owner-original-sql-test-fixtures.d.ts +30 -0
  139. package/dist/coordinator-recipient-owner-original-sql-test-fixtures.d.ts.map +1 -0
  140. package/dist/coordinator-resolved-account-owner-status-query.d.ts +4 -1
  141. package/dist/coordinator-resolved-account-owner-status-query.d.ts.map +1 -1
  142. package/dist/coordinator-resolved-account-owner-status-test-fixtures.d.ts +1 -0
  143. package/dist/coordinator-resolved-account-owner-status-test-fixtures.d.ts.map +1 -1
  144. package/dist/coordinator-resolved-account-owner-status.d.ts +2 -0
  145. package/dist/coordinator-resolved-account-owner-status.d.ts.map +1 -1
  146. package/dist/{coordinator-runtime-kbPwxxKq.js → coordinator-runtime-BXJQAKFD.js} +3 -3
  147. package/dist/{coordinator-runtime-kbPwxxKq.js.map → coordinator-runtime-BXJQAKFD.js.map} +1 -1
  148. package/dist/coordinator-sql-compare.d.ts +22 -0
  149. package/dist/coordinator-sql-compare.d.ts.map +1 -0
  150. package/dist/d1-coordinator-store.d.ts +16 -1
  151. package/dist/d1-coordinator-store.d.ts.map +1 -1
  152. package/dist/index.d.ts +2 -1
  153. package/dist/index.d.ts.map +1 -1
  154. package/dist/index.js +8907 -8434
  155. package/dist/index.js.map +1 -1
  156. package/dist/internal/cloudflare-coordinator.js +1070 -1065
  157. package/dist/internal/cloudflare-coordinator.js.map +1 -1
  158. package/dist/internal/relay-runtime.js +2 -2
  159. package/dist/linked-legacy-setup-test-fixtures.d.ts +2 -0
  160. package/dist/linked-legacy-setup-test-fixtures.d.ts.map +1 -1
  161. package/dist/{owner-enrollment-start-BtoRKf3z.js → owner-enrollment-start-BFyBKWvZ.js} +2626 -2425
  162. package/dist/owner-enrollment-start-BFyBKWvZ.js.map +1 -0
  163. package/dist/owner-enrollment-start.d.ts.map +1 -1
  164. package/dist/relay-admission-table-keys-test-fixtures.d.ts +2 -1
  165. package/dist/relay-admission-table-keys-test-fixtures.d.ts.map +1 -1
  166. package/dist/{relay-peer-client-0XpekgnZ.js → relay-peer-client-DrTb2oZt.js} +2631 -2617
  167. package/dist/relay-peer-client-DrTb2oZt.js.map +1 -0
  168. package/dist/{sync-auth-constants-DvALG0T0.js → sync-auth-constants-BVzVfSmn.js} +4019 -3416
  169. package/dist/sync-auth-constants-BVzVfSmn.js.map +1 -0
  170. package/dist/{sync-reachability-pass-BpDt2z4y.js → sync-reachability-pass-CUe5bK61.js} +12 -12
  171. package/dist/{sync-reachability-pass-BpDt2z4y.js.map → sync-reachability-pass-CUe5bK61.js.map} +1 -1
  172. package/dist/sync-reachability-pass-D9cA54fj.js +2 -0
  173. package/package.json +3 -3
  174. package/dist/owner-enrollment-start-BtoRKf3z.js.map +0 -1
  175. package/dist/relay-peer-client-0XpekgnZ.js.map +0 -1
  176. package/dist/sync-auth-constants-DvALG0T0.js.map +0 -1
  177. package/dist/sync-reachability-pass-Bi4GBi-x.js +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"file":"relay-peer-client-0XpekgnZ.js","names":["InvalidCryptoExchangeError","alloc","isByteArrayWithArrayBuffer","equals","alloc","equals","equals","fromString","toString","src","or","from","basex","decode","encode","encode","decode","from","identity","from","toString","fromString","encode","MSB","decode","read","MSB$1","N1","N2","N3","N4","N5","N6","N7","length","decode","varint","encodingLength","varint.encodingLength","decode","varint.decode","equalBytes","encode","Digest.create","Digest.create","sha256","sha512","Digest.create","Digest.equals","Digest.decode","Digest.Digest","varint.decode","varint.encodingLength","identityBase","base2","base8","base10","base16","base32","base36","base58","base64","base256emoji","sha2","identity","createCodec","bases","bases","deferred","DEFAULT_MAX_BUFFER_SIZE","varint.encodingLength","varint.decode","varint.encode","varint.decode","varint.encodingLength","isBytes","atitle","abool","anumber","abytes","aobject","aexists","aoutput","clean","createView","checkOpts","copyBytes","checkOpts","copyBytes","copyBytes","abytes","isBytes","atitle","anumber","abytes","aobject","bytesToHex","hexToBytes","concatBytes","randomBytes","u64.split","u64.rotrSH","u64.shrSH","u64.rotrSL","u64.shrSL","u64.rotrBH","u64.rotrBL","u64.add4L","u64.add4H","u64.add5L","u64.add5H","u64.add","u64.add3L","u64.add3H","abytes_","anumber_","bytesToHex_","concatBytes_","hexToBytes_","isBytes_","randomBytes","randomBytes_","_0n","_1n","_0n","_1n","_2n","_3n","_4n","_5n","_8n","gcd","_0n","_1n","_4n","_0n","_1n","_2n","_4n","_8n","wcRandomBytes","_0n","_1n","_2n","randomBytes","_0n","_1n","_2n","_3n","uint8ArrayAllocUnsafe","uint8ArrayToString","uint8ArrayAlloc","uint8ArrayAlloc","uint8ArrayFromString","hashAndSign","hashAndVerify","uint8ArrayToString","ECDSAPrivateKeyClass","ECDSAPublicKeyClass","uint8ArrayFromString","uint8ArrayEquals","hashAndVerify","hashAndSign","crypto","uint8arrayToString","ed","hashAndSign","hashAndVerify","uint8ArrayEquals","crypto.hashAndVerify","crypto.hashAndSign","Ed25519PrivateKeyClass","Ed25519PublicKeyClass","utf8.read","utf8.length","utf8.write","uint8ArrayFromString","utils.jwkToPkix","uint8ArrayEquals","hashAndVerify","utils.jwkToPkcs1","hashAndSign","uint8ArrayToString","uint8ArrayFromString","RSAPublicKeyClass","RSAPrivateKeyClass","hashAndSign","webcrypto","hashAndVerify","uint8ArrayFromString","_0n","_2n","wcRandomBytes","hmac","nobleHmac","sha256","secp","uint8ArrayEquals","Secp256k1PrivateKeyClass","Secp256k1PublicKeyClass","secp","pb.KeyType","uint8ArrayEquals","Ed25519PeerIdClass","Secp256k1PeerIdClass","RSAPeerIdClass","uint8ArrayAlloc","uint8ArrayFromString","uint8ArrayConcat","uint8ArrayAlloc","InvalidCryptoExchangeError"],"sources":["../src/sync-identity.ts","../src/coordinator-auth-browser-schema-upgrade.ts","../src/coordinator-device-ownership-schema.ts","../src/better-sqlite-coordinator-store.ts","../src/sync-auth.ts","../src/sync-http-client.ts","../src/coordinator-sync-config.ts","../src/scope-membership-cache.ts","../src/address-utils.ts","../src/sync-peer-addresses.ts","../src/sync-capability.ts","../src/peer-http-policy.ts","../src/peer-http-client-lifecycle.ts","../src/peer-http-headers.ts","../src/peer-http-server-response.ts","../src/peer-http-wire-audit.ts","../../../node_modules/.pnpm/@libp2p+interface@3.4.0/node_modules/@libp2p/interface/dist/src/errors.js","../../../node_modules/.pnpm/@libp2p+interface@3.4.0/node_modules/@libp2p/interface/dist/src/events.js","../../../node_modules/.pnpm/@libp2p+interface@3.4.0/node_modules/@libp2p/interface/dist/src/peer-id.js","../../../node_modules/.pnpm/main-event@1.0.5/node_modules/main-event/dist/src/events.browser.js","../../../node_modules/.pnpm/main-event@1.0.5/node_modules/main-event/dist/src/index.js","../../../node_modules/.pnpm/@libp2p+interface@3.4.0/node_modules/@libp2p/interface/dist/src/index.js","../../../node_modules/.pnpm/uint8arrays@6.1.1/node_modules/uint8arrays/dist/src/alloc.js","../../../node_modules/.pnpm/uint8arrays@6.1.1/node_modules/uint8arrays/dist/src/util/as-uint8array.js","../../../node_modules/.pnpm/uint8arrays@6.1.1/node_modules/uint8arrays/dist/src/concat.js","../../../node_modules/.pnpm/uint8arrays@6.1.1/node_modules/uint8arrays/dist/src/equals.js","../../../node_modules/.pnpm/uint8arraylist@3.0.2/node_modules/uint8arraylist/dist/src/index.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/bytes.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/vendor/base-x.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/bases/base.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/bases/base10.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/bases/base16.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/bases/base2.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/bases/base256emoji.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/bases/base32.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/bases/base36.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/bases/base58.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/bases/base64.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/bases/base8.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/bases/identity.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/codecs/json.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/vendor/varint.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/varint.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/hashes/digest.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/hashes/identity.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/hashes/hasher.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/hashes/sha2-browser.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/cid.js","../../../node_modules/.pnpm/multiformats@14.0.5/node_modules/multiformats/dist/src/basics.js","../../../node_modules/.pnpm/uint8arrays@6.1.1/node_modules/uint8arrays/dist/src/util/bases.js","../../../node_modules/.pnpm/uint8arrays@6.1.1/node_modules/uint8arrays/dist/src/from-string.js","../../../node_modules/.pnpm/uint8-varint@3.0.0/node_modules/uint8-varint/dist/src/index.js","../../../node_modules/.pnpm/uint8arrays@6.1.1/node_modules/uint8arrays/dist/src/with-array-buffer.js","../../../node_modules/.pnpm/uint8arrays@6.1.1/node_modules/uint8arrays/dist/src/to-string.js","../../../node_modules/.pnpm/p-defer@4.0.1/node_modules/p-defer/index.js","../../../node_modules/.pnpm/it-pushable@3.2.4/node_modules/it-pushable/dist/src/fifo.js","../../../node_modules/.pnpm/it-pushable@3.2.4/node_modules/it-pushable/dist/src/index.js","../../../node_modules/.pnpm/p-timeout@7.0.2/node_modules/p-timeout/index.js","../../../node_modules/.pnpm/p-event@8.0.1/node_modules/p-event/index.js","../../../node_modules/.pnpm/@libp2p+utils@7.4.5/node_modules/@libp2p/utils/dist/src/errors.js","../../../node_modules/.pnpm/race-signal@2.0.2/node_modules/race-signal/dist/src/index.js","../../../node_modules/.pnpm/@libp2p+utils@7.4.5/node_modules/@libp2p/utils/dist/src/abstract-message-stream.js","../../../node_modules/.pnpm/@libp2p+utils@7.4.5/node_modules/@libp2p/utils/dist/src/stream-utils.js","../../../node_modules/.pnpm/@libp2p+utils@7.4.5/node_modules/@libp2p/utils/dist/src/length-prefixed-decoder.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/constants.js","../../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/utils.js","../../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/_arx.js","../../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/_poly1305.js","../../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/chacha.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/utils.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/modular.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/curve.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/edwards.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/montgomery.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/ed25519.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/hmac.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/hkdf.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/crypto/js.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/crypto/index.browser.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/crypto.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/encoder.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/metrics.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/logger.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/errors.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/nonce.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/protocol.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/ecdsa/index.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/rsa/der.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/ecdsa/utils.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/ecdsa/ecdsa.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/errors.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/webcrypto/index.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/ed25519/index.browser.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/util.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/ed25519/ed25519.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/ed25519/utils.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/utils/float.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/utils/longbits.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/utils/utf8.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/utils/reader.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/decode.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/utils/pool.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/utils/writer.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/encode.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/stream.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/codec.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/codecs/enum.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/codecs/message.js","../../../node_modules/.pnpm/protons-runtime@7.1.2/node_modules/protons-runtime/dist/src/index.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/keys.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/rsa/rsa.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/rsa/utils.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/rsa/index.browser.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/der.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/weierstrass.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/secp256k1.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/secp256k1/index.browser.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/secp256k1/secp256k1.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/secp256k1/utils.js","../../../node_modules/.pnpm/@libp2p+crypto@5.2.0/node_modules/@libp2p/crypto/dist/src/keys/index.js","../../../node_modules/.pnpm/@libp2p+peer-id@6.0.18/node_modules/@libp2p/peer-id/dist/src/peer-id.js","../../../node_modules/.pnpm/@libp2p+peer-id@6.0.18/node_modules/@libp2p/peer-id/dist/src/index.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/proto/payload.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/utils.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/performHandshake.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/noise.js","../../../node_modules/.pnpm/@libp2p+noise@17.0.7/node_modules/@libp2p/noise/dist/src/index.js","../src/relay-failure-reason.ts","../src/relay-noise-identity.ts","../src/relay-noise-opening.ts","../src/relay-noise-stream.ts","../src/relay-noise.ts","../src/peer-http-server.ts","../src/relay-peer-transport.ts","../src/relay-peer-client.ts"],"sourcesContent":["/**\n * Device identity management for the codemem sync system.\n *\n * Handles Ed25519 keypair generation, fingerprinting, and optional\n * keychain storage. Ported from codemem/sync_identity.py.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport { connect as connectDb, resolveDbPath } from \"./db.js\";\nimport { codememHomeDir } from \"./home.js\";\nimport { adoptLocalCapture, hasPendingLocalCapture } from \"./memory-local-capture.js\";\nimport { readCodememConfigFile } from \"./observer-config.js\";\nimport * as schema from \"./schema.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\nexport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst PRIVATE_KEY_NAME = \"device.key\";\nconst PUBLIC_KEY_NAME = \"device.key.pub\";\nconst KEYCHAIN_SERVICE = \"codemem-sync\";\n\nfunction defaultKeysDir(): string {\n\treturn join(codememHomeDir(), \".config\", \"codemem\", \"keys\");\n}\n\n// ---------------------------------------------------------------------------\n// Fingerprint\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Key store mode\n// ---------------------------------------------------------------------------\n\nfunction keyStoreMode(): \"file\" | \"keychain\" {\n\tconst env = process.env.CODEMEM_SYNC_KEY_STORE?.toLowerCase();\n\tif (env === \"keychain\") return \"keychain\";\n\treturn \"file\";\n}\n\n// ---------------------------------------------------------------------------\n// CLI availability helpers\n// ---------------------------------------------------------------------------\n\nfunction cliAvailable(cmd: string): boolean {\n\ttry {\n\t\texecFileSync(\"which\", [cmd], { stdio: \"pipe\" });\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Keychain storage (platform-specific)\n// ---------------------------------------------------------------------------\n\nfunction warnKeychainLimitations(): void {\n\tif (process.platform !== \"darwin\") return;\n\tif (keyStoreMode() !== \"keychain\") return;\n\tif (process.env.CODEMEM_SYNC_KEYCHAIN_WARN === \"0\") return;\n\tconsole.warn(\n\t\t\"[codemem] keychain storage on macOS uses the `security` CLI and may expose the key in process arguments.\",\n\t);\n}\n\n/** Store a private key in the OS keychain. Returns true on success. */\nexport function storePrivateKeyKeychain(privateKey: Buffer, deviceId: string): boolean {\n\tif (process.platform === \"linux\") {\n\t\tif (!cliAvailable(\"secret-tool\")) return false;\n\t\ttry {\n\t\t\texecFileSync(\n\t\t\t\t\"secret-tool\",\n\t\t\t\t[\"store\", \"--label\", \"codemem sync key\", \"service\", KEYCHAIN_SERVICE, \"account\", deviceId],\n\t\t\t\t{ input: privateKey, stdio: [\"pipe\", \"pipe\", \"pipe\"] },\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (process.platform === \"darwin\") {\n\t\tif (!cliAvailable(\"security\")) return false;\n\t\ttry {\n\t\t\texecFileSync(\n\t\t\t\t\"security\",\n\t\t\t\t[\n\t\t\t\t\t\"add-generic-password\",\n\t\t\t\t\t\"-a\",\n\t\t\t\t\tdeviceId,\n\t\t\t\t\t\"-s\",\n\t\t\t\t\tKEYCHAIN_SERVICE,\n\t\t\t\t\t\"-w\",\n\t\t\t\t\tprivateKey.toString(\"utf-8\"),\n\t\t\t\t\t\"-U\",\n\t\t\t\t],\n\t\t\t\t{ stdio: [\"pipe\", \"pipe\", \"pipe\"] },\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Load a private key from the OS keychain. Returns null if unavailable. */\nexport function loadPrivateKeyKeychain(deviceId: string): Buffer | null {\n\tif (process.platform === \"linux\") {\n\t\tif (!cliAvailable(\"secret-tool\")) return null;\n\t\ttry {\n\t\t\tconst out = execFileSync(\n\t\t\t\t\"secret-tool\",\n\t\t\t\t[\"lookup\", \"service\", KEYCHAIN_SERVICE, \"account\", deviceId],\n\t\t\t\t{ stdio: [\"pipe\", \"pipe\", \"pipe\"] },\n\t\t\t);\n\t\t\treturn Buffer.from(out);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (process.platform === \"darwin\") {\n\t\tif (!cliAvailable(\"security\")) return null;\n\t\ttry {\n\t\t\tconst out = execFileSync(\n\t\t\t\t\"security\",\n\t\t\t\t[\"find-generic-password\", \"-a\", deviceId, \"-s\", KEYCHAIN_SERVICE, \"-w\"],\n\t\t\t\t{ stdio: [\"pipe\", \"pipe\", \"pipe\"] },\n\t\t\t);\n\t\t\treturn Buffer.from(out);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------\n// Key path resolution\n// ---------------------------------------------------------------------------\n\n/** Resolve private and public key file paths. */\nexport function resolveKeyPaths(keysDir?: string): [string, string] {\n\tconst dir = keysDir ?? defaultKeysDir();\n\treturn [join(dir, PRIVATE_KEY_NAME), join(dir, PUBLIC_KEY_NAME)];\n}\n\n// ---------------------------------------------------------------------------\n// Key file I/O\n// ---------------------------------------------------------------------------\n\n/** Read the public key from disk. Returns null if missing or empty. */\nexport function loadPublicKey(keysDir?: string): string | null {\n\tconst [, publicPath] = resolveKeyPaths(keysDir);\n\tif (!existsSync(publicPath)) return null;\n\tconst content = readFileSync(publicPath, \"utf-8\").trim();\n\treturn content || null;\n}\n\n/**\n * Read the private key from disk with keychain fallback. When dbPath identifies an\n * enrolled device, only a key matching that stored identity is returned.\n */\nexport function loadPrivateKey(\n\tkeysDir?: string,\n\tdbPath?: string,\n\tdeviceId?: string,\n): Buffer | null {\n\tconst storedIdentity = dbPath === undefined ? null : loadStoredDeviceIdentity(dbPath);\n\treturn loadPrivateKeyForIdentity(keysDir, deviceId, storedIdentity, () =>\n\t\tdbPath === undefined && !deviceId ? loadStoredDeviceIdentity() : storedIdentity,\n\t);\n}\n\nfunction loadPrivateKeyForIdentity(\n\tkeysDir: string | undefined,\n\tdeviceId: string | undefined,\n\tstoredIdentity: StoredDeviceIdentity | null,\n\tkeychainIdentity: () => StoredDeviceIdentity | null,\n): Buffer | null {\n\tconst [privatePath] = resolveKeyPaths(keysDir);\n\tconst privateKeyFile = readPrivateKeyFile(privatePath);\n\tconst privateKeyFromFile = isUsableEd25519PrivateKey(privateKeyFile.value)\n\t\t? privateKeyFile.value\n\t\t: null;\n\tif (storedIdentity && deviceId && storedIdentity.deviceId !== deviceId) return null;\n\tif (\n\t\tprivateKeyFromFile &&\n\t\t(!storedIdentity || privateKeyMatchesStoredIdentity(privateKeyFromFile, storedIdentity))\n\t) {\n\t\treturn privateKeyFromFile;\n\t}\n\tif (keyStoreMode() === \"keychain\") {\n\t\tconst identity = keychainIdentity();\n\t\tconst resolvedDeviceId = deviceId ?? identity?.deviceId;\n\t\tif (resolvedDeviceId) {\n\t\t\tconst keychainValue = loadPrivateKeyKeychain(resolvedDeviceId);\n\t\t\tif (\n\t\t\t\tisUsableEd25519PrivateKey(keychainValue) &&\n\t\t\t\t(!identity || privateKeyMatchesStoredIdentity(keychainValue, identity))\n\t\t\t) {\n\t\t\t\treturn keychainValue;\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\ninterface StoredDeviceIdentity {\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n}\n\n/** Read-only counterpart of signing-key selection, using the caller's connection.\n * Derives public bytes from the actual private key; never generates or repairs keys. */\nexport function loadRuntimeSigningPublicKey(\n\tdb: Database,\n\toptions: { deviceId: string; keysDir?: string },\n): string | null {\n\ttry {\n\t\tconst rows = db\n\t\t\t.prepare(\"SELECT device_id, public_key, fingerprint FROM sync_device LIMIT 2\")\n\t\t\t.all() as Array<{ device_id: string; public_key: string; fingerprint: string }>;\n\t\tconst row = rows[0];\n\t\tif (rows.length !== 1 || !row || row.device_id !== options.deviceId) return null;\n\t\tconst identity = {\n\t\t\tdeviceId: row.device_id,\n\t\t\tpublicKey: row.public_key,\n\t\t\tfingerprint: row.fingerprint,\n\t\t};\n\t\tconst privateKey = loadPrivateKeyForIdentity(\n\t\t\toptions.keysDir,\n\t\t\toptions.deviceId,\n\t\t\tidentity,\n\t\t\t() => identity,\n\t\t);\n\t\treturn privateKey ? derivePublicKey(privateKey) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Load the enrolled identity from the database for identity-aware key selection. */\nfunction loadStoredDeviceIdentity(dbPath?: string): StoredDeviceIdentity | null {\n\tconst path = resolveDbPath(dbPath);\n\tif (!existsSync(path)) return null;\n\tconst conn = connectDb(path);\n\ttry {\n\t\tconst d = drizzle(conn, { schema });\n\t\tconst row = d\n\t\t\t.select({\n\t\t\t\tdevice_id: schema.syncDevice.device_id,\n\t\t\t\tpublic_key: schema.syncDevice.public_key,\n\t\t\t\tfingerprint: schema.syncDevice.fingerprint,\n\t\t\t})\n\t\t\t.from(schema.syncDevice)\n\t\t\t.limit(1)\n\t\t\t.get();\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tdeviceId: row.device_id,\n\t\t\tpublicKey: row.public_key,\n\t\t\tfingerprint: row.fingerprint,\n\t\t};\n\t} finally {\n\t\tconn.close();\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Key generation & validation\n// ---------------------------------------------------------------------------\n\nfunction canonicalEd25519PublicKey(publicKey: string): string | null {\n\tconst [keyType, keyData] = publicKey.trim().split(/\\s+/);\n\tif (keyType !== \"ssh-ed25519\" || !keyData) return null;\n\treturn `${keyType} ${keyData}`;\n}\n\nfunction publicKeyLooksValid(publicKey: string): boolean {\n\treturn canonicalEd25519PublicKey(publicKey) !== null;\n}\n\nfunction backupInvalidKeyFile(path: string, stamp: string): void {\n\tif (!existsSync(path)) return;\n\tconst backupPath = join(dirname(path), `${basename(path)}.invalid-${stamp}`);\n\trenameSync(path, backupPath);\n}\n\n/**\n * Generate an Ed25519 keypair using Node's native crypto.\n * Stores private key as PEM (PKCS8), public key as SSH format for compatibility.\n */\nexport function generateKeypair(privatePath: string, publicPath: string): void {\n\tmkdirSync(dirname(privatePath), { recursive: true });\n\tif (existsSync(privatePath) && existsSync(publicPath)) return;\n\n\tif (existsSync(privatePath) && !existsSync(publicPath)) {\n\t\t// Private key exists but public is missing — derive public from private\n\t\ttry {\n\t\t\tconst privKeyObj = loadPrivateKeyObject(privatePath);\n\t\t\tconst pubKeyObj = createPublicKey(privKeyObj);\n\t\t\tconst sshPub = pubKeyObj.export({ type: \"spki\", format: \"der\" });\n\t\t\tconst sshPubStr = derToSshEd25519(sshPub);\n\t\t\tif (sshPubStr && publicKeyLooksValid(sshPubStr)) {\n\t\t\t\twriteFileSync(publicPath, `${sshPubStr}\\n`, { mode: 0o644 });\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Derivation failed — fall through to full regeneration with backup\n\t\t}\n\t\t// Back up the orphaned private key before regenerating\n\t\tconst stamp = new Date().toISOString().replace(/[:.]/g, \"\");\n\t\trenameSync(privatePath, `${privatePath}.orphan-${stamp}`);\n\t}\n\n\tconst { publicKey, privateKey } = generateKeyPairSync(\"ed25519\");\n\n\t// Export private key as PEM (PKCS8)\n\tconst privatePem = privateKey.export({ type: \"pkcs8\", format: \"pem\" }) as string;\n\twriteFileSync(privatePath, privatePem, { mode: 0o600 });\n\n\t// Export public key as SSH wire format: \"ssh-ed25519 <base64>\"\n\tconst pubDer = publicKey.export({ type: \"spki\", format: \"der\" });\n\tconst sshPub = derToSshEd25519(pubDer);\n\tif (!sshPub) {\n\t\tthrow new Error(\"failed to convert public key to SSH format\");\n\t}\n\twriteFileSync(publicPath, `${sshPub}\\n`, { mode: 0o644 });\n}\n\n/**\n * Convert a DER-encoded SPKI Ed25519 public key to SSH wire format.\n * The last 32 bytes of the DER are the raw Ed25519 public key.\n */\nfunction derToSshEd25519(spkiDer: Buffer): string | null {\n\t// Ed25519 SPKI DER is 44 bytes: 12-byte header + 32-byte key\n\tif (spkiDer.length !== 44) return null;\n\tconst rawKey = spkiDer.subarray(spkiDer.length - 32);\n\n\t// SSH wire format: string \"ssh-ed25519\" + string <32-byte key>\n\tconst keyType = Buffer.from(\"ssh-ed25519\");\n\tconst buf = Buffer.alloc(4 + keyType.length + 4 + rawKey.length);\n\tlet offset = 0;\n\tbuf.writeUInt32BE(keyType.length, offset);\n\toffset += 4;\n\tkeyType.copy(buf, offset);\n\toffset += keyType.length;\n\tbuf.writeUInt32BE(rawKey.length, offset);\n\toffset += 4;\n\trawKey.copy(buf, offset);\n\n\treturn `ssh-ed25519 ${buf.toString(\"base64\")}`;\n}\n\n/**\n * Load a private key that may be in OpenSSH format (existing keys) or\n * PKCS8 PEM format (newly generated keys). Node's createPrivateKey\n * handles both transparently.\n */\nfunction loadPrivateKeyObject(privatePath: string): ReturnType<typeof createPrivateKey> {\n\treturn loadPrivateKeyObjectFromBytes(readFileSync(privatePath));\n}\n\nfunction loadPrivateKeyObjectFromBytes(raw: Buffer): ReturnType<typeof createPrivateKey> {\n\t// Try PKCS8 PEM first (our generated format), then OpenSSH\n\ttry {\n\t\treturn createPrivateKey(raw);\n\t} catch {\n\t\treturn createPrivateKey({ key: raw, format: \"pem\", type: \"pkcs8\" });\n\t}\n}\n\nfunction derivePublicKey(privateKey: Buffer): string {\n\tconst privateKeyObject = loadPrivateKeyObjectFromBytes(privateKey);\n\tif (privateKeyObject.asymmetricKeyType !== \"ed25519\") {\n\t\tthrow new Error(\"private key is not Ed25519\");\n\t}\n\tconst publicKeyObject = createPublicKey(privateKeyObject);\n\tconst publicKeyDer = publicKeyObject.export({ type: \"spki\", format: \"der\" });\n\tconst publicKey = derToSshEd25519(publicKeyDer);\n\tif (!publicKey || !publicKeyLooksValid(publicKey)) {\n\t\tthrow new Error(\"failed to derive public key\");\n\t}\n\treturn publicKey;\n}\n\nfunction isUsableEd25519PrivateKey(privateKey: Buffer | null): privateKey is Buffer {\n\tif (!privateKey) return false;\n\ttry {\n\t\tderivePublicKey(privateKey);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\ntype PrivateKeyFileRead =\n\t| { status: \"available\"; value: Buffer }\n\t| { status: \"missing\" | \"unreadable\"; value: null };\n\nfunction readPrivateKeyFile(privatePath: string): PrivateKeyFileRead {\n\ttry {\n\t\tif (!existsSync(privatePath)) return { status: \"missing\", value: null };\n\t\treturn { status: \"available\", value: readFileSync(privatePath) };\n\t} catch {\n\t\treturn { status: \"unreadable\", value: null };\n\t}\n}\n\nfunction privateKeyMatchesStoredIdentity(\n\tprivateKey: Buffer,\n\tidentity: StoredDeviceIdentity,\n): boolean {\n\tconst storedPublicKey = canonicalEd25519PublicKey(identity.publicKey);\n\tif (!storedPublicKey || fingerprintPublicKey(identity.publicKey) !== identity.fingerprint) {\n\t\treturn false;\n\t}\n\ttry {\n\t\treturn canonicalEd25519PublicKey(derivePublicKey(privateKey)) === storedPublicKey;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport type DeviceIdentityErrorCode =\n\t| \"device_identity_private_key_missing\"\n\t| \"device_identity_private_key_invalid\"\n\t| \"device_identity_key_mismatch\";\n\nexport class DeviceIdentityError extends Error {\n\treadonly code: DeviceIdentityErrorCode;\n\n\tconstructor(code: DeviceIdentityErrorCode, detail: string) {\n\t\tsuper(`${code}: ${detail}`);\n\t\tthis.name = \"DeviceIdentityError\";\n\t\tthis.code = code;\n\t}\n}\n\nfunction existingIdentityError(code: DeviceIdentityErrorCode, detail: string): DeviceIdentityError {\n\treturn new DeviceIdentityError(code, detail);\n}\n\n/** Validate that an existing keypair is consistent. */\nexport function validateExistingKeypair(privatePath: string, publicPath: string): boolean {\n\tif (!existsSync(privatePath) || !existsSync(publicPath)) return false;\n\tconst publicKey = readFileSync(publicPath, \"utf-8\").trim();\n\tif (!publicKey || !publicKeyLooksValid(publicKey)) return false;\n\ttry {\n\t\tconst privKeyObj = loadPrivateKeyObject(privatePath);\n\t\tconst pubKeyObj = createPublicKey(privKeyObj);\n\t\tconst pubDer = pubKeyObj.export({ type: \"spki\", format: \"der\" });\n\t\tconst derived = derToSshEd25519(pubDer);\n\t\tif (!derived || !publicKeyLooksValid(derived)) return false;\n\t\t// Auto-fix mismatched public key file\n\t\tif (canonicalEd25519PublicKey(derived) !== canonicalEd25519PublicKey(publicKey)) {\n\t\t\twriteFileSync(publicPath, `${derived}\\n`, \"utf-8\");\n\t\t}\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Main entry: ensure device identity\n// ---------------------------------------------------------------------------\n\nexport interface EnsureDeviceIdentityOptions {\n\tkeysDir?: string;\n\tdeviceId?: string;\n}\n\n/** Device identity ensure boundary; constructors and ordinary memory reads do not associate. */\nfunction adoptPendingCaptureForEnsuredIdentity(\n\tdb: Database,\n\tdeviceId: string,\n\tpublicKey: string,\n): void {\n\tif (!hasPendingLocalCapture(db)) return;\n\tconst configuredDevice = process.env.CODEMEM_DEVICE_ID?.trim();\n\tif (configuredDevice && configuredDevice !== deviceId) return;\n\tconst config = readCodememConfigFile();\n\tlet configuredActor = typeof config.actor_id === \"string\" ? config.actor_id.trim() : undefined;\n\tif (Object.hasOwn(process.env, \"CODEMEM_ACTOR_ID\"))\n\t\tconfiguredActor = process.env.CODEMEM_ACTOR_ID?.trim();\n\ttry {\n\t\tdb.transaction(() =>\n\t\t\tadoptLocalCapture(db, deviceId, {\n\t\t\t\texpectedPublicKey: publicKey,\n\t\t\t\tactorId: configuredActor || `local:${deviceId}`,\n\t\t\t\truntimeDeviceId: deviceId,\n\t\t\t}),\n\t\t).immediate();\n\t} catch (error) {\n\t\t// Only the plain actor conflict is nonfatal; SQLite/key failures propagate.\n\t\tif (\n\t\t\t!(error instanceof Error) ||\n\t\t\terror.constructor !== Error ||\n\t\t\terror.message !== \"device_adoption_actor_conflict\"\n\t\t)\n\t\t\tthrow error;\n\t}\n}\n\n/**\n * Ensure this device has a keypair and a row in the sync_device table.\n *\n * Returns [deviceId, fingerprint]. Creates keys and DB row if missing,\n * validates and repairs if existing.\n */\nexport function ensureDeviceIdentity(\n\tdb: Database,\n\toptions?: EnsureDeviceIdentityOptions,\n): [string, string] {\n\tconst keysDir = options?.keysDir ?? defaultKeysDir();\n\tconst [privatePath, publicPath] = resolveKeyPaths(keysDir);\n\twarnKeychainLimitations();\n\n\t// Check for existing device row\n\tconst d = drizzle(db, { schema });\n\tconst row = deviceRowForEnsure(db);\n\tconst existingDeviceId = row?.device_id ?? \"\";\n\tconst existingPublicKey = row?.public_key ?? \"\";\n\tconst existingFingerprint = row?.fingerprint ?? \"\";\n\n\tif (existingDeviceId) {\n\t\tconst privateKeyFile = readPrivateKeyFile(privatePath);\n\t\tconst validPrivateKeyFromFile = isUsableEd25519PrivateKey(privateKeyFile.value)\n\t\t\t? privateKeyFile.value\n\t\t\t: null;\n\t\tconst storedIdentity: StoredDeviceIdentity = {\n\t\t\tdeviceId: existingDeviceId,\n\t\t\tpublicKey: existingPublicKey,\n\t\t\tfingerprint: existingFingerprint,\n\t\t};\n\n\t\tconst fileMatchesStoredIdentity =\n\t\t\tvalidPrivateKeyFromFile !== null &&\n\t\t\tprivateKeyMatchesStoredIdentity(validPrivateKeyFromFile, storedIdentity);\n\t\tconst privateKeyFromKeychain =\n\t\t\t!fileMatchesStoredIdentity && keyStoreMode() === \"keychain\"\n\t\t\t\t? loadPrivateKeyKeychain(existingDeviceId)\n\t\t\t\t: null;\n\t\tconst validPrivateKeyFromKeychain = isUsableEd25519PrivateKey(privateKeyFromKeychain)\n\t\t\t? privateKeyFromKeychain\n\t\t\t: null;\n\t\tconst keychainMatchesStoredIdentity =\n\t\t\tvalidPrivateKeyFromKeychain !== null &&\n\t\t\tprivateKeyMatchesStoredIdentity(validPrivateKeyFromKeychain, storedIdentity);\n\t\tconst privateKey = fileMatchesStoredIdentity\n\t\t\t? validPrivateKeyFromFile\n\t\t\t: keychainMatchesStoredIdentity\n\t\t\t\t? validPrivateKeyFromKeychain\n\t\t\t\t: null;\n\t\tif (!privateKey) {\n\t\t\tif (validPrivateKeyFromFile || validPrivateKeyFromKeychain) {\n\t\t\t\tthrow existingIdentityError(\n\t\t\t\t\t\"device_identity_key_mismatch\",\n\t\t\t\t\t\"the restored private key does not match the peer identity stored in the database\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow existingIdentityError(\n\t\t\t\tprivateKeyFile.status !== \"missing\" || privateKeyFromKeychain\n\t\t\t\t\t? \"device_identity_private_key_invalid\"\n\t\t\t\t\t: \"device_identity_private_key_missing\",\n\t\t\t\tprivateKeyFile.status !== \"missing\" || privateKeyFromKeychain\n\t\t\t\t\t? \"the restored private key is unreadable or unsupported; restore the original Ed25519 key material\"\n\t\t\t\t\t: \"the database contains an existing peer identity but its private key is unavailable; restore the original key material with the database\",\n\t\t\t);\n\t\t}\n\n\t\tlet derivedPublicKey: string;\n\t\ttry {\n\t\t\tderivedPublicKey = derivePublicKey(privateKey);\n\t\t} catch {\n\t\t\tthrow existingIdentityError(\n\t\t\t\t\"device_identity_private_key_invalid\",\n\t\t\t\t\"the restored private key is unreadable or unsupported; restore the original Ed25519 key material\",\n\t\t\t);\n\t\t}\n\t\tconst storedPublicKey = canonicalEd25519PublicKey(existingPublicKey);\n\t\tif (\n\t\t\t!storedPublicKey ||\n\t\t\tcanonicalEd25519PublicKey(derivedPublicKey) !== storedPublicKey ||\n\t\t\tfingerprintPublicKey(existingPublicKey) !== existingFingerprint\n\t\t) {\n\t\t\tthrow existingIdentityError(\n\t\t\t\t\"device_identity_key_mismatch\",\n\t\t\t\t\"the restored private key does not match the peer identity stored in the database\",\n\t\t\t);\n\t\t}\n\n\t\tconst publicKeyOnDisk = loadPublicKey(keysDir);\n\t\tif (publicKeyOnDisk !== existingPublicKey) {\n\t\t\tmkdirSync(dirname(publicPath), { recursive: true });\n\t\t\twriteFileSync(publicPath, `${existingPublicKey}\\n`, { mode: 0o644 });\n\t\t}\n\t\tif (keyStoreMode() === \"keychain\" && fileMatchesStoredIdentity) {\n\t\t\tstorePrivateKeyKeychain(privateKey, existingDeviceId);\n\t\t}\n\t\tadoptPendingCaptureForEnsuredIdentity(db, existingDeviceId, derivedPublicKey);\n\t\treturn [existingDeviceId, existingFingerprint];\n\t}\n\n\t// Validate or regenerate keys\n\tlet keysReady = existsSync(privatePath) && existsSync(publicPath);\n\tif (keysReady && !validateExistingKeypair(privatePath, publicPath)) {\n\t\tconst stamp = new Date()\n\t\t\t.toISOString()\n\t\t\t.replace(/[-:T.Z]/g, \"\")\n\t\t\t.slice(0, 20);\n\t\tbackupInvalidKeyFile(privatePath, stamp);\n\t\tbackupInvalidKeyFile(publicPath, stamp);\n\t\tkeysReady = false;\n\t}\n\tif (!keysReady) {\n\t\tgenerateKeypair(privatePath, publicPath);\n\t}\n\n\tconst publicKey = readFileSync(publicPath, \"utf-8\").trim();\n\tif (!publicKey) {\n\t\tthrow new Error(\"public key missing\");\n\t}\n\tconst fingerprint = fingerprintPublicKey(publicKey);\n\tconst now = new Date().toISOString();\n\n\t// Insert new device row\n\tconst resolvedDeviceId = options?.deviceId ?? randomUUID();\n\tdb.transaction(() => {\n\t\td.insert(schema.syncDevice)\n\t\t\t.values({ device_id: resolvedDeviceId, public_key: publicKey, fingerprint, created_at: now })\n\t\t\t.run();\n\t\tadoptPendingCaptureForEnsuredIdentity(db, resolvedDeviceId, publicKey);\n\t})();\n\tif (keyStoreMode() === \"keychain\") {\n\t\tconst privateKey = existsSync(privatePath) ? readFileSync(privatePath) : null;\n\t\tif (privateKey) {\n\t\t\tstorePrivateKeyKeychain(privateKey, resolvedDeviceId);\n\t\t}\n\t}\n\treturn [resolvedDeviceId, fingerprint];\n}\n\nfunction deviceRowForEnsure(db: Database) {\n\treturn drizzle(db, { schema })\n\t\t.select({\n\t\t\tdevice_id: schema.syncDevice.device_id,\n\t\t\tpublic_key: schema.syncDevice.public_key,\n\t\t\tfingerprint: schema.syncDevice.fingerprint,\n\t\t})\n\t\t.from(schema.syncDevice)\n\t\t.limit(1)\n\t\t.get();\n}\n","import type { Database } from \"better-sqlite3\";\nimport { AUTH_BROWSER_TXN_SCHEMA_SQL } from \"./coordinator-auth-browser-transaction-contract.js\";\n\nconst TABLE = \"coordinator_auth_browser_transactions\";\nconst REBUILT_TABLE = \"coordinator_auth_browser_transactions_owner_upgrade\";\nconst [tableSql, remainder = \"\"] = AUTH_BROWSER_TXN_SCHEMA_SQL.split(\n\t\"CREATE INDEX IF NOT EXISTS idx_auth_browser_txn_purpose_created\",\n);\nconst indexSql =\n\t`CREATE INDEX IF NOT EXISTS idx_auth_browser_txn_purpose_created${remainder}`.split(\n\t\t\"CREATE TABLE IF NOT EXISTS coordinator_auth_signin_purge_floors\",\n\t)[0];\n\n/** Run only in a transaction: preserves every old column and all uniqueness constraints. */\nexport const AUTH_BROWSER_OWNER_PURPOSE_UPGRADE_SQL = `\n${tableSql?.replace(TABLE, REBUILT_TABLE)}\nINSERT INTO ${REBUILT_TABLE} SELECT * FROM ${TABLE};\nDROP TABLE ${TABLE};\nALTER TABLE ${REBUILT_TABLE} RENAME TO ${TABLE};\n${indexSql}\n`;\n\n/** Atomic upgrade preserves same-table indexes/triggers; foreign dependents can abort it. */\nexport function upgradeAuthBrowserOwnerPurposeSchema(db: Database): void {\n\tconst present = db\n\t\t.prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t.get(TABLE) as { sql: string } | undefined;\n\tif (!present || present.sql.includes(\"'owner_enroll'\")) return;\n\t// Recheck after reserving the write lock in case another connection upgraded first.\n\tdb.transaction(() => {\n\t\tconst table = db\n\t\t\t.prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t\t.get(TABLE) as { sql: string } | undefined;\n\t\tif (!table || table.sql.includes(\"'owner_enroll'\")) return;\n\t\tconst objects = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT name, sql FROM sqlite_master WHERE tbl_name = ? AND type IN ('index','trigger') AND sql IS NOT NULL\",\n\t\t\t)\n\t\t\t.all(TABLE) as { name: string; sql: string }[];\n\t\tdb.exec(AUTH_BROWSER_OWNER_PURPOSE_UPGRADE_SQL);\n\t\tfor (const object of objects) {\n\t\t\tconst recreated = db.prepare(\"SELECT 1 FROM sqlite_master WHERE name = ?\").get(object.name);\n\t\t\tif (!recreated) db.exec(object.sql);\n\t\t}\n\t}).immediate();\n}\n","/** Inert ledger schema: only future verified, atomic enrollment writes may populate it. */\nexport const COORDINATOR_DEVICE_OWNERSHIP_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_device_ownership_bindings (\n device_id TEXT PRIMARY KEY NOT NULL CHECK(\n typeof(device_id) = 'text' AND length(trim(device_id)) > 0 AND instr(device_id, char(0)) = 0),\n key_id TEXT NOT NULL UNIQUE CHECK(\n typeof(key_id) = 'text' AND length(key_id) = 64 AND key_id NOT GLOB '*[^a-f0-9]*'\n AND instr(key_id, char(0)) = 0),\n identity_id TEXT NOT NULL CHECK(\n typeof(identity_id) = 'text' AND length(trim(identity_id)) > 0 AND instr(identity_id, char(0)) = 0),\n coordinator_id TEXT NOT NULL CHECK(\n typeof(coordinator_id) = 'text' AND length(trim(coordinator_id)) > 0 AND instr(coordinator_id, char(0)) = 0),\n binding_id TEXT NOT NULL UNIQUE CHECK(\n typeof(binding_id) = 'text' AND length(trim(binding_id)) > 0 AND instr(binding_id, char(0)) = 0),\n provenance TEXT NOT NULL CHECK(\n typeof(provenance) = 'text' AND provenance IN ('owner_enrollment', 'reviewed_legacy_migration')),\n source_ref TEXT NOT NULL CHECK(\n typeof(source_ref) = 'text' AND length(trim(source_ref)) > 0 AND instr(source_ref, char(0)) = 0),\n bound_at TEXT NOT NULL CHECK(\n typeof(bound_at) = 'text' AND length(trim(bound_at)) > 0 AND instr(bound_at, char(0)) = 0)\n);\n\n-- REPLACE's implicit deletes may skip DELETE triggers when recursive triggers are off.\nCREATE TRIGGER IF NOT EXISTS coordinator_device_ownership_insert_collision\nBEFORE INSERT ON coordinator_device_ownership_bindings\nWHEN EXISTS (\n SELECT 1 FROM coordinator_device_ownership_bindings\n WHERE rowid = NEW.rowid OR device_id = NEW.device_id OR key_id = NEW.key_id\n OR binding_id = NEW.binding_id\n)\nBEGIN\n SELECT RAISE(ABORT, 'device_ownership_collision');\nEND;\n\n-- An automatic rowid reads as -1 before insert; positive rowids keep that from matching a row.\nCREATE TRIGGER IF NOT EXISTS coordinator_device_ownership_rowid\nAFTER INSERT ON coordinator_device_ownership_bindings\nWHEN NEW.rowid < 1\nBEGIN\n SELECT RAISE(ABORT, 'device_ownership_rowid');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_ownership_immutable_update\nBEFORE UPDATE ON coordinator_device_ownership_bindings\nBEGIN\n SELECT RAISE(ABORT, 'device_ownership_immutable');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_ownership_immutable_delete\nBEFORE DELETE ON coordinator_device_ownership_bindings\nBEGIN\n SELECT RAISE(ABORT, 'device_ownership_immutable');\nEND;\n`;\n\n/**\n * Earlier installs have a collision trigger that ignores rowid, so INSERT OR\n * REPLACE with an existing rowid could delete a binding without firing its\n * DELETE trigger. Returns the SQL that replaces it, or null when current.\n */\nexport function upgradeDeviceOwnershipTriggersSql(\n\texistingTriggerSql: string | null,\n): string | null {\n\tif (!existingTriggerSql || existingTriggerSql.includes(\"rowid = NEW.rowid\")) return null;\n\treturn \"DROP TRIGGER IF EXISTS coordinator_device_ownership_insert_collision;\";\n}\n","import type {\n\tCoordinatorAuthHeadlessBrowserStartInput,\n\tCoordinatorAuthLinkHeadlessApprovalInput,\n\tCoordinatorAuthLinkHeadlessCreateInput,\n\tCoordinatorAuthLinkHeadlessFinalizeInput,\n} from \"./coordinator-auth-link-headless.js\";\n/**\n * BetterSqliteCoordinatorStore — SQLite-backed state for the coordinator relay server.\n *\n * The coordinator is a cloud relay that manages group membership, device\n * enrollment, presence, invites, and join requests for sync between devices.\n *\n * This store uses its OWN database (separate from the main codemem DB) and\n * owns its own schema — the TS side creates tables directly.\n *\n * Ported from codemem/coordinator_store.py.\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { mkdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { Database as DatabaseType } from \"better-sqlite3\";\nimport Database from \"better-sqlite3\";\nimport { AccountChangeOperations } from \"./coordinator-account-change.js\";\nimport {\n\tCONNECTION_SCHEMA_PRESENCE_SQL,\n\ttype ConnectionSchemaState,\n\treadConnectionSchemaState,\n} from \"./coordinator-account-connection-schema.js\";\nimport { AccountLinkStatusOperations } from \"./coordinator-account-link-status.js\";\nimport { AccountOwnerTargetOperations } from \"./coordinator-account-owner-target.js\";\nimport {\n\tAUTH_ACCOUNT_PROFILE_SCHEMA_SQL,\n\tAuthAccountProfileOperations,\n\ttype CoordinatorAuthAccountProfileInput,\n} from \"./coordinator-auth-account-profile.js\";\nimport { upgradeAuthBrowserOwnerPurposeSchema } from \"./coordinator-auth-browser-schema-upgrade.js\";\nimport {\n\tAUTH_BROWSER_TXN_SCHEMA_SQL,\n\ttype CoordinatorAuthBrowserConfig,\n\ttype CoordinatorAuthBrowserTransactionConsumeInput,\n\ttype CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\ttype CoordinatorAuthBrowserTransactionRetirementOptions,\n\ttype CoordinatorAuthBrowserTransactionScope,\n\ttype CoordinatorAuthBrowserTransactionStartInput,\n\tCoordinatorAuthBrowserTransactions,\n\ttype CoordinatorAuthLinkBrowserTransactionResolveInput,\n\ttype CoordinatorAuthSigninBrowserTransactionCancelInput,\n} from \"./coordinator-auth-browser-transaction.js\";\nimport {\n\tAUTH_CONTROLLER_ACTIVE_SQL,\n\tAUTH_CONTROLLER_CONFLICT_SQL,\n\tAUTH_CONTROLLER_CURRENT_ENROLLMENT_SQL,\n\tAUTH_CONTROLLER_ENROLLMENT_SQL,\n\tAUTH_CONTROLLER_INSERT_SQL,\n\tAUTH_CONTROLLER_RETRY_ACTIVE_SQL,\n\tAUTH_CONTROLLER_RETRY_ELIGIBLE_SQL,\n\tAUTH_CONTROLLER_REVOKE_SQL,\n\tAUTH_CONTROLLER_SCHEMA_SQL,\n\tauthControllerAuthorityValues,\n\tauthControllerConflictValues,\n\tauthControllerInsertValues,\n\tauthControllerRetryActiveValues,\n\tauthControllerRetryEligibleValues,\n\tauthControllerRetryResult,\n\tauthControllerReviewSql,\n\tauthControllerSubjectOwnerConflictValues,\n\tauthControllerUnavailableResult,\n\ttype CoordinatorAuthControllerAttestation,\n\ttype CoordinatorAuthControllerCreateResult,\n\ttype CoordinatorAuthControllerReviewInput,\n\ttype CoordinatorAuthControllerSubjectOwnerInput,\n\tcaptureAuthControllerReview,\n\tisAuthControllerId,\n\tisAuthControllerUniqueError,\n} from \"./coordinator-auth-controller.js\";\nimport {\n\ttype ControllerHistoryInput,\n\tcaptureControllerHistory,\n} from \"./coordinator-auth-controller-history.js\";\nimport { AUTH_CONTROLLER_SUBJECT_OWNER_CONFLICT_SQL } from \"./coordinator-auth-controller-owner.js\";\nimport { COORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_SQL } from \"./coordinator-auth-device-claim-schema.js\";\nimport {\n\tHEADLESS_LINK_SCHEMA_SQL,\n\treadHeadlessLinkBackend,\n} from \"./coordinator-auth-headless-schema.js\";\nimport {\n\ttype AuthLinkBackend,\n\tAuthLinkOperations,\n\ttype AuthLinkStatement,\n} from \"./coordinator-auth-link.js\";\nimport {\n\tAUTH_LINK_BROWSER_START_COLUMN_SQL,\n\tAUTH_LINK_SCHEMA_SQL,\n\ttype CoordinatorAuthLinkClaimInput,\n\ttype CoordinatorAuthLinkConfig,\n\ttype CoordinatorAuthLinkConfirmInput,\n\ttype CoordinatorAuthLinkCreateInput,\n\ttype CoordinatorAuthLinkFailInput,\n\ttype CoordinatorAuthLinkFinalizeInput,\n\ttype CoordinatorAuthLinkMaintenanceOptions,\n\ttype CoordinatorAuthLinkOidcInput,\n\ttype CoordinatorAuthLinkOptions,\n\ttype CoordinatorAuthLinkRequester,\n} from \"./coordinator-auth-link-contract.js\";\nimport { AUTH_LINK_PROFILE_SCHEMA_SQL } from \"./coordinator-auth-link-profile.js\";\nimport {\n\tAUTH_SCHEMA_READINESS_SQL,\n\tAUTH_SCHEMA_READY_COUNT,\n\tassertCoordinatorAuthSchema,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n\twithCoordinatorAuthSchema,\n} from \"./coordinator-auth-schema.js\";\nimport { AuthSessionOperations } from \"./coordinator-auth-session.js\";\nimport {\n\tAUTH_SESSION_RETENTION_COLUMN_SQL,\n\tAUTH_SESSION_SCHEMA_SQL,\n\ttype CoordinatorAuthAccountSignInInput,\n\ttype CoordinatorAuthBoundLinkSessionRedeemInput,\n\ttype CoordinatorAuthLinkSessionRedeemInput,\n\ttype CoordinatorAuthSessionPurgeOptions,\n\ttype CoordinatorAuthSessionScope,\n} from \"./coordinator-auth-session-contract.js\";\nimport {\n\tBOOTSTRAP_AUTHORIZATION_SOURCE_SQL,\n\ttype BootstrapAuthorizationRow,\n\tbootstrapAuthorizationDecision,\n\tbootstrapAuthorizationResult,\n\tbootstrapAuthorizationSourceError,\n\tcaptureBootstrapAuthorizationInput,\n\trejectBootstrapAuthorization,\n} from \"./coordinator-bootstrap-grant-authorization.js\";\nimport {\n\tBOOTSTRAP_PARTICIPANT_SOURCE_SQL,\n\tBOOTSTRAP_PARTICIPANTS_REVOKED_SQL,\n\tBOOTSTRAP_RAW_INSERT_SQL,\n\ttype BootstrapParticipantSource,\n\tbootstrapRawInsertValues,\n\tcaptureBootstrapParticipantSource,\n} from \"./coordinator-bootstrap-grant-issuance.js\";\nimport {\n\tCOORDINATOR_DEVICE_OWNERSHIP_SCHEMA_SQL,\n\tupgradeDeviceOwnershipTriggersSql,\n} from \"./coordinator-device-ownership-schema.js\";\nimport {\n\tCOORDINATOR_DEVICE_REBIND_SCHEMA_SQL,\n\treadDeviceRebindBackend,\n\trebindAttemptsNeedSelfBindRebuild,\n\trebuildRebindAttemptsForSelfBindSql,\n\tupgradePreReleaseRebindAttemptsSql,\n} from \"./coordinator-device-rebind-schema.js\";\nimport {\n\ttype CoordinatorCreateDeviceRevocationInput,\n\ttype CoordinatorListDeviceRevocationsInput,\n\ttype CoordinatorRecordAuthorizedNonceInput,\n\tDEVICE_REVOCATION_SCHEMA_SQL,\n\tDEVICE_REVOCATION_SUBJECT_EXISTS_SQL,\n\tDeviceRevocationOperations,\n} from \"./coordinator-device-revocation.js\";\nimport { parseSshEd25519PublicKeyForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tENROLLMENT_OWNERSHIP_COLUMNS,\n\twithEnrollmentOwnership,\n} from \"./coordinator-enrollment-ownership.js\";\nimport {\n\ttype CoordinatorIdentityGroupGrant,\n\ttype CoordinatorIdentityGroupGrantIssueInput,\n\ttype CoordinatorIdentityGroupGrantIssueResult,\n\ttype CoordinatorIdentityGroupGrantRevokeInput,\n\ttype CoordinatorIdentityGroupGrantScope,\n\tcaptureIdentityGroupGrantInput,\n\tIDENTITY_GROUP_GRANT_INSERT_SQL,\n\tIDENTITY_GROUP_GRANT_LIST_SQL,\n\tIDENTITY_GROUP_GRANT_RETRY_SQL,\n\tIDENTITY_GROUP_GRANT_REVOKE_SQL,\n\tIDENTITY_GROUP_GRANT_SCHEMA_SQL,\n\tIDENTITY_GROUP_GRANT_SOURCE_SQL,\n} from \"./coordinator-identity-group-grant.js\";\nimport { joinReviewGuardEvidence } from \"./coordinator-join-review-guards.js\";\nimport {\n\tcaptureLegacyCompletionOwnerProof,\n\tlegacyCompletionOwnerProofSql,\n} from \"./coordinator-legacy-completion-owner-proof.js\";\nimport {\n\tassertLegacyDeviceScope,\n\tcaptureLegacyEnrollment,\n\tcaptureLegacyEnrollmentPublicKey,\n\tcaptureLegacyProjectInviteInput,\n\tDEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL,\n\tLEGACY_DEVICE_DENIAL_SQL,\n\tLEGACY_ENROLLMENT_DENIAL_SQL,\n\tLEGACY_ENROLLMENT_WRITE_SQL,\n\tlegacyDeviceAuthorizationFailure,\n\tlegacyDeviceDenial,\n\tlegacyDeviceWriteChanges,\n\tlegacyProjectInviteOwnershipEvidence,\n} from \"./coordinator-legacy-device-ownership.js\";\nimport {\n\tLEGACY_OWNER_INPUT_SQL,\n\tLEGACY_OWNER_KEYS_SQL,\n\tLEGACY_OWNER_SOURCE_CURRENT_SQL,\n\tlegacyCompletionWriteResult,\n\tlegacyOwnerKeyMetadata,\n} from \"./coordinator-legacy-owner-compatibility.js\";\nimport type {\n\tCoordinatorLegacyTeamCompletionManifestV1,\n\tCoordinatorLegacyTeamCompletionRecord,\n\tCoordinatorLegacyTeamCompletionScopeBinding,\n\tCoordinatorLegacyTeamCompletionWriteResult,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS,\n\tCoordinatorLegacyTeamCompletionConflictError,\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef,\n\tnormalizeCoordinatorLegacyTeamCompletionGroupIds,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n\trequireCoordinatorLegacyTeamCompletionScopeBindings,\n\trequireCoordinatorLegacyTeamCompletionTeamBinding,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tassertMatchingMembershipEffectReceipt,\n\ttype CoordinatorMembershipEffectReceipt,\n\tCoordinatorMembershipError,\n\tgrantMembershipEffectRequestJson,\n\tmembershipFromEffectReceipt,\n\tnormalizeMembershipEffectId,\n\trevokeMembershipEffectRequestJson,\n} from \"./coordinator-membership-effects.js\";\nimport { COORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL } from \"./coordinator-owner-enrollment-schema.js\";\nimport {\n\ttype NegativeOwnerConsistency,\n\tprepareNegativeOwnerConsistency,\n\twithNegativeOwnerConsistency,\n} from \"./coordinator-owner-negative-consistency.js\";\nimport { OwnerResolutionReviewOperations } from \"./coordinator-owner-resolution-review.js\";\nimport {\n\tCAPTURE_PEER_ENROLLMENTS_SQL,\n\ttype CapturedPeerEnrollment,\n\tcapturePeerEnrollments,\n\tREAD_CURRENT_PEERS_SQL,\n\trequirePeerDiscoveryRows,\n} from \"./coordinator-peer-discovery.js\";\nimport { projectInviteGuardEvidence } from \"./coordinator-project-invite-guards.js\";\nimport {\n\tprepareRecipientOwnerConsistency,\n\trecipientOwnerWriteSql,\n\tvalidateRecipientOwnerInput,\n} from \"./coordinator-recipient-owner-consistency.js\";\nimport { ResolvedAccountOwnerStatusOperations } from \"./coordinator-resolved-account-owner-status.js\";\nimport {\n\ttype CapturedScopeMember,\n\tcaptureScopeAuthorizationInput,\n\tENROLLMENT_FIELDS,\n\tisCurrentScopeMember,\n\tMEMBERSHIP_FIELDS,\n\tparseScopeAuthorizationMembers,\n\tREAD_SCOPE_AUTHORIZATION_SQL,\n\trequireScopeAuthorizationRecord,\n\tSCOPE_FIELDS,\n\tscopeAuthorizationError,\n} from \"./coordinator-scope-authorization.js\";\nimport type {\n\tCoordinatorBootstrapGrant,\n\tCoordinatorBootstrapGrantAuthorizationInput,\n\tCoordinatorBootstrapGrantAuthorizationResult,\n\tCoordinatorConsumeProjectInviteInput,\n\tCoordinatorConsumeRecipientInviteInput,\n\tCoordinatorCreateBootstrapGrantInput,\n\tCoordinatorCreateInviteInput,\n\tCoordinatorCreateJoinRequestInput,\n\tCoordinatorCreateReciprocalApprovalInput,\n\tCoordinatorCreateScopeInput,\n\tCoordinatorEnrollDeviceInput,\n\tCoordinatorEnrollment,\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorGroup,\n\tCoordinatorInspectRecipientInviteInput,\n\tCoordinatorInvite,\n\tCoordinatorJoinRequest,\n\tCoordinatorJoinRequestReviewResult,\n\tCoordinatorListReciprocalApprovalsInput,\n\tCoordinatorListScopeMembershipAuditInput,\n\tCoordinatorListScopesInput,\n\tCoordinatorPeerRecord,\n\tCoordinatorPresenceRecord,\n\tCoordinatorProjectInviteAcceptance,\n\tCoordinatorRecipientInviteAcceptance,\n\tCoordinatorRecipientInviteInspection,\n\tCoordinatorReciprocalApproval,\n\tCoordinatorReviewJoinRequestInput,\n\tCoordinatorRevokeScopeMembershipInput,\n\tCoordinatorScope,\n\tCoordinatorScopeAuthorizationInput,\n\tCoordinatorScopeAuthorizationResult,\n\tCoordinatorScopeMembership,\n\tCoordinatorScopeMembershipAuditEvent,\n\tCoordinatorStore,\n\tCoordinatorUpdateScopeInput,\n\tCoordinatorUpsertPresenceInput,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tCoordinatorReciprocalApprovalRequestChangedError,\n\tnormalizeInviteExpiresAt,\n\trecipientInviteAuthoritativeIdentityId,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tclean,\n\tinspectCoordinatorRecipientInvite as inspectInvite,\n\tmergeCoordinatorAddresses,\n\tnormalizeCoordinatorAuditLimit,\n\tnormalizeCoordinatorBootstrapGrantInput,\n\tnormalizeCoordinatorBootstrapGrantRequest,\n\tnormalizeCoordinatorCreateScopeInput,\n\tnormalizeCoordinatorGrantScopeMembershipInput,\n\tnormalizeCoordinatorInviteMetadata,\n\tnormalizeCoordinatorUpdateScopeInput,\n\tnormalizeEpoch,\n} from \"./coordinator-store-input-rules.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\nexport const DEFAULT_COORDINATOR_DB_PATH = join(homedir(), \".codemem\", \"coordinator.sqlite\");\n\nfunction nowISO(): string {\n\treturn new Date().toISOString();\n}\n\nfunction tokenUrlSafe(bytes: number): string {\n\treturn randomBytes(bytes).toString(\"base64url\").replace(/=+$/, \"\");\n}\n\nfunction tokenDigest(token: string): string {\n\treturn createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\nconst INVITE_COLUMNS = `invite_id, group_id, token, policy, expires_at, created_at, created_by,\n\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest, token_digest,\n\tinviter_actor_id, inviter_display_name, inviter_device_id, pending_person_id,\n\tproject_summaries_json, project_intent_json, consumed_at, bound_device_id, bound_public_key, bound_fingerprint,\n\trecipient_actor_id, recipient_display_name, recipient_device_display_name, trust_state,\n\tbootstrap_grant_id, invite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\treviewed_preview_digest, reviewed_intent_json`;\n\nconst ENROLLMENT_COLUMNS =\n\t\"group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\";\n\nconst ENROLLMENT_PRESENCE_COLUMNS = `enrolled_devices.group_id, enrolled_devices.device_id,\n\tenrolled_devices.public_key, enrolled_devices.fingerprint, enrolled_devices.identity_id,\n\tenrolled_devices.display_name, enrolled_devices.enabled, enrolled_devices.created_at,\n\tpresence_records.expires_at AS presence_expires_at,\n\tpresence_records.capabilities_json AS presence_capabilities_json`;\n\nfunction rowToRecord<T>(row: unknown): T {\n\tif (row == null) throw new Error(\"expected row\");\n\treturn row as T;\n}\n\nfunction rowToEnrollmentWithPresence(row: unknown): CoordinatorEnrollment {\n\tconst record = rowToRecord<Record<string, unknown>>(row);\n\tconst {\n\t\tpresence_capabilities_json: capabilitiesJson,\n\t\tpresence_expires_at: expiresAt,\n\t\t...base\n\t} = record;\n\tif (typeof expiresAt !== \"string\" || typeof capabilitiesJson !== \"string\") {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n\ttry {\n\t\tconst capabilities = JSON.parse(capabilitiesJson) as unknown;\n\t\tif (!capabilities || typeof capabilities !== \"object\" || Array.isArray(capabilities)) {\n\t\t\treturn base as unknown as CoordinatorEnrollment;\n\t\t}\n\t\tconst capabilityRecord = capabilities as Record<string, unknown>;\n\t\treturn {\n\t\t\t...(base as unknown as CoordinatorEnrollment),\n\t\t\tpresence_expires_at: expiresAt,\n\t\t\tpresence_capabilities: {\n\t\t\t\tsync_capability: capabilityRecord.sync_capability,\n\t\t\t\tsync_features: capabilityRecord.sync_features,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n}\n\nfunction insertMembershipAuditSync(\n\tdb: DatabaseType,\n\tinput: {\n\t\teffectId: string;\n\t\taction: \"grant\" | \"revoke\";\n\t\tcurrent: CoordinatorScopeMembership;\n\t\tprevious: CoordinatorScopeMembership | null;\n\t\tactorType: string | null;\n\t\tactorId: string | null;\n\t\tcreatedAt: string;\n\t},\n): void {\n\tdb.prepare(`INSERT INTO coordinator_scope_membership_audit_log(\n\t\t\teffect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(\n\t\tinput.effectId,\n\t\tinput.action,\n\t\tinput.current.scope_id,\n\t\tinput.current.device_id,\n\t\tinput.current.role,\n\t\tinput.current.status,\n\t\tinput.current.membership_epoch,\n\t\tinput.previous?.role ?? null,\n\t\tinput.previous?.status ?? null,\n\t\tinput.previous?.membership_epoch ?? null,\n\t\tinput.current.coordinator_id,\n\t\tinput.current.group_id,\n\t\tinput.actorType,\n\t\tinput.actorId,\n\t\tinput.current.manifest_hash,\n\t\tinput.createdAt,\n\t);\n}\n\nfunction getMembershipEffectReceiptSync(\n\tdb: DatabaseType,\n\teffectId: string,\n): CoordinatorMembershipEffectReceipt | null {\n\tconst row = db\n\t\t.prepare(`SELECT effect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?`)\n\t\t.get(effectId);\n\treturn row ? rowToRecord<CoordinatorMembershipEffectReceipt>(row) : null;\n}\n\nfunction insertMembershipEffectReceiptSync(\n\tdb: DatabaseType,\n\tinput: {\n\t\teffectId: string;\n\t\taction: \"grant\" | \"revoke\";\n\t\trequestJson: string;\n\t\tapplied: boolean;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tmembership: CoordinatorScopeMembership | null;\n\t\tcreatedAt: string;\n\t},\n): void {\n\tdb.prepare(`INSERT INTO coordinator_scope_membership_effect_receipts(\n\t\teffect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(\n\t\tinput.effectId,\n\t\tinput.action,\n\t\tinput.requestJson,\n\t\tinput.applied ? 1 : 0,\n\t\tinput.scopeId,\n\t\tinput.deviceId,\n\t\tinput.membership?.role ?? null,\n\t\tinput.membership?.status ?? null,\n\t\tinput.membership?.membership_epoch ?? null,\n\t\tinput.membership?.coordinator_id ?? null,\n\t\tinput.membership?.group_id ?? null,\n\t\tinput.membership?.manifest_issuer_device_id ?? null,\n\t\tinput.membership?.manifest_hash ?? null,\n\t\tinput.membership?.signed_manifest_json ?? null,\n\t\tinput.membership?.updated_at ?? null,\n\t\tinput.createdAt,\n\t);\n}\n\nfunction assertScopeMembershipDeviceEnrolled(\n\tdb: DatabaseType,\n\tgroupId: string | null,\n\tdeviceId: string,\n): void {\n\tif (!groupId) return;\n\tconst row = db\n\t\t.prepare(\"SELECT 1 FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1\")\n\t\t.get(groupId, deviceId);\n\tif (!row) {\n\t\tthrow new CoordinatorMembershipError(\"device_not_enrolled\");\n\t}\n}\n\nfunction insertBootstrapGrantSync(\n\tdb: DatabaseType,\n\topts: CoordinatorCreateBootstrapGrantInput,\n\trequestedGrantId?: string,\n\trequestedCreatedAt?: string,\n\tauthorization?: { sql: string; values: (string | null)[]; assertAuthorized: () => void },\n): CoordinatorBootstrapGrant {\n\tconst normalized = normalizeCoordinatorBootstrapGrantInput(opts);\n\tconst grantId = requestedGrantId ?? tokenUrlSafe(12);\n\tconst createdAt = requestedCreatedAt ?? nowISO();\n\tconst result = db\n\t\t.prepare(`INSERT INTO coordinator_bootstrap_grants(\n\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t) SELECT ?, ?, ?, ?, ?, ?, ?, NULL WHERE ${authorization?.sql ?? \"1\"}`)\n\t\t.run(\n\t\t\tgrantId,\n\t\t\tnormalized.groupId,\n\t\t\tnormalized.seedDeviceId,\n\t\t\tnormalized.workerDeviceId,\n\t\t\tnormalized.expiresAt,\n\t\t\tcreatedAt,\n\t\t\tnormalized.createdBy,\n\t\t\t...(authorization?.values ?? []),\n\t\t);\n\tif (authorization && result.changes === 0) {\n\t\tauthorization.assertAuthorized();\n\t\tthrow new Error(\"invite_acceptance_incomplete\");\n\t}\n\tconst row = db\n\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t.get(grantId);\n\treturn rowToRecord<CoordinatorBootstrapGrant>(row);\n}\n\nfunction upgradeAuthSessionRetentionSchema(db: DatabaseType): void {\n\tconst present = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM pragma_table_info('coordinator_auth_session_receipts') WHERE name = 'purge_eligible'\",\n\t\t)\n\t\t.get();\n\tif (present) return;\n\tdb.transaction(() => {\n\t\tconst columns = db.prepare(\"PRAGMA table_info(coordinator_auth_session_receipts)\").all() as {\n\t\t\tname: string;\n\t\t}[];\n\t\tif (columns.length === 0 || columns.some((column) => column.name === \"purge_eligible\")) return;\n\t\tdb.exec(\n\t\t\t`ALTER TABLE coordinator_auth_session_receipts ADD COLUMN ${AUTH_SESSION_RETENTION_COLUMN_SQL}`,\n\t\t);\n\t}).immediate();\n}\n\nfunction upgradeAuthLinkBrowserStartSchema(db: DatabaseType): void {\n\tconst present = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM pragma_table_info('coordinator_auth_link_attempts') WHERE name = 'browser_start_hash'\",\n\t\t)\n\t\t.get();\n\tif (present) return;\n\tdb.transaction(() => {\n\t\tconst columns = db.prepare(\"PRAGMA table_info(coordinator_auth_link_attempts)\").all() as {\n\t\t\tname: string;\n\t\t}[];\n\t\tif (columns.length === 0 || columns.some((column) => column.name === \"browser_start_hash\"))\n\t\t\treturn;\n\t\tdb.exec(\n\t\t\t`ALTER TABLE coordinator_auth_link_attempts ADD COLUMN ${AUTH_LINK_BROWSER_START_COLUMN_SQL}`,\n\t\t);\n\t}).immediate();\n}\n\nfunction initializeDeviceLedgerSchemas(db: DatabaseType): void {\n\tupgradeDeviceOwnershipTriggers(db);\n\tdb.exec(COORDINATOR_DEVICE_OWNERSHIP_SCHEMA_SQL);\n\tdb.exec(DEVICE_REVOCATION_SCHEMA_SQL);\n\t// Optional owner storage never forces an upgrade of a legacy/direct coordinator.\n\t// Do not install new-column triggers on an existing pre-0034 table either.\n\tconst ownerTable = db\n\t\t.prepare(\n\t\t\t\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'coordinator_owner_enrollment_attempts'\",\n\t\t)\n\t\t.get();\n\tif (!ownerTable) db.exec(COORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL);\n\t// Additive rebind storage (ADR 0005 Section 8). Only an empty pre-release\n\t// attempts table is recreated; see upgradePreReleaseRebindAttemptsSql.\n\tupgradePreReleaseRebindAttempts(db);\n\tupgradeRebindAttemptsForSelfBind(db);\n\tupgradeRebindStartAuthority(db);\n\tdb.exec(COORDINATOR_DEVICE_REBIND_SCHEMA_SQL);\n}\n\nfunction upgradeRebindStartAuthority(db: DatabaseType): void {\n\tconst needed = () => {\n\t\tconst columns = db.prepare(\"PRAGMA table_info(coordinator_device_rebind_attempts)\").all() as {\n\t\t\tname: string;\n\t\t}[];\n\t\treturn columns.length > 0 && !columns.some((column) => column.name === \"start_authority_json\");\n\t};\n\tif (!needed()) return;\n\tdb.transaction(() => {\n\t\tif (!needed()) return;\n\t\tdb.exec(\n\t\t\t\"ALTER TABLE coordinator_device_rebind_attempts ADD COLUMN start_authority_json TEXT CHECK (start_authority_json IS NULL OR json_valid(start_authority_json))\",\n\t\t);\n\t\tdb.exec(\"DROP TRIGGER IF EXISTS coordinator_device_rebind_attempt_pins\");\n\t\tdb.exec(COORDINATOR_DEVICE_REBIND_SCHEMA_SQL);\n\t}).immediate();\n}\n\nconst REBIND_ATTEMPTS_SQL =\n\t\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'coordinator_device_rebind_attempts'\";\n\nconst OWNERSHIP_COLLISION_TRIGGER_SQL =\n\t\"SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = 'coordinator_device_ownership_insert_collision'\";\n\n/** Reads first; replaces an outdated trigger and recreates it in one transaction. */\nfunction upgradeDeviceOwnershipTriggers(db: DatabaseType): void {\n\tconst plan = () =>\n\t\tupgradeDeviceOwnershipTriggersSql(\n\t\t\t(db.prepare(OWNERSHIP_COLLISION_TRIGGER_SQL).pluck().get() as string | undefined) ?? null,\n\t\t);\n\tif (!plan()) return;\n\tdb.transaction(() => {\n\t\tconst upgrade = plan();\n\t\tif (!upgrade) return;\n\t\tdb.exec(upgrade);\n\t\tdb.exec(COORDINATOR_DEVICE_OWNERSHIP_SCHEMA_SQL);\n\t}).immediate();\n}\n\n/** Reads first; rebuilds an attempts table that forbids self-binds, keeping its rows. */\nfunction upgradeRebindAttemptsForSelfBind(db: DatabaseType): void {\n\tconst needed = () =>\n\t\trebindAttemptsNeedSelfBindRebuild(\n\t\t\t(db.prepare(REBIND_ATTEMPTS_SQL).pluck().get() as string | undefined) ?? null,\n\t\t);\n\tif (!needed()) return;\n\tdb.transaction(() => {\n\t\tif (needed()) db.exec(rebuildRebindAttemptsForSelfBindSql());\n\t}).immediate();\n}\n\n/** Reads first, so opening an up-to-date database takes no write lock. */\nfunction upgradePreReleaseRebindAttempts(db: DatabaseType): void {\n\tconst plan = () => {\n\t\tconst existing = db.prepare(REBIND_ATTEMPTS_SQL).pluck().get() as string | undefined;\n\t\tif (!existing) return null;\n\t\tconst rows = db\n\t\t\t.prepare(\"SELECT count(*) FROM coordinator_device_rebind_attempts\")\n\t\t\t.pluck()\n\t\t\t.get() as number;\n\t\treturn upgradePreReleaseRebindAttemptsSql(existing, rows);\n\t};\n\tif (!plan()) return;\n\tdb.transaction(() => {\n\t\tconst upgrade = plan();\n\t\tif (upgrade) db.exec(upgrade);\n\t}).immediate();\n}\n\nfunction initializeAuthBrowserSchema(db: DatabaseType): void {\n\tupgradeAuthBrowserOwnerPurposeSchema(db);\n\tdb.exec(AUTH_BROWSER_TXN_SCHEMA_SQL);\n}\n\nfunction initializeAuthLinkSchema(db: DatabaseType): void {\n\tconst ready = db.prepare(AUTH_SCHEMA_READINESS_SQL).get() as { ready: number };\n\tif (ready.ready === AUTH_SCHEMA_READY_COUNT) return;\n\tconst existing = db\n\t\t.prepare(\n\t\t\t\"SELECT sql FROM sqlite_master WHERE type='table' AND name='coordinator_auth_link_attempts'\",\n\t\t)\n\t\t.get() as { sql: string } | undefined;\n\tif (existing && !existing.sql.includes(\"authority_kind\")) {\n\t\tupgradeAuthLinkBrowserStartSchema(db);\n\t\tdb.exec(AUTH_LINK_SCHEMA_SQL);\n\t\treturn;\n\t}\n\tdb.transaction(() => {\n\t\tupgradeAuthLinkBrowserStartSchema(db);\n\t\tdb.exec(AUTH_LINK_SCHEMA_SQL);\n\t\tconst explicit = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM pragma_table_info('coordinator_auth_link_attempts') WHERE name = 'authority_kind'\",\n\t\t\t)\n\t\t\t.get();\n\t\tif (explicit) db.exec(COORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_SQL);\n\t}).immediate();\n}\n\nfunction initializeOptionalAuthSchema(db: DatabaseType): void {\n\tif ((db.prepare(CONNECTION_SCHEMA_PRESENCE_SQL).get() as { present: number }).present) return;\n\tdb.exec(AUTH_CONTROLLER_SCHEMA_SQL);\n\tinitializeAuthLinkSchema(db);\n\tupgradeAuthSessionRetentionSchema(db);\n\tdb.exec(AUTH_SESSION_SCHEMA_SQL);\n\tdb.exec(AUTH_ACCOUNT_PROFILE_SCHEMA_SQL);\n\tdb.exec(AUTH_LINK_PROFILE_SCHEMA_SQL);\n\tinitializeAuthBrowserSchema(db);\n}\nfunction initializeSchema(db: DatabaseType): void {\n\tdb.exec(IDENTITY_GROUP_GRANT_SCHEMA_SQL);\n\tinitializeDeviceLedgerSchemas(db);\n\tinitializeOptionalAuthSchema(db);\n\t// Additive headless-link tables; independent of the optional auth schema state.\n\tdb.exec(HEADLESS_LINK_SCHEMA_SQL);\n\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS groups (\n\t\t\tgroup_id TEXT PRIMARY KEY,\n\t\t\tdisplay_name TEXT,\n\t\t\tarchived_at TEXT,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS enrolled_devices (\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\tpublic_key TEXT NOT NULL,\n\t\t\tfingerprint TEXT NOT NULL,\n\t\t\tidentity_id TEXT,\n\t\t\tdisplay_name TEXT,\n\t\t\tenabled INTEGER NOT NULL DEFAULT 1,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (group_id, device_id)\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS presence_records (\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\taddresses_json TEXT NOT NULL,\n\t\t\tlast_seen_at TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tcapabilities_json TEXT NOT NULL DEFAULT '{}',\n\t\t\tPRIMARY KEY (group_id, device_id)\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS request_nonces (\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\tnonce TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (device_id, nonce)\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_request_nonces_created_at\n\t\t\tON request_nonces(created_at);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_invites (\n\t\t\tinvite_id TEXT PRIMARY KEY,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\ttoken TEXT NOT NULL UNIQUE,\n\t\t\tpolicy TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tcreated_by TEXT,\n\t\t\tteam_name_snapshot TEXT,\n\t\t\trevoked_at TEXT,\n\t\t\toperation_id TEXT,\n\t\t\treviewed_project_set_digest TEXT,\n\t\t\ttoken_digest TEXT,\n\t\t\tinviter_actor_id TEXT,\n\t\t\tinviter_display_name TEXT,\n\t\t\tinviter_device_id TEXT,\n\t\t\tpending_person_id TEXT,\n\t\t\tproject_summaries_json TEXT,\n\t\t\tproject_intent_json TEXT,\n\t\t\tconsumed_at TEXT,\n\t\t\tbound_device_id TEXT,\n\t\t\tbound_public_key TEXT,\n\t\t\tbound_fingerprint TEXT,\n\t\t\trecipient_actor_id TEXT,\n\t\t\trecipient_display_name TEXT,\n\t\t\trecipient_device_display_name TEXT,\n\t\t\ttrust_state TEXT,\n\t\t\tbootstrap_grant_id TEXT,\n\t\t\tinvite_kind TEXT,\n\t\t\tpolicy_team_id TEXT,\n\t\t\ttarget_identity_id TEXT,\n\t\t\tassigned_identity_id TEXT,\n\t\t\treviewed_preview_digest TEXT,\n\t\t\treviewed_intent_json TEXT\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_join_requests (\n\t\t\trequest_id TEXT PRIMARY KEY,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\tpublic_key TEXT NOT NULL,\n\t\t\tfingerprint TEXT NOT NULL,\n\t\t\tdisplay_name TEXT,\n\t\t\ttoken TEXT NOT NULL,\n\t\t\tstatus TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\treviewed_at TEXT,\n\t\t\treviewed_by TEXT\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_reciprocal_approvals (\n\t\t\trequest_id TEXT PRIMARY KEY,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\trequesting_device_id TEXT NOT NULL,\n\t\t\trequested_device_id TEXT NOT NULL,\n\t\t\tstatus TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tresolved_at TEXT\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_bootstrap_grants (\n\t\t\tgrant_id TEXT PRIMARY KEY,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tseed_device_id TEXT NOT NULL,\n\t\t\tworker_device_id TEXT NOT NULL,\n\t\t\texpires_at TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tcreated_by TEXT,\n\t\t\trevoked_at TEXT\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_scopes (\n\t\t\tscope_id TEXT PRIMARY KEY,\n\t\t\tlabel TEXT NOT NULL,\n\t\t\tkind TEXT NOT NULL DEFAULT 'user',\n\t\t\tauthority_type TEXT NOT NULL DEFAULT 'coordinator',\n\t\t\tcoordinator_id TEXT,\n\t\t\tgroup_id TEXT,\n\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\tmembership_epoch INTEGER NOT NULL DEFAULT 0,\n\t\t\tmanifest_hash TEXT,\n\t\t\tstatus TEXT NOT NULL DEFAULT 'active',\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tupdated_at TEXT NOT NULL\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scopes_status\n\t\t\tON coordinator_scopes(status);\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scopes_authority_group\n\t\t\tON coordinator_scopes(coordinator_id, group_id);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_scope_memberships (\n\t\t\tscope_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\trole TEXT NOT NULL DEFAULT 'member',\n\t\t\tstatus TEXT NOT NULL DEFAULT 'active',\n\t\t\tmembership_epoch INTEGER NOT NULL DEFAULT 0,\n\t\t\tcoordinator_id TEXT,\n\t\t\tgroup_id TEXT,\n\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\tmanifest_hash TEXT,\n\t\t\tsigned_manifest_json TEXT,\n\t\t\tupdated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (scope_id, device_id)\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_memberships_device_status\n\t\t\tON coordinator_scope_memberships(device_id, status);\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_memberships_scope_status\n\t\t\tON coordinator_scope_memberships(scope_id, status);\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_memberships_authority_group\n\t\t\tON coordinator_scope_memberships(coordinator_id, group_id);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_scope_membership_audit_log (\n\t\t\tevent_id INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\teffect_id TEXT,\n\t\t\taction TEXT NOT NULL,\n\t\t\tscope_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\trole TEXT,\n\t\t\tstatus TEXT NOT NULL,\n\t\t\tmembership_epoch INTEGER NOT NULL,\n\t\t\tprevious_role TEXT,\n\t\t\tprevious_status TEXT,\n\t\t\tprevious_membership_epoch INTEGER,\n\t\t\tcoordinator_id TEXT,\n\t\t\tgroup_id TEXT,\n\t\t\tactor_type TEXT,\n\t\t\tactor_id TEXT,\n\t\t\tmanifest_hash TEXT,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_membership_audit_scope_created\n\t\t\tON coordinator_scope_membership_audit_log(scope_id, created_at, event_id);\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_scope_membership_audit_device_created\n\t\t\tON coordinator_scope_membership_audit_log(device_id, created_at, event_id);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_scope_membership_effect_receipts (\n\t\t\teffect_id TEXT PRIMARY KEY,\n\t\t\taction TEXT NOT NULL CHECK (action IN ('grant', 'revoke')),\n\t\t\trequest_json TEXT NOT NULL,\n\t\t\toutcome_applied INTEGER NOT NULL CHECK (outcome_applied IN (0, 1)),\n\t\t\tscope_id TEXT NOT NULL,\n\t\t\tdevice_id TEXT NOT NULL,\n\t\t\trole TEXT,\n\t\t\tstatus TEXT,\n\t\t\tmembership_epoch INTEGER,\n\t\t\tcoordinator_id TEXT,\n\t\t\tgroup_id TEXT,\n\t\t\tmanifest_issuer_device_id TEXT,\n\t\t\tmanifest_hash TEXT,\n\t\t\tsigned_manifest_json TEXT,\n\t\t\tupdated_at TEXT,\n\t\t\tcreated_at TEXT NOT NULL\n\t\t);\n\n\t\tCREATE TABLE IF NOT EXISTS coordinator_legacy_team_completions (\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tcandidate_ref TEXT NOT NULL,\n\t\t\tmanifest_version INTEGER NOT NULL CHECK (manifest_version = 1),\n\t\t\tmanifest_json TEXT NOT NULL,\n\t\t\tcompleted_at TEXT NOT NULL,\n\t\t\tcreated_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (group_id, candidate_ref)\n\t\t);\n\n\t\tCREATE INDEX IF NOT EXISTS idx_coordinator_legacy_team_completions_group\n\t\t\tON coordinator_legacy_team_completions(group_id, completed_at, candidate_ref);\n\t`);\n\ttry {\n\t\tdb.prepare(\n\t\t\t\"ALTER TABLE coordinator_scope_membership_audit_log ADD COLUMN effect_id TEXT\",\n\t\t).run();\n\t} catch {\n\t\t// already exists\n\t}\n\tdb.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_coordinator_scope_membership_audit_effect\n\t\tON coordinator_scope_membership_audit_log(effect_id) WHERE effect_id IS NOT NULL`);\n\ttry {\n\t\tdb.prepare(\"ALTER TABLE groups ADD COLUMN archived_at TEXT\").run();\n\t} catch {\n\t\t// already exists\n\t}\n\ttry {\n\t\tdb.prepare(\"ALTER TABLE enrolled_devices ADD COLUMN identity_id TEXT\").run();\n\t} catch {\n\t\t// already exists\n\t}\n\tfor (const column of [\n\t\t\"operation_id\",\n\t\t\"reviewed_project_set_digest\",\n\t\t\"token_digest\",\n\t\t\"inviter_actor_id\",\n\t\t\"inviter_display_name\",\n\t\t\"inviter_device_id\",\n\t\t\"pending_person_id\",\n\t\t\"project_summaries_json\",\n\t\t\"project_intent_json\",\n\t\t\"consumed_at\",\n\t\t\"bound_device_id\",\n\t\t\"bound_public_key\",\n\t\t\"bound_fingerprint\",\n\t\t\"recipient_actor_id\",\n\t\t\"recipient_display_name\",\n\t\t\"recipient_device_display_name\",\n\t\t\"trust_state\",\n\t\t\"bootstrap_grant_id\",\n\t\t\"invite_kind\",\n\t\t\"policy_team_id\",\n\t\t\"target_identity_id\",\n\t\t\"assigned_identity_id\",\n\t\t\"reviewed_preview_digest\",\n\t\t\"reviewed_intent_json\",\n\t]) {\n\t\ttry {\n\t\t\tdb.prepare(`ALTER TABLE coordinator_invites ADD COLUMN ${column} TEXT`).run();\n\t\t} catch {\n\t\t\t// already exists\n\t\t}\n\t}\n\tdb.exec(\n\t\t`CREATE UNIQUE INDEX IF NOT EXISTS idx_coordinator_invites_operation_id\n\t\t\tON coordinator_invites(operation_id) WHERE operation_id IS NOT NULL;\n\t\t CREATE UNIQUE INDEX IF NOT EXISTS idx_coordinator_invites_token_digest\n\t\t\tON coordinator_invites(token_digest) WHERE token_digest IS NOT NULL;\n\t\t CREATE INDEX IF NOT EXISTS idx_coordinator_invites_group_created\n\t\t\tON coordinator_invites(group_id, created_at DESC);\n\t\t UPDATE coordinator_invites\n\t\t\tSET invite_kind = CASE WHEN operation_id IS NOT NULL THEN 'project_share' ELSE 'legacy_enrollment' END\n\t\t\tWHERE invite_kind IS NULL;`,\n\t);\n}\n\nexport function connectCoordinator(\n\tpath?: string,\n\toptions: { existingOnly?: boolean } = {},\n): DatabaseType {\n\tconst dbPath = path ?? DEFAULT_COORDINATOR_DB_PATH;\n\tif (options.existingOnly) {\n\t\tconst db = new Database(dbPath, { fileMustExist: true });\n\t\tdb.pragma(\"foreign_keys = ON\");\n\t\tdb.pragma(\"busy_timeout = 5000\");\n\t\treturn db;\n\t}\n\tmkdirSync(dirname(dbPath), { recursive: true });\n\tconst db = new Database(dbPath);\n\tdb.pragma(\"foreign_keys = ON\");\n\tdb.pragma(\"busy_timeout = 5000\");\n\tdb.pragma(\"journal_mode = WAL\");\n\tdb.pragma(\"synchronous = NORMAL\");\n\tinitializeSchema(db);\n\treturn db;\n}\n\nfunction enrollmentRevocationKeyId(publicKey: string): string | null {\n\tconst parsed = parseSshEd25519PublicKeyForRevocation(publicKey);\n\tif (parsed.kind !== \"ed25519\") return null;\n\treturn createHash(\"sha256\").update(parsed.blob).digest(\"hex\");\n}\n\nexport class BetterSqliteCoordinatorStore implements CoordinatorStore {\n\t/** The raw backend, without the auth schema wrapper. */\n\tprivate readonly schemaBackend: AuthLinkBackend;\n\tprivate readonly accountChangeBackend: AuthLinkBackend;\n\tprivate readonly accountChangesCapability: AccountChangeOperations;\n\treadonly path: string;\n\treadonly db: DatabaseType;\n\tprivate readonly authLinks: AuthLinkOperations;\n\treadonly assertAuthSchemaReady: () => Promise<void>;\n\tprivate readonly accountLinkStatus: AccountLinkStatusOperations;\n\tprivate readonly accountOwnerTarget: AccountOwnerTargetOperations;\n\tprivate readonly deviceRevocations: DeviceRevocationOperations;\n\tprivate readonly authSessions: AuthSessionOperations;\n\tprivate readonly authAccountProfiles: AuthAccountProfileOperations;\n\tprivate readonly authBrowserTransactions: CoordinatorAuthBrowserTransactions;\n\n\tconstructor(\n\t\tpath?: string,\n\t\toptions: CoordinatorAuthLinkOptions & { existingOnly?: boolean } = {},\n\t) {\n\t\tthis.path = path ?? DEFAULT_COORDINATOR_DB_PATH;\n\t\tthis.db = connectCoordinator(this.path, options);\n\t\tthis.deviceRevocations = new DeviceRevocationOperations(\n\t\t\t{\n\t\t\t\tall: async (statement) => ({\n\t\t\t\t\tresults: this.db.prepare(statement.sql).all(...statement.values),\n\t\t\t\t}),\n\t\t\t\tbatch: async (statements) =>\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.transaction(() =>\n\t\t\t\t\t\t\tstatements.map((statement) => {\n\t\t\t\t\t\t\t\tconst prepared = this.db.prepare(statement.sql);\n\t\t\t\t\t\t\t\tif (statement.read) return { results: prepared.all(...statement.values) };\n\t\t\t\t\t\t\t\treturn { meta: { changes: prepared.run(...statement.values).changes } };\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.immediate(),\n\t\t\t},\n\t\t\toptions.authClock,\n\t\t);\n\t\tconst rawAuthBackend: AuthLinkBackend = {\n\t\t\tall: async <T>(statement: AuthLinkStatement) =>\n\t\t\t\tthis.db.prepare(statement.sql).all(...statement.values) as T[],\n\t\t\tfirst: async <T>(statement: AuthLinkStatement) =>\n\t\t\t\t(this.db.prepare(statement.sql).get(...statement.values) as T | undefined) ?? null,\n\t\t\trun: async (statement) =>\n\t\t\t\tthis.db\n\t\t\t\t\t.transaction(() => this.db.prepare(statement.sql).run(...statement.values).changes)\n\t\t\t\t\t.immediate(),\n\t\t\tbatch: async (statements) => {\n\t\t\t\treturn this.db\n\t\t\t\t\t.transaction(() =>\n\t\t\t\t\t\tstatements.map(\n\t\t\t\t\t\t\t(statement) => this.db.prepare(statement.sql).run(...statement.values).changes,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.immediate();\n\t\t\t},\n\t\t};\n\t\tthis.assertAuthSchemaReady = () => assertCoordinatorAuthSchema(rawAuthBackend);\n\t\tthis.schemaBackend = rawAuthBackend;\n\t\tconst authBackend = withCoordinatorAuthSchema(rawAuthBackend);\n\t\tthis.accountChangeBackend = withCoordinatorAuthSchema(rawAuthBackend, { connections: true });\n\t\tthis.accountChangesCapability = new AccountChangeOperations(\n\t\t\tthis.accountChangeBackend,\n\t\t\toptions.authClock,\n\t\t);\n\t\tthis.authLinks = new AuthLinkOperations(authBackend, options.authClock);\n\t\tthis.accountLinkStatus = new AccountLinkStatusOperations(authBackend, options.authClock);\n\t\tthis.accountOwnerTarget = new AccountOwnerTargetOperations(authBackend, this);\n\t\tthis.authSessions = new AuthSessionOperations(authBackend, options.authClock);\n\t\tthis.authAccountProfiles = new AuthAccountProfileOperations(authBackend, options.authClock);\n\t\tthis.authBrowserTransactions = new CoordinatorAuthBrowserTransactions(\n\t\t\tauthBackend,\n\t\t\toptions.authClock,\n\t\t);\n\t}\n\t/** ADR 0005 Section 8 rebind storage; null before its tables exist. */\n\treadDeviceRebindBackend(): Promise<AuthLinkBackend | null> {\n\t\treturn readDeviceRebindBackend(this.schemaBackend);\n\t}\n\t/** Headless account-linking storage; null unless both of its tables exist. */\n\treadHeadlessLinkBackend(): Promise<AuthLinkBackend | null> {\n\t\treturn readHeadlessLinkBackend(this.schemaBackend);\n\t}\n\t/** Explicit capability: legacy V2 remains usable without enabling management. */\n\tasync getAccountChanges(): Promise<AccountChangeOperations> {\n\t\tawait this.accountChangeBackend.first({ sql: \"SELECT 1\", values: [] });\n\t\treturn this.accountChangesCapability;\n\t}\n\treadAccountConnectionSchemaState(): Promise<ConnectionSchemaState> {\n\t\treturn readConnectionSchemaState(this.schemaBackend);\n\t}\n\t/** One fresh startup lookup; returned operations still check every SQL entry. */\n\tasync readAccountChangeCapability(): Promise<AccountChangeOperations | null> {\n\t\tconst state = await this.readAccountConnectionSchemaState();\n\t\tif (state === \"upgrade_required\") throw new CoordinatorAuthSchemaUpgradeRequiredError();\n\t\treturn state === \"ready\" ? this.accountChangesCapability : null;\n\t}\n\tasync readAuthBrowserTransactionPurpose(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.readAuthBrowserTransactionPurpose(input, config);\n\t}\n\n\tasync readAuthBrowserTransactionActivity(\n\t\tinput: { binderHash: string },\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.readAuthBrowserTransactionActivity(input, config);\n\t}\n\tasync startAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionStartInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.startAuthBrowserTransaction(input, config);\n\t}\n\tasync startHeadlessAuthLinkBrowserTransaction(\n\t\tinput: CoordinatorAuthHeadlessBrowserStartInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.startHeadlessAuthLinkBrowserTransaction(input, config);\n\t}\n\tasync consumeAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.consumeAuthBrowserTransaction(input, config);\n\t}\n\tasync resolveAuthLinkBrowserTransaction(\n\t\tinput: CoordinatorAuthLinkBrowserTransactionResolveInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.resolveAuthLinkBrowserTransaction(input, config);\n\t}\n\tasync cancelAuthSigninBrowserTransaction(\n\t\tinput: CoordinatorAuthSigninBrowserTransactionCancelInput,\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t) {\n\t\treturn this.authBrowserTransactions.cancelAuthSigninBrowserTransaction(input, scope);\n\t}\n\tasync retireAuthBrowserTransactions(\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t\toptions?: CoordinatorAuthBrowserTransactionRetirementOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.retireAuthBrowserTransactions(config, options);\n\t}\n\tasync purgeAuthSigninBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.purgeAuthSigninBrowserTransactions(scope, options);\n\t}\n\tasync maintainAuthBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.maintainAuthBrowserTransactions(scope, options);\n\t}\n\n\tasync redeemAuthLinkSession(\n\t\tinput: CoordinatorAuthLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authSessions.redeemAuthLinkSession(input, config);\n\t}\n\tasync redeemAuthLinkSessionWithBrowserTransaction(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.redeemAuthLinkSessionWithBrowserTransaction(input, config);\n\t}\n\tasync preserveAuthLinkSessionCompletion(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.preserveAuthLinkSessionCompletion(input, config);\n\t}\n\tasync purgeAuthGuardedSigninSessions(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t) {\n\t\treturn this.authSessions.purgeAuthGuardedSigninSessions(scope, options);\n\t}\n\tasync purgeAuthGuardedSigninReceipts(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t) {\n\t\treturn this.authSessions.purgeAuthGuardedSigninReceipts(scope, options);\n\t}\n\tasync signInWithAuthAccount(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authSessions.signInWithAuthAccount(input, config);\n\t}\n\tasync signInWithConsumedBrowserTransaction(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.signInWithConsumedBrowserTransaction(input, config);\n\t}\n\tasync readAuthSession(credentialHash: string, config: CoordinatorAuthLinkConfig) {\n\t\treturn this.authSessions.readAuthSession(credentialHash, config);\n\t}\n\tasync recordAuthAccountProfile(\n\t\tinput: CoordinatorAuthAccountProfileInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authAccountProfiles.recordAuthAccountProfile(input, config);\n\t}\n\tasync readAuthSessionAccount(credentialHash: string, config: CoordinatorAuthLinkConfig) {\n\t\treturn this.authAccountProfiles.readAuthSessionAccount(credentialHash, config);\n\t}\n\tasync clearRevokedAuthAccountProfile(\n\t\tinput: { linkId: string },\n\t\tscope: { coordinatorId: string },\n\t) {\n\t\treturn this.authAccountProfiles.clearRevokedAuthAccountProfile(input, scope);\n\t}\n\tasync signOutAuthSession(credentialHash: string, scope: CoordinatorAuthSessionScope) {\n\t\treturn this.authSessions.signOutAuthSession(credentialHash, scope);\n\t}\n\tasync revokeAuthAccountLink(input: { linkId: string }, scope: CoordinatorAuthSessionScope) {\n\t\treturn this.authSessions.revokeAuthAccountLink(input, scope);\n\t}\n\n\tasync maintainAuthLinkAttempts(\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions?: CoordinatorAuthLinkMaintenanceOptions,\n\t) {\n\t\treturn this.authLinks.maintainAuthLinkAttempts(config, options);\n\t}\n\treadAccountLinkStatus(...args: Parameters<AccountLinkStatusOperations[\"readAccountLinkStatus\"]>) {\n\t\treturn this.accountLinkStatus.readAccountLinkStatus(...args);\n\t}\n\treadAccountOwnerTarget(\n\t\t...args: Parameters<AccountOwnerTargetOperations[\"readAccountOwnerTarget\"]>\n\t) {\n\t\treturn this.accountOwnerTarget.readAccountOwnerTarget(...args);\n\t}\n\treadResolvedAccountOwnerStatus(\n\t\t...args: Parameters<ResolvedAccountOwnerStatusOperations[\"readResolvedAccountOwnerStatus\"]>\n\t) {\n\t\treturn new ResolvedAccountOwnerStatusOperations({\n\t\t\t...this.accountChangeBackend,\n\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t}).readResolvedAccountOwnerStatus(...args);\n\t}\n\tprivate ownerResolutionReviews(): OwnerResolutionReviewOperations {\n\t\treturn new OwnerResolutionReviewOperations({\n\t\t\t...this.schemaBackend,\n\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t\trun: async ({ sql, values }) => this.db.prepare(sql).run(...values).changes,\n\t\t\tbatch: async (statements) =>\n\t\t\t\tthis.db\n\t\t\t\t\t.transaction(() =>\n\t\t\t\t\t\tstatements.map(({ sql, values }) => {\n\t\t\t\t\t\t\tconst statement = this.db.prepare(sql);\n\t\t\t\t\t\t\tif (statement.reader) {\n\t\t\t\t\t\t\t\tstatement.all(...values);\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn statement.run(...values).changes;\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t\t.immediate(),\n\t\t});\n\t}\n\tpreviewOwnerResolutionReview(\n\t\t...args: Parameters<OwnerResolutionReviewOperations[\"previewOwnerResolutionReview\"]>\n\t) {\n\t\treturn this.ownerResolutionReviews().previewOwnerResolutionReview(...args);\n\t}\n\tconfirmOwnerResolutionReview(\n\t\t...args: Parameters<OwnerResolutionReviewOperations[\"confirmOwnerResolutionReview\"]>\n\t) {\n\t\treturn this.ownerResolutionReviews().confirmOwnerResolutionReview(...args);\n\t}\n\treadAuthDeviceClaimReadiness(\n\t\t...args: Parameters<AccountLinkStatusOperations[\"readAuthDeviceClaimReadiness\"]>\n\t) {\n\t\treturn this.accountLinkStatus.readAuthDeviceClaimReadiness(...args);\n\t}\n\tasync createAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkCreateInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.createAuthLinkAttempt(input, config);\n\t}\n\tasync claimAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.claimAuthLinkAttempt(input, config);\n\t}\n\tasync recordAuthLinkOidcVerified(\n\t\tinput: CoordinatorAuthLinkOidcInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.recordAuthLinkOidcVerified(input, config);\n\t}\n\tasync confirmAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkConfirmInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.confirmAuthLinkAttempt(input, config);\n\t}\n\tasync readAuthLinkCompletionDestination(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.readAuthLinkCompletionDestination(input, config);\n\t}\n\tasync finalizeAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.finalizeAuthLinkAttempt(input, config);\n\t}\n\tasync failAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFailInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.failAuthLinkAttempt(input, config);\n\t}\n\tasync getAuthLinkAttemptStatus(\n\t\tattemptId: string,\n\t\trequester: CoordinatorAuthLinkRequester,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.getAuthLinkAttemptStatus(attemptId, requester, config);\n\t}\n\tasync createHeadlessAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkHeadlessCreateInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.createHeadlessAuthLinkAttempt(input, config);\n\t}\n\tasync confirmHeadlessAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.confirmHeadlessAuthLinkAttempt(input, config);\n\t}\n\tasync getAuthLinkBrowserAttemptStatus(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.getAuthLinkBrowserAttemptStatus(input, config);\n\t}\n\tasync readHeadlessAuthLinkDeviceName(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.readHeadlessAuthLinkDeviceName(input, config);\n\t}\n\tasync readHeadlessAuthLinkApproval(\n\t\tinput: CoordinatorAuthLinkHeadlessApprovalInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.readHeadlessAuthLinkApproval(input, config);\n\t}\n\tasync finalizeHeadlessAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkHeadlessFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.finalizeHeadlessAuthLinkAttempt(input, config);\n\t}\n\n\tprivate enrollDeviceSync(groupId: string, opts: CoordinatorEnrollDeviceInput): void {\n\t\tconst { deviceId, publicKey, fingerprint, identityId, displayName } = captureLegacyEnrollment(\n\t\t\tgroupId,\n\t\t\topts,\n\t\t);\n\t\ttry {\n\t\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t\t.get(groupId, deviceId) ?? null,\n\t\t\t);\n\t\t\tconst keyId = enrollmentRevocationKeyId(publicKey);\n\t\t\tconst currentKeyId =\n\t\t\t\tcurrentPublicKey === null ? null : enrollmentRevocationKeyId(currentPublicKey);\n\t\t\tconst source = [currentPublicKey, groupId, deviceId, groupId, deviceId, currentPublicKey];\n\t\t\tconst result = this.db\n\t\t\t\t.prepare(LEGACY_ENROLLMENT_WRITE_SQL)\n\t\t\t\t.run(\n\t\t\t\t\tgroupId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tpublicKey,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\tidentityId ?? null,\n\t\t\t\t\tdisplayName ?? null,\n\t\t\t\t\tnowISO(),\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tcurrentKeyId,\n\t\t\t\t\t...source,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tcurrentKeyId,\n\t\t\t\t\tcurrentPublicKey,\n\t\t\t\t);\n\t\t\tif (legacyDeviceWriteChanges({ meta: result }) === 1) return;\n\t\t\tconst denial = this.db\n\t\t\t\t.prepare(LEGACY_ENROLLMENT_DENIAL_SQL)\n\t\t\t\t.get(deviceId, keyId, deviceId, keyId, deviceId, currentKeyId, ...source);\n\t\t\tthrow new Error(legacyDeviceDenial(denial));\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t}\n\n\tasync close(): Promise<void> {\n\t\tthis.db.close();\n\t}\n\n\tasync issueIdentityGroupGrantFromControllerAttestation(\n\t\tinput: CoordinatorIdentityGroupGrantIssueInput,\n\t): Promise<CoordinatorIdentityGroupGrantIssueResult> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\"coordinatorId\", \"attestationId\"]);\n\t\tif (!captured) return { kind: \"rejected\", error: \"invalid_grant_input\" };\n\t\ttry {\n\t\t\treturn this.db\n\t\t\t\t.transaction((): CoordinatorIdentityGroupGrantIssueResult => {\n\t\t\t\t\tconst source = this.db\n\t\t\t\t\t\t.prepare(IDENTITY_GROUP_GRANT_SOURCE_SQL)\n\t\t\t\t\t\t.get(captured.coordinatorId, captured.attestationId) as\n\t\t\t\t\t\t| CoordinatorEnrollment\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\tif (!source) return { kind: \"rejected\", error: \"grant_authority_unavailable\" };\n\t\t\t\t\tconst authority = [\n\t\t\t\t\t\tcaptured.coordinatorId,\n\t\t\t\t\t\tcaptured.attestationId,\n\t\t\t\t\t\tsource.group_id,\n\t\t\t\t\t\tsource.device_id,\n\t\t\t\t\t\tsource.public_key,\n\t\t\t\t\t\tsource.fingerprint,\n\t\t\t\t\t\tsource.identity_id,\n\t\t\t\t\t\tsource.device_id,\n\t\t\t\t\t\tenrollmentRevocationKeyId(source.public_key),\n\t\t\t\t\t];\n\t\t\t\t\tconst grant = this.db\n\t\t\t\t\t\t.prepare(IDENTITY_GROUP_GRANT_INSERT_SQL)\n\t\t\t\t\t\t.get(nowISO(), ...authority) as CoordinatorIdentityGroupGrant | undefined;\n\t\t\t\t\tif (grant) return { kind: \"created\", grant };\n\t\t\t\t\tconst existing = this.db.prepare(IDENTITY_GROUP_GRANT_RETRY_SQL).get(...authority) as\n\t\t\t\t\t\t| CoordinatorIdentityGroupGrant\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\tif (existing) return { kind: \"existing\", grant: existing };\n\t\t\t\t\treturn { kind: \"rejected\", error: \"grant_authority_unavailable\" };\n\t\t\t\t})\n\t\t\t\t.immediate();\n\t\t} catch {\n\t\t\tthrow new Error(\"identity_group_grant_write_incomplete\");\n\t\t}\n\t}\n\n\tasync listIdentityGroupGrantRevisions(\n\t\tinput: CoordinatorIdentityGroupGrantScope,\n\t): Promise<CoordinatorIdentityGroupGrant[]> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\"coordinatorId\", \"identityId\"]);\n\t\tif (!captured) throw new Error(\"invalid_grant_input\");\n\t\treturn this.db\n\t\t\t.prepare(IDENTITY_GROUP_GRANT_LIST_SQL)\n\t\t\t.all(captured.coordinatorId, captured.identityId) as CoordinatorIdentityGroupGrant[];\n\t}\n\n\tasync revokeIdentityGroupGrant(\n\t\tinput: CoordinatorIdentityGroupGrantRevokeInput,\n\t): Promise<boolean> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\n\t\t\t\"coordinatorId\",\n\t\t\t\"identityId\",\n\t\t\t\"groupId\",\n\t\t\t\"expectedRevision\",\n\t\t]);\n\t\tif (!captured) return false;\n\t\treturn (\n\t\t\tthis.db\n\t\t\t\t.prepare(IDENTITY_GROUP_GRANT_REVOKE_SQL)\n\t\t\t\t.run(\n\t\t\t\t\tnowISO(),\n\t\t\t\t\tcaptured.coordinatorId,\n\t\t\t\t\tcaptured.identityId,\n\t\t\t\t\tcaptured.groupId,\n\t\t\t\t\tcaptured.expectedRevision,\n\t\t\t\t).changes > 0\n\t\t);\n\t}\n\n\tasync createAuthControllerAttestation(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerCreateResult> {\n\t\tconst review = captureAuthControllerReview(input);\n\t\tif (!review) return { kind: \"rejected\", error: \"invalid_review_input\" };\n\t\tconst conflict = this.db\n\t\t\t.prepare(AUTH_CONTROLLER_CONFLICT_SQL)\n\t\t\t.get(...authControllerConflictValues(review)) as\n\t\t\t| CoordinatorAuthControllerAttestation\n\t\t\t| undefined;\n\t\tconst hasConflict = conflict !== undefined;\n\t\tconst consistency = hasConflict ? null : await this.prepareAuthControllerConsistency(review);\n\t\tif (!hasConflict && !consistency) return authControllerUnavailableResult(review);\n\t\tlet retryAfterPinChange = false;\n\t\tconst result = this.db\n\t\t\t.transaction((): CoordinatorAuthControllerCreateResult => {\n\t\t\t\tconst source = this.db\n\t\t\t\t\t.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL)\n\t\t\t\t\t.get(review.groupId, review.deviceId) as CoordinatorEnrollment | undefined;\n\t\t\t\tif (!source) return authControllerUnavailableResult(review);\n\t\t\t\tconst authority = authControllerAuthorityValues(\n\t\t\t\t\tsource,\n\t\t\t\t\tenrollmentRevocationKeyId(source.public_key),\n\t\t\t\t);\n\t\t\t\tif (hasConflict) return this.resolveAuthControllerRetrySync(review, authority);\n\t\t\t\ttry {\n\t\t\t\t\tconst statement = withNegativeOwnerConsistency(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsql: authControllerReviewSql(AUTH_CONTROLLER_INSERT_SQL, review),\n\t\t\t\t\t\t\tvalues: authControllerInsertValues(review, nowISO(), authority),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tconsistency ?? { sql: \"SELECT 0 AS matches\", values: [] },\n\t\t\t\t\t);\n\t\t\t\t\tconst inserted = this.db.prepare(statement.sql).run(...statement.values);\n\t\t\t\t\tif (inserted.changes === 0) {\n\t\t\t\t\t\tretryAfterPinChange = true;\n\t\t\t\t\t\treturn authControllerUnavailableResult(review);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!isAuthControllerUniqueError(error)) throw error;\n\t\t\t\t\treturn this.resolveAuthControllerRetrySync(review, authority);\n\t\t\t\t}\n\t\t\t\tconst attestation = this.getActiveAuthControllerAttestationSync(\n\t\t\t\t\treview.coordinatorId,\n\t\t\t\t\treview.attestationId,\n\t\t\t\t\tauthority,\n\t\t\t\t);\n\t\t\t\tif (!attestation) throw new Error(\"auth_controller_persistence_incomplete\");\n\t\t\t\treturn { kind: \"created\", attestation };\n\t\t\t})\n\t\t\t.immediate();\n\t\tif (!retryAfterPinChange) return result;\n\t\treturn this.retryAuthControllerAfterPinChange(review);\n\t}\n\n\tprivate async retryAuthControllerAfterPinChange(\n\t\treview: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerCreateResult> {\n\t\t// The winner changes the evidence pin. Recapture without accepting new conflicts.\n\t\tconst retryConsistency = await this.prepareAuthControllerConsistency(review);\n\t\tif (!retryConsistency) return authControllerUnavailableResult(review);\n\t\treturn this.db\n\t\t\t.transaction((): CoordinatorAuthControllerCreateResult => {\n\t\t\t\tconst pin = this.db.prepare(retryConsistency.sql).get(...retryConsistency.values) as\n\t\t\t\t\t| { matches: number }\n\t\t\t\t\t| undefined;\n\t\t\t\tif (pin?.matches !== 1) return authControllerUnavailableResult(review);\n\t\t\t\tconst source = this.db\n\t\t\t\t\t.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL)\n\t\t\t\t\t.get(review.groupId, review.deviceId) as CoordinatorEnrollment | undefined;\n\t\t\t\tif (!source) return authControllerUnavailableResult(review);\n\t\t\t\treturn this.resolveAuthControllerRetrySync(\n\t\t\t\t\treview,\n\t\t\t\t\tauthControllerAuthorityValues(source, enrollmentRevocationKeyId(source.public_key)),\n\t\t\t\t);\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tprivate prepareAuthControllerConsistency(review: CoordinatorAuthControllerReviewInput) {\n\t\treturn prepareNegativeOwnerConsistency(\n\t\t\t{\n\t\t\t\tfirst: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\t(this.db.prepare(sql).get(...values) as T | undefined) ?? null,\n\t\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t\t},\n\t\t\t{\n\t\t\t\t...review,\n\t\t\t\townerIdentityId: review.identityId,\n\t\t\t\tenrollment: { groupId: review.groupId },\n\t\t\t\tverifiedHistory: review.verifiedSnapshot?.legacyHistory,\n\t\t\t},\n\t\t);\n\t}\n\n\tprivate resolveAuthControllerRetrySync(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t\tauthority: (string | null)[],\n\t): CoordinatorAuthControllerCreateResult {\n\t\tif (\n\t\t\t!this.db\n\t\t\t\t.prepare(authControllerReviewSql(AUTH_CONTROLLER_RETRY_ELIGIBLE_SQL, input))\n\t\t\t\t.get(...authControllerRetryEligibleValues(input, authority))\n\t\t)\n\t\t\treturn {\n\t\t\t\tkind: \"rejected\",\n\t\t\t\terror: input.verifiedSnapshot ? \"review_stale\" : \"enrollment_mismatch\",\n\t\t\t};\n\t\tconst row = this.db\n\t\t\t.prepare(AUTH_CONTROLLER_CONFLICT_SQL)\n\t\t\t.get(...authControllerConflictValues(input)) as\n\t\t\t| CoordinatorAuthControllerAttestation\n\t\t\t| undefined;\n\t\tconst result = authControllerRetryResult(input, row ?? null);\n\t\tif (result.kind === \"rejected\") return result;\n\t\tconst active = this.getActiveAuthControllerAttestationSync(\n\t\t\tinput.coordinatorId,\n\t\t\tinput.attestationId,\n\t\t\tauthority,\n\t\t);\n\t\tif (!active) return { kind: \"rejected\", error: \"enrollment_mismatch\" };\n\t\treturn { kind: \"existing\", attestation: active };\n\t}\n\n\tprivate getActiveAuthControllerAttestationSync(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t\tauthority?: (string | null)[],\n\t): CoordinatorAuthControllerAttestation | null {\n\t\tif (!authority) {\n\t\t\tconst source = this.db\n\t\t\t\t.prepare(AUTH_CONTROLLER_CURRENT_ENROLLMENT_SQL)\n\t\t\t\t.get(coordinatorId, attestationId) as CoordinatorEnrollment | undefined;\n\t\t\tif (!source) return null;\n\t\t\tauthority = authControllerAuthorityValues(\n\t\t\t\tsource,\n\t\t\t\tenrollmentRevocationKeyId(source.public_key),\n\t\t\t);\n\t\t}\n\t\treturn (\n\t\t\t(this.db\n\t\t\t\t.prepare(AUTH_CONTROLLER_ACTIVE_SQL)\n\t\t\t\t.get(coordinatorId, attestationId, ...authority) as\n\t\t\t\t| CoordinatorAuthControllerAttestation\n\t\t\t\t| undefined) ?? null\n\t\t);\n\t}\n\n\tasync getActiveAuthControllerAttestation(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t): Promise<CoordinatorAuthControllerAttestation | null> {\n\t\tif (!isAuthControllerId(coordinatorId) || !isAuthControllerId(attestationId)) return null;\n\t\treturn this.getActiveAuthControllerAttestationSync(coordinatorId, attestationId);\n\t}\n\n\tasync readAuthControllerAttestationForSnapshot(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerAttestation | null> {\n\t\tconst review = captureAuthControllerReview(input);\n\t\tif (!review?.verifiedSnapshot?.accountOwnerTarget) return null;\n\t\tconst source = this.db\n\t\t\t.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL)\n\t\t\t.get(review.groupId, review.deviceId) as CoordinatorEnrollment | undefined;\n\t\tif (!source) return null;\n\t\tconst authority = authControllerAuthorityValues(\n\t\t\tsource,\n\t\t\tenrollmentRevocationKeyId(source.public_key),\n\t\t);\n\t\treturn (\n\t\t\t(this.db\n\t\t\t\t.prepare(authControllerReviewSql(AUTH_CONTROLLER_RETRY_ACTIVE_SQL, review))\n\t\t\t\t.get(...authControllerRetryActiveValues(review, authority)) as\n\t\t\t\t| CoordinatorAuthControllerAttestation\n\t\t\t\t| undefined) ?? null\n\t\t);\n\t}\n\n\tasync hasAuthControllerSubjectOwnerConflict(\n\t\tinput: CoordinatorAuthControllerSubjectOwnerInput,\n\t): Promise<boolean> {\n\t\treturn !!this.db\n\t\t\t.prepare(AUTH_CONTROLLER_SUBJECT_OWNER_CONFLICT_SQL)\n\t\t\t.get(...authControllerSubjectOwnerConflictValues(input));\n\t}\n\n\tasync revokeAuthControllerAttestation(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t): Promise<boolean> {\n\t\tif (!isAuthControllerId(coordinatorId) || !isAuthControllerId(attestationId)) return false;\n\t\treturn (\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_REVOKE_SQL).run(nowISO(), coordinatorId, attestationId)\n\t\t\t\t.changes > 0\n\t\t);\n\t}\n\n\tasync createGroup(groupId: string, displayName?: string | null): Promise<void> {\n\t\tthis.db\n\t\t\t.prepare(\n\t\t\t\t\"INSERT OR IGNORE INTO groups(group_id, display_name, archived_at, created_at) VALUES (?, ?, NULL, ?)\",\n\t\t\t)\n\t\t\t.run(groupId, displayName ?? null, nowISO());\n\t}\n\n\tasync getGroup(groupId: string): Promise<CoordinatorGroup | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT group_id, display_name, archived_at, created_at FROM groups WHERE group_id = ?\",\n\t\t\t)\n\t\t\t.get(groupId);\n\t\treturn row ? rowToRecord<CoordinatorGroup>(row) : null;\n\t}\n\n\tasync listGroups(includeArchived = false): Promise<CoordinatorGroup[]> {\n\t\tconst where = includeArchived ? \"\" : \"WHERE archived_at IS NULL\";\n\t\treturn this.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT group_id, display_name, archived_at, created_at FROM groups ${where} ORDER BY created_at ASC`,\n\t\t\t)\n\t\t\t.all()\n\t\t\t.map((row) => rowToRecord<CoordinatorGroup>(row));\n\t}\n\n\tasync renameGroup(groupId: string, displayName: string): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(\"UPDATE groups SET display_name = ? WHERE group_id = ?\")\n\t\t\t.run(displayName, groupId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync archiveGroup(groupId: string, archivedAt = nowISO()): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(\"UPDATE groups SET archived_at = ? WHERE group_id = ? AND archived_at IS NULL\")\n\t\t\t.run(archivedAt, groupId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync unarchiveGroup(groupId: string): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(\n\t\t\t\t\"UPDATE groups SET archived_at = NULL WHERE group_id = ? AND archived_at IS NOT NULL\",\n\t\t\t)\n\t\t\t.run(groupId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync enrollDevice(groupId: string, opts: CoordinatorEnrollDeviceInput): Promise<void> {\n\t\tconst input = captureLegacyEnrollment(groupId, opts);\n\t\ttry {\n\t\t\tthis.db.transaction(() => this.enrollDeviceSync(groupId, input)).immediate();\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t}\n\n\tasync listEnrolledDevices(\n\t\tgroupId: string,\n\t\tincludeDisabled = false,\n\t): Promise<CoordinatorEnrollment[]> {\n\t\tconst where = includeDisabled ? \"\" : \"AND enrolled_devices.enabled = 1\";\n\t\treturn withEnrollmentOwnership(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_PRESENCE_COLUMNS}, ${ENROLLMENT_OWNERSHIP_COLUMNS}\n\t\t\t\t FROM enrolled_devices\n\t\t\t\t LEFT JOIN presence_records\n\t\t\t\t ON presence_records.group_id = enrolled_devices.group_id\n\t\t\t\t AND presence_records.device_id = enrolled_devices.device_id\n\t\t\t\t WHERE enrolled_devices.group_id = ? ${where}\n\t\t\t\t ORDER BY enrolled_devices.created_at ASC, enrolled_devices.device_id ASC`)\n\t\t\t\t.all(groupId)\n\t\t\t\t.map(rowToEnrollmentWithPresence),\n\t\t);\n\t}\n\n\tasync getEnrollment(\n\t\tgroupId: string,\n\t\tdeviceId: string,\n\t\tincludeDisabled = false,\n\t): Promise<CoordinatorEnrollment | null> {\n\t\tconst enabledClause = includeDisabled ? \"\" : \"AND enabled = 1\";\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t FROM enrolled_devices\n\t\t\t\t WHERE group_id = ? AND device_id = ? ${enabledClause}`)\n\t\t\t.get(groupId, deviceId);\n\t\treturn row ? rowToRecord<CoordinatorEnrollment>(row) : null;\n\t}\n\n\tasync renameDevice(groupId: string, deviceId: string, displayName: string): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(`UPDATE enrolled_devices SET display_name = ?\n\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t.run(displayName, groupId, deviceId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync setDeviceEnabled(groupId: string, deviceId: string, enabled: boolean): Promise<boolean> {\n\t\tassertLegacyDeviceScope(groupId, deviceId);\n\t\tif (typeof enabled !== \"boolean\") throw new Error(\"invalid_input\");\n\t\tif (enabled) {\n\t\t\ttry {\n\t\t\t\treturn this.db\n\t\t\t\t\t.transaction(() => {\n\t\t\t\t\t\tconst enrollment = this.db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t\"SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?\",\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.get(groupId, deviceId) as { public_key: string } | undefined;\n\t\t\t\t\t\tif (!enrollment) return false;\n\t\t\t\t\t\tconst publicKey = enrollment.public_key;\n\t\t\t\t\t\tif (typeof publicKey !== \"string\")\n\t\t\t\t\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t\t\t\t\tconst keyId = enrollmentRevocationKeyId(publicKey);\n\t\t\t\t\t\tconst result = this.db\n\t\t\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET enabled = 1\n\t\t\t\t\t\tWHERE group_id = ? AND device_id = ? AND public_key = ?\n\t\t\t\t\t\tAND NOT ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\t\t\tAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}`)\n\t\t\t\t\t\t\t.run(groupId, deviceId, publicKey, deviceId, keyId, deviceId, keyId);\n\t\t\t\t\t\tif (legacyDeviceWriteChanges({ meta: result }) === 1) return true;\n\t\t\t\t\t\tconst denial = legacyDeviceDenial(\n\t\t\t\t\t\t\tthis.db.prepare(LEGACY_DEVICE_DENIAL_SQL).get(deviceId, keyId, deviceId, keyId),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (denial === \"device_ownership_requires_verified_identity\") throw new Error(denial);\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t})\n\t\t\t\t\t.immediate();\n\t\t\t} catch (error) {\n\t\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t\t}\n\t\t}\n\t\tconst result = this.db\n\t\t\t.prepare(`UPDATE enrolled_devices SET enabled = ?\n\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t.run(enabled ? 1 : 0, groupId, deviceId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync removeDevice(groupId: string, deviceId: string): Promise<boolean> {\n\t\t// Atomic: a partial failure must not leave presence/approval rows\n\t\t// orphaned against a still-enrolled device (or vice versa).\n\t\tconst removeAll = this.db.transaction(() => {\n\t\t\tthis.db\n\t\t\t\t.prepare(\"DELETE FROM presence_records WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.run(groupId, deviceId);\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"DELETE FROM coordinator_reciprocal_approvals WHERE group_id = ? AND (requesting_device_id = ? OR requested_device_id = ?)\",\n\t\t\t\t)\n\t\t\t\t.run(groupId, deviceId, deviceId);\n\t\t\tconst result = this.db\n\t\t\t\t.prepare(\"DELETE FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.run(groupId, deviceId);\n\t\t\treturn result.changes > 0;\n\t\t});\n\t\treturn removeAll();\n\t}\n\n\tasync recordNonce(deviceId: string, nonce: string, createdAt: string): Promise<boolean> {\n\t\ttry {\n\t\t\tthis.db\n\t\t\t\t.prepare(\"INSERT INTO request_nonces(device_id, nonce, created_at) VALUES (?, ?, ?)\")\n\t\t\t\t.run(deviceId, nonce, createdAt);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync createDeviceRevocation(input: CoordinatorCreateDeviceRevocationInput) {\n\t\treturn this.deviceRevocations.createDeviceRevocation(input);\n\t}\n\n\tasync listDeviceRevocations(input: CoordinatorListDeviceRevocationsInput) {\n\t\treturn this.deviceRevocations.listDeviceRevocations(input);\n\t}\n\n\tasync recordAuthorizedNonce(input: CoordinatorRecordAuthorizedNonceInput) {\n\t\treturn this.deviceRevocations.recordAuthorizedNonce(input);\n\t}\n\n\tasync cleanupNonces(cutoff: string): Promise<void> {\n\t\tthis.db.prepare(\"DELETE FROM request_nonces WHERE created_at < ?\").run(cutoff);\n\t}\n\n\tasync createInvite(opts: CoordinatorCreateInviteInput): Promise<CoordinatorInvite> {\n\t\tconst now = nowISO();\n\t\t// Normalize to canonical UTC ISO so the lexicographic `expires_at > ?`\n\t\t// comparison in getInviteByToken is sound.\n\t\tconst expiresAt = normalizeInviteExpiresAt(opts.expiresAt);\n\t\tconst inviteId = tokenUrlSafe(12);\n\t\tconst token = tokenUrlSafe(24);\n\t\tconst digest = tokenDigest(token);\n\t\tconst group = await this.getGroup(opts.groupId);\n\t\tconst operationId = clean(opts.operationId);\n\t\tconst reviewedProjectSetDigest = clean(opts.reviewedProjectSetDigest);\n\t\tconst metadata = await normalizeCoordinatorInviteMetadata(opts);\n\t\tconst assignedIdentityId =\n\t\t\tmetadata.inviteKind === \"team_member\" ? `identity:${tokenUrlSafe(18)}` : null;\n\t\tif (Boolean(operationId) !== Boolean(reviewedProjectSetDigest)) {\n\t\t\tthrow new Error(\"operationId and reviewedProjectSetDigest must be provided together.\");\n\t\t}\n\t\tconst readOperationInvite = (): CoordinatorInvite | null => {\n\t\t\tif (!operationId) return null;\n\t\t\tconst existing = this.db\n\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE operation_id = ?`)\n\t\t\t\t.get(operationId) as CoordinatorInvite | undefined;\n\t\t\tif (!existing) return null;\n\t\t\t// Project bearer tokens remain retrievable only until first consume so an\n\t\t\t// interrupted create can return the same invite. Consume replaces the\n\t\t\t// plaintext with a non-secret marker; later create retries must not emit it.\n\t\t\tif (existing.consumed_at) throw new Error(\"invite_already_bound\");\n\t\t\tif (\n\t\t\t\texisting.group_id !== opts.groupId ||\n\t\t\t\texisting.policy !== opts.policy ||\n\t\t\t\texisting.invite_kind !== metadata.inviteKind ||\n\t\t\t\texisting.reviewed_project_set_digest !== reviewedProjectSetDigest ||\n\t\t\t\texisting.inviter_actor_id !== clean(opts.inviterActorId) ||\n\t\t\t\texisting.inviter_display_name !== clean(opts.inviterDisplayName) ||\n\t\t\t\texisting.inviter_device_id !== clean(opts.inviterDeviceId) ||\n\t\t\t\texisting.pending_person_id !== clean(opts.pendingPersonId) ||\n\t\t\t\texisting.project_summaries_json !==\n\t\t\t\t\t(opts.projectSummaries ? JSON.stringify(opts.projectSummaries) : null) ||\n\t\t\t\texisting.project_intent_json !==\n\t\t\t\t\t(opts.projectIntent ? JSON.stringify(opts.projectIntent) : null) ||\n\t\t\t\texisting.policy_team_id !== metadata.policyTeamId ||\n\t\t\t\texisting.target_identity_id !== metadata.targetIdentityId ||\n\t\t\t\texisting.reviewed_preview_digest !== metadata.reviewedPreviewDigest ||\n\t\t\t\texisting.reviewed_intent_json !== metadata.reviewedIntentJson\n\t\t\t) {\n\t\t\t\tthrow new Error(\"invite_operation_intent_conflict\");\n\t\t\t}\n\t\t\treturn existing;\n\t\t};\n\t\tconst renewOperationInvite = (existing: CoordinatorInvite): CoordinatorInvite => {\n\t\t\tif (!existing.revoked_at && existing.expires_at > now) return existing;\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_invites\n\t\t\t\t\tSET token = ?, token_digest = ?, expires_at = ?, created_at = ?, created_by = ?,\n\t\t\t\t\t\tteam_name_snapshot = ?, revoked_at = NULL\n\t\t\t\t\tWHERE operation_id = ? AND token = ?\n\t\t\t\t\t AND (revoked_at IS NOT NULL OR expires_at <= ?)`)\n\t\t\t\t.run(\n\t\t\t\t\ttoken,\n\t\t\t\t\tdigest,\n\t\t\t\t\texpiresAt,\n\t\t\t\t\tnow,\n\t\t\t\t\topts.createdBy ?? null,\n\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\toperationId,\n\t\t\t\t\texisting.token,\n\t\t\t\t\tnow,\n\t\t\t\t);\n\t\t\tconst renewed = readOperationInvite();\n\t\t\tif (!renewed) throw new Error(\"invite_operation_reissue_failed\");\n\t\t\treturn renewed;\n\t\t};\n\t\tif (operationId) {\n\t\t\tconst existing = readOperationInvite();\n\t\t\tif (existing) return renewOperationInvite(existing);\n\t\t}\n\t\ttry {\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_invites(\n\t\t\t\t\tinvite_id, group_id, token, policy, expires_at, created_at, created_by,\n\t\t\t\t\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest,\n\t\t\t\t\ttoken_digest, inviter_actor_id, inviter_display_name, inviter_device_id,\n\t\t\t\t\tpending_person_id, project_summaries_json, project_intent_json, trust_state,\n\t\t\t\t\tinvite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\t\t\t\t\treviewed_preview_digest, reviewed_intent_json\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t\t.run(\n\t\t\t\t\tinviteId,\n\t\t\t\t\topts.groupId,\n\t\t\t\t\ttoken,\n\t\t\t\t\topts.policy,\n\t\t\t\t\texpiresAt,\n\t\t\t\t\tnow,\n\t\t\t\t\topts.createdBy ?? null,\n\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\toperationId,\n\t\t\t\t\treviewedProjectSetDigest,\n\t\t\t\t\tdigest,\n\t\t\t\t\tclean(opts.inviterActorId),\n\t\t\t\t\tclean(opts.inviterDisplayName),\n\t\t\t\t\tclean(opts.inviterDeviceId),\n\t\t\t\t\tclean(opts.pendingPersonId),\n\t\t\t\t\topts.projectSummaries ? JSON.stringify(opts.projectSummaries) : null,\n\t\t\t\t\topts.projectIntent ? JSON.stringify(opts.projectIntent) : null,\n\t\t\t\t\toperationId ? \"pending\" : null,\n\t\t\t\t\tmetadata.inviteKind,\n\t\t\t\t\tmetadata.policyTeamId,\n\t\t\t\t\tmetadata.targetIdentityId,\n\t\t\t\t\tassignedIdentityId,\n\t\t\t\t\tmetadata.reviewedPreviewDigest,\n\t\t\t\t\tmetadata.reviewedIntentJson,\n\t\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (operationId) {\n\t\t\t\tconst existing = readOperationInvite();\n\t\t\t\tif (existing) return renewOperationInvite(existing);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t.get(inviteId);\n\t\treturn rowToRecord<CoordinatorInvite>(row);\n\t}\n\n\tasync getInviteByOperationId(\n\t\tgroupId: string,\n\t\toperationId: string,\n\t): Promise<CoordinatorInvite | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t FROM coordinator_invites WHERE group_id = ? AND operation_id = ?`)\n\t\t\t.get(groupId, operationId);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync getInviteByToken(token: string): Promise<CoordinatorInvite | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t FROM coordinator_invites\n\t\t\t\t WHERE (token_digest = ? OR token = ?)\n\t\t\t\t AND revoked_at IS NULL\n\t\t\t\t AND expires_at > ?`)\n\t\t\t.get(tokenDigest(token), token, new Date().toISOString());\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync getInviteByTokenForInspection(token: string): Promise<CoordinatorInvite | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t)\n\t\t\t.get(tokenDigest(token), token);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync inspectRecipientInvite(\n\t\topts: CoordinatorInspectRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteInspection | null> {\n\t\tconst invite = await this.getInviteByTokenForInspection(opts.token);\n\t\tif (!invite) return null;\n\t\tconst inspection = await inspectInvite(invite);\n\t\tif (!inspection) return null;\n\t\tif (invite.revoked_at) throw new Error(\"invite_invalid\");\n\t\tif (\n\t\t\t!invite.consumed_at &&\n\t\t\tnew Date(invite.expires_at) <= new Date(normalizeInviteExpiresAt(opts.now))\n\t\t) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tconst group = await this.getGroup(invite.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\treturn inspection;\n\t}\n\n\tprivate validateRecipientInviteParticipants(\n\t\tinvite: CoordinatorInvite,\n\t\topts: Pick<\n\t\t\tCoordinatorConsumeRecipientInviteInput,\n\t\t\t\"deviceId\" | \"publicKey\" | \"fingerprint\" | \"identityId\"\n\t\t>,\n\t): (string | null)[] {\n\t\tconst existingEnrollment = this.db\n\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t.get(invite.group_id, opts.deviceId) as CoordinatorEnrollment | undefined;\n\t\tif (\n\t\t\texistingEnrollment &&\n\t\t\t(existingEnrollment.public_key !== opts.publicKey ||\n\t\t\t\texistingEnrollment.fingerprint !== opts.fingerprint ||\n\t\t\t\t(existingEnrollment.identity_id !== null &&\n\t\t\t\t\texistingEnrollment.identity_id !== opts.identityId))\n\t\t)\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t// The immediate transaction keeps both participants unchanged through grant recovery.\n\t\tconst inviterEnrollment = invite.inviter_device_id\n\t\t\t? (this.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS} FROM enrolled_devices\n\t\t\t\tWHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.get(invite.group_id, invite.inviter_device_id) as CoordinatorEnrollment | undefined)\n\t\t\t: undefined;\n\t\tconst subjects = [\n\t\t\topts.deviceId,\n\t\t\tenrollmentRevocationKeyId(opts.publicKey),\n\t\t\tinvite.inviter_device_id ?? null,\n\t\t\tinviterEnrollment ? enrollmentRevocationKeyId(inviterEnrollment.public_key) : null,\n\t\t];\n\t\tconst revoked = this.db\n\t\t\t.prepare(`SELECT 1 WHERE ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`)\n\t\t\t.get(...subjects);\n\t\tif (revoked) throw new Error(\"device_revoked\");\n\t\treturn subjects;\n\t}\n\n\tprivate getRecipientInviteById(inviteId: string): CoordinatorInvite {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t.get(inviteId) as CoordinatorInvite;\n\t}\n\n\tprivate getRecipientInviteBootstrapGrant(grantId: string): CoordinatorBootstrapGrant | null {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id,\n\t\t\texpires_at, created_at, created_by, revoked_at FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t.get(grantId) as CoordinatorBootstrapGrant | undefined;\n\t\treturn row ?? null;\n\t}\n\n\tprivate assertRecipientInviteAuthorized(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\tsubjects: (string | null)[],\n\t): void {\n\t\tthis.validateRecipientInviteParticipants(invite, opts);\n\t\ttry {\n\t\t\tconst row = this.db\n\t\t\t\t.prepare(`SELECT (${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}) AS revoked,\n\t\t\t\t(${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}) AS owned`)\n\t\t\t\t.get(...subjects, ...subjects.slice(0, 2)) as\n\t\t\t\t| { revoked: number; owned: number }\n\t\t\t\t| undefined;\n\t\t\tif (\n\t\t\t\t!row ||\n\t\t\t\t(\"success\" in row && row.success === false) ||\n\t\t\t\t[row.revoked, row.owned].some((value) => value !== 0 && value !== 1)\n\t\t\t)\n\t\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t\tif (row.revoked === 1) throw new Error(\"device_revoked\");\n\t\t\tif (row.owned === 1) throw new Error(\"device_ownership_requires_verified_identity\");\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t}\n\n\tprivate recipientInviteAuthorization(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\tsubjects: (string | null)[],\n\t) {\n\t\treturn {\n\t\t\tsql: `NOT (${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\tOR ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL})`,\n\t\t\tvalues: [...subjects, ...subjects.slice(0, 2)],\n\t\t\tassertAuthorized: () => this.assertRecipientInviteAuthorized(invite, opts, subjects),\n\t\t};\n\t}\n\n\tasync consumeRecipientInvite(\n\t\tinput: CoordinatorConsumeRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteAcceptance> {\n\t\tconst opts = { ...input };\n\t\tconst consumedAt = normalizeInviteExpiresAt(opts.now);\n\t\tconst deviceDisplayName = opts.deviceDisplayName ?? null;\n\t\tvalidateRecipientOwnerInput(opts);\n\t\tconst preflightInvite = await this.getInviteByTokenForInspection(opts.token);\n\t\tconst preflightInspection = preflightInvite ? await inspectInvite(preflightInvite) : null;\n\t\tconst consistency = await prepareRecipientOwnerConsistency(\n\t\t\t{\n\t\t\t\t...this.schemaBackend,\n\t\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t\t},\n\t\t\topts,\n\t\t);\n\t\treturn this.db\n\t\t\t.transaction((): CoordinatorRecipientInviteAcceptance => {\n\t\t\t\tconst invite = this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t\t\t)\n\t\t\t\t\t.get(tokenDigest(opts.token), opts.token) as CoordinatorInvite | undefined;\n\t\t\t\tif (\n\t\t\t\t\t!invite ||\n\t\t\t\t\t!preflightInspection ||\n\t\t\t\t\tinvite.invite_id !== preflightInvite?.invite_id ||\n\t\t\t\t\tinvite.reviewed_intent_json !== preflightInvite.reviewed_intent_json ||\n\t\t\t\t\tinvite.reviewed_preview_digest !== preflightInvite.reviewed_preview_digest ||\n\t\t\t\t\tinvite.policy_team_id !== preflightInvite.policy_team_id ||\n\t\t\t\t\tinvite.target_identity_id !== preflightInvite.target_identity_id ||\n\t\t\t\t\tinvite.assigned_identity_id !== preflightInvite.assigned_identity_id ||\n\t\t\t\t\tpreflightInspection.kind !== opts.inviteKind ||\n\t\t\t\t\tinvite.revoked_at\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invite_invalid\");\n\t\t\t\t}\n\t\t\t\tconst group = this.db\n\t\t\t\t\t.prepare(\"SELECT archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t\t.get(invite.group_id) as { archived_at: string | null } | undefined;\n\t\t\t\tif (!group) throw new Error(\"group_not_found\");\n\t\t\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\t\t\tif (!invite.consumed_at && new Date(invite.expires_at) <= new Date(consumedAt)) {\n\t\t\t\t\tthrow new Error(\"invite_expired\");\n\t\t\t\t}\n\t\t\t\tif (fingerprintPublicKey(opts.publicKey) !== opts.fingerprint) {\n\t\t\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t\t\t}\n\t\t\t\tconst authoritativeIdentityId = recipientInviteAuthoritativeIdentityId(preflightInspection);\n\t\t\t\tif (authoritativeIdentityId !== opts.identityId) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\t\t\t\tconst sameBinding =\n\t\t\t\t\tinvite.bound_device_id === opts.deviceId &&\n\t\t\t\t\tinvite.bound_public_key === opts.publicKey &&\n\t\t\t\t\tinvite.bound_fingerprint === opts.fingerprint;\n\t\t\t\tif (invite.consumed_at && !sameBinding) throw new Error(\"invite_already_bound\");\n\t\t\t\tif (invite.consumed_at && invite.recipient_actor_id !== authoritativeIdentityId) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\t\t\t\tconst participantSubjects = this.validateRecipientInviteParticipants(invite, opts);\n\t\t\t\tconst authorization = this.recipientInviteAuthorization(invite, opts, participantSubjects);\n\t\t\t\tconst { sql: authorizationSql, values: authorizationValues } = authorization;\n\t\t\t\tthis.assertRecipientInviteAuthorized(invite, opts, participantSubjects);\n\t\t\t\tthis.assertRecipientOwnerPin(consistency);\n\t\t\t\tconst retained = consistency.retainedRecheck;\n\t\t\t\tconst changed = this.consumeRecipientOwnerToken(invite, opts, {\n\t\t\t\t\tauthorization,\n\t\t\t\t\tconsistency,\n\t\t\t\t\tconsumedAt,\n\t\t\t\t});\n\t\t\t\tlet pendingPin = retained;\n\t\t\t\tconst saved = this.getRecipientInviteById(invite.invite_id);\n\t\t\t\tif (\n\t\t\t\t\tsaved.bound_device_id !== opts.deviceId ||\n\t\t\t\t\tsaved.bound_public_key !== opts.publicKey ||\n\t\t\t\t\tsaved.bound_fingerprint !== opts.fingerprint\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invite_already_bound\");\n\t\t\t\t}\n\t\t\t\tif (saved.recipient_actor_id !== authoritativeIdentityId)\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\tif (changed === 1) {\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\trecipientOwnerWriteSql(\n\t\t\t\t\t\t\t\t`INSERT INTO enrolled_devices(\n\t\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t\t) SELECT ?, ?, ?, ?, ?, ?, 1, ?\n\t\t\t\t\tWHERE ${authorizationSql}\n\t\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\t\tpublic_key = excluded.public_key,\n\t\t\t\t\t\tfingerprint = excluded.fingerprint,\n\t\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\t\tdisplay_name = COALESCE(enrolled_devices.display_name, excluded.display_name),\n\t\t\t\t\t\tenabled = 1\n\t\t\t\t\tWHERE enrolled_devices.identity_id IS NULL\n\t\t\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id`,\n\t\t\t\t\t\t\t\tretained,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\t...retained.values,\n\t\t\t\t\t\t\tinvite.group_id,\n\t\t\t\t\t\t\topts.deviceId,\n\t\t\t\t\t\t\topts.publicKey,\n\t\t\t\t\t\t\topts.fingerprint,\n\t\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\t\tdeviceDisplayName,\n\t\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t\t...authorizationValues,\n\t\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tpendingPin = this.repairRecipientOwnerIdentity(invite, opts, {\n\t\t\t\t\t\tauthorization,\n\t\t\t\t\t\tconsistency,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tthis.assertRecipientInviteAuthorized(invite, opts, participantSubjects);\n\t\t\t\tthis.validateAcceptedRecipientOwner(invite, opts);\n\t\t\t\tlet bootstrapGrant: CoordinatorBootstrapGrant | null = null;\n\t\t\t\tif (\n\t\t\t\t\tpreflightInspection.kind === \"add_device\" &&\n\t\t\t\t\tinvite.inviter_device_id &&\n\t\t\t\t\t!invite.bootstrap_grant_id &&\n\t\t\t\t\tnew Date(invite.expires_at) > new Date(consumedAt)\n\t\t\t\t) {\n\t\t\t\t\tconst seed = this.db\n\t\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS} FROM enrolled_devices\n\t\t\t\t\t WHERE group_id = ? AND device_id = ? AND enabled = 1`)\n\t\t\t\t\t\t.get(invite.group_id, invite.inviter_device_id) as CoordinatorEnrollment | undefined;\n\t\t\t\t\tif (seed) {\n\t\t\t\t\t\tconst grantId = tokenUrlSafe(12);\n\t\t\t\t\t\tconst claimed = this.db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\trecipientOwnerWriteSql(\n\t\t\t\t\t\t\t\t\t`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\t\t trust_state = 'bootstrap_grant_created'\n\t\t\t\t\t\t\t\t WHERE invite_id = ? AND bootstrap_grant_id IS NULL AND ${authorizationSql}`,\n\t\t\t\t\t\t\t\t\tpendingPin,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run(...pendingPin.values, grantId, invite.invite_id, ...authorizationValues);\n\t\t\t\t\t\tif (claimed.changes === 1) {\n\t\t\t\t\t\t\tbootstrapGrant = insertBootstrapGrantSync(\n\t\t\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tgroupId: invite.group_id,\n\t\t\t\t\t\t\t\t\tseedDeviceId: seed.device_id,\n\t\t\t\t\t\t\t\t\tworkerDeviceId: opts.deviceId,\n\t\t\t\t\t\t\t\t\texpiresAt: invite.expires_at,\n\t\t\t\t\t\t\t\t\tcreatedBy: authoritativeIdentityId,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tgrantId,\n\t\t\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t\t\tauthorization,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst savedWithGrant = this.getRecipientInviteById(invite.invite_id);\n\t\t\t\tif (!bootstrapGrant && savedWithGrant.bootstrap_grant_id) {\n\t\t\t\t\tbootstrapGrant = this.getRecipientInviteBootstrapGrant(savedWithGrant.bootstrap_grant_id);\n\t\t\t\t}\n\t\t\t\t// Trigger effects belong to this transaction too; denial rolls back all acceptance writes.\n\t\t\t\tthis.assertRecipientInviteAuthorized(savedWithGrant, opts, participantSubjects);\n\t\t\t\tthis.assertRecipientOwnerPin(pendingPin);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: changed === 1 ? \"accepted\" : \"existing\",\n\t\t\t\t\tinvite: savedWithGrant,\n\t\t\t\t\treviewed_intent: preflightInspection.reviewed_intent,\n\t\t\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tprivate repairRecipientOwnerIdentity(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\toptions: { authorization: AuthLinkStatement; consistency: NegativeOwnerConsistency },\n\t): AuthLinkStatement {\n\t\tconst { authorization, consistency } = options;\n\t\tconst repaired = this.db\n\t\t\t.prepare(\n\t\t\t\trecipientOwnerWriteSql(\n\t\t\t\t\t`UPDATE enrolled_devices SET identity_id = ?\n\t\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL\n\t\t\tAND public_key = ? AND fingerprint = ? AND ${authorization.sql}`,\n\t\t\t\t\tconsistency,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.run(\n\t\t\t\t...consistency.values,\n\t\t\t\topts.identityId,\n\t\t\t\tinvite.group_id,\n\t\t\t\topts.deviceId,\n\t\t\t\topts.publicKey,\n\t\t\t\topts.fingerprint,\n\t\t\t\t...authorization.values,\n\t\t\t);\n\t\t// A zero-row repair does not consume the initial owner evidence.\n\t\treturn repaired.changes === 1 ? consistency.retainedRecheck : consistency;\n\t}\n\n\tprivate validateAcceptedRecipientOwner(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t) {\n\t\tconst enrollment = this.db\n\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`)\n\t\t\t.get(invite.group_id, opts.deviceId) as CoordinatorEnrollment | undefined;\n\t\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\t\tif (\n\t\t\tenrollment.public_key !== opts.publicKey ||\n\t\t\tenrollment.fingerprint !== opts.fingerprint ||\n\t\t\tenrollment.identity_id !== opts.identityId\n\t\t)\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t}\n\n\tprivate assertRecipientOwnerPin(\n\t\tpredicate: AuthLinkStatement | null,\n\t): asserts predicate is AuthLinkStatement {\n\t\tif (\n\t\t\t!predicate ||\n\t\t\t(this.db.prepare(predicate.sql).get(...predicate.values) as { matches: number } | undefined)\n\t\t\t\t?.matches !== 1\n\t\t)\n\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n\n\tprivate consumeRecipientOwnerToken(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\toptions: {\n\t\t\tauthorization: AuthLinkStatement;\n\t\t\tconsistency: AuthLinkStatement;\n\t\t\tconsumedAt: string;\n\t\t},\n\t) {\n\t\tif (invite.consumed_at) return 0;\n\t\tconst { authorization, consistency, consumedAt } = options;\n\t\treturn this.db\n\t\t\t.prepare(\n\t\t\t\trecipientOwnerWriteSql(\n\t\t\t\t\t`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n bound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?, recipient_display_name = ?, recipient_device_display_name = ?\n WHERE invite_id = ? AND consumed_at IS NULL AND revoked_at IS NULL AND expires_at > ? AND invite_kind = ?\n AND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id AND g.archived_at IS NULL)\n AND ${authorization.sql}`,\n\t\t\t\t\tconsistency,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.run(\n\t\t\t\t...consistency.values,\n\t\t\t\t`consumed:${invite.invite_id}`,\n\t\t\t\tconsumedAt,\n\t\t\t\topts.deviceId,\n\t\t\t\topts.publicKey,\n\t\t\t\topts.fingerprint,\n\t\t\t\topts.identityId,\n\t\t\t\topts.recipientDisplayName ?? null,\n\t\t\t\topts.deviceDisplayName ?? null,\n\t\t\t\tinvite.invite_id,\n\t\t\t\tconsumedAt,\n\t\t\t\topts.inviteKind,\n\t\t\t\t...authorization.values,\n\t\t\t).changes;\n\t}\n\n\tprivate prepareProjectInviteGuards(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeProjectInviteInput,\n\t) {\n\t\tconst current = this.db\n\t\t\t.prepare(`SELECT public_key FROM enrolled_devices\n\t\t\tWHERE group_id = ? AND device_id = ?`)\n\t\t\t.get(invite.group_id, opts.deviceId);\n\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(current ?? null);\n\t\tconst inviter = invite.inviter_device_id\n\t\t\t? (this.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS} FROM enrolled_devices\n\t\t\t\tWHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.get(invite.group_id, invite.inviter_device_id) as CoordinatorEnrollment | undefined)\n\t\t\t: undefined;\n\t\tconst incomingKeyId = enrollmentRevocationKeyId(opts.publicKey);\n\t\tconst evidence = projectInviteGuardEvidence(invite, opts, inviter ?? null, {\n\t\t\trecipient: incomingKeyId,\n\t\t\tinviter: inviter ? enrollmentRevocationKeyId(inviter.public_key) : null,\n\t\t});\n\t\tconst guard = legacyProjectInviteOwnershipEvidence(evidence, opts.deviceId, {\n\t\t\tincoming: incomingKeyId,\n\t\t\tcurrent: currentPublicKey === null ? null : enrollmentRevocationKeyId(currentPublicKey),\n\t\t});\n\t\ttry {\n\t\t\tconst row = this.db\n\t\t\t\t.prepare(`SELECT (${guard.revocationSql}) AS revoked,\n\t\t\t(${guard.ownershipSql}) AS owned`)\n\t\t\t\t.get(...guard.revocationValues, ...guard.ownershipValues) as\n\t\t\t\t| { revoked: number; owned: number }\n\t\t\t\t| undefined;\n\t\t\tif (!row || [row.revoked, row.owned].some((value) => value !== 0 && value !== 1))\n\t\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t\tif (row.revoked === 1) throw new Error(\"device_revoked\");\n\t\t\tif (row.owned === 1) throw new Error(\"device_ownership_requires_verified_identity\");\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t\tthis.validateRecipientInviteParticipants(invite, {\n\t\t\t...opts,\n\t\t\tidentityId: opts.recipientActorId,\n\t\t});\n\t\treturn guard;\n\t}\n\n\tprivate assertProjectInviteEligible(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeProjectInviteInput,\n\t\tguard: ReturnType<BetterSqliteCoordinatorStore[\"prepareProjectInviteGuards\"]>,\n\t): void {\n\t\tconst state = this.db\n\t\t\t.prepare(`SELECT i.revoked_at, g.group_id, g.archived_at\n\t\t\tFROM coordinator_invites i LEFT JOIN groups g ON g.group_id = i.group_id\n\t\t\tWHERE i.invite_id = ?`)\n\t\t\t.get(invite.invite_id) as\n\t\t\t| {\n\t\t\t\t\trevoked_at: string | null;\n\t\t\t\t\tgroup_id: string | null;\n\t\t\t\t\tarchived_at: string | null;\n\t\t\t }\n\t\t\t| undefined;\n\t\tif (!state || state.revoked_at) throw new Error(\"invite_invalid\");\n\t\tif (!state.group_id) throw new Error(\"group_not_found\");\n\t\tif (state.archived_at) throw new Error(\"group_archived\");\n\t\tthis.prepareProjectInviteGuards(invite, opts);\n\t\tconst eligible = this.db\n\t\t\t.prepare(`SELECT 1 WHERE ${guard.boundEligibilitySql}`)\n\t\t\t.get(...guard.boundEligibilityValues);\n\t\tif (!eligible) throw new Error(\"invite_acceptance_incomplete\");\n\t}\n\n\tasync consumeProjectInvite(\n\t\tinput: CoordinatorConsumeProjectInviteInput,\n\t): Promise<CoordinatorProjectInviteAcceptance> {\n\t\tconst opts = captureLegacyProjectInviteInput(input);\n\t\tconst consumedAt = normalizeInviteExpiresAt(opts.now);\n\t\treturn this.db\n\t\t\t.transaction(() => {\n\t\t\t\tlet invite = this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t\t\t)\n\t\t\t\t\t.get(tokenDigest(opts.token), opts.token) as CoordinatorInvite | undefined;\n\t\t\t\tif (!invite?.operation_id || !invite.project_intent_json || invite.revoked_at) {\n\t\t\t\t\tthrow new Error(\"invite_invalid\");\n\t\t\t\t}\n\t\t\t\tconst group = this.db\n\t\t\t\t\t.prepare(\"SELECT archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t\t.get(invite.group_id) as { archived_at: string | null } | undefined;\n\t\t\t\tif (!group) throw new Error(\"group_not_found\");\n\t\t\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\t\t\tif (invite.operation_id !== opts.operationId) throw new Error(\"invite_invalid\");\n\t\t\t\tif (fingerprintPublicKey(opts.publicKey) !== opts.fingerprint) {\n\t\t\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t\t\t}\n\t\t\t\tif (!invite.consumed_at && new Date(invite.expires_at) <= new Date(consumedAt)) {\n\t\t\t\t\tthrow new Error(\"invite_expired\");\n\t\t\t\t}\n\t\t\t\tconst sameBinding =\n\t\t\t\t\tinvite.bound_device_id === opts.deviceId &&\n\t\t\t\t\tinvite.bound_public_key === opts.publicKey &&\n\t\t\t\t\tinvite.bound_fingerprint === opts.fingerprint;\n\t\t\t\tif (invite.consumed_at && !sameBinding) throw new Error(\"invite_already_bound\");\n\t\t\t\tif (\n\t\t\t\t\tinvite.consumed_at &&\n\t\t\t\t\t(invite.recipient_actor_id !== opts.recipientActorId ||\n\t\t\t\t\t\tinvite.recipient_display_name !== opts.recipientDisplayName ||\n\t\t\t\t\t\tinvite.recipient_device_display_name !== opts.deviceDisplayName)\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\t\t\t\tconst guard = this.prepareProjectInviteGuards(invite, opts);\n\t\t\t\tlet accepted = false;\n\t\t\t\tif (!invite.consumed_at) {\n\t\t\t\t\tconst changed = this.db\n\t\t\t\t\t\t.prepare(`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n\t\t\t\t\t\tbound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n\t\t\t\t\t\trecipient_display_name = ?, recipient_device_display_name = ?,\n\t\t\t\t\t\ttrust_state = 'pending_inviter_device'\n\t\t\t\t\t\tWHERE invite_id = ? AND consumed_at IS NULL\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND g.archived_at IS NULL)\n\t\t\t\t\t\tAND ${guard.eligibilitySql}`)\n\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\t`consumed:${invite.invite_id}`,\n\t\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t\topts.deviceId,\n\t\t\t\t\t\t\topts.publicKey,\n\t\t\t\t\t\t\topts.fingerprint,\n\t\t\t\t\t\t\topts.recipientActorId,\n\t\t\t\t\t\t\topts.recipientDisplayName,\n\t\t\t\t\t\t\topts.deviceDisplayName,\n\t\t\t\t\t\t\tinvite.invite_id,\n\t\t\t\t\t\t\t...guard.eligibilityValues,\n\t\t\t\t\t\t);\n\t\t\t\t\taccepted = changed.changes === 1;\n\t\t\t\t\tinvite = this.db\n\t\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t\t\t\t.get(invite.invite_id) as CoordinatorInvite;\n\t\t\t\t\tif (!accepted) {\n\t\t\t\t\t\tconst currentGroup = this.db\n\t\t\t\t\t\t\t.prepare(\"SELECT archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t\t\t\t.get(invite.group_id) as { archived_at: string | null } | undefined;\n\t\t\t\t\t\tif (currentGroup?.archived_at) throw new Error(\"group_archived\");\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tinvite.bound_device_id !== opts.deviceId ||\n\t\t\t\t\t\t\tinvite.bound_public_key !== opts.publicKey ||\n\t\t\t\t\t\t\tinvite.bound_fingerprint !== opts.fingerprint\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(\"invite_already_bound\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tinvite.recipient_actor_id !== opts.recipientActorId ||\n\t\t\t\t\tinvite.recipient_display_name !== opts.recipientDisplayName ||\n\t\t\t\t\tinvite.recipient_device_display_name !== opts.deviceDisplayName\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\n\t\t\t\tif (accepted) {\n\t\t\t\t\tthis.assertProjectInviteEligible(invite, opts, guard);\n\t\t\t\t\tthis.enrollDeviceSync(invite.group_id, {\n\t\t\t\t\t\tdeviceId: opts.deviceId,\n\t\t\t\t\t\tpublicKey: opts.publicKey,\n\t\t\t\t\t\tfingerprint: opts.fingerprint,\n\t\t\t\t\t\tidentityId: opts.recipientActorId,\n\t\t\t\t\t\tdisplayName: opts.deviceDisplayName,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET identity_id = ?\n\t\t\t\t\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL AND enabled = 1\n\t\t\t\t\t\t\tAND public_key = ? AND fingerprint = ? AND ${guard.boundEligibilitySql}`)\n\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\topts.recipientActorId,\n\t\t\t\t\t\t\tinvite.group_id,\n\t\t\t\t\t\t\topts.deviceId,\n\t\t\t\t\t\t\topts.publicKey,\n\t\t\t\t\t\t\topts.fingerprint,\n\t\t\t\t\t\t\t...guard.boundEligibilityValues,\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst seed = invite.inviter_device_id\n\t\t\t\t\t? (this.db\n\t\t\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`)\n\t\t\t\t\t\t\t.get(invite.group_id, invite.inviter_device_id) as CoordinatorEnrollment | undefined)\n\t\t\t\t\t: undefined;\n\t\t\t\tlet bootstrapGrant: CoordinatorBootstrapGrant | null = null;\n\t\t\t\tif (\n\t\t\t\t\tseed &&\n\t\t\t\t\t!invite.bootstrap_grant_id &&\n\t\t\t\t\tnew Date(invite.expires_at) > new Date(consumedAt)\n\t\t\t\t) {\n\t\t\t\t\tconst grantId = tokenUrlSafe(12);\n\t\t\t\t\tconst claimed = this.db\n\t\t\t\t\t\t.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\t\tWHERE invite_id = ? AND bootstrap_grant_id IS NULL AND bound_device_id = ?\n\t\t\t\t\t\tAND ${guard.boundEligibilitySql}`)\n\t\t\t\t\t\t.run(grantId, invite.invite_id, opts.deviceId, ...guard.boundEligibilityValues);\n\t\t\t\t\tif (claimed.changes === 1) {\n\t\t\t\t\t\tbootstrapGrant = insertBootstrapGrantSync(\n\t\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tgroupId: invite.group_id,\n\t\t\t\t\t\t\t\tseedDeviceId: seed.device_id,\n\t\t\t\t\t\t\t\tworkerDeviceId: opts.deviceId,\n\t\t\t\t\t\t\t\texpiresAt: invite.expires_at,\n\t\t\t\t\t\t\t\tcreatedBy: invite.inviter_actor_id,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tgrantId,\n\t\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst saved = this.db\n\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t\t\t.get(invite.invite_id) as CoordinatorInvite;\n\t\t\t\tconst enrollment = this.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`)\n\t\t\t\t\t.get(invite.group_id, opts.deviceId) as CoordinatorEnrollment | undefined;\n\t\t\t\t// Trigger effects are inside the immediate transaction; denial rolls back every write.\n\t\t\t\tthis.assertProjectInviteEligible(saved, opts, guard);\n\t\t\t\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\t\t\t\tif (enrollment.identity_id !== opts.recipientActorId) {\n\t\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t\t}\n\t\t\t\tif (!bootstrapGrant && saved.bootstrap_grant_id) {\n\t\t\t\t\tbootstrapGrant =\n\t\t\t\t\t\t(this.db\n\t\t\t\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at,\n\t\t\t\t\t\t\tcreated_at, created_by, revoked_at FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t\t\t\t\t.get(saved.bootstrap_grant_id) as CoordinatorBootstrapGrant | undefined) ?? null;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tstatus: accepted ? (\"accepted\" as const) : (\"existing\" as const),\n\t\t\t\t\tinvite: saved,\n\t\t\t\t\tenrollment,\n\t\t\t\t\tseed_enrollment: seed ?? null,\n\t\t\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tasync listInvites(groupId: string): Promise<CoordinatorInvite[]> {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t FROM coordinator_invites WHERE group_id = ?\n\t\t\t\t ORDER BY created_at DESC`)\n\t\t\t.all(groupId)\n\t\t\t.map((row) => rowToRecord<CoordinatorInvite>(row));\n\t}\n\n\tasync createJoinRequest(\n\t\topts: CoordinatorCreateJoinRequestInput,\n\t): Promise<CoordinatorJoinRequest> {\n\t\tconst now = nowISO();\n\t\tconst requestId = tokenUrlSafe(12);\n\t\tthis.db\n\t\t\t.prepare(`INSERT INTO coordinator_join_requests(\n\t\t\t\t\trequest_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NULL, NULL)`)\n\t\t\t.run(\n\t\t\t\trequestId,\n\t\t\t\topts.groupId,\n\t\t\t\topts.deviceId,\n\t\t\t\topts.publicKey,\n\t\t\t\topts.fingerprint,\n\t\t\t\topts.displayName ?? null,\n\t\t\t\topts.token,\n\t\t\t\tnow,\n\t\t\t);\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t.get(requestId);\n\t\treturn rowToRecord<CoordinatorJoinRequest>(row);\n\t}\n\n\tasync listJoinRequests(groupId: string, status = \"pending\"): Promise<CoordinatorJoinRequest[]> {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t FROM coordinator_join_requests\n\t\t\t\t WHERE group_id = ? AND status = ?\n\t\t\t\t ORDER BY created_at ASC, device_id ASC`)\n\t\t\t.all(groupId, status)\n\t\t\t.map((row) => rowToRecord<CoordinatorJoinRequest>(row));\n\t}\n\n\tasync reviewJoinRequest(\n\t\topts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null> {\n\t\topts = {\n\t\t\t...opts,\n\t\t\tbootstrapGrant: opts.bootstrapGrant ? { ...opts.bootstrapGrant } : opts.bootstrapGrant,\n\t\t};\n\t\treturn this.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst row = this.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status,\n\t\t\t\t created_at, reviewed_at, reviewed_by\n\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t\t.get(opts.requestId) as (CoordinatorJoinRequest & { public_key: string }) | undefined;\n\t\t\t\tif (!row) return null;\n\t\t\t\tif (row.status !== \"pending\")\n\t\t\t\t\treturn { ...rowToRecord<CoordinatorJoinRequest>(row), _no_transition: true };\n\t\t\t\tconst bootstrapGrantRequest = normalizeCoordinatorBootstrapGrantRequest(\n\t\t\t\t\topts.bootstrapGrant,\n\t\t\t\t);\n\t\t\t\tconst reviewedAt = nowISO();\n\t\t\t\tconst nextStatus = opts.approved ? \"approved\" : \"denied\";\n\t\t\t\tlet bootstrapGrant: CoordinatorBootstrapGrant | null = null;\n\t\t\t\tconst guard = opts.approved\n\t\t\t\t\t? this.prepareJoinApprovalSync(row, bootstrapGrantRequest)\n\t\t\t\t\t: null;\n\t\t\t\tconst transition = this.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_join_requests SET status = ?, reviewed_at = ?, reviewed_by = ?\n\t\t\t\t\tWHERE request_id = ? AND status = 'pending'`)\n\t\t\t\t\t.run(nextStatus, reviewedAt, opts.reviewedBy ?? null, opts.requestId);\n\t\t\t\tif (transition.changes !== 1) throw new Error(\"join_review_incomplete\");\n\t\t\t\tif (guard) {\n\t\t\t\t\tbootstrapGrant = this.applyJoinApprovalSync(\n\t\t\t\t\t\trow,\n\t\t\t\t\t\tguard,\n\t\t\t\t\t\tbootstrapGrantRequest,\n\t\t\t\t\t\treviewedAt,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst updated = this.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t\t.get(opts.requestId);\n\t\t\t\tif (!updated) throw new Error(\"join_review_incomplete\");\n\t\t\t\treturn {\n\t\t\t\t\t...rowToRecord<CoordinatorJoinRequestReviewResult>(updated),\n\t\t\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tprivate prepareJoinApprovalSync(\n\t\trow: CoordinatorJoinRequest & { public_key: string },\n\t\tbootstrap: ReturnType<typeof normalizeCoordinatorBootstrapGrantRequest>,\n\t) {\n\t\tlet seed: CoordinatorEnrollment | null = null;\n\t\tif (bootstrap) {\n\t\t\tseed =\n\t\t\t\t(this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT * FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`,\n\t\t\t\t\t)\n\t\t\t\t\t.get(row.group_id, bootstrap.seedDeviceId) as CoordinatorEnrollment | undefined) ?? null;\n\t\t\tif (!seed) throw new Error(\"bootstrap grant seed device is not enrolled in the group.\");\n\t\t\tif (seed.device_id === row.device_id)\n\t\t\t\tthrow new Error(\"bootstrap grant seed and worker device ids must differ.\");\n\t\t}\n\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.get(row.group_id, row.device_id) ?? null,\n\t\t);\n\t\tconst guard = joinReviewGuardEvidence(\n\t\t\trow,\n\t\t\tseed,\n\t\t\t{\n\t\t\t\trecipient: enrollmentRevocationKeyId(row.public_key),\n\t\t\t\tseed: seed ? enrollmentRevocationKeyId(seed.public_key) : null,\n\t\t\t\tcurrent: currentPublicKey === null ? null : enrollmentRevocationKeyId(currentPublicKey),\n\t\t\t},\n\t\t\tcurrentPublicKey,\n\t\t);\n\t\tthis.assertJoinApprovalCurrentSync(guard);\n\t\treturn guard;\n\t}\n\n\tprivate assertJoinApprovalCurrentSync(guard: ReturnType<typeof joinReviewGuardEvidence>) {\n\t\tif (this.db.prepare(`SELECT 1 WHERE ${guard.revocationSql}`).get(...guard.revocationValues))\n\t\t\tthrow new Error(\"device_revoked\");\n\t\tlet owned: unknown;\n\t\ttry {\n\t\t\towned = this.db.prepare(`SELECT 1 WHERE ${guard.ownershipSql}`).get(...guard.ownershipValues);\n\t\t} catch {\n\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t}\n\t\tif (owned) throw new Error(\"device_ownership_requires_verified_identity\");\n\t\tif (!this.db.prepare(`SELECT 1 WHERE ${guard.eligibilitySql}`).get(...guard.eligibilityValues))\n\t\t\tthrow new Error(\"join_review_incomplete\");\n\t}\n\n\tprivate applyJoinApprovalSync(\n\t\trow: CoordinatorJoinRequest & { public_key: string },\n\t\tguard: ReturnType<typeof joinReviewGuardEvidence>,\n\t\tbootstrap: ReturnType<typeof normalizeCoordinatorBootstrapGrantRequest>,\n\t\treviewedAt: string,\n\t) {\n\t\tthis.assertJoinApprovalCurrentSync(guard);\n\t\tif (!this.db.prepare(`SELECT 1 WHERE ${guard.sourceSql}`).get(...guard.sourceValues))\n\t\t\tthrow new Error(\"join_review_incomplete\");\n\t\tthis.enrollDeviceSync(row.group_id, {\n\t\t\tdeviceId: row.device_id,\n\t\t\tfingerprint: row.fingerprint,\n\t\t\tpublicKey: row.public_key,\n\t\t\tdisplayName: (row.display_name ?? \"\").trim() || null,\n\t\t});\n\t\tthis.assertJoinApprovalCurrentSync(guard);\n\t\tconst grant = bootstrap\n\t\t\t? insertBootstrapGrantSync(this.db, {\n\t\t\t\t\t...bootstrap,\n\t\t\t\t\tgroupId: row.group_id,\n\t\t\t\t\tworkerDeviceId: row.device_id,\n\t\t\t\t})\n\t\t\t: null;\n\t\tthis.assertJoinApprovalCurrentSync(guard);\n\t\tconst complete = this.db\n\t\t\t.prepare(`SELECT 1 FROM coordinator_join_requests jr\n\t\t\tJOIN enrolled_devices e ON e.group_id = jr.group_id AND e.device_id = jr.device_id\n\t\t\tWHERE jr.request_id = ? AND jr.status = 'approved' AND jr.reviewed_at = ?\n\t\t\tAND e.public_key = ? AND e.fingerprint = ? AND e.enabled = 1`)\n\t\t\t.get(row.request_id, reviewedAt, row.public_key, row.fingerprint);\n\t\tif (!complete) throw new Error(\"join_review_incomplete\");\n\t\treturn grant;\n\t}\n\n\tasync createReciprocalApproval(\n\t\topts: CoordinatorCreateReciprocalApprovalInput,\n\t): Promise<CoordinatorReciprocalApproval> {\n\t\tconst groupId = String(opts.groupId ?? \"\").trim();\n\t\tconst requestingDeviceId = String(opts.requestingDeviceId ?? \"\").trim();\n\t\tconst requestedDeviceId = String(opts.requestedDeviceId ?? \"\").trim();\n\t\tconst hasExpectedIncomingRequestId = opts.expectedIncomingRequestId !== undefined;\n\t\tconst expectedIncomingRequestId = opts.expectedIncomingRequestId?.trim() ?? \"\";\n\t\tif (!groupId || !requestingDeviceId || !requestedDeviceId) {\n\t\t\tthrow new Error(\"groupId, requestingDeviceId, and requestedDeviceId are required.\");\n\t\t}\n\t\tif (requestingDeviceId === requestedDeviceId) {\n\t\t\tthrow new Error(\"requesting and requested device ids must differ.\");\n\t\t}\n\t\treturn this.db.transaction(() => {\n\t\t\tconst now = nowISO();\n\t\t\tif (hasExpectedIncomingRequestId) {\n\t\t\t\tconst result = this.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_reciprocal_approvals\n\t\t\t\t\t\t SET status = 'completed', resolved_at = ?\n\t\t\t\t\t\t WHERE request_id = ?\n\t\t\t\t\t\t AND group_id = ?\n\t\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t\t AND status = 'pending'`)\n\t\t\t\t\t.run(now, expectedIncomingRequestId, groupId, requestedDeviceId, requestingDeviceId);\n\t\t\t\tif (result.changes !== 1) {\n\t\t\t\t\tthrow new CoordinatorReciprocalApprovalRequestChangedError();\n\t\t\t\t}\n\t\t\t\tconst completed = this.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.get(expectedIncomingRequestId);\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t\t}\n\t\t\tconst existing = this.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ?\n\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC\n\t\t\t\t\t LIMIT 1`)\n\t\t\t\t.get(groupId, requestingDeviceId, requestedDeviceId);\n\t\t\tif (existing) {\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(existing);\n\t\t\t}\n\t\t\tconst reverse = this.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ?\n\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC\n\t\t\t\t\t LIMIT 1`)\n\t\t\t\t.get(groupId, requestedDeviceId, requestingDeviceId);\n\t\t\tif (reverse) {\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_reciprocal_approvals\n\t\t\t\t\t\t SET status = 'completed', resolved_at = ?\n\t\t\t\t\t\t WHERE request_id = ?`)\n\t\t\t\t\t.run(now, (reverse as CoordinatorReciprocalApproval).request_id);\n\t\t\t\tconst completed = this.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.get((reverse as CoordinatorReciprocalApproval).request_id);\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t\t}\n\t\t\tconst requestId = tokenUrlSafe(12);\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_reciprocal_approvals(\n\t\t\t\t\t\trequest_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t) VALUES (?, ?, ?, ?, 'pending', ?, NULL)`)\n\t\t\t\t.run(requestId, groupId, requestingDeviceId, requestedDeviceId, now);\n\t\t\tconst created = this.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t.get(requestId);\n\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(created);\n\t\t})();\n\t}\n\n\tasync createBootstrapGrant(\n\t\topts: CoordinatorCreateBootstrapGrantInput,\n\t): Promise<CoordinatorBootstrapGrant> {\n\t\tconst input = normalizeCoordinatorBootstrapGrantInput(opts);\n\t\ttry {\n\t\t\treturn this.db\n\t\t\t\t.transaction(() => {\n\t\t\t\t\tconst revoked = this.db.prepare(BOOTSTRAP_PARTICIPANTS_REVOKED_SQL);\n\t\t\t\t\tif (revoked.get(input.seedDeviceId, null, input.workerDeviceId, null)) {\n\t\t\t\t\t\tthrow new Error(\"device_revoked\");\n\t\t\t\t\t}\n\t\t\t\t\tconst source = this.db.prepare(BOOTSTRAP_PARTICIPANT_SOURCE_SQL);\n\t\t\t\t\tconst seed = captureBootstrapParticipantSource(\n\t\t\t\t\t\t(source.get(input.groupId, input.seedDeviceId) as\n\t\t\t\t\t\t\t| BootstrapParticipantSource\n\t\t\t\t\t\t\t| undefined) ?? null,\n\t\t\t\t\t);\n\t\t\t\t\tconst worker = captureBootstrapParticipantSource(\n\t\t\t\t\t\t(source.get(input.groupId, input.workerDeviceId) as\n\t\t\t\t\t\t\t| BootstrapParticipantSource\n\t\t\t\t\t\t\t| undefined) ?? null,\n\t\t\t\t\t);\n\t\t\t\t\tconst subjects = [\n\t\t\t\t\t\tinput.seedDeviceId,\n\t\t\t\t\t\tseed ? enrollmentRevocationKeyId(seed.public_key) : null,\n\t\t\t\t\t\tinput.workerDeviceId,\n\t\t\t\t\t\tworker ? enrollmentRevocationKeyId(worker.public_key) : null,\n\t\t\t\t\t];\n\t\t\t\t\tif (revoked.get(...subjects)) throw new Error(\"device_revoked\");\n\t\t\t\t\tconst values = bootstrapRawInsertValues(\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\t{ grantId: tokenUrlSafe(12), createdAt: nowISO() },\n\t\t\t\t\t\t{ seed, worker },\n\t\t\t\t\t\tsubjects,\n\t\t\t\t\t);\n\t\t\t\t\tconst row = this.db.prepare(BOOTSTRAP_RAW_INSERT_SQL).get(...values);\n\t\t\t\t\t// A trigger may revoke a participant during insertion; abort the entire transaction.\n\t\t\t\t\tif (revoked.get(...subjects)) throw new Error(\"device_revoked\");\n\t\t\t\t\tif (!row) throw new Error(\"bootstrap_grant_write_incomplete\");\n\t\t\t\t\treturn rowToRecord<CoordinatorBootstrapGrant>(row);\n\t\t\t\t})\n\t\t\t\t.immediate();\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"device_revoked\") throw error;\n\t\t\tthrow new Error(\"bootstrap_grant_write_incomplete\");\n\t\t}\n\t}\n\n\tprivate getScopeSync(scopeId: string): CoordinatorScope | null {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t FROM coordinator_scopes WHERE scope_id = ?`)\n\t\t\t.get(scopeId);\n\t\treturn row ? rowToRecord<CoordinatorScope>(row) : null;\n\t}\n\n\tprivate getScopeMembershipSync(\n\t\tscopeId: string,\n\t\tdeviceId: string,\n\t): CoordinatorScopeMembership | null {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t WHERE scope_id = ? AND device_id = ?`)\n\t\t\t.get(scopeId, deviceId);\n\t\treturn row ? rowToRecord<CoordinatorScopeMembership>(row) : null;\n\t}\n\n\tasync createScope(opts: CoordinatorCreateScopeInput): Promise<CoordinatorScope> {\n\t\tconst normalized = normalizeCoordinatorCreateScopeInput(opts);\n\t\tif (this.getScopeSync(normalized.scopeId)) throw new Error(\"scopeId already exists.\");\n\t\tconst now = nowISO();\n\t\tthis.db\n\t\t\t.prepare(`INSERT INTO coordinator_scopes(\n\t\t\t\t\tscope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t.run(\n\t\t\t\tnormalized.scopeId,\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t);\n\t\tconst scope = this.getScopeSync(normalized.scopeId);\n\t\tif (!scope) throw new Error(\"scope insert returned no row\");\n\t\treturn scope;\n\t}\n\n\tasync updateScope(opts: CoordinatorUpdateScopeInput): Promise<CoordinatorScope | null> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst existing = scopeId ? this.getScopeSync(scopeId) : null;\n\t\tif (!existing) return null;\n\t\tconst normalized = normalizeCoordinatorUpdateScopeInput(opts, existing);\n\t\tthis.db\n\t\t\t.prepare(`UPDATE coordinator_scopes\n\t\t\t\t SET label = ?,\n\t\t\t\t\t kind = ?,\n\t\t\t\t\t authority_type = ?,\n\t\t\t\t\t coordinator_id = ?,\n\t\t\t\t\t group_id = ?,\n\t\t\t\t\t manifest_issuer_device_id = ?,\n\t\t\t\t\t membership_epoch = ?,\n\t\t\t\t\t manifest_hash = ?,\n\t\t\t\t\t status = ?,\n\t\t\t\t\t updated_at = ?\n\t\t\t\t WHERE scope_id = ?`)\n\t\t\t.run(\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnowISO(),\n\t\t\t\tnormalized.scopeId,\n\t\t\t);\n\t\treturn this.getScopeSync(normalized.scopeId);\n\t}\n\n\tasync listScopes(opts: CoordinatorListScopesInput = {}): Promise<CoordinatorScope[]> {\n\t\tconst where: string[] = [];\n\t\tconst params: unknown[] = [];\n\t\tconst coordinatorId = clean(opts.coordinatorId);\n\t\tconst groupId = clean(opts.groupId);\n\t\tconst status = clean(opts.status);\n\t\tif (coordinatorId) {\n\t\t\twhere.push(\"coordinator_id = ?\");\n\t\t\tparams.push(coordinatorId);\n\t\t}\n\t\tif (groupId) {\n\t\t\twhere.push(\"group_id = ?\");\n\t\t\tparams.push(groupId);\n\t\t}\n\t\tif (status) {\n\t\t\twhere.push(\"status = ?\");\n\t\t\tparams.push(status);\n\t\t} else if (!opts.includeInactive) {\n\t\t\twhere.push(\"status = 'active'\");\n\t\t}\n\t\tconst whereSql = where.length ? `WHERE ${where.join(\" AND \")}` : \"\";\n\t\treturn this.db\n\t\t\t.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t FROM coordinator_scopes ${whereSql}\n\t\t\t\t ORDER BY coordinator_id ASC, group_id ASC, scope_id ASC`)\n\t\t\t.all(...params)\n\t\t\t.map((row) => rowToRecord<CoordinatorScope>(row));\n\t}\n\n\tasync getScopeAuthorization(\n\t\traw: CoordinatorScopeAuthorizationInput,\n\t): Promise<CoordinatorScopeAuthorizationResult> {\n\t\ttry {\n\t\t\tconst input = captureScopeAuthorizationInput(raw);\n\t\t\treturn this.db\n\t\t\t\t.transaction((): CoordinatorScopeAuthorizationResult => {\n\t\t\t\t\tconst scope = this.getScopeSync(input.scopeId);\n\t\t\t\t\tif (!scope) return { kind: \"rejected\", error: \"scope_not_found\" };\n\t\t\t\t\trequireScopeAuthorizationRecord(scope, SCOPE_FIELDS);\n\t\t\t\t\tconst error = scopeAuthorizationError(scope, input.groupId);\n\t\t\t\t\tif (error) return { kind: \"rejected\", error };\n\t\t\t\t\tconst group = this.db\n\t\t\t\t\t\t.prepare(\"SELECT archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t\t\t.get(input.groupId) as { archived_at: string | null } | undefined;\n\t\t\t\t\tif (!group) return { kind: \"rejected\", error: \"scope_source_mismatch\" };\n\t\t\t\t\tif (group.archived_at !== null) return { kind: \"rejected\", error: \"group_archived\" };\n\t\t\t\t\tconst members = this.captureScopeAuthorizationMembers(scope, input.groupId);\n\t\t\t\t\tconst current = this.db\n\t\t\t\t\t\t.prepare(READ_SCOPE_AUTHORIZATION_SQL)\n\t\t\t\t\t\t.get(JSON.stringify([scope]), JSON.stringify(members)) as\n\t\t\t\t\t\t| (CoordinatorScope & { members_json: string })\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\tif (!current) return { kind: \"rejected\", error: \"scope_authorization_unavailable\" };\n\t\t\t\t\trequireScopeAuthorizationRecord(current, SCOPE_FIELDS);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: \"authorized\",\n\t\t\t\t\t\tauthorizationVersion: 1,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t\tmembers: parseScopeAuthorizationMembers(current.members_json, members),\n\t\t\t\t\t};\n\t\t\t\t})\n\t\t\t\t.immediate();\n\t\t} catch {\n\t\t\treturn { kind: \"rejected\", error: \"scope_authorization_unavailable\" };\n\t\t}\n\t}\n\n\tprivate captureScopeAuthorizationMembers(\n\t\tscope: CoordinatorScope,\n\t\tgroupId: string,\n\t): CapturedScopeMember[] {\n\t\tconst memberships = this.db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT * FROM coordinator_scope_memberships WHERE scope_id = ? ORDER BY device_id ASC\",\n\t\t\t)\n\t\t\t.all(scope.scope_id) as CoordinatorScopeMembership[];\n\t\tconst captured: Array<Omit<CapturedScopeMember, \"keyId\">> = [];\n\t\tfor (const membership of memberships) {\n\t\t\trequireScopeAuthorizationRecord(membership, [\"status\"]);\n\t\t\tif (membership.status !== \"active\") continue;\n\t\t\trequireScopeAuthorizationRecord(membership, MEMBERSHIP_FIELDS);\n\t\t\tif (!isCurrentScopeMember(scope, membership)) continue;\n\t\t\tconst enrollment = this.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT ${ENROLLMENT_FIELDS.join(\", \")} FROM enrolled_devices WHERE group_id = ? AND device_id = ?`,\n\t\t\t\t)\n\t\t\t\t.get(groupId, membership.device_id) as CoordinatorEnrollment | undefined;\n\t\t\tif (!enrollment) continue;\n\t\t\trequireScopeAuthorizationRecord(enrollment, ENROLLMENT_FIELDS);\n\t\t\tif (enrollment.enabled !== 1) continue;\n\t\t\tcaptured.push({ membership: { ...membership }, enrollment: { ...enrollment } });\n\t\t}\n\t\t// Capture the complete source set before any hash hook can change another tuple.\n\t\treturn captured.flatMap((member) => {\n\t\t\tconst keyId = enrollmentRevocationKeyId(member.enrollment.public_key);\n\t\t\treturn keyId === null ? [] : [{ ...member, keyId }];\n\t\t});\n\t}\n\n\tasync grantScopeMembership(\n\t\topts: CoordinatorGrantScopeMembershipInput,\n\t): Promise<CoordinatorScopeMembership> {\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = grantMembershipEffectRequestJson(opts);\n\t\tconst grantScopeMembershipTransaction = () => {\n\t\t\tconst receipt = getMembershipEffectReceiptSync(this.db, effectId);\n\t\t\tif (receipt) {\n\t\t\t\tassertMatchingMembershipEffectReceipt(receipt, \"grant\", requestJson);\n\t\t\t\treturn membershipFromEffectReceipt(receipt);\n\t\t\t}\n\t\t\tconst scopeId = clean(opts.scopeId);\n\t\t\tconst deviceId = clean(opts.deviceId);\n\t\t\tconst scope = scopeId ? this.getScopeSync(scopeId) : null;\n\t\t\tif (!scope) throw new CoordinatorMembershipError(\"scope_not_found\");\n\t\t\tif (scope.status !== \"active\") throw new CoordinatorMembershipError(\"scope_inactive\");\n\t\t\tconst existing = scopeId && deviceId ? this.getScopeMembershipSync(scopeId, deviceId) : null;\n\t\t\tconst normalized = normalizeCoordinatorGrantScopeMembershipInput(opts, scope, existing);\n\t\t\tassertScopeMembershipDeviceEnrolled(this.db, normalized.groupId, normalized.deviceId);\n\t\t\tconst now = nowISO();\n\t\t\tconst result = this.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_scope_memberships(\n\t\t\t\t\t\tscope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t) VALUES (?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?)\n\t\t\t\t\tON CONFLICT(scope_id, device_id) DO UPDATE SET\n\t\t\t\t\t\trole = excluded.role,\n\t\t\t\t\t\tstatus = 'active',\n\t\t\t\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\t\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\t\t\t\tgroup_id = excluded.group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\t\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\t\t\t\tsigned_manifest_json = excluded.signed_manifest_json,\n\t\t\t\t\t\tupdated_at = excluded.updated_at\n\t\t\t\t\tWHERE excluded.membership_epoch > coordinator_scope_memberships.membership_epoch\n\t\t\t\t\t OR (\n\t\t\t\t\t\texcluded.membership_epoch = coordinator_scope_memberships.membership_epoch\n\t\t\t\t\t\tAND coordinator_scope_memberships.status != 'revoked'\n\t\t\t\t\t )`)\n\t\t\t\t.run(\n\t\t\t\t\tnormalized.scopeId,\n\t\t\t\t\tnormalized.deviceId,\n\t\t\t\t\tnormalized.role,\n\t\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\t\tnormalized.coordinatorId,\n\t\t\t\t\tnormalized.groupId,\n\t\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\t\tnormalized.manifestHash,\n\t\t\t\t\tnormalized.signedManifestJson,\n\t\t\t\t\tnow,\n\t\t\t\t);\n\t\t\tif (result.changes <= 0) {\n\t\t\t\tthrow new Error(\"scope membership grant was not applied.\");\n\t\t\t}\n\t\t\tconst row = this.db\n\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t WHERE scope_id = ? AND device_id = ?`)\n\t\t\t\t.get(normalized.scopeId, normalized.deviceId);\n\t\t\tconst membership = rowToRecord<CoordinatorScopeMembership>(row);\n\t\t\tinsertMembershipAuditSync(this.db, {\n\t\t\t\teffectId,\n\t\t\t\taction: \"grant\",\n\t\t\t\tcurrent: membership,\n\t\t\t\tprevious: existing,\n\t\t\t\tactorType: normalized.actorType,\n\t\t\t\tactorId: normalized.actorId,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t\tinsertMembershipEffectReceiptSync(this.db, {\n\t\t\t\teffectId,\n\t\t\t\taction: \"grant\",\n\t\t\t\trequestJson,\n\t\t\t\tapplied: true,\n\t\t\t\tscopeId: normalized.scopeId,\n\t\t\t\tdeviceId: normalized.deviceId,\n\t\t\t\tmembership,\n\t\t\t\tcreatedAt: now,\n\t\t\t});\n\t\t\treturn membership;\n\t\t};\n\t\treturn this.db.transaction(grantScopeMembershipTransaction).immediate();\n\t}\n\n\tasync revokeScopeMembership(opts: CoordinatorRevokeScopeMembershipInput): Promise<boolean> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tif (!scopeId || !deviceId) throw new Error(\"scopeId and deviceId are required.\");\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = revokeMembershipEffectRequestJson(opts);\n\t\treturn this.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst receipt = getMembershipEffectReceiptSync(this.db, effectId);\n\t\t\t\tif (receipt) {\n\t\t\t\t\tassertMatchingMembershipEffectReceipt(receipt, \"revoke\", requestJson);\n\t\t\t\t\treturn receipt.outcome_applied === 1;\n\t\t\t\t}\n\t\t\t\tconst membershipEpoch =\n\t\t\t\t\topts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\t\t\t\tconst requestedGroupId = clean(opts.groupId);\n\t\t\t\tconst scope = requestedGroupId ? this.getScopeSync(scopeId) : null;\n\t\t\t\tif (requestedGroupId && requestedGroupId !== scope?.group_id) {\n\t\t\t\t\tthrow new CoordinatorMembershipError(\"scope_group_mismatch\");\n\t\t\t\t}\n\t\t\t\tconst existing = this.getScopeMembershipSync(scopeId, deviceId);\n\t\t\t\tconst now = nowISO();\n\t\t\t\tif (!existing) {\n\t\t\t\t\tinsertMembershipEffectReceiptSync(this.db, {\n\t\t\t\t\t\teffectId,\n\t\t\t\t\t\taction: \"revoke\",\n\t\t\t\t\t\trequestJson,\n\t\t\t\t\t\tapplied: false,\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\tmembership: null,\n\t\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\t});\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (membershipEpoch != null && membershipEpoch <= existing.membership_epoch) {\n\t\t\t\t\tthrow new Error(\"membershipEpoch must increase on revoke.\");\n\t\t\t\t}\n\t\t\t\tconst result = this.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_scope_memberships\n\t\t\t\t\t\t SET status = 'revoked',\n\t\t\t\t\t\t\t membership_epoch = CASE WHEN ? IS NULL THEN membership_epoch + 1 ELSE ? END,\n\t\t\t\t\t\t\t manifest_hash = COALESCE(?, manifest_hash),\n\t\t\t\t\t\t\t signed_manifest_json = COALESCE(?, signed_manifest_json),\n\t\t\t\t\t\t\t updated_at = ?\n\t\t\t\t\t\t WHERE scope_id = ? AND device_id = ? AND membership_epoch = ? AND status = ?`)\n\t\t\t\t\t.run(\n\t\t\t\t\t\tmembershipEpoch,\n\t\t\t\t\t\tmembershipEpoch,\n\t\t\t\t\t\tclean(opts.manifestHash),\n\t\t\t\t\t\tclean(opts.signedManifestJson),\n\t\t\t\t\t\tnow,\n\t\t\t\t\t\tscopeId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\texisting.membership_epoch,\n\t\t\t\t\t\texisting.status,\n\t\t\t\t\t);\n\t\t\t\tif (result.changes <= 0) return false;\n\t\t\t\tconst membership = this.getScopeMembershipSync(scopeId, deviceId);\n\t\t\t\tif (!membership) throw new Error(\"scope membership revoke was not applied.\");\n\t\t\t\tinsertMembershipAuditSync(this.db, {\n\t\t\t\t\teffectId,\n\t\t\t\t\taction: \"revoke\",\n\t\t\t\t\tcurrent: membership,\n\t\t\t\t\tprevious: existing,\n\t\t\t\t\tactorType: clean(opts.actorType),\n\t\t\t\t\tactorId: clean(opts.actorId),\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t});\n\t\t\t\tinsertMembershipEffectReceiptSync(this.db, {\n\t\t\t\t\teffectId,\n\t\t\t\t\taction: \"revoke\",\n\t\t\t\t\trequestJson,\n\t\t\t\t\tapplied: true,\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tmembership,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t})\n\t\t\t.immediate();\n\t}\n\n\tasync listScopeMemberships(\n\t\tscopeId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedScopeId = clean(scopeId);\n\t\tif (!normalizedScopeId) throw new Error(\"scopeId is required.\");\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn this.db\n\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t WHERE scope_id = ? ${statusWhere}\n\t\t\t\t ORDER BY device_id ASC`)\n\t\t\t.all(normalizedScopeId)\n\t\t\t.map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listDeviceScopeMemberships(\n\t\tdeviceId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedDeviceId = clean(deviceId);\n\t\tif (!normalizedDeviceId) throw new Error(\"deviceId is required.\");\n\t\t// Served by idx_coordinator_scope_memberships_device_status.\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn this.db\n\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t WHERE device_id = ? ${statusWhere}\n\t\t\t\t ORDER BY scope_id ASC`)\n\t\t\t.all(normalizedDeviceId)\n\t\t\t.map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listScopeMembershipAuditEvents(\n\t\topts: CoordinatorListScopeMembershipAuditInput,\n\t): Promise<CoordinatorScopeMembershipAuditEvent[]> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tif (!scopeId) throw new Error(\"scopeId is required.\");\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tconst limit = normalizeCoordinatorAuditLimit(opts.limit);\n\t\tconst where = deviceId ? \"scope_id = ? AND device_id = ?\" : \"scope_id = ?\";\n\t\tconst params = deviceId ? [scopeId, deviceId, limit] : [scopeId, limit];\n\t\treturn this.db\n\t\t\t.prepare(`SELECT event_id, effect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t\t\t FROM coordinator_scope_membership_audit_log\n\t\t\t\t WHERE ${where}\n\t\t\t\t ORDER BY event_id ASC\n\t\t\t\t LIMIT ?`)\n\t\t\t.all(...params)\n\t\t\t.map((row) => rowToRecord<CoordinatorScopeMembershipAuditEvent>(row));\n\t}\n\n\tasync getBootstrapGrant(grantId: string): Promise<CoordinatorBootstrapGrant | null> {\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t.get(grantId);\n\t\treturn row ? rowToRecord<CoordinatorBootstrapGrant>(row) : null;\n\t}\n\n\tasync getBootstrapGrantAuthorization(\n\t\traw: CoordinatorBootstrapGrantAuthorizationInput,\n\t): Promise<CoordinatorBootstrapGrantAuthorizationResult> {\n\t\ttry {\n\t\t\tconst input = captureBootstrapAuthorizationInput(raw);\n\t\t\treturn this.db\n\t\t\t\t.transaction(() => {\n\t\t\t\t\tconst source = this.db.prepare(BOOTSTRAP_AUTHORIZATION_SOURCE_SQL).get(input.grantId) as\n\t\t\t\t\t\t| BootstrapAuthorizationRow\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\tconst sourceError = bootstrapAuthorizationSourceError(input, source ?? null);\n\t\t\t\t\tif (sourceError) return rejectBootstrapAuthorization(sourceError);\n\t\t\t\t\tif (!source) return rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\t\t\t\t\tconst captured = { ...source };\n\t\t\t\t\tconst decision = bootstrapAuthorizationDecision(input, captured, {\n\t\t\t\t\t\tseed:\n\t\t\t\t\t\t\tcaptured.seed_enrollment_public_key === null\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: enrollmentRevocationKeyId(captured.seed_enrollment_public_key),\n\t\t\t\t\t\tworker:\n\t\t\t\t\t\t\tcaptured.worker_enrollment_public_key === null\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: enrollmentRevocationKeyId(captured.worker_enrollment_public_key),\n\t\t\t\t\t});\n\t\t\t\t\tconst current = this.db.prepare(decision.sql).get(...decision.values) as\n\t\t\t\t\t\t| BootstrapAuthorizationRow\n\t\t\t\t\t\t| undefined;\n\t\t\t\t\treturn bootstrapAuthorizationResult(current ?? null);\n\t\t\t\t})\n\t\t\t\t.immediate();\n\t\t} catch {\n\t\t\treturn rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\t\t}\n\t}\n\n\tasync listBootstrapGrants(groupId: string): Promise<CoordinatorBootstrapGrant[]> {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t FROM coordinator_bootstrap_grants WHERE group_id = ?\n\t\t\t\t ORDER BY created_at DESC, grant_id DESC`)\n\t\t\t.all(groupId)\n\t\t\t.map((row) => rowToRecord<CoordinatorBootstrapGrant>(row));\n\t}\n\n\tasync revokeBootstrapGrant(grantId: string, revokedAt = nowISO()): Promise<boolean> {\n\t\tconst result = this.db\n\t\t\t.prepare(`UPDATE coordinator_bootstrap_grants\n\t\t\t\t SET revoked_at = COALESCE(revoked_at, ?)\n\t\t\t\t WHERE grant_id = ?`)\n\t\t\t.run(revokedAt, grantId);\n\t\treturn result.changes > 0;\n\t}\n\n\tasync listReciprocalApprovals(\n\t\topts: CoordinatorListReciprocalApprovalsInput,\n\t): Promise<CoordinatorReciprocalApproval[]> {\n\t\tconst directionColumn =\n\t\t\topts.direction === \"incoming\" ? \"requested_device_id\" : \"requesting_device_id\";\n\t\tconst status = String(opts.status ?? \"pending\").trim() || \"pending\";\n\t\treturn this.db\n\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t WHERE group_id = ? AND ${directionColumn} = ? AND status = ?\n\t\t\t\t ORDER BY created_at ASC, request_id ASC`)\n\t\t\t.all(opts.groupId, opts.deviceId, status)\n\t\t\t.map((row) => rowToRecord<CoordinatorReciprocalApproval>(row));\n\t}\n\n\tasync createLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t): Promise<CoordinatorLegacyTeamCompletionWriteResult> {\n\t\tconst [normalizedGroupId] = normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]);\n\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\tconst group = await this.getGroup(normalizedGroupId);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tconst manifestJson = canonicalCoordinatorLegacyTeamCompletionManifestJson(manifest);\n\t\tconst normalized = JSON.parse(manifestJson) as CoordinatorLegacyTeamCompletionManifestV1;\n\t\trequireCoordinatorLegacyTeamCompletionTeamBinding(normalized);\n\t\tconst existing = this.readStoredLegacyCompletion(normalizedGroupId, normalized.candidate_ref);\n\t\tif (existing)\n\t\t\treturn legacyCompletionWriteResult(existing.manifest_json, manifestJson, \"existing\");\n\t\tconst coordinatorId = await this.requireLegacyTeamCompletionSources(\n\t\t\tnormalizedGroupId,\n\t\t\tnormalized,\n\t\t\tmanifestJson,\n\t\t);\n\t\tconst ownerProof = await this.prepareLegacyTeamCompletionOwnerProof(\n\t\t\tnormalizedGroupId,\n\t\t\tmanifestJson,\n\t\t);\n\t\tconst { result, stored, denial } = this.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst result = this.db\n\t\t\t\t\t.prepare(`${LEGACY_OWNER_INPUT_SQL}${ownerProof.ctes}\n\t\t\tINSERT OR IGNORE INTO coordinator_legacy_team_completions(\n\t\t\t\tgroup_id, candidate_ref, manifest_version, manifest_json, completed_at, created_at\n\t\t\t) SELECT ?, ?, ?, ?, ?, ?\n\t\t\t FROM groups\n\t\t\t WHERE group_id = ? AND archived_at IS NULL\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1\n\t\t\t FROM json_each(?, '$.project_mappings') AS requested\n\t\t\t LEFT JOIN coordinator_scopes AS scope\n\t\t\t ON scope.scope_id = json_extract(requested.value, '$.scope_id')\n\t\t\t AND scope.authority_type = 'coordinator'\n\t\t\t AND scope.coordinator_id = ?\n\t\t\t AND scope.group_id = ?\n\t\t\t\t AND scope.status = 'active'\n\t\t\t WHERE scope.scope_id IS NULL\n\t\t\t )\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1 FROM enrolled_devices AS enrolled\n\t\t\t WHERE enrolled.group_id = ?\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n\t\t\t WHERE json_extract(requested.value, '$.device_id') = enrolled.device_id\n\t\t\t AND json_extract(requested.value, '$.key_fingerprint') = enrolled.fingerprint\n\t\t\t AND json_extract(requested.value, '$.enabled') = enrolled.enabled\n\t\t\t )\n\t\t\t )\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n\t\t\t WHERE json_extract(requested.value, '$.decision') = 'included'\n\t\t\t AND NOT EXISTS (\n\t\t\t SELECT 1 FROM enrolled_devices AS enrolled\n\t\t\t WHERE enrolled.group_id = ?\n\t\t\t AND enrolled.device_id = json_extract(requested.value, '$.device_id')\n\t\t\t AND enrolled.fingerprint = json_extract(requested.value, '$.key_fingerprint')\n\t\t\t AND enrolled.enabled = 1\n\t\t\t )\n\t\t\t ) AND ${LEGACY_OWNER_SOURCE_CURRENT_SQL}\n\t\t\t\t AND (${ownerProof.currentSql}) AND (${ownerProof.compatibleSql})`)\n\t\t\t\t\t.run(\n\t\t\t\t\t\t...ownerProof.values,\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t\tnormalized.candidate_ref,\n\t\t\t\t\t\tnormalized.version,\n\t\t\t\t\t\tmanifestJson,\n\t\t\t\t\t\tnormalized.completed_at,\n\t\t\t\t\t\tnowISO(),\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t\tmanifestJson,\n\t\t\t\t\t\tcoordinatorId,\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t\tmanifestJson,\n\t\t\t\t\t\tmanifestJson,\n\t\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\t);\n\t\t\t\tconst stored = this.readStoredLegacyCompletion(normalizedGroupId, normalized.candidate_ref);\n\t\t\t\tconst denial = stored\n\t\t\t\t\t? null\n\t\t\t\t\t: (this.db.prepare(ownerProof.denialSql).get(...ownerProof.values) as { denial: string });\n\t\t\t\treturn { result, stored, denial };\n\t\t\t})\n\t\t\t.immediate();\n\t\tif (!stored) {\n\t\t\tawait this.requireLegacyTeamCompletionSources(normalizedGroupId, normalized, manifestJson);\n\t\t\tif (denial?.denial === \"completion_conflict\") {\n\t\t\t\tthrow new CoordinatorLegacyTeamCompletionConflictError();\n\t\t\t}\n\t\t\tthrow new Error(\"completion_manifest_unavailable\");\n\t\t}\n\t\treturn legacyCompletionWriteResult(\n\t\t\tstored.manifest_json,\n\t\t\tmanifestJson,\n\t\t\tresult.changes === 1 ? \"created\" : \"existing\",\n\t\t);\n\t}\n\n\tprivate readStoredLegacyCompletion(groupId: string, candidateRef: string) {\n\t\treturn this.db\n\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t.get(groupId, candidateRef) as { manifest_json: string } | undefined;\n\t}\n\n\tprivate async prepareLegacyTeamCompletionOwnerProof(groupId: string, manifestJson: string) {\n\t\tconst keyMetadata = await legacyOwnerKeyMetadata(\n\t\t\tthis.db.prepare(LEGACY_OWNER_KEYS_SQL).all(manifestJson, groupId) as { public_key: string }[],\n\t\t);\n\t\tconst proof = legacyCompletionOwnerProofSql(\n\t\t\tawait captureLegacyCompletionOwnerProof({\n\t\t\t\tbackend: {\n\t\t\t\t\t...this.schemaBackend,\n\t\t\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\t\tthis.db.prepare(sql).all(...values) as T[],\n\t\t\t\t},\n\t\t\t\tgroupId,\n\t\t\t\tmanifestJson,\n\t\t\t\tkeyMetadata,\n\t\t\t}),\n\t\t);\n\t\treturn {\n\t\t\t...proof,\n\t\t\tvalues: [manifestJson, groupId, keyMetadata, ...proof.values],\n\t\t\tdenialSql: `${LEGACY_OWNER_INPUT_SQL}${proof.ctes}\n\t\t SELECT CASE WHEN NOT (${LEGACY_OWNER_SOURCE_CURRENT_SQL}) OR NOT (${proof.currentSql})\n\t\t THEN 'completion_manifest_unavailable'\n\t\t WHEN NOT (${proof.compatibleSql}) THEN 'completion_conflict'\n\t\t ELSE 'completion_manifest_unavailable' END AS denial`,\n\t\t};\n\t}\n\n\tprivate async requireLegacyTeamCompletionSources(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t\tmanifestJson: string,\n\t): Promise<string | null> {\n\t\tconst group = await this.getGroup(groupId);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tconst bindings = this.db\n\t\t\t.prepare(`SELECT DISTINCT requested.scope_id, scope.authority_type,\n\t\t\t\tscope.coordinator_id, scope.group_id, scope.status\n\t\t\t FROM (SELECT json_extract(value, '$.scope_id') AS scope_id\n\t\t\t\tFROM json_each(?, '$.project_mappings')) AS requested\n\t\t\t LEFT JOIN coordinator_scopes AS scope ON scope.scope_id = requested.scope_id`)\n\t\t\t.all(manifestJson) as CoordinatorLegacyTeamCompletionScopeBinding[];\n\t\treturn requireCoordinatorLegacyTeamCompletionScopeBindings(manifest, groupId, bindings);\n\t}\n\n\tasync getLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tcandidateRef: string,\n\t): Promise<CoordinatorLegacyTeamCompletionManifestV1 | null> {\n\t\tconst [normalizedGroupId] = normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]);\n\t\tconst normalizedCandidateRef =\n\t\t\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef(candidateRef);\n\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\tconst row = this.db\n\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t.get(normalizedGroupId, normalizedCandidateRef) as { manifest_json: string } | undefined;\n\t\treturn row\n\t\t\t? normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json))\n\t\t\t: null;\n\t}\n\n\tasync listLegacyTeamCompletions(\n\t\tgroupIds: string[],\n\t): Promise<CoordinatorLegacyTeamCompletionRecord[]> {\n\t\tconst normalizedGroupIds = normalizeCoordinatorLegacyTeamCompletionGroupIds(groupIds);\n\t\tif (normalizedGroupIds.length === 0) return [];\n\t\tconst placeholders = normalizedGroupIds.map(() => \"?\").join(\", \");\n\t\tconst stats = this.db\n\t\t\t.prepare(`SELECT\n\t\t\t\tCOUNT(*) AS record_count,\n\t\t\t\tCOALESCE(SUM(\n\t\t\t\t\tLENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))\n\t\t\t\t), 0) AS batch_bytes,\n\t\t\t\tCOALESCE(MAX(LENGTH(CAST(manifest_json AS BLOB))), 0) AS max_manifest_bytes\n\t\t\tFROM coordinator_legacy_team_completions\n\t\t\tWHERE group_id IN (${placeholders})`)\n\t\t\t.get(...normalizedGroupIds) as {\n\t\t\trecord_count: number;\n\t\t\tbatch_bytes: number;\n\t\t\tmax_manifest_bytes: number;\n\t\t};\n\t\tif (\n\t\t\tstats.record_count > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS ||\n\t\t\tstats.batch_bytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES ||\n\t\t\tstats.max_manifest_bytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES\n\t\t) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tconst rows = this.db\n\t\t\t.prepare(`WITH completion_stats AS (\n\t\t\t\tSELECT\n\t\t\t\t\tCOUNT(*) AS record_count,\n\t\t\t\t\tCOALESCE(SUM(\n\t\t\t\t\t\tLENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))\n\t\t\t\t\t), 0) AS batch_bytes,\n\t\t\t\t\tCOALESCE(MAX(LENGTH(CAST(manifest_json AS BLOB))), 0) AS max_manifest_bytes\n\t\t\t\tFROM coordinator_legacy_team_completions\n\t\t\t\tWHERE group_id IN (${placeholders})\n\t\t\t)\n\t\t\tSELECT completions.group_id, completions.manifest_json\n\t\t\tFROM coordinator_legacy_team_completions AS completions\n\t\t\tCROSS JOIN completion_stats\n\t\t\tWHERE completions.group_id IN (${placeholders})\n\t\t\t\t AND completion_stats.record_count <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS}\n\t\t\t\t AND completion_stats.batch_bytes <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES}\n\t\t\t\t AND completion_stats.max_manifest_bytes <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t AND LENGTH(completions.manifest_json) <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t AND LENGTH(CAST(completions.manifest_json AS BLOB)) <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\tORDER BY completions.group_id, completions.completed_at, completions.candidate_ref\n\t\t\t\tLIMIT ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS + 1}`)\n\t\t\t.all(...normalizedGroupIds, ...normalizedGroupIds) as Array<{\n\t\t\tgroup_id: string;\n\t\t\tmanifest_json: string;\n\t\t}>;\n\t\tif (rows.length === 0 && stats.record_count > 0) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tif (rows.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tconst batchBytes = rows.reduce(\n\t\t\t(total, row) =>\n\t\t\t\ttotal + Buffer.byteLength(row.group_id) + Buffer.byteLength(row.manifest_json),\n\t\t\t0,\n\t\t);\n\t\tif (batchBytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\treturn rows.map((row) => ({\n\t\t\tgroup_id: row.group_id,\n\t\t\tmanifest: normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json)),\n\t\t}));\n\t}\n\n\tasync captureAuthControllerLegacyHistory(input: ControllerHistoryInput) {\n\t\treturn captureControllerHistory(\n\t\t\tinput,\n\t\t\tasync <T>(sql: string, values: string[]) => this.db.prepare(sql).all(...values) as T[],\n\t\t);\n\t}\n\n\tasync upsertPresence(opts: CoordinatorUpsertPresenceInput): Promise<CoordinatorPresenceRecord> {\n\t\tconst now = new Date();\n\t\tconst expiresAt = new Date(now.getTime() + opts.ttlS * 1000).toISOString();\n\t\tconst normalized = mergeCoordinatorAddresses([], opts.addresses);\n\t\tthis.db\n\t\t\t.prepare(`INSERT INTO presence_records(group_id, device_id, addresses_json, last_seen_at, expires_at, capabilities_json)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)\n\t\t\t\t ON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\taddresses_json = excluded.addresses_json,\n\t\t\t\t\tlast_seen_at = excluded.last_seen_at,\n\t\t\t\t\texpires_at = excluded.expires_at,\n\t\t\t\t\tcapabilities_json = excluded.capabilities_json`)\n\t\t\t.run(\n\t\t\t\topts.groupId,\n\t\t\t\topts.deviceId,\n\t\t\t\tJSON.stringify(normalized),\n\t\t\t\tnow.toISOString(),\n\t\t\t\texpiresAt,\n\t\t\t\tJSON.stringify(opts.capabilities ?? {}),\n\t\t\t);\n\t\treturn {\n\t\t\tgroup_id: opts.groupId,\n\t\t\tdevice_id: opts.deviceId,\n\t\t\taddresses: normalized,\n\t\t\texpires_at: expiresAt,\n\t\t};\n\t}\n\n\tasync listGroupPeers(\n\t\tgroupId: string,\n\t\trequestingDeviceId: string,\n\t): Promise<CoordinatorPeerRecord[]> {\n\t\ttry {\n\t\t\treturn this.readGroupPeers(groupId, requestingDeviceId);\n\t\t} catch {\n\t\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t\t}\n\t}\n\n\tprivate readGroupPeers(groupId: string, requestingDeviceId: string): CoordinatorPeerRecord[] {\n\t\tconst now = new Date();\n\t\tconst rows = this.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst captured = capturePeerEnrollments(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(CAPTURE_PEER_ENROLLMENTS_SQL)\n\t\t\t\t\t\t.all(groupId, requestingDeviceId) as CapturedPeerEnrollment[],\n\t\t\t\t);\n\t\t\t\tconst candidates = captured.map((row) => ({\n\t\t\t\t\t...row,\n\t\t\t\t\tkeyId: enrollmentRevocationKeyId(row.public_key),\n\t\t\t\t}));\n\t\t\t\treturn requirePeerDiscoveryRows(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(READ_CURRENT_PEERS_SQL)\n\t\t\t\t\t\t.all(JSON.stringify(candidates), groupId, requestingDeviceId),\n\t\t\t\t);\n\t\t\t})\n\t\t\t.immediate();\n\t\treturn rows.map((row) => {\n\t\t\tconst expiresRaw = String(row.expires_at ?? \"\").trim();\n\t\t\tlet stale = true;\n\t\t\tif (expiresRaw) {\n\t\t\t\tconst expiresAt = new Date(expiresRaw);\n\t\t\t\tstale = Number.isNaN(expiresAt.getTime()) || expiresAt <= now;\n\t\t\t}\n\t\t\tconst addresses = stale\n\t\t\t\t? []\n\t\t\t\t: mergeCoordinatorAddresses(\n\t\t\t\t\t\t[],\n\t\t\t\t\t\tJSON.parse((row.addresses_json as string) || \"[]\") as string[],\n\t\t\t\t\t);\n\t\t\treturn {\n\t\t\t\tdevice_id: String(row.device_id ?? \"\"),\n\t\t\t\tpublic_key: String(row.public_key ?? \"\"),\n\t\t\t\tfingerprint: String(row.fingerprint ?? \"\"),\n\t\t\t\tdisplay_name: (row.display_name as string | null) ?? null,\n\t\t\t\taddresses,\n\t\t\t\tlast_seen_at: (row.last_seen_at as string | null) ?? null,\n\t\t\t\texpires_at: (row.expires_at as string | null) ?? null,\n\t\t\t\tstale,\n\t\t\t\tcapabilities: JSON.parse((row.capabilities_json as string) || \"{}\") as Record<\n\t\t\t\t\tstring,\n\t\t\t\t\tunknown\n\t\t\t\t>,\n\t\t\t} satisfies CoordinatorPeerRecord;\n\t\t});\n\t}\n}\n","/**\n * Sync authentication: request signing, verification, and nonce management.\n *\n * Uses Node's native Ed25519 crypto for sign/verify and SHA-256 canonical\n * request hashing. No ssh-keygen shelling.\n */\n\nimport {\n\tcreateHash,\n\tcreatePrivateKey,\n\tcreatePublicKey,\n\trandomBytes,\n\tsign,\n\tverify,\n} from \"node:crypto\";\nimport { lt } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { Database } from \"./db.js\";\nimport * as schema from \"./schema.js\";\nimport { DEFAULT_TIME_WINDOW_S } from \"./sync-auth-constants.js\";\nimport { loadPrivateKey } from \"./sync-identity.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Signature version. v1 = SSHSIG format (ssh-keygen era), v2 = raw Ed25519.\n *\n * v2 is a breaking change: Python peers using `ssh-keygen -Y verify` cannot\n * verify v2 signatures. Once all peers run the TS runtime, v1 support can\n * be removed. During migration, the verifier accepts both versions.\n */\nexport const SIGNATURE_VERSION = \"v2\";\n\n/** Direct-peer-only recipient-bound signature version. */\nexport const DIRECT_PEER_SIGNATURE_VERSION = \"v3\";\n\nfunction isValidRecipientId(recipientId: string): boolean {\n\treturn (\n\t\tBoolean(recipientId.trim()) && recipientId === recipientId.trim() && !/[\\r\\n]/.test(recipientId)\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Canonical request\n// ---------------------------------------------------------------------------\n\n/**\n * Build a canonical request buffer for signing/verification.\n *\n * SHA-256 hashes the body, then joins method/path/timestamp/nonce/bodyHash\n * with newlines and returns the UTF-8 encoded result.\n */\nexport function buildCanonicalRequest(\n\tmethod: string,\n\tpathWithQuery: string,\n\ttimestamp: string,\n\tnonce: string,\n\tbodyBytes: Buffer,\n): Buffer {\n\tconst bodyHash = createHash(\"sha256\").update(bodyBytes).digest(\"hex\");\n\tconst canonical = [method.toUpperCase(), pathWithQuery, timestamp, nonce, bodyHash].join(\"\\n\");\n\treturn Buffer.from(canonical, \"utf-8\");\n}\n\n/**\n * Build the direct-peer v3 canonical request without changing the v2 bytes.\n * The recipient is the sixth field so the signature cannot be replayed to a\n * different peer.\n */\nexport function buildDirectPeerCanonicalRequest(\n\tmethod: string,\n\tpathWithQuery: string,\n\ttimestamp: string,\n\tnonce: string,\n\tbodyBytes: Buffer,\n\trecipientId: string,\n): Buffer {\n\tif (!isValidRecipientId(recipientId)) {\n\t\tthrow new Error(\"recipientId must be a non-empty single-line value\");\n\t}\n\treturn Buffer.concat([\n\t\tbuildCanonicalRequest(method, pathWithQuery, timestamp, nonce, bodyBytes),\n\t\tBuffer.from(`\\n${recipientId}`, \"utf-8\"),\n\t]);\n}\n\n// ---------------------------------------------------------------------------\n// Sign\n// ---------------------------------------------------------------------------\n\nexport interface SignRequestOptions {\n\tmethod: string;\n\turl: string;\n\tbodyBytes: Buffer;\n\tkeysDir?: string;\n\tdeviceId?: string;\n\tdbPath?: string;\n\ttimestamp?: string;\n\tnonce?: string;\n}\n\nexport interface SignedRequestHeaders {\n\t\"X-Opencode-Timestamp\": string;\n\t\"X-Opencode-Nonce\": string;\n\t\"X-Opencode-Signature\": string;\n}\n\ninterface SigningKeyOptions {\n\tkeysDir?: string;\n\tdeviceId?: string;\n\tdbPath?: string;\n}\n\nfunction requestPath(url: string): string {\n\tconst parsed = new URL(url);\n\treturn `${parsed.pathname || \"/\"}${parsed.search}`;\n}\n\nfunction signCanonicalRequest(canonical: Buffer, options: SigningKeyOptions): string {\n\tconst keyData = loadPrivateKey(options.keysDir, options.dbPath, options.deviceId);\n\tif (!keyData) throw new Error(\"private key missing\");\n\n\tlet privateKeyObj: ReturnType<typeof createPrivateKey>;\n\ttry {\n\t\tprivateKeyObj = createPrivateKey(keyData);\n\t} catch {\n\t\tprivateKeyObj = createPrivateKey({ key: keyData, format: \"pem\", type: \"pkcs8\" });\n\t}\n\treturn sign(null, canonical, privateKeyObj).toString(\"base64\");\n}\n\n/**\n * Sign an HTTP request and return the auth headers.\n *\n * Uses Node's native Ed25519 crypto.sign() — no ssh-keygen shelling.\n * Returns X-Opencode-Timestamp, X-Opencode-Nonce, X-Opencode-Signature headers.\n */\nexport function signRequest(options: SignRequestOptions): SignedRequestHeaders {\n\tconst ts = options.timestamp ?? String(Math.floor(Date.now() / 1000));\n\tconst nonceValue = options.nonce ?? randomBytes(16).toString(\"hex\");\n\n\tconst path = requestPath(options.url);\n\tconst canonical = buildCanonicalRequest(options.method, path, ts, nonceValue, options.bodyBytes);\n\tconst signature = signCanonicalRequest(canonical, options);\n\n\treturn {\n\t\t\"X-Opencode-Timestamp\": ts,\n\t\t\"X-Opencode-Nonce\": nonceValue,\n\t\t\"X-Opencode-Signature\": `${SIGNATURE_VERSION}:${signature}`,\n\t};\n}\n\nexport interface SignDirectPeerRequestOptions\n\textends Omit<SignRequestOptions, \"timestamp\" | \"nonce\"> {\n\trecipientId: string;\n\ttimestamp: string;\n\tnonce: string;\n}\n\nexport interface DirectPeerSignatureHeaders {\n\t\"X-Codemem-Recipient\": string;\n\t\"X-Codemem-Signature\": string;\n}\n\n/** Sign the isolated recipient-bound v3 material for a direct-peer request. */\nexport function signDirectPeerRequest(\n\toptions: SignDirectPeerRequestOptions,\n): DirectPeerSignatureHeaders {\n\tconst path = requestPath(options.url);\n\tconst canonical = buildDirectPeerCanonicalRequest(\n\t\toptions.method,\n\t\tpath,\n\t\toptions.timestamp,\n\t\toptions.nonce,\n\t\toptions.bodyBytes,\n\t\toptions.recipientId,\n\t);\n\tconst signature = signCanonicalRequest(canonical, options);\n\n\treturn {\n\t\t\"X-Codemem-Recipient\": options.recipientId,\n\t\t\"X-Codemem-Signature\": `${DIRECT_PEER_SIGNATURE_VERSION}:${signature}`,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Verify\n// ---------------------------------------------------------------------------\n\nexport interface VerifySignatureOptions {\n\tmethod: string;\n\tpathWithQuery: string;\n\tbodyBytes: Buffer;\n\ttimestamp: string;\n\tnonce: string;\n\tsignature: string;\n\tpublicKey: string;\n\tdeviceId: string;\n\ttimeWindowS?: number;\n}\n\nfunction isFreshTimestamp(timestamp: string, timeWindowS: number): boolean {\n\tif (!/^\\d+$/.test(timestamp)) return false;\n\tconst seconds = Number.parseInt(timestamp, 10);\n\treturn Math.abs(Math.floor(Date.now() / 1000) - seconds) <= timeWindowS;\n}\n\nfunction decodeStrictBase64(encoded: string): Buffer | undefined {\n\tif (!encoded) return undefined;\n\tconst decoded = Buffer.from(encoded, \"base64\");\n\treturn decoded.toString(\"base64\") === encoded ? decoded : undefined;\n}\n\n/**\n * Verify a signed request.\n *\n * Checks timestamp freshness, signature version prefix, then uses\n * Node's native crypto.verify() with the sender's Ed25519 public key.\n */\nexport function verifySignature(options: VerifySignatureOptions): boolean {\n\tconst timeWindow = options.timeWindowS ?? DEFAULT_TIME_WINDOW_S;\n\n\tif (!isFreshTimestamp(options.timestamp, timeWindow)) return false;\n\n\t// Validate signature version prefix — accept both v1 and v2 during migration\n\tconst ACCEPTED_VERSIONS = [\"v1\", \"v2\"];\n\tconst colonIdx = options.signature.indexOf(\":\");\n\tif (colonIdx < 1) return false;\n\tconst sigVersion = options.signature.slice(0, colonIdx);\n\tif (!ACCEPTED_VERSIONS.includes(sigVersion)) return false;\n\n\tconst signatureBytes = decodeStrictBase64(options.signature.slice(colonIdx + 1));\n\tif (!signatureBytes) return false;\n\n\tconst canonical = buildCanonicalRequest(\n\t\toptions.method,\n\t\toptions.pathWithQuery,\n\t\toptions.timestamp,\n\t\toptions.nonce,\n\t\toptions.bodyBytes,\n\t);\n\n\ttry {\n\t\tconst publicKeyObj = sshEd25519ToPublicKey(options.publicKey);\n\t\treturn verify(null, canonical, publicKeyObj, signatureBytes);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport interface VerifyDirectPeerSignatureOptions {\n\tmethod: string;\n\tpathWithQuery: string;\n\tbodyBytes: Buffer;\n\ttimestamp: string;\n\tnonce: string;\n\trecipientId?: string;\n\texpectedRecipientId: string;\n\tsignature?: string;\n\tpublicKey: string;\n\ttimeWindowS?: number;\n}\n\nexport type DirectPeerSignatureVerification =\n\t| { status: \"absent\" }\n\t| {\n\t\t\tstatus: \"invalid\";\n\t\t\treason:\n\t\t\t\t| \"incomplete_material\"\n\t\t\t\t| \"malformed_recipient\"\n\t\t\t\t| \"invalid_timestamp\"\n\t\t\t\t| \"unsupported_version\"\n\t\t\t\t| \"invalid_signature\"\n\t\t\t\t| \"recipient_mismatch\";\n\t }\n\t| { status: \"valid\"; version: \"v3\" };\n\n/**\n * Verify direct-peer v3 material with an explicit absent/invalid distinction.\n * Callers may permit legacy v2 only for `absent`; any `invalid` result must fail\n * closed rather than falling back to the accompanying v2 signature.\n */\nexport function verifyDirectPeerSignature(\n\toptions: VerifyDirectPeerSignatureOptions,\n): DirectPeerSignatureVerification {\n\tconst recipientId = options.recipientId === \"\" ? undefined : options.recipientId;\n\tconst signature = options.signature === \"\" ? undefined : options.signature;\n\tif (recipientId === undefined && signature === undefined) {\n\t\treturn { status: \"absent\" };\n\t}\n\tif (!recipientId || !signature) {\n\t\treturn { status: \"invalid\", reason: \"incomplete_material\" };\n\t}\n\tif (!isValidRecipientId(recipientId)) {\n\t\treturn { status: \"invalid\", reason: \"malformed_recipient\" };\n\t}\n\tconst timeWindow = options.timeWindowS ?? DEFAULT_TIME_WINDOW_S;\n\tif (!isFreshTimestamp(options.timestamp, timeWindow)) {\n\t\treturn { status: \"invalid\", reason: \"invalid_timestamp\" };\n\t}\n\n\tconst prefix = `${DIRECT_PEER_SIGNATURE_VERSION}:`;\n\tif (!signature.startsWith(prefix)) {\n\t\treturn { status: \"invalid\", reason: \"unsupported_version\" };\n\t}\n\tconst signatureBytes = decodeStrictBase64(signature.slice(prefix.length));\n\tif (!signatureBytes) {\n\t\treturn { status: \"invalid\", reason: \"invalid_signature\" };\n\t}\n\n\tconst canonical = buildDirectPeerCanonicalRequest(\n\t\toptions.method,\n\t\toptions.pathWithQuery,\n\t\toptions.timestamp,\n\t\toptions.nonce,\n\t\toptions.bodyBytes,\n\t\trecipientId,\n\t);\n\ttry {\n\t\tconst publicKeyObj = sshEd25519ToPublicKey(options.publicKey);\n\t\tif (!verify(null, canonical, publicKeyObj, signatureBytes)) {\n\t\t\treturn { status: \"invalid\", reason: \"invalid_signature\" };\n\t\t}\n\t} catch {\n\t\treturn { status: \"invalid\", reason: \"invalid_signature\" };\n\t}\n\tif (recipientId !== options.expectedRecipientId) {\n\t\treturn { status: \"invalid\", reason: \"recipient_mismatch\" };\n\t}\n\treturn {\n\t\tstatus: \"valid\",\n\t\tversion: DIRECT_PEER_SIGNATURE_VERSION,\n\t};\n}\n\n/**\n * Parse an SSH ed25519 public key string into a Node crypto KeyObject.\n *\n * SSH format: \"ssh-ed25519 <base64-wire-format>\"\n * Wire format: uint32 key-type-len + key-type + uint32 key-data-len + key-data\n */\nfunction sshEd25519ToPublicKey(sshPub: string): ReturnType<typeof createPublicKey> {\n\tconst parts = sshPub.trim().split(/\\s+/);\n\tconst [keyType, keyData] = parts;\n\tif (keyType !== \"ssh-ed25519\" || !keyData) {\n\t\tthrow new Error(\"not an ssh-ed25519 key\");\n\t}\n\tconst wireFormat = Buffer.from(keyData, \"base64\");\n\n\t// Read key type length\n\tif (wireFormat.length < 4) throw new Error(\"truncated wire format\");\n\tconst typeLen = wireFormat.readUInt32BE(0);\n\tconst typeEnd = 4 + typeLen;\n\tif (wireFormat.length < typeEnd + 4) throw new Error(\"truncated wire format\");\n\n\t// Read key data length\n\tconst keyLen = wireFormat.readUInt32BE(typeEnd);\n\tconst keyStart = typeEnd + 4;\n\tif (wireFormat.length < keyStart + keyLen) throw new Error(\"truncated wire format\");\n\tconst rawKey = wireFormat.subarray(keyStart, keyStart + keyLen);\n\n\tif (rawKey.length !== 32) throw new Error(`unexpected Ed25519 key length: ${rawKey.length}`);\n\n\t// Wrap raw 32-byte key in SPKI DER: 12-byte Ed25519 header + 32-byte key\n\tconst ed25519SpkiPrefix = Buffer.from(\"302a300506032b6570032100\", \"hex\");\n\tconst spkiDer = Buffer.concat([ed25519SpkiPrefix, rawKey]);\n\n\treturn createPublicKey({ key: spkiDer, format: \"der\", type: \"spki\" });\n}\n\n// ---------------------------------------------------------------------------\n// Auth headers (convenience)\n// ---------------------------------------------------------------------------\n\nexport interface BuildAuthHeadersOptions {\n\tdeviceId: string;\n\tmethod: string;\n\turl: string;\n\tbodyBytes: Buffer;\n\tbootstrapGrantId?: string;\n\tkeysDir?: string;\n\tdbPath?: string;\n\ttimestamp?: string;\n\tnonce?: string;\n}\n\nexport type AuthHeaders = Record<string, string> &\n\tSignedRequestHeaders & {\n\t\t\"X-Opencode-Device\": string;\n\t};\n\n/**\n * Build full auth headers including device ID and request signature.\n */\nexport function buildAuthHeaders(options: BuildAuthHeadersOptions): AuthHeaders {\n\treturn {\n\t\t\"X-Opencode-Device\": options.deviceId,\n\t\t...(options.bootstrapGrantId ? { \"X-Codemem-Bootstrap-Grant\": options.bootstrapGrantId } : {}),\n\t\t...signRequest({\n\t\t\tmethod: options.method,\n\t\t\turl: options.url,\n\t\t\tbodyBytes: options.bodyBytes,\n\t\t\tkeysDir: options.keysDir,\n\t\t\tdeviceId: options.deviceId,\n\t\t\tdbPath: options.dbPath,\n\t\t\ttimestamp: options.timestamp,\n\t\t\tnonce: options.nonce,\n\t\t}),\n\t};\n}\n\nexport interface BuildDirectPeerAuthHeadersOptions extends BuildAuthHeadersOptions {\n\trecipientId: string;\n}\n\nexport type DirectPeerAuthHeaders = AuthHeaders & DirectPeerSignatureHeaders;\n\n/** Build dual v2 + recipient-bound v3 headers for direct-peer requests only. */\nexport function buildDirectPeerAuthHeaders(\n\toptions: BuildDirectPeerAuthHeadersOptions,\n): DirectPeerAuthHeaders {\n\tconst legacyHeaders = buildAuthHeaders(options);\n\tconst directHeaders = signDirectPeerRequest({\n\t\tmethod: options.method,\n\t\turl: options.url,\n\t\tbodyBytes: options.bodyBytes,\n\t\trecipientId: options.recipientId,\n\t\tkeysDir: options.keysDir,\n\t\tdeviceId: options.deviceId,\n\t\tdbPath: options.dbPath,\n\t\ttimestamp: legacyHeaders[\"X-Opencode-Timestamp\"],\n\t\tnonce: legacyHeaders[\"X-Opencode-Nonce\"],\n\t});\n\n\treturn {\n\t\t...legacyHeaders,\n\t\t...directHeaders,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Nonce management\n// ---------------------------------------------------------------------------\n\n/**\n * Record a nonce to prevent replay attacks.\n *\n * Returns true on success, false if the nonce was already recorded\n * (duplicate = potential replay).\n */\nexport function recordNonce(\n\tdb: Database,\n\tdeviceId: string,\n\tnonce: string,\n\tcreatedAt: string,\n): boolean {\n\tconst d = drizzle(db, { schema });\n\ttry {\n\t\td.insert(schema.syncNonces).values({ nonce, device_id: deviceId, created_at: createdAt }).run();\n\t\treturn true;\n\t} catch (err: unknown) {\n\t\tif (err instanceof Error && err.message.includes(\"UNIQUE constraint failed\")) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n/**\n * Remove nonces older than the given cutoff timestamp.\n */\nexport function cleanupNonces(db: Database, cutoff: string): void {\n\tconst d = drizzle(db, { schema });\n\td.delete(schema.syncNonces).where(lt(schema.syncNonces.created_at, cutoff)).run();\n}\n","/**\n * Sync HTTP client: JSON request helper using Node.js built-in fetch.\n *\n * Async counterpart to the synchronous Python http.client implementation.\n * Ported from codemem/sync/http_client.py.\n */\n\n// ---------------------------------------------------------------------------\n// URL helpers\n// ---------------------------------------------------------------------------\n\nfunction stripTrailingSlashes(value: string): string {\n\tlet end = value.length;\n\twhile (end > 0 && value.charCodeAt(end - 1) === 47) end--;\n\treturn end === value.length ? value : value.slice(0, end);\n}\n\nfunction hasUrlScheme(value: string): boolean {\n\tconst separator = value.indexOf(\"://\");\n\tif (separator <= 0) return false;\n\tconst first = value.charCodeAt(0);\n\tif (!((first >= 65 && first <= 90) || (first >= 97 && first <= 122))) return false;\n\tfor (let i = 1; i < separator; i++) {\n\t\tconst code = value.charCodeAt(i);\n\t\tconst isLetter = (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n\t\tconst isDigit = code >= 48 && code <= 57;\n\t\tif (!isLetter && !isDigit && code !== 43 && code !== 45 && code !== 46) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Normalize a peer address into a base URL.\n *\n * Adds `http://` when no scheme is present, trims whitespace and trailing slashes.\n */\nexport function buildBaseUrl(address: string): string {\n\tconst trimmed = stripTrailingSlashes(address.trim());\n\tif (!trimmed) return \"\";\n\t// Check for an existing scheme (e.g. http://, https://)\n\tif (hasUrlScheme(trimmed)) return trimmed;\n\treturn `http://${trimmed}`;\n}\n\n// ---------------------------------------------------------------------------\n// JSON request\n// ---------------------------------------------------------------------------\n\nexport interface RequestJsonOptions {\n\theaders?: Record<string, string>;\n\tbody?: Record<string, unknown>;\n\tbodyBytes?: Uint8Array;\n\ttimeoutS?: number;\n\tmaxResponseBytes?: number;\n\tredirect?: \"error\";\n\tsignal?: AbortSignal;\n}\n\nexport type RequestJsonExecutor = typeof requestJson;\n\nfunction isolateDirectPeerConnection(headers: Record<string, string>): Record<string, string> {\n\tconst isDirectPeer = Object.keys(headers).some(\n\t\t(name) => name.toLowerCase() === \"x-codemem-recipient\",\n\t);\n\tif (!isDirectPeer) return headers;\n\n\t// Sync preparation can block expiry callbacks past a peer's idle deadline.\n\t// Close reads too, so a later write cannot reuse their expired connection.\n\treturn {\n\t\t...Object.fromEntries(\n\t\t\tObject.entries(headers).filter(([name]) => name.toLowerCase() !== \"connection\"),\n\t\t),\n\t\tConnection: \"close\",\n\t};\n}\n\nfunction requestRedirectPolicy(\n\theaders: Record<string, string>,\n\tredirect?: \"error\",\n): \"error\" | \"follow\" {\n\tconst carriesAdminCredential = Object.keys(headers).some(\n\t\t(name) => name.toLowerCase() === \"x-codemem-coordinator-admin\",\n\t);\n\tif (carriesAdminCredential) return \"error\";\n\treturn redirect ?? \"follow\";\n}\n\nfunction buildRequestHeaders(options: {\n\theaders?: Record<string, string>;\n\tbodyBytes?: Uint8Array;\n}): Record<string, string> {\n\tconst headers: Record<string, string> = { Accept: \"application/json\" };\n\tif (options.bodyBytes != null) {\n\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\theaders[\"Content-Length\"] = String(options.bodyBytes.byteLength);\n\t}\n\tif (options.headers) Object.assign(headers, options.headers);\n\treturn headers;\n}\n\nfunction requestSignal(timeoutS: number, signal?: AbortSignal): AbortSignal {\n\tconst timeout = AbortSignal.timeout(Math.round(timeoutS * 1000));\n\treturn signal ? AbortSignal.any([signal, timeout]) : timeout;\n}\n\n/**\n * Send an HTTP request and parse the JSON response.\n *\n * Returns `[statusCode, parsedBody]`. The body is null when the response\n * has no content. Non-JSON responses are returned as `{ error: \"non_json_response: ...\" }`.\n */\nexport async function requestJson(\n\tmethod: string,\n\turl: string,\n\toptions: RequestJsonOptions = {},\n): Promise<[status: number, body: Record<string, unknown> | null]> {\n\tconst { headers, body, timeoutS = 3 } = options;\n\tlet { bodyBytes } = options;\n\n\tif (bodyBytes == null && body != null) {\n\t\tbodyBytes = new TextEncoder().encode(JSON.stringify(body));\n\t}\n\n\tconst requestHeaders = buildRequestHeaders({ headers, bodyBytes });\n\tconst requestBody = (bodyBytes ?? null) as RequestInit[\"body\"] | null;\n\n\tconst response = await fetch(url, {\n\t\tmethod,\n\t\theaders: isolateDirectPeerConnection(requestHeaders),\n\t\tbody: requestBody,\n\t\tredirect: requestRedirectPolicy(requestHeaders, options.redirect),\n\t\tsignal: requestSignal(timeoutS, options.signal),\n\t});\n\n\tlet raw: string;\n\tif (options.maxResponseBytes != null && response.body) {\n\t\tconst declaredLength = Number(response.headers.get(\"content-length\"));\n\t\tif (Number.isFinite(declaredLength) && declaredLength > options.maxResponseBytes) {\n\t\t\tawait response.body.cancel();\n\t\t\treturn [response.status, { error: \"response_too_large\" }];\n\t\t}\n\t\tconst reader = response.body.getReader();\n\t\tconst decoder = new TextDecoder();\n\t\tlet totalBytes = 0;\n\t\traw = \"\";\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\ttotalBytes += value.byteLength;\n\t\t\t\tif (totalBytes > options.maxResponseBytes) {\n\t\t\t\t\tawait reader.cancel();\n\t\t\t\t\treturn [response.status, { error: \"response_too_large\" }];\n\t\t\t\t}\n\t\t\t\traw += decoder.decode(value, { stream: true });\n\t\t\t}\n\t\t\traw += decoder.decode();\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t} else {\n\t\traw = await response.text();\n\t}\n\tif (!raw) return [response.status, null];\n\n\tlet payload: unknown;\n\ttry {\n\t\tpayload = JSON.parse(raw);\n\t} catch {\n\t\tconst snippet = raw.slice(0, 240).trim();\n\t\treturn [\n\t\t\tresponse.status,\n\t\t\t{ error: snippet ? `non_json_response: ${snippet}` : \"non_json_response\" },\n\t\t];\n\t}\n\n\tif (typeof payload === \"object\" && payload !== null && !Array.isArray(payload)) {\n\t\treturn [response.status, payload as Record<string, unknown>];\n\t}\n\treturn [\n\t\tresponse.status,\n\t\t{ error: `unexpected_json_type: ${Array.isArray(payload) ? \"array\" : typeof payload}` },\n\t];\n}\n","import { getCodememEnvOverrides, readCodememConfigFile } from \"./observer-config.js\";\n\ntype ConfigRecord = Record<string, unknown>;\n\nfunction clean(value: unknown): string {\n\treturn typeof value === \"string\" ? value.trim() : \"\";\n}\n\nfunction parseIntOr(value: unknown, fallback: number): number {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return Math.trunc(value);\n\tif (typeof value === \"string\" && /^-?\\d+$/.test(value.trim()))\n\t\treturn Number.parseInt(value.trim(), 10);\n\treturn fallback;\n}\n\nfunction parseBoolOr(value: unknown, fallback: boolean): boolean {\n\tif (typeof value === \"boolean\") return value;\n\tif (typeof value === \"string\") {\n\t\tconst normalized = value.trim().toLowerCase();\n\t\tif ([\"1\", \"true\", \"yes\", \"on\"].includes(normalized)) return true;\n\t\tif ([\"0\", \"false\", \"no\", \"off\"].includes(normalized)) return false;\n\t}\n\treturn fallback;\n}\n\nfunction parseStringList(value: unknown): string[] {\n\tif (Array.isArray(value)) {\n\t\treturn value\n\t\t\t.filter((item): item is string => typeof item === \"string\")\n\t\t\t.map((item) => item.trim())\n\t\t\t.filter(Boolean);\n\t}\n\tif (typeof value === \"string\") {\n\t\treturn value\n\t\t\t.split(\",\")\n\t\t\t.map((item) => item.trim())\n\t\t\t.filter(Boolean);\n\t}\n\treturn [];\n}\n\nexport interface CoordinatorSyncConfig {\n\tsyncEnabled: boolean;\n\tsyncHost: string;\n\tsyncPort: number;\n\tsyncIntervalS: number;\n\tsyncAdvertise: string;\n\tsyncMdns: boolean;\n\tsyncRetentionEnabled: boolean;\n\tsyncRetentionMaxAgeDays: number;\n\tsyncRetentionMaxSizeMb: number;\n\tsyncRetentionIntervalS: number;\n\tsyncRetentionMaxRuntimeMs: number;\n\tsyncRetentionMaxOpsPerPass: number;\n\trawEventsRetentionEnabled: boolean;\n\t/** Whether raw_events_retention_enabled was explicitly set (file or env), so\n\t * callers can treat an explicit `false` as authoritative over legacy knobs. */\n\trawEventsRetentionConfigured: boolean;\n\trawEventsRetentionMaxAgeDays: number;\n\tsyncProjectsInclude: string[];\n\tsyncProjectsExclude: string[];\n\tsyncOpsLimit: number;\n\tsyncCoordinatorUrl: string;\n\tsyncCoordinatorGroup: string;\n\tsyncCoordinatorGroups: string[];\n\tsyncCoordinatorTimeoutS: number;\n\tsyncCoordinatorPresenceTtlS: number;\n\tsyncCoordinatorAdminSecret: string;\n}\n\nfunction readRawSyncConfig(config?: ConfigRecord): ConfigRecord {\n\tconst raw = { ...(config ?? readCodememConfigFile()) } as ConfigRecord;\n\tconst envOverrides = getCodememEnvOverrides();\n\tfor (const key of Object.keys(envOverrides)) {\n\t\tconst value = process.env[envOverrides[key] as string];\n\t\tif (value != null) raw[key] = value;\n\t}\n\treturn raw;\n}\n\n/** Device-side relay settings. Relay runs automatically when the coordinator advertises it. */\nexport interface RelayClientSettings {\n\t/** `sync_relay_enabled`, default true. False opts this device out and skips every relay fetch. */\n\tenabled: boolean;\n\t/** `sync_relay_service_key`: explicit operator key that wins over the advertised key. */\n\tserviceKey: string;\n}\n\nexport function readRelayClientSettings(config?: ConfigRecord): RelayClientSettings {\n\tconst raw = readRawSyncConfig(config);\n\treturn {\n\t\tenabled: parseBoolOr(raw.sync_relay_enabled, true),\n\t\tserviceKey: clean(raw.sync_relay_service_key),\n\t};\n}\n\nexport function readCoordinatorSyncConfig(config?: ConfigRecord): CoordinatorSyncConfig {\n\tconst raw = readRawSyncConfig(config);\n\tconst syncCoordinatorGroup = clean(raw.sync_coordinator_group);\n\tconst syncCoordinatorGroups = parseStringList(raw.sync_coordinator_groups);\n\tif (syncCoordinatorGroups.length === 0 && syncCoordinatorGroup) {\n\t\tsyncCoordinatorGroups.push(syncCoordinatorGroup);\n\t}\n\treturn {\n\t\tsyncEnabled: parseBoolOr(raw.sync_enabled, false),\n\t\tsyncHost: clean(raw.sync_host) || \"0.0.0.0\",\n\t\tsyncPort: parseIntOr(raw.sync_port, 7337),\n\t\tsyncIntervalS: parseIntOr(raw.sync_interval_s, 120),\n\t\tsyncAdvertise: clean(raw.sync_advertise) || \"auto\",\n\t\tsyncMdns: parseBoolOr(raw.sync_mdns, false),\n\t\tsyncRetentionEnabled: parseBoolOr(raw.sync_retention_enabled, false),\n\t\tsyncRetentionMaxAgeDays: Math.max(1, parseIntOr(raw.sync_retention_max_age_days, 30)),\n\t\tsyncRetentionMaxSizeMb: Math.max(1, parseIntOr(raw.sync_retention_max_size_mb, 512)),\n\t\tsyncRetentionIntervalS: Math.max(5, parseIntOr(raw.sync_retention_interval_s, 300)),\n\t\tsyncRetentionMaxRuntimeMs: Math.max(100, parseIntOr(raw.sync_retention_max_runtime_ms, 2000)),\n\t\tsyncRetentionMaxOpsPerPass: Math.max(1, parseIntOr(raw.sync_retention_max_ops_per_pass, 5000)),\n\t\trawEventsRetentionEnabled: parseBoolOr(raw.raw_events_retention_enabled, false),\n\t\trawEventsRetentionConfigured: raw.raw_events_retention_enabled !== undefined,\n\t\trawEventsRetentionMaxAgeDays: Math.max(\n\t\t\t1,\n\t\t\tparseIntOr(raw.raw_events_retention_max_age_days, 90),\n\t\t),\n\t\tsyncProjectsInclude: parseStringList(raw.sync_projects_include),\n\t\tsyncProjectsExclude: parseStringList(raw.sync_projects_exclude),\n\t\tsyncOpsLimit: Math.max(1, Math.min(1000, parseIntOr(raw.sync_ops_limit, 500))),\n\t\tsyncCoordinatorUrl: clean(raw.sync_coordinator_url),\n\t\tsyncCoordinatorGroup,\n\t\tsyncCoordinatorGroups,\n\t\tsyncCoordinatorTimeoutS: parseIntOr(raw.sync_coordinator_timeout_s, 3),\n\t\tsyncCoordinatorPresenceTtlS: parseIntOr(raw.sync_coordinator_presence_ttl_s, 180),\n\t\tsyncCoordinatorAdminSecret: clean(raw.sync_coordinator_admin_secret),\n\t};\n}\n\nexport function coordinatorEnabled(config: CoordinatorSyncConfig): boolean {\n\treturn Boolean(config.syncCoordinatorUrl && config.syncCoordinatorGroups.length > 0);\n}\n","import { BetterSqliteCoordinatorStore, DEFAULT_COORDINATOR_DB_PATH } from \"./coordinator-store.js\";\nimport type { CoordinatorScope, CoordinatorScopeMembership } from \"./coordinator-store-contract.js\";\nimport {\n\ttype CoordinatorSyncConfig,\n\tcoordinatorEnabled,\n\treadCoordinatorSyncConfig,\n} from \"./coordinator-sync-config.js\";\nimport type { Database } from \"./db.js\";\nimport {\n\tloadCachedScope,\n\ttype ScopeMembershipCacheAuthority,\n} from \"./scope-membership-cache-read.js\";\nimport { reconcileScopeAuthorizationEvidence } from \"./scope-membership-evidence.js\";\nimport {\n\tnormalizeScopeCatalog,\n\tnormalizeScopeSnapshot,\n\ttype ScopeMembershipCatalog,\n\ttype ScopeMembershipSnapshot,\n} from \"./scope-membership-snapshot.js\";\nimport { buildAuthHeaders } from \"./sync-auth.js\";\nimport { buildBaseUrl, requestJson } from \"./sync-http-client.js\";\nimport { ensureDeviceIdentity } from \"./sync-identity.js\";\n\nexport {\n\ttype CachedDeviceScopeMemberships,\n\ttype CachedScopeAuthorization,\n\ttype CachedScopeMembership,\n\tDEFAULT_SCOPE_MEMBERSHIP_CACHE_MAX_AGE_MS,\n\ttype EffectiveCachedScopeAuthorization,\n\tgetCachedScopeAuthorization,\n\tgetEffectiveCachedScopeAuthorization,\n\tlistCachedScopesForDevice,\n\ttype ScopeMembershipAuthorizationState,\n\ttype ScopeMembershipCacheAuthority,\n\ttype ScopeMembershipCacheFreshness,\n\ttype ScopeMembershipCacheState,\n} from \"./scope-membership-cache-read.js\";\n\nexport interface ScopeMembershipCacheFetchers {\n\tlistScopes(groupId: string): Promise<ScopeMembershipCatalog>;\n\tgetScopeSnapshot(groupId: string, scopeId: string): Promise<ScopeMembershipSnapshot>;\n}\n\nexport interface RefreshScopeMembershipCacheOptions {\n\tgroupIds: string[];\n\tcoordinatorId?: string | null;\n\tremoteUrl?: string | null;\n\tadminSecret?: string | null;\n\t/** @deprecated The refresh database is taken from refreshScopeMembershipCache(db, opts). */\n\tdb?: Database;\n\tkeysDir?: string | null;\n\tdbPath?: string;\n\t/** Separate local coordinator storage; dbPath remains the memory/signing database. */\n\tcoordinatorDbPath?: string;\n\tnow?: Date;\n\tfetchers?: ScopeMembershipCacheFetchers;\n}\n\nexport interface RefreshScopeMembershipCacheGroupResult {\n\tgroupId: string;\n\tstatus: \"refreshed\" | \"stale\";\n\tscopeCount: number;\n\tmembershipCount: number;\n\terror: string | null;\n}\n\nexport interface RefreshScopeMembershipCacheResult {\n\tstatus: \"refreshed\" | \"partial\" | \"stale\" | \"skipped\";\n\tcoordinatorId: string | null;\n\tgroups: RefreshScopeMembershipCacheGroupResult[];\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nfunction nowIso(now?: Date): string {\n\treturn (now ?? new Date()).toISOString();\n}\n\nfunction groupIds(input: string[]): string[] {\n\treturn [...new Set(input.map((item) => item.trim()).filter(Boolean))].toSorted();\n}\n\nfunction authorityId(remoteUrl: string | null | undefined): string {\n\tconst remote = clean(remoteUrl);\n\tif (!remote) return \"local\";\n\ttry {\n\t\treturn buildBaseUrl(remote);\n\t} catch {\n\t\treturn remote;\n\t}\n}\n\nfunction errorMessage(error: unknown): string {\n\tif (error instanceof Error) return error.message;\n\treturn String(error ?? \"unknown\");\n}\n\nexport function ensureScopeMembershipCacheStateTable(db: Database): void {\n\tif (hasRefreshRevision(db)) return;\n\t// Recheck under the write lock: another process may have upgraded the cache.\n\tdb.transaction(() => {\n\t\tif (hasRefreshRevision(db)) return;\n\t\tdb.exec(`\n\t\tCREATE TABLE IF NOT EXISTS scope_membership_cache_state (\n\t\t\tcoordinator_id TEXT NOT NULL,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tlast_refresh_at TEXT NOT NULL,\n\t\t\tlast_success_at TEXT,\n\t\t\tlast_error TEXT,\n\t\t\tupdated_at TEXT NOT NULL,\n\t\t\trefresh_revision INTEGER NOT NULL DEFAULT 0,\n\t\t\tPRIMARY KEY (coordinator_id, group_id)\n\t\t)\n\t`);\n\t\tif (!hasRefreshRevision(db))\n\t\t\tdb.exec(\n\t\t\t\t\"ALTER TABLE scope_membership_cache_state ADD COLUMN refresh_revision INTEGER NOT NULL DEFAULT 0\",\n\t\t\t);\n\t}).immediate();\n}\n\nfunction hasRefreshRevision(db: Database): boolean {\n\treturn !!db\n\t\t.prepare(\"SELECT 1 FROM pragma_table_info('scope_membership_cache_state') WHERE name = ?\")\n\t\t.get(\"refresh_revision\");\n}\n\n/** Local write ordering only; neither a membership epoch nor a permission lease. */\nfunction readRefreshRevision(db: Database, authority: ScopeMembershipCacheAuthority): number {\n\tconst row = db\n\t\t.prepare(`SELECT refresh_revision FROM scope_membership_cache_state\n\t\tWHERE coordinator_id = ? AND group_id = ?`)\n\t\t.get(authority.coordinatorId, authority.groupId) as { refresh_revision: number } | undefined;\n\tconst revision = row ? row.refresh_revision : 0;\n\tif (!Number.isSafeInteger(revision) || revision < 0 || revision >= Number.MAX_SAFE_INTEGER)\n\t\tthrow new Error(\"Scope membership cache revision unavailable.\");\n\treturn revision;\n}\n\nfunction coordinatorUrl(opts: RefreshScopeMembershipCacheOptions): string {\n\tconst remote = clean(opts.remoteUrl);\n\tif (!remote) throw new Error(\"Coordinator URL required.\");\n\treturn buildBaseUrl(remote);\n}\n\nfunction signedCoordinatorGet(\n\tdb: Database,\n\turl: string,\n\tkeysDir?: string | null,\n\tdbPath?: string,\n): Promise<Record<string, unknown> | null> {\n\tconst [deviceId] = ensureDeviceIdentity(db, { keysDir: keysDir ?? undefined });\n\tconst bodyBytes = Buffer.alloc(0);\n\tconst headers = buildAuthHeaders({\n\t\tdeviceId,\n\t\tmethod: \"GET\",\n\t\turl,\n\t\tbodyBytes,\n\t\tkeysDir: keysDir ?? undefined,\n\t\tdbPath,\n\t});\n\treturn requestJson(\"GET\", url, {\n\t\theaders,\n\t}).then(([status, payload]) => {\n\t\tif (status < 200 || status >= 300) {\n\t\t\tthrow new Error(`Coordinator membership snapshot failed (${status})`);\n\t\t}\n\t\treturn payload;\n\t});\n}\n\nfunction authenticatedFetchers(\n\tdb: Database,\n\topts: RefreshScopeMembershipCacheOptions,\n): ScopeMembershipCacheFetchers {\n\tconst baseUrl = coordinatorUrl(opts);\n\treturn {\n\t\tlistScopes: async (groupId) => {\n\t\t\tconst url = `${baseUrl}/v1/scopes?group_id=${encodeURIComponent(groupId)}`;\n\t\t\treturn (await signedCoordinatorGet(\n\t\t\t\tdb,\n\t\t\t\turl,\n\t\t\t\topts.keysDir,\n\t\t\t\topts.dbPath,\n\t\t\t)) as unknown as ScopeMembershipCatalog;\n\t\t},\n\t\tgetScopeSnapshot: async (groupId, scopeId) => {\n\t\t\tconst url = `${baseUrl}/v1/scopes/${encodeURIComponent(scopeId)}/members?group_id=${encodeURIComponent(groupId)}`;\n\t\t\treturn (await signedCoordinatorGet(\n\t\t\t\tdb,\n\t\t\t\turl,\n\t\t\t\topts.keysDir,\n\t\t\t\topts.dbPath,\n\t\t\t)) as unknown as ScopeMembershipSnapshot;\n\t\t},\n\t};\n}\n\nfunction defaultFetchers(\n\tdb: Database,\n\topts: RefreshScopeMembershipCacheOptions,\n): ScopeMembershipCacheFetchers {\n\tif (clean(opts.remoteUrl)) return authenticatedFetchers(db, opts);\n\treturn {\n\t\tlistScopes: (groupId) =>\n\t\t\twithLocalCoordinator(opts, async (store) => ({\n\t\t\t\tversion: 1,\n\t\t\t\titems: await store.listScopes({ groupId }),\n\t\t\t})),\n\t\tgetScopeSnapshot: (groupId, scopeId) =>\n\t\t\twithLocalCoordinator(opts, async (store) => {\n\t\t\t\tconst decision = await store.getScopeAuthorization({ groupId, scopeId });\n\t\t\t\tif (decision.kind !== \"authorized\") throw new Error(decision.error);\n\t\t\t\treturn {\n\t\t\t\t\tauthorization_version: decision.authorizationVersion,\n\t\t\t\t\tscope: decision.scope,\n\t\t\t\t\titems: decision.members.map(({ membership, enrollment, keyId }) => ({\n\t\t\t\t\t\tmembership,\n\t\t\t\t\t\tenrollment,\n\t\t\t\t\t\tkey_id: keyId,\n\t\t\t\t\t})),\n\t\t\t\t};\n\t\t\t}),\n\t};\n}\n\nasync function withLocalCoordinator<T>(\n\topts: RefreshScopeMembershipCacheOptions,\n\tread: (store: BetterSqliteCoordinatorStore) => Promise<T>,\n): Promise<T> {\n\tconst store = new BetterSqliteCoordinatorStore(\n\t\topts.coordinatorDbPath ?? DEFAULT_COORDINATOR_DB_PATH,\n\t);\n\ttry {\n\t\treturn await read(store);\n\t} finally {\n\t\tawait store.close();\n\t}\n}\n\nfunction upsertScope(db: Database, scope: CoordinatorScope): void {\n\tdb.prepare(\n\t\t`INSERT INTO replication_scopes(\n\t\t\tscope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n\t\tON CONFLICT(scope_id) DO UPDATE SET\n\t\t\tlabel = excluded.label,\n\t\t\tkind = excluded.kind,\n\t\t\tauthority_type = excluded.authority_type,\n\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\tgroup_id = excluded.group_id,\n\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\tstatus = excluded.status,\n\t\t\tupdated_at = excluded.updated_at\n\t\tWHERE excluded.membership_epoch >= replication_scopes.membership_epoch`,\n\t).run(\n\t\tscope.scope_id,\n\t\tscope.label,\n\t\tscope.kind,\n\t\tscope.authority_type,\n\t\tscope.coordinator_id,\n\t\tscope.group_id,\n\t\tscope.manifest_issuer_device_id,\n\t\tscope.membership_epoch,\n\t\tscope.manifest_hash,\n\t\tscope.status,\n\t\tscope.created_at,\n\t\tscope.updated_at,\n\t);\n}\n\nfunction placeholders(count: number): string {\n\treturn Array.from({ length: count }, () => \"?\").join(\", \");\n}\n\nfunction reconcileScopeMembershipSnapshot(\n\tdb: Database,\n\tbatch: CurrentScopeBatch,\n\tauthority: ScopeMembershipCacheAuthority,\n\ttimestamp: string,\n): void {\n\tconst { scope, memberships, sourceCoordinatorId } = batch;\n\t// The authorized scope-members endpoint returns the complete membership list\n\t// that is active at the current epoch, so absence is fail-closed here.\n\tconst deviceIds = memberships.map((membership) => membership.device_id);\n\tconst deviceFilter =\n\t\tdeviceIds.length > 0 ? `AND device_id NOT IN (${placeholders(deviceIds.length)})` : \"\";\n\tdb.prepare(\n\t\t`UPDATE scope_memberships\n\t\t SET status = 'revoked',\n\t\t\t membership_epoch = CASE WHEN membership_epoch > ? THEN membership_epoch ELSE ? END,\n\t\t\t coordinator_id = ?,\n\t\t\t group_id = ?,\n\t\t\t updated_at = ?\n\t\t WHERE scope_id = ?\n\t\t\t AND COALESCE(coordinator_id, ?) IN (?, ?)\n\t\t\t AND COALESCE(group_id, ?) = ?\n\t\t\t AND status != 'revoked'\n\t\t\t ${deviceFilter}`,\n\t).run(\n\t\tscope.membership_epoch,\n\t\tscope.membership_epoch,\n\t\tauthority.coordinatorId,\n\t\tauthority.groupId,\n\t\ttimestamp,\n\t\tscope.scope_id,\n\t\tauthority.coordinatorId,\n\t\tauthority.coordinatorId,\n\t\tsourceCoordinatorId,\n\t\tauthority.groupId,\n\t\tauthority.groupId,\n\t\t...deviceIds,\n\t);\n}\n\nfunction reconcileGroupScopeSnapshot(\n\tdb: Database,\n\tauthority: ScopeMembershipCacheAuthority,\n\tscopes: CoordinatorScope[],\n\ttimestamp: string,\n): void {\n\tconst scopeIds = scopes.map((scope) => scope.scope_id);\n\tconst scopeFilter =\n\t\tscopeIds.length > 0 ? `AND scope_id NOT IN (${placeholders(scopeIds.length)})` : \"\";\n\tconst missing = db\n\t\t.prepare(\n\t\t\t`SELECT scope_id\n\t\t\t FROM replication_scopes\n\t\t\t WHERE coordinator_id = ?\n\t\t\t\t AND group_id = ?\n\t\t\t\t AND status <> 'archived'\n\t\t\t\t ${scopeFilter}`,\n\t\t)\n\t\t.all(authority.coordinatorId, authority.groupId, ...scopeIds) as Array<{ scope_id: string }>;\n\tif (missing.length === 0) return;\n\tconst missingScopeIds = missing.map((row) => row.scope_id);\n\tdb.prepare(\n\t\t`UPDATE replication_scopes\n\t\t SET status = 'archived', updated_at = ?\n\t\t WHERE coordinator_id = ?\n\t\t\t AND group_id = ?\n\t\t\t AND scope_id IN (${placeholders(missingScopeIds.length)})`,\n\t).run(timestamp, authority.coordinatorId, authority.groupId, ...missingScopeIds);\n\t// Enrolled-device scope listings are filtered by the requester's current access.\n\t// Archiving the omitted scope fails closed without poisoning unchanged peer rows\n\t// as revoked; a later visible snapshot can reconcile its full membership list.\n}\n\nexport function upsertCachedScopeMemberships(\n\tdb: Database,\n\tmemberships: CoordinatorScopeMembership[],\n): number {\n\tconst insert = db.prepare(\n\t\t`INSERT INTO scope_memberships(\n\t\t\tscope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n\t\tON CONFLICT(scope_id, device_id) DO UPDATE SET\n\t\t\trole = excluded.role,\n\t\t\tstatus = excluded.status,\n\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\tgroup_id = excluded.group_id,\n\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\tsigned_manifest_json = excluded.signed_manifest_json,\n\t\t\tupdated_at = excluded.updated_at\n\t\tWHERE excluded.membership_epoch > scope_memberships.membership_epoch\n\t\t\tOR (\n\t\t\t\texcluded.membership_epoch = scope_memberships.membership_epoch\n\t\t\t\tAND scope_memberships.status != 'revoked'\n\t\t\t)`,\n\t);\n\tlet count = 0;\n\tdb.transaction(() => {\n\t\tfor (const membership of memberships) {\n\t\t\tinsert.run(\n\t\t\t\tmembership.scope_id,\n\t\t\t\tmembership.device_id,\n\t\t\t\tmembership.role,\n\t\t\t\tmembership.status,\n\t\t\t\tmembership.membership_epoch,\n\t\t\t\tmembership.coordinator_id,\n\t\t\t\tmembership.group_id,\n\t\t\t\tmembership.manifest_issuer_device_id,\n\t\t\t\tmembership.manifest_hash,\n\t\t\t\tmembership.signed_manifest_json,\n\t\t\t\tmembership.updated_at,\n\t\t\t);\n\t\t\tcount += 1;\n\t\t}\n\t})();\n\treturn count;\n}\n\nfunction recordRefreshState(\n\tdb: Database,\n\tinput: ScopeMembershipCacheAuthority & { ok: boolean; error?: string | null; now: string },\n): void {\n\tensureScopeMembershipCacheStateTable(db);\n\treadRefreshRevision(db, input);\n\tconst result = db\n\t\t.prepare(\n\t\t\t`INSERT INTO scope_membership_cache_state(\n\t\t\tcoordinator_id, group_id, last_refresh_at, last_success_at, last_error, updated_at, refresh_revision\n\t\t) VALUES (?, ?, ?, ?, ?, ?, 1)\n\t\tON CONFLICT(coordinator_id, group_id) DO UPDATE SET\n\t\t\tlast_refresh_at = excluded.last_refresh_at,\n\t\t\tlast_success_at = COALESCE(excluded.last_success_at, scope_membership_cache_state.last_success_at),\n\t\t\tlast_error = excluded.last_error,\n\t\t\tupdated_at = excluded.updated_at,\n\t\t\trefresh_revision = scope_membership_cache_state.refresh_revision + 1\n\t\tWHERE scope_membership_cache_state.refresh_revision < 9007199254740991`,\n\t\t)\n\t\t.run(\n\t\t\tinput.coordinatorId,\n\t\t\tinput.groupId,\n\t\t\tinput.now,\n\t\t\tinput.ok ? input.now : null,\n\t\t\tinput.ok ? null : (input.error ?? \"unknown\"),\n\t\t\tinput.now,\n\t\t);\n\tif (result.changes !== 1) throw new Error(\"Scope membership cache revision unavailable.\");\n}\n\nfunction recordRefreshFailure(\n\tdb: Database,\n\tinput: ScopeMembershipCacheAuthority & { error: string; now: string },\n\texpectedRevision: number | undefined,\n): string {\n\tif (expectedRevision === undefined) return \"Scope membership cache revision unavailable.\";\n\ttry {\n\t\tdb.transaction(() => {\n\t\t\t// A delayed failure must not overwrite a newer refresh or advance its revision.\n\t\t\tif (readRefreshRevision(db, input) !== expectedRevision) return;\n\t\t\trecordRefreshState(db, { ...input, ok: false });\n\t\t}).immediate();\n\t\treturn input.error;\n\t} catch {\n\t\treturn \"Scope membership cache refresh state unavailable.\";\n\t}\n}\n\nexport async function refreshScopeMembershipCache(\n\tdb: Database,\n\topts: RefreshScopeMembershipCacheOptions,\n): Promise<RefreshScopeMembershipCacheResult> {\n\tconst groups = groupIds(opts.groupIds);\n\tif (groups.length === 0) return { status: \"skipped\", coordinatorId: null, groups: [] };\n\tconst coordinatorId = clean(opts.coordinatorId) ?? authorityId(opts.remoteUrl);\n\tconst authorityForGroup = (groupId: string): ScopeMembershipCacheAuthority => ({\n\t\tcoordinatorId,\n\t\tgroupId,\n\t});\n\tconst fetchers = opts.fetchers ?? defaultFetchers(db, opts);\n\tconst timestamp = nowIso(opts.now);\n\tconst results: RefreshScopeMembershipCacheGroupResult[] = [];\n\n\tfor (const groupId of groups) {\n\t\tlet expectedRevision: number | undefined;\n\t\ttry {\n\t\t\tconst authority = authorityForGroup(groupId);\n\t\t\tensureScopeMembershipCacheStateTable(db);\n\t\t\texpectedRevision = readRefreshRevision(db, authority);\n\t\t\tconst membershipBatches = await gatherCurrentSnapshots(fetchers, authority);\n\t\t\tconst scopes = membershipBatches.map((batch) => batch.scope);\n\t\t\tconst error = persistCurrentSnapshots(\n\t\t\t\tdb,\n\t\t\t\tmembershipBatches,\n\t\t\t\tauthority,\n\t\t\t\ttimestamp,\n\t\t\t\texpectedRevision,\n\t\t\t);\n\t\t\tconst membershipCount = membershipBatches.reduce(\n\t\t\t\t(count, batch) => count + batch.memberships.length,\n\t\t\t\t0,\n\t\t\t);\n\t\t\tresults.push({\n\t\t\t\tgroupId,\n\t\t\t\tstatus: error ? \"stale\" : \"refreshed\",\n\t\t\t\tscopeCount: error ? 0 : scopes.length,\n\t\t\t\tmembershipCount: error ? 0 : membershipCount,\n\t\t\t\terror,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = recordRefreshFailure(\n\t\t\t\tdb,\n\t\t\t\t{ coordinatorId, groupId, error: errorMessage(error), now: timestamp },\n\t\t\t\texpectedRevision,\n\t\t\t);\n\t\t\tresults.push({ groupId, status: \"stale\", scopeCount: 0, membershipCount: 0, error: message });\n\t\t}\n\t}\n\n\tconst refreshed = results.filter((result) => result.status === \"refreshed\").length;\n\tlet status: RefreshScopeMembershipCacheResult[\"status\"] = \"partial\";\n\tif (refreshed === results.length) status = \"refreshed\";\n\telse if (refreshed === 0) status = \"stale\";\n\treturn { status, coordinatorId, groups: results };\n}\n\ntype CurrentScopeBatch = ReturnType<typeof normalizeScopeSnapshot>;\n\nasync function gatherCurrentSnapshots(\n\tfetchers: ScopeMembershipCacheFetchers,\n\tauthority: ScopeMembershipCacheAuthority,\n): Promise<CurrentScopeBatch[]> {\n\tconst catalog = normalizeScopeCatalog(\n\t\tawait fetchers.listScopes(authority.groupId),\n\t\tauthority.groupId,\n\t);\n\tconst batches: CurrentScopeBatch[] = [];\n\tfor (const scope of catalog) {\n\t\tconst snapshot = await fetchers.getScopeSnapshot(authority.groupId, scope.scope_id);\n\t\tbatches.push(\n\t\t\tnormalizeScopeSnapshot(snapshot, scope, authority.groupId, authority.coordinatorId),\n\t\t);\n\t}\n\treturn batches;\n}\n\nfunction matchesSnapshotSource(\n\trow: { coordinator_id: string | null; group_id: string | null },\n\tbatch: CurrentScopeBatch,\n): boolean {\n\treturn (\n\t\t(row.group_id === null || row.group_id === batch.scope.group_id) &&\n\t\t(row.coordinator_id === null ||\n\t\t\trow.coordinator_id === batch.scope.coordinator_id ||\n\t\t\trow.coordinator_id === batch.sourceCoordinatorId)\n\t);\n}\n\nfunction requireUnsupersededSnapshot(db: Database, batch: CurrentScopeBatch): boolean {\n\tconst { scope, memberships } = batch;\n\tconst stored = loadCachedScope(db, scope.scope_id);\n\tif (\n\t\tstored &&\n\t\t(stored.membership_epoch > scope.membership_epoch || !matchesSnapshotSource(stored, batch))\n\t)\n\t\tthrow new Error(\"Current scope snapshot conflicts with cached authority or epoch.\");\n\tconst rows = db\n\t\t.prepare(\n\t\t\t\"SELECT device_id, status, membership_epoch, coordinator_id, group_id FROM scope_memberships WHERE scope_id = ?\",\n\t\t)\n\t\t.all(scope.scope_id) as CoordinatorScopeMembership[];\n\tconst incoming = new Map(memberships.map((member) => [member.device_id, member]));\n\tlet revivalConflict = false;\n\tfor (const row of rows) {\n\t\tconst member = incoming.get(row.device_id);\n\t\t// Current omissions remove access even when the member advanced beyond the scope epoch.\n\t\tif (\n\t\t\t(member && row.membership_epoch > member.membership_epoch) ||\n\t\t\t!matchesSnapshotSource(row, batch)\n\t\t)\n\t\t\tthrow new Error(\"Current scope snapshot superseded by cached membership.\");\n\t\tif (member && row.status === \"revoked\" && row.membership_epoch === member.membership_epoch)\n\t\t\trevivalConflict = true;\n\t}\n\treturn revivalConflict;\n}\n\nfunction migrateSnapshotMembershipAuthority(db: Database, batch: CurrentScopeBatch): void {\n\tdb.prepare(\n\t\t`UPDATE scope_memberships SET coordinator_id = ?, group_id = ?\n\t\t WHERE scope_id = ? AND COALESCE(group_id, ?) = ?\n\t\t AND COALESCE(coordinator_id, ?) IN (?, ?)`,\n\t).run(\n\t\tbatch.scope.coordinator_id,\n\t\tbatch.scope.group_id,\n\t\tbatch.scope.scope_id,\n\t\tbatch.scope.group_id,\n\t\tbatch.scope.group_id,\n\t\tbatch.scope.coordinator_id,\n\t\tbatch.scope.coordinator_id,\n\t\tbatch.sourceCoordinatorId,\n\t);\n}\n\nfunction persistCurrentSnapshots(\n\tdb: Database,\n\tbatches: CurrentScopeBatch[],\n\tauthority: ScopeMembershipCacheAuthority,\n\ttimestamp: string,\n\texpectedRevision: number,\n): string | null {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tif (readRefreshRevision(db, authority) !== expectedRevision)\n\t\t\t\treturn \"Current scope snapshot superseded by a newer cache refresh.\";\n\t\t\t// Validate every batch before writes, even when an earlier batch cannot revive a row.\n\t\t\tconst conflicts = batches.map((batch) => requireUnsupersededSnapshot(db, batch));\n\t\t\tconst error = conflicts.some(Boolean)\n\t\t\t\t? \"Current scope snapshot cannot revive cached revoked membership at the same epoch.\"\n\t\t\t\t: null;\n\t\t\tfor (const batch of batches) {\n\t\t\t\tif (!error) {\n\t\t\t\t\tupsertScope(db, batch.scope);\n\t\t\t\t\tmigrateSnapshotMembershipAuthority(db, batch);\n\t\t\t\t\tupsertCachedScopeMemberships(db, batch.memberships);\n\t\t\t\t}\n\t\t\t\treconcileScopeMembershipSnapshot(db, batch, authority, timestamp);\n\t\t\t}\n\t\t\treconcileGroupScopeSnapshot(\n\t\t\t\tdb,\n\t\t\t\tauthority,\n\t\t\t\tbatches.map((batch) => batch.scope),\n\t\t\t\ttimestamp,\n\t\t\t);\n\t\t\ttry {\n\t\t\t\treconcileScopeAuthorizationEvidence(db, batches, authority, {\n\t\t\t\t\tremovalOnly: error !== null,\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\"Scope authorization evidence unavailable.\");\n\t\t\t}\n\t\t\trecordRefreshState(db, { ...authority, ok: error === null, error, now: timestamp });\n\t\t\treturn error;\n\t\t})\n\t\t.immediate();\n}\n\nexport async function refreshConfiguredScopeMembershipCache(\n\tdb: Database,\n\tconfig?: CoordinatorSyncConfig,\n\toptions?: { keysDir?: string | null; dbPath?: string },\n): Promise<RefreshScopeMembershipCacheResult> {\n\tconst syncConfig = config ?? readCoordinatorSyncConfig();\n\tif (!coordinatorEnabled(syncConfig)) {\n\t\treturn { status: \"skipped\", coordinatorId: null, groups: [] };\n\t}\n\treturn refreshScopeMembershipCache(db, {\n\t\tgroupIds: syncConfig.syncCoordinatorGroups,\n\t\tcoordinatorId: authorityId(syncConfig.syncCoordinatorUrl),\n\t\tremoteUrl: syncConfig.syncCoordinatorUrl,\n\t\tadminSecret: syncConfig.syncCoordinatorAdminSecret,\n\t\tkeysDir: options?.keysDir ?? null,\n\t\tdbPath: options?.dbPath,\n\t});\n}\n","/**\n * Shared address normalization utilities for the sync system.\n *\n * Used by both coordinator-store and sync-discovery to ensure\n * consistent address handling across the sync pipeline.\n */\n\n/** Keep serial peer dialing bounded when network interfaces churn over time. */\nexport const MAX_PEER_ADDRESSES = 8;\n\n/** Leave room for previously configured or successfully dialed fallback addresses. */\nconst COORDINATOR_FALLBACK_ADDRESSES = 2;\n\ninterface MergeAddressOptions {\n\tdefaultHttpPort?: number;\n\tmaxAddresses?: number;\n}\n\n/**\n * Normalize an address to a consistent URL form.\n *\n * Uses the built-in URL constructor for consistent normalization:\n * lowercases host, strips default ports (80/443), trims trailing slashes.\n * Returns empty string for invalid/empty input.\n */\nexport function normalizeAddress(address: string, options?: { defaultHttpPort?: number }): string {\n\tconst value = address.trim();\n\tif (!value) return \"\";\n\n\tconst hasScheme = value.includes(\"://\");\n\tconst withScheme = hasScheme ? value : `http://${value}`;\n\tconst hasExplicitDefaultHttpPort = /^http:\\/\\/(?:\\[[^\\]]+\\]|[^/?#:]+):0*80(?:[/?#]|$)/i.test(\n\t\twithScheme,\n\t);\n\n\ttry {\n\t\tconst url = new URL(withScheme);\n\t\tif (!url.hostname) return \"\";\n\t\tif (url.port && (Number(url.port) <= 0 || Number(url.port) > 65535)) return \"\";\n\t\tif (\n\t\t\t!url.port &&\n\t\t\t!hasExplicitDefaultHttpPort &&\n\t\t\turl.protocol === \"http:\" &&\n\t\t\toptions?.defaultHttpPort\n\t\t) {\n\t\t\tconst port = Math.trunc(options.defaultHttpPort);\n\t\t\tif (port <= 0 || port > 65535) return \"\";\n\t\t\tif (port !== 80 && (!hasScheme || /^http:\\/\\//i.test(value))) {\n\t\t\t\turl.port = String(port);\n\t\t\t}\n\t\t}\n\t\treturn url.origin + url.pathname.replace(/\\/+$/, \"\");\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nexport function formatHostPort(host: string, port: number): string {\n\tconst value = host.trim();\n\tif (!value) return \"\";\n\tconst normalizedPort = Math.trunc(port);\n\tif (normalizedPort <= 0 || normalizedPort > 65535) return \"\";\n\tconst authorityHost = value.includes(\":\") && !value.startsWith(\"[\") ? `[${value}]` : value;\n\treturn `${authorityHost}:${normalizedPort}`;\n}\n\n/**\n * Produce a dedupe key for an address while preserving scheme and path.\n */\nexport function addressDedupeKey(address: string): string {\n\tif (!address) return \"\";\n\ttry {\n\t\tconst url = new URL(address);\n\t\tconst host = url.hostname.toLowerCase();\n\t\tif (host && url.port) return `${url.protocol}//${host}:${url.port}${url.pathname}`;\n\t\tif (host) return `${url.protocol}//${host}${url.pathname}`;\n\t} catch {\n\t\t// Not parseable\n\t}\n\treturn address;\n}\n\n/**\n * Merge two address lists, normalizing and deduplicating.\n * Existing addresses come first, then new candidates.\n */\nexport function mergeAddresses(\n\texisting: string[],\n\tcandidates: string[],\n\toptions?: MergeAddressOptions,\n): string[] {\n\tconst normalized: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const address of [...existing, ...candidates]) {\n\t\tconst cleaned = normalizeAddress(address, options);\n\t\tconst key = addressDedupeKey(cleaned);\n\t\tif (!cleaned || seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tnormalized.push(cleaned);\n\t\tif (options?.maxAddresses && normalized.length >= options.maxAddresses) break;\n\t}\n\treturn normalized;\n}\n\n/**\n * Merge address lists while preferring newly discovered candidates first.\n * Useful for coordinator presence refreshes where fresh addresses should beat\n * stale cached LAN/Docker addresses without dropping still-useful fallbacks.\n */\nexport function mergeAddressesPreferCandidates(\n\texisting: string[],\n\tcandidates: string[],\n\toptions?: MergeAddressOptions,\n): string[] {\n\treturn mergeAddresses(candidates, existing, options);\n}\n\nfunction isIpv6LinkLocalAddress(address: string): boolean {\n\ttry {\n\t\t// URL hosts use brackets; fe80::/10 includes fe80 through febf.\n\t\treturn /^\\[fe[89ab][0-9a-f]:/i.test(new URL(address).hostname);\n\t} catch {\n\t\t// Preserve legacy normalization behavior for addresses without a URL origin.\n\t\treturn false;\n\t}\n}\n\n/** Prefer coordinator results without letting a full response evict every existing fallback. */\nexport function mergeCoordinatorPeerAddresses(\n\texisting: string[],\n\tcandidates: string[],\n\tmanual: string[] = [],\n\toptions?: { requiredFreshAddresses?: number; successfulAddress?: string },\n): string[] {\n\tconst pinned = mergeAddresses(manual, []);\n\tconst manualFallbacks =\n\t\tpinned.length <= MAX_PEER_ADDRESSES\n\t\t\t? pinned\n\t\t\t: mergeAddresses(pinned.slice(0, 2), pinned.slice(-2));\n\tconst protectedAddresses = mergeAddresses(\n\t\toptions?.successfulAddress ? [options.successfulAddress] : [],\n\t\tmanualFallbacks,\n\t\t{ maxAddresses: MAX_PEER_ADDRESSES },\n\t);\n\tconst freshCandidates = mergeAddresses(candidates, []);\n\t// Explicit pairing keeps its supplied order; only coordinator presence is ranked.\n\tif (options?.requiredFreshAddresses === undefined) {\n\t\tfreshCandidates.sort(\n\t\t\t(left, right) => Number(isIpv6LinkLocalAddress(left)) - Number(isIpv6LinkLocalAddress(right)),\n\t\t);\n\t}\n\tconst fallbackFreshLimit = protectedAddresses.length\n\t\t? MAX_PEER_ADDRESSES - protectedAddresses.length\n\t\t: MAX_PEER_ADDRESSES - COORDINATOR_FALLBACK_ADDRESSES;\n\tconst coordinatorFreshLimit =\n\t\toptions?.requiredFreshAddresses === undefined\n\t\t\t? Math.min(freshCandidates.length, MAX_PEER_ADDRESSES - COORDINATOR_FALLBACK_ADDRESSES)\n\t\t\t: 0;\n\tconst freshLimit = Math.max(\n\t\tfallbackFreshLimit,\n\t\t// A large manual archive must not crowd current coordinator addresses out of dialing.\n\t\tcoordinatorFreshLimit,\n\t\tMath.min(\n\t\t\toptions?.requiredFreshAddresses ?? (freshCandidates.length > 0 ? 1 : 0),\n\t\t\tMAX_PEER_ADDRESSES,\n\t\t),\n\t);\n\tif (freshLimit === 0) return protectedAddresses;\n\tconst fresh = freshCandidates.slice(0, freshLimit);\n\tconst withManual = mergeAddresses(\n\t\tfresh,\n\t\tprotectedAddresses.slice(0, MAX_PEER_ADDRESSES - freshLimit),\n\t\t{\n\t\t\tmaxAddresses: MAX_PEER_ADDRESSES,\n\t\t},\n\t);\n\tconst withFallbacks = mergeAddresses(withManual, existing, { maxAddresses: MAX_PEER_ADDRESSES });\n\treturn mergeAddresses(withFallbacks, freshCandidates, { maxAddresses: MAX_PEER_ADDRESSES });\n}\n","import { eq, sql } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport {\n\tMAX_PEER_ADDRESSES,\n\tmergeAddresses,\n\tmergeCoordinatorPeerAddresses,\n} from \"./address-utils.js\";\nimport type { Database } from \"./db.js\";\nimport * as schema from \"./schema.js\";\n\nexport function loadPeerAddresses(db: Database, peerDeviceId: string): string[] {\n\tconst d = drizzle(db, { schema });\n\tconst row = d\n\t\t.select({ addresses_json: schema.syncPeers.addresses_json })\n\t\t.from(schema.syncPeers)\n\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t.get();\n\tif (!row?.addresses_json) return [];\n\ttry {\n\t\tconst raw = JSON.parse(row.addresses_json);\n\t\tif (!Array.isArray(raw)) return [];\n\t\treturn raw.filter((item): item is string => typeof item === \"string\");\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/** Null means the peer predates source tracking; its existing addresses must be preserved on first refresh. */\nexport function loadManualPeerAddresses(db: Database, peerDeviceId: string): string[] | null {\n\tconst row = db\n\t\t.prepare(\"SELECT manual_addresses_json FROM sync_peers WHERE peer_device_id = ?\")\n\t\t.get(peerDeviceId) as { manual_addresses_json: string | null } | undefined;\n\tif (row?.manual_addresses_json == null) return null;\n\ttry {\n\t\tconst raw: unknown = JSON.parse(row.manual_addresses_json);\n\t\treturn Array.isArray(raw) ? raw.filter((item): item is string => typeof item === \"string\") : [];\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nexport function loadSuccessfulPeerAddress(db: Database, peerDeviceId: string): string | null {\n\tconst row = db\n\t\t.prepare(\"SELECT last_success_address FROM sync_peers WHERE peer_device_id = ?\")\n\t\t.get(peerDeviceId) as { last_success_address: string | null } | undefined;\n\treturn row?.last_success_address ?? null;\n}\n\nexport function updatePeerAddresses(\n\tdb: Database,\n\tpeerDeviceId: string,\n\taddresses: string[],\n\toptions?: {\n\t\tname?: string;\n\t\tpinnedFingerprint?: string;\n\t\tpublicKey?: string;\n\t\treplaceTrust?: boolean;\n\t\tcoordinatorCandidates?: boolean;\n\t},\n): string[] {\n\tconst existingAddresses = loadPeerAddresses(db, peerDeviceId);\n\tconst storedManual = loadManualPeerAddresses(db, peerDeviceId);\n\tconst legacyManual = storedManual == null ? existingAddresses : storedManual;\n\tconst manual =\n\t\toptions?.replaceTrust && addresses.length > 0\n\t\t\t? mergeAddresses(legacyManual, addresses)\n\t\t\t: legacyManual;\n\tconst successfulAddress = loadSuccessfulPeerAddress(db, peerDeviceId) ?? undefined;\n\tlet merged = mergeAddresses(existingAddresses, addresses);\n\tif (options?.coordinatorCandidates) {\n\t\tmerged = mergeCoordinatorPeerAddresses(existingAddresses, addresses, manual, {\n\t\t\tsuccessfulAddress,\n\t\t});\n\t} else if (options?.replaceTrust && addresses.length > 0) {\n\t\tmerged = mergeCoordinatorPeerAddresses(existingAddresses, addresses, manual, {\n\t\t\trequiredFreshAddresses: Math.min(mergeAddresses(addresses, []).length, MAX_PEER_ADDRESSES),\n\t\t\tsuccessfulAddress,\n\t\t});\n\t}\n\tconst now = new Date().toISOString();\n\tconst addressesJson = JSON.stringify(merged);\n\n\t// Atomic UPSERT — avoids TOCTOU race with concurrent sync workers\n\tconst d = drizzle(db, { schema });\n\td.insert(schema.syncPeers)\n\t\t.values({\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\tname: options?.name ?? null,\n\t\t\tpinned_fingerprint: options?.pinnedFingerprint ?? null,\n\t\t\tpublic_key: options?.publicKey ?? null,\n\t\t\taddresses_json: addressesJson,\n\t\t\tmanual_addresses_json: JSON.stringify(manual),\n\t\t\tcreated_at: now,\n\t\t\tlast_seen_at: now,\n\t\t})\n\t\t.onConflictDoUpdate({\n\t\t\ttarget: schema.syncPeers.peer_device_id,\n\t\t\tset: {\n\t\t\t\tname: sql`COALESCE(excluded.name, ${schema.syncPeers.name})`,\n\t\t\t\tpinned_fingerprint: options?.replaceTrust\n\t\t\t\t\t? sql`COALESCE(excluded.pinned_fingerprint, ${schema.syncPeers.pinned_fingerprint})`\n\t\t\t\t\t: sql`COALESCE(${schema.syncPeers.pinned_fingerprint}, excluded.pinned_fingerprint)`,\n\t\t\t\tpublic_key: options?.replaceTrust\n\t\t\t\t\t? sql`COALESCE(excluded.public_key, ${schema.syncPeers.public_key})`\n\t\t\t\t\t: sql`COALESCE(${schema.syncPeers.public_key}, excluded.public_key)`,\n\t\t\t\taddresses_json: sql`excluded.addresses_json`,\n\t\t\t\tmanual_addresses_json: sql`excluded.manual_addresses_json`,\n\t\t\t\tlast_seen_at: sql`excluded.last_seen_at`,\n\t\t\t},\n\t\t})\n\t\t.run();\n\n\treturn merged;\n}\n","/**\n * Sync protocol capability negotiation helpers.\n *\n * Capability is intentionally separate from protocol_version. The wire protocol\n * remains version 2 while peers advertise how much of the future scope-aware\n * sync contract they understand.\n */\n\nexport const SYNC_CAPABILITIES = [\"unsupported\", \"aware\", \"enforcing\", \"scoped\"] as const;\n\nexport const SYNC_CAPABILITY_HEADER = \"X-Codemem-Sync-Capability\";\n\nexport const SYNC_FEATURES_HEADER = \"X-Codemem-Sync-Features\";\nexport const SYNC_AUTHORIZATION_REFRESH_HEADER = \"X-Codemem-Refresh-Authorization\";\nexport const SYNC_FEATURES = [\n\t\"reassign_scope\",\n\t\"memory_scope_retirement_v1\",\n\t\"relay\",\n\t\"relay_aware\",\n] as const;\n// Retirement is recognized but not advertised until snapshot and admission gates are complete.\n// `relay_aware` marks a build that reports `relay` truthfully, so a peer can tell \"this device\n// runs no relay client\" from \"this device predates the `relay` feature\". `relay` itself is\n// advertised only by a viewer that runs a relay client; see `setLocalSyncFeature`.\nexport const LOCAL_SYNC_FEATURES: SyncFeature[] = [\"reassign_scope\", \"relay_aware\"];\n\n/**\n * Turn a locally advertised feature on or off for this process. The viewer calls\n * this for `relay` once it knows whether it runs a relay client, before any peer\n * exchange, so status replies and outbound headers describe this device truthfully.\n */\nexport function setLocalSyncFeature(feature: SyncFeature, enabled: boolean): void {\n\tconst index = LOCAL_SYNC_FEATURES.indexOf(feature);\n\tif (enabled && index < 0) LOCAL_SYNC_FEATURES.push(feature);\n\tif (!enabled && index >= 0) LOCAL_SYNC_FEATURES.splice(index, 1);\n\tLOCAL_SYNC_FEATURES.sort();\n}\n\nexport type SyncCapability = (typeof SYNC_CAPABILITIES)[number];\nexport type SyncFeature = (typeof SYNC_FEATURES)[number];\n\nexport function normalizeSyncFeatures(value: unknown): SyncFeature[] {\n\tconst values = Array.isArray(value) ? value : typeof value === \"string\" ? value.split(\",\") : [];\n\treturn [\n\t\t...new Set(\n\t\t\tvalues\n\t\t\t\t.map((item) => String(item).trim().toLowerCase())\n\t\t\t\t.filter((item): item is SyncFeature => SYNC_FEATURES.includes(item as SyncFeature)),\n\t\t),\n\t].toSorted();\n}\n\nexport function supportsSyncFeature(value: unknown, feature: SyncFeature): boolean {\n\treturn normalizeSyncFeatures(value).includes(feature);\n}\n\n/**\n * Local sync capability advertised on every wire response and outbound request.\n *\n * `scoped` (rank 3) signals the peer understands the per-Space sync protocol\n * defined in docs/plans/2026-05-25-scoped-sync-protocol.md:\n * - GET /v1/status emits `authorized_scopes` when caller is also scoped.\n * - GET /v1/ops and GET /v1/snapshot accept a signed `scope_id` query param.\n * - POST /v1/ops accepts a `scope_id` field in the signed body.\n *\n * Mixed-version pairs negotiate down to the lower rank (`aware`), so legacy\n * default-scope behavior is preserved end-to-end for either side that does\n * not advertise `scoped`.\n */\nexport const LOCAL_SYNC_CAPABILITY: SyncCapability = \"scoped\";\n\nconst CAPABILITY_RANK: Record<SyncCapability, number> = {\n\tunsupported: 0,\n\taware: 1,\n\tenforcing: 2,\n\tscoped: 3,\n};\n\n/**\n * True when the negotiated capability supports per-Space scoped sync.\n *\n * Use this to gate `authorized_scopes` enumeration on /v1/status and to\n * decide whether to honor an explicit `scope_id` parameter on the other\n * sync routes. Returns false for `aware` / `enforcing` / `unsupported`,\n * preserving legacy default-scope behavior.\n */\nexport function isScopedSyncCapability(capability: SyncCapability): boolean {\n\treturn CAPABILITY_RANK[capability] >= CAPABILITY_RANK.scoped;\n}\n\nexport function normalizeSyncCapability(value: unknown): SyncCapability {\n\tif (typeof value !== \"string\") return \"unsupported\";\n\tconst normalized = value.trim().toLowerCase();\n\treturn SYNC_CAPABILITIES.includes(normalized as SyncCapability)\n\t\t? (normalized as SyncCapability)\n\t\t: \"unsupported\";\n}\n\nexport function negotiateSyncCapability(\n\tlocalCapability: unknown,\n\tpeerCapability: unknown,\n): SyncCapability {\n\tconst local = normalizeSyncCapability(localCapability);\n\tconst peer = normalizeSyncCapability(peerCapability);\n\treturn CAPABILITY_RANK[local] <= CAPABILITY_RANK[peer] ? local : peer;\n}\n","export const PEER_HTTP_LIMITS = Object.freeze({\n\theaderBytes: 16384,\n\trequestBytes: 1048576,\n\tresponseBytes: 16777216,\n\texchangeMs: 60000,\n\tcleanupMs: 1500,\n});\n\nexport type PeerHttpExchangeErrorCode =\n\t| \"framing\"\n\t| \"response_too_large\"\n\t| \"deadline\"\n\t| \"cancelled\"\n\t| \"transport\"\n\t| \"cleanup\";\n\nconst MESSAGES: Record<PeerHttpExchangeErrorCode, string> = {\n\tframing: \"Invalid peer HTTP framing\",\n\tresponse_too_large: \"Peer HTTP response exceeds the size limit\",\n\tdeadline: \"Peer HTTP exchange deadline exceeded\",\n\tcancelled: \"Peer HTTP exchange cancelled\",\n\ttransport: \"Peer HTTP transport failed\",\n\tcleanup: \"Peer HTTP cleanup failed\",\n};\n\nexport class PeerHttpExchangeError extends Error {\n\tconstructor(readonly code: PeerHttpExchangeErrorCode) {\n\t\tsuper(MESSAGES[code]);\n\t\tthis.name = \"PeerHttpExchangeError\";\n\t}\n}\n","import { performance } from \"node:perf_hooks\";\nimport { Duplex } from \"node:stream\";\nimport { types } from \"node:util\";\nimport type { OwnedPeerHttpConnection } from \"./peer-http-client.js\";\nimport {\n\tPEER_HTTP_LIMITS,\n\tPeerHttpExchangeError,\n\ttype PeerHttpExchangeErrorCode,\n} from \"./peer-http-policy.js\";\n\n/** One exchange's absolute deadline and first locally classified failure. */\nexport class PeerHttpLifetime {\n\treadonly controller = new AbortController();\n\tprivate readonly stopped = Promise.withResolvers<never>();\n\tprivate readonly timer: ReturnType<typeof setTimeout>;\n\tprivate failure?: PeerHttpExchangeError;\n\tprivate readonly abort = (): void => {\n\t\tthis.fail(\"cancelled\");\n\t};\n\n\tconstructor(\n\t\treadonly deadlineMs: number,\n\t\tprivate readonly signal?: AbortSignal,\n\t) {\n\t\tvoid this.stopped.promise.catch(() => {});\n\t\tthis.timer = setTimeout(\n\t\t\t() => this.fail(\"deadline\"),\n\t\t\tMath.max(0, deadlineMs - performance.now()),\n\t\t);\n\t\tsignal?.addEventListener(\"abort\", this.abort, { once: true });\n\t\tif (signal?.aborted) this.abort();\n\t}\n\n\tget failed(): boolean {\n\t\treturn this.failure !== undefined;\n\t}\n\n\tfail(code: PeerHttpExchangeErrorCode): PeerHttpExchangeError {\n\t\tthis.failure ??= new PeerHttpExchangeError(code);\n\t\t// The relay route reads this reason to tell a malformed response from a deadline.\n\t\tthis.controller.abort(this.failure);\n\t\tthis.stopped.reject(this.failure);\n\t\treturn this.failure;\n\t}\n\n\tcheck(): void {\n\t\tif (this.failure) throw this.failure;\n\t\tif (performance.now() >= this.deadlineMs) throw this.fail(\"deadline\");\n\t}\n\n\tasync wait<T>(promise: Promise<T>): Promise<T> {\n\t\tconst value = await Promise.race([promise, this.stopped.promise]);\n\t\tthis.check();\n\t\treturn value;\n\t}\n\n\tclose(): void {\n\t\tclearTimeout(this.timer);\n\t\tthis.signal?.removeEventListener(\"abort\", this.abort);\n\t}\n}\n\n/** The trusted port owns raw I/O and disposal. This wrapper calls its disposer at most once. */\nexport function adoptPeerHttpConnection(connection: OwnedPeerHttpConnection) {\n\tconst dispose = connection.dispose.bind(connection);\n\tlet cleanup: Promise<void> | undefined;\n\tconst cleanupOwner = {\n\t\tdispose: (error: Error): Promise<void> => {\n\t\t\tcleanup ??= boundedCleanup(() => dispose(error));\n\t\t\treturn cleanup;\n\t\t},\n\t};\n\ttry {\n\t\t// A missing value or arbitrary thenable cannot prove clean raw I/O and disposal.\n\t\tconst completion = connection.completion;\n\t\tif (!types.isPromise(completion)) return { valid: false as const, ...cleanupOwner };\n\t\tvoid completion.catch(() => {});\n\t\tconst duplex = connection.duplex;\n\t\tif (!(duplex instanceof Duplex)) return { valid: false as const, ...cleanupOwner };\n\t\treturn { valid: true as const, ...cleanupOwner, duplex, completion };\n\t} catch {\n\t\t// Preserve the captured disposer when a later port getter or validation fails.\n\t\treturn { valid: false as const, ...cleanupOwner };\n\t}\n}\n\nasync function boundedCleanup(dispose: () => Promise<void>): Promise<void> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\ttry {\n\t\tawait Promise.race([\n\t\t\tPromise.resolve().then(dispose),\n\t\t\tnew Promise<never>((_resolve, reject) => {\n\t\t\t\ttimer = setTimeout(\n\t\t\t\t\t() => reject(new PeerHttpExchangeError(\"cleanup\")),\n\t\t\t\t\tPEER_HTTP_LIMITS.cleanupMs,\n\t\t\t\t);\n\t\t\t}),\n\t\t]);\n\t} catch {\n\t\tthrow new PeerHttpExchangeError(\"cleanup\");\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n","import { validateHeaderName, validateHeaderValue } from \"node:http\";\nimport { PEER_HTTP_LIMITS, PeerHttpExchangeError } from \"./peer-http-policy.js\";\nimport type { RequestJsonOptions } from \"./sync-http-client.js\";\n\nconst FORBIDDEN = new Set([\"transfer-encoding\", \"trailer\", \"upgrade\", \"expect\"]);\nconst typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);\nconst byteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, \"byteLength\")?.get;\nconst tag = Object.getOwnPropertyDescriptor(typedArrayPrototype, Symbol.toStringTag)?.get;\nconst nativeSet = Uint8Array.prototype.set;\n\nexport function peerHttpBodyCap(direction: \"request\" | \"response\", supplied?: number): number {\n\tconst maximum =\n\t\tdirection === \"request\" ? PEER_HTTP_LIMITS.requestBytes : PEER_HTTP_LIMITS.responseBytes;\n\tconst value = supplied === undefined ? maximum : supplied;\n\tif (!Number.isSafeInteger(value) || value < 0 || value > maximum)\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\treturn value;\n}\n\nfunction validateHeader(name: string, value: string, seen: Set<string>): string {\n\tvalidateHeaderName(name);\n\tvalidateHeaderValue(name, value);\n\tconst lower = name.toLowerCase();\n\tif (typeof value !== \"string\" || seen.has(lower) || FORBIDDEN.has(lower))\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\tseen.add(lower);\n\treturn lower;\n}\n\nfunction declaredLength(rawHeaders: readonly string[]): number {\n\tif (!Array.isArray(rawHeaders) || rawHeaders.length % 2 !== 0) throw new Error();\n\tconst seen = new Set<string>();\n\tlet declared: string | undefined;\n\tfor (let index = 0; index < rawHeaders.length; index += 2) {\n\t\tconst name = rawHeaders[index];\n\t\tconst value = rawHeaders[index + 1];\n\t\tif (typeof name !== \"string\" || typeof value !== \"string\") throw new Error();\n\t\tif (validateHeader(name, value, seen) === \"content-length\") declared = value;\n\t}\n\tif (declared === undefined || !/^[0-9]+$/.test(declared)) throw new Error();\n\treturn Number(declared);\n}\n\n/** Header policy only. The caller separately checks HTTP version, trailers and wire EOF. */\nexport function readPeerHttpBodyLength(\n\trawHeaders: readonly string[],\n\toptions: { direction: \"request\" | \"response\"; maxBodyBytes?: number },\n): number {\n\tlet captured: { direction: \"request\" | \"response\"; cap: number; length: number };\n\ttry {\n\t\tconst { direction, maxBodyBytes } = options;\n\t\tif (direction !== \"request\" && direction !== \"response\") throw new Error();\n\t\tcaptured = {\n\t\t\tdirection,\n\t\t\tcap: peerHttpBodyCap(direction, maxBodyBytes),\n\t\t\tlength: declaredLength(rawHeaders),\n\t\t};\n\t} catch {\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t}\n\tif (captured.length > captured.cap && captured.direction === \"response\")\n\t\tthrow new PeerHttpExchangeError(\"response_too_large\");\n\tif (!Number.isSafeInteger(captured.length) || captured.length > captured.cap)\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\treturn captured.length;\n}\n\nfunction copyBody(options: RequestJsonOptions): { bytes: Buffer; supplied: boolean } {\n\tconst bytes = options.bodyBytes;\n\tif (bytes === undefined) {\n\t\tif (options.body !== undefined) throw new Error();\n\t\treturn { bytes: Buffer.alloc(0), supplied: false };\n\t}\n\tif (tag?.call(bytes) !== \"Uint8Array\") throw new Error();\n\tconst length: number = byteLength?.call(bytes);\n\tif (!Number.isSafeInteger(length) || length > PEER_HTTP_LIMITS.requestBytes) throw new Error();\n\tconst owned = Buffer.alloc(length);\n\tnativeSet.call(owned, bytes);\n\treturn { bytes: owned, supplied: true };\n}\n\nfunction requestTarget(url: string) {\n\tif (typeof url !== \"string\") throw new Error();\n\tfor (const character of url) {\n\t\tconst code = character.charCodeAt(0);\n\t\tif (code <= 32 || code === 127 || character === \"\\\\\" || character === \"#\") throw new Error();\n\t}\n\tconst parsed = new URL(url);\n\tif (\n\t\t(parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n\t\tparsed.username ||\n\t\tparsed.password\n\t)\n\t\tthrow new Error();\n\tconst match = /^https?:\\/\\/[^/?#]+(.*)$/.exec(url);\n\tlet path = match?.[1];\n\tif (path === undefined) throw new Error();\n\tif (path === \"\" || path.startsWith(\"?\")) path = `/${path}`;\n\tif (path !== parsed.pathname + parsed.search) throw new Error();\n\treturn { path, host: parsed.host, hostname: parsed.hostname };\n}\n\nfunction prepareHeaders(\n\tsupplied: Record<string, string> | undefined,\n\thost: string,\n\tbody: ReturnType<typeof copyBody>,\n) {\n\tconst headers: Record<string, string> = Object.create(null);\n\tconst seen = new Set<string>();\n\tif (supplied !== undefined) {\n\t\tif (typeof supplied !== \"object\" || supplied === null || Array.isArray(supplied))\n\t\t\tthrow new Error();\n\t\tfor (const name of Object.keys(supplied)) {\n\t\t\tconst value = supplied[name];\n\t\t\tif (typeof value !== \"string\") throw new Error();\n\t\t\theaders[validateHeader(name, value, seen)] = value;\n\t\t}\n\t}\n\tif (headers.host !== undefined && headers.host !== host) throw new Error();\n\tconst length = headers[\"content-length\"];\n\tif (length !== undefined && (!/^[0-9]+$/.test(length) || Number(length) !== body.bytes.length))\n\t\tthrow new Error();\n\theaders.host = host;\n\theaders.connection = \"close\";\n\theaders[\"content-length\"] ??= String(body.bytes.length);\n\theaders.accept ??= \"application/json\";\n\tif (body.supplied) headers[\"content-type\"] ??= \"application/json\";\n\treturn headers;\n}\n\n/** Captures request inputs and bounds the exact deterministic native header serialization. */\nexport function preparePeerHttpRequest(method: string, url: string, options: RequestJsonOptions) {\n\ttry {\n\t\tif (typeof options !== \"object\" || options === null || Array.isArray(options))\n\t\t\tthrow new Error();\n\t\tif (method !== \"GET\" && method !== \"POST\") throw new Error();\n\t\tconst target = requestTarget(url);\n\t\tconst body = copyBody(options);\n\t\tconst { headers: supplied, timeoutS, maxResponseBytes } = options;\n\t\tif (timeoutS !== undefined && (!Number.isFinite(timeoutS) || timeoutS <= 0 || timeoutS > 60))\n\t\t\tthrow new Error();\n\t\tconst headers = prepareHeaders(supplied, target.host, body);\n\t\tlet headerBytes = Buffer.byteLength(`${method} ${target.path} HTTP/1.1\\r\\n\\r\\n`, \"latin1\");\n\t\tfor (const [name, value] of Object.entries(headers))\n\t\t\theaderBytes += Buffer.byteLength(`${name}: ${value}\\r\\n`, \"latin1\");\n\t\tif (headerBytes > PEER_HTTP_LIMITS.headerBytes) throw new Error();\n\t\treturn {\n\t\t\tmethod,\n\t\t\t...target,\n\t\t\theaders,\n\t\t\tbody: body.bytes,\n\t\t\tlifetimeMs: timeoutS === undefined ? PEER_HTTP_LIMITS.exchangeMs : timeoutS * 1000,\n\t\t\tmaxResponseBytes: peerHttpBodyCap(\"response\", maxResponseBytes),\n\t\t};\n\t} catch {\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t}\n}\n","import { STATUS_CODES } from \"node:http\";\nimport { readPeerHttpBodyLength } from \"./peer-http-headers.js\";\nimport { PEER_HTTP_LIMITS, PeerHttpExchangeError } from \"./peer-http-policy.js\";\nimport type { PeerHttpServerResponse } from \"./peer-http-server.js\";\n\nconst typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);\nconst byteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, \"byteLength\")?.get;\nconst tag = Object.getOwnPropertyDescriptor(typedArrayPrototype, Symbol.toStringTag)?.get;\nconst nativeSet = Uint8Array.prototype.set;\n\nfunction copyResponseBody(bytes: Uint8Array): Buffer {\n\tif (tag?.call(bytes) !== \"Uint8Array\") throw new PeerHttpExchangeError(\"framing\");\n\tconst length: number = byteLength?.call(bytes);\n\tif (length > PEER_HTTP_LIMITS.responseBytes)\n\t\tthrow new PeerHttpExchangeError(\"response_too_large\");\n\tif (!Number.isSafeInteger(length) || length < 0) throw new PeerHttpExchangeError(\"framing\");\n\tconst owned = Buffer.alloc(length);\n\tnativeSet.call(owned, bytes);\n\treturn owned;\n}\n\nfunction captureHeaders(supplied: PeerHttpServerResponse[\"headers\"], length: number) {\n\tconst headers: Record<string, string> = Object.create(null);\n\tconst rawHeaders: string[] = [];\n\tif (supplied !== undefined) {\n\t\tif (typeof supplied !== \"object\" || supplied === null || Array.isArray(supplied))\n\t\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t\tfor (const name of Object.keys(supplied)) {\n\t\t\tconst value = supplied[name];\n\t\t\tif (typeof value !== \"string\") throw new PeerHttpExchangeError(\"framing\");\n\t\t\trawHeaders.push(name, value);\n\t\t\theaders[name.toLowerCase()] = value;\n\t\t}\n\t}\n\tif (headers[\"content-length\"] === undefined) rawHeaders.push(\"content-length\", String(length));\n\tif (readPeerHttpBodyLength(rawHeaders, { direction: \"response\" }) !== length)\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\theaders[\"content-length\"] = String(length);\n\theaders.connection = \"close\";\n\treturn headers;\n}\n\n/** Capture and account for every byte before allowing native HTTP to write anything. */\nexport function capturePeerHttpResponse(response: PeerHttpServerResponse) {\n\ttry {\n\t\tconst { status, headers: supplied, bodyBytes } = response;\n\t\tif (!Number.isSafeInteger(status) || status < 200 || status > 599)\n\t\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t\tconst body = copyResponseBody(bodyBytes);\n\t\tif ((status === 204 || status === 304) && body.length !== 0)\n\t\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t\tconst headers = captureHeaders(supplied, body.length);\n\t\tconst message = STATUS_CODES[status] ?? \"unknown\";\n\t\tlet size = Buffer.byteLength(`HTTP/1.1 ${status} ${message}\\r\\n\\r\\n`, \"latin1\");\n\t\tfor (const [name, value] of Object.entries(headers))\n\t\t\tsize += Buffer.byteLength(`${name}: ${value}\\r\\n`, \"latin1\");\n\t\tif (size > PEER_HTTP_LIMITS.headerBytes) throw new PeerHttpExchangeError(\"framing\");\n\t\treturn { status, message, headers, body };\n\t} catch (error) {\n\t\tif (error instanceof PeerHttpExchangeError) throw error;\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t}\n}\n","import { PEER_HTTP_LIMITS, PeerHttpExchangeError } from \"./peer-http-policy.js\";\n\nexport type PeerHttpWireAuditState = \"headers\" | \"body\" | \"ended\" | \"failed\";\n\nexport interface PeerHttpWireAuditOptions {\n\tdirection: \"request\" | \"response\";\n\tmaxHeaderBytes?: number;\n\tmaxBodyBytes?: number;\n}\n\nconst typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);\nconst nativeByteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, \"byteLength\")?.get;\nconst nativeTag = Object.getOwnPropertyDescriptor(typedArrayPrototype, Symbol.toStringTag)?.get;\nconst nativeValues = Uint8Array.prototype.values;\n\nfunction lowerLimit(value: number | undefined, minimum: number, maximum: number): number {\n\tconst limit = value === undefined ? maximum : value;\n\tif (!Number.isSafeInteger(limit) || limit < minimum || limit > maximum)\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\treturn limit;\n}\n\nfunction captureLimits(options: PeerHttpWireAuditOptions) {\n\ttry {\n\t\tconst { direction, maxHeaderBytes, maxBodyBytes } = options;\n\t\tif (direction !== \"request\" && direction !== \"response\")\n\t\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t\tconst bodyCap =\n\t\t\tdirection === \"request\" ? PEER_HTTP_LIMITS.requestBytes : PEER_HTTP_LIMITS.responseBytes;\n\t\treturn {\n\t\t\theader: lowerLimit(maxHeaderBytes, 4, PEER_HTTP_LIMITS.headerBytes),\n\t\t\tbody: lowerLimit(maxBodyBytes, 0, bodyCap),\n\t\t};\n\t} catch {\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t}\n}\n\n/** Constant-space byte accounting only. Native HTTP still owns syntax and body policy.\n * Install the observer BEFORE the native parser on an owned pure-JS RelayNoiseDuplex,\n * excluding native Socket parser.consume bypass. Catch throws and destroy the owned connection.\n * Retain observation through plaintext EOF after parser removal, then call finish(), never at\n * HTTP message end. Success also requires native completion/body policy and clean raw I/O/disposal.\n * This audit alone proves neither HTTP syntax, authentication, completeness nor RTC bounds. */\nexport class PeerHttpWireAudit {\n\tprivate readonly limits: ReturnType<typeof captureLimits>;\n\tprivate current: PeerHttpWireAuditState = \"headers\";\n\tprivate failure?: PeerHttpExchangeError;\n\tprivate total = 0;\n\tprivate headerBytes = 0;\n\tprivate matched = 0;\n\tprivate expectedBody?: number;\n\n\tconstructor(options: PeerHttpWireAuditOptions) {\n\t\tthis.limits = captureLimits(options);\n\t}\n\n\tget state(): PeerHttpWireAuditState {\n\t\treturn this.current;\n\t}\n\n\tprivate fail(): never {\n\t\tthis.failure ??= new PeerHttpExchangeError(\"framing\");\n\t\tthis.current = \"failed\";\n\t\tthrow this.failure;\n\t}\n\n\tprivate requireActive(): void {\n\t\tif (this.current === \"failed\" || this.current === \"ended\") this.fail();\n\t}\n\n\tobserve(chunk: unknown): void {\n\t\ttry {\n\t\t\tthis.requireActive();\n\t\t\tif (nativeTag?.call(chunk) !== \"Uint8Array\") this.fail();\n\t\t\t// Validates attachment without consulting caller metadata, species or iteration hooks.\n\t\t\tnativeValues.call(chunk as Uint8Array);\n\t\t\tconst length: number = nativeByteLength?.call(chunk);\n\t\t\tif (\n\t\t\t\t!Number.isSafeInteger(length) ||\n\t\t\t\tlength < 0 ||\n\t\t\t\tlength > this.limits.header + this.limits.body - this.total\n\t\t\t)\n\t\t\t\tthis.fail();\n\t\t\tthis.total += length;\n\t\t\tfor (let index = 0; index < length && this.current === \"headers\"; index++) {\n\t\t\t\tthis.observeHeaderByte((chunk as Uint8Array)[index] ?? 0);\n\t\t\t}\n\t\t\tthis.checkBodyLength();\n\t\t} catch {\n\t\t\tthis.fail();\n\t\t}\n\t}\n\n\tprivate observeHeaderByte(byte: number): void {\n\t\tthis.headerBytes++;\n\t\tconst expected = this.matched === 0 || this.matched === 2 ? 13 : 10;\n\t\tif (byte === expected) this.matched++;\n\t\telse this.matched = byte === 13 ? 1 : 0;\n\t\tif (this.matched === 4) {\n\t\t\tthis.current = \"body\";\n\t\t\treturn;\n\t\t}\n\t\tif (this.headerBytes >= this.limits.header) this.fail();\n\t}\n\n\tprivate checkBodyLength(): void {\n\t\tif (this.current !== \"body\") return;\n\t\tconst bodyBytes = this.total - this.headerBytes;\n\t\tif (\n\t\t\tbodyBytes > this.limits.body ||\n\t\t\t(this.expectedBody !== undefined && bodyBytes > this.expectedBody)\n\t\t)\n\t\t\tthis.fail();\n\t}\n\n\t/** Call once from the native message event after validating rawHeaders and Content-Length. */\n\texpectBodyBytes(length: number): void {\n\t\tthis.requireActive();\n\t\tif (\n\t\t\tthis.current !== \"body\" ||\n\t\t\tthis.expectedBody !== undefined ||\n\t\t\t!Number.isSafeInteger(length) ||\n\t\t\tlength < 0 ||\n\t\t\tlength > this.limits.body\n\t\t)\n\t\t\tthis.fail();\n\t\tthis.expectedBody = length;\n\t\tthis.checkBodyLength();\n\t}\n\n\t/** Plaintext EOF only. Repeated successful finish() calls are idempotent. */\n\tfinish(): void {\n\t\tif (this.current === \"ended\") return;\n\t\tthis.requireActive();\n\t\tif (\n\t\t\tthis.current !== \"body\" ||\n\t\t\tthis.expectedBody === undefined ||\n\t\t\tthis.total !== this.headerBytes + this.expectedBody\n\t\t)\n\t\t\tthis.fail();\n\t\tthis.current = \"ended\";\n\t}\n}\n","/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError';\n constructor(message = 'The operation was aborted') {\n super(message);\n this.name = 'AbortError';\n }\n}\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError';\n constructor(message = 'Unexpected Peer') {\n super(message);\n this.name = 'UnexpectedPeerError';\n }\n}\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError';\n constructor(message = 'Invalid crypto exchange') {\n super(message);\n this.name = 'InvalidCryptoExchangeError';\n }\n}\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError';\n constructor(message = 'Invalid parameters') {\n super(message);\n this.name = 'InvalidParametersError';\n }\n}\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError';\n constructor(message = 'Invalid public key') {\n super(message);\n this.name = 'InvalidPublicKeyError';\n }\n}\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError';\n constructor(message = 'Invalid private key') {\n super(message);\n this.name = 'InvalidPrivateKeyError';\n }\n}\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError';\n constructor(message = 'Unsupported operation') {\n super(message);\n this.name = 'UnsupportedOperationError';\n }\n}\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError';\n constructor(message = 'The connection is closing') {\n super(message);\n this.name = 'ConnectionClosingError';\n }\n}\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError';\n constructor(message = 'The connection is closed') {\n super(message);\n this.name = 'ConnectionClosedError';\n }\n}\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError';\n constructor(message = 'Connection failed') {\n super(message);\n this.name = 'ConnectionFailedError';\n }\n}\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError';\n constructor(message = 'The muxer is closed') {\n super(message);\n this.name = 'MuxerClosedError';\n }\n}\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError';\n constructor(message = 'The stream has been reset') {\n super(message);\n this.name = 'StreamResetError';\n }\n}\n/**\n * Thrown when a protocol stream is aborted locally\n */\nexport class StreamAbortedError extends Error {\n static name = 'StreamAbortedError';\n constructor(message = 'The stream has been aborted') {\n super(message);\n this.name = 'StreamAbortedError';\n }\n}\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError';\n constructor(message = 'The stream is in an invalid state') {\n super(message);\n this.name = 'StreamStateError';\n }\n}\n/**\n * Thrown when a stream buffer is full\n */\nexport class StreamBufferError extends Error {\n static name = 'StreamBufferError';\n constructor(message = 'The stream buffer was full') {\n super(message);\n this.name = 'StreamBufferError';\n }\n}\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError';\n constructor(message = 'Not found') {\n super(message);\n this.name = 'NotFoundError';\n }\n}\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError';\n constructor(message = 'Invalid PeerID') {\n super(message);\n this.name = 'InvalidPeerIdError';\n }\n}\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError';\n constructor(message = 'Invalid multiaddr') {\n super(message);\n this.name = 'InvalidMultiaddrError';\n }\n}\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError';\n constructor(message = 'Invalid CID') {\n super(message);\n this.name = 'InvalidCIDError';\n }\n}\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError';\n constructor(message = 'Invalid Multihash') {\n super(message);\n this.name = 'InvalidMultihashError';\n }\n}\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError';\n constructor(message = 'Unsupported protocol error') {\n super(message);\n this.name = 'UnsupportedProtocolError';\n }\n}\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError';\n constructor(message = 'Invalid message') {\n super(message);\n this.name = 'InvalidMessageError';\n }\n}\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError';\n constructor(message = 'Protocol error') {\n super(message);\n this.name = 'ProtocolError';\n }\n}\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError';\n constructor(message = 'Timed out') {\n super(message);\n this.name = 'TimeoutError';\n }\n}\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError';\n constructor(message = 'Not started') {\n super(message);\n this.name = 'NotStartedError';\n }\n}\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError';\n constructor(message = 'Already started') {\n super(message);\n this.name = 'AlreadyStartedError';\n }\n}\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError';\n constructor(message = 'Dial error') {\n super(message);\n this.name = 'DialError';\n }\n}\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError';\n constructor(message = 'Listen error') {\n super(message);\n this.name = 'ListenError';\n }\n}\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError';\n constructor(message = 'Limited connection') {\n super(message);\n this.name = 'LimitedConnectionError';\n }\n}\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError';\n constructor(message = 'Too many inbound protocol streams') {\n super(message);\n this.name = 'TooManyInboundProtocolStreamsError';\n }\n}\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError';\n constructor(message = 'Too many outbound protocol streams') {\n super(message);\n this.name = 'TooManyOutboundProtocolStreamsError';\n }\n}\n/**\n * Thrown when an attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError';\n constructor(message = 'Unsupported key type') {\n super(message);\n this.name = 'UnsupportedKeyTypeError';\n }\n}\n/**\n * Thrown when an operation has not been implemented\n */\nexport class NotImplementedError extends Error {\n static name = 'NotImplementedError';\n constructor(message = 'Not implemented') {\n super(message);\n this.name = 'NotImplementedError';\n }\n}\n//# sourceMappingURL=errors.js.map","/**\n * A custom implementation of MessageEvent as the Undici version does too much\n * validation in it's constructor so is very slow.\n */\nexport class StreamMessageEvent extends Event {\n data;\n constructor(data, eventInitDict) {\n super('message', eventInitDict);\n this.data = data;\n }\n}\n/**\n * An event dispatched when the stream is closed. The `error` property can be\n * inspected to discover if the closing was graceful or not, and the `local`\n * property shows which end of the stream initiated the closure\n */\nexport class StreamCloseEvent extends Event {\n error;\n local;\n constructor(local, error, eventInitDict) {\n super('close', eventInitDict);\n this.error = error;\n this.local = local;\n }\n}\nexport class StreamAbortEvent extends StreamCloseEvent {\n constructor(error, eventInitDict) {\n super(true, error, eventInitDict);\n }\n}\nexport class StreamResetEvent extends StreamCloseEvent {\n constructor(error, eventInitDict) {\n super(false, error, eventInitDict);\n }\n}\n//# sourceMappingURL=events.js.map","/**\n * All PeerId implementations must use this symbol as the name of a property\n * with a boolean `true` value\n */\nexport const peerIdSymbol = Symbol.for('@libp2p/peer-id');\n/**\n * Returns true if the passed argument is a PeerId implementation\n */\nexport function isPeerId(other) {\n return Boolean(other?.[peerIdSymbol]);\n}\n//# sourceMappingURL=peer-id.js.map","/**\n * Noop for browser compatibility\n */\nexport function setMaxListeners() { }\n//# sourceMappingURL=events.browser.js.map","/**\n * @packageDocumentation\n *\n * Adds types to the EventTarget class.\n *\n * Hopefully this won't be necessary\n * forever:\n *\n * - https://github.com/microsoft/TypeScript/issues/28357\n * - https://github.com/microsoft/TypeScript/issues/43477\n * - https://github.com/microsoft/TypeScript/issues/299\n * - https://www.npmjs.com/package/typed-events\n * - https://www.npmjs.com/package/typed-event-emitter\n * - https://www.npmjs.com/package/typed-event-target\n * - etc\n *\n * In addition to types, a `safeDispatchEvent` method is available which\n * prevents dispatching events that aren't in the event map, and a\n * `listenerCount` method which reports the number of listeners that are\n * currently registered for a given event.\n *\n * @example\n *\n * ```ts\n * import { TypedEventEmitter } from 'main-event'\n * import type { TypedEventTarget } from 'main-event'\n *\n * interface EventTypes {\n * 'test': CustomEvent<string>\n * }\n *\n * const target = new TypedEventEmitter<EventTypes>()\n *\n * // it's a regular EventTarget\n * console.info(target instanceof EventTarget) // true\n *\n * // register listeners normally\n * target.addEventListener('test', (evt) => {\n * // evt is CustomEvent<string>\n * })\n *\n * // @ts-expect-error 'derp' is not in the event map\n * target.addEventListener('derp', () => {})\n *\n * // use normal dispatchEvent method\n * target.dispatchEvent(new CustomEvent('test', {\n * detail: 'hello'\n * }))\n *\n * // use type safe dispatch method\n * target.safeDispatchEvent('test', {\n * detail: 'world'\n * })\n *\n * // report listener count\n * console.info(target.listenerCount('test')) // 0\n *\n * // event emitters can be used purely as interfaces too\n * function acceptTarget (target: TypedEventTarget<EventTypes>) {\n * // ...\n * }\n * ```\n */\nimport { setMaxListeners } from \"./events.js\";\nfunction isEventObject(obj) {\n return typeof obj?.handleEvent === 'function';\n}\n/**\n * Returns true if the passed argument is a boolean value\n */\nfunction isBoolean(obj) {\n return obj === true || obj === false;\n}\n/**\n * @see https://dom.spec.whatwg.org/#concept-flatten-options\n */\nfunction flattenOptions(options) {\n if (isBoolean(options)) {\n return options;\n }\n return options?.capture ?? false;\n}\n/**\n * @see https://dom.spec.whatwg.org/#event-flatten-more\n */\nfunction flattenMoreOptions(options) {\n const opts = {\n capture: flattenOptions(options),\n once: Boolean(options?.once)\n };\n if (options?.passive != null) {\n opts.passive = options?.passive;\n }\n if (options?.signal != null) {\n opts.signal = options?.signal;\n }\n return opts;\n}\n/**\n * Returns true if the capture/useCapture arg of each opts are equal\n */\nfunction captureIsEqual(optsA, optsB) {\n return flattenMoreOptions(optsA).capture === flattenMoreOptions(optsB).capture;\n}\n/**\n * An implementation of a typed event target\n */\nexport class TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n setMaxListeners(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, opts) {\n const options = flattenMoreOptions(opts);\n if (options?.signal?.aborted === true) {\n return;\n }\n // the wrapper - and not `listener` - is what is registered with the native\n // EventTarget, so a reference to it must be kept in order to be able to\n // remove it again later\n const wrapper = (evt) => {\n if (options.once) {\n this.removeEventListener(type, listener, options);\n }\n if (isEventObject(listener)) {\n listener.handleEvent(evt);\n }\n else {\n listener(evt);\n }\n };\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n // if there is already an entry in the list for the same type, callback and\n // capture value, listening again is a no-op\n // @see https://dom.spec.whatwg.org/#add-an-event-listener\n const alreadyListening = list.some(entry => {\n if (entry.callback !== listener) {\n return false;\n }\n // listener is already present, check capture options\n return captureIsEqual(entry.options, options);\n });\n if (alreadyListening) {\n return;\n }\n super.addEventListener(type, wrapper, options);\n const onAbort = () => {\n this.removeEventListener(type, listener, options);\n };\n options.signal?.addEventListener('abort', onAbort);\n list.push({\n callback: listener,\n wrapper,\n options,\n onAbort\n });\n }\n removeEventListener(type, listener, options) {\n const list = this.#listeners.get(type);\n if (list == null) {\n super.removeEventListener(type, listener ?? null, options);\n return;\n }\n this.#listeners.set(type, list.filter(entry => {\n // listeners are the same so we need to check the capture argument\n if (entry.callback === listener && captureIsEqual(entry.options, options)) {\n super.removeEventListener(type, entry.wrapper, options);\n // remove abort signal abort event listener if set\n entry.options?.signal?.removeEventListener('abort', entry.onAbort);\n return false;\n }\n return true;\n }));\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\nexport { setMaxListeners };\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities');\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies');\nexport * from \"./connection.js\";\nexport * from \"./connection-encrypter.js\";\nexport * from \"./connection-gater.js\";\nexport * from \"./connection-protector.js\";\nexport * from \"./content-routing.js\";\nexport * from \"./errors.js\";\nexport * from \"./events.js\";\nexport * from \"./keys.js\";\nexport * from \"./message-stream.js\";\nexport * from \"./metrics.js\";\nexport * from \"./multiaddr-connection.js\";\nexport * from \"./peer-discovery.js\";\nexport * from \"./peer-id.js\";\nexport * from \"./peer-info.js\";\nexport * from \"./peer-routing.js\";\nexport * from \"./peer-store.js\";\nexport * from \"./record.js\";\nexport * from \"./startable.js\";\nexport * from \"./stream-handler.js\";\nexport * from \"./stream-muxer.js\";\nexport * from \"./stream.js\";\nexport * from \"./topology.js\";\nexport * from \"./transport.js\";\nexport * from 'main-event';\n//# sourceMappingURL=index.js.map","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc(size = 0) {\n return new Uint8Array(size);\n}\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe(size = 0) {\n return new Uint8Array(size);\n}\n//# sourceMappingURL=alloc.js.map","function isByteArrayWithArrayBuffer(b) {\n return b?.buffer instanceof ArrayBuffer;\n}\n/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nexport function asUint8Array(buf) {\n if (isByteArrayWithArrayBuffer(buf)) {\n return buf;\n }\n const b = buf.slice();\n return new Uint8Array(b.buffer, 0, b.byteLength);\n}\n//# sourceMappingURL=as-uint8array.js.map","import { allocUnsafe } from '#alloc';\nimport { asUint8Array } from '#util/as-uint8array';\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat(arrays, length) {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0);\n }\n const output = allocUnsafe(length);\n let offset = 0;\n for (const arr of arrays) {\n output.set(arr, offset);\n offset += arr.length;\n }\n return asUint8Array(output);\n}\n//# sourceMappingURL=concat.js.map","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals(a, b) {\n if (a === b) {\n return true;\n }\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n//# sourceMappingURL=equals.js.map","/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc';\nimport { concat } from 'uint8arrays/concat';\nimport { equals } from 'uint8arrays/equals';\nconst symbol = Symbol.for('@achingbrain/uint8arraylist');\nfunction findBufAndOffset(bufs, index) {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds');\n }\n let offset = 0;\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength;\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n };\n }\n offset = bufEnd;\n }\n throw new RangeError('index is out of bounds');\n}\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList(value) {\n return Boolean(value?.[symbol]);\n}\nexport class Uint8ArrayList {\n bufs;\n length;\n [symbol] = true;\n constructor(...data) {\n this.bufs = [];\n this.length = 0;\n if (data.length > 0) {\n this.appendAll(data);\n }\n }\n *[Symbol.iterator]() {\n yield* this.bufs;\n }\n get byteLength() {\n return this.length;\n }\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append(...bufs) {\n this.appendAll(bufs);\n }\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll(bufs) {\n let length = 0;\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength;\n this.bufs.push(buf);\n }\n else if (isUint8ArrayList(buf)) {\n length += buf.byteLength;\n for (const chunk of buf.bufs) {\n this.bufs.push(chunk);\n }\n }\n else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList');\n }\n }\n this.length += length;\n }\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend(...bufs) {\n this.prependAll(bufs);\n }\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll(bufs) {\n let length = 0;\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength;\n this.bufs.unshift(buf);\n }\n else if (isUint8ArrayList(buf)) {\n length += buf.byteLength;\n this.bufs.unshift(...buf.bufs);\n }\n else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList');\n }\n }\n this.length += length;\n }\n /**\n * Read the value at `index`\n */\n get(index) {\n const res = findBufAndOffset(this.bufs, index);\n return res.buf[res.index];\n }\n /**\n * Set the value at `index` to `value`\n */\n set(index, value) {\n const res = findBufAndOffset(this.bufs, index);\n res.buf[res.index] = value;\n }\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write(buf, offset = 0) {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i]);\n }\n }\n else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i));\n }\n }\n else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList');\n }\n }\n /**\n * Remove bytes from the front of the pool\n */\n consume(bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes);\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return;\n }\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = [];\n this.length = 0;\n return;\n }\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength;\n this.length -= this.bufs[0].byteLength;\n this.bufs.shift();\n }\n else {\n this.bufs[0] = this.bufs[0].subarray(bytes);\n this.length -= bytes;\n break;\n }\n }\n }\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice(beginInclusive, endExclusive) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive);\n return concat(bufs, length);\n }\n /**\n * Returns a section of the array from the given start and end element index.\n *\n * This is a no-copy operation where the data extracted data comes from a\n * single Uint8Array internally, otherwise it is a copy operation.\n */\n subarray(beginInclusive, endExclusive) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive);\n if (bufs.length === 1) {\n return bufs[0];\n }\n return concat(bufs, length);\n }\n /**\n * Returns a new Uint8ArrayList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist(beginInclusive, endExclusive) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive);\n const list = new Uint8ArrayList();\n list.length = length;\n // don't loop, just set the bufs\n list.bufs = bufs;\n return list;\n }\n _subList(beginInclusive, endExclusive) {\n beginInclusive = beginInclusive ?? 0;\n endExclusive = endExclusive ?? this.length;\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive;\n }\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive;\n }\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds');\n }\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 };\n }\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: [...this.bufs], length: this.length };\n }\n const bufs = [];\n let offset = 0;\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i];\n const bufStart = offset;\n const bufEnd = bufStart + buf.byteLength;\n // for next loop\n offset = bufEnd;\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue;\n }\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd;\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd;\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf);\n break;\n }\n // requested part of buffer\n const start = beginInclusive - bufStart;\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)));\n break;\n }\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf);\n continue;\n }\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart));\n continue;\n }\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf);\n break;\n }\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart));\n break;\n }\n // slice started before this buffer and ends after it\n bufs.push(buf);\n }\n return { bufs, length: endExclusive - beginInclusive };\n }\n indexOf(search, offset = 0) {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array');\n }\n const needle = search instanceof Uint8Array ? search : search.subarray();\n offset = Number(offset ?? 0);\n if (isNaN(offset)) {\n offset = 0;\n }\n if (offset < 0) {\n offset = this.length + offset;\n }\n if (offset < 0) {\n offset = 0;\n }\n if (search.length === 0) {\n return offset > this.length ? this.length : offset;\n }\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M = needle.byteLength;\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long');\n }\n // radix\n const radix = 256;\n const rightmostPositions = new Int32Array(radix);\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1;\n }\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j;\n }\n // Return offset of first match, -1 if no match\n const right = rightmostPositions;\n const lastIndex = this.byteLength - needle.byteLength;\n const lastPatIndex = needle.byteLength - 1;\n let skip;\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0;\n for (let j = lastPatIndex; j >= 0; j--) {\n const char = this.get(i + j);\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char]);\n break;\n }\n }\n if (skip === 0) {\n return i;\n }\n }\n return -1;\n }\n getInt8(byteOffset) {\n const buf = this.subarray(byteOffset, byteOffset + 1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getInt8(0);\n }\n setInt8(byteOffset, value) {\n const buf = allocUnsafe(1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setInt8(0, value);\n this.write(buf, byteOffset);\n }\n getInt16(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getInt16(0, littleEndian);\n }\n setInt16(byteOffset, value, littleEndian) {\n const buf = alloc(2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setInt16(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getInt32(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getInt32(0, littleEndian);\n }\n setInt32(byteOffset, value, littleEndian) {\n const buf = alloc(4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setInt32(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getBigInt64(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getBigInt64(0, littleEndian);\n }\n setBigInt64(byteOffset, value, littleEndian) {\n const buf = alloc(8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setBigInt64(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getUint8(byteOffset) {\n const buf = this.subarray(byteOffset, byteOffset + 1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getUint8(0);\n }\n setUint8(byteOffset, value) {\n const buf = allocUnsafe(1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setUint8(0, value);\n this.write(buf, byteOffset);\n }\n getUint16(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getUint16(0, littleEndian);\n }\n setUint16(byteOffset, value, littleEndian) {\n const buf = alloc(2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setUint16(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getUint32(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getUint32(0, littleEndian);\n }\n setUint32(byteOffset, value, littleEndian) {\n const buf = alloc(4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setUint32(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getBigUint64(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getBigUint64(0, littleEndian);\n }\n setBigUint64(byteOffset, value, littleEndian) {\n const buf = alloc(8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setBigUint64(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getFloat32(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getFloat32(0, littleEndian);\n }\n setFloat32(byteOffset, value, littleEndian) {\n const buf = alloc(4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setFloat32(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getFloat64(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getFloat64(0, littleEndian);\n }\n setFloat64(byteOffset, value, littleEndian) {\n const buf = alloc(8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setFloat64(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (!(other instanceof Uint8ArrayList)) {\n return false;\n }\n if (other.bufs.length !== this.bufs.length) {\n return false;\n }\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false;\n }\n }\n return true;\n }\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays(bufs, length) {\n const list = new Uint8ArrayList();\n list.bufs = bufs;\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0);\n }\n list.length = length;\n return list;\n }\n}\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n//# sourceMappingURL=index.js.map","export const empty = new Uint8Array(0);\nexport function toHex(d) {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\n}\nexport function fromHex(hex) {\n const hexes = hex.match(/../g);\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n}\nexport function equals(aa, bb) {\n if (aa === bb) {\n return true;\n }\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n}\n/**\n * Normalize binary input to a plain `Uint8Array` backed by an `ArrayBuffer`.\n *\n * Returns the input itself when it is already a plain `Uint8Array` over an\n * `ArrayBuffer`, otherwise a fresh view (or, for `SharedArrayBuffer`-backed\n * input, a copy) over the same bytes.\n *\n * Throws if input is not a recognised binary type.\n */\nexport function coerce(o) {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {\n return toArrayBufferBackedArray(o);\n }\n if (o instanceof ArrayBuffer) {\n return new Uint8Array(o);\n }\n if (ArrayBuffer.isView(o)) {\n return toArrayBufferBackedArray(new Uint8Array(o.buffer, o.byteOffset, o.byteLength));\n }\n throw new Error('Unknown type, must be binary type');\n}\nexport function isBinary(o) {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o);\n}\n/**\n * Convert the passed string into a byte array, constraining each character\n * value to a single byte\n */\nexport function fromString(str) {\n const output = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n output[i] = str.charCodeAt(i);\n }\n return output;\n}\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000;\n/**\n * Convert the passed byte array to a string, interpreting each byte as a single\n * character\n */\nexport function toString(b) {\n const len = b.length;\n if (len <= MAX_ARGUMENTS_LENGTH) {\n // @ts-expect-error cannot ordinarily apply a Uint8Array\n return String.fromCharCode.apply(String, b); // avoid extra subarray()\n }\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = '';\n let i = 0;\n while (i < len) {\n res += String.fromCharCode.apply(String, \n // @ts-expect-error cannot ordinarily apply a Uint8Array\n b.subarray(i, i += MAX_ARGUMENTS_LENGTH));\n }\n return res;\n}\nfunction isByteArrayWithArrayBuffer(b) {\n return b?.buffer instanceof ArrayBuffer;\n}\n/**\n * Ensures `b` is backed by an ArrayBuffer - if not a new Uint8Array will be\n * created and the contents of `b` copied into it.\n */\nexport function toArrayBufferBackedArray(b) {\n if (isByteArrayWithArrayBuffer(b)) {\n return b;\n }\n return b.slice();\n}\n//# sourceMappingURL=bytes.js.map","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n * @param {boolean} [caseInsensitive]\n */\nfunction base(ALPHABET, name, caseInsensitive) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n // For case-insensitive codecs, map the opposite case to the same index so\n // differently cased input decodes without errors (multibase spec).\n if (caseInsensitive) {\n var xl = x.toLowerCase().charCodeAt(0);\n var xu = x.toUpperCase().charCodeAt(0);\n if (xl !== xc) {\n BASE_MAP[xl] = i;\n }\n if (xu !== xc) {\n BASE_MAP[xu] = i;\n }\n }\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable<number>} source\n */\n function encode(source) {\n // @ts-ignore\n if (source instanceof Uint8Array)\n ;\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n }\n else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n /**\n * @param {string | string[]} string\n */\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${name} character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\nexport default _brrp__multiformats_scope_baseX;\n//# sourceMappingURL=base-x.js.map","import { coerce } from \"../bytes.js\";\nimport basex from '../vendor/base-x.js';\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nexport function or(left, right) {\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nexport class Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nexport function from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nexport function baseX({ name, prefix, alphabet, caseInsensitive = false }) {\n const { encode, decode } = basex(alphabet, name, caseInsensitive);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => coerce(decode(text))\n });\n}\nfunction decode(string, alphabetIdx, bitsPerChar, name) {\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = alphabetIdx[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\nfunction createAlphabetIdx(alphabet, caseInsensitive) {\n // Build the character lookup table:\n const alphabetIdx = {};\n for (let i = 0; i < alphabet.length; ++i) {\n alphabetIdx[alphabet[i]] = i;\n // For case-insensitive codecs, map the opposite case to the same index so\n // differently cased input decodes without errors (multibase spec).\n if (caseInsensitive) {\n const lower = alphabet[i].toLowerCase();\n const upper = alphabet[i].toUpperCase();\n if (lower !== alphabet[i]) {\n alphabetIdx[lower] = i;\n }\n if (upper !== alphabet[i]) {\n alphabetIdx[upper] = i;\n }\n }\n }\n return alphabetIdx;\n}\n/**\n * RFC4648 Factory\n */\nexport function rfc4648({ name, prefix, bitsPerChar, alphabet, caseInsensitive = false }) {\n const alphabetIdx = createAlphabetIdx(alphabet, caseInsensitive);\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabetIdx, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map","import { baseX } from \"./base.js\";\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n});\n//# sourceMappingURL=base10.js.map","import { rfc4648 } from \"./base.js\";\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4,\n caseInsensitive: true\n});\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4,\n caseInsensitive: true\n});\n//# sourceMappingURL=base16.js.map","import { rfc4648 } from \"./base.js\";\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n});\n//# sourceMappingURL=base2.js.map","import { from } from \"./base.js\";\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map","import { rfc4648 } from \"./base.js\";\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5,\n caseInsensitive: true\n});\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5,\n caseInsensitive: true\n});\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5,\n caseInsensitive: true\n});\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5,\n caseInsensitive: true\n});\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5,\n caseInsensitive: true\n});\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5,\n caseInsensitive: true\n});\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5,\n caseInsensitive: true\n});\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5,\n caseInsensitive: true\n});\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});\n//# sourceMappingURL=base32.js.map","import { baseX } from \"./base.js\";\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz',\n caseInsensitive: true\n});\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n caseInsensitive: true\n});\n//# sourceMappingURL=base36.js.map","import { baseX } from \"./base.js\";\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base58.js.map","import { rfc4648 } from \"./base.js\";\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});\n//# sourceMappingURL=base64.js.map","import { rfc4648 } from \"./base.js\";\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n});\n//# sourceMappingURL=base8.js.map","import { coerce, fromString, toString } from \"../bytes.js\";\nimport { from } from \"./base.js\";\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(coerce(buf)),\n decode: (str) => coerce(fromString(str))\n});\n//# sourceMappingURL=identity.js.map","const textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nexport const name = 'json';\nexport const code = 0x0200;\nexport function encode(node) {\n return textEncoder.encode(JSON.stringify(node));\n}\nexport function decode(data) {\n return JSON.parse(textDecoder.decode(data));\n}\n//# sourceMappingURL=json.js.map","/* eslint-disable */\nvar encode_1 = encode;\nvar MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 0x80, REST$1 = 0x7F;\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n // @ts-ignore\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (/** @type {number} */ value) {\n return (value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10);\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\nexport default _brrp_varint;\n//# sourceMappingURL=varint.js.map","import varint from './vendor/varint.js';\nexport function decode(data, offset = 0) {\n const code = varint.decode(data, offset);\n const length = varint.decode.bytes;\n if (length > 9) {\n throw new RangeError('Invalid varint: too long');\n }\n if (length > 1 && data[offset + length - 1] === 0) {\n throw new RangeError('Invalid varint: not minimally encoded');\n }\n return [code, length];\n}\nexport function encodeTo(int, target, offset = 0) {\n varint.encode(int, target, offset);\n return target;\n}\nexport function encodingLength(int) {\n return varint.encodingLength(int);\n}\n//# sourceMappingURL=varint.js.map","import { coerce, equals as equalBytes, toArrayBufferBackedArray } from \"../bytes.js\";\nimport * as varint from \"../varint.js\";\n/**\n * Creates a multihash digest.\n */\nexport function create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = varint.encodingLength(code);\n const digestOffset = sizeOffset + varint.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n varint.encodeTo(code, bytes, 0);\n varint.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode(multihash) {\n const bytes = coerce(multihash);\n const [code, sizeOffset] = varint.decode(bytes);\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nexport function equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = toArrayBufferBackedArray(digest);\n this.bytes = toArrayBufferBackedArray(bytes);\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map","import { coerce } from \"../bytes.js\";\nimport * as Digest from \"./digest.js\";\nconst code = 0x0;\nconst name = 'identity';\nconst encode = coerce;\nfunction digest(input, options) {\n if (options?.truncate != null && options.truncate !== input.byteLength) {\n if (options.truncate < 0 || options.truncate > input.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${input.byteLength}`);\n }\n input = input.subarray(0, options.truncate);\n }\n return Digest.create(code, encode(input));\n}\nexport const identity = { code, name, encode, digest };\n//# sourceMappingURL=identity.js.map","import * as Digest from \"./digest.js\";\nconst DEFAULT_MIN_DIGEST_LENGTH = 20;\nexport function from({ name, code, encode, minDigestLength, maxDigestLength }) {\n return new Hasher(name, code, encode, minDigestLength, maxDigestLength);\n}\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher {\n name;\n code;\n encode;\n minDigestLength;\n maxDigestLength;\n constructor(name, code, encode, minDigestLength, maxDigestLength) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH;\n this.maxDigestLength = maxDigestLength;\n }\n digest(input, options) {\n if (options?.truncate != null) {\n if (options.truncate < this.minDigestLength) {\n throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);\n }\n if (this.maxDigestLength != null && options.truncate > this.maxDigestLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`);\n }\n }\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n if (result instanceof Uint8Array) {\n return createDigest(result, this.code, options?.truncate);\n }\n return result.then(digest => createDigest(digest, this.code, options?.truncate));\n }\n else {\n throw Error('Unknown type, must be binary type');\n /* c8 ignore next 1 */\n }\n }\n}\n/**\n * Create a Digest from the passed uint8array and code, optionally truncating it\n * first.\n */\nfunction createDigest(digest, code, truncate) {\n if (truncate != null && truncate !== digest.byteLength) {\n if (truncate > digest.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${digest.byteLength}`);\n }\n digest = digest.subarray(0, truncate);\n }\n return Digest.create(code, digest);\n}\n//# sourceMappingURL=hasher.js.map","import { from } from \"./hasher.js\";\nfunction sha(name) {\n return async (data) => new Uint8Array(await crypto.subtle.digest(name, data));\n}\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n});\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n});\n//# sourceMappingURL=sha2-browser.js.map","import { base32 } from \"./bases/base32.js\";\nimport { base36 } from \"./bases/base36.js\";\nimport { base58btc } from \"./bases/base58.js\";\nimport { coerce, toArrayBufferBackedArray } from \"./bytes.js\";\nimport * as Digest from \"./hashes/digest.js\";\nimport * as varint from \"./varint.js\";\n// This way TS will also expose all the types from module\nexport * from \"./link/interface.js\";\nexport function format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));\n }\n}\nexport function toJSON(link) {\n return {\n '/': format(link)\n };\n}\nexport function fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nexport class CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = toArrayBufferBackedArray(bytes);\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = this.bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = Digest.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = Digest.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = varint.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc;\n return [\n base58btc.prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ];\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc;\n return [base58btc.prefix, decoder.decode(source)];\n }\n case base32.prefix: {\n const decoder = base ?? base32;\n return [base32.prefix, decoder.decode(source)];\n }\n case base36.prefix: {\n const decoder = base ?? base36;\n return [base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = varint.encodingLength(version);\n const hashOffset = codeOffset + varint.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n varint.encodeTo(version, bytes, 0);\n varint.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map","import * as base10 from \"./bases/base10.js\";\nimport * as base16 from \"./bases/base16.js\";\nimport * as base2 from \"./bases/base2.js\";\nimport * as base256emoji from \"./bases/base256emoji.js\";\nimport * as base32 from \"./bases/base32.js\";\nimport * as base36 from \"./bases/base36.js\";\nimport * as base58 from \"./bases/base58.js\";\nimport * as base64 from \"./bases/base64.js\";\nimport * as base8 from \"./bases/base8.js\";\nimport * as identityBase from \"./bases/identity.js\";\nimport * as json from \"./codecs/json.js\";\nimport * as raw from \"./codecs/raw.js\";\nimport * as identity from \"./hashes/identity.js\";\nimport * as sha2 from \"./hashes/sha2.js\";\nimport { CID, hasher, digest, varint, bytes } from \"./index.js\";\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji };\nexport const hashes = { ...sha2, ...identity };\nexport const codecs = { raw, json };\nexport { CID, hasher, digest, varint, bytes };\n//# sourceMappingURL=basics.js.map","import { bases } from 'multiformats/basics';\nimport { allocUnsafe } from '#alloc';\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n };\n}\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, (str) => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, (str) => {\n str = str.substring(1);\n const buf = allocUnsafe(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n ...bases\n};\nexport default BASES;\n//# sourceMappingURL=bases.js.map","import bases from \"./util/bases.js\";\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString(string, encoding = 'utf8') {\n const base = bases[encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`);\n}\n//# sourceMappingURL=from-string.js.map","/* eslint-disable no-fallthrough */\nimport { allocUnsafe } from 'uint8arrays/alloc';\nconst N1 = Math.pow(2, 7);\nconst N2 = Math.pow(2, 14);\nconst N3 = Math.pow(2, 21);\nconst N4 = Math.pow(2, 28);\nconst N5 = Math.pow(2, 35);\nconst N6 = Math.pow(2, 42);\nconst N7 = Math.pow(2, 49);\n/** Most significant bit of a byte */\nconst MSB = 0x80;\n/** Rest of the bits in a byte */\nconst REST = 0x7f;\nexport function encodingLength(value) {\n if (value < N1) {\n return 1;\n }\n if (value < N2) {\n return 2;\n }\n if (value < N3) {\n return 3;\n }\n if (value < N4) {\n return 4;\n }\n if (value < N5) {\n return 5;\n }\n if (value < N6) {\n return 6;\n }\n if (value < N7) {\n return 7;\n }\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint');\n }\n return 8;\n}\nexport function encodeUint8Array(value, buf, offset = 0) {\n switch (encodingLength(value)) {\n case 8: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 7: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 6: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 5: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 4: {\n buf[offset++] = (value & 0xFF) | MSB;\n value >>>= 7;\n }\n case 3: {\n buf[offset++] = (value & 0xFF) | MSB;\n value >>>= 7;\n }\n case 2: {\n buf[offset++] = (value & 0xFF) | MSB;\n value >>>= 7;\n }\n case 1: {\n buf[offset++] = (value & 0xFF);\n value >>>= 7;\n break;\n }\n default: throw new Error('unreachable');\n }\n return buf;\n}\nexport function encodeUint8ArrayList(value, buf, offset = 0) {\n switch (encodingLength(value)) {\n case 8: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 7: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 6: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 5: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 4: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value >>>= 7;\n }\n case 3: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value >>>= 7;\n }\n case 2: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value >>>= 7;\n }\n case 1: {\n buf.set(offset++, (value & 0xFF));\n value >>>= 7;\n break;\n }\n default: throw new Error('unreachable');\n }\n return buf;\n}\nexport function decodeUint8Array(buf, offset) {\n let b = buf[offset];\n let res = 0;\n res += b & REST;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 1];\n res += (b & REST) << 7;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 2];\n res += (b & REST) << 14;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 3];\n res += (b & REST) << 21;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 4];\n res += (b & REST) * N4;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 5];\n res += (b & REST) * N5;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 6];\n res += (b & REST) * N6;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 7];\n res += (b & REST) * N7;\n if (b < MSB) {\n return res;\n }\n throw new RangeError('Could not decode varint');\n}\nexport function decodeUint8ArrayList(buf, offset) {\n let b = buf.get(offset);\n let res = 0;\n res += b & REST;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 1);\n res += (b & REST) << 7;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 2);\n res += (b & REST) << 14;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 3);\n res += (b & REST) << 21;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 4);\n res += (b & REST) * N4;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 5);\n res += (b & REST) * N5;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 6);\n res += (b & REST) * N6;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 7);\n res += (b & REST) * N7;\n if (b < MSB) {\n return res;\n }\n throw new RangeError('Could not decode varint');\n}\nexport function encode(value, buf, offset = 0) {\n if (buf == null) {\n buf = allocUnsafe(encodingLength(value));\n }\n if (buf instanceof Uint8Array) {\n return encodeUint8Array(value, buf, offset);\n }\n else {\n return encodeUint8ArrayList(value, buf, offset);\n }\n}\nexport function decode(buf, offset = 0) {\n if (buf instanceof Uint8Array) {\n return decodeUint8Array(buf, offset);\n }\n else {\n return decodeUint8ArrayList(buf, offset);\n }\n}\n//# sourceMappingURL=index.js.map","function isArrayBufferBacked(arr) {\n return arr.buffer instanceof ArrayBuffer;\n}\n/**\n * If the passed `arr` is of type `Uint8Array<ArrayBuffer>`, it is returned\n * unchanged, otherwise a new `Uint8Array<ArrayBuffer>` is created with the\n * data being a copy of the data in the passed `arr`.\n */\nexport function withArrayBuffer(arr) {\n if (isArrayBufferBacked(arr)) {\n return arr;\n }\n return arr.slice();\n}\n//# sourceMappingURL=with-array-buffer.js.map","import bases from \"./util/bases.js\";\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString(array, encoding = 'utf8') {\n const base = bases[encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // strip multibase prefix\n return base.encoder.encode(array).substring(1);\n}\n//# sourceMappingURL=to-string.js.map","export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n","// ported from https://www.npmjs.com/package/fast-fifo\nclass FixedFIFO {\n buffer;\n mask;\n top;\n btm;\n next;\n constructor(hwm) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {\n throw new Error('Max size for a FixedFIFO should be a power of two');\n }\n this.buffer = new Array(hwm);\n this.mask = hwm - 1;\n this.top = 0;\n this.btm = 0;\n this.next = null;\n }\n push(data) {\n if (this.buffer[this.top] !== undefined) {\n return false;\n }\n this.buffer[this.top] = data;\n this.top = (this.top + 1) & this.mask;\n return true;\n }\n shift() {\n const last = this.buffer[this.btm];\n if (last === undefined) {\n return undefined;\n }\n this.buffer[this.btm] = undefined;\n this.btm = (this.btm + 1) & this.mask;\n return last;\n }\n isEmpty() {\n return this.buffer[this.btm] === undefined;\n }\n}\nexport class FIFO {\n size;\n hwm;\n head;\n tail;\n constructor(options = {}) {\n this.hwm = options.splitLimit ?? 16;\n this.head = new FixedFIFO(this.hwm);\n this.tail = this.head;\n this.size = 0;\n }\n calculateSize(obj) {\n if (obj?.byteLength != null) {\n return obj.byteLength;\n }\n return 1;\n }\n push(val) {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value);\n }\n if (!this.head.push(val)) {\n const prev = this.head;\n this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);\n this.head.push(val);\n }\n }\n shift() {\n let val = this.tail.shift();\n if (val === undefined && (this.tail.next != null)) {\n const next = this.tail.next;\n this.tail.next = null;\n this.tail = next;\n val = this.tail.shift();\n }\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value);\n }\n return val;\n }\n isEmpty() {\n return this.head.isEmpty();\n }\n}\n//# sourceMappingURL=fifo.js.map","/**\n * @packageDocumentation\n *\n * An iterable that you can push values into.\n *\n * @example\n *\n * ```js\n * import { pushable } from 'it-pushable'\n *\n * const source = pushable()\n *\n * setTimeout(() => source.push('hello'), 100)\n * setTimeout(() => source.push('world'), 200)\n * setTimeout(() => source.end(), 300)\n *\n * const start = Date.now()\n *\n * for await (const value of source) {\n * console.log(`got \"${value}\" after ${Date.now() - start}ms`)\n * }\n * console.log(`done after ${Date.now() - start}ms`)\n *\n * // Output:\n * // got \"hello\" after 105ms\n * // got \"world\" after 207ms\n * // done after 309ms\n * ```\n *\n * @example\n *\n * ```js\n * import { pushableV } from 'it-pushable'\n * import all from 'it-all'\n *\n * const source = pushableV()\n *\n * source.push(1)\n * source.push(2)\n * source.push(3)\n * source.end()\n *\n * console.info(await all(source))\n *\n * // Output:\n * // [ [1, 2, 3] ]\n * ```\n */\nimport deferred from 'p-defer';\nimport { FIFO } from \"./fifo.js\";\nexport class AbortError extends Error {\n type;\n code;\n constructor(message, code) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.code = code ?? 'ABORT_ERR';\n }\n}\nexport function pushable(options = {}) {\n const getNext = (buffer) => {\n const next = buffer.shift();\n if (next == null) {\n return { done: true };\n }\n if (next.error != null) {\n throw next.error;\n }\n return {\n done: next.done === true,\n // @ts-expect-error if done is false, value will be present\n value: next.value\n };\n };\n return _pushable(getNext, options);\n}\nexport function pushableV(options = {}) {\n const getNext = (buffer) => {\n let next;\n const values = [];\n while (!buffer.isEmpty()) {\n next = buffer.shift();\n if (next == null) {\n break;\n }\n if (next.error != null) {\n throw next.error;\n }\n if (next.done === false) {\n // @ts-expect-error if done is false value should be pushed\n values.push(next.value);\n }\n }\n if (next == null) {\n return { done: true };\n }\n return {\n done: next.done === true,\n value: values\n };\n };\n return _pushable(getNext, options);\n}\nfunction _pushable(getNext, options) {\n options = options ?? {};\n let onEnd = options.onEnd;\n let buffer = new FIFO();\n let pushable;\n let onNext;\n let ended;\n let drain = deferred();\n const waitNext = async () => {\n try {\n if (!buffer.isEmpty()) {\n return getNext(buffer);\n }\n if (ended) {\n return { done: true };\n }\n return await new Promise((resolve, reject) => {\n onNext = (next) => {\n onNext = null;\n buffer.push(next);\n try {\n resolve(getNext(buffer));\n }\n catch (err) {\n reject(err);\n }\n return pushable;\n };\n });\n }\n finally {\n if (buffer.isEmpty()) {\n // settle promise in the microtask queue to give consumers a chance to\n // await after calling .push\n queueMicrotask(() => {\n drain.resolve();\n drain = deferred();\n });\n }\n }\n };\n const bufferNext = (next) => {\n if (onNext != null) {\n return onNext(next);\n }\n buffer.push(next);\n return pushable;\n };\n const bufferError = (err) => {\n buffer = new FIFO();\n if (onNext != null) {\n return onNext({ error: err });\n }\n buffer.push({ error: err });\n return pushable;\n };\n const push = (value) => {\n if (ended) {\n return pushable;\n }\n // @ts-expect-error `byteLength` is not declared on PushType\n if (options?.objectMode !== true && value?.byteLength == null) {\n throw new Error('objectMode was not true but tried to push non-Uint8Array value');\n }\n return bufferNext({ done: false, value });\n };\n const end = (err) => {\n if (ended) {\n return pushable;\n }\n ended = true;\n return (err != null) ? bufferError(err) : bufferNext({ done: true });\n };\n const _return = () => {\n buffer = new FIFO();\n end();\n return { done: true };\n };\n const _throw = (err) => {\n end(err);\n return { done: true };\n };\n pushable = {\n [Symbol.asyncIterator]() { return this; },\n next: waitNext,\n return: _return,\n throw: _throw,\n push,\n end,\n get readableLength() {\n return buffer.size;\n },\n onEmpty: async (options) => {\n const signal = options?.signal;\n signal?.throwIfAborted();\n if (buffer.isEmpty()) {\n return;\n }\n let cancel;\n let listener;\n if (signal != null) {\n cancel = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError());\n };\n signal.addEventListener('abort', listener);\n });\n }\n try {\n await Promise.race([\n drain.promise,\n cancel\n ]);\n }\n finally {\n if (listener != null && signal != null) {\n signal?.removeEventListener('abort', listener);\n }\n }\n }\n };\n if (onEnd == null) {\n return pushable;\n }\n const _pushable = pushable;\n pushable = {\n [Symbol.asyncIterator]() { return this; },\n next() {\n return _pushable.next();\n },\n throw(err) {\n _pushable.throw(err);\n if (onEnd != null) {\n onEnd(err);\n onEnd = undefined;\n }\n return { done: true };\n },\n return() {\n _pushable.return();\n if (onEnd != null) {\n onEnd();\n onEnd = undefined;\n }\n return { done: true };\n },\n push,\n end(err) {\n _pushable.end(err);\n if (onEnd != null) {\n onEnd(err);\n onEnd = undefined;\n }\n return pushable;\n },\n get readableLength() {\n return _pushable.readableLength;\n },\n onEmpty: (opts) => {\n return _pushable.onEmpty(opts);\n }\n };\n return pushable;\n}\n//# sourceMappingURL=index.js.map","export class TimeoutError extends Error {\n\tname = 'TimeoutError';\n\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tError.captureStackTrace?.(this, TimeoutError);\n\t}\n}\n\nconst getAbortedReason = signal => signal.reason ?? new DOMException('This operation was aborted.', 'AbortError');\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t\tsignal,\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (signal?.aborted) {\n\t\t\treject(getAbortedReason(signal));\n\t\t\t// The input still needs a rejection handler even though cancellation won.\n\t\t\t// eslint-disable-next-line promise/prefer-await-to-then, promise/prefer-catch\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\tif (signal) {\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\t// Use .then() instead of async IIFE to preserve stack traces\n\t\t// eslint-disable-next-line promise/prefer-await-to-then, promise/prefer-catch\n\t\tpromise.then(resolve, reject);\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\t});\n\n\t// eslint-disable-next-line promise/prefer-await-to-then\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && signal) {\n\t\t\tsignal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","import pTimeout from 'p-timeout';\n\n// A filter function can stand in for the options. The options are copied, so a later change to the caller's object cannot reach the call.\nconst normalizeOptions = options => typeof options === 'function' ? {filter: options} : {...options};\n\n// A `count` or `limit`: a whole number of zero or more, or `Infinity`.\nconst isCount = value => value === Infinity || (Number.isSafeInteger(value) && value >= 0);\n\n// The removal method has to come from the same family as the one used to add, otherwise the listener is never detached.\nconst listenerMethodPairs = [\n\t['addEventListener', 'removeEventListener'],\n\t['on', 'off'],\n\t['addListener', 'removeListener'],\n];\n\nconst normalizeEmitter = emitter => {\n\tfor (const [addMethod, removeMethod] of listenerMethodPairs) {\n\t\tconst addListener = emitter?.[addMethod];\n\t\tconst removeListener = emitter?.[removeMethod];\n\n\t\tif (typeof addListener === 'function' && typeof removeListener === 'function') {\n\t\t\treturn {\n\t\t\t\taddListener: addListener.bind(emitter),\n\t\t\t\tremoveListener: removeListener.bind(emitter),\n\t\t\t};\n\t\t}\n\t}\n\n\tthrow new TypeError('Emitter is not compatible');\n};\n\n// Which handler serves each event name. A single name is a list of one. A name claimed by an earlier family keeps that handler, so the main event takes priority over `rejectionEvents`, which in turn takes priority over `resolutionEvents`. Registration and removal both walk the returned map, so they always agree, a repeated name gets one listener, and a later edit to the caller's arrays cannot reach them.\nconst listenerHandlers = families => {\n\tconst handlers = new Map();\n\n\tfor (const [names, handler] of families) {\n\t\tfor (const name of Array.isArray(names) ? names : [names]) {\n\t\t\tif (!handlers.has(name)) {\n\t\t\t\thandlers.set(name, handler);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn handlers;\n};\n\n// Attaches the abort handler first, so an emitter that fires the abort itself while a listener is being attached still reaches the caller. An emitter that hands over buffered events the moment a listener is attached can end the call part way through, and anything attached after that would never be removed, so attaching stops once the call is done. The call can also end before the emitter stores the listener, since Node's `EventEmitter` emits `newListener` first, so the cleanup misses that listener and it is removed here.\nconst attachListeners = ({addListener, removeListener, handlers, signal, abortHandler, isDone}) => {\n\tsignal?.addEventListener('abort', abortHandler, {once: true});\n\n\tfor (const [eventName, listener] of handlers) {\n\t\taddListener(eventName, listener);\n\n\t\tif (isDone()) {\n\t\t\tremoveListener(eventName, listener);\n\t\t\treturn;\n\t\t}\n\t}\n};\n\n// `once: true` only detaches the abort handler when the signal fires, so a call that ended another way has to remove it.\nconst detachListeners = ({removeListener, handlers, signal, abortHandler}) => {\n\tfor (const [eventName, listener] of handlers) {\n\t\tremoveListener(eventName, listener);\n\t}\n\n\tsignal?.removeEventListener('abort', abortHandler);\n};\n\n// Filters run one after another, so that an asynchronous one cannot reorder the values or read a `limit` that belongs to a later event. A verdict or a failure that arrives once the call is done is dropped, since the outcome is already decided and a cancelled promise must never settle.\nconst createFilterQueue = (filter, isDone, onError) => {\n\tlet queue = Promise.resolve();\n\n\treturn (value, onVerdict) => {\n\t\tqueue = queue.then(async () => {\n\t\t\t// The call is over, so the filter could only produce a verdict that is discarded.\n\t\t\tif (isDone()) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet isAccepted;\n\t\t\t// The filter's return value is a verdict rather than a rejection, so it is checked instead of caught.\n\t\t\ttry {\n\t\t\t\tisAccepted = filter ? await filter(value) : true;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isDone()) {\n\t\t\t\t\tonError(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!isDone()) {\n\t\t\t\tonVerdict(isAccepted);\n\t\t\t}\n\t\t});\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\t// The setup below can throw before `cancel` is assigned, and the returned promise documents a `.cancel()` method, so it starts out as a no-op.\n\tlet cancel = () => {};\n\t// Set by `cancel()`, which every path that stops listening runs, so an event still going through an asynchronous `filter` can tell that its result is no longer wanted.\n\tlet isDone = false;\n\tlet deadlineTimer;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = normalizeOptions(options);\n\n\t\t// Held in a local so the filter is called on its own, and `this` inside it is not the options object the library works from.\n\t\tconst {filter} = options;\n\n\t\tif (!isCount(options.count)) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\t// Checked here, before anything is attached, because `p-timeout` throws for it before it subscribes to this promise, which would leave the listeners attached and this rejection unhandled.\n\t\tif (typeof options.timeout === 'number'\n\t\t\t&& !(options.timeout > 0)) {\n\t\t\tthrow new TypeError(`Expected the \\`timeout\\` option to be a positive number, got \\`${options.timeout}\\``);\n\t\t}\n\n\t\toptions.signal?.throwIfAborted();\n\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\t// A count of zero is already satisfied, so it must not wait for an event or leave a listener behind.\n\t\tif (options.count === 0) {\n\t\t\tresolve([]);\n\t\t\treturn;\n\t\t}\n\n\t\tconst items = [];\n\n\t\t// The reason is a single value, so it must not be wrapped the way a rejection event's arguments are.\n\t\tconst rejectWithReason = reason => {\n\t\t\tcancel();\n\t\t\treject(reason);\n\t\t};\n\n\t\tconst queueFilter = createFilterQueue(filter, () => isDone, rejectWithReason);\n\n\t\tconst acceptItem = value => {\n\t\t\titems.push(value);\n\n\t\t\tif (options.count !== items.length) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tcancel();\n\t\t\tresolve(items);\n\t\t};\n\n\t\tconst onItem = (...arguments_) => {\n\t\t\t// The promise is already settled, so the array the caller holds must not keep growing. An emitter can still call a listener it removed during the same emit.\n\t\t\tif (isDone) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\tif (!filter) {\n\t\t\t\tacceptItem(value);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tqueueFilter(value, isAccepted => {\n\t\t\t\tif (isAccepted) {\n\t\t\t\t\tacceptItem(value);\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\n\t\tconst rejectHandler = (...arguments_) => {\n\t\t\trejectWithReason(options.rejectionMultiArgs ? arguments_ : arguments_[0]);\n\t\t};\n\n\t\tconst abortHandler = () => {\n\t\t\trejectWithReason(options.signal.reason);\n\t\t};\n\n\t\t// Allow multiple events. The main event takes priority over a rejection event, as documented. An explicit `undefined` reads as \"not set\" rather than overriding the default, so a forwarded partial options object does not end up listening for the literal name `\"undefined\"`.\n\t\tconst listening = {\n\t\t\taddListener,\n\t\t\tremoveListener,\n\t\t\thandlers: listenerHandlers([[event, onItem], [options.rejectionEvents ?? ['error'], rejectHandler]]),\n\t\t\tsignal: options.signal,\n\t\t\tabortHandler,\n\t\t\tisDone: () => isDone,\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tisDone = true;\n\n\t\t\t// Stopping the listening on any path has to release the deadline too, or it would hold the event loop open for a timer that can no longer do anything.\n\t\t\tclearTimeout(deadlineTimer);\n\n\t\t\tdetachListeners(listening);\n\t\t};\n\n\t\tattachListeners(listening);\n\n\t\t// A call that settled above was already cleaned up by `cancel()`, abort handler included.\n\t\tif (isDone || !options.resolveImmediately) {\n\t\t\treturn;\n\t\t}\n\n\t\t// The promise is fulfilled right away, and `pTimeout` clears its timer as soon as the promise settles, so the deadline is tracked here instead. An infinite deadline has nothing to wait for, and `setTimeout` would clamp it to 1 millisecond.\n\t\tif (Number.isFinite(options.timeout)) {\n\t\t\tdeadlineTimer = setTimeout(cancel, options.timeout);\n\t\t}\n\n\t\tresolve(items);\n\t});\n\n\treturnValue.cancel = cancel;\n\n\t// An invalid `timeout` already rejected the promise above, so it must not reach `pTimeout`.\n\tif (typeof options.timeout === 'number' && options.timeout > 0 && !options.resolveImmediately) {\n\t\tconst timeout = pTimeout(returnValue, {milliseconds: options.timeout});\n\t\t// When cancelling, also clear the timeout timer\n\t\ttimeout.cancel = () => {\n\t\t\tcancel();\n\t\t\ttimeout.clear();\n\t\t};\n\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tconst arrayPromise = pEventMultiple(emitter, event, {\n\t\t...normalizeOptions(options),\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t});\n\tconst promise = arrayPromise.then(array => array[0]);\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\toptions = normalizeOptions(options);\n\n\t// Held in a local so the filter is called on its own, and `this` inside it is not the options object the library works from.\n\tconst {filter} = options;\n\n\t// An explicit `undefined` reads as \"not set\" rather than overriding the default.\n\tconst limit = options.limit ?? Infinity;\n\tif (!isCount(limit)) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\t// Set as soon as a resolution event arrives, so no further value can enter the iteration while the queued filters drain.\n\tlet isResolving = false;\n\t// Wrapped as `{reason}`, so a rejection whose reason is `undefined` still counts as one.\n\tlet pendingError;\n\t// The payload of the resolution event, held until a read reports the iteration as done. See `cancel()`.\n\tlet resolutionValue;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\n\tconst cancel = finalValue => {\n\t\tisDone = true;\n\t\tdetachListeners(listening);\n\n\t\t// The first read that reports the iteration as done carries the payload of the resolution event, the same way a generator's first `{done: true}` result carries its return value. Published versions handed it over like this, and the async iterator protocol allows it, so `next()` callers can still read a final payload such as an exit code. Every read after that one gets `undefined`, as the protocol requires. Without a pending read, the payload waits in `resolutionValue` for the next one.\n\t\tresolutionValue = finalValue;\n\t\tfor (const {resolve} of nextQueue.splice(0)) {\n\t\t\tresolve({done: true, value: resolutionValue});\n\t\t\tresolutionValue = undefined;\n\t\t}\n\t};\n\n\tconst rejectIterator = reason => {\n\t\tif (isDone) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tnextQueue.shift().reject(reason);\n\t\t} else {\n\t\t\tpendingError = {reason};\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst queueFilter = createFilterQueue(filter, () => isDone, rejectIterator);\n\n\tconst acceptValue = value => {\n\t\tif (nextQueue.length > 0) {\n\t\t\tnextQueue.shift().resolve({done: false, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\t};\n\n\tconst valueHandler = (...arguments_) => {\n\t\t// The iteration is over, so a value that is still arriving must not be added to the queue. A resolution event ends the iteration, so a value emitted after it does not belong to it, not even in the same burst before the queued filters have drained.\n\t\tif (isDone || isResolving) {\n\t\t\treturn;\n\t\t}\n\n\t\teventCount++;\n\t\tconst isLastEvent = eventCount === limit;\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tconst onVerdict = isAccepted => {\n\t\t\tif (isAccepted) {\n\t\t\t\tacceptValue(value);\n\t\t\t}\n\n\t\t\t// A rejected value still counts towards the limit, so the iterator ends either way.\n\t\t\tif (isLastEvent) {\n\t\t\t\tcancel();\n\t\t\t}\n\t\t};\n\n\t\tif (filter) {\n\t\t\tqueueFilter(value, onVerdict);\n\t\t} else {\n\t\t\tonVerdict(true);\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\trejectIterator(options.rejectionMultiArgs ? arguments_ : arguments_[0]);\n\t};\n\n\tconst resolveHandler = (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\t\tisResolving = true;\n\n\t\t// The event ends the iteration, so its payload is never yielded as a value. It queues behind the value filters, even without a filter, so that a value which was already received still gets in. The event ends the iteration either way: the verdict only decides whether its payload is handed over as the final value, which is how published versions behaved, and a failure in the filter rejects the iteration.\n\t\tqueueFilter(value, isAccepted => {\n\t\t\t// `cancel()` settles any pending read, and the first one gets the payload.\n\t\t\tcancel(isAccepted ? value : undefined);\n\t\t});\n\t};\n\n\t// The reason is a single value, so it must not be wrapped the way a rejection event's arguments are.\n\tconst abortHandler = () => {\n\t\trejectIterator(options.signal.reason);\n\t};\n\n\t// Allow multiple events. A name that is already handled as a value must not also reject or end the iteration, and a rejection wins over a resolution, so a name never ends up with two handlers. An explicit `undefined` reads as \"not set\" rather than overriding the default, so a forwarded partial options object does not end up listening for the literal name `\"undefined\"`.\n\tconst listening = {\n\t\taddListener,\n\t\tremoveListener,\n\t\thandlers: listenerHandlers([\n\t\t\t[event, valueHandler],\n\t\t\t[options.rejectionEvents ?? ['error'], rejectHandler],\n\t\t\t[options.resolutionEvents ?? [], resolveHandler],\n\t\t]),\n\t\tsignal: options.signal,\n\t\tabortHandler,\n\t\tisDone: () => isDone,\n\t};\n\n\tconst iterator = {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\t// A value that was already received is always handed over, so the iteration is never reported done while one is still buffered.\n\t\t\t\treturn {\n\t\t\t\t\tdone: false,\n\t\t\t\t\tvalue: valueQueue.shift(),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (pendingError) {\n\t\t\t\tconst {reason} = pendingError;\n\t\t\t\tpendingError = undefined;\n\t\t\t\tthrow reason;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\t// Handed over once, so only the first read after the buffered values gets the payload of the resolution event.\n\t\t\t\tconst value = resolutionValue;\n\t\t\t\tresolutionValue = undefined;\n\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\t// Without a final value, `cancel()` also drops the payload of a resolution event that was not read yet.\n\t\t\tcancel();\n\n\t\t\t// The consumer ended the iteration, so nothing that is still buffered can come out of it.\n\t\t\tvalueQueue.length = 0;\n\t\t\tpendingError = undefined;\n\n\t\t\treturn {\n\t\t\t\tdone: true,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n\n\t// Return an empty async iterator to avoid any further cost. A limit of zero is already reached, so nothing is attached, and `cancel()` has nothing to remove.\n\tif (limit === 0) {\n\t\tisDone = true;\n\t\tlistening.handlers.clear();\n\t\treturn iterator;\n\t}\n\n\tattachListeners(listening);\n\n\t// Ending above runs `cancel()`, which already took the abort handler off, so there is nothing left here.\n\treturn iterator;\n}\n\nexport {TimeoutError} from 'p-timeout';\n","/**\n * A rate limit was hit\n */\nexport class RateLimitError extends Error {\n remainingPoints;\n msBeforeNext;\n consumedPoints;\n isFirstInDuration;\n constructor(message = 'Rate limit exceeded', props) {\n super(message);\n this.name = 'RateLimitError';\n this.remainingPoints = props.remainingPoints;\n this.msBeforeNext = props.msBeforeNext;\n this.consumedPoints = props.consumedPoints;\n this.isFirstInDuration = props.isFirstInDuration;\n }\n}\nexport class QueueFullError extends Error {\n static name = 'QueueFullError';\n constructor(message = 'The queue was full') {\n super(message);\n this.name = 'QueueFullError';\n }\n}\nexport class UnexpectedEOFError extends Error {\n static name = 'UnexpectedEOFError';\n name = 'UnexpectedEOFError';\n}\nexport class MaxEarlyStreamsError extends Error {\n static name = 'MaxEarlyStreamsError';\n name = 'MaxEarlyStreamsError';\n}\nexport class StreamClosedError extends Error {\n static name = 'StreamClosedError';\n name = 'StreamClosedError';\n}\n//# sourceMappingURL=errors.js.map","/**\n * @packageDocumentation\n *\n * Pass a promise and an abort signal and await the result.\n *\n * @example Basic usage\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws an AbortError\n * const resolve = await raceSignal(promise, controller.signal)\n * ```\n *\n * @example Overriding errors\n *\n * By default the thrown error is the `.reason` property of the signal but it's\n * possible to override this behaviour with the `translateError` option:\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws `Error('Oh no!')`\n * const resolve = await raceSignal(promise, controller.signal, {\n * translateError: (signal) => {\n * // use `signal`, or don't\n * return new Error('Oh no!')\n * }\n * })\n * ```\n */\nfunction defaultTranslate(signal) {\n return signal.reason;\n}\nexport function raceSignal(promise, signal, opts) {\n if (signal == null || promise == null) {\n return promise;\n }\n const translateError = opts?.translateError ?? defaultTranslate;\n if (signal.aborted) {\n // the passed promise may yet resolve or reject but the use has signalled\n // they are no longer interested so smother the error\n promise.catch(() => { });\n return Promise.reject(translateError(signal));\n }\n let listener;\n return Promise.race([\n promise,\n new Promise((resolve, reject) => {\n listener = () => {\n reject(translateError(signal));\n };\n signal.addEventListener('abort', listener);\n })\n ])\n .finally(() => {\n if (listener != null) {\n signal.removeEventListener('abort', listener);\n }\n });\n}\n//# sourceMappingURL=index.js.map","import { StreamResetError, TypedEventEmitter, StreamMessageEvent, StreamBufferError, StreamResetEvent, StreamAbortEvent, StreamCloseEvent, StreamStateError } from '@libp2p/interface';\nimport { pushable } from 'it-pushable';\nimport { raceSignal } from 'race-signal';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { StreamClosedError } from \"./errors.js\";\nconst DEFAULT_MAX_READ_BUFFER_LENGTH = Math.pow(2, 20) * 4; // 4MB\nexport class AbstractMessageStream extends TypedEventEmitter {\n status;\n timeline;\n inactivityTimeout;\n maxReadBufferLength;\n maxWriteBufferLength;\n log;\n direction;\n maxMessageSize;\n readStatus;\n writeStatus;\n remoteReadStatus;\n remoteWriteStatus;\n writableNeedsDrain;\n /**\n * Any data stored here is emitted before any new incoming data.\n *\n * This is used when the stream is paused or if data is pushed onto the stream\n */\n readBuffer;\n writeBuffer;\n sendingData;\n #readableEnded = false;\n /**\n * The error the stream was aborted or reset with, thrown by async iterators\n * after they have yielded all received data\n */\n #closeError;\n /**\n * Ends active async iterators. Unlike 'end' these run each time the readable\n * end is done, eg. again after data is pushed back following 'end'\n */\n #iteratorEnds = new Set();\n onDrainPromise;\n constructor(init) {\n super();\n this.status = 'open';\n this.log = init.log;\n this.direction = init.direction ?? 'outbound';\n this.inactivityTimeout = init.inactivityTimeout ?? 120_000;\n this.maxReadBufferLength = init.maxReadBufferLength ?? DEFAULT_MAX_READ_BUFFER_LENGTH;\n this.maxWriteBufferLength = init.maxWriteBufferLength;\n this.maxMessageSize = init.maxMessageSize;\n this.readBuffer = new Uint8ArrayList();\n this.writeBuffer = new Uint8ArrayList();\n this.readStatus = 'readable';\n this.remoteReadStatus = 'readable';\n this.writeStatus = 'writable';\n this.remoteWriteStatus = 'writable';\n this.sendingData = false;\n this.writableNeedsDrain = false;\n // @ts-expect-error type could have required fields other than 'open'\n this.timeline = {\n open: Date.now()\n };\n this.processSendQueue = this.processSendQueue.bind(this);\n const continueSendingOnDrain = () => {\n if (this.writableNeedsDrain) {\n this.log.trace('drain event received, continue sending data');\n this.writableNeedsDrain = false;\n queueMicrotask(() => {\n try {\n this.processSendQueue();\n }\n catch (err) {\n this.log.error('processSendQueue threw - %e', err);\n }\n });\n }\n this.onDrainPromise?.resolve();\n };\n this.addEventListener('drain', continueSendingOnDrain);\n const rejectOnDrainOnClose = (evt) => {\n this.onDrainPromise?.reject(evt.error ?? new StreamClosedError());\n };\n this.addEventListener('close', rejectOnDrainOnClose);\n }\n get readBufferLength() {\n return this.readBuffer.byteLength;\n }\n get readableEnded() {\n return this.#readableEnded;\n }\n get writeBufferLength() {\n return this.writeBuffer.byteLength;\n }\n async onDrain(options) {\n if (this.writableNeedsDrain !== true) {\n return Promise.resolve();\n }\n if (this.onDrainPromise == null) {\n this.onDrainPromise = Promise.withResolvers();\n }\n return raceSignal(this.onDrainPromise.promise, options?.signal);\n }\n async *[Symbol.asyncIterator]() {\n const output = pushable();\n let error;\n const streamAsyncIterableOnMessageListener = (evt) => {\n output.push(evt.data);\n };\n this.addEventListener('message', streamAsyncIterableOnMessageListener);\n const streamAsyncIterableEnd = () => {\n this.#iteratorEnds.delete(streamAsyncIterableEnd);\n // data pushed back later must stay buffered for the next reader\n this.removeEventListener('message', streamAsyncIterableOnMessageListener);\n // ending the pushable with an error discards data not yet yielded, so\n // throw the error after the output drains instead\n error = this.#closeError;\n output.end();\n };\n this.#iteratorEnds.add(streamAsyncIterableEnd);\n // there may already be nothing left to read\n if (this.readableDone()) {\n streamAsyncIterableEnd();\n }\n try {\n yield* output;\n if (error != null) {\n throw error;\n }\n }\n finally {\n this.removeEventListener('message', streamAsyncIterableOnMessageListener);\n this.#iteratorEnds.delete(streamAsyncIterableEnd);\n }\n }\n /**\n * Returns true if nothing is buffered and nothing more will arrive, because\n * the remote writable end is closed or our readable end is closing or closed\n */\n readableDone() {\n return this.readBuffer.byteLength === 0 && (this.remoteWriteStatus === 'closed' || this.readStatus === 'closing' || this.readStatus === 'closed');\n }\n isReadable() {\n return this.status === 'open';\n }\n send(data) {\n if (this.writeStatus === 'closed' || this.writeStatus === 'closing') {\n throw new StreamStateError(`Cannot write to a stream that is ${this.writeStatus}`);\n }\n this.log.trace('append %d bytes to write buffer', data.byteLength);\n this.writeBuffer.append(data);\n return this.processSendQueue();\n }\n /**\n * Close immediately for reading and writing and send a reset message (local\n * error)\n */\n abort(err) {\n if (this.status === 'aborted' || this.status === 'reset' || this.status === 'closed') {\n // a paused reader can still hold unread data after the stream closes,\n // discard it so iterators waiting on it end\n if (this.readBuffer.byteLength > 0) {\n this.#closeError ??= err;\n this.readBuffer.consume(this.readBuffer.byteLength);\n this.readStatus = 'closed';\n this.maybeDispatchEnd();\n }\n return;\n }\n this.log.error('abort with error - %e', err);\n this.status = 'aborted';\n this.#closeError = err;\n // throw away unread data\n if (this.readBuffer.byteLength > 0) {\n this.readBuffer.consume(this.readBuffer.byteLength);\n }\n // throw away unsent data\n if (this.writeBuffer.byteLength > 0) {\n this.writeBuffer.consume(this.writeBuffer.byteLength);\n this.safeDispatchEvent('idle');\n }\n this.writeStatus = 'closed';\n this.remoteWriteStatus = 'closed';\n this.readStatus = 'closed';\n this.remoteReadStatus = 'closed';\n this.timeline.close = Date.now();\n this.maybeDispatchEnd();\n try {\n this.sendReset(err);\n }\n catch (err) {\n this.log.error('failed to send reset to remote - %e', err);\n }\n this.dispatchEvent(new StreamAbortEvent(err));\n }\n pause() {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError('Cannot pause a stream that is closing/closed');\n }\n if (this.readStatus === 'paused') {\n return;\n }\n this.readStatus = 'paused';\n this.sendPause();\n }\n resume() {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError('Cannot resume a stream that is closing/closed');\n }\n if (this.readStatus === 'readable') {\n return;\n }\n this.readStatus = 'readable';\n // emit any data that accumulated while we were paused\n this.dispatchReadBuffer();\n this.sendResume();\n }\n push(data) {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError(`Cannot push data onto a stream that is ${this.readStatus}`);\n }\n if (data.byteLength === 0) {\n return;\n }\n this.readBuffer.append(data);\n if (this.readStatus === 'paused' || this.listenerCount('message') === 0) {\n // abort if the read buffer is too large\n this.checkReadBufferLength();\n return;\n }\n // TODO: use a microtask instead?\n setTimeout(() => {\n this.dispatchReadBuffer();\n }, 0);\n }\n unshift(data) {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError(`Cannot push data onto a stream that is ${this.readStatus}`);\n }\n if (data.byteLength === 0) {\n return;\n }\n this.readBuffer.prepend(data);\n if (this.readStatus === 'paused' || this.listenerCount('message') === 0) {\n // abort if the read buffer is too large\n this.checkReadBufferLength();\n return;\n }\n // TODO: use a microtask instead?\n setTimeout(() => {\n this.dispatchReadBuffer();\n }, 0);\n }\n /**\n * When an extending class reads data from it's implementation-specific source,\n * call this method to allow the stream consumer to read the data.\n */\n onData(data) {\n if (data.byteLength === 0) {\n // this.log('ignoring empty data')\n return;\n }\n // discard the data if our readable end is closed\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('ignoring data - read status %s', this.readStatus);\n return;\n }\n this.readBuffer.append(data);\n this.dispatchReadBuffer();\n }\n addEventListener(...args) {\n // @ts-expect-error cannot ensure args has enough members\n super.addEventListener.apply(this, args);\n // if a 'message' listener is being added and we have queued data, dispatch\n // the data\n if (args[0] === 'message' && this.readBuffer.byteLength > 0) {\n // event listeners can be added in constructors and often use object\n // properties - if this the case we can access a class member before it\n // has been initialized so dispatch the message in the microtask queue\n queueMicrotask(() => {\n this.dispatchReadBuffer();\n });\n }\n }\n /**\n * Receive a reset message (remote error) - close immediately for writing,\n * buffered data can still be read. Ignored once the stream has closed\n */\n onRemoteReset() {\n // only emit one 'close' event and keep the first close error\n if (this.status === 'aborted' || this.status === 'reset' || this.status === 'closed') {\n return;\n }\n this.log('remote reset');\n const err = new StreamResetError();\n this.#closeError = err;\n this.status = 'reset';\n this.writeStatus = 'closed';\n this.remoteWriteStatus = 'closed';\n this.remoteReadStatus = 'closed';\n this.timeline.close = Date.now();\n if (this.readBuffer.byteLength === 0) {\n this.readStatus = 'closed';\n this.maybeDispatchEnd();\n }\n this.dispatchEvent(new StreamResetEvent(err));\n }\n /**\n * The underlying resource or transport this stream uses has closed - it is\n * not possible to send any more messages though any data still in the read\n * buffer may still be read\n */\n onTransportClosed(err) {\n this.log('transport closed');\n if (this.readStatus === 'readable' && this.readBuffer.byteLength === 0) {\n this.log('close readable end after transport closed and read buffer is empty');\n this.readStatus = 'closed';\n }\n if (this.remoteReadStatus !== 'closed') {\n this.remoteReadStatus = 'closed';\n }\n if (this.remoteWriteStatus !== 'closed') {\n this.remoteWriteStatus = 'closed';\n }\n if (this.writeStatus !== 'closed') {\n this.writeStatus = 'closed';\n }\n if (err != null) {\n // abort dispatches 'end' itself, once the stream is fully terminal\n this.abort(err);\n }\n else if (this.status === 'open' || this.status === 'closing') {\n this.timeline.close = Date.now();\n this.status = 'closed';\n // this may be the end even if the readable end was not closed above\n this.maybeDispatchEnd();\n this.dispatchEvent(new StreamCloseEvent());\n }\n }\n /**\n * Called by extending classes when the remote closes its writable end\n */\n onRemoteCloseWrite() {\n if (this.remoteWriteStatus === 'closed') {\n return;\n }\n this.log.trace('on remote close write');\n this.remoteWriteStatus = 'closed';\n this.safeDispatchEvent('remoteCloseWrite');\n this.maybeDispatchEnd();\n if (this.writeStatus === 'closed') {\n this.onTransportClosed();\n }\n }\n /**\n * Called by extending classes when the remote closes its readable end\n */\n onRemoteCloseRead() {\n this.log.trace('on remote close read');\n this.remoteReadStatus = 'closed';\n // throw away any unsent bytes if the remote closes it's readable end\n if (this.writeBuffer.byteLength > 0) {\n this.writeBuffer.consume(this.writeBuffer.byteLength);\n this.safeDispatchEvent('idle');\n }\n }\n processSendQueue() {\n // bail if the underlying transport is full\n if (this.writableNeedsDrain) {\n this.log.trace('not processing send queue as drain is required');\n this.checkWriteBufferLength();\n return false;\n }\n // bail if there is no data to send\n if (this.writeBuffer.byteLength === 0) {\n this.log.trace('not processing send queue as no bytes to send');\n return true;\n }\n // bail if we are already sending data\n if (this.sendingData) {\n this.log.trace('not processing send queue as already sending data');\n return true;\n }\n if (this.writeStatus !== 'writable' && this.writeStatus !== 'closing') {\n this.log.trace('not processing send queue as stream is %s', this.writeStatus);\n return false;\n }\n this.sendingData = true;\n this.log.trace('processing send queue with %d queued bytes', this.writeBuffer.byteLength);\n try {\n let canSendMore = true;\n const totalBytes = this.writeBuffer.byteLength;\n let sentBytes = 0;\n // send as much data as possible while we have data to send and the\n // underlying muxer can still accept data\n while (this.writeBuffer.byteLength > 0) {\n const end = Math.min(this.maxMessageSize ?? this.writeBuffer.byteLength, this.writeBuffer.byteLength);\n // this can happen if a subclass changes the max message size dynamically\n if (end === 0) {\n canSendMore = false;\n break;\n }\n // chunk to send to the remote end\n const toSend = this.writeBuffer.sublist(0, end);\n // copy toSend in case the extending class modifies the list\n const willSend = new Uint8ArrayList(toSend);\n this.writeBuffer.consume(toSend.byteLength);\n // sending data can cause buffers to fill up, events to be emitted and\n // this method to be invoked again\n let sendResult;\n try {\n sendResult = this.sendData(toSend);\n }\n catch (err) {\n // restore the consumed chunk so abort() emits 'idle' for the drained\n // write buffer (normally emitted here on completion, but the send threw)\n this.writeBuffer.prepend(willSend);\n this.abort(err);\n throw err;\n }\n canSendMore = sendResult.canSendMore;\n sentBytes += sendResult.sentBytes;\n if (sendResult.sentBytes !== willSend.byteLength) {\n willSend.consume(sendResult.sentBytes);\n this.writeBuffer.prepend(willSend);\n }\n if (!canSendMore) {\n break;\n }\n }\n if (!canSendMore) {\n this.log.trace('sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer', sentBytes, totalBytes, this.writeBuffer.byteLength);\n this.writableNeedsDrain = true;\n this.checkWriteBufferLength();\n }\n // we processed all bytes in the queue, resolve the write queue idle promise\n if (this.writeBuffer.byteLength === 0) {\n this.safeDispatchEvent('idle');\n }\n return canSendMore;\n }\n finally {\n this.sendingData = false;\n }\n }\n /**\n * If nothing is buffered and no more data will be delivered, end any active\n * async iterators and emit 'end'. 'end' is emitted at most once\n */\n maybeDispatchEnd() {\n if (!this.readableDone()) {\n return;\n }\n this.#iteratorEnds.forEach(end => { end(); });\n if (this.#readableEnded) {\n return;\n }\n this.#readableEnded = true;\n this.safeDispatchEvent('end');\n }\n dispatchReadBuffer() {\n try {\n if (this.listenerCount('message') === 0) {\n this.log.trace('not dispatching pause buffer as there are no listeners for the message event');\n return;\n }\n if (this.readBuffer.byteLength === 0) {\n this.log.trace('not dispatching pause buffer as there is no data to dispatch');\n return;\n }\n if (this.readStatus === 'paused') {\n this.log.trace('not dispatching pause buffer we are paused');\n return;\n }\n // discard the pause buffer if our readable end is closed\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('dropping %d bytes because the readable end is %s', this.readBuffer.byteLength, this.readStatus);\n this.readBuffer.consume(this.readBuffer.byteLength);\n return;\n }\n const buf = this.readBuffer.sublist();\n this.readBuffer.consume(buf.byteLength);\n this.dispatchEvent(new StreamMessageEvent(buf));\n }\n finally {\n if (this.readBuffer.byteLength === 0 && this.remoteWriteStatus === 'closed') {\n this.log('close readable end after dispatching read buffer and remote writable end is closed');\n this.readStatus = 'closed';\n this.maybeDispatchEnd();\n }\n // abort if we failed to consume the read buffer and it is too large\n this.checkReadBufferLength();\n }\n }\n checkReadBufferLength() {\n if (this.readBuffer.byteLength > this.maxReadBufferLength) {\n this.abort(new StreamBufferError(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`));\n }\n }\n checkWriteBufferLength() {\n if (this.maxWriteBufferLength == null) {\n return;\n }\n if (this.writeBuffer.byteLength > this.maxWriteBufferLength) {\n this.abort(new StreamBufferError(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`));\n }\n }\n onMuxerNeedsDrain() {\n this.writableNeedsDrain = true;\n }\n onMuxerDrain() {\n this.safeDispatchEvent('drain');\n }\n}\n//# sourceMappingURL=abstract-message-stream.js.map","import { StreamMessageEvent, StreamCloseEvent, InvalidParametersError, StreamBufferError } from '@libp2p/interface';\nimport { pipe as itPipe } from 'it-pipe';\nimport { pushable } from 'it-pushable';\nimport { pEvent } from 'p-event';\nimport { raceSignal } from 'race-signal';\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { UnexpectedEOFError } from \"./errors.js\";\nconst DEFAULT_MAX_BUFFER_SIZE = 4_194_304;\nexport class UnwrappedError extends Error {\n static name = 'UnwrappedError';\n name = 'UnwrappedError';\n}\n/**\n * The reported length of the next data message was not a positive integer\n */\nexport class InvalidMessageLengthError extends Error {\n name = 'InvalidMessageLengthError';\n code = 'ERR_INVALID_MSG_LENGTH';\n}\n/**\n * The reported length of the next data message was larger than the configured\n * max allowable value\n */\nexport class InvalidDataLengthError extends Error {\n name = 'InvalidDataLengthError';\n code = 'ERR_MSG_DATA_TOO_LONG';\n}\n/**\n * The varint used to specify the length of the next data message contained more\n * bytes than the configured max allowable value\n */\nexport class InvalidDataLengthLengthError extends Error {\n name = 'InvalidDataLengthLengthError';\n code = 'ERR_MSG_LENGTH_TOO_LONG';\n}\nfunction isStream(obj) {\n return typeof obj?.closeRead === 'function';\n}\nfunction isMultiaddrConnection(obj) {\n return typeof obj?.close === 'function';\n}\nfunction isEOF(obj) {\n if (isStream(obj)) {\n return obj.remoteWriteStatus !== 'writable' && obj.readBufferLength === 0;\n }\n if (isMultiaddrConnection(obj)) {\n return obj.status !== 'open';\n }\n return false;\n}\nfunction isValid(obj) {\n return obj?.addEventListener != null && obj?.removeEventListener != null && obj?.send != null && obj?.push != null && obj?.log != null;\n}\nexport function byteStream(stream, opts) {\n const maxBufferSize = opts?.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;\n const readBuffer = new Uint8ArrayList();\n let hasBytes;\n let unwrapped = false;\n let overflow;\n if (!isValid(stream)) {\n throw new InvalidParametersError('Argument should be a Stream or a Multiaddr');\n }\n const byteStreamOnMessageListener = (evt) => {\n // the underlying stream owns incoming data once we have been unwrapped\n if (unwrapped) {\n return;\n }\n if (overflow != null) {\n // the stream is being aborted after a previous overflow, ignore any\n // more data\n return;\n }\n readBuffer.append(evt.data);\n if (readBuffer.byteLength > maxBufferSize) {\n const readBufferSize = readBuffer.byteLength;\n readBuffer.consume(readBufferSize);\n // hasBytes only exists while a read is in flight and is already settled\n // otherwise, so rejecting it reaches nobody between reads.\n const err = new StreamBufferError(`Read buffer overflow - ${readBufferSize} > ${maxBufferSize}`);\n overflow = err;\n hasBytes?.reject(err);\n // let the current dispatch finish first\n queueMicrotask(() => {\n stream.abort(err);\n });\n return;\n }\n hasBytes?.resolve();\n };\n stream.addEventListener('message', byteStreamOnMessageListener);\n const byteStreamOnCloseListener = (evt) => {\n if (evt.error != null) {\n hasBytes?.reject(evt.error);\n }\n else {\n hasBytes?.resolve();\n }\n };\n stream.addEventListener('close', byteStreamOnCloseListener);\n const byteStreamOnRemoteCloseWrite = () => {\n hasBytes?.resolve();\n };\n stream.addEventListener('remoteCloseWrite', byteStreamOnRemoteCloseWrite);\n const byteStream = {\n readBuffer,\n // @ts-expect-error options type prevents type inference\n async read(options) {\n if (unwrapped === true) {\n throw new UnwrappedError('Stream was unwrapped');\n }\n if (overflow != null) {\n throw overflow;\n }\n if (isEOF(stream)) {\n if (readBuffer.byteLength === 0 && options?.bytes == null) {\n return null;\n }\n if (options?.bytes != null && readBuffer.byteLength < options.bytes) {\n stream.log.error('closed after reading %d/%d bytes', readBuffer.byteLength, options.bytes);\n throw new UnexpectedEOFError(`Unexpected EOF - stream closed after reading ${readBuffer.byteLength}/${options.bytes} bytes`);\n }\n }\n const bytesToRead = options?.bytes ?? 1;\n hasBytes = Promise.withResolvers();\n while (true) {\n if (readBuffer.byteLength >= bytesToRead) {\n // if we are about to exit the loop this promise will not be awaited\n // so resolve it to prevent and unhandled promise rejections that may\n // occur\n hasBytes.resolve();\n break;\n }\n await raceSignal(hasBytes.promise, options?.signal);\n if (isEOF(stream)) {\n if (readBuffer.byteLength === 0 && options?.bytes == null) {\n return null;\n }\n break;\n }\n hasBytes = Promise.withResolvers();\n }\n const toRead = options?.bytes ?? readBuffer.byteLength;\n if (readBuffer.byteLength < toRead) {\n if (isEOF(stream)) {\n stream.log.error('closed while reading %d/%d bytes', readBuffer.byteLength, toRead);\n throw new UnexpectedEOFError(`Unexpected EOF - stream closed while reading ${readBuffer.byteLength}/${toRead} bytes`);\n }\n return byteStream.read(options);\n }\n const output = readBuffer.sublist(0, toRead);\n readBuffer.consume(toRead);\n return output;\n },\n async write(data, options) {\n if (unwrapped === true) {\n throw new UnwrappedError('Stream was unwrapped');\n }\n if (!stream.send(data)) {\n await pEvent(stream, 'drain', {\n signal: options?.signal,\n rejectionEvents: ['close']\n });\n }\n },\n unwrap() {\n // already unwrapped, just return the original stream\n if (unwrapped) {\n return stream;\n }\n // only unwrap once\n unwrapped = true;\n stream.removeEventListener('message', byteStreamOnMessageListener);\n stream.removeEventListener('close', byteStreamOnCloseListener);\n stream.removeEventListener('remoteCloseWrite', byteStreamOnRemoteCloseWrite);\n // emit any unread data\n if (readBuffer.byteLength > 0) {\n stream.log('stream unwrapped with %d unread bytes', readBuffer.byteLength);\n stream.unshift(readBuffer);\n readBuffer.consume(readBuffer.byteLength);\n }\n return stream;\n }\n };\n return byteStream;\n}\nexport function lpStream(stream, opts = {}) {\n const bytes = byteStream(stream, opts);\n if (opts.maxDataLength != null && opts.maxLengthLength == null) {\n // if max data length is set but max length length is not, calculate the\n // max length length needed to encode max data length\n opts.maxLengthLength = varint.encodingLength(opts.maxDataLength);\n }\n const decodeLength = opts?.lengthDecoder ?? varint.decode;\n const encodeLength = opts?.lengthEncoder ?? varint.encode;\n const lpStream = {\n async read(options) {\n let dataLength = -1;\n const lengthBuffer = new Uint8ArrayList();\n while (true) {\n // read one byte at a time until we can decode a varint\n const buf = await bytes.read({\n ...options,\n bytes: 1\n });\n // the underlying resource closed gracefully\n if (buf == null) {\n break;\n }\n // append byte and try to decode\n lengthBuffer.append(buf);\n try {\n dataLength = decodeLength(lengthBuffer);\n }\n catch (err) {\n if (err instanceof RangeError) {\n continue;\n }\n throw err;\n }\n if (dataLength < 0) {\n throw new InvalidMessageLengthError('Invalid message length');\n }\n if (opts?.maxLengthLength != null && lengthBuffer.byteLength > opts.maxLengthLength) {\n throw new InvalidDataLengthLengthError(`Message length length too long - ${lengthBuffer.byteLength} > ${opts.maxLengthLength}`);\n }\n if (dataLength > -1) {\n break;\n }\n }\n if (opts?.maxDataLength != null && dataLength > opts.maxDataLength) {\n throw new InvalidDataLengthError(`Message length too long - ${dataLength} > ${opts.maxDataLength}`);\n }\n const buf = await bytes.read({\n ...options,\n bytes: dataLength\n });\n if (buf == null) {\n stream.log.error('tried to read %d bytes but the stream closed', dataLength);\n throw new UnexpectedEOFError(`Unexpected EOF - tried to read ${dataLength} bytes but the stream closed`);\n }\n if (buf.byteLength !== dataLength) {\n stream.log.error('read %d/%d bytes before the stream closed', buf.byteLength, dataLength);\n throw new UnexpectedEOFError(`Unexpected EOF - read ${buf.byteLength}/${dataLength} bytes before the stream closed`);\n }\n return buf;\n },\n async write(data, options) {\n // encode, write\n await bytes.write(new Uint8ArrayList(encodeLength(data.byteLength), data), options);\n },\n async writeV(data, options) {\n const list = new Uint8ArrayList(...data.flatMap(buf => ([encodeLength(buf.byteLength), buf])));\n // encode, write\n await bytes.write(list, options);\n },\n unwrap() {\n return bytes.unwrap();\n }\n };\n return lpStream;\n}\nexport function pbStream(stream, opts) {\n const lp = lpStream(stream, opts);\n const pbStream = {\n read: async (proto, options) => {\n // readLP, decode\n const value = await lp.read(options);\n return proto.decode(value, options);\n },\n write: async (message, proto, options) => {\n // encode, writeLP\n await lp.write(proto.encode(message), options);\n },\n writeV: async (messages, proto, options) => {\n // encode, writeLP\n await lp.writeV(messages.map(message => proto.encode(message)), options);\n },\n pb: (proto) => {\n return {\n read: async (options) => pbStream.read(proto, options),\n write: async (d, options) => pbStream.write(d, proto, options),\n writeV: async (d, options) => pbStream.writeV(d, proto, options),\n unwrap: () => pbStream\n };\n },\n unwrap: () => {\n return lp.unwrap();\n }\n };\n return pbStream;\n}\nexport async function echo(stream, options) {\n const log = stream.log.newScope('echo');\n const start = Date.now();\n let bytes = 0;\n try {\n for await (const buf of stream) {\n bytes += buf.byteLength;\n if (!stream.send(buf)) {\n stream.pause();\n await pEvent(stream, 'drain', {\n rejectionEvents: [\n 'close'\n ],\n ...options\n });\n stream.resume();\n }\n }\n log('echoed %d bytes in %dms', bytes, Date.now() - start);\n await stream.close(options);\n }\n catch (err) {\n stream.abort(err);\n }\n}\nfunction isMessageStream(obj) {\n return obj?.addEventListener != null;\n}\nexport function messageStreamToDuplex(stream) {\n const source = pushable();\n let onError;\n const onMessage = (evt) => {\n source.push(evt.data);\n };\n const onRemoteCloseWrite = () => {\n source.end();\n stream.removeEventListener('message', onMessage);\n stream.removeEventListener('close', onClose);\n stream.removeEventListener('remoteCloseWrite', onRemoteCloseWrite);\n };\n const onClose = (evt) => {\n source.end(evt.error);\n if (evt.error != null) {\n onError?.reject(evt.error);\n }\n stream.removeEventListener('message', onMessage);\n stream.removeEventListener('close', onClose);\n stream.removeEventListener('remoteCloseWrite', onRemoteCloseWrite);\n };\n stream.addEventListener('message', onMessage);\n stream.addEventListener('close', onClose, {\n once: true\n });\n stream.addEventListener('remoteCloseWrite', onRemoteCloseWrite, {\n once: true\n });\n return {\n source,\n async sink(source) {\n async function* toGenerator() {\n yield* source;\n }\n const gen = toGenerator();\n while (true) {\n onError = Promise.withResolvers();\n const { done, value } = await Promise.race([\n gen.next(),\n onError.promise\n ]);\n if (stream.writeStatus === 'closing' || stream.writeStatus === 'closed') {\n break;\n }\n if (value != null) {\n if (!stream.send(value)) {\n await Promise.race([\n pEvent(stream, 'drain', {\n rejectionEvents: [\n 'close'\n ]\n })\n ]);\n }\n }\n if (done === true) {\n break;\n }\n }\n await stream.close();\n }\n };\n}\nexport function pipe(...input) {\n const sources = input.map(source => {\n if (isMessageStream(source)) {\n return messageStreamToDuplex(source);\n }\n return source;\n });\n // @ts-expect-error it-pipe types say args cannot be spread like this\n return itPipe(...sources);\n}\n//# sourceMappingURL=stream-utils.js.map","import { InvalidParametersError } from '@libp2p/interface';\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { InvalidMessageLengthError } from \"./stream-utils.js\";\nconst DEFAULT_MAX_BUFFER_SIZE = 1024 * 1024 * 4;\nconst DEFAULT_MAX_DATA_LENGTH = 1024 * 1024 * 4;\n/**\n * Decode length-prefixed data from a buffer\n */\nexport class LengthPrefixedDecoder {\n buffer;\n maxBufferSize;\n lengthDecoder;\n maxDataLength;\n encodingLength;\n constructor(init = {}) {\n this.buffer = new Uint8ArrayList();\n this.maxBufferSize = init.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;\n this.maxDataLength = init.maxDataLength ?? DEFAULT_MAX_DATA_LENGTH;\n this.lengthDecoder = init.lengthDecoder ?? varint.decode;\n this.encodingLength = init.encodingLength ?? varint.encodingLength;\n }\n /**\n * Decodes length-prefixed data\n */\n *decode(buf) {\n this.buffer.append(buf);\n if (this.buffer.byteLength > this.maxBufferSize) {\n throw new InvalidParametersError(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);\n }\n // Loop to consume as many bytes from the buffer as possible\n // Eg: when a single chunk contains several frames\n while (true) {\n let dataLength;\n try {\n dataLength = this.lengthDecoder(this.buffer);\n }\n catch (err) {\n if (err instanceof RangeError) {\n // ignore errors where we don't have enough data to read the length\n // prefix\n break;\n }\n throw err;\n }\n if (dataLength < 0 || dataLength > this.maxDataLength) {\n throw new InvalidMessageLengthError('Invalid message length');\n }\n const lengthLength = this.encodingLength(dataLength);\n const chunkLength = lengthLength + dataLength;\n if (this.buffer.byteLength >= chunkLength) {\n const buf = this.buffer.sublist(lengthLength, chunkLength);\n this.buffer.consume(chunkLength);\n if (buf.byteLength > 0) {\n yield buf;\n }\n }\n else {\n break;\n }\n }\n }\n}\n//# sourceMappingURL=length-prefixed-decoder.js.map","export const NOISE_MSG_MAX_LENGTH_BYTES = 65535;\nexport const NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG = NOISE_MSG_MAX_LENGTH_BYTES - 16;\nexport const DUMP_SESSION_KEYS = Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);\nexport const CHACHA_TAG_LENGTH = 16;\n//# sourceMappingURL=constants.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - Value to inspect.\n * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.\n * @example\n * Guards a value before treating it as raw key material.\n *\n * ```ts\n * isBytes(new Uint8Array());\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /\n // cross-realm cases. The fallback still requires a real ArrayBuffer view\n // so plain JSON-deserialized `{ constructor: ... }`\n // spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is boolean.\n * @param value - Value to validate.\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validates a boolean option before branching on it.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is a non-negative safe integer.\n * @param n - Value to validate.\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validates a non-negative length or counter.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - Value to validate.\n * @param length - Expected byte length.\n * @param title - Optional label used in error messages.\n * @returns The validated byte array.\n * On Node, `Buffer` is accepted too because it is a Uint8Array view.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument lengths. {@link RangeError}\n * @example\n * Validates a fixed-length nonce or key buffer.\n *\n * ```ts\n * abytes(new Uint8Array([1, 2]), 2);\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(label === 'object'\n ? 'expected valid options object'\n : `\"${label}\" expected object, got type=${typeof value}`);\n};\n/**\n * Asserts a hash- or MAC-like instance has not been destroyed or finished.\n * @param instance - Stateful instance to validate.\n * @param checkFinished - Whether to reject finished instances.\n * When `false`, only `destroyed` is checked.\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Guards against calling `update()` or `digest()` on a finished hash.\n *\n * ```ts\n * aexists({ destroyed: false, finished: false });\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,\n * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @example\n * Verifies that a caller-provided output buffer is large enough.\n *\n * ```ts\n * aoutput(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Asserts output is a sufficiently-sized, 4-byte-aligned byte array.\n * {@link aoutput} plus an {@link isAligned32} check, for `digestInto()` paths\n * that write through zero-allocation `u32` word views.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @throws On wrong output buffer alignment. {@link Error}\n * @example\n * Verifies that a caller-provided output buffer is large enough and aligned.\n *\n * ```ts\n * aoutput32(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput32(out, instance) {\n aoutput(out, instance);\n if (!isAligned32(out))\n throw new Error('invalid output, must be aligned');\n}\n/**\n * Casts a typed-array view to Uint8Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint8Array view over the same bytes.\n * @example\n * Views 32-bit words as raw bytes without copying.\n *\n * ```ts\n * u8(new Uint32Array([1]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed-array view to Uint32Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint32Array view over the same bytes. Callers are expected to provide a\n * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.\n * @example\n * Views a byte buffer as 32-bit words for block processing.\n *\n * ```ts\n * u32(new Uint8Array(4));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place.\n * Warning: JS provides no guarantees.\n * @param arrays - Arrays to wipe.\n * @example\n * Wipes a temporary key buffer after use.\n *\n * ```ts\n * const bytes = new Uint8Array([1]);\n * clean(bytes);\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - Typed-array view to wrap.\n * @returns DataView over the same bytes.\n * @example\n * Creates an endian-aware view for length encoding.\n *\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Whether the current platform is little-endian.\n * Most are; some IBM systems are not.\n */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Reverses byte order of one 32-bit word.\n * @param word - Unsigned 32-bit word to swap.\n * @returns The same word with bytes reversed.\n * @example\n * Swaps a big-endian word into little-endian byte order.\n *\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Normalizes one 32-bit word to the little-endian representation expected by cipher cores.\n * @param n - Unsigned 32-bit word to normalize.\n * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.\n * @example\n * Normalizes a host-endian word before passing it into an ARX/AES core.\n *\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - Uint32Array whose words should be swapped.\n * @returns The same array after in-place byte swapping.\n * @example\n * Swaps every 32-bit word in a word-view buffer.\n *\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.\n * @param u - Word view to normalize in place.\n * @returns Little-endian normalized word view.\n * @example\n * Normalizes a word-view buffer before block processing.\n *\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion:\n// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Formats ciphertext bytes for logs or test vectors.\n *\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\nconst _0n = /* @__PURE__ */ BigInt(0);\n// Used in ff1, via bytesToNumberBE\n/**\n * Converts a big-endian hex string into bigint.\n * @param hex - Hexadecimal string without `0x`.\n * @returns Parsed bigint value. The empty string is treated as `0n`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parses a big-endian field element or counter from hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n // Numeric parser, not byte-hex decoder: odd-length forms like 'f' are valid,\n // and malformed syntax follows BigInt's native error behavior.\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// Used in ff1\n// BE: Big Endian, LE: Little Endian\n/**\n * Converts big-endian bytes into bigint.\n * @param bytes - Big-endian bytes.\n * @returns Parsed bigint value. Empty input is treated as `0n`.\n * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}\n * @example\n * Reads a big-endian integer from serialized bytes.\n *\n * ```ts\n * bytesToNumberBE(new Uint8Array([1, 0]));\n * ```\n */\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n */\nfunction abignumber(n) {\n if (typeof n === 'bigint') {\n if (!(_0n <= n))\n throw new RangeError('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\n// Used in ff1\n/**\n * Converts a number into big-endian bytes of fixed length.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian bytes padded to `len`.\n * Negative values, `len = 0`, and values that do not fit are rejected before\n * downstream hex parsing.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Encodes a counter as fixed-width big-endian bytes.\n *\n * ```ts\n * numberToBytesBE(1, 2);\n * ```\n */\nexport function numberToBytesBE(n, len) {\n anumber(len);\n if (len === 0)\n throw new Error('zero output length is invalid');\n n = abignumber(n);\n const expectedLen = len * 2;\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > expectedLen)\n throw new RangeError('number is too large');\n return hexToBytes(hex.padStart(expectedLen, '0'));\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @param str - String to encode.\n * @returns UTF-8 bytes in a detached fresh Uint8Array copy.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encodes application text before encryption or MACing.\n *\n * ```ts\n * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // {@link https://bugzil.la/1681809 | Firefox bug 1681809}\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @param bytes - UTF-8 bytes.\n * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed\n * UTF-8 is replacement-decoded instead of rejected.\n * @example\n * Decodes UTF-8 plaintext back into a string.\n *\n * ```ts\n * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'\n * ```\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Checks if two U8A use same underlying buffer and overlaps.\n * This is invalid and can corrupt data.\n * @param a - First byte view.\n * @param b - Second byte view.\n * @returns `true` when the views overlap in memory.\n * @example\n * Detects whether two slices alias the same backing buffer.\n *\n * ```ts\n * overlapBytes(new Uint8Array(4), new Uint8Array(4));\n * ```\n */\nexport function overlapBytes(a, b) {\n // Zero-length views cannot overwrite anything, even if their offset sits inside another range.\n if (!a.byteLength || !b.byteLength)\n return false;\n return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy\n a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end\n b.byteOffset < a.byteOffset + a.byteLength // b starts before a end\n );\n}\n/**\n * If input and output overlap and input starts before output, we will overwrite end of input before\n * we start processing it, so this is not supported by forward-processing ciphers.\n * @param input - Input bytes.\n * @param output - Output bytes.\n * @throws If the output view would overwrite unread input bytes. {@link Error}\n * @example\n * Rejects an in-place layout that would overwrite unread input bytes.\n *\n * ```ts\n * const buffer = new Uint8Array(8);\n * complexOverlapBytes(buffer.subarray(0, 4), buffer.subarray(2, 6));\n * ```\n */\nexport function complexOverlapBytes(input, output) {\n // This is very cursed. It works somehow, but I'm completely unsure,\n // reasoning about overlapping aligned windows is very hard.\n if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)\n throw new Error('complex overlap of input and output is not supported');\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - Byte arrays to concatenate.\n * @returns Combined byte array.\n * @throws On wrong argument types inside the byte-array list. {@link TypeError}\n * @example\n * Builds a `nonce || ciphertext` style buffer.\n *\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Merges user options into defaults.\n * @param defaults - Default option values.\n * @param opts - User-provided overrides.\n * @returns Combined options object.\n * `defaults` is a library-owned mutable object; user-provided `opts` only need to be\n * object-shaped, since \"plain object\" checks reject valid proxy/cross-realm containers.\n * The merge mutates `defaults` in place and returns the same object, so direct callers\n * should pass a fresh defaults object unless they intentionally want shared state updated.\n * @throws If options are missing or not an object. {@link Error}\n * @example\n * Applies user overrides to the default cipher options.\n *\n * ```ts\n * checkOpts({ rounds: 20 }, { rounds: 8 });\n * ```\n */\nexport function checkOpts(defaults, opts) {\n aobject(defaults, 'defaults');\n aobject(opts, 'opts');\n // Mutates defaults by design. __proto__ follows Object.assign semantics here and can only\n // affect this local option object; callers already control this low-level options surface.\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/**\n * Compares two byte arrays in kinda constant time once lengths already match.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns `true` when the arrays contain the same bytes. Different lengths still return early.\n * @example\n * Compares an expected authentication tag with the received one.\n *\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Wraps a keyed MAC constructor into a one-shot helper with `.create()`.\n * @param keyLen - Valid probe-key length used to read static metadata once.\n * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes\n * can pass any representative size as long as those values stay fixed.\n * @param macCons - Keyed MAC constructor or factory.\n * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.\n * @returns Callable MAC helper with `.create()`.\n */\nexport function wrapMacConstructor(keyLen, macCons, fromMsg) {\n const mac = macCons;\n const getArgs = (fromMsg || (() => []));\n const macC = (msg, key) => mac(key, ...getArgs(msg))\n .update(msg)\n .digest();\n const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));\n macC.outputLen = tmp.outputLen;\n macC.blockLen = tmp.blockLen;\n macC.create = (key, ...args) => mac(key, ...args);\n return macC;\n}\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * Used internally by the exported cipher constructors.\n * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`\n * arity (`fn.length === 2`), so wrapped output-capable methods must use a normal\n * second parameter, not a default/rest parameter. AAD support is explicit in\n * `params.withAAD`; optional AAD starts after the nonce slot when one is present.\n * @__NO_SIDE_EFFECTS__\n * @param params - Static cipher metadata. See {@link CipherParams}.\n * @param constructor - Cipher constructor.\n * @returns Wrapped constructor with validation.\n */\nexport const wrapCipher = (params, constructor) => {\n function wrappedCipher(key, ...args) {\n // Validate key\n abytes(key, undefined, 'key');\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');\n }\n // Keep tag length available for decrypt-size checks after constructor validation.\n const tagl = params.tagLength;\n const aadStart = params.nonceLength !== undefined ? 1 : 0;\n // No-AAD constructors otherwise silently ignore byte args meant as AAD.\n if (!params.withAAD) {\n for (let i = aadStart; i < args.length; i++)\n if (isBytes(args[i]))\n throw new Error('AAD not supported');\n }\n // Validate the first AAD slot early; rest-arg AAD constructors validate the tail themselves.\n if (params.withAAD && args[aadStart] !== undefined)\n abytes(args[aadStart], undefined, 'AAD');\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength, output) => {\n if (output !== undefined) {\n if (fnLength !== 2)\n throw new Error('cipher output not supported');\n abytes(output, undefined, 'output');\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data, output) {\n if (called)\n throw new Error('cannot encrypt() twice with same key + nonce');\n // Any encrypt attempt consumes the instance, even if validation rejects below.\n called = true;\n abytes(data, undefined, 'data');\n checkOutput(cipher.encrypt.length, output);\n return cipher.encrypt(data, output);\n },\n decrypt(data, output) {\n abytes(data, undefined, 'data');\n if (tagl && data.length < tagl)\n throw new Error('\"ciphertext\" expected length >= tagLength=' + tagl);\n checkOutput(cipher.decrypt.length, output);\n return cipher.decrypt(data, output);\n },\n };\n return wrCipher;\n }\n Object.assign(wrappedCipher, params);\n return wrappedCipher;\n};\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n * @param expectedLength - Required output length.\n * @param out - Optional destination buffer.\n * @param onlyAligned - Whether `out` must be 4-byte aligned.\n * @returns Output buffer ready for writing.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If the provided output buffer has the wrong size. {@link RangeError}\n * @throws If the provided output buffer has the wrong alignment. {@link Error}\n * @example\n * Reuses a caller-provided output buffer when lengths match.\n *\n * ```ts\n * getOutput(16, new Uint8Array(16));\n * ```\n */\nexport function getOutput(expectedLength, out, onlyAligned = true) {\n if (out === undefined)\n return new Uint8Array(expectedLength);\n // Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.\n abytes(out, expectedLength, 'output');\n if (onlyAligned && !isAligned32(out))\n throw new Error('invalid output, must be aligned');\n return out;\n}\n/**\n * Encodes data and AAD lengths into a 16-byte buffer.\n * @param dataLength - Data length. Units are caller-defined: GCM passes bit\n * lengths, ChaCha20-Poly1305 passes byte lengths — the helper writes the raw values.\n * @param aadLength - AAD length, same unit convention as `dataLength`.\n * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305\n * conventions even though the helper parameter order is `(dataLength, aadLength)`.\n * @param isLE - Whether to encode lengths as little-endian.\n * @returns 16-byte length block.\n * @throws On wrong argument types passed to the endian validator. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Builds the length block appended by GCM and Poly1305.\n *\n * ```ts\n * u64Lengths(16, 8, true);\n * ```\n */\nexport function u64Lengths(dataLength, aadLength, isLE) {\n // Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.\n anumber(dataLength);\n anumber(aadLength);\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n view.setBigUint64(0, BigInt(aadLength), isLE);\n view.setBigUint64(8, BigInt(dataLength), isLE);\n return num;\n}\n/**\n * Checks whether a byte array is aligned to a 4-byte offset.\n * @param bytes - Byte array to inspect.\n * @returns `true` when the view is 4-byte aligned.\n * @example\n * Checks whether a buffer can be safely viewed as Uint32Array.\n *\n * ```ts\n * isAligned32(new Uint8Array(4));\n * ```\n */\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n/**\n * Copies bytes into a new Uint8Array.\n * @param bytes - Bytes to copy.\n * @returns Copied byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Copies input into an aligned Uint8Array before block processing.\n *\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Uses CSPRNG for nonce, nonce injected in ciphertext.\n * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and\n * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext\n * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`\n * buffer on encrypt and intentionally does not support caller-provided destination buffers.\n * Too-short decrypt inputs are split into short/empty nonce views and then delegated\n * to the wrapped cipher instead of being rejected here first.\n *\n * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha\n * should be limited to `2**23` (8M) messages to get a collision chance of\n * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to\n * `2**-33`, still negligible but creeping up.\n * @param fn - Cipher constructor that expects a nonce.\n * @param randomBytes_ - Random-byte source used for nonce generation.\n * @returns Cipher constructor that prepends the nonce to ciphertext.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}\n * @example\n * Prepends a fresh random nonce to every ciphertext.\n *\n * ```ts\n * import { gcm } from '@noble/ciphers/aes.js';\n * import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';\n * const wrapped = managedNonce(gcm);\n * const key = randomBytes(16);\n * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));\n * wrapped(key).decrypt(ciphertext);\n * ```\n */\nexport function managedNonce(fn, randomBytes_ = randomBytes) {\n if (typeof fn !== 'function')\n throw new TypeError('\"fn\" expected cipher constructor, got type=' + typeof fn);\n if (typeof randomBytes_ !== 'function')\n throw new TypeError('\"randomBytes_\" expected function, got type=' + typeof randomBytes_);\n const { nonceLength } = fn;\n anumber(nonceLength, 'fn.nonceLength');\n const addNonce = (nonce, ciphertext, plaintext) => {\n const out = concatBytes(nonce, ciphertext);\n // Wrapped ciphers may alias caller plaintext on encrypt(); never zero\n // caller-owned buffers here.\n if (!overlapBytes(plaintext, ciphertext))\n ciphertext.fill(0);\n return out;\n };\n // NOTE: we cannot support DST here, it would be mistake:\n // - we don't know how much dst length cipher requires\n // - nonce may unalign dst and break everything\n // - we create new u8a anyway (concatBytes)\n // - previously we passed all args to cipher, but that was mistake!\n const res = ((key, ...args) => ({\n encrypt(plaintext) {\n abytes(plaintext, undefined, 'data');\n const nonce = randomBytes_(nonceLength);\n const encrypted = fn(key, nonce, ...args).encrypt(plaintext);\n // @ts-ignore\n if (encrypted instanceof Promise)\n return encrypted.then((ct) => addNonce(nonce, ct, plaintext));\n return addNonce(nonce, encrypted, plaintext);\n },\n decrypt(ciphertext) {\n abytes(ciphertext, undefined, 'data');\n const nonce = ciphertext.subarray(0, nonceLength);\n const decrypted = ciphertext.subarray(nonceLength);\n return fn(key, nonce, ...args).decrypt(decrypted);\n },\n }));\n // Auto-nonce wrappers still preserve the wrapped payload geometry.\n if ('blockSize' in fn)\n res.blockSize = fn.blockSize;\n if ('tagLength' in fn)\n res.tagLength = fn.tagLength;\n if ('withAAD' in fn)\n res.withAAD = fn.withAAD;\n return res;\n}\n","/**\n * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\n\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | cnt(1) | nonce(3)\n chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).\nCounter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.\nCurrent noble policy is strict non-wrap for the shared 32-bit counter path:\nexported ARX ciphers reject initial `0xffffffff` and stop before any implicit\nwrap back to zero.\nSee {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.\n\n * @module\n */\nimport { abool, abytes, anumber, checkOpts, clean, complexOverlapBytes, copyBytes, getOutput, isAligned32, isLE, randomBytes, swap32IfBE, u32, } from \"./utils.js\";\n// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.\n// Non-ASCII input would not match UTF-8 `TextEncoder` output.\nconst encodeStr = (str) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));\n// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.\n// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.\n// RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is\n// kept for legacy allowShortKeys Salsa/ChaCha variants.\nconst sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();\n// RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as\n// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.\nconst sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();\n/**\n * Rotates a 32-bit word left.\n * @param a - Input word.\n * @param b - Rotation count in bits.\n * @returns Rotated 32-bit word.\n * @example\n * Moves the top byte of `0x12345678` into the low byte position.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(a, b) {\n return (a << b) | (a >>> (32 - b));\n}\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\n// RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words.\nconst BLOCK_LEN32 = 16;\n// Counter policy for the shared public `counter` argument:\n// - RFC/IETF ChaCha20 uses a 32-bit counter.\n// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit\n// counter state and carry into the next word.\n// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium\n// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max\n// boundary instead of carrying.\n// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from\n// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.\n// Noble intentionally throws instead of silently picking one wrap model for users. In the default\n// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically\n// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement\n// whatever wider carry / wrap policy they need on top.\nconst MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();\nconst U32_EMPTY = /* @__PURE__ */ Uint32Array.of();\nfunction runCipher(core, sigma, key, nonce, data, output, counter, rounds) {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isLE && isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n // RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and\n // truncating the final partial block instead of materializing the whole keystream.\n if (!isLE) {\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n // RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order.\n swap32IfBE(b32);\n if (counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n return;\n }\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n // See MAX_COUNTER policy note above: never silently wrap the shared public counter.\n if (counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0)\n throw new Error('arx: invalid block position');\n for (let j = 0, posj; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n/**\n * Creates an ARX stream cipher from a 32-bit core permutation.\n * Used internally to build the exported Salsa and ChaCha stream ciphers.\n * @param core - Core function that fills one keystream block.\n * @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.\n * @returns Stream cipher function over byte arrays.\n * @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}\n */\nexport function createCipher(core, opts) {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);\n if (typeof core !== 'function')\n throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (key, nonce, data, output, counter = 0) => {\n abytes(key, undefined, 'key');\n abytes(nonce, undefined, 'nonce');\n abytes(data, undefined, 'data');\n const len = data.length;\n // Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs\n // must match the logical result length exactly instead of returning an oversized workspace.\n const hasOutput = output !== undefined;\n output = getOutput(len, output, false);\n if (hasOutput)\n complexOverlapBytes(data, output);\n anumber(counter);\n // See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.\n if (counter < 0 || counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n const toClean = [];\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length;\n let k;\n let sigma;\n if (l === 32) {\n // Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and\n // final clean(...) all mutate or wipe the temporary buffer in place.\n toClean.push((k = copyBytes(key)));\n sigma = sigma32_32;\n }\n else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n }\n else {\n abytes(key, 32, 'arx key');\n throw new Error('invalid key size');\n // throw new Error(`\"arx key\" expected Uint8Array of length 32, got length=${l}`);\n }\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Copy before taking u32(...) views on misaligned inputs, and on big-endian so later\n // swap32IfBE(...) never mutates caller nonce bytes in place.\n if (!isLE || !isAligned32(nonce))\n toClean.push((nonce = copyBytes(nonce)));\n let k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24)\n throw new Error('arx: extended nonce must be 24 bytes');\n const n16 = nonce.subarray(0, 16);\n if (isLE)\n extendNonceFn(sigma, k32, u32(n16), k32);\n else {\n const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));\n extendNonceFn(sigmaRaw, k32, u32(n16), k32);\n clean(sigmaRaw);\n swap32IfBE(k32);\n }\n nonce = nonce.subarray(16);\n }\n else if (!isLE)\n swap32IfBE(k32);\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n // Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero\n // counter bytes, while Salsa/XSalsa append them after the nonce words.\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = swap32IfBE(u32(nonce));\n // Ensure temporary key/nonce copies are wiped even if the remaining\n // runtime guard in runCipher(...) throws on counter overflow.\n try {\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n return output;\n }\n finally {\n clean(...toClean);\n }\n };\n}\n/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */\nexport class _XorStreamPRG {\n blockLen;\n keyLen;\n nonceLen;\n state;\n buf;\n key;\n nonce;\n pos;\n ctr;\n cipher;\n destroyed = false;\n constructor(cipher, blockLen, keyLen, nonceLen, seed) {\n this.cipher = cipher;\n this.blockLen = blockLen;\n this.keyLen = keyLen;\n this.nonceLen = nonceLen;\n this.state = new Uint8Array(this.keyLen + this.nonceLen);\n this.reseed(seed);\n this.ctr = 0;\n this.pos = this.blockLen;\n this.buf = new Uint8Array(this.blockLen);\n // Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher\n // inputs in place through these subarray views.\n this.key = this.state.subarray(0, this.keyLen);\n this.nonce = this.state.subarray(this.keyLen);\n }\n reseed(seed) {\n abytes(seed, undefined, 'seed');\n if (!seed || seed.length === 0)\n throw new Error('entropy required');\n // Mix variable-length entropy cyclically across the whole key||nonce state, then restart the\n // keystream so buffered leftovers from the previous state are never reused.\n for (let i = 0; i < seed.length; i++)\n this.state[i % this.state.length] ^= seed[i];\n this.ctr = 0;\n this.pos = this.blockLen;\n }\n addEntropy(seed) {\n if (this.destroyed)\n throw new Error('cannot use destroyed PRG');\n // Reject empty entropy before re-keying, otherwise a throwing call would still advance state.\n abytes(seed, undefined, 'seed');\n if (seed.length === 0)\n throw new Error('entropy required');\n // Re-key from the current stream first, then mix external entropy into the fresh key||nonce\n // state through reseed() so stale buffered bytes are discarded.\n this.state.set(this.randomBytes(this.state.length));\n this.reseed(seed);\n }\n randomBytes(len) {\n if (this.destroyed)\n throw new Error('cannot use destroyed PRG');\n anumber(len);\n if (len === 0)\n return new Uint8Array(0);\n const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;\n const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);\n // Preflight overflow so failed reads don't partially consume keystream\n // and leave the PRG repeating blocks.\n if (blocks > 0 && this.ctr > MAX_COUNTER - blocks)\n throw new Error('arx: counter overflow');\n const out = new Uint8Array(len);\n let outPos = 0;\n // `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream\n // ciphers then emit raw keystream bytes directly into those buffers.\n // Serve buffered leftovers first so split reads stay identical to one larger read.\n if (this.pos < this.blockLen) {\n const take = Math.min(len, this.blockLen - this.pos);\n out.set(this.buf.subarray(this.pos, this.pos + take), 0);\n this.pos += take;\n outPos += take;\n if (outPos === len)\n return out; // fast path\n }\n // Full blocks directly to out\n const full = Math.floor((len - outPos) / this.blockLen);\n if (full > 0) {\n const blockBytes = full * this.blockLen;\n const b = out.subarray(outPos, outPos + blockBytes);\n this.cipher(this.key, this.nonce, b, b, this.ctr);\n this.ctr += full;\n outPos += blockBytes;\n }\n // Save leftovers\n const left = len - outPos;\n if (left > 0) {\n this.buf.fill(0);\n // NOTE: cipher will handle overflow\n this.cipher(this.key, this.nonce, this.buf, this.buf, this.ctr++);\n out.set(this.buf.subarray(0, left), outPos);\n this.pos = left;\n }\n return out;\n }\n // Clone seeds the new instance from this stream, so the source PRG advances too.\n clone() {\n if (this.destroyed)\n throw new Error('cannot use destroyed PRG');\n return new _XorStreamPRG(this.cipher, this.blockLen, this.keyLen, this.nonceLen, this.randomBytes(this.state.length));\n }\n // Zeroes the current state, leftover buffer, and marks the instance destroyed.\n // The instance fails closed: any later randomBytes()/addEntropy()/clone() throws instead\n // of silently continuing from zero key||nonce state (which would yield predictable output).\n clean() {\n this.pos = 0;\n this.ctr = 0;\n this.buf.fill(0);\n this.state.fill(0);\n this.destroyed = true;\n }\n}\n/**\n * Creates a PRG constructor from a stream cipher.\n * @param cipher - Stream cipher used to fill output blocks.\n * @param blockLen - Keystream block length in bytes.\n * @param keyLen - Internal key length in bytes.\n * @param nonceLen - Internal nonce length in bytes.\n * @returns PRG factory for seeded concrete `_XorStreamPRG` instances.\n * @example\n * Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.\n * ```ts\n * import { xchacha20 } from '@noble/ciphers/chacha.js';\n * import { createPRG } from '@noble/ciphers/_arx.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const init = createPRG(xchacha20, 64, 32, 24);\n * const prg = init(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const createPRG = (cipher, blockLen, keyLen, nonceLen) => {\n return ((seed = randomBytes(32)) => new _XorStreamPRG(cipher, blockLen, keyLen, nonceLen, seed));\n};\n","/**\n * Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},\n * {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})\n * is a fast and parallel secret-key message-authentication code suitable for\n * a wide variety of applications. It was standardized in\n * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.\n *\n * Polynomial MACs are not perfect for every situation:\n * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.\n * See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.\n * To combat invisible salamanders, `hash(key)` can be included in ciphertext,\n * however, this would violate ciphertext indistinguishability:\n * an attacker would know which key was used - so `HKDF(key, i)`\n * could be used instead.\n *\n * Check out the {@link https://cr.yp.to/mac.html | original website}.\n * Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.\n * @module\n */\n// prettier-ignore\nimport { abytes, aexists, aoutput, clean, copyBytes, wrapMacConstructor } from \"./utils.js\";\n// A simple-loop reference version (`poly1305_small`) lives in\n// `test/misc/micro-ciphers.ts`, provided for auditability.\n// Little-endian 2-byte load used by the Poly1305 limb decomposition.\nfunction u8to16(a, i) {\n return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\n}\n/**\n * Incremental Poly1305 MAC state.\n * Prefer `poly1305()` for one-shot use.\n * @param key - 32-byte Poly1305 one-time key.\n * @example\n * Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.\n *\n * ```ts\n * import { Poly1305 } from '@noble/ciphers/_poly1305.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const mac = new Poly1305(key);\n * mac.update(new Uint8Array([1, 2, 3]));\n * mac.digest();\n * ```\n */\nexport class Poly1305 {\n blockLen = 16;\n outputLen = 16;\n buffer = new Uint8Array(16);\n r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3\n h = new Uint16Array(10);\n pad = new Uint16Array(8);\n pos = 0;\n finished = false;\n destroyed = false;\n // Can be speed-up using BigUint64Array, at the cost of complexity\n constructor(key) {\n key = copyBytes(abytes(key, 32, 'key'));\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n // RFC 8439 §2.5.1 / RFC 7539 §2.5.1 clamp r before multiplication.\n // These masks unpack that clamped value into 13-bit limbs, while pad\n // keeps the raw s half for finalize().\n // {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++)\n this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n process(data, offset, isLast = false) {\n // RFC 8439 §2.5 / §2.5.1 and RFC 7539 §2.5 / §2.5.1 add an extra high\n // bit to every full 16-byte block. The final partial block gets its\n // explicit `1` byte during digestInto(), so `hibit` stays zero there.\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n let c = 0;\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n // RFC 8439 §2.5 / RFC 7539 §2.5 reduce modulo 2^130-5 before repacking\n // to 16-bit words and adding the raw s half.\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++)\n g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++)\n h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n clean(g);\n }\n update(data) {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const { buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.\n this.destroyed = true;\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n // RFC 8439 §2.5 / RFC 7539 §2.5: the final short block appends a\n // single `0x01` byte and zero-fills the remaining bytes before the\n // last multiplication step.\n buffer[pos++] = 1;\n for (; pos < 16; pos++)\n buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy out before destroy() zeroes the internal buffer.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\n/**\n * Poly1305 MAC from RFC 8439.\n * @param msg - Message bytes to authenticate.\n * @param key - 32-byte Poly1305 one-time key.\n * @returns 16-byte authentication tag.\n * @example\n * Authenticates one message with a one-shot Poly1305 call and a fresh key.\n *\n * ```ts\n * import { poly1305 } from '@noble/ciphers/_poly1305.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * poly1305(new Uint8Array(), key);\n * ```\n */\nexport const poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));\n","/**\n * ChaCha stream cipher, released\n * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.\n * It was standardized in\n * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and\n * is now used in TLS 1.3.\n *\n * {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}\n * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with\n * randomly-generated nonces.\n *\n * Check out\n * {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},\n * {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and\n * {@link https://cr.yp.to/chacha.html | website}.\n *\n * @module\n */\nimport { createCipher, createPRG, rotl } from \"./_arx.js\";\nimport { poly1305 } from \"./_poly1305.js\";\nimport { abytes, clean, equalBytes, getOutput, isLE, swap32IfBE, u64Lengths, wrapCipher, } from \"./utils.js\";\n/**\n * ChaCha core function. Uses an unrolled loop (chachaCore, hchacha) - 4x\n * faster than a simple loop, but larger & harder to read. A simple-loop\n * reference version lives in `test/misc/micro-ciphers.ts`;\n * `test/arx.test.ts` keeps the two aligned.\n * The specific implementation is selected in `createCipher` below.\n */\n/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */\n// prettier-ignore\nfunction chachaCore(s, k, n, out, cnt, rounds = 20) {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n // RFC 8439 §2.3 / §2.3.1: add the original state words back in state order.\n let oi = 0;\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha hashes key and nonce into key' and nonce' for xchacha20.\n * Algorithmically identical to `hchacha_small` from `test/misc/micro-ciphers.ts`,\n * but this exported path normalizes word order on big-endian hosts.\n * Reuses `chachaCore` and subtracts its feed-forward, keeping the hot per-block\n * path untouched.\n * @param s - Sigma constants as 32-bit words.\n * @param k - Key words.\n * @param i - Nonce-prefix words.\n * @param out - Output buffer for the derived subkey.\n * @example\n * Derives the XChaCha subkey from sigma, key, and nonce-prefix words.\n *\n * ```ts\n * const sigma = new Uint32Array(4);\n * const key = new Uint32Array(8);\n * const nonce = new Uint32Array(4);\n * const out = new Uint32Array(8);\n * hchacha(sigma, key, nonce, out);\n * ```\n */\n// prettier-ignore\nexport function hchacha(s, k, i, out) {\n // Runs the shared chachaCore permutation, then subtracts the RFC 8439 feed-forward\n // it applies, recovering the raw permutation words hchacha needs.\n // LE hosts read the caller arrays in place (no copies); BE hosts get\n // byte-swapped scratch copies, wiped before returning.\n const s2 = isLE ? s : swap32IfBE(s.slice(0, 4));\n const k2 = isLE ? k : swap32IfBE(k.slice(0, 8));\n const i2 = isLE ? i : swap32IfBE(i.slice(0, 4));\n const t = new Uint32Array(16);\n chachaCore(s2, k2, i2.subarray(1), t, i2[0]);\n let oi = 0;\n out[oi++] = (t[0] - s2[0]) | 0;\n out[oi++] = (t[1] - s2[1]) | 0;\n out[oi++] = (t[2] - s2[2]) | 0;\n out[oi++] = (t[3] - s2[3]) | 0;\n out[oi++] = (t[12] - i2[0]) | 0;\n out[oi++] = (t[13] - i2[1]) | 0;\n out[oi++] = (t[14] - i2[2]) | 0;\n out[oi++] = (t[15] - i2[3]) | 0;\n swap32IfBE(out);\n if (!isLE)\n clean(s2, k2, i2);\n clean(t);\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public\n * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`\n * near `MAX_COUNTER` for the full counter-policy rationale.\n * @param key - 16-byte or 32-byte key.\n * @param nonce - 8-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.\n *\n * ```ts\n * import { chacha20orig } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(8);\n * chacha20orig(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.\n *\n * ```ts\n * import { chacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha20(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n/**\n * XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).\n * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.\n * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public\n * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`\n * near `MAX_COUNTER` for the full counter-policy rationale.\n * @param key - 32-byte key.\n * @param nonce - 24-byte extended nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.\n *\n * ```ts\n * import { xchacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(24);\n * xchacha20(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n/**\n * Reduced 8-round chacha, described in original paper.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.\n *\n * ```ts\n * import { chacha8 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha8(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n/**\n * Reduced 12-round chacha, described in original paper.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.\n *\n * ```ts\n * import { chacha12 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha12(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\n// Test-only hook: exposes the unrolled production core so tests can compare it\n// with the simple/reference core from `test/misc/micro-ciphers.ts`.\nexport const __TESTS = /* @__PURE__ */ Object.freeze({ chachaCore });\n// RFC 8439 §2.8.1 pad16(x): shared zero block for AAD/ciphertext padding.\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// RFC 8439 §2.8 / §2.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.\nconst updatePadded = (h, msg) => {\n h.update(msg);\n const leftover = msg.length % 16;\n if (leftover)\n h.update(ZEROS16.subarray(leftover));\n};\n// RFC 8439 §2.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key\n// generation only needs 32 zero bytes.\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(fn, key, nonce, ciphertext, AAD) {\n if (AAD !== undefined)\n abytes(AAD, undefined, 'AAD');\n // RFC 8439 §2.6 / §2.8: derive the Poly1305 one-time key from counter 0,\n // then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).\n const authKey = fn(key, nonce, ZEROS32);\n const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);\n // Methods below can be replaced with\n // `return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)`\n // from `test/misc/micro-ciphers.ts`.\n const h = poly1305.create(authKey);\n if (AAD)\n updatePadded(h, AAD);\n updatePadded(h, ciphertext);\n h.update(lengths);\n const res = h.digest();\n clean(authKey, lengths);\n return res;\n}\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them, but it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {\n // This borrows caller key/nonce/AAD buffers by reference; mutating them after construction\n // changes future encrypt/decrypt results.\n const tagLength = 16;\n return {\n encrypt(plaintext, output) {\n const plength = plaintext.length;\n output = getOutput(plength + tagLength, output, false);\n output.set(plaintext);\n const oPlain = output.subarray(0, -tagLength);\n // RFC 8439 §2.8: payload encryption starts at counter 1 because counter 0 produced the OTK.\n xorStream(key, nonce, oPlain, oPlain, 1);\n const tag = computeTag(xorStream, key, nonce, oPlain, AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output;\n },\n decrypt(ciphertext, output) {\n output = getOutput(ciphertext.length - tagLength, output, false);\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n // RFC 8439 §2.8 / §4: authenticate ciphertext before decrypting it, and compare tags with\n // the constant-time equalBytes() helper rather than decrypting speculative plaintext first.\n if (!equalBytes(passedTag, tag)) {\n clean(tag);\n throw new Error('invalid tag');\n }\n output.set(ciphertext.subarray(0, -tagLength));\n // Actual decryption\n xorStream(key, nonce, output, output, 1); // start stream with i=1\n clean(tag);\n return output;\n },\n };\n};\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n *\n * Unsafe to use random nonces under the same key, due to collision chance.\n * Prefer XChaCha instead.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and nonce.\n *\n * ```ts\n * import { chacha20poly1305 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * const aad = new TextEncoder().encode('session metadata');\n * const cipher = chacha20poly1305(key, nonce, aad);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16, withAAD: true }, \n/* @__PURE__ */ _poly1305_aead(chacha20));\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n *\n * Can be safely used with random nonces (CSPRNG).\n * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.\n * @param key - 32-byte key.\n * @param nonce - 24-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.\n *\n * ```ts\n * import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(24);\n * const aad = new TextEncoder().encode('session metadata');\n * const cipher = xchacha20poly1305(key, nonce, aad);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16, withAAD: true }, \n/* @__PURE__ */ _poly1305_aead(xchacha20));\n/**\n * Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.\n * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,\n * only 32 random bytes are mixed into the 40-byte state.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n * @example\n * Seeds the test-only ChaCha20 DRBG from fresh entropy.\n *\n * ```ts\n * import { rngChacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngChacha20(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngChacha20 = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);\n/**\n * Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * Faster than `rngChacha20`.\n * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,\n * only 32 random bytes are mixed into the 44-byte state.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n * @example\n * Seeds the faster test-only ChaCha8 DRBG from fresh entropy.\n *\n * ```ts\n * import { rngChacha8 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngChacha8(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngChacha8 = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);\n","const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n const h = fromNumH(n);\n const l = fromNumL(n);\n view.setUint32(byteOffset, isLE ? l : h, isLE);\n view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n aobject(value, label);\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null)\n throw new TypeError(`\"${label}\" expected plain object`);\n // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n // prototype setter. Reject it before merging so inherited option values cannot be injected.\n if (Object.hasOwn(value, '__proto__'))\n throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n const host = globalThis;\n if (typeof host.scheduler?.yield === 'function') {\n const promise = host.scheduler.yield();\n // Keep the original scheduler rejection; this handler exists only for cleanup.\n if (onReject)\n promise.catch(onReject);\n return promise;\n }\n return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick(onReject);\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts = Date.now();\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n const encoded = new TextEncoder().encode(str);\n try {\n // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n // buffer can then wipe it independently of TextEncoder's temporary result.\n return new Uint8Array(encoded); // https://bugzil.la/1681809\n }\n finally {\n clean(encoded);\n }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n aopts(defaults, 'defaults');\n if (opts !== undefined)\n aopts(opts, title);\n // Callers read optional fields directly, so omitted values must not fall through to ambient\n // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n const merged = Object.assign(Object.create(null), defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, pos);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n buffer.fill(0);\n }\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneIntoMeta(to) {\n const { buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nclass SHA2_32B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nclass SHA2_64B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, anumber as anumber_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, randomBytes as randomBytes_, } from '@noble/hashes/utils.js';\n/**\n * Validates that a value is an array, optionally validating each element.\n * @param item - Value to validate.\n * @param title - Label included in thrown errors.\n * @param inner - Optional per-element validator, called with the element and its label.\n * @returns The validated array.\n * @example\n * Validate an array of points before batch processing.\n *\n * ```ts\n * aarray([1n, 2n], 'scalars');\n * ```\n */\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\n/**\n * Validates that a value is a byte array.\n * @param value - Value to validate.\n * @param length - Optional exact byte length.\n * @param title - Optional field name.\n * @returns Original byte array.\n * @example\n * Reject non-byte input before passing data into curve code.\n *\n * ```ts\n * abytes(new Uint8Array(1));\n * ```\n */\nexport const abytes = (value, length, title) => abytes_(value, length, title);\n/**\n * Validates that a value is a non-negative safe integer.\n * @param n - Value to validate.\n * @param title - Optional field name.\n * @returns The validated number.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber = anumber_;\n/**\n * Asserts something is a string.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a label string.\n *\n * ```ts\n * astring('example', 'label');\n * ```\n */\nexport function astring(value, title = '') {\n if (typeof value !== 'string') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected string, got type=' + typeof value);\n }\n return value;\n}\n/**\n * Asserts something is a plain object-ish value, not null or array.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated object.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate an options object before checking fields.\n *\n * ```ts\n * aobject({ flag: true });\n * ```\n */\nexport function aobject(value, title = 'object') {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(title === 'object'\n ? 'expected valid options object'\n : `\"${title}\" expected object, got type=${typeof value}`);\n return value;\n}\n/**\n * Asserts something is a function.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated function.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a required method before calling it.\n *\n * ```ts\n * afunction(() => true, 'predicate');\n * ```\n */\nexport function afunction(value, title) {\n if (typeof value !== 'function')\n throw new TypeError(`\"${title}\" is invalid: expected function, got ${typeof value}`);\n return value;\n}\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex = bytesToHex_;\n/**\n * Concatenates byte arrays.\n * @param arrays - Byte arrays to join.\n * @returns Concatenated bytes.\n * @example\n * Join domain-separated chunks into one buffer.\n *\n * ```ts\n * concatBytes(Uint8Array.of(1), Uint8Array.of(2));\n * ```\n */\nexport const concatBytes = (...arrays) => concatBytes_(...arrays);\n/**\n * Decodes lowercase or uppercase hex into bytes.\n * @param hex - Hex string to decode.\n * @returns Decoded bytes.\n * @example\n * Parse fixture hex into bytes before hashing.\n *\n * ```ts\n * hexToBytes('0102');\n * ```\n */\nexport const hexToBytes = (hex) => hexToBytes_(hex);\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - Value to inspect.\n * @returns `true` when `a` is a Uint8Array.\n * @example\n * Branch on byte input before decoding it.\n *\n * ```ts\n * isBytes(new Uint8Array(1));\n * ```\n */\nexport const isBytes = isBytes_;\n/**\n * Reads random bytes from the platform CSPRNG.\n * @param bytesLength - Number of random bytes to read.\n * @returns Fresh random bytes.\n * @example\n * Generate a random seed for a keypair.\n *\n * ```ts\n * randomBytes(2);\n * ```\n */\nexport const randomBytes = (bytesLength) => randomBytes_(bytesLength);\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Validates that a flag is boolean.\n * @param value - Value to validate.\n * @param title - Optional field name.\n * @returns Original value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Reject non-boolean option flags early.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate one integer-like value before serializing it.\n *\n * ```ts\n * abignumber(1n);\n * ```\n */\nexport function abignumber(n) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n))\n throw new RangeError('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\n/**\n * Validates that a value is a safe integer.\n * @param value - Integer to validate.\n * @param title - Optional field name.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a window size before scalar arithmetic uses it.\n *\n * ```ts\n * asafenumber(1);\n * ```\n */\nexport function asafenumber(value, title = '') {\n if (typeof value !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected number, got type=' + typeof value);\n }\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(prefix + 'expected safe integer, got ' + value);\n }\n}\n/**\n * Encodes a bigint into even-length big-endian hex.\n * The historical \"unpadded\" name only means \"no fixed-width field padding\"; odd-length hex still\n * gets one leading zero nibble so the result always represents whole bytes.\n * @param num - Number to encode.\n * @returns Big-endian hex string.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Encode a scalar into hex without a `0x` prefix.\n *\n * ```ts\n * numberToHexUnpadded(255n);\n * ```\n */\nexport function numberToHexUnpadded(num) {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n/**\n * Parses a big-endian hex string into bigint.\n * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the\n * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.\n * @param hex - Hex string without `0x`.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parse a scalar from fixture hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\n/**\n * Parses big-endian bytes into bigint.\n * @param bytes - Bytes in big-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in network byte order.\n *\n * ```ts\n * bytesToNumberBE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex_(bytes));\n}\n/**\n * Parses little-endian bytes into bigint.\n * @param bytes - Bytes in little-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in little-endian form.\n *\n * ```ts\n * bytesToNumberLE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberLE(bytes) {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n/**\n * Encodes a bigint into fixed-length big-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n, len) {\n anumber_(len);\n if (len === 0)\n throw new Error('zero output length is invalid');\n n = abignumber(n);\n const expectedLen = len * 2;\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > expectedLen)\n throw new RangeError('number is too large');\n return hexToBytes_(hex.padStart(expectedLen, '0'));\n}\n/**\n * Encodes a bigint into fixed-length little-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Little-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\n/**\n * Encodes a bigint into variable-length big-endian bytes.\n * @param n - Number to encode.\n * @returns Variable-length big-endian bytes.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a bigint without fixed-width padding.\n *\n * ```ts\n * numberToVarBytesBE(255n);\n * ```\n */\nexport function numberToVarBytesBE(n) {\n return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n// Compares 2 u8a-s in kinda constant time\n/**\n * Compares two byte arrays in constant-ish time.\n * @param a - Left byte array.\n * @param b - Right byte array.\n * @returns `true` when bytes match.\n * @example\n * Compare two encoded points without early exit.\n *\n * ```ts\n * equalBytes(Uint8Array.of(1), Uint8Array.of(1));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n * @param bytes - Bytes to copy.\n * @returns Detached copy.\n * @example\n * Make an isolated copy before mutating serialized bytes.\n *\n * ```ts\n * copyBytes(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n * @param ascii - ASCII input text.\n * @returns Encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode an ASCII domain-separation tag.\n *\n * ```ts\n * asciiToBytes('ABC');\n * ```\n */\nexport function asciiToBytes(ascii) {\n if (typeof ascii !== 'string')\n throw new TypeError('ascii string expected, got ' + typeof ascii);\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new RangeError(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n/**\n * Checks whether n is non-negative bigint. Historical name.\n * @param n - candidate value\n * @returns `true` when the value is bigint and 0 or larger\n * @example\n * Check a candidate scalar before range validation.\n *\n * ```ts\n * isPosBig(2n);\n * ```\n */\nexport function isPosBig(n) {\n return typeof n === 'bigint' && _0n <= n;\n}\n/**\n * Checks whether a bigint lies inside a half-open range.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * @returns `true` when the value is inside the range.\n * @example\n * Check whether a candidate scalar fits the field order.\n *\n * ```ts\n * inRange(2n, 1n, 3n);\n * ```\n */\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts `min <= n < max`. NOTE: upper bound is exclusive.\n * @param title - Value label for error messages.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * Wrong-type inputs are not separated from out-of-range values here: they still flow through the\n * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Assert that a bigint stays within one half-open range.\n *\n * ```ts\n * aInRange('x', 2n, 1n, 256n);\n * ```\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n * @param n - Value to inspect.\n * @returns Bit length.\n * @throws If the value is negative. {@link Error}\n * @example\n * Measure the bit length of a scalar before serialization.\n *\n * ```ts\n * bitLen(8n);\n * ```\n */\nexport function bitLen(n) {\n // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a\n // contract bug and must not silently collapse to zero bits.\n if (n < _0n)\n throw new Error('expected non-negative bigint, got ' + n);\n // Native radix conversion beats a shift loop at every size, and the loop is quadratic in bits.\n return n === _0n ? 0 : n.toString(2).length;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw\n * bigint shift semantics; because the mask is built as `1n << pos`,\n * they currently collapse to `0n` and make the helper a no-op.\n * @returns Bit as bigint.\n * @example\n * Gets single bit at position.\n *\n * ```ts\n * bitGet(5n, 0);\n * ```\n */\nexport function bitGet(n, pos) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,\n * so they currently behave like left shifts.\n * @param value - Whether the bit should be set.\n * @returns Updated bigint.\n * @example\n * Sets single bit at position.\n *\n * ```ts\n * bitSet(0n, 1, true);\n * ```\n */\nexport function bitSet(n, pos, value) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n abool(value, 'value');\n const mask = _1n << BigInt(pos);\n // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.\n return value ? n | mask : n & ~mask;\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift\n * semantics and therefore produce `-1n`.\n * @returns Bitmask value.\n * @example\n * Calculate mask for N bits.\n *\n * ```ts\n * bitMask(4);\n * ```\n */\nexport const bitMask = (n) => {\n asafenumber(n, 'n');\n return (_1n << BigInt(n)) - _1n;\n};\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n * is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n * other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hmacFn = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);\n * const drbg = createHmacDrbg(32, 32, hmacFn);\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function')\n throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len) => new Uint8Array(len);\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n // Step B, Step C: set hashLen to 8*ceil(hlen/8).\n // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.\n let v = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k = u8n(hashLen);\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n // hmac(k)(v, ...values)\n const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));\n const reseed = (seed = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters)\n throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = pred(gen())) === undefined)\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * Extra keys are intentionally ignored because many callers validate only the subset they use from\n * richer option bags or runtime objects.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `aobject()`, `afunction()`, `abool()`, or `asafenumber()` instead.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @param title - Object label included in thrown errors.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(object, fields = {}, optFields = {}, title = 'object') {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n/**\n * Throws not implemented error.\n * @returns Never returns.\n * @throws If the unfinished code path is reached. {@link Error}\n * @example\n * Surface the placeholder error from an unfinished code path.\n *\n * ```ts\n * try {\n * notImplemented();\n * } catch {}\n * ```\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, abytes, afunction, anumber, aobject, asafenumber, bitLen, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, } from \"../utils.js\";\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _15n = /* @__PURE__ */ BigInt(15), _16n = /* @__PURE__ */ BigInt(16);\n// 2^64: exponents below this use plain square-and-multiply in pow()/FpPow(); the windowed path's\n// table build (14 multiplications) only pays off for longer exponents (break-even ~50 bits).\nconst POW_WINDOWED_MIN = /* @__PURE__ */ BigInt('0x10000000000000000');\n/**\n * @param a - Dividend value.\n * @param b - Positive modulus.\n * @returns Reduced value in `[0, b)` only when `b` is positive.\n * @throws If the modulus is not positive. {@link Error}\n * @example\n * Normalize a bigint into one field residue.\n *\n * ```ts\n * mod(-1n, 5n);\n * ```\n */\nexport function mod(a, b) {\n if (b <= _0n)\n throw new Error('mod: expected positive modulus, got ' + b);\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to a power with modular reduction.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen\n * modulus instead of relying on the `power===0/1` fast paths to normalize it.\n * @param num - Base value.\n * @param power - Exponent value.\n * @param modulo - Reduction modulus.\n * @returns Modular exponentiation result.\n * @throws If the modulus or exponent is invalid. {@link Error}\n * @example\n * Raise one bigint to a modular power.\n *\n * ```ts\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n * ```\n */\nexport function pow(num, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow: expected modulus > 1, got ' + modulo);\n // Non-bigint exponents coerce every comparison below to false and would silently return 1.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return _1n;\n if (power === _1n)\n return num;\n let d = num % modulo;\n if (d < _0n)\n d += modulo;\n // Control flow in both branches below depends only on the exponent, never on `num` — invertCt()\n // relies on that for its (public-exponent) secret-independence guarantee.\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents.\n let p = _1n;\n while (power > _0n) {\n if (power & _1n)\n p = (p * d) % modulo;\n d = (d * d) % modulo;\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first: a 14-multiplication table drops per-window cost to <1\n // multiplication (vs ~2 per window for square-and-multiply), ~25-30% faster for the dense\n // 256-bit exponents of sqrt / Legendre / invertCt.\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = _1n;\n table[1] = d;\n for (let i = 2; i < 16; i++)\n table[i] = (table[i - 1] * d) % modulo;\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n const digit = digits[w];\n if (digit !== 0)\n p = (p * table[digit]) % modulo;\n }\n return p;\n}\n/**\n * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.\n * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen\n * modulus; the `power===0` fast path intentionally returns the input unchanged.\n * @param x - Base value.\n * @param power - Number of squarings.\n * @param modulo - Reduction modulus.\n * @returns Repeated-squaring result.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Apply repeated squaring inside one field.\n *\n * ```ts\n * pow2(3n, 2n, 11n);\n * ```\n */\nexport function pow2(x, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow2: expected modulus > 1, got ' + modulo);\n if (power < _0n)\n throw new Error('pow2: expected non-negative exponent, got ' + power);\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.\n * @param number - Value to invert.\n * @param modulo - Modulus greater than 1.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n // modulo = 1 is the zero ring: gcd(x, 1) = 1 makes the loop below \"succeed\" and return the\n // useless inverse 0. Reject it like pow() and invertCt() do.\n if (modulo <= _1n)\n throw new Error('invert: expected modulus > 1, got ' + modulo);\n // This is variable-time: the loop count depends on `number`. For a secret-independent\n // (Fermat) alternative over a prime modulus, see {@link invertCt} (~4x slower).\n let a = mod(number, modulo);\n let b = modulo;\n // Only the Bézout coefficient of `number` (x/u chain) is tracked; the coefficient of `modulo`\n // never affects the output, so it is not computed.\n // prettier-ignore\n let x = _0n, u = _1n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n // prettier-ignore\n b = a, a = r, x = u, u = m;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Inverses number over modulo using Fermat's little theorem: `a^(p-2) ≡ a⁻¹ (mod p)`.\n *\n * Unlike {@link invert} (extended Euclidean), the exponent `p-2` is a public constant, so the\n * underlying square-and-multiply has the same control flow for every secret `a`: there is no\n * data-dependent branching or loop count that could leak `a` through timing (e.g. Minerva-style\n * ECDSA nonce-inversion attacks). This is only \"algorithmically\" constant-time — JS bigint\n * multiplication/reduction is still value-dependent — and it is roughly 4x slower than\n * {@link invert}.\n *\n * REQUIRES a prime modulus; Fermat's theorem does not hold otherwise. The result is verified to be\n * a real inverse, so a non-prime modulus (or a non-invertible input) fails closed with an error\n * instead of returning a wrong value.\n * @param a - Value to invert.\n * @param prime - Prime modulus.\n * @returns Multiplicative inverse in `[1, prime)`.\n * @throws If the modulus is below 2, the input reduces to zero, or the inverse does not exist.\n * {@link Error}\n * @example\n * Compute one modular inverse without secret-dependent branching.\n *\n * ```ts\n * invertCt(3n, 11n); // 4n, since 3 * 4 = 12 ≡ 1 (mod 11)\n * ```\n */\nexport function invertCt(a, prime) {\n if (prime <= _1n)\n throw new Error('invertCt: expected prime modulus > 1, got ' + prime);\n const an = mod(a, prime);\n if (an === _0n)\n throw new Error('invertCt: expected non-zero number');\n // Exponent (prime - 2) is public, so FpPow's square-and-multiply is secret-independent.\n const inverse = pow(an, prime - _2n, prime);\n // O(1) safety net: verifies the inverse and rejects composite moduli where a^(p-2) is not one.\n if (mod(an * inverse, prime) !== _1n)\n throw new Error('invertCt: does not exist');\n return inverse;\n}\nfunction assertIsSquare(Fp, root, n) {\n const F = Fp;\n if (!F.eql(F.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// The Legendre symbol and every sqrt variant here are only defined over an odd (prime) modulus.\n// An even ORDER makes their integer divisions — (p-1)/2, (p+1)/4, (p-5)/8, (p+7)/16 — truncate and\n// silently return a wrong result, so reject it explicitly at the entry points instead. This is a\n// cheap necessary-condition check, not a primality test (composite odd moduli are caught later by\n// the Legendre-result / assertIsSquare checks).\nfunction aoddModulus(order, fnName) {\n if ((order & _1n) === _0n)\n throw new Error(fnName + ': expected odd modulus, got ' + order);\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const F = Fp;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8(Fp, n) {\n const F = Fp;\n const p5div8 = (F.ORDER - _5n) / _8n;\n const n2 = F.mul(n, _2n);\n const v = F.pow(n2, p5div8);\n const nv = F.mul(n, v);\n const i = F.mul(F.mul(nv, _2n), v);\n const root = F.mul(nv, F.sub(i, F.ONE));\n assertIsSquare(F, root, n);\n return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return ((Fp, n) => {\n const F = Fp;\n let tv1 = F.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(F, root, n);\n return root;\n });\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`\n * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.\n * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P - field order\n * @returns function that takes field Fp (created from P) and number n\n * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}\n * @example\n * Construct a square-root helper for primes that need Tonelli-Shanks.\n *\n * ```ts\n * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = tonelliShanks(17n)(Fp, 4n);\n * ```\n */\nexport function tonelliShanks(P) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n aoddModulus(P, 'tonelliShanks');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000)\n throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1)\n return sqrt3mod4;\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n const F = Fp;\n if (F.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1)\n throw new Error('Cannot find square root');\n // Initialize variables for the main loop\n let M = S;\n let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n // Unreachable over a genuine field (no zero divisors; n=0 already returned above). A zero t\n // means composite ORDER, where a fabricated root would be wrong: fail closed instead.\n if (F.is0(t))\n throw new Error('Cannot find square root: probably non-prime P');\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = F.sqr(t); // t^(2^1)\n while (!F.eql(t_tmp, F.ONE)) {\n i++;\n t_tmp = F.sqr(t_tmp); // t^(2^2)...\n if (i === M)\n throw new Error('Cannot find square root');\n }\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = F.pow(c, exponent); // b = 2^(M - i - 1)\n // Update variables\n M = i;\n c = F.sqr(b); // c = b^2\n t = F.mul(t, c); // t = (t * b^2)\n R = F.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness\n * (used for hash-to-curve).\n * @param P - Field order.\n * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time\n * behavior and this selector assumes prime-field-style integer moduli.\n * @throws If the field is unsupported or the square root does not exist. {@link Error}\n * @example\n * Choose the square-root helper appropriate for one field modulus.\n *\n * ```ts\n * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = FpSqrt(17n)(Fp, 4n);\n * ```\n */\nexport function FpSqrt(P) {\n aoddModulus(P, 'Fp.sqrt');\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n/**\n * @param num - Value to inspect.\n * @param modulo - Field modulus.\n * @returns `true` when the least-significant little-endian bit is set.\n * @throws If the modulus is invalid for `mod(...)`. {@link Error}\n * @example\n * Inspect the low bit used by little-endian sign conventions.\n *\n * ```ts\n * isNegativeLE(3n, 11n);\n * ```\n */\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\n// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime\n// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and\n// field-specific extras like `isOdd` are left to the callers that actually need them.\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\n/**\n * @param field - Field implementation.\n * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it\n * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or\n * field-specific extras beyond positive `BYTES` / `BITS`.\n * @throws If the field shape or numeric metadata are invalid. {@link Error}\n * @example\n * Check that a field implementation exposes the operations curve code expects.\n *\n * ```ts\n * import { Field, validateField } from '@noble/curves/abstract/modular.js';\n * const Fp = validateField(Field(17n));\n * ```\n */\nexport function validateField(field) {\n aobject(field, 'field');\n if (typeof field.ORDER !== 'bigint')\n throw new TypeError('param \"ORDER\" is invalid: expected bigint, got ' + typeof field.ORDER);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n for (const name of FIELD_FIELDS)\n afunction(field[name], 'field.' + name);\n // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n if (field.BYTES < 1 || field.BITS < 1)\n throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n)\n throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @param Fp - Field implementation.\n * @param num - Base value.\n * @param power - Exponent value.\n * @returns Powered field element.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Raise one field element to a public exponent.\n *\n * ```ts\n * import { Field, FpPow } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpPow(Fp, 3n, 5n);\n * ```\n */\nexport function FpPow(Fp, num, power) {\n validateField(Fp);\n const F = Fp;\n // Non-bigint exponents (e.g. an accidental field element) coerce every comparison below to\n // false and would silently return ONE.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return F.ONE;\n if (power === _1n)\n return num;\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents (e.g. poseidon\n // sbox x^5), which would waste the 14-multiplication table build.\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first — same shape as pow() above, over generic field ops.\n // Speeds up dense long exponents (extension-field sqrt / Legendre, e.g. Fp2 decompression).\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = F.ONE;\n table[1] = num;\n for (let i = 2; i < 16; i++)\n table[i] = F.mul(table[i - 1], num);\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = F.sqr(F.sqr(F.sqr(F.sqr(p))));\n const digit = digits[w];\n if (digit !== 0)\n p = F.mul(p, table[digit]);\n }\n return p;\n}\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n validateField(Fp);\n aarray(nums, 'nums');\n abool(passZero, 'passZero');\n const F = Fp;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (F.is0(num))\n return acc;\n inverted[i] = acc;\n return F.mul(acc, num);\n }, F.ONE);\n // Invert last element\n const invertedAcc = F.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (F.is0(num))\n return acc;\n // Non-zero `num` means the forward pass already stored a defined prefix product at index i.\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n/**\n * @param Fp - Field implementation.\n * @param lhs - Dividend value.\n * @param rhs - Divisor value.\n * @returns Division result.\n * @throws If the divisor is non-invertible. {@link Error}\n * @example\n * Divide one field element by another.\n *\n * ```ts\n * import { Field, FpDiv } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpDiv(Fp, 6n, 3n);\n * ```\n */\nexport function FpDiv(Fp, lhs, rhs) {\n validateField(Fp);\n const F = Fp;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the powered value does not match a valid Legendre symbol. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre(Fp, n) {\n validateField(Fp);\n const F = Fp;\n aoddModulus(F.ORDER, 'FpLegendre');\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (F.ORDER - _1n) / _2n;\n const powered = F.pow(n, p1mod2);\n const yes = F.eql(powered, F.ONE);\n const zero = F.eql(powered, F.ZERO);\n const no = F.eql(powered, F.neg(F.ONE));\n if (!yes && !zero && !no)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n/**\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict \"quadratic\n * residue\" terminology often reserves that name for the non-zero square class.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Check whether one field element has a square root in the field.\n *\n * ```ts\n * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const isSquare = FpIsSquare(Fp, 4n);\n * ```\n */\nexport function FpIsSquare(Fp, n) {\n const l = FpLegendre(Fp, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\n}\n/**\n * @param n - Curve order. Callers are expected to pass a positive order.\n * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached\n * value when overriding the derived bit length.\n * @returns Byte and bit lengths.\n * @throws If the order or cached bit length is invalid. {@link Error}\n * @example\n * Measure the encoding sizes needed for one modulus.\n *\n * ```ts\n * nLength(255n);\n * ```\n */\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n if (n <= _0n)\n throw new Error('invalid n length: expected positive n, got ' + n);\n if (nBitLength !== undefined && nBitLength < 1)\n throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);\n const bits = bitLen(n);\n // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison\n // any math that relies on the derived field metadata.\n if (nBitLength !== undefined && nBitLength < bits)\n throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the\n// cached helper write would keep the field surface externally mutable.\nconst FIELD_SQRT = new WeakMap();\nclass _Field {\n ORDER;\n BITS;\n BYTES;\n isLE;\n ZERO = _0n;\n ONE = _1n;\n _lengths;\n _mod;\n constructor(ORDER, opts = {}) {\n // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv\n // would stop modeling field arithmetic.\n if (ORDER <= _1n)\n throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.\n if (typeof opts.BITS === 'number')\n _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties\n // explicitly instead of relying on writable prototype shadowing via assignment.\n Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });\n if (typeof opts.isLE === 'boolean')\n this.isLE = opts.isLE;\n if (opts.allowedLengths)\n this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean')\n this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n Object.freeze(this);\n }\n create(num) {\n return mod(num, this.ORDER);\n }\n isValid(num) {\n if (typeof num !== 'bigint')\n throw new TypeError('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num) {\n return (num & _1n) === _1n;\n }\n neg(num) {\n return mod(-num, this.ORDER);\n }\n eql(lhs, rhs) {\n return lhs === rhs;\n }\n sqr(num) {\n return mod(num * num, this.ORDER);\n }\n add(lhs, rhs) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs, rhs) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs, rhs) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num, power) {\n return pow(num, power, this.ORDER);\n }\n div(lhs, rhs) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n // Same as above, but doesn't normalize\n sqrN(num) {\n return num * num;\n }\n addN(lhs, rhs) {\n return lhs + rhs;\n }\n subN(lhs, rhs) {\n return lhs - rhs;\n }\n mulN(lhs, rhs) {\n return lhs * rhs;\n }\n inv(num) {\n return invert(num, this.ORDER);\n }\n sqrt(num) {\n // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping\n // the field instance itself mutable.\n let sqrt = FIELD_SQRT.get(this);\n if (!sqrt)\n FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num) {\n // Serialize fixed-width limbs without re-validating the field range. Callers that need a\n // canonical encoding must pass a valid element; some protocols intentionally serialize raw\n // residues here and reduce or validate them elsewhere.\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n // `allowedLengths` must list real positive byte lengths; otherwise empty input would get\n // padded into zero and silently decode as a field element.\n if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes)\n scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // Range validation is optional here because some protocols intentionally decode raw residues\n // and reduce or validate them elsewhere.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst) {\n // `passZero` keeps the `bigint[]` contract honest: zero inputs map to `0` instead of leaking\n // `undefined` into a `bigint[]`. Callers that must distinguish non-invertible inputs should use\n // `FpInvertBatch` directly, whose default omits `passZero` and returns `(bigint | undefined)[]`.\n return FpInvertBatch(this, lst, true);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a, b, condition) {\n // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject\n // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.\n abool(condition, 'condition');\n return condition ? b : a;\n }\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for\n * all elements for performance and protocol-flexibility reasons; callers are responsible for\n * supplying valid elements when they need canonical field behavior.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER - field order, probably prime, or could be composite\n * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.\n * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight\n * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.\n * @example\n * Construct one prime field with optional overrides.\n *\n * ```ts\n * Field(11n);\n * ```\n */\nexport function Field(ORDER, opts = {}) {\n // Freeze the shared method surface before any instance is reachable; otherwise callers can\n // poison every Field instance by monkey-patching `_Field.prototype` even if each instance is\n // frozen. Freezing here instead of module scope keeps `_Field` tree-shakeable for importers\n // that never construct a field; the call is idempotent and cheap.\n Object.freeze(_Field.prototype);\n return new _Field(ORDER, opts);\n}\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,\n * which is the only square root but is not odd.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the odd square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtOdd(Fp, 4n);\n * ```\n */\nexport function FpSqrtOdd(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? root : F.neg(root);\n}\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Even square root.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the even square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtEven(Fp, 4n);\n * ```\n */\nexport function FpSqrtEven(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? F.neg(root) : root;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an\n * order greater than 1.\n * @returns byte length of field\n * @throws If the field order is not a bigint. {@link Error}\n * @example\n * Read the fixed-width byte length of one field.\n *\n * ```ts\n * getFieldBytesLength(255n);\n * ```\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.\n if (fieldOrder <= _1n)\n throw new Error('field order must be greater than 1');\n // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.\n const bitLength = bitLen(fieldOrder - _1n);\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger\n * absolute floor for policy reasons.\n * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.\n * @returns byte length of target hash\n * @throws If the field order is invalid. {@link Error}\n * @example\n * Compute the minimum hash length needed for field reduction.\n *\n * ```ts\n * getMinHashLength(255n);\n * ```\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard\n * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look\n * accidentally acceptable for real scalar derivation.\n * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},\n * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and\n * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380\n * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.\n * @param key - Uniform input bytes.\n * @param fieldOrder - Size of subgroup.\n * @param isLE - interpret hash bytes as LE num\n * @returns valid private scalar\n * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}\n * @example\n * Map hash output into a private scalar range.\n *\n * ```ts\n * mapHashToField(new Uint8Array(48).fill(1), 255n);\n * ```\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = Math.max(getMinHashLength(fieldOrder), 16);\n // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge\n // inputs: easier to reason about JS timing / allocation behavior.\n if (len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // Map into the non-zero scalar range [1, fieldOrder-1]: reduce mod (fieldOrder-1) to land in\n // [0, fieldOrder-2], then add 1. This shifts the range off zero; it is NOT equal to\n // `mod(num, fieldOrder)` (which spans [0, fieldOrder-1] and can be 0). A residual modulo bias\n // remains but is negligible (~2^-(nBits/2), e.g. ~2^-128 for a 256-bit order) because `key` is\n // required to be at least `getMinHashLength(fieldOrder)` (~1.5x field size) bytes of input.\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF-based ScalarMultiplier, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, afunction, aobject, bitLen, bitMask, bytesToNumberBE, inRange, isBytes, isPosBig, validateObject, } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _4n = /* @__PURE__ */ BigInt(4);\nconst BLIND_BYTES = 16;\nconst BLIND_BITS = 128;\n// Fixed-window width for the constant-time multiply of un-precomputed points (W===1).\n// A flat 2^FW_WINDOW table has a small, scalar-independent build cost that amortizes over a single\n// multiply, unlike the larger per-point wNAF tables that only pay off when cached.\nconst FW_WINDOW = 5;\n// Precompute tables are capped at ~2 GiB of estimated heap. Rejecting larger windows up front\n// turns a typo'd window size into an immediate error instead of a multi-GB allocation (or an\n// effective hang) when the lazy table is built on first multiply.\nconst TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();\n/**\n * Validates the static surface of a point constructor.\n * This is only a cheap sanity check for the constructor hooks and fields consumed by generic\n * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.\n * @param Point - Runtime point constructor.\n * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}\n * @example\n * Check that one point constructor exposes the static hooks generic helpers need.\n *\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { validatePointCons } from '@noble/curves/abstract/curve.js';\n * validatePointCons(ed25519.Point);\n * ```\n */\nexport function validatePointCons(Point) {\n const pc = Point;\n if (typeof pc !== 'function')\n throw new TypeError('\"Point\" expected constructor, got type=' + typeof Point);\n afunction(pc.fromAffine, 'Point.fromAffine');\n afunction(pc.fromBytes, 'Point.fromBytes');\n afunction(pc.fromHex, 'Point.fromHex');\n // Generic helpers (ScalarMultiplier, normalizeZ, MSM) dereference BASE / ZERO:\n // fail here with a typed error instead of an `undefined` access later.\n aobject(pc.BASE, 'Point.BASE');\n aobject(pc.ZERO, 'Point.ZERO');\n validateField(pc.Fp);\n validateField(pc.Fn);\n}\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n * Input points are left unchanged; the normalized points are returned as fresh instances.\n * @param c - Point constructor.\n * @param points - Projective points.\n * @returns Fresh projective points reconstructed from normalized affine coordinates.\n * @example\n * Batch-normalize projective points with a single shared inversion.\n *\n * ```ts\n * import { normalizeZ } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);\n * ```\n */\nexport function normalizeZ(c, points) {\n // Match MSM helpers: reject malformed public inputs before reading projective internals.\n validatePointCons(c);\n validateMSMPoints(points, c);\n // Identity points (Z=0) rely on an implicit contract: FpInvertBatch without `passZero`\n // yields `undefined` for zero inputs, and `toAffine(undefined)` falls back to its internal\n // is0 handling instead of using the batch inverse.\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits, min = 1) {\n if (!Number.isSafeInteger(W) || W < min || W > bits)\n throw new Error('invalid window size, expected [' + min + '..' + bits + '], got W=' + W);\n}\n// Rough per-point heap estimate for the {@link TABLE_BYTES_MAX} cap: up to 4 projective/extended\n// coordinates of Fp.BYTES each, plus bigint/object overhead. Callers pass the point count of the\n// largest table the checked parameters can produce.\nfunction validateTableBytes(numPoints, fpBytes) {\n const bytes = numPoints * (4 * fpBytes + 128);\n if (bytes > TABLE_BYTES_MAX)\n throw new Error('invalid window size: table would need ~' +\n Math.ceil(bytes / 2 ** 20) +\n ' MiB, max ' +\n TABLE_BYTES_MAX / 2 ** 20 +\n ' MiB');\n}\n/**\n * Probes an RNG once, at construction time: returns `undefined` when it is unavailable —\n * throws or returns malformed bytes — so callers can downgrade to their unblinded /\n * deterministic constant-time fallback. Blinding is defense-in-depth (DPA/template\n * hardening), not a correctness or key-secrecy requirement, so availability-based\n * downgrade is acceptable.\n *\n * The downgrade decision is deliberately static. After a successful probe the RNG becomes\n * part of the trusted contract: later misbehavior must fail closed in per-call validation\n * (throw), never downgrade — a dynamic fallback would let a tampered RNG silently strip\n * blinding on demand. A probe can only ever classify broken environments, not adversarial\n * RNGs: a stateful RNG can always behave while probed and misbehave later.\n * @param randomBytes - RNG to probe, or `undefined` when the environment provides none.\n * @param length - Byte length requested from the probe call.\n * @returns The RNG when the probe produced `length` valid bytes; `undefined` otherwise.\n * @example\n * Probe an RNG once before enabling scalar blinding.\n *\n * ```ts\n * import { probeRandomBytes } from '@noble/curves/abstract/curve.js';\n * import { randomBytes } from '@noble/hashes/utils.js';\n * const rng = probeRandomBytes(randomBytes, 16);\n * ```\n */\nexport function probeRandomBytes(randomBytes, length) {\n if (randomBytes === undefined)\n return undefined;\n afunction(randomBytes, 'randomBytes');\n try {\n const probe = randomBytes(length);\n if (!isBytes(probe) || probe.length !== length)\n return undefined;\n }\n catch {\n return undefined;\n }\n return randomBytes;\n}\nfunction validateMSMPoints(points, c) {\n aarray(points, 'points');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\n// Default bound is field membership (0 <= s < field.ORDER); a `maxScalar` override widens it\n// to 0 <= s < maxScalar for callers that accept oversized scalars.\nfunction validateMSMScalars(scalars, field, maxScalar) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n const ok = maxScalar === undefined ? field.isValid(s) : isPosBig(s) && s < maxScalar;\n if (!ok)\n throw new Error('invalid scalar at index ' + i);\n });\n}\nconst pointWindowSizes = new WeakMap();\nfunction getWindowSize(P) {\n // `1` is the uncached sentinel: use the non-precomputed (wNAF / fixed-window) path.\n return pointWindowSizes.get(P) || 1;\n}\n/** Table of odd multiples [1P, 3P, ..., (2⋅size−1)P]; width-W wNAF uses size = 2^(W−2). */\nfunction oddMultiples(p, size) {\n const dbl = p.double();\n const t = [p];\n for (let j = 1; j < size; j++)\n t.push(t[j - 1].add(dbl));\n return t;\n}\n/**\n * Width-W wNAF signed-digit recoding (W >= 2), LSB-first: digits are 0 or odd with\n * |digit| < 2^(W−1); nonzero density ~1/(W+1) (a nonzero digit is followed by W−1 zeros).\n */\nfunction wnafDigits(n, W) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const d = [];\n while (n > _0n) {\n let w = 0;\n if (n & _1n) {\n w = Number(n & mask); // n mod 2^W, odd\n if (w >= half)\n w -= size; // signed residue\n n -= BigInt(w); // n - w ≡ 0 mod 2^W: next W−1 digits are zero\n }\n d.push(w);\n n >>= _1n;\n }\n return d;\n}\n/**\n * Fixed-position signed-window recoding for precomputed wNAF: `n = Σ digits[w]⋅2^(w⋅W)` with\n * digits in `[−2^(W−1)+1, 2^(W−1)]`. Digit count is fixed by `windows` (callers reserve one\n * extra window for the final carry), so recoding length does not depend on the scalar.\n */\nfunction signedWindowDigits(n, W, windows) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const shiftBy = BigInt(W);\n const d = [];\n for (let w = 0; w < windows; w++) {\n let v = Number(n & mask);\n n >>= shiftBy;\n if (v > half) {\n v -= size; // negative digit, carry into the next window\n n += _1n;\n }\n d.push(v);\n }\n // Internal invariant: leftover bits mean the window count did not cover the scalar.\n if (n !== _0n)\n throw new Error('invalid wnaf');\n return d;\n}\n/**\n * Shared vartime walk over per-scalar wNAF digit streams: one doubling of a single shared\n * accumulator per bit position of the longest recoding, one signed table addition per\n * nonzero digit. `tables[i]` must hold the odd multiples of the i-th point.\n */\nfunction wnafWalk(zero, tables, digits) {\n let max = 0;\n for (const d of digits)\n max = Math.max(max, d.length);\n let acc = zero;\n for (let bit = max - 1; bit >= 0; bit--) {\n if (bit !== max - 1)\n acc = acc.double();\n for (let i = 0; i < digits.length; i++) {\n const w = digits[i][bit]; // reads past shorter recodings yield undefined, skipped below\n if (w) {\n const item = tables[i][(Math.abs(w) - 1) >> 1];\n acc = acc.add(w < 0 ? item.negate() : item);\n }\n }\n }\n return acc;\n}\n/**\n * Elliptic curve multiplication of Point by scalar.\n * Routes between cached-table, fixed-window, and one-shot wNAF paths; entry points validate\n * their own scalars (`mulCT`/`mulCTBlinded`: `1 <= s < Fn.ORDER`; `mulUnsafe`: up to the\n * `Fn.ORDER^4` DoS cap via {@link mulAddUnsafe}).\n * Table generation is expensive and happens on first call of `multiply()`\n * (or eagerly via `precompute(W, false)`). By default, `BASE` point is precomputed.\n *\n * Cached algorithm is signed fixed-window wNAF:\n * - table stores, for every window w, the multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P` — all doublings\n * are baked in, so a multiplication is exactly one table addition per window\n * - window count is fixed (`ceil(bits/W) + 1`), so the point-operation count is scalar-independent\n * (basis of the constant-time path)\n * - for a 256-bit curve and W=6: 44⋅32 = 1408 table points, 44 additions per multiply\n * - secret scalars are additionally blinded (see {@link ScalarMultiplier.mulCTBlinded}), which\n * widens tables by 128 bits\n * @param Point - Point constructor.\n * @param randomBytes - RNG used for scalar blinding; required by the blinded secret path.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { ScalarMultiplier } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const mul = new ScalarMultiplier(p256.Point);\n * ```\n */\nexport class ScalarMultiplier {\n Point;\n BASE;\n ZERO;\n randomBytes;\n wnafPrecomputes = new WeakMap();\n baseCanBeBlinded;\n bits;\n // Parametrized with a given Point class (not individual point)\n constructor(Point, randomBytes) {\n validatePointCons(Point);\n // Probe the RNG once (see {@link probeRandomBytes}): in environments without working\n // randomness (e.g. no WebCrypto), shouldBlind() then routes secret multiplication to the\n // unblinded constant-time path instead of throwing on every multiply(). The shape of\n // returned bytes is still validated on every blinded call, where breakage fails closed.\n this.randomBytes = probeRandomBytes(randomBytes, BLIND_BYTES);\n this.Point = Point;\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.bits = Point.Fn.BITS;\n }\n /**\n * Creates a signed fixed-window wNAF precomputation table: for every window w, the\n * multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,\n * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra\n * window absorbs the final carry of signed-digit recoding.\n * For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.\n * @param point - Point instance\n * @param W - window size\n * @param bits - scalar bitlength the table must cover\n */\n buildWnafTable(point, W, bits) {\n // W needs no re-validation: its only source is setWindowSize(), which enforces\n // 1 <= W <= Fn.BITS <= bits (the blinded path only ever widens bits) and caps the\n // resulting table at ~2 GiB (sized against the wider blinded layout).\n const windows = Math.ceil(bits / W) + 1;\n const half = 2 ** (W - 1);\n const comp = [];\n let base = point;\n for (let w = 0; w < windows; w++) {\n let acc = base;\n for (let i = 0; i < half; i++) {\n comp.push(acc);\n acc = acc.add(base);\n }\n base = comp[comp.length - 1].double(); // 2⋅(2^(W−1)⋅base) = next window's base\n }\n return { W, bits, windows, comp };\n }\n /**\n * Implements ec multiplication using precomputed signed fixed-window wNAF tables.\n * Constant-time: fixed window count with one table addition per window — zero digits feed\n * the fake accumulator — and no doublings; the lookup scans the whole window slice.\n * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},\n * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});\n * signedWindowDigits throws if `n` exceeds the table.\n * @returns real and fake (for const-time) points\n */\n wnafCachedCT(precomputes, n) {\n const { W, windows, comp } = precomputes;\n const half = 2 ** (W - 1);\n const digits = signedWindowDigits(n, W, windows);\n let p = this.ZERO;\n let f = this.BASE;\n for (let w = 0; w < windows; w++) {\n const digit = digits[w];\n const start = w * half;\n // Data-oblivious select: touch every entry of the window before the digit branch.\n const idx = Math.abs(digit) - 1; // -1 for zero digits: matches nothing, `sel` unused\n let sel = comp[start];\n for (let i = 1; i < half; i++)\n sel = i === idx ? comp[start + i] : sel;\n const neg = sel.negate(); // compute both signs; the digit only picks one\n if (digit === 0)\n f = f.add(comp[start]);\n else\n p = p.add(digit < 0 ? neg : sel);\n }\n return { p, f };\n }\n // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width\n // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with\n // incompatible `transform(...)` layouts and expect a separate cache entry.\n getWnafPrecomputes(W, point, bits, transform) {\n let entries = this.wnafPrecomputes.get(point);\n let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);\n if (!comp) {\n comp = this.buildWnafTable(point, W, bits);\n if (typeof transform === 'function')\n comp = { ...comp, comp: transform(comp.comp) };\n if (!entries) {\n entries = [];\n this.wnafPrecomputes.set(point, entries);\n }\n entries.push(comp);\n }\n return comp;\n }\n assertPoint(point) {\n if (!(point instanceof this.Point))\n throw new TypeError('\"point\" expected Point instance, got type=' + typeof point);\n }\n // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style\n // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.\n // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.\n validateMulInput(point, scalar) {\n this.assertPoint(point);\n if (!inRange(scalar, _1n, this.Point.Fn.ORDER))\n throw new Error('invalid scalar');\n }\n // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.\n // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window\n // multiply. `n` must be < 2^bits.\n runCT(point, n, bits, transform) {\n const W = getWindowSize(point);\n if (W === 1)\n return this.fixedWindowCT(point, n, bits);\n return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);\n }\n mulCT(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n return this.runCT(point, scalar, this.bits, transform);\n }\n mulCTBlinded(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n // Blinding computes n = scalar + blind*Fn.ORDER, then n*P via a constant-time multiply. This\n // equals scalar*P only when Fn.ORDER*P == O; callers guarantee that via shouldBlind() (always\n // for cofactor-1 curves; for cofactored curves only BASE, and only after checking BASE*n == O).\n // Fail before building the (large) precompute table if randomness is unavailable.\n if (this.randomBytes === undefined)\n throw new Error('randomBytes is required for scalar blinding');\n const bits = this.Point.Fn.BITS + BLIND_BITS;\n const blind = this.randomBytes(BLIND_BYTES);\n if (!isBytes(blind) || blind.length !== BLIND_BYTES)\n throw new Error('randomBytes returned invalid byte array');\n // Force the top two bits of the 128-bit blind to 10xxxxxx, so blind is in [2^127, 1.5*2^127):\n // * `| 0x80` (bit 127 = 1) is the load-bearing part: it guarantees blind >= 2^127, so the blind\n // is always a full-width, nonzero factor and the scalar is masked even with a degenerate RNG.\n // * `& 0x3f` (bit 126 = 0) is a safety margin: it caps blind < 1.5*2^127, keeping\n // blind*Fn.ORDER + scalar < 0.75*2^(nBits+128), i.e. ~half a window below the 2^(nBits+128)\n // ceiling. Not strictly required for the bound (see below), but it reserves headroom so the\n // guarantee does not rest on the tight `Fn.ORDER < 2^Fn.BITS` fact and the final carry window\n // only ever holds a small carry, never a full digit.\n blind[0] = (blind[0] & 0x3f) | 0x80;\n // Even at the extreme (blind < 2^128, scalar < Fn.ORDER < 2^nBits): n <= 2^128*Fn.ORDER - 1 <\n // 2^(nBits+128), so n stays below 2^bits and within the blinded table's\n // window count. Both cached CT kernels run a fixed number of windows/rows with one point-add\n // each, so the add count is independent of scalar (constant-time).\n const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;\n return this.runCT(point, n, bits, transform);\n }\n /**\n * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.\n * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is\n * far cheaper to build for a single use. The point-operation sequence is independent of `n`:\n * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over\n * every table entry, and one addition (adds the identity when the window digit is 0 — never\n * skipped).\n *\n * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any\n * add), which holds for the Weierstrass/Edwards point types used here. The table is left in\n * projective form (no normalizeZ): normalizing this small a table costs more than the\n * mixed-add savings it would buy for a single multiply.\n * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape\n * (this path needs no fake accumulator — its op-count is already scalar-independent).\n */\n fixedWindowCT(point, n, bits) {\n const W = FW_WINDOW;\n const size = 1 << W;\n const mask = bitMask(W);\n // Flat table [O, point, 2*point, ..., (size-1)*point].\n const table = new Array(size);\n table[0] = this.ZERO;\n for (let i = 1; i < size; i++)\n table[i] = table[i - 1].add(point);\n // Horner MSB->LSB. windows*W >= bits and n < 2^bits, so every bit of n is consumed.\n const windows = Math.ceil(bits / W);\n let acc = this.ZERO;\n for (let window = windows - 1; window >= 0; window--) {\n // W doublings per window; skipped for the first (topmost) window, where acc is still the\n // identity. The skip is scalar-independent: it depends only on the loop index.\n if (window !== windows - 1)\n for (let d = 0; d < W; d++)\n acc = acc.double();\n const digit = Number((n >> BigInt(window * W)) & mask);\n // Data-oblivious select: touch every entry, same as wnafCachedCT.\n let sel = table[0];\n for (let i = 1; i < size; i++)\n sel = i === digit ? table[i] : sel;\n acc = acc.add(sel); // one add per window, even for digit 0\n }\n return { p: acc, f: acc };\n }\n shouldBlind(point, cofactor) {\n // No usable RNG (probed in the constructor): blinding is impossible, use the plain CT path.\n if (this.randomBytes === undefined)\n return false;\n if (cofactor === _1n)\n return true;\n if (point !== this.BASE)\n return false;\n if (this.baseCanBeBlinded === undefined)\n this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();\n return this.baseCanBeBlinded;\n }\n mulSecret(point, scalar, cofactor, transform) {\n return this.shouldBlind(point, cofactor)\n ? this.mulCTBlinded(point, scalar, transform)\n : this.mulCT(point, scalar, transform);\n }\n mulUnsafe(point, scalar, transform) {\n this.assertPoint(point);\n if (!isPosBig(scalar))\n throw new Error('invalid scalar');\n const W = getWindowSize(point);\n // W === 1 (un-precomputed): one-shot width-4 wNAF via {@link mulAddUnsafe} with L=1 —\n // a cached table would be thrown away after one use. `allowOversized` swaps the\n // `s < Fn.ORDER` check for mulAddUnsafe's `Fn.ORDER^4` DoS cap.\n //\n // Oversized scalar could happen when:\n // a) user passes large scalar on their own (rare)\n // b) `assertValidity()` calls `isTorsionFree()`, which multiplies point by `Fn.ORDER`\n if (W === 1 || scalar >= this.Point.Fn.ORDER)\n return mulAddUnsafe(this.Point, [point], [scalar], true);\n // Precomputed points reuse the CT kernel (fake accumulator discarded): with W=6 only\n // ~1/64 of window-adds are skippable, so a dedicated vartime kernel saved just ~6% on\n // this path while doubling the cached-table code surface.\n const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);\n return this.wnafCachedCT(precomputes, scalar).p;\n }\n // Remembers the window size used for precomputed wNAF multiplication of the given point\n // and drops any previously built tables. Usually only the base point is precomputed.\n // W=1 resets the point to the un-precomputed (table-less) paths.\n // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).\n setWindowSize(point, W) {\n this.assertPoint(point);\n validateW(W, this.bits);\n // Size against the widest table this W can produce: the blinded path adds BLIND_BITS.\n const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;\n validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);\n pointWindowSizes.set(point, W);\n this.wnafPrecomputes.delete(point);\n }\n // True when a window size is set: tables themselves are built lazily on first multiply.\n hasWindowSize(point) {\n return getWindowSize(point) !== 1;\n }\n}\n/**\n * Combined multi-scalar multiplication `Σ scalars[i]⋅points[i]` via interleaved width-4 wNAF\n * (Strauss–Shamir). Every input gets its own table of odd multiples `[1P, 3P, 5P, 7P]` and\n * signed-digit recoding, but all walks share one doubling chain, so total cost is\n * `~bits` doublings + `L⋅bits/5` additions instead of `L⋅bits` doublings for separate\n * multiplications. Intended for the 2-4 point shapes of signature verification\n * (`R = u1⋅G + u2⋅P`); use {@link pippenger} for larger batches.\n *\n * Not constant-time: only for public inputs. Scalars must satisfy `0 <= s < Fn.ORDER`;\n * fold negative signs into the points before calling.\n * @param c - Point constructor.\n * @param points - Array of curve points.\n * @param scalars - Array of non-negative scalars, same length as points.\n * @param allowOversized - Replace the `s < Fn.ORDER` scalar check with a `Fn.ORDER^4` DoS cap.\n * Off by default. For scalars that must NOT be reduced mod ORDER: torsion checks\n * (`Fn.ORDER⋅P ≟ O`) and cofactor-clearing multiples. Walk length grows with `bitLen(s)`.\n * @returns Combined multiplication result; identity for empty input.\n * @throws If the point set or scalar set is invalid. {@link Error}\n * @example\n * Combined multi-scalar multiplication via Strauss–Shamir.\n *\n * ```ts\n * import { mulAddUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const G = p256.Point.BASE;\n * const R = mulAddUnsafe(p256.Point, [G, G.double()], [2n, 3n]); // 2⋅G + 3⋅(2⋅G)\n * ```\n */\nexport function mulAddUnsafe(c, points, scalars, allowOversized = false) {\n validatePointCons(c);\n validateMSMPoints(points, c);\n abool(allowOversized, 'allowOversized');\n // Oversized cap is ORDER^4: hard bound to mitigate DoS, walk length grows with bitLen(s).\n validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n : undefined);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const tables = points.map((p) => oddMultiples(p, 4));\n const digits = scalars.map((n) => wnafDigits(n, 4));\n return wnafWalk(c.ZERO, tables, digits);\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Point-operation count is scalar-independent (for same L), even when 1 point + scalar, or when\n * scalar = 0 — but bucket indices are scalar windows, so the memory-access pattern is\n * scalar-dependent: do not rely on this for secret scalars.\n *\n * A repaired LFG bucket-set variant from ePrint 2024/750 was benchmarked on BLS12-381 G1\n * against this implementation: ~1.4x faster at 2048 points and ~1.1-1.25x faster at\n * 4096-32768 points, at the cost of extra recoding and multiplier-table complexity.\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger(c, points, scalars) {\n // 0 is accepted in scalars\n validatePointCons(c);\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n // Without this, the window loop below would still run ~Fn.BITS doublings of ZERO.\n if (plength === 0)\n return zero;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...) over a FIXED set\n * of points: each point gets a one-time table of odd multiples\n * `[1P, 3P, ..., (2^(W−1)−1)P]`, and the returned closure evaluates MSMs against those\n * tables. All scalars share one doubling chain (Straus 1964) — one doubling per scalar bit\n * plus one signed table addition per nonzero width-W wNAF digit (density ~1/(W+1)) — the\n * \"interleaving\" method of Möller, \"Algorithms for multi-exponentiation\" (SAC 2001).\n *\n * Table memory is `L⋅2^(W−2)` points, capped at ~2 GiB. Prefer this over {@link pippenger}\n * when the same points are reused across many MSMs (fixed-base commitments etc.) and up to a\n * few hundred points; prefer pippenger for one-shot MSMs or thousands of points, where\n * bucketing beats per-point tables.\n *\n * Not constant-time (zero digits are skipped): public inputs only.\n * @param c - Curve Point constructor\n * @param points - array of L curve points, captured by the returned closure\n * @param windowSize - window width W in bits, from 2 to Fn.BITS; also capped so the\n * per-closure tables stay under ~2 GiB\n * @returns Function which multiplies points with scalars. The closure accepts at most\n * `points.length` scalars, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { interleavedMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = interleavedMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function interleavedMSMUnsafe(c, points, windowSize) {\n validatePointCons(c);\n const fieldN = c.Fn;\n // Signed odd digits need at least width 2 (W=2 is plain NAF with a single-entry table).\n validateW(windowSize, fieldN.BITS, 2);\n validateMSMPoints(points, c);\n validateTableBytes(points.length * 2 ** (windowSize - 2), c.Fp.BYTES);\n const tables = points.map((p) => oddMultiples(p, 2 ** (windowSize - 2)));\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must not be larger than array of points');\n return wnafWalk(c.ZERO, tables, scalars.map((n) => wnafDigits(n, windowSize)));\n };\n}\nfunction createField(order, field, isLE) {\n if (field) {\n // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback\n // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov\n // behavior.\n if (field.ORDER !== order)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\n }\n}\n/**\n * Validates basic CURVE shape and field membership, then creates fields.\n * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or\n * that the curve equation itself is otherwise sane.\n * @param type - Curve family.\n * @param CURVE - Curve parameters.\n * @param curveOpts - Optional field overrides. See {@link FpFn}:\n * - `Fp` (optional): Optional base-field override.\n * - `Fn` (optional): Optional scalar-field override.\n * @param FpFnLE - Whether field encoding is little-endian.\n * @returns Frozen curve parameters and fields.\n * @throws If the curve parameters or field overrides are invalid. {@link Error}\n * @example\n * Build curve fields from raw constants before constructing a curve instance.\n *\n * ```ts\n * const curve = createCurveFields('weierstrass', {\n * p: 17n,\n * n: 19n,\n * h: 1n,\n * a: 2n,\n * b: 2n,\n * Gx: 5n,\n * Gy: 1n,\n * });\n * ```\n */\nexport function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n if (type !== 'weierstrass' && type !== 'edwards')\n throw new Error('expected curve type \"weierstrass\" or \"edwards\"');\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n // Validate before reading Fp/Fn so explicit null fails with an options-object error.\n validateObject(curveOpts);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(isPosBig(val) && val !== _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n/**\n * @param randomSecretKey - Secret-key generator.\n * @param getPublicKey - Public-key derivation helper.\n * @returns Keypair generator.\n * @example\n * Build a `keygen()` helper from existing secret-key and public-key primitives.\n *\n * ```ts\n * import { createKeygen } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);\n * const pair = keygen();\n * ```\n */\nexport function createKeygen(randomSecretKey, getPublicKey) {\n return function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abool, abytes, aInRange, asafenumber, bytesToHex, bytesToNumberLE, concatBytes, copyBytes, hexToBytes, isBytes, notImplemented, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, normalizeZ, ScalarMultiplier, validatePointCons, } from \"./curve.js\";\nimport { FpLegendre } from \"./modular.js\";\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _4n = /* @__PURE__ */ BigInt(4), _8n = /* @__PURE__ */ BigInt(8);\n// Affine Edwards-equation check only; this does not prove subgroup membership, canonical\n// encoding, prime-order base-point requirements, or identity exclusion.\nfunction isEdValidXY(Fp, CURVE, x, y) {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n/**\n * @param params - Curve parameters. See {@link EdwardsOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.\n * @returns Edwards point constructor. Generator validation here only checks\n * that `(Gx, Gy)` satisfies the affine Edwards equation.\n * RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`\n * are left to the caller's chosen parameters, since eager subgroup\n * validation here adds about 10-15ms to heavyweight imports like ed448.\n * The returned constructor also eagerly marks `Point.BASE` for W=6\n * precompute caching. Some code paths still assume\n * `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.\n * @throws If the curve parameters or Edwards overrides are invalid. {@link Error}\n * @example\n * ```ts\n * import { edwards } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * // Build a point constructor from explicit curve parameters, then use its base point.\n * const Point = edwards(jubjub.Point.CURVE());\n * Point.BASE.toHex();\n * ```\n */\nexport function edwards(params, extraOpts = {}) {\n validateObject(extraOpts, {}, {}, 'extraOpts');\n const opts = extraOpts;\n const validated = createCurveFields('edwards', params, opts, opts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor } = CURVE;\n // The unified add-2008-hwcd formulas (see EdwardsPoint.add/double) are complete —\n // exception-free for every input pair — only when a is a square and d a non-square in Fp\n // (Bernstein–Birkner–Joye–Lange–Peters, \"Twisted Edwards curves\", thm 3.3). The constant-time\n // kernels in curve.ts assume completeness, so an incomplete curve could silently produce\n // wrong results on exceptional inputs. Fail construction instead.\n if (FpLegendre(Fp, CURVE.a) !== 1)\n throw new Error('edwards: CURVE.a must be a square in Fp for complete addition formulas');\n if (FpLegendre(Fp, CURVE.d) !== -1)\n throw new Error('edwards: CURVE.d must be a non-square in Fp for complete addition formulas');\n validateObject(opts, {}, { uvRatio: 'function', randomBytes: 'function' });\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n // Coordinate and ZIP-215 bounds follow the base-field byte container, not scalar bytes.\n const MASK = _2n << (BigInt(Fp.BYTES * 8) - _1n);\n function isOdd(n) {\n if (!Fp.isOdd)\n throw new Error('Field does not have .isOdd()');\n return Fp.isOdd(n);\n }\n // sqrt(u/v)\n const uvRatio = opts.uvRatio === undefined\n ? (u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n }\n : opts.uvRatio;\n // Validate whether the passed curve params are valid.\n // equation ax² + y² = 1 + dx²y² should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Multiplication by param `a` sits on the double() / add() hot paths. For the common twists\n // a=-1 (ed25519, jubjub) and a=1 (ed448) the full field multiplication is replaced with\n // negation / identity. Selection depends only on public curve constants.\n const mulA = Fp.eql(CURVE.a, Fp.neg(Fp.ONE)) ? (x) => Fp.neg(x)\n : Fp.eql(CURVE.a, Fp.ONE) ? (x) => x\n : (x) => Fp.mul(CURVE.a, x); // prettier-ignore\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title, n, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n function aedpoint(other) {\n if (!(other instanceof Point))\n throw new Error('EdwardsPoint expected');\n }\n // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE, Fp.mul(CURVE.Gx, CURVE.Gy));\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ONE, Fp.ZERO);\n static Fp = Fp;\n static Fn = Fn;\n X;\n Y;\n Z;\n T;\n constructor(X, Y, Z, T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /**\n * Create one extended Edwards point from affine coordinates.\n * Does NOT validate that the point is on-curve or torsion-free.\n * Use `.assertValidity()` on adversarial inputs.\n */\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, Fp.ONE, Fp.mul(x, y));\n }\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes, zip215 = false) {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = Fp.sqr(y); // denominator is always non-0 mod p.\n const u = Fp.sub(y2, Fp.ONE); // u = y² - 1\n const v = Fp.sub(Fp.mulN(d, y2), a); // v = d y² - a.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('bad point: invalid y coordinate');\n const isXOdd = isOdd(x); // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && Fp.is0(x) && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = Fp.neg(x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(hex, zip215 = false) {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n precompute(windowSize = 6, isLazy = true) {\n wnaf.setWindowSize(this, windowSize);\n if (!isLazy)\n this.multiply(_2n); // random number\n return this;\n }\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity() {\n const p = this;\n const { a, d } = CURVE;\n // Keep generic Edwards validation fail-closed on the neutral point.\n // Even though ZERO is algebraically valid and can roundtrip through encodings, higher-level\n // callers often reach it only through broken hash/scalar plumbing; rejecting it here avoids\n // silently treating that degenerate state as an ordinary public point.\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = Fp.sqr(X); // X²\n const Y2 = Fp.sqr(Y); // Y²\n const Z2 = Fp.sqr(Z); // Z²\n const Z4 = Fp.sqr(Z2); // Z⁴\n const aX2 = Fp.mul(X2, a); // aX²\n const left = Fp.mul(Fp.add(aX2, Y2), Z2); // (aX² + Y²)Z²\n const right = Fp.add(Z4, Fp.mul(d, Fp.mul(X2, Y2))); // Z⁴ + dX²Y²\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = Fp.mul(X, Y);\n const ZT = Fp.mul(Z, T);\n if (!Fp.eql(XY, ZT))\n throw new Error('bad point: equation left != right (2)');\n }\n // Compare one point to another.\n equals(other) {\n aedpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = Fp.mul(X1, Z2);\n const X2Z1 = Fp.mul(X2, Z1);\n const Y1Z2 = Fp.mul(Y1, Z2);\n const Y2Z1 = Fp.mul(Y2, Z1);\n return Fp.eql(X1Z2, X2Z1) && Fp.eql(Y1Z2, Y2Z1);\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(Fp.neg(this.X), this.Y, this.Z, Fp.neg(this.T));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = Fp.sqr(X1); // A = X12\n const B = Fp.sqr(Y1); // B = Y12\n const C = Fp.mul(Fp.sqr(Z1), _2n); // C = 2*Z12\n const D = mulA(A); // D = a*A\n const x1y1 = Fp.addN(X1, Y1);\n const E = Fp.sub(Fp.subN(Fp.sqr(x1y1), A), B); // E = (X1+Y1)2-A-B\n const G = Fp.addN(D, B); // G = D+B\n const F = Fp.subN(G, C); // F = G-C\n const H = Fp.subN(D, B); // H = D-B\n const X3 = Fp.mul(E, F); // X3 = E*F\n const Y3 = Fp.mul(G, H); // Y3 = G*H\n const T3 = Fp.mul(E, H); // T3 = E*H\n const Z3 = Fp.mul(F, G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n aedpoint(other);\n const { d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = Fp.mul(X1, X2); // A = X1*X2\n const B = Fp.mul(Y1, Y2); // B = Y1*Y2\n const C = Fp.mul(Fp.mulN(T1, d), T2); // C = T1*d*T2\n const D = Fp.mul(Z1, Z2); // D = Z1*Z2\n // E = (X1+Y1)*(X2+Y2)-A-B\n const E = Fp.sub(Fp.subN(Fp.mulN(Fp.addN(X1, Y1), Fp.addN(X2, Y2)), A), B);\n const F = Fp.subN(D, C); // F = D-C\n const G = Fp.addN(D, C); // G = D+C\n const H = Fp.sub(B, mulA(A)); // H = B-a*A\n const X3 = Fp.mul(E, F); // X3 = E*F\n const Y3 = Fp.mul(G, H); // Y3 = G*H\n const T3 = Fp.mul(E, H); // T3 = E*H\n const Z3 = Fp.mul(F, G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aedpoint(other);\n return this.add(other.negate());\n }\n // Constant-time multiplication.\n multiply(scalar) {\n // 1 <= scalar < L\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In keygen/signing-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar))\n throw new RangeError('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);\n return normalize([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but\n // n and larger values are rejected instead of being reduced mod n to the identity point.\n multiplyUnsafe(scalar) {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar))\n throw new RangeError('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n)\n return Point.ZERO;\n if (this.is0() || scalar === _1n)\n return this;\n return wnaf.mulUnsafe(this, scalar, normalize);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Clears cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.clearCofactor().is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.mulUnsafe(this, CURVE.n).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ) {\n const p = this;\n let iz = invertedZ;\n if (iz != null && typeof iz !== 'bigint')\n throw new TypeError('\"invertedZ\" expected bigint, got type=' + typeof iz);\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? Fp.create(_8n) : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ONE };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this;\n // 2.8-3.8x speed-up vs naive\n if (cofactor === _2n)\n return this.double();\n if (cofactor === _4n)\n return this.double().double();\n if (cofactor === _8n)\n return this.double().double().double();\n return this.multiplyUnsafe(cofactor);\n }\n toBytes() {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= isOdd(x) ? 0x80 : 0;\n return bytes;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n // Keep constructor work cheap: subgroup/generator validation belongs to the caller's curve\n // parameters, and doing the extra checks here adds about 10-15ms to heavy module imports.\n // Callers that construct custom curves are responsible for supplying the correct base point.\n // try {\n // Point.BASE.assertValidity();\n // if (!Point.BASE.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n // } catch {\n // throw new Error('bad curve params: generator point');\n // }\n const normalize = (points) => normalizeZ(Point, points);\n const wnaf = new ScalarMultiplier(Point, randomBytes);\n // Enable W=6 wNAF precomputes. Slows down first publicKey computation.\n // Disable for tiny toy curves, with scalar fields < 6 bits.\n if (wnaf.bits >= 6)\n Point.BASE.precompute(6);\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points. Multiple Edwards representatives can describe the\n * same abstract wrapper element, so wrapper validity is not the same thing as\n * the hidden representative being torsion-free.\n * @param ep - Backing Edwards point.\n * @example\n * Base class for prime-order points like Ristretto255 and Decaf448.\n *\n * ```ts\n * import { ristretto255 } from '@noble/curves/ed25519.js';\n * const point = ristretto255.Point.BASE.multiply(2n);\n * ```\n */\nexport class PrimeEdwardsPoint {\n static BASE;\n static ZERO;\n static Fp;\n static Fn;\n ep;\n /**\n * Wrap one internal Edwards representative directly.\n * This is not a canonical encoding boundary: alternate Edwards\n * representatives may still describe the same abstract wrapper element.\n */\n constructor(ep) {\n this.ep = ep;\n }\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes) {\n notImplemented();\n }\n static fromHex(_hex) {\n notImplemented();\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n // Common implementations\n clearCofactor() {\n // no-op for the abstract prime-order wrapper group; this is about the\n // wrapper element, not the hidden Edwards representative.\n return this;\n }\n assertValidity() {\n // Keep wrapper validity at the abstract-group boundary. Canonical decode\n // may choose Edwards representatives that differ by small torsion, so\n // checking `this.ep.isTorsionFree()` here would reject valid wrapper points.\n this.ep.assertValidity();\n }\n /**\n * Return affine coordinates of the current internal Edwards representative.\n * This is a convenience helper, not a canonical Ristretto/Decaf encoding.\n * Equal abstract elements may expose different `x` / `y`; use\n * `toBytes()` / `fromBytes()` for canonical roundtrips.\n */\n toAffine(invertedZ) {\n return this.ep.toAffine(invertedZ);\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return this.toHex();\n }\n isTorsionFree() {\n // Abstract Ristretto/Decaf elements are already prime-order even when the\n // hidden Edwards representative is not torsion-free.\n return true;\n }\n isSmallOrder() {\n return false;\n }\n add(other) {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n subtract(other) {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return this.init(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return this.init(this.ep.double());\n }\n negate() {\n return this.init(this.ep.negate());\n }\n precompute(windowSize, isLazy) {\n this.ep.precompute(windowSize, isLazy);\n // Keep the wrapper identity stable like the backing Edwards API instead of\n // allocating a fresh wrapper around the same cached point.\n return this;\n }\n}\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n * @param Point - Edwards point constructor.\n * @param cHash - Hash function.\n * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.\n * @returns EdDSA helper namespace.\n * @throws If the hash function, options, or derived point operations are invalid. {@link Error}\n * @example\n * Initializes EdDSA signatures over given Edwards curve.\n *\n * ```ts\n * import { eddsa } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * import { sha512 } from '@noble/hashes/sha2.js';\n * const sigs = eddsa(jubjub.Point, sha512);\n * const { secretKey, publicKey } = sigs.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = sigs.sign(msg, secretKey);\n * const isValid = sigs.verify(sig, msg, publicKey);\n * ```\n */\nexport function eddsa(Point, cHash, eddsaOpts = {}) {\n validatePointCons(Point);\n if (typeof cHash !== 'function')\n throw new Error('\"hash\" function param is required');\n const hash = cHash;\n const opts = eddsaOpts;\n validateObject(opts, {}, {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n zip215: 'boolean',\n mapToCurve: 'function',\n toMontgomery: 'function',\n toMontgomerySecret: 'function',\n });\n const { prehash } = opts;\n const { BASE, Fp, Fn } = Point;\n const outputLen = hash.outputLen;\n const expectedLen = 2 * Fp.BYTES;\n // When hash metadata is available, reject incompatible EdDSA wrappers at construction time\n // instead of deferring the mismatch until the first keygen/sign call.\n if (outputLen !== undefined) {\n asafenumber(outputLen, 'hash.outputLen');\n if (outputLen !== expectedLen)\n throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);\n }\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const toMontgomery = opts.toMontgomery;\n const toMontgomerySecret = opts.toMontgomerySecret;\n const adjustScalarBytes = opts.adjustScalarBytes === undefined\n ? (bytes) => bytes\n : opts.adjustScalarBytes;\n const domain = opts.domain === undefined\n ? (data, ctx, phflag) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }\n : opts.domain; // NOOP\n // Parse an EdDSA digest as a little-endian integer and reduce it modulo the scalar field order.\n function modN_LE(hash) {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key) {\n const len = lengths.secretKey;\n abytes(key, lengths.secretKey, 'secretKey');\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = abytes(hash(key), 2 * len, 'hashedSecretKey');\n // Slice before clamping so in-place adjustors don't corrupt the prefix half.\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5\n * Also exposes the derived scalar/prefix tuple and point form reused by sign().\n */\n function getExtendedPublicKey(secretKey) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey) {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n // Hash domain-separated chunks into a little-endian scalar modulo the group order.\n function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {\n const msg = concatBytes(...msgs);\n return modN_LE(hash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n }\n /** Signs message with secret key. RFC8032 5.1.6 */\n function sign(msg, secretKey, options = {}) {\n validateObject(options, {}, {}, 'options');\n // Snapshot once: nonce and challenge must use the same invocation-time message bytes.\n msg = copyBytes(abytes(msg, undefined, 'message'));\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n // RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point\n // signature.\n // We intentionally keep the safe multiply() rejection here so a miswired all-zero hash provider\n // fails loudly instead of silently producing a degenerate signature.\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s))\n throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n // Keep the shared helper strict by default: RFC 8032 / NIST-style wrappers should reject\n // non-canonical encodings unless they explicitly opt into ZIP-215's more permissive decode rules.\n const verifyOpts = {\n zip215: opts.zip215,\n };\n /**\n * Verifies EdDSA signature against message and public key. RFC 8032 §§5.1.7 and 5.2.7.\n * A cofactored verification equation is checked.\n */\n function verify(sig, msg, publicKey, options = verifyOpts) {\n // Validate before destructuring so explicit null follows the standard options error.\n validateObject(options);\n // Preserve the wrapper-selected default for `{}` / `{ zip215: undefined }`, not just omitted opts.\n const { context } = options;\n const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215;\n const len = lengths.signature;\n sig = abytes(sig, len, 'signature');\n msg = abytes(msg, undefined, 'message');\n publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n if (zip215 !== undefined)\n abool(zip215, 'zip215');\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // ZIP-215 is more permissive than RFC 8032 / NIST186-5. Use it only for wrappers that\n // explicitly want consensus-style unreduced encoding acceptance.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n // RFC 8032 §§5.1.7/5.2.7 and FIPS 186-5 §§7.7.2/7.8.2 only decode A' and check the cofactored\n // verification equation; they do not add a separate low-order-public-key rejection here.\n // Strict mode still rejects small-order A' intentionally for SBS-style non-repudiation and to\n // avoid ambiguous verification outcomes where unusual low-order keys can make distinct\n // key/signature/message combinations verify.\n if (!zip215 && A.isSmallOrder())\n return false;\n // ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the\n // exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points.\n const k = hashDomainToScalar(context, r, publicKey, msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Check the cofactored verification equation via the curve cofactor h.\n // [h][S]B = [h]R + [h][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed) {\n seed = seed === undefined ? randomBytes(lengths.seed) : seed;\n return abytes(seed, lengths.seed, 'seed');\n }\n function isValidSecretKey(key) {\n return isBytes(key) && key.length === lengths.secretKey;\n }\n function isValidPublicKey(key, zip215) {\n try {\n // Preserve the wrapper-selected default for omitted / `undefined` ZIP-215 flags here too.\n return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215);\n }\n catch (error) {\n return false;\n }\n }\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /** Converts an Edwards public key to a companion Montgomery public key. */\n toMontgomery(publicKey) {\n if (toMontgomery === undefined)\n throw new Error('Montgomery conversion is not supported for this curve');\n return toMontgomery(Point.fromBytes(publicKey));\n },\n toMontgomerySecret(secretKey) {\n if (toMontgomerySecret === undefined)\n throw new Error('Montgomery conversion is not supported for this curve');\n return toMontgomerySecret(secretKey);\n },\n };\n Object.freeze(lengths);\n Object.freeze(utils);\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\n","/**\n * Montgomery curve methods. It's not really whole montgomery curve,\n * just bunch of very specific methods for X25519 / X448 from\n * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, aInRange, bytesToNumberLE, copyBytes, numberToBytesLE, randomBytes, validateObject, } from \"../utils.js\";\nimport { createKeygen } from \"./curve.js\";\nimport { mod } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\n// cswap from RFC7748 \"example code\", adapted to BigInt.\n//\n// RFC: \"dummy = mask(swap) AND (x_2 XOR x_3), where mask(swap) is the all-1 or all-0 word of the\n// same length as x_2 and x_3\". On fixed-width machine words both cases cost the same. BigInt has\n// no fixed width, so a {0n, 1n} selector does not: V8 short-circuits `0n * v` - and, identically,\n// `0n & v`, `v + 0n`, `v - 0n` - to a no-op, while `1n * v` is a real multiply. The ladder calls\n// this with swap = k_t XOR k_(t+1), which would make total running time a linear function of how\n// often adjacent bits of the secret scalar differ: remotely measurable, and worth ~4 bits of a\n// long-term key.\n//\n// So select with a full-width mask instead, and interpolate rather than mask off a dummy.\n/**\n * Selector for cswap(): `P` to keep, `P + 1` to swap, chosen by the low bit of `swap`.\n * Higher bits are ignored, and `swap` is passed in whole rather than as a {0n, 1n} bit on\n * purpose: `P + (swap & _1n)` would short-circuit the addition whenever the bit is clear, which\n * is the very leak this construction avoids, one round-trip further down. Subtracting `swap`\n * with its low bit cleared keeps every operand full-width instead.\n * @param P - Field modulus.\n * @param swap - Value whose low bit selects; ignored above that bit.\n * @returns `P` when the low bit is clear, `P + 1` when it is set.\n */\nfunction cmask(P, swap) {\n return P + swap - ((swap >> _1n) << _1n);\n}\n/**\n * Swap two field elements when `mask` is `P + 1`, keep them when it is `P`:\n *\n * d = 6P + x_3 - x_2\n * x_2' = d * mask + x_2 (mod P) x_3' = (x_2 + x_3) - x_2'\n *\n * The extra `6P * mask` vanishes modulo P, so `mask === P` leaves x_2 and `mask === P + 1`\n * leaves x_3. Without the offset, the reduction dividend changes sign with input order and crosses\n * BigInt limb boundaries; those classes measured differently on the tested Node/V8 build. For\n * canonical inputs, the deliberately left-associative `offset + x_3 - x_2` is between 5P and 7P,\n * keeping the dividend positive and in one word-count band for both RFC fields and masks. Six is\n * the smallest coefficient `c` for which the shared offset `cP` has that property.\n *\n * This reduced the tested sign/size timing ratios, but JavaScript BigInt has no constant-time\n * contract and the contents of the multiply and remainder still vary. Valid ladder states can\n * contain genuine zero coordinates; this construction does not mask those value-shape effects.\n * Computing `x_3'` independently as `((6P + x_2 - x_3) * mask + x_3) % P` is more symmetric.\n * On the tested Node/V8 build, it reduced the timing difference between keeping `(0, v)` and\n * swapping `(v, 0)`—both return `(0, v)`—from about 10%/13% for X25519/X448 to about 3%.\n * Successful calls cannot reach that zero-in-the-first-output case. For the case they can reach,\n * swapping `(0, v)` and keeping `(v, 0)` both return `(v, 0)`; the difference instead grew from\n * about 0.7%/1.1% to 2.7%/2.8%. The extra multiply/remainder also made public\n * `getSharedSecret()` about 16% slower. The retained one-remainder form measured about 2.5%\n * slower than the prior helper for public X25519 `getSharedSecret()` in the same environment.\n * x_3' falls out of the sum, which a swap leaves invariant: no second multiply or reduction is\n * needed. Bind `6P` once per field so production and the timing regression exercise the same\n * configured helper without paying for the multiplication in every ladder round.\n *\n * The returned function is called twice per ladder round, so it validates nothing. Both elements\n * MUST already be reduced mod P; unreduced input silently corrupts the kept-side output.\n * @param P - Field modulus.\n * @returns A field-bound swap function taking mask, x_2, and x_3.\n */\nfunction cswap(P) {\n const offset = BigInt(6) * P;\n return (mask, x_2, x_3) => {\n const sum = x_2 + x_3;\n const d = offset + x_3 - x_2;\n const a = (d * mask + x_2) % P;\n return { x_2: a, x_3: sum - a };\n };\n}\n/** Internal helpers, exported for tests only. Not part of the public API. */\nexport const __TEST = /* @__PURE__ */ Object.freeze({\n cmask,\n cswap,\n});\nfunction validateOpts(curve) {\n // Validate constructor config eagerly, but do not call user-provided hooks here:\n // `randomBytes` may be transcript-backed or otherwise contextual. Runtime type checks are\n // enough to fail fast on malformed configs without consuming user state.\n validateObject(curve, {\n P: 'bigint',\n type: 'string',\n adjustScalarBytes: 'function',\n powPminus2: 'function',\n }, {\n randomBytes: 'function',\n scalarMultBase: 'function',\n });\n return Object.freeze({ ...curve });\n}\n/**\n * @param curveDef - Montgomery curve definition.\n * @returns ECDH helper namespace.\n * @throws If the curve definition or derived shared point is invalid. {@link Error}\n * @example\n * Build an X25519 helper from curve parameters, then derive one public key.\n *\n * ```ts\n * import { montgomery } from '@noble/curves/abstract/montgomery.js';\n * const P = 2n ** 255n - 19n;\n * const mod = (num: bigint) => {\n * const out = num % P;\n * return out >= 0n ? out : out + P;\n * };\n * const pow = (num: bigint, power: bigint) => {\n * let res = 1n;\n * for (; power > 0n; power >>= 1n) {\n * if (power & 1n) res = mod(res * num);\n * num = mod(num * num);\n * }\n * return res;\n * };\n * const x25519 = montgomery({\n * P,\n * type: 'x25519',\n * adjustScalarBytes(bytes: Uint8Array) {\n * bytes[0] &= 248;\n * bytes[31] &= 127;\n * bytes[31] |= 64;\n * return bytes;\n * },\n * powPminus2(x) {\n * return pow(x, P - 2n);\n * },\n * });\n * const publicKey = x25519.getPublicKey(new Uint8Array(32).fill(1));\n * ```\n */\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;\n const mulBaseHook = CURVE.scalarMultBase;\n const is25519 = type === 'x25519';\n if (!is25519 && type !== 'x448')\n throw new Error('invalid type');\n const randomBytes_ = rand === undefined ? randomBytes : rand;\n const montgomeryBits = is25519 ? 255 : 448;\n const swap = cswap(P);\n const fieldLen = is25519 ? 32 : 56;\n const Gu = is25519 ? BigInt(9) : BigInt(5);\n // RFC 7748 #5:\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and\n // (156326 - 2) / 4 = 39081 for curve448/X448\n // const a = is25519 ? 486662n : 156326n;\n const a24 = is25519 ? BigInt(121665) : BigInt(39081);\n // RFC: x25519 \"the resulting integer is of the form 2^254 plus\n // eight times a value between 0 and 2^251 - 1 (inclusive)\"\n // x448: \"2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)\"\n const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);\n const maxAdded = is25519\n ? BigInt(8) * (_2n ** BigInt(251) - _1n)\n : BigInt(4) * (_2n ** BigInt(445) - _1n);\n const maxScalar = minScalar + maxAdded + _1n; // (inclusive)\n const modP = (n) => mod(n, P);\n const GuBytes = encodeU(Gu);\n function encodeU(u) {\n return numberToBytesLE(modP(u), fieldLen);\n }\n function decodeU(u) {\n const _u = copyBytes(abytes(u, fieldLen, 'uCoordinate'));\n // RFC: When receiving such an array, implementations of X25519\n // (but not X448) MUST mask the most significant bit in the final byte.\n if (is25519)\n _u[31] &= 127; // 0b0111_1111\n // RFC: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime. The non-canonical\n // values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224\n // - 1 through 2^448 - 1 for X448.\n return modP(bytesToNumberLE(_u));\n }\n function decodeScalar(scalar) {\n return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, 'scalar'))));\n }\n /**\n * u coordinates whose order divides the cofactor, on the curve and on its quadratic twist -\n * the ladder sends every one of them to zero. Same blocklist libsodium and post-CVE-2017-0379\n * Libgcrypt carry. decodeU() reduces mod P first, so the non-canonical encodings P and P + 1\n * collapse onto 0 and 1, and `type` admits no curve beyond these two, so both lists are total.\n *\n * Complete by construction: x-only doubling sends u to (u^2 - 1)^2 / 4u(u^2 + a*u + 1). Order 4\n * therefore needs (u^2 - 1)^2 === 0, i.e. u = +-1; order 2 needs u(u^2 + a*u + 1) === 0, and\n * a^2 - 4 is a non-residue on both curves, leaving u = 0. curve448 stops there (cofactor 4);\n * curve25519 (cofactor 8) adds the two order-8 roots below. Cross-checked by clearing the\n * cofactor with those same doublings over 200k random u: no sixth value exists.\n */\n const lowOrderU = new Set(is25519\n ? [\n _0n,\n _1n,\n P - _1n,\n BigInt('325606250916557431795983626356110631294008115727848805560023387167927233504'),\n BigInt('39382357235489614581723060781553021112529911719440698176882885853963445705823'),\n ]\n : [_0n, _1n, P - _1n]);\n function scalarMult(scalar, u) {\n // Some public keys are useless, of low-order. Curve author doesn't think\n // it needs to be validated, but we do it nonetheless.\n // https://cr.yp.to/ecdh.html#validate\n //\n // Reject them BEFORE the ladder. RFC 7748 #6.1 also permits detecting them from the\n // all-zero output, but that first runs all 255 rounds against the long-term secret,\n // handing an unauthenticated attacker a free timing oracle. Low-order inputs also drive\n // the ladder into a degenerate state (x_2 + z_2 === 0) whose extra zero-operand\n // multiplications amplify any residual key-dependent timing.\n const pointU = decodeU(u);\n if (lowOrderU.has(pointU))\n throw new Error('invalid private or public key received');\n const pu = montgomeryLadder(pointU, decodeScalar(scalar));\n // Unreachable for RFC 7748 clamped scalars, which are cofactor multiples smaller than the\n // group order; kept because adjustScalarBytes is caller-supplied.\n if (pu === _0n)\n throw new Error('invalid private or public key received');\n return encodeU(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n // With a curve-provided fixed-base hook (Edwards tables), the ladder is skipped, but the\n // contract — scalar validation, low-order rejection, encoding — stays identical.\n function scalarMultBase(scalar) {\n if (mulBaseHook === undefined)\n return scalarMult(scalar, GuBytes);\n const k = decodeScalar(scalar);\n aInRange('scalar', k, minScalar, maxScalar);\n const pu = modP(mulBaseHook(k));\n if (pu === _0n)\n throw new Error('invalid private or public key received');\n return encodeU(pu);\n }\n const getPublicKey = scalarMultBase;\n const getSharedSecret = scalarMult;\n /**\n * Montgomery x-only multiplication ladder for the selected X25519/X448 curve.\n * @param pointU - decoded Montgomery u coordinate for the selected curve\n * @param scalar - decoded clamped scalar by which the point is multiplied\n * @returns resulting Montgomery u coordinate for the selected curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, minScalar, maxScalar);\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n // The RFC tracks `swap` across rounds to hold k_t XOR k_(t+1); the low bit of `kx >> t` is\n // the same value, without the carried state. aInRange above pins bit (montgomeryBits - 1)\n // of k set and everything above it clear, so `kx >> t` is never zero and its width is a\n // function of t alone - never of a secret bit.\n const kx = k ^ (k >> _1n);\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const mask = cmask(P, kx >> t);\n ({ x_2, x_3 } = swap(mask, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // trailing cswap: the RFC's `swap` holds k_0 here, which is the low bit of k\n const mask = cmask(P, k);\n ({ x_2, x_3 } = swap(mask, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));\n const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent\n return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))\n }\n const lengths = {\n secretKey: fieldLen,\n publicKey: fieldLen,\n seed: fieldLen,\n };\n const randomSecretKey = (seed) => {\n seed = seed === undefined ? randomBytes_(fieldLen) : seed;\n abytes(seed, lengths.seed, 'seed');\n // Reuse caller-supplied seed bytes verbatim; clamping is deferred until\n // decodeScalar(...) when the secret key is actually used.\n return seed;\n };\n const utils = { randomSecretKey };\n Object.freeze(lengths);\n Object.freeze(utils);\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getSharedSecret,\n getPublicKey,\n scalarMult,\n scalarMultBase,\n utils,\n GuBytes: GuBytes.slice(),\n lengths,\n });\n}\n","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport {} from \"./abstract/curve.js\";\nimport { eddsa, edwards, PrimeEdwardsPoint, } from \"./abstract/edwards.js\";\nimport { createFROST } from \"./abstract/frost.js\";\nimport { _DST_scalar, createHasher, expand_message_xmd, } from \"./abstract/hash-to-curve.js\";\nimport { FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2, } from \"./abstract/modular.js\";\nimport { montgomery } from \"./abstract/montgomery.js\";\nimport { createOPRF } from \"./abstract/oprf.js\";\nimport { asciiToBytes, bytesToNumberLE, equalBytes } from \"./utils.js\";\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed');\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\nfunction ed25519_pow_2_252_3(x) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ This is x^((p-5)/8); multiply by x once more to get x^((p+3)/8).\n return { pow_p_5_8, b2 };\n}\n// Mutates and returns the provided 32-byte buffer in place.\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// sqrt(u/v). Returns `{ isValid, value }`; on non-squares `value` is still a\n// dummy root-shaped field element so callers can stay constant-time.\nfunction uvRatio(u, v) {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\n// Public field alias stays stricter than the RFC 8032 Appendix A sample code:\n// `Fp.inv(0)` throws instead of returning `0`.\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nfunction toMontgomery(point) {\n // Birational map from Ed25519 to Curve25519 / X25519:\n // (u, v) = ((1 + y) / (1 - y), sqrt(-486664) * u / x)\n // (x, y) = (sqrt(-486664) * u / v, (u - 1) / (u + 1))\n const { y } = point;\n return Fp.toBytes(Fp.div(_1n + y, _1n - y));\n}\nfunction toMontgomerySecret(secretKey) {\n const size = ed25519_Point.Fp.BYTES;\n abytes(secretKey, size);\n return adjustScalarBytes(sha512(secretKey.subarray(0, size))).subarray(0, size);\n}\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\n// RFC 8032 `dom2` helper for ctx/ph variants only. Plain Ed25519 keeps the\n// empty-domain path in `ed()` and would be wrong if routed through this helper.\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(asciiToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nfunction ed(opts) {\n // Ed25519 keeps ZIP-215 default verification semantics for consensus compatibility.\n return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, toMontgomery, toMontgomerySecret, zip215: true }, opts));\n}\n/**\n * ed25519 curve with EdDSA signatures.\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Generate one Ed25519 keypair, sign a message, and verify it.\n *\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false });\n * ```\n */\nexport const ed25519 = /* @__PURE__ */ ed({});\n/**\n * Context version of ed25519 (ctx for domain separation). See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Sign and verify with Ed25519ctx under one explicit context.\n *\n * ```ts\n * const context = new TextEncoder().encode('docs');\n * const { secretKey, publicKey } = ed25519ctx.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ctx.sign(msg, secretKey, { context });\n * const isValid = ed25519ctx.verify(sig, msg, publicKey, { context });\n * ```\n */\nexport const ed25519ctx = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/**\n * Prehashed version of ed25519. See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Use the prehashed Ed25519 variant for one message.\n *\n * ```ts\n * const { secretKey, publicKey } = ed25519ph.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ph.sign(msg, secretKey);\n * const isValid = ed25519ph.verify(sig, msg, publicKey);\n * ```\n */\nexport const ed25519ph = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n/**\n * FROST threshold signatures over ed25519. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ed25519 signing.\n *\n * ```ts\n * const alice = ed25519_FROST.Identifier.derive('alice@example.com');\n * const bob = ed25519_FROST.Identifier.derive('bob@example.com');\n * const carol = ed25519_FROST.Identifier.derive('carol@example.com');\n * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ed25519_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-ED25519-SHA512-v1',\n Point: ed25519_Point,\n validatePoint: (p) => {\n p.assertValidity();\n if (!p.isTorsionFree())\n throw new Error('bad point: not torsion-free');\n },\n hash: sha512,\n // RFC 9591 keeps H2 undecorated here for RFC 8032 compatibility. In createFROST(),\n // `H2: ''` becomes an empty DST prefix; the built-in hashToScalar fallback treats\n // that the same as omitted DST, even though custom hooks can still observe the empty bag.\n H2: '',\n}))();\n/**\n * ECDH using curve25519 aka x25519.\n * `getSharedSecret()` rejects low-order peer inputs by default, and seeded\n * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it.\n * @example\n * Derive one shared secret between two X25519 peers.\n *\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const alicePublic = x25519.getPublicKey(alice.secretKey);\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519 = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n const powPminus2 = (x) => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n };\n return montgomery({\n P,\n type: 'x25519',\n powPminus2,\n adjustScalarBytes,\n // ~3x faster fixed-base: [k]B on the birationally-equivalent Edwards curve using cached\n // base tables, mapped back via u = (1+y)/(1-y) = (Z+Y)/(Z-Y) with one Fermat inversion.\n // Same construction as libsodium's crypto_scalarmult_curve25519_base.\n scalarMultBase: (k) => {\n // Clamped k (≈2^254) exceeds n, but B has prime order n, so [k]B == [k mod n]B.\n const kn = mod(k, ed25519_Point.Fn.ORDER);\n // k ≡ 0 (mod n): [k]B is the point at infinity, whose u is 0 in the x-only ladder;\n // returning 0 makes montgomery() reject it exactly like the ladder path.\n if (kn === _0n)\n return _0n;\n const p = ed25519_Point.BASE.multiply(kn);\n // Z-Y == 0 only at the identity, which kn != 0 excludes.\n return mod((p.Z + p.Y) * powPminus2(mod(p.Z - p.Y, P)), P);\n },\n });\n})();\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// RFC 9380 Appendix G.2.2 / Err4730 requires `sgn0(c1) = 0` for the Edwards\n// map constant below, so use the even root explicitly.\n// 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)();\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\nconst ELL2_J = /* @__PURE__ */ BigInt(486662);\n/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u) {\n // 4. c4 = (q - 5) / 8: tv2^c4 below reuses the ed25519_pow_2_252_3 addition chain,\n // whose pow_p_5_8 output is exactly x^((p-5)/8).\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let xd = Fp.add(tv1, Fp.ONE);\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = ed25519_pow_2_252_3(tv2).pow_p_5_8; // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let y1 = Fp.cmov(y12, y11, e1);\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n let y2 = Fp.cmov(y22, y21, e2);\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n// sgn0(c1) MUST equal 0\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))();\nfunction map_to_curve_elligator2_edwards25519(u) {\n // 1. (xMn, xMd, yMn, yMd) = map_to_curve_elligator2_curve25519(u)\n const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u);\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let yd = Fp.add(xMn, xMd);\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n // Noble normalizes the RFC rational representation to affine `{ x, y }`\n // before returning from the internal helper.\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n/**\n * Hashing to ed25519 points / field. RFC 9380 methods.\n * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the\n * internal map callback below consumes one field element bigint, not `[bigint]`.\n * @example\n * Hash one message onto the ed25519 curve.\n *\n * ```ts\n * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ed25519_hasher = /* @__PURE__ */ (() => createHasher(ed25519_Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n}))();\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// `SQRT_RATIO_M1(1, number)` specialization. Returns `{ isValid, value }`,\n// where non-squares get the nonnegative `sqrt(SQRT_M1 / number)` branch.\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\n// RFC 9496 §4.3.4 MAP parser: masks bit 255 and reduces modulo p for element\n// derivation. The decode path has the opposite contract and rejects that bit.\nconst bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n/**\n * Computes Elligator map for Ristretto255.\n * Primary formula source is RFC 9496 §4.3.4 MAP; RFC 9380 Appendix B builds\n * `hash_to_ristretto255` on top of this helper.\n * Returns an internal Edwards representative, not a public `_RistrettoPoint`.\n */\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519_CURVE;\n const r = Fp.mul(Fp.mulN(SQRT_M1, r0), r0); // 1\n const Ns = Fp.mul(Fp.addN(r, _1n), ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = Fp.mul(Fp.subN(c, Fp.mulN(d, r)), Fp.add(r, d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = Fp.mul(s, r0); // 6\n if (!Fp.isOdd(s_))\n s_ = Fp.neg(s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = Fp.sub(Fp.mulN(Fp.mulN(c, Fp.subN(r, _1n)), D_MINUS_ONE_SQ), D); // 9\n const s2 = Fp.sqrN(s);\n const W0 = Fp.mul(Fp.addN(s, s), D); // 10\n const W1 = Fp.mul(Nt, SQRT_AD_MINUS_ONE); // 11\n const W2 = Fp.sub(_1n, s2); // 12\n const W3 = Fp.add(_1n, s2); // 13\n return new ed25519_Point(Fp.mul(W0, W3), Fp.mul(W2, W1), Fp.mul(W1, W3), Fp.mul(W0, W2));\n}\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n // prettier-ignore\n static ZERO = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n // prettier-ignore\n static Fp = \n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn = \n /* @__PURE__ */ (() => Fn)();\n constructor(ep) {\n super(ep);\n }\n /**\n * Create one Ristretto255 point from affine Edwards coordinates.\n * This wraps the internal Edwards representative directly and is not a\n * canonical ristretto255 decoding path.\n * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.\n */\n static fromAffine(ap) {\n return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n }\n assertSame(other) {\n if (!(other instanceof _RistrettoPoint))\n throw new Error('RistrettoPoint expected');\n }\n init(ep) {\n return new _RistrettoPoint(ep);\n }\n static fromBytes(bytes) {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || Fp.isOdd(s))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = Fp.sqr(s);\n const u1 = Fp.add(_1n, Fp.mulN(a, s2)); // 4 (a is -1)\n const u2 = Fp.sub(_1n, Fp.mulN(a, s2)); // 5\n const u1_2 = Fp.sqr(u1);\n const u2_2 = Fp.sqr(u2);\n const v = Fp.sub(Fp.mulN(Fp.mulN(a, d), u1_2), u2_2); // 6\n const { isValid, value: I } = invertSqrt(Fp.mul(v, u2_2)); // 7\n const Dx = Fp.mul(I, u2); // 8\n const Dy = Fp.mul(Fp.mulN(I, Dx), v); // 9\n let x = Fp.mul(Fp.addN(s, s), Dx); // 10\n if (Fp.isOdd(x))\n x = Fp.neg(x); // 10\n const y = Fp.mul(u1, Dy); // 11\n const t = Fp.mul(x, y); // 12\n if (!isValid || Fp.isOdd(t) || Fp.is0(y))\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, Fp.ONE, t));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n return _RistrettoPoint.fromBytes(hexToBytes(hex));\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes() {\n let { X, Y, Z, T } = this.ep;\n const u1 = Fp.mul(Fp.add(Z, Y), Fp.sub(Z, Y)); // 1\n const u2 = Fp.mul(X, Y); // 2\n // Square root always exists\n const u2sq = Fp.sqr(u2);\n const { value: invsqrt } = invertSqrt(Fp.mul(u1, u2sq)); // 3\n const D1 = Fp.mul(invsqrt, u1); // 4\n const D2 = Fp.mul(invsqrt, u2); // 5\n const zInv = Fp.mul(Fp.mulN(D1, D2), T); // 6\n let D; // 7\n if (Fp.isOdd(Fp.mul(T, zInv))) {\n let _x = Fp.mul(Y, SQRT_M1);\n let _y = Fp.mul(X, SQRT_M1);\n X = _x;\n Y = _y;\n D = Fp.mul(D1, INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (Fp.isOdd(Fp.mul(X, zInv)))\n Y = Fp.neg(Y); // 9\n let s = Fp.mul(Fp.subN(Z, Y), D); // 10 (check footer's note, no sqrt(-a))\n if (Fp.isOdd(s))\n s = Fp.neg(s);\n return Fp.toBytes(s); // 11\n }\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other) {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = Fp.eql(Fp.mul(X1, Y2), Fp.mul(Y1, X2));\n const two = Fp.eql(Fp.mul(Y1, Y2), Fp.mul(X1, X2));\n return one || two;\n }\n is0() {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n/** Prime-order Ristretto255 group bundle. */\nexport const ristretto255 = /* @__PURE__ */ (() => {\n Object.freeze(_RistrettoPoint.BASE);\n Object.freeze(_RistrettoPoint.ZERO);\n Object.freeze(_RistrettoPoint.prototype);\n Object.freeze(_RistrettoPoint);\n return Object.freeze({ Point: _RistrettoPoint });\n})();\n/**\n * Hashing to ristretto255 points / field. RFC 9380 methods.\n * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496\n * §4.3.4 element-derivation building block, and `hashToScalar()` is a\n * library-specific helper for OPRF-style use.\n * @example\n * Hash one message onto ristretto255.\n *\n * ```ts\n * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ristretto255_hasher = \n/* @__PURE__ */ Object.freeze({\n Point: _RistrettoPoint,\n /**\n * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n * * There are no test vectors\n * * encodeToCurve / mapToCurve is undefined\n * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n * * hashToScalar is undefined too, so we just use OPRF implementation\n * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n (os2ip -> bytes255ToNumberLE)\n * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF\n version here. Using `bytes255ToNumblerLE` will create a different result\n if we use `bytes255ToNumberLE` as os2ip\n * * current version is closest to spec.\n */\n hashToCurve(msg, options) {\n // == 'hash_to_ristretto255'\n // Preserve explicit empty/invalid DST overrides so expand_message_xmd() can reject them.\n const DST = options?.DST === undefined ? 'ristretto255_XMD:SHA-512_R255MAP_RO_' : options.DST;\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n // NOTE: RFC 9380 incorrectly calls this function `ristretto255_map`.\n // In RFC 9496, `map` was the per-point function inside the construction.\n // That also led to confusion that `ristretto255_map` is `mapToCurve`.\n // It is not: it is the older hash-to-curve construction.\n return ristretto255_hasher.deriveToCurve(xmd);\n },\n hashToScalar(msg, options) {\n const DST = options?.DST === undefined ? _DST_scalar : options.DST;\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 64 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction from before\n * RFC 9380 was finalized.\n * It was later reused as a component in the newer\n * `hash_to_ristretto255` function defined in RFC 9380.\n */\n deriveToCurve(bytes) {\n // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n },\n});\n/**\n * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over ristretto255.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = ristretto255_oprf.oprf.generateKeyPair();\n * const blind = ristretto255_oprf.oprf.blind(input);\n * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const ristretto255_oprf = /* @__PURE__ */ (() => createOPRF({\n name: 'ristretto255-SHA512',\n Point: _RistrettoPoint,\n hash: sha512,\n hashToGroup: ristretto255_hasher.hashToCurve,\n hashToScalar: ristretto255_hasher.hashToScalar,\n}))();\n/**\n * FROST threshold signatures over ristretto255. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ristretto255 signing.\n *\n * ```ts\n * const alice = ristretto255_FROST.Identifier.derive('alice@example.com');\n * const bob = ristretto255_FROST.Identifier.derive('bob@example.com');\n * const carol = ristretto255_FROST.Identifier.derive('carol@example.com');\n * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ristretto255_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-RISTRETTO255-SHA512-v1',\n Point: _RistrettoPoint,\n validatePoint: (p) => {\n // Prime-order wrappers are torsion-free at the abstract-group level.\n p.assertValidity();\n },\n hash: sha512,\n}))();\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * The subgroup generated by `T` is `{ O, T, 2T, 3T, 4T, 5T, 6T, 7T }`; the\n * array below is that set, not the powers in that exact index order.\n * @example\n * Decode one known torsion point for debugging.\n *\n * ```ts\n * import { ED25519_TORSION_SUBGROUP, ed25519 } from '@noble/curves/ed25519.js';\n * const point = ed25519.Point.fromHex(ED25519_TORSION_SUBGROUP[1]);\n * ```\n */\nexport const ED25519_TORSION_SUBGROUP = /* @__PURE__ */ Object.freeze([\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n]);\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, aoutput, clean, } from \"./utils.js\";\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 §3 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC {\n oHash;\n iHash;\n blockLen;\n outputLen;\n canXOF = false;\n finished = false;\n destroyed = false;\n constructor(hash, key) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('expected Hash instance');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of the first block) of the outer hash here,\n // we can re-use it between multiple calls via clone.\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const buf = out.subarray(0, this.outputLen);\n // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n this.iHash.digestInto(buf);\n this.oHash.update(buf);\n this.oHash.digestInto(buf);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since the key\n // is already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.canXOF = canXOF;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\nexport const hmac = /* @__PURE__ */ (() => {\n const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());\n hmac_.create = (hash, key) => new _HMAC(hash, key);\n return hmac_;\n})();\n","/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}.\n * @module\n */\nimport { hmac } from \"./hmac.js\";\nimport { abytes, ahash, anumber, clean } from \"./utils.js\";\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @returns Pseudorandom key derived from input keying material.\n * @example\n * Run the HKDF extract step.\n * ```ts\n * import { extract } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\nexport function extract(hash, ikm, salt) {\n ahash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n return hmac(hash, salt, ikm);\n}\n// Shared mutable scratch byte for the RFC 5869 block counter `N`.\n// Safe to reuse because `expand()` is synchronous and resets it with `clean(...)` before returning.\nconst HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);\n// Shared RFC 5869 empty string for both `info === undefined` and the first-block `T(0)` input.\nconst EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets\n * (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes.\n * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @param _recycled - Internal destroyed extract hashes owned by the combined `hkdf()` call.\n * @returns Output keying material with the requested length.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * Run the HKDF expand step.\n * ```ts\n * import { expand } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);\n * ```\n */\nexport function expand(hash, prk, info, length = 32, _recycled) {\n ahash(hash);\n anumber(length, 'length');\n abytes(prk, undefined, 'prk');\n const olen = hash.outputLen;\n // RFC 5869 §2.3: PRK is \"a pseudorandom key of at least HashLen octets\".\n if (prk.length < olen)\n throw new Error('\"prk\" must be at least HashLen octets');\n // RFC 5869 §2.3 only bounds `L` by `<= 255*HashLen`; `L=0` is valid and yields empty OKM.\n if (length > 255 * olen)\n throw new Error('Length must be <= 255*HashLen');\n const blocks = Math.ceil(length / olen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n else\n abytes(info, undefined, 'info');\n if (!blocks) {\n if (_recycled)\n clean(prk); // Full hkdf() owns this intermediate PRK.\n return new Uint8Array();\n }\n // first L(ength) octets of T\n // The private PRK can become both T and a one-block result after HMAC consumes the key.\n const okm = _recycled && blocks === 1 ? prk : new Uint8Array(blocks * olen);\n const { iHash, oHash } = hmac.create(hash, prk);\n // Driving them directly also skips `_HMAC.digestInto`'s per-digest destroy.\n const T = _recycled ? prk : new Uint8Array(olen);\n // Full hkdf() donates one destroyed extract hash; standalone creates one alternating worker.\n const worker = blocks > 1 ? _recycled?.iHash || hash.create() : undefined;\n for (let counter = 0; counter < blocks - 1; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n const iWork = iHash._cloneInto(worker);\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n if (counter)\n iWork.update(T);\n iWork.update(info).update(HKDF_COUNTER).digestInto(T);\n oHash._cloneInto(worker).update(T).digestInto(T);\n okm.set(T, olen * counter);\n }\n // Midstates are key-equivalent: they allow computing HMAC(prk, ...) for any message.\n HKDF_COUNTER[0] = blocks; // Final block consumes them; retain worker for cleanup.\n if (blocks > 1)\n iHash.update(T);\n iHash.update(info).update(HKDF_COUNTER).digestInto(T);\n oHash.update(T).digestInto(T);\n okm.set(T, olen * (blocks - 1));\n iHash.destroy(); // Raw digests may leave key-derived base/worker state; wipe all explicitly.\n oHash.destroy();\n worker?.destroy();\n if (T !== okm)\n clean(T); // Wipe private T/PRK; standalone preserves caller-owned PRK.\n clean(HKDF_COUNTER);\n // Exact fit: return without the extra copy.\n if (length === okm.length)\n return okm;\n // Copy the requested prefix, then wipe the full buffer: its tail holds\n // up to HashLen-1 bytes of derived key material past `length`.\n const res = okm.slice(0, length);\n clean(okm);\n return res;\n}\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information bytes\n * @param length - length of output keying material in bytes.\n * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @returns Output keying material derived from the input key.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * HKDF (RFC 5869): derive keys from an initial input.\n * ```ts\n * import { hkdf } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = utf8ToBytes('application-key');\n * const okm = hkdf(sha256, inputKey, salt, info, 32);\n * ```\n */\nexport const hkdf = (hash, ikm, salt, info, length) => {\n ahash(hash);\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n const HMAC = hmac.create(hash, salt).update(ikm);\n // The intermediate PRK is secret key material; wipe it instead of\n // leaving it for GC.\n return expand(hash, HMAC.digest(), info, length, HMAC); // expand() owns and consumes it.\n};\n","import { chacha20poly1305 } from '@noble/ciphers/chacha.js';\nimport { x25519 } from '@noble/curves/ed25519.js';\nimport { extract, expand } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nexport const pureJsCrypto = {\n hashSHA256(data) {\n return sha256(data.subarray());\n },\n getHKDF(ck, ikm) {\n const prk = extract(sha256, ikm, ck);\n const okmU8Array = expand(sha256, prk, undefined, 96);\n const okm = okmU8Array;\n const k1 = okm.subarray(0, 32);\n const k2 = okm.subarray(32, 64);\n const k3 = okm.subarray(64, 96);\n return [k1, k2, k3];\n },\n generateX25519KeyPair() {\n const secretKey = x25519.utils.randomSecretKey();\n const publicKey = x25519.getPublicKey(secretKey);\n return {\n publicKey,\n privateKey: secretKey\n };\n },\n generateX25519KeyPairFromSeed(seed) {\n const publicKey = x25519.getPublicKey(seed);\n return {\n publicKey,\n privateKey: seed\n };\n },\n generateX25519SharedKey(privateKey, publicKey) {\n return x25519.getSharedSecret(privateKey.subarray(), publicKey.subarray());\n },\n chaCha20Poly1305Encrypt(plaintext, nonce, ad, k) {\n return chacha20poly1305(k, nonce, ad).encrypt(plaintext.subarray());\n },\n chaCha20Poly1305Decrypt(ciphertext, nonce, ad, k, dst) {\n return chacha20poly1305(k, nonce, ad).decrypt(ciphertext.subarray(), dst);\n }\n};\n//# sourceMappingURL=js.js.map","import { pureJsCrypto } from \"./js.js\";\nexport const defaultCrypto = pureJsCrypto;\n//# sourceMappingURL=index.browser.js.map","export function wrapCrypto(crypto) {\n return {\n generateKeypair: crypto.generateX25519KeyPair,\n dh: (keypair, publicKey) => crypto.generateX25519SharedKey(keypair.privateKey, publicKey).subarray(0, 32),\n encrypt: crypto.chaCha20Poly1305Encrypt,\n decrypt: crypto.chaCha20Poly1305Decrypt,\n hash: crypto.hashSHA256,\n hkdf: crypto.getHKDF\n };\n}\n//# sourceMappingURL=crypto.js.map","import { allocUnsafe as uint8ArrayAllocUnsafe } from 'uint8arrays/alloc';\nexport const uint16BEEncode = (value) => {\n const target = uint8ArrayAllocUnsafe(2);\n target[0] = value >> 8;\n target[1] = value;\n return target;\n};\nuint16BEEncode.bytes = 2;\nexport const uint16BEDecode = (data) => {\n if (data.length < 2) {\n throw RangeError('Could not decode int16BE');\n }\n if (data instanceof Uint8Array) {\n let value = 0;\n value += data[0] << 8;\n value += data[1];\n return value;\n }\n return data.getUint16(0);\n};\nuint16BEDecode.bytes = 2;\n//# sourceMappingURL=encoder.js.map","export function registerMetrics(metrics) {\n return {\n xxHandshakeSuccesses: metrics.registerCounter('libp2p_noise_xxhandshake_successes_total', {\n help: 'Total count of noise xxHandshakes successes_'\n }),\n xxHandshakeErrors: metrics.registerCounter('libp2p_noise_xxhandshake_error_total', {\n help: 'Total count of noise xxHandshakes errors'\n }),\n encryptedPackets: metrics.registerCounter('libp2p_noise_encrypted_packets_total', {\n help: 'Total count of noise encrypted packets successfully'\n }),\n decryptedPackets: metrics.registerCounter('libp2p_noise_decrypted_packets_total', {\n help: 'Total count of noise decrypted packets'\n }),\n decryptErrors: metrics.registerCounter('libp2p_noise_decrypt_errors_total', {\n help: 'Total count of noise decrypt errors'\n })\n };\n}\n//# sourceMappingURL=metrics.js.map","import { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { DUMP_SESSION_KEYS } from \"./constants.js\";\nexport function logLocalStaticKeys(s, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (s) {\n keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${uint8ArrayToString(s.publicKey, 'hex')}`);\n keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${uint8ArrayToString(s.privateKey, 'hex')}`);\n }\n else {\n keyLogger('Missing local static keys.');\n }\n}\nexport function logLocalEphemeralKeys(e, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (e) {\n keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${uint8ArrayToString(e.publicKey, 'hex')}`);\n keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${uint8ArrayToString(e.privateKey, 'hex')}`);\n }\n else {\n keyLogger('Missing local ephemeral keys.');\n }\n}\nexport function logRemoteStaticKey(rs, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (rs) {\n keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${uint8ArrayToString(rs.subarray(), 'hex')}`);\n }\n else {\n keyLogger('Missing remote static public key.');\n }\n}\nexport function logRemoteEphemeralKey(re, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (re) {\n keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${uint8ArrayToString(re.subarray(), 'hex')}`);\n }\n else {\n keyLogger('Missing remote ephemeral keys.');\n }\n}\nexport function logCipherState(cs1, cs2, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n keyLogger(`CIPHER_STATE_1 ${cs1.n.getUint64()} ${cs1.k && uint8ArrayToString(cs1.k, 'hex')}`);\n keyLogger(`CIPHER_STATE_2 ${cs2.n.getUint64()} ${cs2.k && uint8ArrayToString(cs2.k, 'hex')}`);\n}\n//# sourceMappingURL=logger.js.map","export class InvalidCryptoExchangeError extends Error {\n code;\n constructor(message = 'Invalid crypto exchange') {\n super(message);\n this.code = InvalidCryptoExchangeError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_EXCHANGE';\n}\n//# sourceMappingURL=errors.js.map","import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport const MIN_NONCE = 0;\n// For performance reasons, the nonce is represented as a JS `number`\n// Although JS `number` can safely represent integers up to 2 ** 53 - 1, we choose to only use\n// 4 bytes to store the data for performance reason.\n// This is a slight deviation from the noise spec, which describes the max nonce as 2 ** 64 - 2\n// The effect is that this implementation will need a new handshake to be performed after fewer messages are exchanged than other implementations with full uint64 nonces.\n// this MAX_NONCE is still a large number of messages, so the practical effect of this is negligible.\nexport const MAX_NONCE = 0xffffffff;\nconst ERR_MAX_NONCE = 'Cipherstate has reached maximum n, a new handshake must be performed';\n/**\n * The nonce is an uint that's increased over time.\n * Maintaining different representations help improve performance.\n */\nexport class Nonce {\n n;\n bytes;\n view;\n constructor(n = MIN_NONCE) {\n this.n = n;\n this.bytes = uint8ArrayAlloc(12);\n this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength);\n this.view.setUint32(4, n, true);\n }\n increment() {\n this.n++;\n // Even though we're treating the nonce as 8 bytes, RFC7539 specifies 12 bytes for a nonce.\n this.view.setUint32(4, this.n, true);\n }\n getBytes() {\n return this.bytes;\n }\n getUint64() {\n return this.n;\n }\n assertValue() {\n if (this.n > MAX_NONCE) {\n throw new Error(ERR_MAX_NONCE);\n }\n }\n}\n//# sourceMappingURL=nonce.js.map","import { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { InvalidCryptoExchangeError } from \"./errors.js\";\nimport { Nonce } from \"./nonce.js\";\n// Code in this file is a direct translation of a subset of the noise protocol https://noiseprotocol.org/noise.html,\n// agnostic to libp2p's usage of noise\nexport const ZEROLEN = uint8ArrayAlloc(0);\nexport class CipherState {\n k;\n n;\n crypto;\n constructor(crypto, k = undefined, n = 0) {\n this.crypto = crypto;\n this.k = k;\n this.n = new Nonce(n);\n }\n hasKey() {\n return Boolean(this.k);\n }\n encryptWithAd(ad, plaintext) {\n if (!this.hasKey()) {\n return plaintext;\n }\n this.n.assertValue();\n const e = this.crypto.encrypt(plaintext, this.n.getBytes(), ad, this.k);\n this.n.increment();\n return e;\n }\n decryptWithAd(ad, ciphertext, dst) {\n if (!this.hasKey()) {\n return ciphertext;\n }\n this.n.assertValue();\n const plaintext = this.crypto.decrypt(ciphertext, this.n.getBytes(), ad, this.k, dst);\n this.n.increment();\n return plaintext;\n }\n}\nexport class SymmetricState {\n cs;\n ck;\n h;\n crypto;\n constructor(crypto, protocolName) {\n this.crypto = crypto;\n const protocolNameBytes = uint8ArrayFromString(protocolName, 'utf-8');\n this.h = hashProtocolName(crypto, protocolNameBytes);\n this.ck = this.h;\n this.cs = new CipherState(crypto);\n }\n mixKey(ikm) {\n const [ck, tempK] = this.crypto.hkdf(this.ck, ikm);\n this.ck = ck;\n this.cs = new CipherState(this.crypto, tempK);\n }\n mixHash(data) {\n this.h = this.crypto.hash(new Uint8ArrayList(this.h, data));\n }\n encryptAndHash(plaintext) {\n const ciphertext = this.cs.encryptWithAd(this.h, plaintext);\n this.mixHash(ciphertext);\n return ciphertext;\n }\n decryptAndHash(ciphertext) {\n const plaintext = this.cs.decryptWithAd(this.h, ciphertext);\n this.mixHash(ciphertext);\n return plaintext;\n }\n split() {\n const [tempK1, tempK2] = this.crypto.hkdf(this.ck, ZEROLEN);\n return [new CipherState(this.crypto, tempK1), new CipherState(this.crypto, tempK2)];\n }\n}\nexport class AbstractHandshakeState {\n ss;\n s;\n e;\n rs;\n re;\n initiator;\n crypto;\n constructor(init) {\n const { crypto, protocolName, prologue, initiator, s, e, rs, re } = init;\n this.crypto = crypto;\n this.ss = new SymmetricState(crypto, protocolName);\n this.ss.mixHash(prologue);\n this.initiator = initiator;\n this.s = s;\n this.e = e;\n this.rs = rs;\n this.re = re;\n }\n writeE() {\n if (this.e) {\n throw new Error('ephemeral keypair is already set');\n }\n const e = this.crypto.generateKeypair();\n this.ss.mixHash(e.publicKey);\n this.e = e;\n return e.publicKey;\n }\n writeS() {\n if (!this.s) {\n throw new Error('static keypair is not set');\n }\n return this.ss.encryptAndHash(this.s.publicKey);\n }\n writeEE() {\n if (!this.e) {\n throw new Error('ephemeral keypair is not set');\n }\n if (!this.re) {\n throw new Error('remote ephemeral public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.e, this.re));\n }\n writeES() {\n if (this.initiator) {\n if (!this.e) {\n throw new Error('ephemeral keypair is not set');\n }\n if (!this.rs) {\n throw new Error('remote static public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.e, this.rs));\n }\n else {\n if (!this.s) {\n throw new Error('static keypair is not set');\n }\n if (!this.re) {\n throw new Error('remote ephemeral public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.s, this.re));\n }\n }\n writeSE() {\n if (this.initiator) {\n if (!this.s) {\n throw new Error('static keypair is not set');\n }\n if (!this.re) {\n throw new Error('remote ephemeral public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.s, this.re));\n }\n else {\n if (!this.e) {\n throw new Error('ephemeral keypair is not set');\n }\n if (!this.rs) {\n throw new Error('remote static public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.e, this.rs));\n }\n }\n readE(message, offset = 0) {\n if (this.re) {\n throw new Error('remote ephemeral public key is already set');\n }\n if (message.byteLength < offset + 32) {\n throw new Error('message is not long enough');\n }\n this.re = message.sublist(offset, offset + 32);\n this.ss.mixHash(this.re);\n }\n readS(message, offset = 0) {\n if (this.rs) {\n throw new Error('remote static public key is already set');\n }\n const cipherLength = 32 + (this.ss.cs.hasKey() ? 16 : 0);\n if (message.byteLength < offset + cipherLength) {\n throw new Error('message is not long enough');\n }\n const temp = message.sublist(offset, offset + cipherLength);\n this.rs = this.ss.decryptAndHash(temp);\n return cipherLength;\n }\n readEE() {\n this.writeEE();\n }\n readES() {\n this.writeES();\n }\n readSE() {\n this.writeSE();\n }\n}\n/**\n * A IHandshakeState that's optimized for the XX pattern\n */\nexport class XXHandshakeState extends AbstractHandshakeState {\n // e\n writeMessageA(payload) {\n return new Uint8ArrayList(this.writeE(), this.ss.encryptAndHash(payload));\n }\n // e, ee, s, es\n writeMessageB(payload) {\n const e = this.writeE();\n this.writeEE();\n const encS = this.writeS();\n this.writeES();\n return new Uint8ArrayList(e, encS, this.ss.encryptAndHash(payload));\n }\n // s, se\n writeMessageC(payload) {\n const encS = this.writeS();\n this.writeSE();\n return new Uint8ArrayList(encS, this.ss.encryptAndHash(payload));\n }\n // e\n readMessageA(message) {\n try {\n this.readE(message);\n return this.ss.decryptAndHash(message.sublist(32));\n }\n catch (e) {\n throw new InvalidCryptoExchangeError(`handshake stage 0 validation fail: ${e.message}`);\n }\n }\n // e, ee, s, es\n readMessageB(message) {\n try {\n this.readE(message);\n this.readEE();\n const consumed = this.readS(message, 32);\n this.readES();\n return this.ss.decryptAndHash(message.sublist(32 + consumed));\n }\n catch (e) {\n throw new InvalidCryptoExchangeError(`handshake stage 1 validation fail: ${e.message}`);\n }\n }\n // s, se\n readMessageC(message) {\n try {\n const consumed = this.readS(message);\n this.readSE();\n return this.ss.decryptAndHash(message.sublist(consumed));\n }\n catch (e) {\n throw new InvalidCryptoExchangeError(`handshake stage 2 validation fail: ${e.message}`);\n }\n }\n}\nfunction hashProtocolName(crypto, protocolName) {\n if (protocolName.length <= 32) {\n const h = uint8ArrayAlloc(32);\n h.set(protocolName);\n return h;\n }\n else {\n return crypto.hash(protocolName);\n }\n}\n//# sourceMappingURL=protocol.js.map","import { withArrayBuffer } from 'uint8arrays/with-array-buffer';\nexport const ECDSA_P_256_OID = '1.2.840.10045.3.1.7';\nexport const ECDSA_P_384_OID = '1.3.132.0.34';\nexport const ECDSA_P_521_OID = '1.3.132.0.35';\nexport async function generateECDSAKey(curve = 'P-256') {\n const keyPair = await crypto.subtle.generateKey({\n name: 'ECDSA',\n namedCurve: curve\n }, true, ['sign', 'verify']);\n return {\n publicKey: await crypto.subtle.exportKey('jwk', keyPair.publicKey),\n privateKey: await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n };\n}\nexport async function hashAndSign(key, msg, options) {\n const privateKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['sign']);\n options?.signal?.throwIfAborted();\n const signature = await crypto.subtle.sign({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, privateKey, withArrayBuffer(msg.subarray()));\n options?.signal?.throwIfAborted();\n return new Uint8Array(signature, 0, signature.byteLength);\n}\nexport async function hashAndVerify(key, sig, msg, options) {\n const publicKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['verify']);\n options?.signal?.throwIfAborted();\n const result = await crypto.subtle.verify({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, publicKey, withArrayBuffer(sig), withArrayBuffer(msg.subarray()));\n options?.signal?.throwIfAborted();\n return result;\n}\n//# sourceMappingURL=index.js.map","import { Uint8ArrayList } from 'uint8arraylist';\nconst TAG_MASK = parseInt('11111', 2);\nconst LONG_LENGTH_MASK = parseInt('10000000', 2);\nconst LONG_LENGTH_BYTES_MASK = parseInt('01111111', 2);\nconst decoders = {\n 0x0: readSequence,\n 0x1: readSequence,\n 0x2: readInteger,\n 0x3: readBitString,\n 0x4: readOctetString,\n 0x5: readNull,\n 0x6: readObjectIdentifier,\n 0x10: readSequence,\n 0x16: readSequence,\n 0x30: readSequence\n};\nexport function decodeDer(buf, context = { offset: 0 }) {\n const tag = buf[context.offset] & TAG_MASK;\n context.offset++;\n if (decoders[tag] != null) {\n return decoders[tag](buf, context);\n }\n throw new Error('No decoder for tag ' + tag);\n}\nfunction readLength(buf, context) {\n let length = 0;\n if ((buf[context.offset] & LONG_LENGTH_MASK) === LONG_LENGTH_MASK) {\n // long length\n const count = buf[context.offset] & LONG_LENGTH_BYTES_MASK;\n let str = '0x';\n context.offset++;\n for (let i = 0; i < count; i++, context.offset++) {\n if (context.offset >= buf.byteLength) {\n throw new Error('invalid DER element length');\n }\n str += buf[context.offset].toString(16).padStart(2, '0');\n }\n length = parseInt(str, 16);\n }\n else {\n length = buf[context.offset];\n context.offset++;\n }\n // length can be NaN (indefinite-form 0x80), negative, or larger than the\n // bytes that remain; reject all three\n if (!Number.isInteger(length) || length < 0 || length > buf.byteLength - context.offset) {\n throw new Error('invalid DER element length');\n }\n return length;\n}\nfunction readSequence(buf, context) {\n readLength(buf, context);\n const entries = [];\n while (true) {\n if (context.offset >= buf.byteLength) {\n break;\n }\n const result = decodeDer(buf, context);\n if (result === null) {\n break;\n }\n entries.push(result);\n }\n return entries;\n}\nfunction readInteger(buf, context) {\n const length = readLength(buf, context);\n const start = context.offset;\n const end = context.offset + length;\n const vals = [];\n for (let i = start; i < end; i++) {\n if (i === start && buf[i] === 0) {\n continue;\n }\n vals.push(buf[i]);\n }\n context.offset += length;\n return Uint8Array.from(vals);\n}\nfunction readObjectIdentifier(buf, context) {\n const count = readLength(buf, context);\n const finalOffset = context.offset + count;\n const byte = buf[context.offset];\n context.offset++;\n let val1 = 0;\n let val2 = 0;\n if (byte < 40) {\n val1 = 0;\n val2 = byte;\n }\n else if (byte < 80) {\n val1 = 1;\n val2 = byte - 40;\n }\n else {\n val1 = 2;\n val2 = byte - 80;\n }\n let oid = `${val1}.${val2}`;\n let num = [];\n while (context.offset < finalOffset) {\n const byte = buf[context.offset];\n context.offset++;\n // remove msb\n num.push(byte & 0b01111111);\n if (byte < 128) {\n num.reverse();\n // reached the end of the encoding\n let val = 0;\n for (let i = 0; i < num.length; i++) {\n val += num[i] << (i * 7);\n }\n oid += `.${val}`;\n num = [];\n }\n }\n return oid;\n}\nfunction readNull(buf, context) {\n context.offset++;\n return null;\n}\nfunction readBitString(buf, context) {\n const length = readLength(buf, context);\n const unusedBits = buf[context.offset];\n context.offset++;\n const bytes = buf.subarray(context.offset, context.offset + length - 1);\n context.offset += length;\n if (unusedBits !== 0) {\n // need to shift all bytes along by this many bits\n throw new Error('Unused bits in bit string is unimplemented');\n }\n return bytes;\n}\nfunction readOctetString(buf, context) {\n const length = readLength(buf, context);\n const bytes = buf.subarray(context.offset, context.offset + length);\n context.offset += length;\n return bytes;\n}\nfunction encodeNumber(value) {\n let number = value.toString(16);\n if (number.length % 2 === 1) {\n number = '0' + number;\n }\n const array = new Uint8ArrayList();\n for (let i = 0; i < number.length; i += 2) {\n array.append(Uint8Array.from([parseInt(`${number[i]}${number[i + 1]}`, 16)]));\n }\n return array;\n}\nfunction encodeLength(bytes) {\n if (bytes.byteLength < 128) {\n return Uint8Array.from([bytes.byteLength]);\n }\n // long length\n const length = encodeNumber(bytes.byteLength);\n return new Uint8ArrayList(Uint8Array.from([\n length.byteLength | LONG_LENGTH_MASK\n ]), length);\n}\nexport function encodeInteger(value) {\n const contents = new Uint8ArrayList();\n const mask = 0b10000000;\n const positive = (value.subarray()[0] & mask) === mask;\n if (positive) {\n contents.append(Uint8Array.from([0]));\n }\n contents.append(value);\n return new Uint8ArrayList(Uint8Array.from([0x02]), encodeLength(contents), contents);\n}\nexport function encodeBitString(value) {\n // unused bits is always 0 with full-byte-only values\n const unusedBits = Uint8Array.from([0]);\n const contents = new Uint8ArrayList(unusedBits, value);\n return new Uint8ArrayList(Uint8Array.from([0x03]), encodeLength(contents), contents);\n}\nexport function encodeOctetString(value) {\n return new Uint8ArrayList(Uint8Array.from([0x04]), encodeLength(value), value);\n}\nexport function encodeSequence(values, tag = 0x30) {\n const output = new Uint8ArrayList();\n for (const buf of values) {\n output.append(buf);\n }\n return new Uint8ArrayList(Uint8Array.from([tag]), encodeLength(output), output);\n}\n//# sourceMappingURL=der.js.map","import { InvalidParametersError } from '@libp2p/interface';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { decodeDer, encodeBitString, encodeInteger, encodeOctetString, encodeSequence } from \"../rsa/der.js\";\nimport { ECDSAPrivateKey as ECDSAPrivateKeyClass, ECDSAPublicKey as ECDSAPublicKeyClass } from \"./ecdsa.js\";\nimport { generateECDSAKey } from \"./index.js\";\n// 1.2.840.10045.3.1.7 prime256v1 (ANSI X9.62 named elliptic curve)\nconst OID_256 = Uint8Array.from([0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07]);\n// 1.3.132.0.34 secp384r1 (SECG (Certicom) named elliptic curve)\nconst OID_384 = Uint8Array.from([0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22]);\n// 1.3.132.0.35 secp521r1 (SECG (Certicom) named elliptic curve)\nconst OID_521 = Uint8Array.from([0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23]);\nconst P_256_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-256'\n};\nconst P_384_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-384'\n};\nconst P_521_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-521'\n};\nconst P_256_KEY_LENGTH = 32;\nconst P_384_KEY_LENGTH = 48;\nconst P_521_KEY_LENGTH = 66;\nexport function unmarshalECDSAPrivateKey(bytes) {\n const message = decodeDer(bytes);\n return pkiMessageToECDSAPrivateKey(message);\n}\nexport function pkiMessageToECDSAPrivateKey(message) {\n const privateKey = message[1];\n const d = uint8ArrayToString(privateKey, 'base64url');\n const coordinates = message[2][1][0];\n const offset = 1;\n let x;\n let y;\n if (privateKey.byteLength === P_256_KEY_LENGTH) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_256_KEY_LENGTH), 'base64url');\n y = uint8ArrayToString(coordinates.subarray(offset + P_256_KEY_LENGTH), 'base64url');\n return new ECDSAPrivateKeyClass({\n ...P_256_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n });\n }\n if (privateKey.byteLength === P_384_KEY_LENGTH) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_384_KEY_LENGTH), 'base64url');\n y = uint8ArrayToString(coordinates.subarray(offset + P_384_KEY_LENGTH), 'base64url');\n return new ECDSAPrivateKeyClass({\n ...P_384_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n });\n }\n if (privateKey.byteLength === P_521_KEY_LENGTH) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_521_KEY_LENGTH), 'base64url');\n y = uint8ArrayToString(coordinates.subarray(offset + P_521_KEY_LENGTH), 'base64url');\n return new ECDSAPrivateKeyClass({\n ...P_521_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n });\n }\n throw new InvalidParametersError(`Private key length was wrong length, got ${privateKey.byteLength}, expected 32, 48 or 66`);\n}\nexport function unmarshalECDSAPublicKey(bytes) {\n const message = decodeDer(bytes);\n return pkiMessageToECDSAPublicKey(message);\n}\nexport function pkiMessageToECDSAPublicKey(message) {\n const coordinates = message[1][1][0];\n const offset = 1;\n let x;\n let y;\n if (coordinates.byteLength === ((P_256_KEY_LENGTH * 2) + 1)) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_256_KEY_LENGTH), 'base64url');\n y = uint8ArrayToString(coordinates.subarray(offset + P_256_KEY_LENGTH), 'base64url');\n return new ECDSAPublicKeyClass({\n ...P_256_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n });\n }\n if (coordinates.byteLength === ((P_384_KEY_LENGTH * 2) + 1)) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_384_KEY_LENGTH), 'base64url');\n y = uint8ArrayToString(coordinates.subarray(offset + P_384_KEY_LENGTH), 'base64url');\n return new ECDSAPublicKeyClass({\n ...P_384_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n });\n }\n if (coordinates.byteLength === ((P_521_KEY_LENGTH * 2) + 1)) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_521_KEY_LENGTH), 'base64url');\n y = uint8ArrayToString(coordinates.subarray(offset + P_521_KEY_LENGTH), 'base64url');\n return new ECDSAPublicKeyClass({\n ...P_521_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n });\n }\n throw new InvalidParametersError(`coordinates were wrong length, got ${coordinates.byteLength}, expected 65, 97 or 133`);\n}\nexport function privateKeyToPKIMessage(privateKey) {\n return encodeSequence([\n encodeInteger(Uint8Array.from([1])), // header\n encodeOctetString(uint8ArrayFromString(privateKey.d ?? '', 'base64url')), // body\n encodeSequence([\n getOID(privateKey.crv)\n ], 0xA0),\n encodeSequence([\n encodeBitString(new Uint8ArrayList(Uint8Array.from([0x04]), uint8ArrayFromString(privateKey.x ?? '', 'base64url'), uint8ArrayFromString(privateKey.y ?? '', 'base64url')))\n ], 0xA1)\n ]).subarray();\n}\nexport function publicKeyToPKIMessage(publicKey) {\n return encodeSequence([\n encodeInteger(Uint8Array.from([1])), // header\n encodeSequence([\n getOID(publicKey.crv)\n ], 0xA0),\n encodeSequence([\n encodeBitString(new Uint8ArrayList(Uint8Array.from([0x04]), uint8ArrayFromString(publicKey.x ?? '', 'base64url'), uint8ArrayFromString(publicKey.y ?? '', 'base64url')))\n ], 0xA1)\n ]).subarray();\n}\nfunction getOID(curve) {\n if (curve === 'P-256') {\n return OID_256;\n }\n if (curve === 'P-384') {\n return OID_384;\n }\n if (curve === 'P-521') {\n return OID_521;\n }\n throw new InvalidParametersError(`Invalid curve ${curve}`);\n}\nexport async function generateECDSAKeyPair(curve = 'P-256') {\n const key = await generateECDSAKey(curve);\n return new ECDSAPrivateKeyClass(key.privateKey);\n}\nexport function ensureECDSAKey(key, length) {\n key = Uint8Array.from(key ?? []);\n if (key.length !== length) {\n throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`);\n }\n return key;\n}\n//# sourceMappingURL=utils.js.map","import { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport { identity } from 'multiformats/hashes/identity';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { publicKeyToProtobuf } from \"../index.js\";\nimport { hashAndVerify, hashAndSign } from \"./index.js\";\nimport { privateKeyToPKIMessage, publicKeyToPKIMessage } from \"./utils.js\";\nexport class ECDSAPublicKey {\n type = 'ECDSA';\n jwk;\n _raw;\n constructor(jwk) {\n this.jwk = jwk;\n }\n get raw() {\n if (this._raw == null) {\n this._raw = publicKeyToPKIMessage(this.jwk);\n }\n return this._raw;\n }\n toMultihash() {\n return identity.digest(publicKeyToProtobuf(this));\n }\n toCID() {\n return CID.createV1(114, this.toMultihash());\n }\n toString() {\n return base58btc.encode(this.toMultihash().bytes).substring(1);\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n async verify(data, sig, options) {\n return hashAndVerify(this.jwk, sig, data, options);\n }\n}\nexport class ECDSAPrivateKey {\n type = 'ECDSA';\n jwk;\n publicKey;\n _raw;\n constructor(jwk) {\n this.jwk = jwk;\n this.publicKey = new ECDSAPublicKey({\n crv: jwk.crv,\n ext: jwk.ext,\n key_ops: ['verify'],\n kty: 'EC',\n x: jwk.x,\n y: jwk.y\n });\n }\n get raw() {\n if (this._raw == null) {\n this._raw = privateKeyToPKIMessage(this.jwk);\n }\n return this._raw;\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n async sign(message, options) {\n return hashAndSign(this.jwk, message, options);\n }\n}\n//# sourceMappingURL=ecdsa.js.map","/**\n * Signing a message failed\n */\nexport class SigningError extends Error {\n constructor(message = 'An error occurred while signing a message') {\n super(message);\n this.name = 'SigningError';\n }\n}\n/**\n * Verifying a message signature failed\n */\nexport class VerificationError extends Error {\n constructor(message = 'An error occurred while verifying a message') {\n super(message);\n this.name = 'VerificationError';\n }\n}\n/**\n * WebCrypto was not available in the current context\n */\nexport class WebCryptoMissingError extends Error {\n constructor(message = 'Missing Web Crypto API') {\n super(message);\n this.name = 'WebCryptoMissingError';\n }\n}\n//# sourceMappingURL=errors.js.map","import { WebCryptoMissingError } from \"../errors.js\";\n// Check native crypto exists and is enabled (in insecure browser contexts\n// `globalThis.crypto` exists but `globalThis.crypto.subtle` does not).\nexport default {\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto?.subtle == null) {\n throw new WebCryptoMissingError('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api');\n }\n return nativeCrypto;\n }\n};\n//# sourceMappingURL=index.js.map","import { ed25519 as ed } from '@noble/curves/ed25519.js';\nimport { toString as uint8arrayToString } from 'uint8arrays/to-string';\nimport { withArrayBuffer } from 'uint8arrays/with-array-buffer';\nimport crypto from \"../../webcrypto/index.js\";\nconst PUBLIC_KEY_BYTE_LENGTH = 32;\nconst PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32;\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength };\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\n// memoize support result to skip additional awaits every time we use an ed key\nlet ed25519Supported;\nconst webCryptoEd25519SupportedPromise = (async () => {\n try {\n await crypto.get().subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']);\n return true;\n }\n catch {\n return false;\n }\n})();\nexport function generateKey() {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomSecretKey();\n const publicKey = ed.getPublicKey(privateKeyRaw);\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\nexport function generateKeyFromSeed(seed) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.');\n }\n else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.');\n }\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed;\n const publicKey = ed.getPublicKey(privateKeyRaw);\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\nasync function hashAndSignWebCrypto(privateKey, msg) {\n let privateKeyRaw;\n if (privateKey.length === PRIVATE_KEY_BYTE_LENGTH) {\n privateKeyRaw = privateKey.subarray(0, 32);\n }\n else {\n privateKeyRaw = privateKey;\n }\n const jwk = {\n crv: 'Ed25519',\n kty: 'OKP',\n x: uint8arrayToString(privateKey.subarray(32), 'base64url'),\n d: uint8arrayToString(privateKeyRaw, 'base64url'),\n ext: true,\n key_ops: ['sign']\n };\n const key = await crypto.get().subtle.importKey('jwk', jwk, { name: 'Ed25519' }, true, ['sign']);\n const sig = await crypto.get().subtle.sign({ name: 'Ed25519' }, key, withArrayBuffer(msg instanceof Uint8Array ? msg : msg.subarray()));\n return new Uint8Array(sig, 0, sig.byteLength);\n}\nexport function hashAndSignNoble(privateKey, msg) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);\n}\nexport async function hashAndSign(privateKey, msg) {\n if (ed25519Supported == null) {\n ed25519Supported = await webCryptoEd25519SupportedPromise;\n }\n if (ed25519Supported) {\n return hashAndSignWebCrypto(privateKey, msg);\n }\n return hashAndSignNoble(privateKey, msg);\n}\nasync function hashAndVerifyWebCrypto(publicKey, sig, msg) {\n if (publicKey.buffer instanceof ArrayBuffer) {\n const key = await crypto.get().subtle.importKey('raw', publicKey.buffer, { name: 'Ed25519' }, false, ['verify']);\n const isValid = await crypto.get().subtle.verify({ name: 'Ed25519' }, key, withArrayBuffer(sig), withArrayBuffer(msg instanceof Uint8Array ? msg : msg.subarray()));\n return isValid;\n }\n throw new TypeError('WebCrypto does not support SharedArrayBuffer for Ed25519 keys');\n}\nexport function hashAndVerifyNoble(publicKey, sig, msg) {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);\n}\nexport async function hashAndVerify(publicKey, sig, msg) {\n if (ed25519Supported == null) {\n ed25519Supported = await webCryptoEd25519SupportedPromise;\n }\n if (ed25519Supported) {\n return hashAndVerifyWebCrypto(publicKey, sig, msg);\n }\n return hashAndVerifyNoble(publicKey, sig, msg);\n}\nfunction concatKeys(privateKeyRaw, publicKey) {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i];\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];\n }\n return privateKey;\n}\n//# sourceMappingURL=index.browser.js.map","import { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nexport function base64urlToBuffer(str, len) {\n let buf = uint8ArrayFromString(str, 'base64urlpad');\n if (len != null) {\n if (buf.length > len) {\n throw new Error('byte array longer than desired length');\n }\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf]);\n }\n return buf;\n}\nexport function isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=util.js.map","import { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport { identity } from 'multiformats/hashes/identity';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { isPromise } from \"../../util.js\";\nimport { publicKeyToProtobuf } from \"../index.js\";\nimport * as crypto from \"./index.js\";\nimport { ensureEd25519Key } from \"./utils.js\";\nexport class Ed25519PublicKey {\n type = 'Ed25519';\n raw;\n constructor(key) {\n this.raw = ensureEd25519Key(key, crypto.publicKeyLength);\n }\n toMultihash() {\n return identity.digest(publicKeyToProtobuf(this));\n }\n toCID() {\n return CID.createV1(114, this.toMultihash());\n }\n toString() {\n return base58btc.encode(this.toMultihash().bytes).substring(1);\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n verify(data, sig, options) {\n options?.signal?.throwIfAborted();\n const result = crypto.hashAndVerify(this.raw, sig, data);\n if (isPromise(result)) {\n return result.then(res => {\n options?.signal?.throwIfAborted();\n return res;\n });\n }\n return result;\n }\n}\nexport class Ed25519PrivateKey {\n type = 'Ed25519';\n raw;\n publicKey;\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor(key, publicKey) {\n this.raw = ensureEd25519Key(key, crypto.privateKeyLength);\n this.publicKey = new Ed25519PublicKey(publicKey);\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n sign(message, options) {\n options?.signal?.throwIfAborted();\n const sig = crypto.hashAndSign(this.raw, message);\n if (isPromise(sig)) {\n return sig.then(res => {\n options?.signal?.throwIfAborted();\n return res;\n });\n }\n options?.signal?.throwIfAborted();\n return sig;\n }\n}\n//# sourceMappingURL=ed25519.js.map","import { InvalidParametersError } from '@libp2p/interface';\nimport { Ed25519PublicKey as Ed25519PublicKeyClass, Ed25519PrivateKey as Ed25519PrivateKeyClass } from \"./ed25519.js\";\nimport * as crypto from \"./index.js\";\nexport function unmarshalEd25519PrivateKey(bytes) {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureEd25519Key(bytes, crypto.privateKeyLength + crypto.publicKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length);\n return new Ed25519PrivateKeyClass(privateKeyBytes, publicKeyBytes);\n }\n bytes = ensureEd25519Key(bytes, crypto.privateKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength);\n return new Ed25519PrivateKeyClass(privateKeyBytes, publicKeyBytes);\n}\nexport function unmarshalEd25519PublicKey(bytes) {\n bytes = ensureEd25519Key(bytes, crypto.publicKeyLength);\n return new Ed25519PublicKeyClass(bytes);\n}\nexport async function generateEd25519KeyPair() {\n const { privateKey, publicKey } = crypto.generateKey();\n return new Ed25519PrivateKeyClass(privateKey, publicKey);\n}\nexport async function generateEd25519KeyPairFromSeed(seed) {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed);\n return new Ed25519PrivateKeyClass(privateKey, publicKey);\n}\nexport function ensureEd25519Key(key, length) {\n key = Uint8Array.from(key ?? []);\n if (key.length !== length) {\n throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`);\n }\n return key;\n}\n//# sourceMappingURL=utils.js.map","const f32 = new Float32Array([-0]);\nconst f8b = new Uint8Array(f32.buffer);\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE(val, buf, pos) {\n f32[0] = val;\n buf[pos] = f8b[0];\n buf[pos + 1] = f8b[1];\n buf[pos + 2] = f8b[2];\n buf[pos + 3] = f8b[3];\n}\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE(val, buf, pos) {\n f32[0] = val;\n buf[pos] = f8b[3];\n buf[pos + 1] = f8b[2];\n buf[pos + 2] = f8b[1];\n buf[pos + 3] = f8b[0];\n}\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE(buf, pos) {\n f8b[0] = buf[pos];\n f8b[1] = buf[pos + 1];\n f8b[2] = buf[pos + 2];\n f8b[3] = buf[pos + 3];\n return f32[0];\n}\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE(buf, pos) {\n f8b[3] = buf[pos];\n f8b[2] = buf[pos + 1];\n f8b[1] = buf[pos + 2];\n f8b[0] = buf[pos + 3];\n return f32[0];\n}\nconst f64 = new Float64Array([-0]);\nconst d8b = new Uint8Array(f64.buffer);\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE(val, buf, pos) {\n f64[0] = val;\n buf[pos] = d8b[0];\n buf[pos + 1] = d8b[1];\n buf[pos + 2] = d8b[2];\n buf[pos + 3] = d8b[3];\n buf[pos + 4] = d8b[4];\n buf[pos + 5] = d8b[5];\n buf[pos + 6] = d8b[6];\n buf[pos + 7] = d8b[7];\n}\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE(val, buf, pos) {\n f64[0] = val;\n buf[pos] = d8b[7];\n buf[pos + 1] = d8b[6];\n buf[pos + 2] = d8b[5];\n buf[pos + 3] = d8b[4];\n buf[pos + 4] = d8b[3];\n buf[pos + 5] = d8b[2];\n buf[pos + 6] = d8b[1];\n buf[pos + 7] = d8b[0];\n}\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE(buf, pos) {\n d8b[0] = buf[pos];\n d8b[1] = buf[pos + 1];\n d8b[2] = buf[pos + 2];\n d8b[3] = buf[pos + 3];\n d8b[4] = buf[pos + 4];\n d8b[5] = buf[pos + 5];\n d8b[6] = buf[pos + 6];\n d8b[7] = buf[pos + 7];\n return f64[0];\n}\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE(buf, pos) {\n d8b[7] = buf[pos];\n d8b[6] = buf[pos + 1];\n d8b[5] = buf[pos + 2];\n d8b[4] = buf[pos + 3];\n d8b[3] = buf[pos + 4];\n d8b[2] = buf[pos + 5];\n d8b[1] = buf[pos + 6];\n d8b[0] = buf[pos + 7];\n return f64[0];\n}\n//# sourceMappingURL=float.js.map","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER);\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n lo;\n hi;\n constructor(lo, hi) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n /**\n * Low bits\n */\n this.lo = lo | 0;\n /**\n * High bits\n */\n this.hi = hi | 0;\n }\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber(unsigned = false) {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0;\n let hi = ~this.hi >>> 0;\n if (lo === 0) {\n hi = hi + 1 >>> 0;\n }\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n }\n /**\n * Converts this long bits to a bigint\n */\n toBigInt(unsigned = false) {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);\n }\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0;\n let hi = ~this.hi >>> 0;\n if (lo === 0) {\n hi = hi + 1 >>> 0;\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n));\n }\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);\n }\n /**\n * Converts this long bits to a string\n */\n toString(unsigned = false) {\n return this.toBigInt(unsigned).toString();\n }\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode() {\n const mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = (this.lo << 1 ^ mask) >>> 0;\n return this;\n }\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode() {\n const mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = (this.hi >>> 1 ^ mask) >>> 0;\n return this;\n }\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length() {\n const part0 = this.lo;\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0;\n const part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n }\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt(value) {\n if (value === 0n) {\n return zero;\n }\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value));\n }\n const negative = value < 0n;\n if (negative) {\n value = -value;\n }\n let hi = value >> 32n;\n let lo = value - (hi << 32n);\n if (negative) {\n hi = ~hi | 0n;\n lo = ~lo | 0n;\n if (++lo > TWO_32) {\n lo = 0n;\n if (++hi > TWO_32) {\n hi = 0n;\n }\n }\n }\n return new LongBits(Number(lo), Number(hi));\n }\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber(value) {\n if (value === 0) {\n return zero;\n }\n const sign = value < 0;\n if (sign) {\n value = -value;\n }\n let lo = value >>> 0;\n let hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295) {\n hi = 0;\n }\n }\n }\n return new LongBits(lo, hi);\n }\n /**\n * Constructs new long bits from a number, long or string\n */\n static from(value) {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value);\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value);\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value));\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n }\n}\nconst zero = new LongBits(0, 0);\nzero.toBigInt = function () { return 0n; };\nzero.zzEncode = zero.zzDecode = function () { return this; };\nzero.length = function () { return 1; };\nconst TWO_32 = 4294967296n;\n//# sourceMappingURL=longbits.js.map","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length(string) {\n let len = 0;\n let c = 0;\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i);\n if (c < 128) {\n len += 1;\n }\n else if (c < 2048) {\n len += 2;\n }\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i;\n len += 4;\n }\n else {\n len += 3;\n }\n }\n return len;\n}\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read(buffer, start, end) {\n const len = end - start;\n if (len < 1) {\n return '';\n }\n let parts;\n const chunk = [];\n let i = 0; // char offset\n let t; // temporary\n while (start < end) {\n t = buffer[start++];\n if (t < 128) {\n chunk[i++] = t;\n }\n else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\n }\n else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\n chunk[i++] = 0xD800 + (t >> 10);\n chunk[i++] = 0xDC00 + (t & 1023);\n }\n else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\n }\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk));\n i = 0;\n }\n }\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\n }\n return parts.join('');\n }\n return String.fromCharCode.apply(String, chunk.slice(0, i));\n}\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write(string, buffer, offset) {\n const start = offset;\n let c1; // character 1\n let c2; // character 2\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i);\n if (c1 < 128) {\n buffer[offset++] = c1;\n }\n else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192;\n buffer[offset++] = c1 & 63 | 128;\n }\n else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\n ++i;\n buffer[offset++] = c1 >> 18 | 240;\n buffer[offset++] = c1 >> 12 & 63 | 128;\n buffer[offset++] = c1 >> 6 & 63 | 128;\n buffer[offset++] = c1 & 63 | 128;\n }\n else {\n buffer[offset++] = c1 >> 12 | 224;\n buffer[offset++] = c1 >> 6 & 63 | 128;\n buffer[offset++] = c1 & 63 | 128;\n }\n }\n return offset - start;\n}\n//# sourceMappingURL=utf8.js.map","import { decodeUint8Array, encodingLength } from 'uint8-varint';\nimport { withArrayBuffer } from 'uint8arrays/with-array-buffer';\nimport { readFloatLE, readDoubleLE } from \"./float.js\";\nimport { LongBits } from \"./longbits.js\";\nimport * as utf8 from \"./utf8.js\";\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`);\n}\nfunction readFixed32End(buf, end) {\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0;\n}\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader {\n buf;\n pos;\n len;\n _slice = Uint8Array.prototype.subarray;\n constructor(buffer) {\n /**\n * Read buffer\n */\n this.buf = withArrayBuffer(buffer);\n /**\n * Read buffer position\n */\n this.pos = 0;\n /**\n * Read buffer length\n */\n this.len = buffer.length;\n }\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32() {\n let value = 4294967295;\n value = (this.buf[this.pos] & 127) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return value;\n }\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return value;\n }\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return value;\n }\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return value;\n }\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return value;\n }\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n }\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32() {\n return this.uint32() | 0;\n }\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32() {\n const value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n }\n /**\n * Reads a varint as a boolean\n */\n bool() {\n return this.uint32() !== 0;\n }\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const res = readFixed32End(this.buf, this.pos += 4);\n return res;\n }\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const res = readFixed32End(this.buf, this.pos += 4) | 0;\n return res;\n }\n /**\n * Reads a float (32 bit) as a number\n */\n float() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const value = readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n }\n /**\n * Reads a double (64 bit float) as a number\n */\n double() {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const value = readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n }\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes() {\n const length = this.uint32();\n const start = this.pos;\n const end = this.pos + length;\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length);\n }\n this.pos += length;\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end);\n }\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string() {\n const bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n }\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip(length) {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) {\n throw indexOutOfRange(this, length);\n }\n this.pos += length;\n }\n else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n } while ((this.buf[this.pos++] & 128) !== 0);\n }\n return this;\n }\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`);\n }\n return this;\n }\n readLongVarint() {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0);\n let i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n i = 0;\n }\n else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n }\n else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n }\n throw Error('invalid varint encoding');\n }\n readFixed64() {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8);\n }\n const lo = readFixed32End(this.buf, this.pos += 4);\n const hi = readFixed32End(this.buf, this.pos += 4);\n return new LongBits(lo, hi);\n }\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64() {\n return this.readLongVarint().toBigInt();\n }\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number() {\n return this.readLongVarint().toNumber();\n }\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String() {\n return this.readLongVarint().toString();\n }\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64() {\n return this.readLongVarint().toBigInt(true);\n }\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number() {\n const value = decodeUint8Array(this.buf, this.pos);\n this.pos += encodingLength(value);\n return value;\n }\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String() {\n return this.readLongVarint().toString(true);\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64() {\n return this.readLongVarint().zzDecode().toBigInt();\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number() {\n return this.readLongVarint().zzDecode().toNumber();\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String() {\n return this.readLongVarint().zzDecode().toString();\n }\n /**\n * Reads fixed 64 bits\n */\n fixed64() {\n return this.readFixed64().toBigInt();\n }\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number() {\n return this.readFixed64().toNumber();\n }\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String() {\n return this.readFixed64().toString();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64() {\n return this.readFixed64().toBigInt();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number() {\n return this.readFixed64().toNumber();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String() {\n return this.readFixed64().toString();\n }\n}\nexport function createReader(buf) {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray());\n}\n//# sourceMappingURL=reader.js.map","import { createReader } from \"./utils/reader.js\";\nexport function decodeMessage(buf, codec, opts) {\n const reader = createReader(buf);\n return codec.decode(reader, undefined, opts);\n}\n//# sourceMappingURL=decode.js.map","import { allocUnsafe } from 'uint8arrays/alloc';\n/**\n * A general purpose buffer pool\n */\nexport default function pool(size) {\n const SIZE = size ?? 8192;\n const MAX = SIZE >>> 1;\n let slab;\n let offset = SIZE;\n return function poolAlloc(size) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size);\n }\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE);\n offset = 0;\n }\n const buf = slab.subarray(offset, offset += size);\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1;\n }\n return buf;\n };\n}\n//# sourceMappingURL=pool.js.map","import { encodeUint8Array, encodingLength } from 'uint8-varint';\nimport { allocUnsafe } from 'uint8arrays/alloc';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { writeFloatLE, writeDoubleLE } from \"./float.js\";\nimport { LongBits } from \"./longbits.js\";\nimport pool from \"./pool.js\";\nimport * as utf8 from \"./utf8.js\";\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n fn;\n /**\n * Value byte length\n */\n len;\n /**\n * Next operation\n */\n next;\n /**\n * Value to write\n */\n val;\n constructor(fn, len, val) {\n this.fn = fn;\n this.len = len;\n this.next = undefined;\n this.val = val; // type varies\n }\n}\n/* istanbul ignore next */\nfunction noop() { }\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n head;\n /**\n * Current tail\n */\n tail;\n /**\n * Current buffer length\n */\n len;\n /**\n * Next state\n */\n next;\n constructor(writer) {\n this.head = writer.head;\n this.tail = writer.tail;\n this.len = writer.len;\n this.next = writer.states;\n }\n}\nconst bufferPool = pool();\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc(size) {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size);\n }\n return bufferPool(size);\n}\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter {\n /**\n * Current length\n */\n len;\n /**\n * Operations head\n */\n head;\n /**\n * Operations tail\n */\n tail;\n /**\n * Linked forked states\n */\n states;\n constructor() {\n this.len = 0;\n this.head = new Op(noop, 0, 0);\n this.tail = this.head;\n this.states = null;\n }\n /**\n * Pushes a new operation to the queue\n */\n _push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n }\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp((value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5, value)).len;\n return this;\n }\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n }\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value) {\n const bits = LongBits.fromBigInt(value);\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value) {\n return this._push(encodeUint8Array, encodingLength(value), value);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value) {\n return this.uint64(BigInt(value));\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value) {\n return this.uint64(value);\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value) {\n return this.uint64Number(value);\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value) {\n return this.uint64String(value);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value) {\n const bits = LongBits.fromBigInt(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value) {\n const bits = LongBits.fromNumber(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value) {\n return this.sint64(BigInt(value));\n }\n /**\n * Writes a boolish value as a varint\n */\n bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n }\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n }\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value) {\n return this.fixed32(value);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value) {\n const bits = LongBits.fromBigInt(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value) {\n const bits = LongBits.fromNumber(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value) {\n return this.fixed64(BigInt(value));\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value) {\n return this.fixed64(value);\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value) {\n return this.fixed64Number(value);\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value) {\n return this.fixed64String(value);\n }\n /**\n * Writes a float (32 bit)\n */\n float(value) {\n return this._push(writeFloatLE, 4, value);\n }\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double(value) {\n return this._push(writeDoubleLE, 8, value);\n }\n /**\n * Writes a sequence of bytes\n */\n bytes(value) {\n const len = value.length >>> 0;\n if (len === 0) {\n return this._push(writeByte, 1, 0);\n }\n return this.uint32(len)._push(writeBytes, len, value);\n }\n /**\n * Writes a string\n */\n string(value) {\n const len = utf8.length(value);\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n }\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n }\n /**\n * Resets this instance to the last state\n */\n reset() {\n if (this.states != null) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n }\n else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n }\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim() {\n const head = this.head;\n const tail = this.tail;\n const len = this.len;\n this.reset().uint32(len);\n if (len !== 0) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n }\n /**\n * Finishes the write operation\n */\n finish() {\n let head = this.head.next; // skip noop\n const buf = alloc(this.len);\n let pos = 0;\n while (head != null) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n }\n}\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n next;\n constructor(len, val) {\n super(writeVarint32, len, val);\n this.next = undefined;\n }\n}\nfunction writeVarint64(val, buf, pos) {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\nfunction writeFixed32(val, buf, pos) {\n buf[pos] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\nfunction writeBytes(val, buf, pos) {\n buf.set(val, pos);\n}\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value) {\n const len = value.length >>> 0;\n this.uint32(len);\n if (len > 0) {\n this._push(writeBytesBuffer, len, value);\n }\n return this;\n };\n Uint8ArrayWriter.prototype.string = function (value) {\n const len = globalThis.Buffer.byteLength(value);\n this.uint32(len);\n if (len > 0) {\n this._push(writeStringBuffer, len, value);\n }\n return this;\n };\n}\nfunction writeBytesBuffer(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos);\n // @ts-expect-error buf isn't a Uint8Array?\n }\n else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos);\n }\n else {\n buf.set(uint8ArrayFromString(val), pos);\n }\n}\n/**\n * Creates a new writer\n */\nexport function createWriter() {\n return new Uint8ArrayWriter();\n}\n//# sourceMappingURL=writer.js.map","import { createWriter } from \"./utils/writer.js\";\nexport function encodeMessage(message, codec) {\n const w = createWriter();\n codec.encode(message, w, {\n lengthDelimited: false\n });\n return w.finish();\n}\n//# sourceMappingURL=encode.js.map","import { createReader } from \"./utils/reader.js\";\nexport function* streamMessage(buf, codec, opts) {\n const reader = createReader(buf);\n yield* codec.stream(reader, undefined, '.', opts);\n}\n//# sourceMappingURL=stream.js.map","// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport const CODEC_TYPES = {\n VARINT: 0,\n BIT64: 1,\n LENGTH_DELIMITED: 2,\n START_GROUP: 3,\n END_GROUP: 4,\n BIT32: 5\n};\nexport function createCodec(name, type, encode, decode, stream) {\n return {\n name,\n type,\n encode,\n decode,\n stream\n };\n}\n//# sourceMappingURL=codec.js.map","import { createCodec, CODEC_TYPES } from \"../codec.js\";\nexport function enumeration(v) {\n function findValue(val) {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value');\n }\n return v[val];\n }\n const encode = function enumEncode(val, writer) {\n const enumValue = findValue(val);\n writer.int32(enumValue);\n };\n const decode = function enumDecode(reader) {\n const val = reader.int32();\n return findValue(val);\n };\n const stream = function* enumStream(reader, prefix) {\n // enums are simple values that are decoded inline so this is a no-op\n };\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode, stream);\n}\n//# sourceMappingURL=enum.js.map","import { createCodec, CODEC_TYPES } from \"../codec.js\";\nexport function message(encode, decode, stream) {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, stream);\n}\n//# sourceMappingURL=message.js.map","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\nexport { decodeMessage } from \"./decode.js\";\nexport { encodeMessage } from \"./encode.js\";\nexport { streamMessage } from \"./stream.js\";\nexport { enumeration } from \"./codecs/enum.js\";\nexport { message } from \"./codecs/message.js\";\nexport { createReader as reader } from \"./utils/reader.js\";\nexport { createWriter as writer } from \"./utils/writer.js\";\n/**\n * This will be removed in a future release\n *\n * @deprecated\n */\nexport class CodeError extends Error {\n code;\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\n/**\n * Thrown when a repeated field has too many elements\n */\nexport class MaxLengthError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_MAX_LENGTH';\n name = 'MaxLengthError';\n}\n/**\n * Thrown when a map has too many elements\n */\nexport class MaxSizeError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_MAX_SIZE';\n name = 'MaxSizeError';\n}\nexport class ParseError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_PARSE_ERROR';\n name = 'ParseError';\n}\nexport class NoMessagesFoundError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_NO_MESSAGES_FOUND';\n name = 'NoMessagesFoundError';\n}\n//# sourceMappingURL=index.js.map","import { decodeMessage, encodeMessage, enumeration, message, streamMessage } from 'protons-runtime';\nexport var KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"secp256k1\"] = \"secp256k1\";\n KeyType[\"ECDSA\"] = \"ECDSA\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"secp256k1\"] = 2] = \"secp256k1\";\n __KeyTypeValues[__KeyTypeValues[\"ECDSA\"] = 3] = \"ECDSA\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return enumeration(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nexport var PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.Type = KeyType.codec().decode(reader);\n break;\n }\n case 2: {\n obj.Data = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n }, function* (reader, length, prefix, opts = {}) {\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n yield {\n field: `${prefix}.Type`,\n value: KeyType.codec().decode(reader)\n };\n break;\n }\n case 2: {\n yield {\n field: `${prefix}.Data`,\n value: reader.bytes()\n };\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n });\n }\n return _codec;\n };\n function encode(obj) {\n return encodeMessage(obj, PublicKey.codec());\n }\n PublicKey.encode = encode;\n function decode(buf, opts) {\n return decodeMessage(buf, PublicKey.codec(), opts);\n }\n PublicKey.decode = decode;\n function stream(buf, opts) {\n return streamMessage(buf, PublicKey.codec(), opts);\n }\n PublicKey.stream = stream;\n})(PublicKey || (PublicKey = {}));\nexport var PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.Type = KeyType.codec().decode(reader);\n break;\n }\n case 2: {\n obj.Data = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n }, function* (reader, length, prefix, opts = {}) {\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n yield {\n field: `${prefix}.Type`,\n value: KeyType.codec().decode(reader)\n };\n break;\n }\n case 2: {\n yield {\n field: `${prefix}.Data`,\n value: reader.bytes()\n };\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n });\n }\n return _codec;\n };\n function encode(obj) {\n return encodeMessage(obj, PrivateKey.codec());\n }\n PrivateKey.encode = encode;\n function decode(buf, opts) {\n return decodeMessage(buf, PrivateKey.codec(), opts);\n }\n PrivateKey.decode = decode;\n function stream(buf, opts) {\n return streamMessage(buf, PrivateKey.codec(), opts);\n }\n PrivateKey.stream = stream;\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map","import { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { hashAndSign, utils, hashAndVerify } from \"./index.js\";\nexport class RSAPublicKey {\n type = 'RSA';\n jwk;\n _raw;\n _multihash;\n constructor(jwk, digest) {\n this.jwk = jwk;\n this._multihash = digest;\n }\n get raw() {\n if (this._raw == null) {\n this._raw = utils.jwkToPkix(this.jwk);\n }\n return this._raw;\n }\n toMultihash() {\n return this._multihash;\n }\n toCID() {\n return CID.createV1(114, this._multihash);\n }\n toString() {\n return base58btc.encode(this.toMultihash().bytes).substring(1);\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n verify(data, sig, options) {\n return hashAndVerify(this.jwk, sig, data, options);\n }\n}\nexport class RSAPrivateKey {\n type = 'RSA';\n jwk;\n _raw;\n publicKey;\n constructor(jwk, publicKey) {\n this.jwk = jwk;\n this.publicKey = publicKey;\n }\n get raw() {\n if (this._raw == null) {\n this._raw = utils.jwkToPkcs1(this.jwk);\n }\n return this._raw;\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n sign(message, options) {\n return hashAndSign(this.jwk, message, options);\n }\n}\n//# sourceMappingURL=rsa.js.map","import { InvalidParametersError, InvalidPublicKeyError } from '@libp2p/interface';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { create } from 'multiformats/hashes/digest';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport * as pb from \"../keys.js\";\nimport { decodeDer, encodeBitString, encodeInteger, encodeSequence } from \"./der.js\";\nimport { generateRSAKey, rsaKeySize } from \"./index.js\";\nimport { RSAPrivateKey as RSAPrivateKeyClass, RSAPublicKey as RSAPublicKeyClass } from \"./rsa.js\";\nexport const MAX_RSA_KEY_SIZE = 8192;\nconst SHA2_256_CODE = 0x12;\nconst MAX_RSA_JWK_SIZE = 1062;\nconst RSA_ALGORITHM_IDENTIFIER = Uint8Array.from([\n 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00\n]);\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK private key\n */\nexport function pkcs1ToJwk(bytes) {\n const message = decodeDer(bytes);\n return pkcs1MessageToJwk(message);\n}\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK private key\n */\nexport function pkcs1MessageToJwk(message) {\n return {\n n: uint8ArrayToString(message[1], 'base64url'),\n e: uint8ArrayToString(message[2], 'base64url'),\n d: uint8ArrayToString(message[3], 'base64url'),\n p: uint8ArrayToString(message[4], 'base64url'),\n q: uint8ArrayToString(message[5], 'base64url'),\n dp: uint8ArrayToString(message[6], 'base64url'),\n dq: uint8ArrayToString(message[7], 'base64url'),\n qi: uint8ArrayToString(message[8], 'base64url'),\n kty: 'RSA'\n };\n}\n/**\n * Convert a JWK private key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1(jwk) {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new InvalidParametersError('JWK was missing components');\n }\n return encodeSequence([\n encodeInteger(Uint8Array.from([0])),\n encodeInteger(uint8ArrayFromString(jwk.n, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.e, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.d, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.p, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.q, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.dp, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.dq, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.qi, 'base64url'))\n ]).subarray();\n}\n/**\n * Convert a PKIX in ASN1 DER format to a JWK public key\n */\nexport function pkixToJwk(bytes) {\n const message = decodeDer(bytes, {\n offset: 0\n });\n return pkixMessageToJwk(message);\n}\nexport function pkixMessageToJwk(message) {\n const keys = decodeDer(message[1], {\n offset: 0\n });\n // this looks fragile but DER is a canonical format so we are safe to have\n // deeply property chains like this\n return {\n kty: 'RSA',\n n: uint8ArrayToString(keys[0], 'base64url'),\n e: uint8ArrayToString(keys[1], 'base64url')\n };\n}\n/**\n * Convert a JWK public key to PKIX in ASN1 DER format\n */\nexport function jwkToPkix(jwk) {\n if (jwk.n == null || jwk.e == null) {\n throw new InvalidParametersError('JWK was missing components');\n }\n const subjectPublicKeyInfo = encodeSequence([\n RSA_ALGORITHM_IDENTIFIER,\n encodeBitString(encodeSequence([\n encodeInteger(uint8ArrayFromString(jwk.n, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.e, 'base64url'))\n ]))\n ]);\n return subjectPublicKeyInfo.subarray();\n}\n/**\n * Turn PKCS#1 DER bytes into a PrivateKey\n */\nexport function pkcs1ToRSAPrivateKey(bytes) {\n const message = decodeDer(bytes);\n return pkcs1MessageToRSAPrivateKey(message);\n}\n/**\n * Turn PKCS#1 DER bytes into a PrivateKey\n */\nexport function pkcs1MessageToRSAPrivateKey(message) {\n const jwk = pkcs1MessageToJwk(message);\n return jwkToRSAPrivateKey(jwk);\n}\n/**\n * Turn a PKIX message into a PublicKey\n */\nexport function pkixToRSAPublicKey(bytes, digest) {\n if (bytes.byteLength >= MAX_RSA_JWK_SIZE) {\n throw new InvalidPublicKeyError('Key size is too large');\n }\n const message = decodeDer(bytes, {\n offset: 0\n });\n return pkixMessageToRSAPublicKey(message, bytes, digest);\n}\nexport function pkixMessageToRSAPublicKey(message, bytes, digest) {\n const jwk = pkixMessageToJwk(message);\n if (digest == null) {\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: bytes\n }));\n digest = create(SHA2_256_CODE, hash);\n }\n return new RSAPublicKeyClass(jwk, digest);\n}\nexport function jwkToRSAPrivateKey(jwk) {\n if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large');\n }\n const keys = jwkToJWKKeyPair(jwk);\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: jwkToPkix(keys.publicKey)\n }));\n const digest = create(SHA2_256_CODE, hash);\n return new RSAPrivateKeyClass(keys.privateKey, new RSAPublicKeyClass(keys.publicKey, digest));\n}\nexport async function generateRSAKeyPair(bits) {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large');\n }\n const keys = await generateRSAKey(bits);\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: jwkToPkix(keys.publicKey)\n }));\n const digest = create(SHA2_256_CODE, hash);\n return new RSAPrivateKeyClass(keys.privateKey, new RSAPublicKeyClass(keys.publicKey, digest));\n}\n/**\n * Takes a jwk key and returns a JWK KeyPair\n */\nexport function jwkToJWKKeyPair(key) {\n if (key == null) {\n throw new InvalidParametersError('Missing key parameter');\n }\n return {\n privateKey: key,\n publicKey: {\n kty: key.kty,\n n: key.n,\n e: key.e\n }\n };\n}\n//# sourceMappingURL=utils.js.map","import { InvalidParametersError } from '@libp2p/interface';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { withArrayBuffer } from 'uint8arrays/with-array-buffer';\nimport randomBytes from \"../../random-bytes.js\";\nimport webcrypto from \"../../webcrypto/index.js\";\nimport * as utils from \"./utils.js\";\nexport const RSAES_PKCS1_V1_5_OID = '1.2.840.113549.1.1.1';\nexport { utils };\nexport async function generateRSAKey(bits, options) {\n const pair = await webcrypto.get().subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n }, true, ['sign', 'verify']);\n options?.signal?.throwIfAborted();\n const keys = await exportKey(pair, options);\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\nexport { randomBytes as getRandomValues };\nexport async function hashAndSign(key, msg, options) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['sign']);\n options?.signal?.throwIfAborted();\n const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, withArrayBuffer(msg instanceof Uint8Array ? msg : msg.subarray()));\n options?.signal?.throwIfAborted();\n return new Uint8Array(sig, 0, sig.byteLength);\n}\nexport async function hashAndVerify(key, sig, msg, options) {\n const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['verify']);\n options?.signal?.throwIfAborted();\n const result = await webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, withArrayBuffer(sig), withArrayBuffer(msg instanceof Uint8Array ? msg : msg.subarray()));\n options?.signal?.throwIfAborted();\n return result;\n}\nasync function exportKey(pair, options) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new InvalidParametersError('Private and public key are required');\n }\n const result = await Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ]);\n options?.signal?.throwIfAborted();\n return result;\n}\nexport function rsaKeySize(jwk) {\n if (jwk.kty !== 'RSA') {\n throw new InvalidParametersError('invalid key type');\n }\n else if (jwk.n == null) {\n throw new InvalidParametersError('invalid key modulus');\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url');\n return bytes.length * 8;\n}\n//# sourceMappingURL=index.browser.js.map","/**\n * ASN.1 DER (Distinguished Encoding Rules) helpers for ECDSA signatures.\n * Only implements the tiny subset needed for `SEQUENCE(INTEGER r, INTEGER s)`.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abignumber, abytes, asafenumber, astring, bytesToNumberBE, numberToHexUnpadded, validateObject, } from \"../utils.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\n/**\n * @param m - Error message.\n * @example\n * Throw a DER-specific error when signature parsing encounters invalid bytes.\n *\n * ```ts\n * new DERErr('bad der');\n * ```\n */\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n// Plain const so the freezes can live inside the pure initializer of the `DER` export below:\n// bare top-level `Object.freeze(...)` calls would defeat tree-shaking for every importer.\nconst _DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = _DER;\n asafenumber(tag, 'tag');\n if (tag < 0 || tag > 255)\n throw new E('tlv.encode: wrong tag');\n astring(data, 'data');\n // Internal helper: callers hand this already-validated hex payload, so we only enforce\n // byte alignment here instead of re-validating every nibble.\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = _DER;\n data = abytes(data, undefined, 'DER data');\n let pos = 0;\n if (tag < 0 || tag > 255)\n throw new E('tlv.decode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n // First bit of first length byte is the short/long form flag.\n const isLong = !!(first & 0b1000_0000);\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n // This would overflow u32 in JS.\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big');\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = _DER;\n abignumber(num);\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = _DER;\n if (data.length < 1)\n throw new E('invalid signature integer: empty');\n if (data[0] & 0b1000_0000)\n throw new E('invalid signature integer: negative');\n // Single-byte zero `00` is the canonical DER INTEGER encoding for zero.\n if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(bytes, maxScalarBytes) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = _DER;\n if (maxScalarBytes !== undefined) {\n asafenumber(maxScalarBytes, 'maxScalarBytes');\n if (maxScalarBytes < 1)\n throw new E('invalid signature: maxScalarBytes must be positive');\n }\n const data = abytes(bytes, undefined, 'signature');\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n // Enforce curve-provided bounds before bytes-to-hex-to-BigInt conversion can amplify memory.\n if (maxScalarBytes !== undefined &&\n (rBytes.length > maxScalarBytes || sBytes.length > maxScalarBytes))\n throw new E('invalid signature: integer too large');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = _DER;\n validateObject(sig, { r: 'bigint', s: 'bigint' }, {}, 'sig');\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and\n * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.\n * @example\n * ASN.1 DER encoding utilities.\n *\n * ```ts\n * const der = DER.hexFromSig({ r: 1n, s: 2n });\n * ```\n */\nexport const DER = /* @__PURE__ */ (() => {\n Object.freeze(_DER._tlv);\n Object.freeze(_DER._int);\n return Object.freeze(_DER);\n})();\n","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport { abool, abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, hexToBytes, isBytes, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, mulAddUnsafe, normalizeZ, probeRandomBytes, ScalarMultiplier, validatePointCons, } from \"./curve.js\";\nimport { DER } from \"./der.js\";\nimport { getMinHashLength, invertCt, mapHashToField } from \"./modular.js\";\n// DER codec lives in der.ts; re-exported here because ECDSA signatures are its main consumer.\nexport { DER, DERErr } from \"./der.js\";\n// We construct the basis so `den` is always positive and equals `n`,\n// but the `num` sign depends on the basis, not on the secret value.\n// Exact half-way cases round away from zero, which keeps the split symmetric\n// around the reduced-basis boundaries used by endomorphism decomposition.\nconst divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k, basis, n) {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // Callers must provide a reduced GLV basis whose vectors satisfy\n // `a + b * lambda ≡ 0 (mod n)`; this helper only sees the basis and `n`.\n // Reject unreduced scalars instead of silently treating them mod n.\n aInRange('scalar', k, _0n, n);\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg)\n k1 = -k1;\n if (k2neg)\n k2 = -k2;\n // Double check that resulting scalar is less than half bits of N: the wNAF pair walk\n // relies on the halves being short. This should only happen on wrong bases.\n // Also, the math inside is complex enough that this guard is worth keeping.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed for k');\n }\n return { k1neg, k1, k2neg, k2 };\n}\nfunction validateSigFormat(format) {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format;\n}\nfunction validateSigOpts(opts, def) {\n validateObject(opts);\n const optsn = {};\n // Normalize only the declared option subset from `def`; unknown keys are\n // intentionally ignored so shared / superset option bags stay valid here too.\n // `extraEntropy` stays an opaque payload until the signing path consumes it.\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS, 'lowS');\n abool(optsn.prehash, 'prehash');\n if (optsn.format !== undefined)\n validateSigFormat(optsn.format);\n return optsn;\n}\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n * @param params - Curve parameters. See {@link WeierstrassOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.\n * @returns Weierstrass point constructor.\n * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}\n *\n * @example\n * Construct a point type from explicit Weierstrass curve parameters.\n *\n * ```js\n * const opts = {\n * p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n * h: 1n,\n * a: 0n,\n * b: 7n,\n * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n * };\n * const secp160k1_Point = weierstrass(opts);\n * ```\n */\nexport function weierstrass(params, extraOpts = {}) {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const Fp = validated.Fp;\n const Fn = validated.Fn;\n let CURVE = validated.CURVE;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(extraOpts, {}, {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n randomBytes: 'function',\n });\n // Snapshot every hook and take an owned copy of nested GLV configuration. Later mutations of\n // the caller's options must not change arithmetic, subgroup, or codec policy.\n const { endo: endoOpts, allowInfinityPoint, clearCofactor, isTorsionFree, fromBytes, toBytes, } = extraOpts;\n const randomBytes = extraOpts.randomBytes === undefined ? wcRandomBytes : extraOpts.randomBytes;\n if (endoOpts) {\n if (!Fp.is0(CURVE.a) || typeof endoOpts.beta !== 'bigint' || !Array.isArray(endoOpts.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n const endo = endoOpts\n ? {\n beta: endoOpts.beta,\n basises: endoOpts.basises.map((basis) => [...basis]),\n }\n : undefined;\n const lengths = getWLengths(Fp, Fn);\n function assertCompressionIsSupported() {\n if (!Fp.isOdd)\n throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n // Implements IEEE P1363 point encoding\n function pointToBytes(_c, point, isCompressed) {\n // Handle infinity before toAffine(), which maps ZERO to (0, 0) silently: without this the\n // encoder would emit an all-zero byte string that decodes back as a different point. Only\n // curves that opt into infinity as a public point value get the SEC 1 byte form.\n if (point.is0()) {\n if (!allowInfinityPoint)\n throw new Error('bad point: ZERO');\n return Uint8Array.of(0); // SEC 1 v2.0 §2.3.3\n }\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd(y);\n return concatBytes(pprefix(hasEvenY), bx);\n }\n else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // SEC 1 v2.0 §2.3.4 decodes 0x00 as infinity, but §3.2.2 rejects infinity as a public key.\n // Leaving 0x00 undecodable by default makes that rejection structural rather than a check:\n // callers reuse this parser as the strict key boundary, and infinity is simply not\n // expressible. Curves where infinity is a real wire value opt into the codec instead.\n // secp256k1 crosstests show OpenSSL raw point codecs accept 0x00 too.\n if (allowInfinityPoint && length === 1 && head === 0x00)\n return { x: Fp.ZERO, y: Fp.ZERO };\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x))\n throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y))\n throw new Error('bad point: is not on curve');\n return { x, y };\n }\n else {\n throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);\n }\n }\n const encodePoint = toBytes === undefined ? pointToBytes : toBytes;\n const decodePoint = fromBytes === undefined ? pointFromBytes : fromBytes;\n // Hoisted from double() / add(): curve params never change after construction.\n // Koblitz curves (a=0, e.g. secp256k1) skip the three a-multiplications per operation;\n // the selection depends only on public curve constants.\n const b3 = Fp.mul(CURVE.b, _3n);\n const mulA = Fp.is0(CURVE.a) ? (_) => Fp.ZERO : (x) => Fp.mul(CURVE.a, x);\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x);\n const x3 = Fp.mul(x2, x);\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x, y) {\n const left = Fp.sqr(y);\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n // Keep constructor-time generator validation cheap: callers are responsible for supplying the\n // correct prime-order base point, while eager subgroup checks here would slow heavy module imports.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2)))\n throw new Error('bad curve params: a or b');\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title, n, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n)))\n throw new Error(`bad point coordinate ${title}`);\n // Extension-field elements are objects. Keep point coordinates detached from caller-owned\n // objects so their mutation cannot invalidate cached on-curve / subgroup checks. Primitive\n // field elements (bigints in shipped prime fields) are already immutable values.\n return typeof n === 'object' && n !== null ? Fp.create(n) : n;\n }\n function aprjpoint(other) {\n if (!(other instanceof Point))\n throw new Error('Weierstrass Point expected');\n }\n function splitEndoScalarN(k) {\n if (!endo || !endo.basises)\n throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n /**\n * Appends a (point, scalar) pair to the inputs of a vartime wNAF walk\n * ({@link mulAddUnsafe}). With GLV endomorphism the scalar is split into two half-width\n * pairs against P and ψ(P) = (β⋅x, y), halving the walk's shared doubling chain;\n * split signs fold into the points.\n */\n function pushWnafPair(points, scalars, p, k) {\n if (!Fn.isValid(k))\n throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(k);\n const psi = new Point(Fp.mul(p.X, endo.beta), p.Y, p.Z);\n points.push(k1neg ? p.negate() : p, k2neg ? psi.negate() : psi);\n scalars.push(k1, k2);\n }\n else {\n points.push(p);\n scalars.push(k);\n }\n }\n // Successful assertValidity() results are cached: Point instances are frozen at construction,\n // so on-curve + subgroup facts cannot change afterwards. Only success is cached — invalid\n // points re-throw on every call. This matters most for pairing curves, where subgroup checks\n // cost a scalar multiplication and the same instance is re-validated across layers\n // (signature fromBytes, pairingBatch) or across repeated verifies with a cached public key.\n const validityCache = new WeakSet();\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n static Fp = Fp;\n static Fn = Fn;\n X;\n Y;\n Z;\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X, Y, Z) {\n this.X = acoord('x', X);\n // This is not just about ZERO / infinity: ambient curves can have real\n // finite points with y=0. Those points are 2-torsion, so they cannot lie\n // in the odd prime-order subgroups this point type is meant to represent.\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n static fromBytes(bytes) {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex) {\n return Point.fromBytes(hexToBytes(hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * @param isLazy - true will defer table computation until the first multiplication\n */\n precompute(windowSize = 6, isLazy = true) {\n wnaf.setWindowSize(this, windowSize);\n if (!isLazy)\n this.multiply(_3n); // random number\n return this;\n }\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity() {\n const p = this;\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points\n // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.\n if (allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))\n return;\n throw new Error('bad point: ZERO');\n }\n if (validityCache.has(p))\n return;\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n validityCache.add(p);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n /** Compare one point to another. */\n equals(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate() {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = mulA(Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = mulA(t2);\n t3 = Fp.sub(t0, t2);\n t3 = mulA(t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = mulA(t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = mulA(t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = mulA(t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aprjpoint(other);\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n /**\n * Constant time multiplication.\n * Uses precomputed tables (signed fixed-window wNAF) when available.\n * Uses scalar blinding and avoids endomorphism splitting in the secret-scalar path.\n * @param scalar - by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In key/signature-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar))\n throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);\n return normalize([p, f])[0];\n }\n /**\n * Non-constant-time multiplication. Uses width-4 wNAF with GLV endomorphism splitting\n * when available (two half-width scalars sharing one halved doubling chain).\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(scalar) {\n const p = this;\n const sc = scalar;\n // Public-scalar callers may need 0, but n and larger values stay rejected here too.\n // Reducing them mod n would turn bad caller input into an accidental identity point.\n if (!Fn.isValid(sc))\n throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0())\n return Point.ZERO;\n if (sc === _1n)\n return p;\n if (wnaf.hasWindowSize(this))\n return wnaf.mulUnsafe(p, sc, normalize); // precomputes\n const points = [];\n const scalars = [];\n pushWnafPair(points, scalars, p, sc);\n return mulAddUnsafe(Point, points, scalars);\n }\n /**\n * Non-constant-time double-scalar multiplication `a⋅this + b⋅other` (Strauss–Shamir).\n * Both walks share one doubling chain via {@link mulAddUnsafe}, and GLV endomorphism\n * (when available) halves the chain again by splitting each scalar into two half-width\n * parts. Used by ECDSA verification and public-key recovery for `R = u1⋅G + u2⋅P`.\n * Only for public scalars.\n */\n mulAddUnsafe(a, other, b) {\n aprjpoint(other);\n const points = [];\n const scalars = [];\n pushWnafPair(points, scalars, this, a);\n pushWnafPair(points, scalars, other, b);\n return mulAddUnsafe(Point, points, scalars);\n }\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * (X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ) {\n const p = this;\n let iz = invertedZ;\n if (iz != null && !Fp.isValid(iz))\n throw new RangeError('\"invertedZ\" expected valid field element');\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE))\n return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n }\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree() {\n if (cofactor === _1n)\n return true;\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n // unsafe() will use the uncached wNAF path internally, since CURVE_ORDER >= Fn.ORDER\n return wnaf.mulUnsafe(this, CURVE_ORDER).is0();\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n // Default fallback assumes the cofactor fits the usual subgroup-scalar\n // multiplyUnsafe() contract. Curves with larger / structured cofactors\n // should define a clearCofactor override anyway (e.g. psi/Frobenius maps).\n return this.multiplyUnsafe(cofactor);\n }\n isSmallOrder() {\n if (cofactor === _1n)\n return this.is0(); // Fast-path\n return this.clearCofactor().is0();\n }\n toBytes(isCompressed = true) {\n abool(isCompressed, 'isCompressed');\n // assertValidity() covers on-curve and subgroup membership. The encoder below repeats the\n // infinity check rather than relying on this call, so it stays correct for any caller.\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const normalize = (points) => normalizeZ(Point, points);\n const wnaf = new ScalarMultiplier(Point, randomBytes);\n // Enable W=6 wNAF precomputes. Slows down first publicKey computation.\n // Disable for tiny toy curves, with scalar fields < 6 bits.\n if (wnaf.bits >= 6)\n Point.BASE.precompute(6);\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY) {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\nfunction getWLengths(Fp, Fn) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n // Raw compact `(r || s)` signature width; DER and recovered signatures use\n // different lengths outside this helper.\n signature: 2 * Fn.BYTES,\n };\n}\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n * @param Point - Weierstrass point constructor.\n * @param ecdhOpts - Optional randomness helpers:\n * - `randomBytes` (optional): Optional RNG override.\n * @returns ECDH helper namespace.\n * @example\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n *\n * ```ts\n * import { ecdh } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const dh = ecdh(p256.Point);\n * const alice = dh.keygen();\n * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);\n * ```\n */\nexport function ecdh(Point, ecdhOpts = {}) {\n validatePointCons(Point);\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes === undefined ? wcRandomBytes : ecdhOpts.randomBytes;\n // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte\n // minimum even on toy curves.\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), {\n seed: Math.max(getMinHashLength(Fn.ORDER), 16),\n });\n function isValidSecretKey(secretKey) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n }\n catch (error) {\n return false;\n }\n }\n function isValidPublicKey(publicKey, isCompressed) {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n // SEC 1 §3.2.2: the identity is never a valid public key, even on curves whose codec\n // can decode it.\n return !Point.fromBytes(publicKey).is0();\n }\n catch (error) {\n return false;\n }\n }\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed) {\n seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey, isCompressed = true) {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n const allowedLengths = Fn._lengths;\n if (!isBytes(item))\n return undefined;\n const l = abytes(item, undefined, 'key').length;\n const isPub = l === publicKey || l === publicKeyUncompressed;\n const isSec = l === secretKey || !!allowedLengths?.includes(l);\n // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.\n if (isPub && isSec)\n return undefined;\n return isPub;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes encoded shared point from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.\n * Returns the encoded shared point on purpose: callers that need `x_P`\n * can derive it from the encoded point, but `x_P` alone cannot recover the\n * point/parity back.\n * This helper only exposes the fully validated public-key path, not cofactor DH.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns shared point encoding\n */\n function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {\n if (isProbPub(secretKeyA) === true)\n throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false)\n throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n if (b.is0())\n throw new Error('invalid public key: point at infinity');\n return b.multiply(s).toBytes(isCompressed);\n }\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n Object.freeze(utils);\n Object.freeze(lengths);\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point - created using {@link weierstrass} function\n * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:\n * - `lowS`: Default low-S policy.\n * - `hmac`: HMAC implementation used by RFC6979 DRBG.\n * - `randomBytes`: Optional RNG override.\n * - `bits2int`: Optional hash-to-int conversion override.\n * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.\n *\n * @returns ECDSA helper namespace.\n * @example\n * Create an ECDSA signer/verifier bundle for one curve implementation.\n *\n * ```ts\n * import { ecdsa } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const p256ecdsa = ecdsa(p256.Point, sha256);\n * const { secretKey, publicKey } = p256ecdsa.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256ecdsa.sign(msg, secretKey);\n * const isValid = p256ecdsa.verify(sig, msg, publicKey);\n * ```\n */\nexport function ecdsa(Point, hash, ecdsaOpts = {}) {\n validatePointCons(Point);\n // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n const hash_ = hash;\n ahash(hash_);\n validateObject(ecdsaOpts, {}, {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n });\n const opts = Object.assign({}, ecdsaOpts);\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const hmac = opts.hmac === undefined\n ? (key, msg) => nobleHmac(hash_, key, msg)\n : opts.hmac;\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n // Nonce-inversion blinding in k2sig draws `getMinHashLength(n)` bytes per sign. Probe the RNG\n // once (see {@link probeRandomBytes}, shared with ScalarMultiplier): in environments without\n // working randomness, signing downgrades to Fermat inversion (invertCt) instead of throwing on\n // every sign(). The shape of returned bytes is still validated (by mapHashToField) on every\n // blinded call, where breakage fails closed.\n const blindLength = getMinHashLength(CURVE_ORDER);\n const csprng = probeRandomBytes(randomBytes, blindLength);\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, opts);\n const defaultSigOpts = {\n prehash: true,\n lowS: typeof opts.lowS === 'boolean' ? opts.lowS : true,\n format: 'compact',\n extraEntropy: false,\n };\n // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature\n // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.\n // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the\n // smallest such lift is 1 + 2n, not 2n.\n const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title, num) {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertFieldSignIsSupported() {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n }\n // Recovery id of an affine point (x, y) whose x reduces to signature `r` mod n:\n // bit 0 = y parity, bit 1 = x overflowed the group order (x = r + n).\n function getRecoveryBit(x, y, r) {\n assertFieldSignIsSupported();\n return (x === r ? 0 : 2) | Number(Fp.isOdd(y));\n }\n function assertRecoverableCurve() {\n // ECDSA recovery only supports curves where the current recovery id can distinguish\n // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.\n // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.\n // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit recovered signatures for those curves.\n if (hasLargeRecoveryLifts)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes, format) {\n validateSigFormat(format);\n const size = lengths.signature;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature {\n r;\n s;\n recovery;\n constructor(r, s, recovery) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertRecoverableCurve();\n if (![0, 1, 2, 3].includes(recovery))\n throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n static fromBytes(bytes, format = defaultSigOpts.format) {\n validateSigLength(bytes, format);\n let recid;\n if (format === 'der') {\n // Valid scalar INTEGERs use at most Fn.BYTES plus one DER sign-padding byte. Keep the\n // total bound conservative so malformed inputs are rejected before parsing any INTEGER.\n if (bytes.length > 2 * Fn.BYTES + 16)\n throw new DER.Err('invalid signature: DER signature too long');\n const { r, s } = DER.toSig(abytes(bytes), Fn.BYTES + 1);\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n static fromHex(hex, format) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n assertRecovery() {\n const { recovery } = this;\n if (recovery == null)\n throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n // Unlike the top-level helper below, this method expects a digest that has\n // already been hashed to the curve's message representative.\n recoverPublicKey(messageHash) {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj))\n throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.mulAddUnsafe(u1, R, u2);\n if (Q.is0())\n throw new Error('invalid recovery: point at infinify');\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n toBytes(format = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der')\n return hexToBytes(DER.hexFromSig(this));\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertRecoverableCurve();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);\n }\n return concatBytes(rb, sb);\n }\n toHex(format) {\n return bytesToHex(this.toBytes(format));\n }\n }\n Object.freeze(Signature.prototype);\n Object.freeze(Signature);\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = opts.bits2int === undefined\n ? function bits2int_def(bytes) {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192)\n throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n }\n : opts.bits2int;\n const bits2int_modN = opts.bits2int_modN === undefined\n ? function bits2int_modN_def(bytes) {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n }\n : opts.bits2int_modN;\n const ORDER_MASK = bitMask(fnBits);\n // Pads output with zero as per spec.\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num) {\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n function validateMsgAndHash(message, prehash) {\n abytes(message, undefined, 'message');\n return (prehash ? abytes(hash_(message), undefined, 'prehashed message') : message);\n }\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(message, secretKey, opts) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d))\n throw new Error('invalid private key');\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // The nonce inversion is blinded: with random b ∈ [1,n−1], s = (bk)^-1(bm + bdr) per\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. Fn.inv()'s extended-Euclidean\n // loop count depends on its input (cf. Minerva), but here it only ever sees b·k — uniformly\n // random, independent of k — so its timing reveals nothing about the nonce; b also masks d in\n // the products. Without a CSPRNG (probed in ecdsa()) we fall back to Fermat inversion\n // (invertCt), whose control flow is data-independent, at ~4x the inversion cost.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k))\n return; // Valid scalars (including k) must be in 1..N-1\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n let s;\n if (csprng !== undefined) {\n // mapHashToField maps 1.5x-order-length uniform bytes into [1, n-1], negligible bias.\n const b = bytesToNumberBE(mapHashToField(csprng(blindLength), CURVE_ORDER));\n const ibk = Fn.inv(Fn.mul(b, k)); // (bk)^-1: inversion input is decorrelated from k\n const bm = Fn.mul(b, m);\n const bd = Fn.mul(b, d);\n s = Fn.create(ibk * Fn.create(bm + bd * r)); // s = (bk)^-1(bm + bdr) = k^-1(m + rd) mod n\n }\n else {\n const ik = invertCt(k, CURVE_ORDER); // k^-1 mod n with data-independent control flow\n s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n }\n if (s === _0n)\n return;\n let recovery = getRecoveryBit(q.x, q.y, r); // recovery bit (2 or 3 when q.x>n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n /**\n * Signs a message or message hash with a secret key.\n * With the default `prehash: true`, raw message bytes are hashed internally;\n * only `{ prehash: false }` expects a caller-supplied digest.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message, secretKey, opts = {}) {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1⋅G + u2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, message, publicKey, opts = {}) {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n // SEC 1 verification keys must not be the identity, even when the generic point decoder\n // permits infinity for another protocol (for example, a pairing curve).\n if (P.is0())\n return false;\n if (lowS && sig.hasHighS())\n return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.mulAddUnsafe(u1, P, u2); // u1⋅G + u2⋅P, joint Strauss–Shamir\n if (R.is0())\n return false;\n const q = R.toAffine();\n const v = Fn.create(q.x); // v = R.x mod n\n if (v !== r)\n return false;\n // R is the exact point `recoverPublicKey(r, recid)` reconstructs (sR = hG + rP),\n // so binding the signature to its recovery id only needs R's parity/overflow bits.\n if (format === 'recovered' && sig.recovery !== getRecoveryBit(q.x, q.y, r))\n return false;\n return true;\n }\n catch (e) {\n return false;\n }\n }\n function recoverPublicKey(signature, message, opts = {}) {\n // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message\n // bytes first unless the caller passes `{ prehash: false }`.\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n // utils.isValidPublicKey() already rejects the identity, so ECDSA needs no shadow copy.\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash: hash_,\n });\n}\n","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen } from \"./abstract/curve.js\";\nimport { createFROST, } from \"./abstract/frost.js\";\nimport { createHasher, isogenyMap, mapToCurveSimpleSWU, } from \"./abstract/hash-to-curve.js\";\nimport { Field, mapHashToField, pow2 } from \"./abstract/modular.js\";\nimport { ecdsa, weierstrass, } from \"./abstract/weierstrass.js\";\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes, copyBytes, } from \"./utils.js\";\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\nconst secp256k1_ENDO = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fpk1 = /* @__PURE__ */ Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * Generate one secp256k1 keypair, sign a message, and verify it.\n *\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = Object.create(null);\n// BIP-340 phrases tags as UTF-8, but all current standardized names here are 7-bit ASCII.\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(asciiToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toBytes(true).slice(1);\nconst affineXToBytes = ({ x }) => Fpk1.toBytes(x);\nconst hasEven = (y) => !Fpk1.isOdd(y);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(abytes(priv, 32, 'secretKey'));\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const affine = p.toAffine();\n const scalar = hasEven(affine.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: affineXToBytes(affine) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x))\n throw new Error('invalid x: Fail if x ≥ p');\n const xx = Fp.sqr(x);\n const c = Fp.add(Fp.mulN(xx, x), BigInt(7)); // Let c = x³ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y))\n y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\n// BIP-340 callers still need to supply canonical 32-byte inputs where required; this alias only\n// parses big-endian bytes and does not enforce the fixed-width contract itself.\nconst num = bytesToNumberBE;\n/** Create tagged hash, convert it to bigint, reduce modulo-n. */\nfunction challenge(...args) {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/** Schnorr public key is just `x` coordinate of Point as per BIP340. */\nfunction schnorrGetPublicKey(secretKey) {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not\n * be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden\n * deterministic signing against side-channel and fault-injection attacks.\n */\nfunction schnorrSign(message, secretKey, auxRand = randomBytes(32)) {\n const { Fn, BASE } = Pointk1;\n // Snapshot once: nonce, challenge, and self-verification must use one transcript.\n const m = copyBytes(abytes(message, undefined, 'message'));\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n // Let t be the byte-wise xor of bytes(d) and hash/aux(a).\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a)));\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // BIP340 defines k' = int(rand) mod n. We can't reuse schnorrGetExtPubKey(rand)\n // here: that helper parses canonical secret keys and rejects rand >= n instead\n // of reducing the nonce hash modulo the group order.\n const k_ = Fn.create(num(rand));\n // BIP-340: \"Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G.\"\n if (k_ === _0n)\n throw new Error('sign failed: k is zero');\n const p = BASE.multiply(k_); // Rejects zero; only the raw nonce hash needs reduction.\n const affine = p.toAffine();\n const k = hasEven(affine.y) ? k_ : Fn.neg(k_);\n const rx = affineXToBytes(affine);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const rBytes = sig.subarray(0, 32);\n const r = num(rBytes); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!Fp.isValidNot0(r))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches\n // s = 0 only with negligible probability (k + e*d ≡ 0 mod n), so treat zero-s inputs as\n // crafted edge cases and fail closed instead of carrying that extra verification surface.\n if (!Fn.isValidNot0(s))\n return false;\n // int(challenge(bytes(r) || bytes(P) || m)) % n\n const e = challenge(rBytes, pointToBytes(P), m);\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.mulAddUnsafe(s, P, Fn.neg(e)); // s⋅G + (-e)⋅P, joint Strauss–Shamir\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n if (R.is0() || !hasEven(y) || !Fp.eql(x, r))\n return false;\n return true;\n }\n catch (error) {\n return false;\n }\n}\nexport const __TEST = /* @__PURE__ */ Object.freeze({ lift_x, frostTweakPublic, frostTweakSecret });\n/**\n * Schnorr signatures over secp256k1.\n * See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}.\n * @example\n * Generate one BIP340 Schnorr keypair, sign a message, and verify it.\n *\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed) => {\n seed = seed === undefined ? randomBytes(seedLength) : seed;\n return mapHashToField(abytes(seed, seedLength, 'seed'), secp256k1_CURVE.n);\n };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: Object.freeze({\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n }),\n lengths: Object.freeze({\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n }),\n });\n})();\n// RFC 9380 Appendix E.1 3-isogeny coefficients for secp256k1, stored in ascending degree order.\n// The final `1` in each denominator array is the explicit monic leading term.\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\n// RFC 9380 §8.7 secp256k1 E' parameters for the SWU-to-isogeny pipeline below.\nlet mapSWU;\nconst getMapSWU = () => mapSWU ||\n (mapSWU = mapToCurveSimpleSWU(Fpk1, {\n // Building the SWU sqrt-ratio helper eagerly adds noticeable `secp256k1.js` import cost, so\n // defer it to first use; after that the cached mapper is reused directly.\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }));\n/**\n * Hashing / encoding to secp256k1 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto secp256k1.\n *\n * ```ts\n * const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(Pointk1, (scalars) => {\n const { x, y } = getMapSWU()(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\n/**\n * FROST threshold signatures over secp256k1. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 secp256k1 signing.\n *\n * ```ts\n * const alice = secp256k1_FROST.Identifier.derive('alice@example.com');\n * const bob = secp256k1_FROST.Identifier.derive('bob@example.com');\n * const carol = secp256k1_FROST.Identifier.derive('carol@example.com');\n * const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const secp256k1_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-secp256k1-SHA256-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n}))();\n// Taproot utils\n// `undefined` means \"disable TapTweak entirely\"; callers that want the BIP-341/BIP-386 empty\n// merkle root must pass `new Uint8Array(0)` explicitly.\nfunction tweak(point, merkleRoot) {\n if (merkleRoot === undefined)\n return _0n;\n const x = pointToBytes(point);\n const t = bytesToNumberBE(taggedHash('TapTweak', x, merkleRoot));\n // BIP-341 taproot_tweak_pubkey/taproot_tweak_seckey: \"if t >= SECP256K1_ORDER:\n // raise ValueError\". TapTweak must reject overflow instead of reducing modulo n.\n if (!Pointk1.Fn.isValid(t))\n throw new Error('invalid TapTweak hash');\n return t;\n}\nfunction frostPubToEvenY(pub) {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can skip unnecessary cloning.\n if (hasEven(VK.y))\n return pub;\n return {\n signers: { min: pub.signers.min, max: pub.signers.max },\n commitments: pub.commitments.map((i) => Pointk1.fromBytes(i).negate().toBytes()),\n verifyingShares: Object.fromEntries(Object.entries(pub.verifyingShares).map(([k, v]) => [\n k,\n Pointk1.fromBytes(v).negate().toBytes(),\n ])),\n };\n}\nfunction frostSecretToEvenY(s, pub) {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can preserve package identity.\n if (hasEven(VK.y))\n return s;\n const Fn = Pointk1.Fn;\n return {\n ...s,\n signingShare: Fn.toBytes(Fn.neg(Fn.fromBytes(s.signingShare))),\n };\n}\nfunction frostNoncesToEvenY(groupCommitment, nonces) {\n if (hasEven(groupCommitment.y))\n return nonces;\n const Fn = Pointk1.Fn;\n return {\n binding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.binding))),\n hiding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.hiding))),\n };\n}\nfunction frostTweakSecret(s, pub, merkleRoot) {\n const Fn = Pointk1.Fn;\n const keyPackage = frostSecretToEvenY(s, pub);\n const evenPub = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(evenPub.commitments[0]), merkleRoot);\n const signingShare = Fn.toBytes(Fn.add(Fn.fromBytes(keyPackage.signingShare), t));\n return {\n identifier: keyPackage.identifier,\n signingShare,\n };\n}\nfunction frostTweakPublic(pub, merkleRoot) {\n const PKPackage = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(PKPackage.commitments[0]), merkleRoot);\n // Disabled TapTweak (t=0): return the even-Y-normalized package as-is. multiply() rejects\n // zero scalars, and adding [0]G would be a no-op anyway.\n if (t === _0n)\n return PKPackage;\n const tp = Pointk1.BASE.multiply(t);\n const commitments = PKPackage.commitments.map((c, i) => (i === 0 ? Pointk1.fromBytes(c).add(tp) : Pointk1.fromBytes(c)).toBytes());\n const verifyingShares = {};\n for (const k in PKPackage.verifyingShares) {\n verifyingShares[k] = Pointk1.fromBytes(PKPackage.verifyingShares[k]).add(tp).toBytes();\n }\n return {\n signers: { min: PKPackage.signers.min, max: PKPackage.signers.max },\n commitments,\n verifyingShares,\n };\n}\n/**\n * FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591.\n * DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while\n * `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves.\n * @example\n * Create one trusted-dealer package for Taproot-compatible FROST signing.\n *\n * ```ts\n * const alice = schnorr_FROST.Identifier.derive('alice@example.com');\n * const bob = schnorr_FROST.Identifier.derive('bob@example.com');\n * const carol = schnorr_FROST.Identifier.derive('carol@example.com');\n * const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const schnorr_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-secp256k1-SHA256-TR-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n // Taproot related hacks\n parsePublicKey(publicKey) {\n // External Taproot keys are x-only, but local key packages still use compressed points.\n if (publicKey.length === 32)\n return lift_x(bytesToNumberBE(publicKey));\n if (publicKey.length === 33)\n return Pointk1.fromBytes(publicKey);\n throw new Error(`expected x-only or compressed public key, got length=${publicKey.length}`);\n },\n adjustScalar(n) {\n const PK = Pointk1.BASE.multiply(n);\n return hasEven(PK.y) ? n : Pointk1.Fn.neg(n);\n },\n adjustPoint: (p) => (hasEven(p.y) ? p : p.negate()),\n challenge(R, PK, msg) {\n return challenge(pointToBytes(R), pointToBytes(PK), msg);\n },\n adjustNonces: frostNoncesToEvenY,\n adjustGroupCommitmentShare: (GC, GCShare) => (!hasEven(GC.y) ? GCShare.negate() : GCShare),\n adjustPublic: frostPubToEvenY,\n adjustSecret: frostSecretToEvenY,\n adjustTx: {\n // Compat with official implementation\n encode: (tx) => tx.subarray(1),\n decode: (tx) => concatBytes(Uint8Array.of(0x02), tx),\n },\n adjustDKG: (k) => {\n // Compatibility with frost-secp256k1-tr: DKG output is auto-tweaked with the\n // empty Taproot merkle root, while dealer-generated keys stay untweaked.\n const merkleRoot = new Uint8Array(0);\n return {\n public: frostTweakPublic(k.public, merkleRoot),\n secret: frostTweakSecret(k.secret, k.public, merkleRoot),\n };\n },\n}))();\n","import { secp256k1 as secp } from '@noble/curves/secp256k1.js';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { SigningError, VerificationError } from \"../../errors.js\";\nimport { isPromise } from \"../../util.js\";\nconst PUBLIC_KEY_BYTE_LENGTH = 33;\nconst PRIVATE_KEY_BYTE_LENGTH = 32;\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength };\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign(key, msg, options) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p\n .then(({ digest }) => {\n options?.signal?.throwIfAborted();\n return secp.sign(digest, key, {\n prehash: false,\n format: 'der'\n });\n })\n .catch(err => {\n if (err.name === 'AbortError') {\n throw err;\n }\n throw new SigningError(String(err));\n });\n }\n try {\n return secp.sign(p.digest, key, {\n prehash: false,\n format: 'der'\n });\n }\n catch (err) {\n throw new SigningError(String(err));\n }\n}\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify(key, sig, msg, options) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p\n .then(({ digest }) => {\n options?.signal?.throwIfAborted();\n return secp.verify(sig, digest, key, {\n prehash: false,\n format: 'der'\n });\n })\n .catch(err => {\n if (err.name === 'AbortError') {\n throw err;\n }\n throw new VerificationError(String(err));\n });\n }\n try {\n options?.signal?.throwIfAborted();\n return secp.verify(sig, p.digest, key, {\n prehash: false,\n format: 'der'\n });\n }\n catch (err) {\n throw new VerificationError(String(err));\n }\n}\n//# sourceMappingURL=index.browser.js.map","import { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport { identity } from 'multiformats/hashes/identity';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { publicKeyToProtobuf } from \"../index.js\";\nimport { hashAndVerify, hashAndSign } from \"./index.js\";\nimport { validateSecp256k1PublicKey, compressSecp256k1PublicKey, computeSecp256k1PublicKey, validateSecp256k1PrivateKey } from \"./utils.js\";\nexport class Secp256k1PublicKey {\n type = 'secp256k1';\n raw;\n _key;\n constructor(key) {\n this._key = validateSecp256k1PublicKey(key);\n this.raw = compressSecp256k1PublicKey(this._key);\n }\n toMultihash() {\n return identity.digest(publicKeyToProtobuf(this));\n }\n toCID() {\n return CID.createV1(114, this.toMultihash());\n }\n toString() {\n return base58btc.encode(this.toMultihash().bytes).substring(1);\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n verify(data, sig, options) {\n return hashAndVerify(this._key, sig, data, options);\n }\n}\nexport class Secp256k1PrivateKey {\n type = 'secp256k1';\n raw;\n publicKey;\n constructor(key, publicKey) {\n this.raw = validateSecp256k1PrivateKey(key);\n this.publicKey = new Secp256k1PublicKey(publicKey ?? computeSecp256k1PublicKey(key));\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n sign(message, options) {\n return hashAndSign(this.raw, message, options);\n }\n}\n//# sourceMappingURL=secp256k1.js.map","import { InvalidPrivateKeyError, InvalidPublicKeyError } from '@libp2p/interface';\nimport { secp256k1 as secp } from '@noble/curves/secp256k1.js';\nimport { Secp256k1PublicKey as Secp256k1PublicKeyClass, Secp256k1PrivateKey as Secp256k1PrivateKeyClass } from \"./secp256k1.js\";\nconst PRIVATE_KEY_BYTE_LENGTH = 32;\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function unmarshalSecp256k1PrivateKey(bytes) {\n return new Secp256k1PrivateKeyClass(bytes);\n}\nexport function unmarshalSecp256k1PublicKey(bytes) {\n return new Secp256k1PublicKeyClass(bytes);\n}\nexport async function generateSecp256k1KeyPair() {\n const privateKeyBytes = generateSecp256k1PrivateKey();\n return new Secp256k1PrivateKeyClass(privateKeyBytes);\n}\nexport function compressSecp256k1PublicKey(key) {\n return secp.Point.fromBytes(key).toBytes();\n}\nexport function decompressSecp256k1PublicKey(key) {\n return secp.Point.fromBytes(key).toBytes(false);\n}\nexport function validateSecp256k1PrivateKey(key) {\n try {\n secp.getPublicKey(key, true);\n return key;\n }\n catch (err) {\n throw new InvalidPrivateKeyError(String(err));\n }\n}\nexport function validateSecp256k1PublicKey(key) {\n try {\n secp.Point.fromBytes(key);\n return key;\n }\n catch (err) {\n throw new InvalidPublicKeyError(String(err));\n }\n}\nexport function computeSecp256k1PublicKey(privateKey) {\n try {\n return secp.getPublicKey(privateKey, true);\n }\n catch (err) {\n throw new InvalidPrivateKeyError(String(err));\n }\n}\nexport function generateSecp256k1PrivateKey() {\n return secp.utils.randomSecretKey();\n}\n//# sourceMappingURL=utils.js.map","/**\n * @packageDocumentation\n *\n * ## Supported Key Types\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\nimport { InvalidParametersError, InvalidPublicKeyError, UnsupportedKeyTypeError } from '@libp2p/interface';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { ECDSAPrivateKey as ECDSAPrivateKeyClass } from \"./ecdsa/ecdsa.js\";\nimport { ECDSA_P_256_OID, ECDSA_P_384_OID, ECDSA_P_521_OID } from \"./ecdsa/index.js\";\nimport { generateECDSAKeyPair, pkiMessageToECDSAPrivateKey, pkiMessageToECDSAPublicKey, unmarshalECDSAPrivateKey, unmarshalECDSAPublicKey } from \"./ecdsa/utils.js\";\nimport { privateKeyLength as ed25519PrivateKeyLength, publicKeyLength as ed25519PublicKeyLength } from \"./ed25519/index.js\";\nimport { generateEd25519KeyPair, generateEd25519KeyPairFromSeed, unmarshalEd25519PrivateKey, unmarshalEd25519PublicKey } from \"./ed25519/utils.js\";\nimport * as pb from \"./keys.js\";\nimport { decodeDer } from \"./rsa/der.js\";\nimport { RSAES_PKCS1_V1_5_OID } from \"./rsa/index.js\";\nimport { pkcs1ToRSAPrivateKey, pkixToRSAPublicKey, generateRSAKeyPair, pkcs1MessageToRSAPrivateKey, pkixMessageToRSAPublicKey, jwkToRSAPrivateKey } from \"./rsa/utils.js\";\nimport { privateKeyLength as secp256k1PrivateKeyLength, publicKeyLength as secp256k1PublicKeyLength } from \"./secp256k1/index.js\";\nimport { generateSecp256k1KeyPair, unmarshalSecp256k1PrivateKey, unmarshalSecp256k1PublicKey } from \"./secp256k1/utils.js\";\nexport { generateEphemeralKeyPair } from \"./ecdh/index.js\";\nexport { keyStretcher } from \"./key-stretcher.js\";\nexport async function generateKeyPair(type, bits) {\n if (type === 'Ed25519') {\n return generateEd25519KeyPair();\n }\n if (type === 'secp256k1') {\n return generateSecp256k1KeyPair();\n }\n if (type === 'RSA') {\n return generateRSAKeyPair(toBits(bits));\n }\n if (type === 'ECDSA') {\n return generateECDSAKeyPair(toCurve(bits));\n }\n throw new UnsupportedKeyTypeError();\n}\nexport async function generateKeyPairFromSeed(type, seed) {\n if (type !== 'Ed25519') {\n throw new UnsupportedKeyTypeError('Seed key derivation only supported for Ed25519 keys');\n }\n return generateEd25519KeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object.\n *\n * For RSA public keys optionally pass the multihash digest of the public key if\n * it is known. If the digest is omitted it will be calculated which can be\n * expensive.\n *\n * For other key types the digest option is ignored.\n */\nexport function publicKeyFromProtobuf(buf, digest) {\n const { Type, Data } = pb.PublicKey.decode(buf);\n const data = Data ?? new Uint8Array();\n switch (Type) {\n case pb.KeyType.RSA:\n return pkixToRSAPublicKey(data, digest);\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PublicKey(data);\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PublicKey(data);\n case pb.KeyType.ECDSA:\n return unmarshalECDSAPublicKey(data);\n default:\n throw new UnsupportedKeyTypeError();\n }\n}\n/**\n * Creates a public key from the raw key bytes\n */\nexport function publicKeyFromRaw(buf) {\n if (buf.byteLength === ed25519PublicKeyLength) {\n return unmarshalEd25519PublicKey(buf);\n }\n else if (buf.byteLength === secp256k1PublicKeyLength) {\n return unmarshalSecp256k1PublicKey(buf);\n }\n const message = decodeDer(buf);\n const ecdsaOid = message[1]?.[0];\n if (ecdsaOid === ECDSA_P_256_OID || ecdsaOid === ECDSA_P_384_OID || ecdsaOid === ECDSA_P_521_OID) {\n return pkiMessageToECDSAPublicKey(message);\n }\n if (message[0]?.[0] === RSAES_PKCS1_V1_5_OID) {\n return pkixMessageToRSAPublicKey(message, buf);\n }\n throw new InvalidParametersError('Could not extract public key from raw bytes');\n}\n/**\n * Creates a public key from an identity multihash which contains a protobuf\n * encoded Ed25519 or secp256k1 public key.\n *\n * RSA keys are not supported as in practice we they are not stored in identity\n * multihash since the hash would be very large.\n */\nexport function publicKeyFromMultihash(digest) {\n const { Type, Data } = pb.PublicKey.decode(digest.digest);\n const data = Data ?? new Uint8Array();\n switch (Type) {\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PublicKey(data);\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PublicKey(data);\n case pb.KeyType.ECDSA:\n return unmarshalECDSAPublicKey(data);\n default:\n throw new UnsupportedKeyTypeError();\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function publicKeyToProtobuf(key) {\n return pb.PublicKey.encode({\n Type: pb.KeyType[key.type],\n Data: key.raw\n });\n}\n/**\n * Returns a public key for the peer that is safe for verifying its signatures.\n *\n * A supplied key must derive to the peer id, otherwise `InvalidPublicKeyError`\n * is thrown, even if the peer id embeds a key. With no supplied key the key\n * inlined in the peer id is returned, or `InvalidPublicKeyError` is thrown if\n * there is none. Malformed key bytes also throw `InvalidPublicKeyError`.\n */\nexport async function publicKeyForPeer(peer, key, options) {\n options?.signal?.throwIfAborted();\n if (key != null) {\n let publicKey;\n try {\n publicKey = key instanceof Uint8Array ? publicKeyFromProtobuf(key) : key;\n }\n catch (err) {\n throw new InvalidPublicKeyError(`Could not decode public key - ${err.message}`);\n }\n if (!uint8ArrayEquals(publicKey.toMultihash().bytes, peer.toMultihash().bytes)) {\n throw new InvalidPublicKeyError('Public key does not match peer id');\n }\n return publicKey;\n }\n if (peer.publicKey == null) {\n throw new InvalidPublicKeyError('No public key available for peer id');\n }\n return peer.publicKey;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport function privateKeyFromProtobuf(buf) {\n const decoded = pb.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case pb.KeyType.RSA:\n return pkcs1ToRSAPrivateKey(data);\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PrivateKey(data);\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PrivateKey(data);\n case pb.KeyType.ECDSA:\n return unmarshalECDSAPrivateKey(data);\n default:\n throw new UnsupportedKeyTypeError();\n }\n}\n/**\n * Creates a private key from the raw key bytes. For Ed25519 keys this requires\n * the public key to be appended to the private key otherwise we can't\n * differentiate between Ed25519 and secp256k1 keys as they are the same length.\n */\nexport function privateKeyFromRaw(buf) {\n if (buf.byteLength === ed25519PrivateKeyLength) {\n return unmarshalEd25519PrivateKey(buf);\n }\n else if (buf.byteLength === secp256k1PrivateKeyLength) {\n return unmarshalSecp256k1PrivateKey(buf);\n }\n const message = decodeDer(buf);\n const ecdsaOid = message[2]?.[0];\n if (ecdsaOid === ECDSA_P_256_OID || ecdsaOid === ECDSA_P_384_OID || ecdsaOid === ECDSA_P_521_OID) {\n return pkiMessageToECDSAPrivateKey(message);\n }\n if (message.length > 8) {\n return pkcs1MessageToRSAPrivateKey(message);\n }\n throw new InvalidParametersError('Could not extract private key from raw bytes');\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function privateKeyToProtobuf(key) {\n return pb.PrivateKey.encode({\n Type: pb.KeyType[key.type],\n Data: key.raw\n });\n}\nfunction toBits(bits) {\n if (bits == null) {\n return 2048;\n }\n return parseInt(bits, 10);\n}\nfunction toCurve(curve) {\n if (curve === 'P-256' || curve == null) {\n return 'P-256';\n }\n if (curve === 'P-384') {\n return 'P-384';\n }\n if (curve === 'P-521') {\n return 'P-521';\n }\n throw new InvalidParametersError('Unsupported curve, should be P-256, P-384 or P-521');\n}\n/**\n * Convert a libp2p RSA or ECDSA private key to a WebCrypto CryptoKeyPair\n */\nexport async function privateKeyToCryptoKeyPair(privateKey) {\n if (privateKey.type === 'RSA') {\n return {\n privateKey: await crypto.subtle.importKey('jwk', privateKey.jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']),\n publicKey: await crypto.subtle.importKey('jwk', privateKey.publicKey.jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify'])\n };\n }\n if (privateKey.type === 'ECDSA') {\n return {\n privateKey: await crypto.subtle.importKey('jwk', privateKey.jwk, {\n name: 'ECDSA',\n namedCurve: privateKey.jwk.crv ?? 'P-256'\n }, true, ['sign']),\n publicKey: await crypto.subtle.importKey('jwk', privateKey.publicKey.jwk, {\n name: 'ECDSA',\n namedCurve: privateKey.publicKey.jwk.crv ?? 'P-256'\n }, true, ['verify'])\n };\n }\n throw new InvalidParametersError('Only RSA and ECDSA keys are supported');\n}\n/**\n * Convert a RSA or ECDSA WebCrypto CryptoKeyPair to a libp2p private key\n */\nexport async function privateKeyFromCryptoKeyPair(keyPair) {\n if (keyPair.privateKey.algorithm.name === 'RSASSA-PKCS1-v1_5') {\n const jwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey);\n return jwkToRSAPrivateKey(jwk);\n }\n if (keyPair.privateKey.algorithm.name === 'ECDSA') {\n const jwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey);\n return new ECDSAPrivateKeyClass(jwk);\n }\n throw new InvalidParametersError('Only RSA and ECDSA keys are supported');\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\nimport { peerIdSymbol } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport { identity } from 'multiformats/hashes/identity';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nclass PeerIdImpl {\n type;\n multihash;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n toMultihash() {\n return this.multihash;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return this.toString() === id;\n }\n else if (id?.toMultihash()?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.toMultihash().bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nexport class RSAPeerId extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nexport class Ed25519PeerId extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.publicKey;\n }\n}\nexport class Secp256k1PeerId extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.publicKey;\n }\n}\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nexport class URLPeerId {\n type = 'url';\n multihash;\n publicKey;\n url;\n constructor(url) {\n this.url = url.toString();\n this.multihash = identity.digest(uint8ArrayFromString(this.url));\n }\n [inspect]() {\n return `PeerId(${this.url})`;\n }\n [peerIdSymbol] = true;\n toString() {\n return this.toCID().toString();\n }\n toMultihash() {\n return this.multihash;\n }\n toCID() {\n return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.toMultihash());\n }\n toJSON() {\n return this.toString();\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (other instanceof Uint8Array) {\n other = uint8ArrayToString(other);\n }\n return other.toString() === this.toString();\n }\n}\n//# sourceMappingURL=peer-id.js.map","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\nimport { publicKeyFromMultihash } from '@libp2p/crypto/keys';\nimport { InvalidCIDError, InvalidMultihashError, InvalidParametersError, UnsupportedKeyTypeError } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport * as Digest from 'multiformats/hashes/digest';\nimport { identity } from 'multiformats/hashes/identity';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { RSAPeerId as RSAPeerIdClass, Ed25519PeerId as Ed25519PeerIdClass, Secp256k1PeerId as Secp256k1PeerIdClass, URLPeerId as URLPeerIdClass } from \"./peer-id.js\";\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nexport function peerIdFromString(str, decoder) {\n let multihash;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n multihash = Digest.decode(base58btc.decode(`z${str}`));\n }\n else if (str.startsWith('k51qzi5uqu5') || str.startsWith('kzwfwjn5ji4') || str.startsWith('k2k4r8') || str.startsWith('bafz')) {\n // base36 encoded CIDv1 with libp2p-key and identity hash (for ed25519/secp256k1/rsa) or base32 encoded CIDv1 with libp2p-key and identity hash (for ed25519/secp256k1/rsa)\n return peerIdFromCID(CID.parse(str));\n }\n else {\n if (decoder == null) {\n throw new InvalidParametersError('Please pass a multibase decoder for strings that do not start with \"1\" or \"Q\"');\n }\n multihash = Digest.decode(decoder.decode(str));\n }\n return peerIdFromMultihash(multihash);\n}\nexport function peerIdFromPublicKey(publicKey) {\n if (publicKey.type === 'Ed25519') {\n return new Ed25519PeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n });\n }\n else if (publicKey.type === 'secp256k1') {\n return new Secp256k1PeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n });\n }\n else if (publicKey.type === 'RSA') {\n return new RSAPeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n });\n }\n throw new UnsupportedKeyTypeError();\n}\nexport function peerIdFromPrivateKey(privateKey) {\n return peerIdFromPublicKey(privateKey.publicKey);\n}\nexport function peerIdFromMultihash(multihash) {\n if (isSha256Multihash(multihash)) {\n return new RSAPeerIdClass({ multihash });\n }\n else if (isIdentityMultihash(multihash)) {\n try {\n const publicKey = publicKeyFromMultihash(multihash);\n if (publicKey.type === 'Ed25519') {\n return new Ed25519PeerIdClass({ multihash, publicKey });\n }\n else if (publicKey.type === 'secp256k1') {\n return new Secp256k1PeerIdClass({ multihash, publicKey });\n }\n }\n catch (err) {\n // was not Ed or secp key, try URL\n const url = uint8ArrayToString(multihash.digest);\n return new URLPeerIdClass(new URL(url));\n }\n }\n throw new InvalidMultihashError('Supplied PeerID Multihash is invalid');\n}\nexport function peerIdFromCID(cid) {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new InvalidCIDError('Supplied PeerID CID is invalid');\n }\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = uint8ArrayToString(cid.multihash.digest);\n return new URLPeerIdClass(new URL(url));\n }\n return peerIdFromMultihash(cid.multihash);\n}\nfunction isIdentityMultihash(multihash) {\n return multihash.code === identity.code;\n}\nfunction isSha256Multihash(multihash) {\n return multihash.code === sha256.code;\n}\n//# sourceMappingURL=index.js.map","import { decodeMessage, encodeMessage, MaxLengthError, message, streamMessage } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var NoiseExtensions;\n(function (NoiseExtensions) {\n let _codec;\n NoiseExtensions.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.webtransportCerthashes != null && obj.webtransportCerthashes.length > 0) {\n for (const value of obj.webtransportCerthashes) {\n w.uint32(10);\n w.bytes(value);\n }\n }\n if (obj.streamMuxers != null && obj.streamMuxers.length > 0) {\n for (const value of obj.streamMuxers) {\n w.uint32(18);\n w.string(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n webtransportCerthashes: [],\n streamMuxers: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.webtransportCerthashes != null && obj.webtransportCerthashes.length === opts.limits.webtransportCerthashes) {\n throw new MaxLengthError('Decode error - repeated field \"webtransportCerthashes\" had too many elements');\n }\n obj.webtransportCerthashes.push(reader.bytes());\n break;\n }\n case 2: {\n if (opts.limits?.streamMuxers != null && obj.streamMuxers.length === opts.limits.streamMuxers) {\n throw new MaxLengthError('Decode error - repeated field \"streamMuxers\" had too many elements');\n }\n obj.streamMuxers.push(reader.string());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n }, function* (reader, length, prefix, opts = {}) {\n const obj = {\n webtransportCerthashes: 0,\n streamMuxers: 0\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.webtransportCerthashes != null && obj.webtransportCerthashes === opts.limits.webtransportCerthashes) {\n throw new MaxLengthError('Streaming decode error - repeated field \"webtransportCerthashes\" had too many elements');\n }\n yield {\n field: `${prefix}.webtransportCerthashes[]`,\n index: obj.webtransportCerthashes,\n value: reader.bytes()\n };\n obj.webtransportCerthashes++;\n break;\n }\n case 2: {\n if (opts.limits?.streamMuxers != null && obj.streamMuxers === opts.limits.streamMuxers) {\n throw new MaxLengthError('Streaming decode error - repeated field \"streamMuxers\" had too many elements');\n }\n yield {\n field: `${prefix}.streamMuxers[]`,\n index: obj.streamMuxers,\n value: reader.string()\n };\n obj.streamMuxers++;\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n });\n }\n return _codec;\n };\n function encode(obj) {\n return encodeMessage(obj, NoiseExtensions.codec());\n }\n NoiseExtensions.encode = encode;\n function decode(buf, opts) {\n return decodeMessage(buf, NoiseExtensions.codec(), opts);\n }\n NoiseExtensions.decode = decode;\n function stream(buf, opts) {\n return streamMessage(buf, NoiseExtensions.codec(), opts);\n }\n NoiseExtensions.stream = stream;\n})(NoiseExtensions || (NoiseExtensions = {}));\nexport var NoiseHandshakePayload;\n(function (NoiseHandshakePayload) {\n let _codec;\n NoiseHandshakePayload.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.identityKey != null && obj.identityKey.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.identityKey);\n }\n if ((obj.identitySig != null && obj.identitySig.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.identitySig);\n }\n if (obj.extensions != null) {\n w.uint32(34);\n NoiseExtensions.codec().encode(obj.extensions, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n identityKey: uint8ArrayAlloc(0),\n identitySig: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.identityKey = reader.bytes();\n break;\n }\n case 2: {\n obj.identitySig = reader.bytes();\n break;\n }\n case 4: {\n obj.extensions = NoiseExtensions.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.extensions\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n }, function* (reader, length, prefix, opts = {}) {\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n yield {\n field: `${prefix}.identityKey`,\n value: reader.bytes()\n };\n break;\n }\n case 2: {\n yield {\n field: `${prefix}.identitySig`,\n value: reader.bytes()\n };\n break;\n }\n case 4: {\n yield* NoiseExtensions.codec().stream(reader, reader.uint32(), `${prefix}.extensions`, {\n limits: opts.limits?.extensions\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n });\n }\n return _codec;\n };\n function encode(obj) {\n return encodeMessage(obj, NoiseHandshakePayload.codec());\n }\n NoiseHandshakePayload.encode = encode;\n function decode(buf, opts) {\n return decodeMessage(buf, NoiseHandshakePayload.codec(), opts);\n }\n NoiseHandshakePayload.decode = decode;\n function stream(buf, opts) {\n return streamMessage(buf, NoiseHandshakePayload.codec(), opts);\n }\n NoiseHandshakePayload.stream = stream;\n})(NoiseHandshakePayload || (NoiseHandshakePayload = {}));\n//# sourceMappingURL=payload.js.map","import { publicKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys';\nimport { StreamMessageEvent, UnexpectedPeerError } from '@libp2p/interface';\nimport { peerIdFromPublicKey } from '@libp2p/peer-id';\nimport { AbstractMessageStream, LengthPrefixedDecoder } from '@libp2p/utils';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { CHACHA_TAG_LENGTH, NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from \"./constants.js\";\nimport { uint16BEEncode, uint16BEDecode } from \"./encoder.js\";\nimport { NoiseHandshakePayload } from \"./proto/payload.js\";\nexport async function createHandshakePayload(privateKey, staticPublicKey, extensions) {\n const identitySig = await privateKey.sign(getSignaturePayload(staticPublicKey));\n return NoiseHandshakePayload.encode({\n identityKey: publicKeyToProtobuf(privateKey.publicKey),\n identitySig,\n extensions\n });\n}\nexport async function decodeHandshakePayload(payloadBytes, remoteStaticKey, remotePeer) {\n try {\n const payload = NoiseHandshakePayload.decode(payloadBytes);\n const publicKey = publicKeyFromProtobuf(payload.identityKey);\n const payloadPeer = peerIdFromPublicKey(publicKey);\n // compare peer ids, an expected peer id may not carry its public key (e.g. RSA)\n if (remotePeer != null) {\n if (!remotePeer.equals(payloadPeer)) {\n throw new Error(`Payload peer id ${payloadPeer} does not match expected remote peer id ${remotePeer}`);\n }\n }\n if (!remoteStaticKey) {\n throw new Error('Remote static does not exist');\n }\n const signaturePayload = getSignaturePayload(remoteStaticKey);\n if (!(await publicKey.verify(signaturePayload, payload.identitySig))) {\n throw new Error('Invalid payload signature');\n }\n return { payload, remotePeer: payloadPeer };\n }\n catch (e) {\n throw new UnexpectedPeerError(e.message);\n }\n}\nexport function getSignaturePayload(publicKey) {\n const prefix = uint8ArrayFromString('noise-libp2p-static-key:');\n if (publicKey instanceof Uint8Array) {\n return uint8ArrayConcat([prefix, publicKey], prefix.length + publicKey.length);\n }\n publicKey.prepend(prefix);\n return publicKey;\n}\nclass EncryptedMessageStream extends AbstractMessageStream {\n stream;\n handshake;\n metrics;\n decoder;\n constructor(stream, handshake, metrics) {\n super({\n log: stream.log,\n inactivityTimeout: stream.inactivityTimeout,\n maxReadBufferLength: stream.maxReadBufferLength,\n direction: stream.direction\n });\n this.stream = stream;\n this.handshake = handshake;\n this.metrics = metrics;\n this.decoder = new LengthPrefixedDecoder({\n lengthDecoder: uint16BEDecode,\n maxBufferSize: 16 * 1024 * 1024,\n encodingLength: () => 2\n });\n const noiseOnMessageDecrypt = (evt) => {\n try {\n for (const buf of this.decoder.decode(evt.data)) {\n this.onData(this.decrypt(buf));\n }\n }\n catch (err) {\n this.abort(err);\n }\n };\n this.stream.addEventListener('message', noiseOnMessageDecrypt);\n const noiseOnClose = (evt) => {\n if (evt.error != null) {\n if (evt.local === true) {\n this.abort(evt.error);\n }\n else {\n this.onRemoteReset();\n }\n }\n else {\n this.onTransportClosed();\n }\n };\n this.stream.addEventListener('close', noiseOnClose);\n const noiseOnDrain = () => {\n this.safeDispatchEvent('drain');\n };\n this.stream.addEventListener('drain', noiseOnDrain);\n const noiseOnRemoteCloseWrite = () => {\n this.onRemoteCloseWrite();\n };\n this.stream.addEventListener('remoteCloseWrite', noiseOnRemoteCloseWrite);\n }\n encrypt(chunk) {\n const output = new Uint8ArrayList();\n for (let i = 0; i < chunk.byteLength; i += NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG;\n if (end > chunk.byteLength) {\n end = chunk.byteLength;\n }\n let data;\n if (chunk instanceof Uint8Array) {\n data = this.handshake.encrypt(chunk.subarray(i, end));\n }\n else {\n data = this.handshake.encrypt(chunk.sublist(i, end));\n }\n this.metrics?.encryptedPackets.increment();\n output.append(uint16BEEncode(data.byteLength));\n output.append(data);\n }\n return output;\n }\n decrypt(chunk) {\n const output = new Uint8ArrayList();\n for (let i = 0; i < chunk.byteLength; i += NOISE_MSG_MAX_LENGTH_BYTES) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES;\n if (end > chunk.byteLength) {\n end = chunk.byteLength;\n }\n if (end - CHACHA_TAG_LENGTH < i) {\n throw new Error('Invalid chunk');\n }\n let encrypted;\n if (chunk instanceof Uint8Array) {\n encrypted = chunk.subarray(i, end);\n }\n else {\n encrypted = chunk.sublist(i, end);\n }\n // memory allocation is not cheap so reuse the encrypted Uint8Array\n // see https://github.com/ChainSafe/js-libp2p-noise/pull/242#issue-1422126164\n // this is ok because chacha20 reads bytes one by one and don't reread after that\n // it's also tested in https://github.com/ChainSafe/as-chacha20poly1305/pull/1/files#diff-25252846b58979dcaf4e41d47b3eadd7e4f335e7fb98da6c049b1f9cd011f381R48\n const dst = chunk.subarray(i, end - CHACHA_TAG_LENGTH);\n try {\n const plaintext = this.handshake.decrypt(encrypted, dst);\n this.metrics?.decryptedPackets.increment();\n output.append(plaintext);\n }\n catch (e) {\n this.metrics?.decryptErrors.increment();\n throw e;\n }\n }\n return output;\n }\n close(options) {\n return this.stream.close(options);\n }\n sendPause() {\n this.stream.pause();\n }\n sendResume() {\n this.stream.resume();\n }\n sendReset(err) {\n this.stream.abort(err);\n }\n sendData(data) {\n return {\n sentBytes: data.byteLength,\n canSendMore: this.stream.send(this.encrypt(data))\n };\n }\n}\nexport function toMessageStream(connection, handshake, metrics) {\n return new EncryptedMessageStream(connection, handshake, metrics);\n}\n//# sourceMappingURL=utils.js.map","import { logLocalStaticKeys, logLocalEphemeralKeys, logRemoteEphemeralKey, logRemoteStaticKey, logCipherState } from \"./logger.js\";\nimport { ZEROLEN, XXHandshakeState } from \"./protocol.js\";\nimport { createHandshakePayload, decodeHandshakePayload } from \"./utils.js\";\nexport async function performHandshakeInitiator(init, options) {\n const { log, connection, crypto, privateKey, prologue, s, remotePeer, extensions } = init;\n const payload = await createHandshakePayload(privateKey, s.publicKey, extensions);\n const xx = new XXHandshakeState({\n crypto,\n protocolName: 'Noise_XX_25519_ChaChaPoly_SHA256',\n initiator: true,\n prologue,\n s\n });\n logLocalStaticKeys(xx.s, log);\n log.trace('Stage 0 - Initiator starting to send first message.');\n await connection.write(xx.writeMessageA(ZEROLEN), options);\n log.trace('Stage 0 - Initiator finished sending first message.');\n logLocalEphemeralKeys(xx.e, log);\n log.trace('Stage 1 - Initiator waiting to receive first message from responder...');\n const plaintext = xx.readMessageB(await connection.read(options));\n log.trace('Stage 1 - Initiator received the message.');\n logRemoteEphemeralKey(xx.re, log);\n logRemoteStaticKey(xx.rs, log);\n log.trace(\"Initiator going to check remote's signature...\");\n const received = await decodeHandshakePayload(plaintext, xx.rs, remotePeer);\n log.trace('All good with the signature!');\n log.trace('Stage 2 - Initiator sending third handshake message.');\n await connection.write(xx.writeMessageC(payload), options);\n log.trace('Stage 2 - Initiator sent message with signed payload.');\n const [cs1, cs2] = xx.ss.split();\n logCipherState(cs1, cs2, log);\n return {\n payload: received.payload,\n remotePeer: received.remotePeer,\n encrypt: (plaintext) => cs1.encryptWithAd(ZEROLEN, plaintext),\n decrypt: (ciphertext, dst) => cs2.decryptWithAd(ZEROLEN, ciphertext, dst)\n };\n}\nexport async function performHandshakeResponder(init, options) {\n const { log, connection, crypto, privateKey, prologue, s, remotePeer, extensions } = init;\n const payload = await createHandshakePayload(privateKey, s.publicKey, extensions);\n const xx = new XXHandshakeState({\n crypto,\n protocolName: 'Noise_XX_25519_ChaChaPoly_SHA256',\n initiator: false,\n prologue,\n s\n });\n logLocalStaticKeys(xx.s, log);\n log.trace('Stage 0 - Responder waiting to receive first message.');\n xx.readMessageA(await connection.read(options));\n log.trace('Stage 0 - Responder received first message.');\n logRemoteEphemeralKey(xx.re, log);\n log.trace('Stage 1 - Responder sending out first message with signed payload and static key.');\n await connection.write(xx.writeMessageB(payload), options);\n log.trace('Stage 1 - Responder sent the second handshake message with signed payload.');\n logLocalEphemeralKeys(xx.e, log);\n log.trace('Stage 2 - Responder waiting for third handshake message...');\n const plaintext = xx.readMessageC(await connection.read(options));\n log.trace('Stage 2 - Responder received the message, finished handshake.');\n const received = await decodeHandshakePayload(plaintext, xx.rs, remotePeer);\n const [cs1, cs2] = xx.ss.split();\n logCipherState(cs1, cs2, log);\n return {\n payload: received.payload,\n remotePeer: received.remotePeer,\n encrypt: (plaintext) => cs2.encryptWithAd(ZEROLEN, plaintext),\n decrypt: (ciphertext, dst) => cs1.decryptWithAd(ZEROLEN, ciphertext, dst)\n };\n}\n//# sourceMappingURL=performHandshake.js.map","import { InvalidCryptoExchangeError, serviceCapabilities } from '@libp2p/interface';\nimport { lpStream } from '@libp2p/utils';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { NOISE_MSG_MAX_LENGTH_BYTES } from \"./constants.js\";\nimport { defaultCrypto } from \"./crypto/index.js\";\nimport { wrapCrypto } from \"./crypto.js\";\nimport { uint16BEDecode, uint16BEEncode } from \"./encoder.js\";\nimport { registerMetrics } from \"./metrics.js\";\nimport { performHandshakeInitiator, performHandshakeResponder } from \"./performHandshake.js\";\nimport { toMessageStream } from \"./utils.js\";\nexport class Noise {\n protocol = '/noise';\n crypto;\n prologue;\n staticKey;\n extensions;\n metrics;\n components;\n log;\n constructor(components, init = {}) {\n const { staticNoiseKey, extensions, crypto, prologueBytes } = init;\n const { metrics } = components;\n this.components = components;\n this.log = components.logger.forComponent('libp2p:noise');\n const _crypto = crypto ?? defaultCrypto;\n this.crypto = wrapCrypto(_crypto);\n this.extensions = {\n webtransportCerthashes: [],\n ...extensions\n };\n this.metrics = metrics ? registerMetrics(metrics) : undefined;\n if (staticNoiseKey) {\n // accepts x25519 private key of length 32\n this.staticKey = _crypto.generateX25519KeyPairFromSeed(staticNoiseKey);\n }\n else {\n this.staticKey = _crypto.generateX25519KeyPair();\n }\n this.prologue = prologueBytes ?? uint8ArrayAlloc(0);\n }\n [Symbol.toStringTag] = '@libp2p/noise';\n [serviceCapabilities] = [\n '@libp2p/connection-encryption',\n '@libp2p/noise'\n ];\n /**\n * Encrypt outgoing data to the remote party (handshake as initiator)\n *\n * @param connection - streaming iterable duplex that will be encrypted\n * @param options\n * @param options.remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer\n * @param options.signal - Used to abort the operation\n */\n async secureOutbound(connection, options) {\n const log = connection.log?.newScope('noise') ?? this.log;\n const wrappedConnection = lpStream(connection, {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n });\n const handshake = await this.performHandshakeInitiator(wrappedConnection, this.components.privateKey, log, options?.remotePeer, options);\n return {\n connection: toMessageStream(wrappedConnection.unwrap(), handshake, this.metrics),\n remoteExtensions: handshake.payload.extensions,\n remotePeer: handshake.remotePeer,\n streamMuxer: options?.skipStreamMuxerNegotiation === true ? undefined : this.getStreamMuxer(handshake.payload.extensions?.streamMuxers)\n };\n }\n getStreamMuxer(protocols) {\n if (protocols == null || protocols.length === 0) {\n return;\n }\n const streamMuxers = this.components.upgrader.getStreamMuxers();\n if (streamMuxers != null) {\n for (const protocol of protocols) {\n const streamMuxer = streamMuxers.get(protocol);\n if (streamMuxer != null) {\n return streamMuxer;\n }\n }\n }\n if (protocols.length) {\n throw new InvalidCryptoExchangeError('Early muxer negotiation was requested but the initiator and responder had no common muxers');\n }\n }\n /**\n * Decrypt incoming data (handshake as responder).\n *\n * @param connection - streaming iterable duplex that will be encrypted\n * @param options\n * @param options.remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer\n * @param options.signal - Used to abort the operation\n */\n async secureInbound(connection, options) {\n const log = connection.log?.newScope('noise') ?? this.log;\n const wrappedConnection = lpStream(connection, {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n });\n const handshake = await this.performHandshakeResponder(wrappedConnection, this.components.privateKey, log, options?.remotePeer, options);\n return {\n connection: toMessageStream(wrappedConnection.unwrap(), handshake, this.metrics),\n remoteExtensions: handshake.payload.extensions,\n remotePeer: handshake.remotePeer,\n streamMuxer: options?.skipStreamMuxerNegotiation === true ? undefined : this.getStreamMuxer(handshake.payload.extensions?.streamMuxers)\n };\n }\n /**\n * Perform XX handshake as initiator.\n */\n async performHandshakeInitiator(connection, \n // TODO: pass private key in noise constructor via Components\n privateKey, log, remotePeer, options) {\n let result;\n const streamMuxers = options?.skipStreamMuxerNegotiation === true ? [] : [...this.components.upgrader.getStreamMuxers().keys()];\n try {\n result = await performHandshakeInitiator({\n connection,\n privateKey,\n remotePeer,\n log: log.newScope('xxhandshake'),\n crypto: this.crypto,\n prologue: this.prologue,\n s: this.staticKey,\n extensions: {\n streamMuxers,\n webtransportCerthashes: [],\n ...this.extensions\n }\n }, options);\n this.metrics?.xxHandshakeSuccesses.increment();\n }\n catch (e) {\n this.metrics?.xxHandshakeErrors.increment();\n throw e;\n }\n return result;\n }\n /**\n * Perform XX handshake as responder.\n */\n async performHandshakeResponder(connection, privateKey, log, remotePeer, options) {\n let result;\n const streamMuxers = options?.skipStreamMuxerNegotiation === true ? [] : [...this.components.upgrader.getStreamMuxers().keys()];\n try {\n result = await performHandshakeResponder({\n connection,\n privateKey,\n remotePeer,\n log: log.newScope('xxhandshake'),\n crypto: this.crypto,\n prologue: this.prologue,\n s: this.staticKey,\n extensions: {\n streamMuxers,\n webtransportCerthashes: [],\n ...this.extensions\n }\n }, options);\n this.metrics?.xxHandshakeSuccesses.increment();\n }\n catch (e) {\n this.metrics?.xxHandshakeErrors.increment();\n throw e;\n }\n return result;\n }\n}\n//# sourceMappingURL=noise.js.map","/**\n * @packageDocumentation\n *\n * This repository contains TypeScript implementation of noise protocol, an encryption protocol used in libp2p.\n *\n * Formerly published as [`@chainsafe/libp2p-noise`](https://www.npmjs.com/package/@chainsafe/libp2p-noise).\n *\n * ## Usage\n *\n * Install with `npm i @libp2p/noise`.\n *\n * Example of using default noise configuration and passing it to the libp2p config:\n *\n * ```ts\n * import { createLibp2p } from 'libp2p'\n * import { noise } from '@libp2p/noise'\n *\n * const libp2p = await createLibp2p({\n * connectionEncrypters: [noise()],\n * // ... other options\n * })\n * ```\n *\n * See the [NoiseInit](https://github.com/libp2p/js-libp2p/blob/main/packages/connection-encrypter-noise/src/noise.ts) interface for noise configuration options.\n *\n * To use a fixed x25519 static key instead of generating one per session, pass it as `staticNoiseKey`:\n *\n * ```ts\n * import { createLibp2p } from 'libp2p'\n * import { noise, pureJsCrypto } from '@libp2p/noise'\n *\n * const staticNoiseKey = pureJsCrypto.generateX25519KeyPair().privateKey\n *\n * const node = await createLibp2p({\n * connectionEncrypters: [noise({ staticNoiseKey })]\n * })\n * ```\n *\n * ## API\n *\n * This module exposes an implementation of the [ConnectionEncrypter](https://libp2p.github.io/js-libp2p/interfaces/_libp2p_interface.ConnectionEncrypter.html) interface.\n *\n * ## Bring your own crypto\n *\n * You can provide a custom crypto implementation (instead of the default, based on [@noble](https://paulmillr.com/noble/)) by adding a `crypto` field to the init argument passed to the `Noise` factory.\n *\n * The implementation must conform to the `ICryptoInterface`, defined in <https://github.com/libp2p/js-libp2p/blob/main/packages/connection-encrypter-noise/src/crypto.ts>\n */\nimport { Noise } from \"./noise.js\";\nexport { pureJsCrypto } from \"./crypto/js.js\";\nexport function noise(init = {}) {\n return (components) => new Noise(components, init);\n}\n//# sourceMappingURL=index.js.map","import { PeerHttpExchangeError } from \"./peer-http-policy.js\";\n\n/**\n * Stable local reason codes for relay route failures. They are recorded only in local results and\n * attempt history. Relay control frames still carry no failure reason, and peers never see these.\n * docs/relay-runtime.md documents each code and the operator's next action.\n */\nexport const RELAY_FAILURE_REASONS = [\n\t\"relay_disabled\",\n\t\"relay_peer_revoked\",\n\t\"relay_unavailable\",\n\t\"relay_admission_failed\",\n\t\"relay_rejected\",\n\t\"relay_aborted\",\n\t\"relay_frame_invalid\",\n\t\"relay_handshake_failed\",\n\t\"relay_record_invalid\",\n\t\"relay_expired\",\n] as const;\n\nexport type RelayFailureReason = (typeof RELAY_FAILURE_REASONS)[number];\n\n/** An error raised where a relay failure originates, tagged with its local reason. */\nexport class RelayFailure extends Error {\n\tconstructor(\n\t\treadonly reason: RelayFailureReason,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"RelayFailure\";\n\t}\n}\n\n/**\n * Maps an error to its reason. Untagged errors take `fallback`, which callers choose from the\n * route phase they know, because Noise and stream errors arrive without a relay tag.\n */\nexport function relayFailureReason(\n\terror: unknown,\n\tfallback: RelayFailureReason,\n): RelayFailureReason {\n\tif (error instanceof RelayFailure) return error.reason;\n\tif (\n\t\terror instanceof PeerHttpExchangeError &&\n\t\t(error.code === \"deadline\" || error.code === \"cancelled\")\n\t)\n\t\treturn \"relay_expired\";\n\treturn fallback;\n}\n\n/** Tags an untagged error with `fallback`, keeping its message. Tagged errors pass through. */\nexport function asRelayFailure(error: unknown, fallback: RelayFailureReason): RelayFailure {\n\tif (error instanceof RelayFailure) return error;\n\tconst message = error instanceof Error ? error.message : \"Relay peer connection failed\";\n\treturn new RelayFailure(relayFailureReason(error, fallback), message);\n}\n\n/** Keeps the first recorded reason. Later, repeated, or reordered failures cannot replace it. */\nexport function createRelayFailureRecorder() {\n\tlet first: RelayFailureReason | undefined;\n\treturn {\n\t\trecord(reason: RelayFailureReason): void {\n\t\t\tfirst ??= reason;\n\t\t},\n\t\treason(): RelayFailureReason | undefined {\n\t\t\treturn first;\n\t\t},\n\t};\n}\n","import { createPrivateKey, createPublicKey, KeyObject, timingSafeEqual } from \"node:crypto\";\nimport { privateKeyFromRaw, publicKeyFromRaw } from \"@libp2p/crypto/keys\";\nimport type { PeerId } from \"@libp2p/interface\";\nimport { peerIdFromPublicKey } from \"@libp2p/peer-id\";\nimport { parseRelayEd25519PublicKey } from \"./relay-ed25519.js\";\n\nexport interface RelayNoiseLocalIdentity {\n\treadonly key: KeyObject | Uint8Array;\n\treadonly expectedPin: string;\n}\n\n/** Imports only caller-owned in-memory material. This module never loads or generates identity keys. */\nexport function importRelayNoiseIdentity(identity: RelayNoiseLocalIdentity) {\n\tconst expected = parseRelayEd25519PublicKey(identity.expectedPin).rawKey;\n\tlet key: KeyObject;\n\tif (identity.key instanceof KeyObject) {\n\t\tkey = identity.key;\n\t} else if (identity.key instanceof Uint8Array) {\n\t\tconst encoded = Buffer.from(identity.key);\n\t\ttry {\n\t\t\tkey = createPrivateKey({ key: encoded, format: \"der\", type: \"pkcs8\" });\n\t\t} finally {\n\t\t\tencoded.fill(0);\n\t\t}\n\t} else {\n\t\tthrow new Error(\"Noise identity requires a private KeyObject or PKCS8 bytes\");\n\t}\n\tif (key.type !== \"private\" || key.asymmetricKeyType !== \"ed25519\") {\n\t\tthrow new Error(\"Noise identity must be Ed25519\");\n\t}\n\tconst publicJwk = createPublicKey(key).export({ format: \"jwk\" });\n\tconst privateJwk = key.export({ format: \"jwk\" });\n\tconst rawPublic = decodeJwk32(publicJwk.x);\n\tif (!timingSafeEqual(rawPublic, expected)) throw new Error(\"Noise local pin mismatch\");\n\tconst seed = decodeJwk32(privateJwk.d);\n\tlet rawPrivate: Buffer | undefined;\n\ttry {\n\t\trawPrivate = Buffer.concat([seed, rawPublic]);\n\t\t// The pinned public importer copies its input before retaining the key.\n\t\tconst privateKey = privateKeyFromRaw(rawPrivate);\n\t\tif (privateKey.type !== \"Ed25519\") throw new Error(\"Noise identity must be Ed25519\");\n\t\treturn { privateKey, peerId: peerIdFromPublicKey(privateKey.publicKey) };\n\t} finally {\n\t\tseed.fill(0);\n\t\trawPrivate?.fill(0);\n\t}\n}\n\nfunction decodeJwk32(value: string | undefined): Buffer {\n\tif (typeof value !== \"string\") throw new Error(\"Invalid Ed25519 JWK\");\n\tconst bytes = Buffer.from(value, \"base64url\");\n\tif (bytes.length !== 32 || bytes.toString(\"base64url\") !== value) {\n\t\tbytes.fill(0);\n\t\tthrow new Error(\"Invalid Ed25519 JWK\");\n\t}\n\treturn bytes;\n}\n\nexport function relayNoiseExpectedPeer(pin: string) {\n\tconst rawKey = Buffer.from(parseRelayEd25519PublicKey(pin).rawKey);\n\tconst publicKey = publicKeyFromRaw(rawKey);\n\tif (publicKey.type !== \"Ed25519\") throw new Error(\"Noise peer pin must be Ed25519\");\n\treturn { rawKey, peerId: peerIdFromPublicKey(publicKey) };\n}\n\nexport function verifyRelayNoisePeer(observed: PeerId, expectedPin: string): void {\n\tconst expected = relayNoiseExpectedPeer(expectedPin);\n\tconst key = observed.publicKey;\n\tif (\n\t\t!observed.equals(expected.peerId) ||\n\t\tkey?.type !== \"Ed25519\" ||\n\t\tkey.raw.byteLength !== 32 ||\n\t\t!timingSafeEqual(key.raw, expected.rawKey)\n\t) {\n\t\tthrow new Error(\"Noise remote pin mismatch\");\n\t}\n}\n\nexport interface RelayNoiseContext {\n\treadonly transportLabel: 1 | 2 | 3;\n\treadonly sessionId: Uint8Array;\n}\n\nexport function relayNoisePrologue(context: RelayNoiseContext): Uint8Array {\n\tif (\n\t\t(context.transportLabel !== 1 &&\n\t\t\tcontext.transportLabel !== 2 &&\n\t\t\tcontext.transportLabel !== 3) ||\n\t\t!(context.sessionId instanceof Uint8Array) ||\n\t\tcontext.sessionId.byteLength !== 16\n\t) {\n\t\tthrow new Error(\"Invalid Noise transport context\");\n\t}\n\treturn Buffer.concat([\n\t\tBuffer.from(\"codemem-peer-stream/1\\0\", \"ascii\"),\n\t\tBuffer.from([context.transportLabel]),\n\t\tBuffer.from(context.sessionId),\n\t]);\n}\n","import { createHash } from \"node:crypto\";\n\nexport const RELAY_NOISE_OPENING_BYTES = 34;\n\n/** The sole wire-format check outside the library: pinned XX Message A, with no payload. */\nexport class RelayNoiseOpening {\n\tprivate readonly bytes = Buffer.alloc(RELAY_NOISE_OPENING_BYTES);\n\tprivate length = 0;\n\tprivate terminal = false;\n\n\tappend(chunk: Uint8Array): Uint8Array | undefined {\n\t\tif (this.terminal) throw new Error(\"Noise opening already consumed\");\n\t\tif (!(chunk instanceof Uint8Array) || chunk.byteLength > this.bytes.length - this.length) {\n\t\t\tthis.terminal = true;\n\t\t\tthrow new Error(\"Extra early Noise data\");\n\t\t}\n\t\tthis.bytes.set(chunk, this.length);\n\t\tthis.length += chunk.byteLength;\n\t\tif (this.length >= 2 && this.bytes.readUInt16BE(0) !== 32) {\n\t\t\tthis.terminal = true;\n\t\t\tthrow new Error(\"Invalid Noise opening length\");\n\t\t}\n\t\tif (this.length !== this.bytes.length) return;\n\t\tthis.terminal = true;\n\t\treturn Uint8Array.from(this.bytes);\n\t}\n\n\tend(): void {\n\t\tthis.terminal = true;\n\t\tif (this.length !== this.bytes.length) throw new Error(\"Truncated Noise opening\");\n\t}\n}\n\nexport function relayNoiseOpeningDigest(bytes: Uint8Array): string {\n\tconst opening = new RelayNoiseOpening();\n\topening.append(bytes);\n\topening.end();\n\treturn createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\n/** The caller must independently verify admission before supplying this digest. */\nexport function validateRelayNoiseOpeningDigest(digest: string): void {\n\tif (typeof digest !== \"string\" || !/^[0-9a-f]{64}$/.test(digest)) {\n\t\tthrow new Error(\"Invalid verified Noise opening digest\");\n\t}\n}\n","import { Duplex } from \"node:stream\";\nimport type {\n\tAbortOptions,\n\tLogger,\n\tMessageStream,\n\tStreamCloseEvent,\n\tStreamMessageEvent,\n} from \"@libp2p/interface\";\nimport { AbstractMessageStream } from \"@libp2p/utils\";\nimport { RelayNoiseOpening, relayNoiseOpeningDigest } from \"./relay-noise-opening.js\";\n\nexport const relayNoiseSilentLog: Logger = Object.freeze(\n\tObject.assign(() => {}, {\n\t\terror: () => {},\n\t\ttrace: () => {},\n\t\tenabled: false,\n\t\tnewScope: (): Logger => relayNoiseSilentLog,\n\t}),\n);\n\nexport interface RelayNoiseWireOptions {\n\treadonly bufferBytes: number;\n\treadonly opening?: \"hold\" | { readonly verifiedDigest: string };\n\treadonly account: (bytes: number) => void;\n\treadonly onFailure: (error: Error) => void;\n\treadonly onReadEnd: () => void;\n}\n\nfunction asError(error: unknown): Error {\n\treturn error instanceof Error ? error : new Error(\"Noise stream failed\");\n}\n\n// Each congestion episode needs a new wait. The pinned base class caches its onDrain promise.\nfunction waitForDrain(stream: MessageStream, signal?: AbortSignal): Promise<void> {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst finish = (error?: Error): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tstream.removeEventListener(\"drain\", wake);\n\t\t\tstream.removeEventListener(\"idle\", wake);\n\t\t\tstream.removeEventListener(\"close\", closed);\n\t\t\tsignal?.removeEventListener(\"abort\", aborted);\n\t\t\tif (error !== undefined) reject(error);\n\t\t\telse resolve();\n\t\t};\n\t\tconst check = (): void => {\n\t\t\tif (!stream.writableNeedsDrain && stream.writeBufferLength === 0) finish();\n\t\t};\n\t\tconst wake = (): void => queueMicrotask(check);\n\t\tconst closed = (event: StreamCloseEvent): void =>\n\t\t\tfinish(event.error ?? new Error(\"Noise stream closed during write\"));\n\t\tconst aborted = (): void => finish(new Error(\"Noise write cancelled\"));\n\t\tstream.addEventListener(\"drain\", wake);\n\t\tstream.addEventListener(\"idle\", wake);\n\t\tstream.addEventListener(\"close\", closed);\n\t\tsignal?.addEventListener(\"abort\", aborted, { once: true });\n\t\tif (signal?.aborted) aborted();\n\t\telse if (stream.status !== \"open\" && stream.status !== \"closing\")\n\t\t\tfinish(new Error(\"Noise stream is closed\"));\n\t\telse check();\n\t});\n}\n\n/** Owns the supplied ordered transport until it closes. No network operations are created here. */\nexport class RelayNoiseWire extends AbstractMessageStream {\n\treadonly opening: Promise<Uint8Array>;\n\tprivate readonly capture = Promise.withResolvers<Uint8Array>();\n\tprivate readonly prefix = new RelayNoiseOpening();\n\tprivate held?: Uint8Array;\n\tprivate gateOpen: boolean;\n\tprivate closing?: Promise<void>;\n\tprivate failed = false;\n\n\tconstructor(\n\t\tprivate readonly transport: Duplex,\n\t\tprivate readonly options: RelayNoiseWireOptions,\n\t) {\n\t\tsuper({\n\t\t\tlog: relayNoiseSilentLog,\n\t\t\tinactivityTimeout: 0,\n\t\t\tmaxReadBufferLength: options.bufferBytes,\n\t\t\tmaxWriteBufferLength: options.bufferBytes,\n\t\t});\n\t\tthis.gateOpen = options.opening === undefined;\n\t\tthis.opening = this.capture.promise;\n\t\tvoid this.opening.catch(() => {});\n\t\ttransport.on(\"data\", this.receive);\n\t\ttransport.on(\"drain\", this.drain);\n\t\ttransport.on(\"end\", this.end);\n\t\ttransport.on(\"error\", this.error);\n\t\ttransport.on(\"close\", this.closed);\n\t\tif (transport.destroyed || transport.readableEnded)\n\t\t\tthis.fail(new Error(\"Noise transport already ended\"));\n\t}\n\n\tprivate readonly receive = (chunk: unknown): void => {\n\t\ttry {\n\t\t\tif (!(chunk instanceof Uint8Array)) throw new Error(\"Noise transport requires byte chunks\");\n\t\t\tthis.options.account(chunk.byteLength);\n\t\t\tif (!this.gateOpen) {\n\t\t\t\tif (this.options.opening === \"hold\") throw new Error(\"Noise data before opening release\");\n\t\t\t\tthis.captureOpening(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (chunk.byteLength + this.readBufferLength > this.options.bufferBytes)\n\t\t\t\tthrow new Error(\"Noise wire read buffer exceeded\");\n\t\t\tthis.onData(Buffer.from(chunk));\n\t\t} catch (error) {\n\t\t\tthis.fail(asError(error));\n\t\t}\n\t};\n\n\tprivate captureOpening(chunk: Uint8Array): void {\n\t\tconst complete = this.prefix.append(chunk);\n\t\tif (complete === undefined) return;\n\t\tconst mode = this.options.opening;\n\t\tif (typeof mode === \"object\" && relayNoiseOpeningDigest(complete) !== mode.verifiedDigest) {\n\t\t\tthrow new Error(\"Noise opening digest mismatch\");\n\t\t}\n\t\tthis.held = complete;\n\t\tif (mode !== \"hold\") this.transport.pause();\n\t\tthis.capture.resolve(Uint8Array.from(complete));\n\t}\n\n\t/** One-shot release after the caller's independent admission and ACCEPTED checks. */\n\treleaseOpening(): void {\n\t\tif (this.gateOpen || this.held === undefined || this.status !== \"open\") {\n\t\t\tconst error = new Error(\"Noise opening unavailable or already released\");\n\t\t\tthis.fail(error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (this.transport.readableLength !== 0) {\n\t\t\tconst error = new Error(\"Extra early Noise data\");\n\t\t\tthis.fail(error);\n\t\t\tthrow error;\n\t\t}\n\t\tconst held = this.held;\n\t\tthis.held = undefined;\n\t\tthis.gateOpen = true;\n\t\tif (this.options.opening === \"hold\") {\n\t\t\tif (!this.writeTransport(held)) this.onMuxerNeedsDrain();\n\t\t} else {\n\t\t\tthis.onData(held);\n\t\t\tthis.transport.resume();\n\t\t}\n\t}\n\n\toverride send(data: Parameters<MessageStream[\"send\"]>[0]): boolean {\n\t\tif (data.byteLength + this.writeBufferLength > this.options.bufferBytes) {\n\t\t\tconst error = new Error(\"Noise wire write buffer exceeded\");\n\t\t\tthis.fail(error);\n\t\t\tthrow error;\n\t\t}\n\t\treturn super.send(data);\n\t}\n\n\toverride abort(error: Error): void {\n\t\tthis.capture.reject(error);\n\t\tthis.held = undefined;\n\t\tsuper.abort(error);\n\t}\n\n\tsendData(data: Parameters<AbstractMessageStream[\"sendData\"]>[0]) {\n\t\tthis.options.account(data.byteLength);\n\t\tif (!this.gateOpen) {\n\t\t\tif (this.options.opening !== \"hold\")\n\t\t\t\tthrow new Error(\"Noise response before opening verification\");\n\t\t\tthis.captureOpening(data.subarray());\n\t\t\treturn { sentBytes: data.byteLength, canSendMore: true };\n\t\t}\n\t\treturn { sentBytes: data.byteLength, canSendMore: this.writeTransport(data.subarray()) };\n\t}\n\n\tprivate writeTransport(data: Uint8Array): boolean {\n\t\tif (data.byteLength + this.transport.writableLength > this.options.bufferBytes)\n\t\t\tthrow new Error(\"Noise transport write buffer exceeded\");\n\t\treturn this.transport.write(Buffer.from(data));\n\t}\n\n\tsendReset(error: Error): void {\n\t\tthis.transport.destroy(error);\n\t}\n\tsendPause(): void {\n\t\tthis.transport.pause();\n\t}\n\tsendResume(): void {\n\t\tif (this.gateOpen) this.transport.resume();\n\t}\n\n\tclose(options?: AbortOptions): Promise<void> {\n\t\tif (this.closing !== undefined) return this.closing;\n\t\tif (this.writeStatus === \"closed\") return Promise.resolve();\n\t\tthis.writeStatus = \"closing\";\n\t\tthis.closing = waitForDrain(this, options?.signal)\n\t\t\t.then(\n\t\t\t\t() =>\n\t\t\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\t\t\tlet settled = false;\n\t\t\t\t\t\tconst finish = (error?: Error | null): void => {\n\t\t\t\t\t\t\tif (settled) return;\n\t\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\t\tthis.transport.off(\"error\", failed);\n\t\t\t\t\t\t\tthis.transport.off(\"close\", closed);\n\t\t\t\t\t\t\toptions?.signal?.removeEventListener(\"abort\", aborted);\n\t\t\t\t\t\t\tif (error != null) {\n\t\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthis.writeStatus = \"closed\";\n\t\t\t\t\t\t\tif (this.remoteWriteStatus === \"closed\") this.onTransportClosed();\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst failed = (error: Error): void => finish(error);\n\t\t\t\t\t\tconst closed = (): void => finish(new Error(\"Noise transport closed while ending\"));\n\t\t\t\t\t\tconst aborted = (): void => {\n\t\t\t\t\t\t\tconst error = new Error(\"Noise close cancelled\");\n\t\t\t\t\t\t\tthis.fail(error);\n\t\t\t\t\t\t\tfinish(error);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\t\t\taborted();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (this.transport.destroyed) {\n\t\t\t\t\t\t\tclosed();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.transport.once(\"error\", failed);\n\t\t\t\t\t\tthis.transport.once(\"close\", closed);\n\t\t\t\t\t\toptions?.signal?.addEventListener(\"abort\", aborted, { once: true });\n\t\t\t\t\t\tthis.transport.end(() => finish());\n\t\t\t\t\t}),\n\t\t\t)\n\t\t\t.catch((error: unknown) => {\n\t\t\t\t// The drain can reject before end() installs its cancellation handlers.\n\t\t\t\tconst failure = asError(error);\n\t\t\t\tthis.fail(failure);\n\t\t\t\tthrow failure;\n\t\t\t});\n\t\treturn this.closing;\n\t}\n\n\tprivate fail(error: Error): void {\n\t\tif (this.failed) return;\n\t\tthis.failed = true;\n\t\tthis.capture.reject(error);\n\t\tthis.held = undefined;\n\t\tthis.abort(error);\n\t\tthis.options.onFailure(error);\n\t}\n\tprivate readonly drain = (): void => this.onMuxerDrain();\n\tprivate readonly end = (): void => {\n\t\tif (!this.gateOpen) {\n\t\t\tthis.fail(new Error(\"Truncated or unreleased Noise opening\"));\n\t\t\treturn;\n\t\t}\n\t\tthis.onRemoteCloseWrite();\n\t\tthis.options.onReadEnd();\n\t};\n\tprivate readonly error = (error: Error): void => this.fail(error);\n\tprivate readonly closed = (): void => {\n\t\tthis.capture.reject(new Error(\"Noise transport closed\"));\n\t\tthis.held = undefined;\n\t\tthis.onTransportClosed();\n\t\tthis.transport.off(\"data\", this.receive);\n\t\tthis.transport.off(\"drain\", this.drain);\n\t\tthis.transport.off(\"end\", this.end);\n\t\tthis.transport.off(\"error\", this.error);\n\t\tthis.transport.off(\"close\", this.closed);\n\t};\n}\n\nexport interface RelayNoisePlaintextOptions {\n\treadonly bufferBytes: number;\n\treadonly accountSent: (bytes: number) => void;\n\treadonly accountReceived: (bytes: number) => void;\n}\n\ntype WriteCallback = (error?: Error | null) => void;\n\n/** Bounds queues even when a caller ignores the Writable backpressure return value. */\nexport class RelayNoiseDuplex extends Duplex {\n\tprivate readonly controller = new AbortController();\n\tprivate pendingWrite?: WriteCallback;\n\tprivate pendingRead?: Buffer;\n\tprivate pendingReadOffset = 0;\n\tprivate drainingRead = false;\n\tprivate readingNode = false;\n\tprivate upstreamEnded = false;\n\tprivate eofPushed = false;\n\n\tconstructor(\n\t\tprivate readonly stream: MessageStream,\n\t\tprivate readonly limits: RelayNoisePlaintextOptions,\n\t) {\n\t\tsuper({ allowHalfOpen: true, highWaterMark: Math.min(16_384, limits.bufferBytes) });\n\t\tstream.maxReadBufferLength = limits.bufferBytes;\n\t\tstream.maxWriteBufferLength = limits.bufferBytes;\n\t\tthis.on(\"error\", this.observeError);\n\t\tthis.once(\"close\", () => this.off(\"error\", this.observeError));\n\t\tstream.addEventListener(\"message\", this.message);\n\t\tstream.addEventListener(\"end\", this.endRead);\n\t\tstream.addEventListener(\"close\", this.closeStream);\n\t\tif (stream.readableEnded) this.endRead();\n\t}\n\n\toverride write(\n\t\tchunk: Uint8Array | string,\n\t\tencodingOrCallback?: BufferEncoding | WriteCallback,\n\t\tcallback?: WriteCallback,\n\t): boolean {\n\t\tconst encoding = typeof encodingOrCallback === \"string\" ? encodingOrCallback : undefined;\n\t\tconst done = typeof encodingOrCallback === \"function\" ? encodingOrCallback : callback;\n\t\ttry {\n\t\t\tif (typeof chunk !== \"string\" && !(chunk instanceof Uint8Array)) {\n\t\t\t\tthrow new Error(\"Noise plaintext writes require bytes or a string\");\n\t\t\t}\n\t\t\tconst length =\n\t\t\t\ttypeof chunk === \"string\" ? Buffer.byteLength(chunk, encoding) : chunk.byteLength;\n\t\t\tif (!Number.isSafeInteger(length) || length < 0)\n\t\t\t\tthrow new Error(\"Invalid Noise plaintext byte length\");\n\t\t\tif (length + this.writableLength > this.limits.bufferBytes)\n\t\t\t\tthrow new Error(\"Noise plaintext write buffer exceeded\");\n\t\t\tthis.limits.accountSent(length);\n\t\t} catch (error) {\n\t\t\tconst failure = asError(error);\n\t\t\tqueueMicrotask(() => done?.(failure));\n\t\t\tthis.destroy(failure);\n\t\t\treturn false;\n\t\t}\n\t\tif (encoding !== undefined) return super.write(chunk, encoding, done);\n\t\treturn super.write(chunk, done);\n\t}\n\n\t// Writable.end(chunk) otherwise bypasses the public write override and its queue/budget checks.\n\toverride end(\n\t\tchunkOrCallback?: Uint8Array | string | (() => void),\n\t\tencodingOrCallback?: BufferEncoding | (() => void),\n\t\tcallback?: () => void,\n\t): this {\n\t\tif (typeof chunkOrCallback === \"function\") return super.end(chunkOrCallback);\n\t\tconst done = typeof encodingOrCallback === \"function\" ? encodingOrCallback : callback;\n\t\tif (chunkOrCallback !== undefined) {\n\t\t\tif (typeof encodingOrCallback === \"string\") this.write(chunkOrCallback, encodingOrCallback);\n\t\t\telse this.write(chunkOrCallback);\n\t\t}\n\t\treturn super.end(done);\n\t}\n\n\toverride read(size?: number) {\n\t\tif (size !== undefined && size !== null && typeof size !== \"number\") {\n\t\t\tthrow new TypeError(\"Noise read size must be a number or omitted\");\n\t\t}\n\t\tif (typeof size === \"number\" && size > this.limits.bufferBytes) {\n\t\t\tthrow new RangeError(\n\t\t\t\t`Noise read size exceeds the ${this.limits.bufferBytes}-byte buffer limit`,\n\t\t\t);\n\t\t}\n\t\tif (this.readingNode) return super.read(size);\n\t\tthis.readingNode = true;\n\t\ttry {\n\t\t\tconst chunk = super.read(size);\n\t\t\t// Node can request _read before consuming a full buffer and then wait for a push.\n\t\t\t// Retry after consumption creates capacity, including when the cap equals its high-water mark.\n\t\t\tthis._read();\n\t\t\treturn chunk;\n\t\t} finally {\n\t\t\tthis.readingNode = false;\n\t\t}\n\t}\n\n\toverride _read(): void {\n\t\ttry {\n\t\t\tif (this.destroyed || this.drainingRead) return;\n\t\t\tif (\n\t\t\t\tthis.drainPendingRead() &&\n\t\t\t\t!this.upstreamEnded &&\n\t\t\t\tthis.readableLength < this.limits.bufferBytes\n\t\t\t)\n\t\t\t\tthis.stream.resume();\n\t\t} catch (error) {\n\t\t\tthis.destroy(asError(error));\n\t\t}\n\t}\n\tprivate drainPendingRead(): boolean {\n\t\tif (this.destroyed || this.drainingRead) return false;\n\t\tthis.drainingRead = true;\n\t\ttry {\n\t\t\tlet ready = true;\n\t\t\tif (this.pendingRead !== undefined) {\n\t\t\t\tconst capacity = this.limits.bufferBytes - this.readableLength;\n\t\t\t\tif (capacity <= 0) return false;\n\t\t\t\tconst end = Math.min(this.pendingRead.length, this.pendingReadOffset + capacity);\n\t\t\t\tconst chunk = Buffer.from(this.pendingRead.subarray(this.pendingReadOffset, end));\n\t\t\t\tthis.pendingReadOffset = end;\n\t\t\t\tif (end === this.pendingRead.length) {\n\t\t\t\t\tthis.pendingRead = undefined;\n\t\t\t\t\tthis.pendingReadOffset = 0;\n\t\t\t\t}\n\t\t\t\tready = this.push(chunk);\n\t\t\t}\n\t\t\tif (this.pendingRead !== undefined) return false;\n\t\t\tif (this.upstreamEnded && !this.eofPushed) {\n\t\t\t\tthis.eofPushed = true;\n\t\t\t\tthis.push(null);\n\t\t\t}\n\t\t\treturn ready;\n\t\t} finally {\n\t\t\tthis.drainingRead = false;\n\t\t}\n\t}\n\toverride _write(chunk: Buffer, _encoding: BufferEncoding, callback: WriteCallback): void {\n\t\tthis.pendingWrite = callback;\n\t\tvoid this.sendChunked(chunk).then(\n\t\t\t() => this.finishWrite(),\n\t\t\t(error: unknown) => this.finishWrite(asError(error)),\n\t\t);\n\t}\n\tprivate async sendChunked(chunk: Uint8Array): Promise<void> {\n\t\t// Leave room for the library's two-byte length and 16-byte authentication tag.\n\t\tconst size = Math.min(65_519, this.limits.bufferBytes - 18);\n\t\tif (size <= 0) throw new Error(\"Noise buffer cannot contain an encrypted record\");\n\t\tfor (let offset = 0; offset < chunk.byteLength; offset += size) {\n\t\t\tthis.controller.signal.throwIfAborted();\n\t\t\tif (!this.stream.send(chunk.subarray(offset, offset + size))) {\n\t\t\t\tawait waitForDrain(this.stream, this.controller.signal);\n\t\t\t}\n\t\t}\n\t}\n\tprivate finishWrite(error?: Error): void {\n\t\tconst callback = this.pendingWrite;\n\t\tthis.pendingWrite = undefined;\n\t\tcallback?.(error);\n\t}\n\toverride _final(callback: WriteCallback): void {\n\t\tvoid this.stream.close({ signal: this.controller.signal }).then(\n\t\t\t() => callback(),\n\t\t\t(error: unknown) => callback(asError(error)),\n\t\t);\n\t}\n\toverride _destroy(error: Error | null, callback: WriteCallback): void {\n\t\tthis.pendingRead = undefined;\n\t\tthis.pendingReadOffset = 0;\n\t\tthis.stream.removeEventListener(\"message\", this.message);\n\t\tthis.stream.removeEventListener(\"end\", this.endRead);\n\t\tthis.stream.removeEventListener(\"close\", this.closeStream);\n\t\tif (error === null && this.readableEnded && this.writableFinished) {\n\t\t\tthis.controller.abort();\n\t\t\tcallback(null);\n\t\t\treturn;\n\t\t}\n\t\tconst failure = error ?? new Error(\"Noise stream disposed\");\n\t\tthis.controller.abort(failure);\n\t\tthis.finishWrite(failure);\n\t\tthis.stream.abort(failure);\n\t\tcallback(error);\n\t}\n\tprivate readonly message = (event: StreamMessageEvent): void => {\n\t\ttry {\n\t\t\tif (this.destroyed) return;\n\t\t\tconst length = event.data.byteLength;\n\t\t\tif (\n\t\t\t\tthis.pendingRead !== undefined ||\n\t\t\t\t!Number.isSafeInteger(length) ||\n\t\t\t\tlength < 0 ||\n\t\t\t\tlength > this.limits.bufferBytes\n\t\t\t)\n\t\t\t\tthrow new Error(\"Noise plaintext read buffer exceeded\");\n\t\t\tthis.limits.accountReceived(length);\n\t\t\tif (this.destroyed) return;\n\t\t\t// Own one bounded snapshot rather than retain a view into a larger ciphertext allocation.\n\t\t\tthis.pendingRead = Buffer.from(event.data.subarray());\n\t\t\tif (!this.drainPendingRead() && !this.upstreamEnded && !this.destroyed) this.stream.pause();\n\t\t} catch (error) {\n\t\t\tthis.destroy(asError(error));\n\t\t}\n\t};\n\tprivate readonly endRead = (): void => {\n\t\tthis.upstreamEnded = true;\n\t\tthis.drainPendingRead();\n\t};\n\tprivate readonly closeStream = (event: StreamCloseEvent): void => {\n\t\tif (event.error !== undefined) {\n\t\t\tthis.destroy(event.error);\n\t\t\treturn;\n\t\t}\n\t\tthis.endRead();\n\t\t// The wire can close inside _final before its promise resolves and Node emits finish.\n\t\tif (!this.writableEnded)\n\t\t\tthis.destroy(new Error(\"Noise stream closed before local writes ended\"));\n\t};\n\tprivate readonly observeError = (): void => {};\n}\n","import { performance } from \"node:perf_hooks\";\nimport type { Duplex } from \"node:stream\";\nimport type { Upgrader } from \"@libp2p/interface\";\nimport { type NoiseComponents, noise } from \"@libp2p/noise\";\nimport { parseRelayEd25519PublicKey } from \"./relay-ed25519.js\";\nimport { RelayFailure } from \"./relay-failure-reason.js\";\nimport {\n\timportRelayNoiseIdentity,\n\ttype RelayNoiseContext,\n\ttype RelayNoiseLocalIdentity,\n\trelayNoiseExpectedPeer,\n\trelayNoisePrologue,\n\tverifyRelayNoisePeer,\n} from \"./relay-noise-identity.js\";\nimport { relayNoiseOpeningDigest, validateRelayNoiseOpeningDigest } from \"./relay-noise-opening.js\";\nimport { RelayNoiseDuplex, RelayNoiseWire, relayNoiseSilentLog } from \"./relay-noise-stream.js\";\n\nexport interface RelayNoiseLimits {\n\treadonly handshakeMs: number;\n\treadonly handshakeBytes: number;\n\treadonly sessionMs: number;\n\treadonly sentBytes: number;\n\treadonly receivedBytes: number;\n\treadonly bufferBytes: number;\n}\n\nexport const RELAY_NOISE_LIMITS: Readonly<RelayNoiseLimits> = Object.freeze({\n\thandshakeMs: 10_000,\n\thandshakeBytes: 256 * 1024,\n\tsessionMs: 15 * 60 * 1000,\n\tsentBytes: 1024 * 1024 * 1024,\n\treceivedBytes: 1024 * 1024 * 1024,\n\tbufferBytes: 256 * 1024,\n});\n\nexport interface RelayNoiseOptions {\n\treadonly transport: Duplex;\n\treadonly localIdentity: RelayNoiseLocalIdentity;\n\treadonly expectedRemotePin: string;\n\treadonly context: RelayNoiseContext;\n\treadonly signal?: AbortSignal;\n\t/** Absolute monotonic time from performance.now(), including local Message A preparation. */\n\treadonly deadlineMs: number;\n\treadonly limits?: Partial<RelayNoiseLimits>;\n}\n\nexport interface AuthenticatedRelayNoiseStream {\n\treadonly duplex: Duplex;\n\treadonly observedPin: string;\n\treadonly observedPeerId: string;\n\treadonly observedPublicKey: Uint8Array;\n}\n\nconst authenticatedPeerPins = new WeakMap<Duplex, string>();\n\n/** Bind callers to the exact duplex created after remote Noise peer verification. */\nexport function readAuthenticatedRelayNoisePeerPin(duplex: Duplex): string | null {\n\treturn authenticatedPeerPins.get(duplex) ?? null;\n}\n\nexport interface PreparedRelayNoiseInitiator {\n\treadonly opening: Promise<{ readonly bytes: Uint8Array; readonly digest: string }>;\n\treadonly authenticated: Promise<AuthenticatedRelayNoiseStream>;\n\t/** Call once after admission and ACCEPTED. The timestamp is local performance.now() at acceptance. */\n\trelease(acceptedAtMs: number): void;\n\tcancel(): void;\n}\n\nexport function restrictedRelayNoiseUpgrader(): Upgrader {\n\tconst unsupported = (): never => {\n\t\tthrow new Error(\"Standalone Noise streams do not support networking\");\n\t};\n\treturn {\n\t\tupgradeInbound: unsupported,\n\t\tupgradeOutbound: unsupported,\n\t\tcreateInboundAbortSignal: unsupported,\n\t\tgetStreamMuxers: () => new Map(),\n\t\tgetConnectionEncrypters: () => new Map(),\n\t};\n}\n\nfunction resolveLimits(input: Partial<RelayNoiseLimits> | undefined): RelayNoiseLimits {\n\tconst result = { ...RELAY_NOISE_LIMITS };\n\tfor (const name of Object.keys(result) as (keyof RelayNoiseLimits)[]) {\n\t\tconst value = input?.[name] === undefined ? result[name] : input[name];\n\t\tif (!Number.isSafeInteger(value) || value <= 0 || value > RELAY_NOISE_LIMITS[name]) {\n\t\t\tthrow new Error(`Invalid Noise limit: ${name}`);\n\t\t}\n\t\tresult[name] = value;\n\t}\n\treturn result;\n}\n\nfunction observe<T>(promise: Promise<T>): Promise<T> {\n\tvoid promise.catch(() => {});\n\treturn promise;\n}\n\nclass RelayNoiseAttempt {\n\treadonly wire: RelayNoiseWire;\n\treadonly limits: RelayNoiseLimits;\n\treadonly controller = new AbortController();\n\tprivate readonly owner: Pick<NoiseComponents, \"peerId\" | \"privateKey\">;\n\tprivate readonly expectedPin: string;\n\tprivate readonly prologue: Uint8Array;\n\tprivate readonly remote: ReturnType<typeof relayNoiseExpectedPeer>;\n\tprivate timer?: ReturnType<typeof setTimeout>;\n\tprivate handshaking = true;\n\tprivate accepted = false;\n\tprivate handshakeBytes = 0;\n\tprivate sentBytes = 0;\n\tprivate receivedBytes = 0;\n\tprivate phaseDeadline: number;\n\tprivate duplex?: RelayNoiseDuplex;\n\tprivate failed?: Error;\n\tprivate terminated = false;\n\n\tconstructor(\n\t\tprivate readonly options: RelayNoiseOptions,\n\t\topening: \"hold\" | { verifiedDigest: string },\n\t) {\n\t\tthis.options = { ...options };\n\t\ttry {\n\t\t\tthis.limits = resolveLimits(options.limits);\n\t\t\tif (!Number.isFinite(options.deadlineMs) || options.deadlineMs <= performance.now())\n\t\t\t\tthrow new Error(\"Noise deadline expired or invalid\");\n\t\t\tif (\n\t\t\t\toptions.transport.destroyed ||\n\t\t\t\toptions.transport.readableEnded ||\n\t\t\t\toptions.transport.writableEnded ||\n\t\t\t\toptions.transport.readableObjectMode ||\n\t\t\t\toptions.transport.writableObjectMode ||\n\t\t\t\toptions.transport.readableHighWaterMark > this.limits.bufferBytes ||\n\t\t\t\toptions.transport.writableHighWaterMark > this.limits.bufferBytes ||\n\t\t\t\toptions.transport.readableLength > this.limits.bufferBytes ||\n\t\t\t\toptions.transport.writableLength !== 0\n\t\t\t)\n\t\t\t\tthrow new Error(\"Noise transport buffers exceed limits or contain pending writes\");\n\t\t\tthis.owner = importRelayNoiseIdentity(options.localIdentity);\n\t\t\tthis.expectedPin = options.expectedRemotePin;\n\t\t\tthis.remote = relayNoiseExpectedPeer(this.expectedPin);\n\t\t\tthis.prologue = relayNoisePrologue(options.context);\n\t\t\tthis.phaseDeadline = options.deadlineMs;\n\t\t} catch (error) {\n\t\t\toptions.transport.destroy();\n\t\t\tthrow error;\n\t\t}\n\t\toptions.transport.on(\"error\", this.transportError);\n\t\toptions.transport.once(\"close\", this.transportClosed);\n\t\tthis.wire = new RelayNoiseWire(options.transport, {\n\t\t\tbufferBytes: this.limits.bufferBytes,\n\t\t\topening,\n\t\t\taccount: (bytes) => this.accountWire(bytes),\n\t\t\tonFailure: (error) => this.stop(error),\n\t\t\tonReadEnd: () => {\n\t\t\t\tif (this.handshaking) this.stop(new Error(\"Noise handshake truncated\"));\n\t\t\t},\n\t\t});\n\t\toptions.signal?.addEventListener(\"abort\", this.cancel, { once: true });\n\t\tthis.setTimer();\n\t\tif (options.signal?.aborted) this.cancel();\n\t}\n\n\taccept(acceptedAtMs: number): void {\n\t\tthis.checkActive();\n\t\tconst now = performance.now();\n\t\tif (this.accepted || !Number.isFinite(acceptedAtMs) || acceptedAtMs < 0 || acceptedAtMs > now) {\n\t\t\tconst error = new Error(\"Noise acceptance timestamp invalid or reused\");\n\t\t\tthis.stop(error);\n\t\t\tthrow error;\n\t\t}\n\t\tthis.accepted = true;\n\t\tthis.phaseDeadline = Math.min(this.options.deadlineMs, acceptedAtMs + this.limits.handshakeMs);\n\t\tthis.checkActive();\n\t\tthis.setTimer();\n\t}\n\n\tasync authenticate(role: \"initiator\" | \"responder\"): Promise<AuthenticatedRelayNoiseStream> {\n\t\ttry {\n\t\t\tthis.checkActive();\n\t\t\t// A factory is private to this attempt. No static key, crypto override, or signer is accepted.\n\t\t\tconst encrypter = noise({ prologueBytes: Uint8Array.from(this.prologue) })({\n\t\t\t\t...this.owner,\n\t\t\t\tlogger: { forComponent: () => relayNoiseSilentLog },\n\t\t\t\tupgrader: restrictedRelayNoiseUpgrader(),\n\t\t\t});\n\t\t\tconst settings = {\n\t\t\t\tremotePeer: this.remote.peerId,\n\t\t\t\tsignal: this.controller.signal,\n\t\t\t\tskipStreamMuxerNegotiation: true,\n\t\t\t};\n\t\t\tlet secured: Awaited<ReturnType<typeof encrypter.secureInbound>>;\n\t\t\tif (role === \"initiator\") secured = await encrypter.secureOutbound(this.wire, settings);\n\t\t\telse secured = await encrypter.secureInbound(this.wire, settings);\n\t\t\tthis.checkActive();\n\t\t\tverifyRelayNoisePeer(secured.remotePeer, this.expectedPin);\n\t\t\tthis.handshaking = false;\n\t\t\tthis.phaseDeadline = Math.min(\n\t\t\t\tthis.options.deadlineMs,\n\t\t\t\tperformance.now() + this.limits.sessionMs,\n\t\t\t);\n\t\t\tthis.setTimer();\n\t\t\tthis.duplex = new RelayNoiseDuplex(secured.connection, {\n\t\t\t\tbufferBytes: this.limits.bufferBytes,\n\t\t\t\taccountSent: (bytes) => this.accountPlaintext(\"sentBytes\", bytes),\n\t\t\t\taccountReceived: (bytes) => this.accountPlaintext(\"receivedBytes\", bytes),\n\t\t\t});\n\t\t\tthis.duplex.once(\"close\", this.applicationClosed);\n\t\t\tconst { wireKey } = parseRelayEd25519PublicKey(this.expectedPin);\n\t\t\tauthenticatedPeerPins.set(\n\t\t\t\tthis.duplex,\n\t\t\t\t`ssh-ed25519 ${Buffer.from(wireKey).toString(\"base64\")}`,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tduplex: this.duplex,\n\t\t\t\tobservedPin: this.expectedPin,\n\t\t\t\tobservedPeerId: secured.remotePeer.toString(),\n\t\t\t\tobservedPublicKey: Uint8Array.from(this.remote.rawKey),\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : new Error(\"Noise authentication failed\");\n\t\t\tthis.stop(failure);\n\t\t\tthrow failure;\n\t\t}\n\t}\n\n\tprivate accountWire(bytes: number): void {\n\t\tthis.checkActive();\n\t\tif (!this.handshaking) return;\n\t\tif (\n\t\t\t!Number.isSafeInteger(bytes) ||\n\t\t\tbytes < 0 ||\n\t\t\tbytes > this.limits.handshakeBytes - this.handshakeBytes\n\t\t) {\n\t\t\tconst error = new Error(\"Noise handshake byte budget exceeded\");\n\t\t\tthis.stop(error);\n\t\t\tthrow error;\n\t\t}\n\t\tthis.handshakeBytes += bytes;\n\t}\n\tprivate accountPlaintext(direction: \"sentBytes\" | \"receivedBytes\", bytes: number): void {\n\t\tthis.checkActive();\n\t\tif (\n\t\t\t!Number.isSafeInteger(bytes) ||\n\t\t\tbytes < 0 ||\n\t\t\tbytes > this.limits[direction] - this[direction]\n\t\t) {\n\t\t\tconst error = new Error(\"Noise plaintext byte budget exceeded\");\n\t\t\tthis.stop(error);\n\t\t\tthrow error;\n\t\t}\n\t\tthis[direction] += bytes;\n\t}\n\tprivate checkActive(): void {\n\t\tif (this.failed !== undefined) throw this.failed;\n\t\tif (this.terminated) throw new Error(\"Noise stream closed\");\n\t\tif (performance.now() >= this.phaseDeadline) {\n\t\t\tconst error = new RelayFailure(\"relay_expired\", \"Noise deadline exceeded\");\n\t\t\tthis.stop(error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\tprivate setTimer(): void {\n\t\tif (this.timer !== undefined) clearTimeout(this.timer);\n\t\tconst timer = setTimeout(\n\t\t\t() => {\n\t\t\t\tif (this.timer !== timer || this.terminated) return;\n\t\t\t\tthis.timer = undefined;\n\t\t\t\tif (performance.now() < this.phaseDeadline) {\n\t\t\t\t\tthis.setTimer();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.stop(new RelayFailure(\"relay_expired\", \"Noise deadline exceeded\"));\n\t\t\t},\n\t\t\tMath.min(2_147_483_647, Math.max(1, Math.ceil(this.phaseDeadline - performance.now()))),\n\t\t);\n\t\ttimer.unref();\n\t\tthis.timer = timer;\n\t}\n\tstop(error: Error): void {\n\t\tif (this.terminated) return;\n\t\tthis.terminated = true;\n\t\tthis.failed = error;\n\t\tthis.clearLifecycle();\n\t\tthis.controller.abort(error);\n\t\tthis.duplex?.destroy(error);\n\t\tthis.wire?.abort(error);\n\t\tthis.options.transport.destroy(error);\n\t}\n\tprivate clearLifecycle(): void {\n\t\tif (this.timer !== undefined) clearTimeout(this.timer);\n\t\tthis.timer = undefined;\n\t\tthis.options.signal?.removeEventListener(\"abort\", this.cancel);\n\t}\n\tprivate finishCleanly(): void {\n\t\tif (this.terminated) return;\n\t\tthis.terminated = true;\n\t\tthis.clearLifecycle();\n\t\t// Mark the wire terminal before disposing wrappers, so their reset path sends no error.\n\t\tthis.wire.onTransportClosed();\n\t\tthis.controller.abort();\n\t\tthis.options.transport.destroy();\n\t}\n\tprivate hasCleanTransportEnd(): boolean {\n\t\treturn (\n\t\t\t!this.handshaking &&\n\t\t\tthis.duplex?.errored === null &&\n\t\t\tthis.options.transport.errored === null &&\n\t\t\tthis.options.transport.readableEnded &&\n\t\t\tthis.options.transport.writableFinished\n\t\t);\n\t}\n\tprivate isCleanlyFinished(): boolean {\n\t\treturn (\n\t\t\tthis.hasCleanTransportEnd() &&\n\t\t\tthis.duplex?.readableEnded === true &&\n\t\t\tthis.duplex.writableFinished\n\t\t);\n\t}\n\tprivate readonly applicationClosed = (): void => {\n\t\tif (this.isCleanlyFinished()) {\n\t\t\tthis.finishCleanly();\n\t\t\treturn;\n\t\t}\n\t\tthis.stop(this.duplex?.errored ?? new Error(\"Noise application stream closed prematurely\"));\n\t};\n\tprivate readonly cancel = (): void => this.stop(new Error(\"Noise attempt cancelled\"));\n\tprivate readonly transportError = (error: Error): void => this.stop(error);\n\tprivate readonly transportClosed = (): void => {\n\t\tif (this.isCleanlyFinished()) this.finishCleanly();\n\t\telse if (!this.hasCleanTransportEnd())\n\t\t\tthis.stop(this.options.transport.errored ?? new Error(\"Noise transport closed prematurely\"));\n\t\t// A clean physical close may precede consumption of buffered plaintext. Node owns that EOF.\n\t\tthis.options.transport.off(\"error\", this.transportError);\n\t};\n}\n\n/** Prepares locally, without sending wire bytes. The same attempt continues after release. */\nexport function prepareRelayNoiseInitiator(\n\toptions: RelayNoiseOptions,\n): PreparedRelayNoiseInitiator {\n\tconst attempt = new RelayNoiseAttempt(options, \"hold\");\n\tconst authenticated = observe(attempt.authenticate(\"initiator\"));\n\tconst opening = observe(\n\t\tattempt.wire.opening.then((bytes) => ({ bytes, digest: relayNoiseOpeningDigest(bytes) })),\n\t);\n\treturn {\n\t\topening,\n\t\tauthenticated,\n\t\trelease: (acceptedAtMs) => {\n\t\t\ttry {\n\t\t\t\tattempt.accept(acceptedAtMs);\n\t\t\t\tattempt.wire.releaseOpening();\n\t\t\t} catch (error) {\n\t\t\t\tattempt.stop(error instanceof Error ? error : new Error(\"Noise release failed\"));\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tcancel: () => attempt.stop(new Error(\"Noise attempt cancelled\")),\n\t};\n}\n\n/** Admission verification is caller-owned. A digest is only a byte binding, never authorization. */\nexport async function acceptRelayNoiseResponder(\n\toptions: RelayNoiseOptions & {\n\t\treadonly verifiedMessageADigest: string;\n\t\treadonly acceptedAtMs: number;\n\t},\n): Promise<AuthenticatedRelayNoiseStream> {\n\ttry {\n\t\tvalidateRelayNoiseOpeningDigest(options.verifiedMessageADigest);\n\t} catch (error) {\n\t\toptions.transport.destroy();\n\t\tthrow error;\n\t}\n\tconst attempt = new RelayNoiseAttempt(options, {\n\t\tverifiedDigest: options.verifiedMessageADigest,\n\t});\n\ttry {\n\t\tattempt.accept(options.acceptedAtMs);\n\t\tawait attempt.wire.opening;\n\t\t// Nothing has entered the inbound factory before the complete prefix check.\n\t\tattempt.wire.releaseOpening();\n\t\treturn await attempt.authenticate(\"responder\");\n\t} catch (error) {\n\t\tattempt.stop(error instanceof Error ? error : new Error(\"Noise opening rejected\"));\n\t\tthrow error;\n\t}\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { performance } from \"node:perf_hooks\";\nimport type { Duplex } from \"node:stream\";\nimport { finished } from \"node:stream/promises\";\nimport type { OwnedPeerHttpConnection } from \"./peer-http-client.js\";\nimport { adoptPeerHttpConnection, PeerHttpLifetime } from \"./peer-http-client-lifecycle.js\";\nimport { readPeerHttpBodyLength } from \"./peer-http-headers.js\";\nimport { PEER_HTTP_LIMITS, PeerHttpExchangeError } from \"./peer-http-policy.js\";\nimport { capturePeerHttpResponse } from \"./peer-http-server-response.js\";\nimport { PeerHttpWireAudit } from \"./peer-http-wire-audit.js\";\nimport { readAuthenticatedRelayNoisePeerPin } from \"./relay-noise.js\";\nimport { RelayNoiseDuplex } from \"./relay-noise-stream.js\";\n\nexport interface PeerHttpServerRequest {\n\treadonly method: \"GET\" | \"POST\";\n\treadonly target: string;\n\treadonly url: string;\n\treadonly headers: Readonly<Record<string, string>>;\n\treadonly bodyBytes: Uint8Array;\n\treadonly peerPin: string;\n\treadonly signal: AbortSignal;\n}\n\nexport interface PeerHttpServerResponse {\n\treadonly status: number;\n\treadonly headers?: Readonly<Record<string, string>>;\n\treadonly bodyBytes: Uint8Array;\n}\n\nexport interface PeerHttpServerOptions {\n\treadonly origin: string;\n\treadonly dispatch: (request: PeerHttpServerRequest) => Promise<PeerHttpServerResponse>;\n\treadonly deadlineMs?: number;\n\treadonly signal?: AbortSignal;\n}\n\nfunction captureOptions(options: PeerHttpServerOptions, startedAt: number) {\n\ttry {\n\t\tconst { origin, dispatch, deadlineMs, signal } = options;\n\t\tconst parsed = new URL(origin);\n\t\tif (\n\t\t\ttypeof origin !== \"string\" ||\n\t\t\t!/^https?:\\/\\/[^/?#]+\\/?$/.test(origin) ||\n\t\t\t(parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n\t\t\tparsed.username ||\n\t\t\tparsed.password ||\n\t\t\tparsed.pathname !== \"/\" ||\n\t\t\tparsed.search ||\n\t\t\tparsed.hash ||\n\t\t\ttypeof dispatch !== \"function\" ||\n\t\t\t(deadlineMs !== undefined && !Number.isFinite(deadlineMs)) ||\n\t\t\t(signal !== undefined && !(signal instanceof AbortSignal))\n\t\t)\n\t\t\tthrow new Error();\n\t\treturn {\n\t\t\torigin: parsed.origin,\n\t\t\thost: parsed.host,\n\t\t\tdispatch,\n\t\t\tsignal,\n\t\t\tdeadline: Math.min(startedAt + PEER_HTTP_LIMITS.exchangeMs, deadlineMs ?? Infinity),\n\t\t};\n\t} catch {\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t}\n}\n\nfunction requireFreshConnection(duplex: Duplex): string {\n\tif (\n\t\t!(duplex instanceof RelayNoiseDuplex) ||\n\t\tduplex.destroyed ||\n\t\tduplex.errored ||\n\t\tduplex.readableEnded ||\n\t\tduplex.writableEnded ||\n\t\tduplex.readableLength !== 0 ||\n\t\tduplex.writableLength !== 0 ||\n\t\tduplex.readableFlowing === true\n\t)\n\t\tthrow new PeerHttpExchangeError(\"transport\");\n\tconst peerPin = readAuthenticatedRelayNoisePeerPin(duplex);\n\tif (peerPin === null) throw new PeerHttpExchangeError(\"transport\");\n\treturn peerPin;\n}\n\nfunction validateTargetCharacters(target: string): void {\n\tfor (const character of target) {\n\t\tconst code = character.charCodeAt(0);\n\t\tif (code <= 32 || code === 127 || character === \"\\\\\" || character === \"#\")\n\t\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t}\n}\n\ninterface CapturedRequest {\n\treadonly method: \"GET\" | \"POST\";\n\treadonly target: string;\n\treadonly url: string;\n\treadonly headers: Readonly<Record<string, string>>;\n\treadonly length: number;\n}\n\nfunction captureRequest(\n\tincoming: IncomingMessage,\n\toptions: ReturnType<typeof captureOptions>,\n): CapturedRequest {\n\tconst method = incoming.method;\n\tconst target = incoming.url;\n\tif (\n\t\t(method !== \"GET\" && method !== \"POST\") ||\n\t\tincoming.httpVersion !== \"1.1\" ||\n\t\ttarget === undefined ||\n\t\t!target.startsWith(\"/\") ||\n\t\ttarget.startsWith(\"//\")\n\t)\n\t\tthrow new PeerHttpExchangeError(\"framing\");\n\tvalidateTargetCharacters(target);\n\tconst url = options.origin + target;\n\tconst parsed = new URL(url);\n\tif (parsed.pathname + parsed.search !== target) throw new PeerHttpExchangeError(\"framing\");\n\tconst length = readPeerHttpBodyLength(incoming.rawHeaders, { direction: \"request\" });\n\tconst headers: Record<string, string> = Object.create(null);\n\tfor (let index = 0; index < incoming.rawHeaders.length; index += 2) {\n\t\tconst name = incoming.rawHeaders[index];\n\t\tconst value = incoming.rawHeaders[index + 1];\n\t\tif (typeof name !== \"string\" || typeof value !== \"string\")\n\t\t\tthrow new PeerHttpExchangeError(\"framing\");\n\t\theaders[name.toLowerCase()] = value;\n\t}\n\tif (headers.host !== options.host) throw new PeerHttpExchangeError(\"framing\");\n\treturn { method, target, url, headers: Object.freeze(headers), length };\n}\n\nfunction receiveBody(incoming: IncomingMessage, length: number, lifetime: PeerHttpLifetime) {\n\treturn new Promise<Buffer>((resolve, reject) => {\n\t\tconst bytes = Buffer.alloc(length);\n\t\tlet received = 0;\n\t\tincoming.once(\"error\", () => reject(lifetime.fail(\"transport\")));\n\t\tincoming.once(\"aborted\", () => reject(lifetime.fail(\"framing\")));\n\t\tincoming.on(\"data\", (chunk: Buffer) => {\n\t\t\tif (!Buffer.isBuffer(chunk) || received + chunk.length > length) {\n\t\t\t\treject(lifetime.fail(\"framing\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tchunk.copy(bytes, received);\n\t\t\treceived += chunk.length;\n\t\t});\n\t\tincoming.once(\"end\", () => {\n\t\t\tif (!incoming.complete || received !== length || incoming.rawTrailers.length !== 0)\n\t\t\t\treject(lifetime.fail(\"framing\"));\n\t\t\telse resolve(bytes);\n\t\t});\n\t});\n}\n\nfunction observeRequest(duplex: Duplex, lifetime: PeerHttpLifetime) {\n\tconst audit = new PeerHttpWireAudit({ direction: \"request\" });\n\tconst eof = Promise.withResolvers<void>();\n\tvoid eof.promise.catch(() => {});\n\tconst data = (chunk: unknown): void => {\n\t\ttry {\n\t\t\taudit.observe(chunk);\n\t\t} catch {\n\t\t\tlifetime.fail(\"framing\");\n\t\t}\n\t};\n\tconst end = (): void => {\n\t\ttry {\n\t\t\taudit.finish();\n\t\t\teof.resolve();\n\t\t} catch {\n\t\t\teof.reject(lifetime.fail(\"framing\"));\n\t\t}\n\t};\n\tconst error = (): void => {\n\t\tlifetime.fail(\"transport\");\n\t};\n\tduplex.on(\"data\", data);\n\tduplex.once(\"end\", end);\n\tduplex.on(\"error\", error);\n\treturn {\n\t\taudit,\n\t\teof: eof.promise,\n\t\tremove: () => {\n\t\t\tduplex.off(\"data\", data);\n\t\t\tduplex.off(\"end\", end);\n\t\t\tduplex.off(\"error\", error);\n\t\t},\n\t};\n}\n\nasync function writeResponse(\n\tresponse: ServerResponse,\n\tcaptured: ReturnType<typeof capturePeerHttpResponse>,\n\tlifetime: PeerHttpLifetime,\n): Promise<void> {\n\tlifetime.check();\n\tresponse.sendDate = false;\n\tresponse.writeHead(captured.status, captured.message, captured.headers);\n\tfor (let offset = 0; offset < captured.body.length; offset += 16384) {\n\t\tlifetime.check();\n\t\tlet drained = false;\n\t\tlet written = false;\n\t\tlet resume = (): void => {};\n\t\tconst onDrain = (): void => {\n\t\t\tdrained = true;\n\t\t\tresume();\n\t\t};\n\t\ttry {\n\t\t\tawait lifetime.wait(\n\t\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\t\tresume = () => {\n\t\t\t\t\t\tif (drained && written) resolve();\n\t\t\t\t\t};\n\t\t\t\t\tresponse.once(\"drain\", onDrain);\n\t\t\t\t\tdrained = response.write(captured.body.subarray(offset, offset + 16384), (error) => {\n\t\t\t\t\t\tif (error) reject(lifetime.fail(\"transport\"));\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\twritten = true;\n\t\t\t\t\t\t\tresume();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tresume();\n\t\t\t\t}),\n\t\t\t);\n\t\t} finally {\n\t\t\tresponse.off(\"drain\", onDrain);\n\t\t}\n\t}\n\tlifetime.check();\n\tawait lifetime.wait(new Promise<void>((resolve) => response.end(resolve)));\n}\n\nasync function dispatchRequest(\n\tincoming: IncomingMessage,\n\tresponse: ServerResponse,\n\toptions: ReturnType<typeof captureOptions>,\n\taudit: PeerHttpWireAudit,\n\tlifetime: PeerHttpLifetime,\n\tpeerPin: string,\n): Promise<void> {\n\tresponse.on(\"error\", () => lifetime.fail(\"transport\"));\n\tlifetime.check();\n\tlet request: ReturnType<typeof captureRequest>;\n\ttry {\n\t\trequest = captureRequest(incoming, options);\n\t\taudit.expectBodyBytes(request.length);\n\t} catch {\n\t\tthrow lifetime.fail(\"framing\");\n\t}\n\tconst bodyBytes = await lifetime.wait(receiveBody(incoming, request.length, lifetime));\n\tlifetime.check();\n\tconst dto: PeerHttpServerRequest = Object.freeze({\n\t\tmethod: request.method,\n\t\ttarget: request.target,\n\t\turl: request.url,\n\t\theaders: request.headers,\n\t\tbodyBytes,\n\t\tpeerPin,\n\t\tsignal: lifetime.controller.signal,\n\t});\n\tconst result = await lifetime.wait(options.dispatch(dto));\n\tlifetime.check();\n\tlet captured: ReturnType<typeof capturePeerHttpResponse>;\n\ttry {\n\t\tcaptured = capturePeerHttpResponse(result);\n\t} catch (error) {\n\t\tthrow lifetime.fail(error instanceof PeerHttpExchangeError ? error.code : \"framing\");\n\t}\n\tlifetime.check();\n\tawait writeResponse(response, captured, lifetime);\n}\n\nasync function exchange(\n\tduplex: Duplex,\n\tcompletion: Promise<void>,\n\toptions: ReturnType<typeof captureOptions>,\n\tlifetime: PeerHttpLifetime,\n): Promise<void> {\n\tconst peerPin = requireFreshConnection(duplex);\n\tduplex.pause();\n\tconst observer = observeRequest(duplex, lifetime);\n\tconst plaintext = finished(duplex, { cleanup: true });\n\tvoid plaintext.catch(() => {});\n\tconst response = Promise.withResolvers<void>();\n\tvoid response.promise.catch(() => {});\n\tlet requested = false;\n\tconst server = createServer({\n\t\t// captureRequest requires the logical Host before dispatch. Avoid Node's implicit 400 bypass.\n\t\trequireHostHeader: false,\n\t\tmaxHeaderSize: PEER_HTTP_LIMITS.headerBytes,\n\t\trequestTimeout: 0,\n\t\theadersTimeout: 0,\n\t\tkeepAliveTimeout: 0,\n\t});\n\t// Preserve a pending response when request EOF arrives before asynchronous dispatch finishes.\n\tObject.assign(server, { httpAllowHalfOpen: true });\n\tserver.maxHeadersCount = 0;\n\tserver.on(\"request\", (incoming, outgoing) => {\n\t\tif (requested) {\n\t\t\tlifetime.fail(\"framing\");\n\t\t\treturn;\n\t\t}\n\t\trequested = true;\n\t\tvoid dispatchRequest(incoming, outgoing, options, observer.audit, lifetime, peerPin).then(\n\t\t\tresponse.resolve,\n\t\t\t() => response.reject(lifetime.fail(\"transport\")),\n\t\t);\n\t});\n\tfor (const event of [\"checkContinue\", \"checkExpectation\", \"upgrade\", \"connect\", \"clientError\"])\n\t\tserver.on(event, () => lifetime.fail(\"framing\"));\n\ttry {\n\t\t// The independent audit precedes Node's synchronous pure-JS socket parser attachment.\n\t\tserver.emit(\"connection\", duplex);\n\t\tduplex.resume();\n\t\tawait lifetime.wait(Promise.all([response.promise, observer.eof, plaintext, completion]));\n\t} finally {\n\t\tobserver.remove();\n\t}\n}\n\n/** Inert one-exchange adapter. The caller's dispatcher must enforce channel-bound authorization. */\nexport async function servePeerHttpConnection(\n\tconnection: OwnedPeerHttpConnection,\n\toptions: PeerHttpServerOptions,\n): Promise<void> {\n\tconst startedAt = performance.now();\n\tlet owner: ReturnType<typeof adoptPeerHttpConnection> | undefined;\n\tlet lifetime: PeerHttpLifetime | undefined;\n\tlet stop: (() => void) | undefined;\n\ttry {\n\t\towner = adoptPeerHttpConnection(connection);\n\t\tif (!owner.valid) throw new PeerHttpExchangeError(\"transport\");\n\t\tconst captured = captureOptions(options, startedAt);\n\t\tlifetime = new PeerHttpLifetime(captured.deadline, captured.signal);\n\t\tconst active = lifetime;\n\t\tconst duplex = owner.duplex;\n\t\tstop = () => {\n\t\t\tduplex.destroy(active.fail(\"transport\"));\n\t\t};\n\t\tactive.controller.signal.addEventListener(\"abort\", stop, { once: true });\n\t\tvoid owner.completion.catch(() => active.fail(\"transport\"));\n\t\tactive.check();\n\t\tawait exchange(duplex, owner.completion, captured, active);\n\t} catch (error) {\n\t\tconst code = error instanceof PeerHttpExchangeError ? error.code : \"transport\";\n\t\tconst failure = lifetime?.fail(code) ?? new PeerHttpExchangeError(code);\n\t\tif (owner?.valid) owner.duplex.destroy(failure);\n\t\tif (owner) await owner.dispose(failure);\n\t\tthrow failure;\n\t} finally {\n\t\tif (stop) lifetime?.controller.signal.removeEventListener(\"abort\", stop);\n\t\tlifetime?.close();\n\t}\n}\n","import { performance } from \"node:perf_hooks\";\nimport { Duplex } from \"node:stream\";\nimport type { OwnedPeerHttpConnection } from \"./peer-http-client.js\";\nimport { PeerHttpExchangeError } from \"./peer-http-policy.js\";\nimport type { RelayControl } from \"./relay-control-codec.js\";\nimport { encodeRelayDataFrame } from \"./relay-data-frame.js\";\nimport {\n\tRelayFailure,\n\ttype RelayFailureReason,\n\trelayFailureReason,\n} from \"./relay-failure-reason.js\";\n\ntype Done = (error?: Error | null) => void;\nconst BUFFER_BYTES = 256 * 1024;\nconst FRAME_RESERVE_BYTES = 65_558 + 14;\nconst nativeByteLength = Object.getOwnPropertyDescriptor(\n\tObject.getPrototypeOf(Uint8Array.prototype),\n\t\"byteLength\",\n)?.get;\n\nexport interface RelayPeerTransportOptions {\n\treadonly sessionId: string;\n\treadonly side: \"source\" | \"target\";\n\treadonly deadlineMs: number;\n\treadonly signal: AbortSignal;\n\treadonly validate: () => void;\n\treadonly send: (message: RelayControl | Uint8Array) => Promise<void>;\n\treadonly remove: (options: { clean: boolean }) => void;\n\t/** Native writes still owned after the cleanup grace require physical socket termination. */\n\treadonly terminate: () => void;\n\t/** Called synchronously with the first terminal reason, before asynchronous cleanup finishes. */\n\treadonly onFailure?: (reason: RelayFailureReason) => void;\n}\n\n/** An executor failure such as malformed framing aborts the route, but did not expire it. */\nexport function relayAbortReason(\n\tsignal: AbortSignal,\n\toptions: { readonly secured: boolean },\n): RelayFailureReason {\n\tconst cause: unknown = signal.reason;\n\tif (\n\t\t!(cause instanceof PeerHttpExchangeError) ||\n\t\tcause.code === \"deadline\" ||\n\t\tcause.code === \"cancelled\"\n\t)\n\t\treturn \"relay_expired\";\n\treturn options.secured ? \"relay_record_invalid\" : \"relay_handshake_failed\";\n}\n\n/** One logical route. Disposing this stream never closes an otherwise healthy outer socket. */\nexport class RelayPeerTransport extends Duplex {\n\treadonly completion: Promise<void>;\n\tprivate readonly result = Promise.withResolvers<void>();\n\tprivate readonly remoteEOF = Promise.withResolvers<void>();\n\tprivate remoteEnd = false;\n\tprivate endSubmitted = false;\n\tprivate endWritten = false;\n\tprivate released = false;\n\tprivate frames = 0;\n\tprivate bytes = 0;\n\tprivate writes = 0;\n\tprivate pending?: Done;\n\tprivate readonly deadlineTimer: ReturnType<typeof setTimeout>;\n\tprivate idleTimer?: ReturnType<typeof setTimeout>;\n\tprivate receivingPartial = false;\n\tprivate waitingForResponse = false;\n\tprivate secured = false;\n\tprivate reason?: RelayFailureReason;\n\n\tconstructor(private readonly options: RelayPeerTransportOptions) {\n\t\tsuper({ allowHalfOpen: true, autoDestroy: true, highWaterMark: 16384 });\n\t\tif (!Number.isFinite(options.deadlineMs)) throw new Error(\"Invalid relay deadline\");\n\t\tthis.completion = this.result.promise;\n\t\tvoid this.completion.catch(() => {});\n\t\tvoid this.remoteEOF.promise.catch(() => {});\n\t\tthis.on(\"error\", () => {});\n\t\tthis.once(\"close\", () => {\n\t\t\tif (this.errored) this.result.reject(this.errored);\n\t\t\telse this.result.resolve();\n\t\t});\n\t\tthis.deadlineTimer = setTimeout(\n\t\t\t() => this.destroy(new RelayFailure(\"relay_expired\", \"Relay route expired\")),\n\t\t\tMath.max(0, Math.min(options.deadlineMs - performance.now(), 60_000)),\n\t\t);\n\t\tthis.deadlineTimer.unref();\n\t\toptions.signal.addEventListener(\"abort\", this.aborted, { once: true });\n\t\tif (options.signal.aborted) this.aborted();\n\t}\n\n\t/** HTTP dispatch disables this once the complete request is available for authorization. */\n\tsetReceivingPartial({ active }: { active: boolean }): void {\n\t\tthis.receivingPartial = active;\n\t\tclearTimeout(this.idleTimer);\n\t\tif (!active || this.destroyed) return;\n\t\tthis.idleTimer = setTimeout(\n\t\t\t() => this.destroy(new RelayFailure(\"relay_expired\", \"Relay receive idle\")),\n\t\t\t10_000,\n\t\t);\n\t\tthis.idleTimer.unref();\n\t}\n\n\t/** Observe only when an application consumer starts reading. Attaching this must not drain bytes. */\n\tobservePlaintext(duplex: Duplex): void {\n\t\tthis.waitingForResponse = this.options.side === \"source\";\n\t\tif (this.options.side === \"target\") this.setReceivingPartial({ active: true });\n\t\tconst observe = (): void => {\n\t\t\tif (this.destroyed) return;\n\t\t\tif (this.waitingForResponse) {\n\t\t\t\tthis.waitingForResponse = false;\n\t\t\t\tthis.receivingPartial = true;\n\t\t\t}\n\t\t\tthis.setReceivingPartial({ active: this.receivingPartial });\n\t\t};\n\t\tconst attach = (event: string | symbol): void => {\n\t\t\tif (event !== \"data\") return;\n\t\t\tduplex.off(\"newListener\", attach);\n\t\t\tduplex.prependListener(\"data\", observe);\n\t\t};\n\t\tduplex.on(\"newListener\", attach);\n\t\tduplex.once(\"close\", () => {\n\t\t\tduplex.off(\"newListener\", attach);\n\t\t\tduplex.off(\"data\", observe);\n\t\t});\n\t}\n\n\t/** Marks Noise authentication complete, so later untagged stream failures are record faults. */\n\tmarkSecured(): void {\n\t\tthis.secured = true;\n\t}\n\n\t/** The first terminal reason. Unset while the route is open or after a clean completion. */\n\tget failureReason(): RelayFailureReason | undefined {\n\t\treturn this.reason;\n\t}\n\n\tprivate check(): void {\n\t\tif (this.destroyed || this.released || performance.now() >= this.options.deadlineMs)\n\t\t\tthrow new RelayFailure(\"relay_expired\", \"Relay route unavailable\");\n\t\tthis.options.validate();\n\t}\n\n\tprivate account(length: number): void {\n\t\tthis.check();\n\t\tif (++this.frames > 2048 || length > 20 * 1024 * 1024 - this.bytes)\n\t\t\tthrow new RelayFailure(\"relay_unavailable\", \"Relay route wire budget exceeded\");\n\t\tthis.bytes += length;\n\t}\n\n\treceive(payload: Uint8Array): void {\n\t\ttry {\n\t\t\tif (this.remoteEnd) throw new RelayFailure(\"relay_frame_invalid\", \"Relay DATA after End\");\n\t\t\tthis.account(payload.byteLength + 22);\n\t\t\tif (this.readableLength + payload.byteLength > BUFFER_BYTES)\n\t\t\t\tthrow new RelayFailure(\"relay_frame_invalid\", \"Relay route read buffer exceeded\");\n\t\t\tthis.push(Buffer.from(payload));\n\t\t} catch (error) {\n\t\t\tthis.destroy(relayPeerError(error));\n\t\t}\n\t}\n\n\treceiveEnd(): void {\n\t\ttry {\n\t\t\tthis.check();\n\t\t\tif (this.remoteEnd || (this.options.side === \"source\" && !this.endSubmitted))\n\t\t\t\tthrow new RelayFailure(\"relay_frame_invalid\", \"Relay End out of order\");\n\t\t\tthis.remoteEnd = true;\n\t\t\tthis.remoteEOF.resolve();\n\t\t\tthis.setReceivingPartial({ active: false });\n\t\t\tthis.push(null);\n\t\t} catch (error) {\n\t\t\tthis.destroy(relayPeerError(error));\n\t\t}\n\t}\n\n\toverride setEncoding(_encoding: BufferEncoding): this {\n\t\tthrow new TypeError(\"Relay transport requires byte reads\");\n\t}\n\n\toverride write(\n\t\tchunk: Uint8Array | string,\n\t\tencodingOrCallback?: BufferEncoding | Done,\n\t\tcallback?: Done,\n\t): boolean {\n\t\tconst done = typeof encodingOrCallback === \"function\" ? encodingOrCallback : callback;\n\t\ttry {\n\t\t\tif (!(chunk instanceof Uint8Array)) throw new TypeError(\"Relay writes require bytes\");\n\t\t\tconst length: number = nativeByteLength?.call(chunk);\n\t\t\tif (\n\t\t\t\t!Number.isSafeInteger(length) ||\n\t\t\t\tlength < 0 ||\n\t\t\t\tlength + this.writableLength > BUFFER_BYTES - FRAME_RESERVE_BYTES\n\t\t\t)\n\t\t\t\tthrow new RelayFailure(\"relay_unavailable\", \"Relay route write buffer exceeded\");\n\t\t\tconst owned = Buffer.allocUnsafe(length);\n\t\t\tfor (let index = 0; index < length; index++) owned[index] = chunk[index] ?? 0;\n\t\t\treturn super.write(owned, done);\n\t\t} catch (error) {\n\t\t\tconst failure = relayPeerError(error);\n\t\t\tqueueMicrotask(() => done?.(failure));\n\t\t\tthis.destroy(failure);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\toverride end(\n\t\tchunkOrCallback?: Uint8Array | string | (() => void),\n\t\tencodingOrCallback?: BufferEncoding | (() => void),\n\t\tcallback?: () => void,\n\t): this {\n\t\tif (typeof chunkOrCallback === \"function\") return super.end(chunkOrCallback);\n\t\tconst done = typeof encodingOrCallback === \"function\" ? encodingOrCallback : callback;\n\t\tif (chunkOrCallback !== undefined) this.write(chunkOrCallback);\n\t\treturn super.end(done);\n\t}\n\n\toverride _read(): void {}\n\n\tprivate run(operation: () => Promise<void>, callback: Done): void {\n\t\tlet settled = false;\n\t\tconst finish: Done = (error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tthis.pending = undefined;\n\t\t\tcallback(error);\n\t\t};\n\t\tthis.pending = finish;\n\t\tvoid operation().then(\n\t\t\t() => finish(),\n\t\t\t(error: unknown) => finish(relayPeerError(error)),\n\t\t);\n\t}\n\n\tprivate async send(message: RelayControl | Uint8Array): Promise<void> {\n\t\tthis.check();\n\t\tthis.writes++;\n\t\ttry {\n\t\t\tawait this.options.send(message);\n\t\t\tthis.check();\n\t\t} finally {\n\t\t\tthis.writes--;\n\t\t}\n\t}\n\n\toverride _write(chunk: Buffer, _encoding: BufferEncoding, callback: Done): void {\n\t\tthis.run(async () => {\n\t\t\tfor (let offset = 0; offset < chunk.length; offset += 65_536) {\n\t\t\t\tconst frame = encodeRelayDataFrame({\n\t\t\t\t\tsessionId: this.options.sessionId,\n\t\t\t\t\tpayload: chunk.subarray(offset, offset + 65_536),\n\t\t\t\t});\n\t\t\t\tthis.account(frame.length);\n\t\t\t\tawait this.send(frame);\n\t\t\t}\n\t\t}, callback);\n\t}\n\n\toverride _final(callback: Done): void {\n\t\tthis.run(async () => {\n\t\t\tif (this.options.side === \"target\") await this.remoteEOF.promise;\n\t\t\tthis.check();\n\t\t\tthis.endSubmitted = true;\n\t\t\tawait this.send(this.control(\"end\"));\n\t\t\tthis.endWritten = true;\n\t\t}, callback);\n\t}\n\n\tprivate control(mode: \"abort\" | \"end\"): RelayControl {\n\t\treturn { v: 1, type: \"CLOSE\", session: this.options.sessionId, body: { mode } };\n\t}\n\n\tprivate readonly aborted = (): void => {\n\t\tthis.destroy(new RelayFailure(this.abortReason(), \"Relay route cancelled\"));\n\t};\n\n\tprivate abortReason(): RelayFailureReason {\n\t\treturn relayAbortReason(this.options.signal, { secured: this.secured });\n\t}\n\n\toverride _destroy(error: Error | null, callback: Done): void {\n\t\tconst clean = !error && this.remoteEnd && this.endWritten && this.writes === 0;\n\t\tconst failure = error ?? new Error(\"Relay route disposed before clean completion\");\n\t\t// Streams call _destroy once, so the first terminal error decides the reason.\n\t\tif (!clean) {\n\t\t\tthis.reason = relayFailureReason(\n\t\t\t\tfailure,\n\t\t\t\tthis.secured ? \"relay_record_invalid\" : \"relay_handshake_failed\",\n\t\t\t);\n\t\t\tthis.options.onFailure?.(this.reason);\n\t\t}\n\t\tthis.released = true;\n\t\tclearTimeout(this.deadlineTimer);\n\t\tclearTimeout(this.idleTimer);\n\t\tthis.options.signal.removeEventListener(\"abort\", this.aborted);\n\t\tthis.remoteEOF.reject(failure);\n\t\tthis.pending?.(failure);\n\t\tif (clean) {\n\t\t\tthis.options.remove({ clean: true });\n\t\t\tcallback(null);\n\t\t\treturn;\n\t\t}\n\t\tlet settled = false;\n\t\tlet abortPending = true;\n\t\tconst finish = (): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tclearTimeout(timer);\n\t\t\tthis.options.remove({ clean: false });\n\t\t\tcallback(failure);\n\t\t};\n\t\tconst timer = setTimeout(() => {\n\t\t\tif (this.writes > 0 || abortPending) this.options.terminate();\n\t\t\tfinish();\n\t\t}, 1500);\n\t\tvoid this.options\n\t\t\t.send(this.control(\"abort\"))\n\t\t\t.catch(() => {})\n\t\t\t.finally(() => {\n\t\t\t\tabortPending = false;\n\t\t\t\tif (this.writes > 0) return;\n\t\t\t\tfinish();\n\t\t\t});\n\t}\n}\n\nexport function relayPeerError(error: unknown): Error {\n\treturn error instanceof Error ? error : new Error(\"Relay peer connection failed\");\n}\n\nexport function ownRelayPeerConnection(\n\traw: RelayPeerTransport,\n\tduplex: Duplex,\n): OwnedPeerHttpConnection {\n\traw.observePlaintext(duplex);\n\treturn {\n\t\tduplex,\n\t\tcompletion: raw.completion,\n\t\tasync dispose(error) {\n\t\t\tduplex.destroy(error);\n\t\t\traw.destroy(error);\n\t\t\tawait raw.completion.catch(() => {});\n\t\t},\n\t};\n}\n","import { createPublicKey, KeyObject, randomBytes, sign } from \"node:crypto\";\nimport { performance } from \"node:perf_hooks\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport WebSocket, { type ClientOptions, type RawData } from \"ws\";\nimport type { OwnedPeerHttpConnection, PeerHttpConnectionFactory } from \"./peer-http-client.js\";\nimport { PeerHttpExchangeError, type PeerHttpExchangeErrorCode } from \"./peer-http-policy.js\";\nimport { type PeerHttpServerOptions, servePeerHttpConnection } from \"./peer-http-server.js\";\nimport {\n\tdecodeRelayCheckPacket,\n\tencodeRelayAdmissionBody,\n\tencodeRelayCheckPacket,\n\tencodeRelayRegistrationBody,\n\ttype RelayAdmissionBody,\n\ttype RelayCheckPacket,\n} from \"./relay-admission-codec.js\";\nimport { verifyRelayCheckProof } from \"./relay-admission-proof.js\";\nimport { readRelayAdmissionReply } from \"./relay-admission-reply.js\";\nimport {\n\tdecodeRelayControl,\n\tencodeRelayControl,\n\ttype RelayControl,\n} from \"./relay-control-codec.js\";\nimport { decodeRelayDataFrame } from \"./relay-data-frame.js\";\nimport { parseRelayEd25519PublicKey } from \"./relay-ed25519.js\";\nimport {\n\tasRelayFailure,\n\tcreateRelayFailureRecorder,\n\tRELAY_FAILURE_REASONS,\n\tRelayFailure,\n\ttype RelayFailureReason,\n\trelayFailureReason,\n} from \"./relay-failure-reason.js\";\nimport { acceptRelayNoiseResponder, prepareRelayNoiseInitiator } from \"./relay-noise.js\";\nimport type { RelayNoiseLocalIdentity } from \"./relay-noise-identity.js\";\nimport {\n\townRelayPeerConnection,\n\tRelayPeerTransport,\n\trelayAbortReason,\n\trelayPeerError,\n} from \"./relay-peer-transport.js\";\nimport {\n\trelayAudienceId,\n\trelayBodyDigest,\n\trelayRealmId,\n\tverifyRelayServiceProof,\n} from \"./relay-service-proof.js\";\n\ntype Deferred<T> = ReturnType<typeof Promise.withResolvers<T>>;\ntype ControlOf<T extends RelayControl[\"type\"]> = Extract<RelayControl, { type: T }>;\nconst MAX_SOCKET_SESSIONS = 4096;\nexport interface RelayPeerContext {\n\treadonly peerDeviceId: string;\n\treadonly peerPin: string;\n\treadonly sessionId: string;\n\treadonly deadlineMs: number;\n\treadonly signal: AbortSignal;\n\t/** Invoke again immediately before shared HTTP dispatch. Admission grants no scope. */\n\trevalidate(): void;\n\tsetReceivingPartial(options: { active: boolean }): void;\n\t/** Serves one exchange and handles receive-idle suspension and pre-dispatch pin revalidation. */\n\tserve(options: PeerHttpServerOptions): Promise<void>;\n}\n\nexport interface RelayPairPacing {\n\treadonly monotonicMs: () => number;\n\tdelay(milliseconds: number, signal: AbortSignal): Promise<void>;\n}\n\nconst nativePairPacing: RelayPairPacing = {\n\tmonotonicMs: () => performance.now(),\n\tdelay: (milliseconds, signal) => delay(milliseconds, undefined, { signal }),\n};\n\nexport interface RelayPeerClientOptions {\n\treadonly enabled?: boolean;\n\treadonly url: string;\n\treadonly allowLoopbackWs?: boolean;\n\treadonly servicePublicKey: string;\n\treadonly deviceId: string;\n\treadonly localIdentity: RelayNoiseLocalIdentity & { readonly key: KeyObject };\n\treadonly authorityId: string;\n\treadonly groupId: string;\n\treadonly relayAudienceId: string;\n\treadonly externalPathname: string;\n\treadonly coordinator: RelayPeerCoordinator;\n\treadonly resolvePeerPin: (peerDeviceId: string) => string | null;\n\treadonly validateLocal: () => boolean;\n\t/** Pair pacing only. Registration, proof freshness and route lifetimes use native clocks. */\n\treadonly pairPacing?: RelayPairPacing;\n\treadonly onInbound: (\n\t\tconnection: OwnedPeerHttpConnection,\n\t\tcontext: RelayPeerContext,\n\t) => Promise<void>;\n\t/** Local diagnostics only. Never includes peer, route, key, payload, or raw error text. */\n\treadonly onInboundFailure?: (failure: RelayInboundFailure) => void;\n}\n\nexport interface RelayInboundFailure {\n\treadonly stage: \"admission\" | \"handshake\" | \"http\";\n\treadonly reason: RelayFailureReason;\n\treadonly httpCode?: PeerHttpExchangeErrorCode;\n}\n\nexport interface RelayPeerCoordinator {\n\tcheck(options: {\n\t\treadonly packet: RelayCheckPacket;\n\t\treadonly deviceHeader: string;\n\t\treadonly signal: AbortSignal;\n\t}): Promise<Uint8Array | null>;\n}\n\nexport interface RelayPeerConnectionFactory extends PeerHttpConnectionFactory {\n\t/** The first local failure reason across this factory's routes. Later failures never replace it. */\n\tfailureReason(): RelayFailureReason | undefined;\n}\n\nexport interface RelayPeerClient {\n\tconnect(signal: AbortSignal, deadlineMs: number): Promise<void>;\n\tmaintainRegistration(signal: AbortSignal, deadlineMs: number): Promise<void>;\n\t/** Create one factory per sync pass so its failure reason describes only that pass. */\n\tfactory(peerDeviceId: string, currentPin: string): RelayPeerConnectionFactory;\n\t/** Call synchronously when local trust or the operator switch changes. */\n\trevalidate(): void;\n\tclose(): Promise<void>;\n}\n\ninterface Setup {\n\treadonly session: string;\n\treadonly proof: Deferred<ControlOf<\"SERVICE_PROOF\">>;\n\treadonly challenge: Deferred<RelayControl>;\n\treadonly registered: Deferred<ControlOf<\"REGISTERED\">>;\n\tproofReceived: boolean;\n\tchallengeId?: string;\n\tregisterSent: boolean;\n}\ninterface Route {\n\treadonly id: string;\n\tsocket?: WebSocket;\n\treadonly peer: string;\n\treadonly pin: string;\n\treadonly side: \"source\" | \"target\";\n\treadonly raw: RelayPeerTransport;\n\treadonly cancel: AbortController;\n\treadonly accepted: Deferred<void>;\n\tdeadline: number;\n\ttimer: ReturnType<typeof setTimeout>;\n\tactive: boolean;\n\topened: boolean;\n\tacceptedAtMs: number;\n\tinboundStage?: RelayInboundFailure[\"stage\"];\n}\n\nfunction deferred<T>(): Deferred<T> {\n\tconst value = Promise.withResolvers<T>();\n\tvoid value.promise.catch(() => {});\n\treturn value;\n}\n\nfunction wait<T>(promise: Promise<T>, signal: AbortSignal, deadline: number): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst finish = (result: { value: T } | { error: Error }): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tclearTimeout(timer);\n\t\t\tsignal.removeEventListener(\"abort\", abort);\n\t\t\tif (\"error\" in result) reject(result.error);\n\t\t\telse resolve(result.value);\n\t\t};\n\t\tconst abort = (): void =>\n\t\t\tfinish({ error: new RelayFailure(\"relay_expired\", \"Relay operation cancelled or expired\") });\n\t\tconst timer = setTimeout(abort, Math.max(0, deadline - performance.now()));\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\tvoid promise.then(\n\t\t\t(value) => finish({ value }),\n\t\t\t(error: unknown) => finish({ error: relayPeerError(error) }),\n\t\t);\n\t\tif (signal.aborted || deadline <= performance.now()) abort();\n\t});\n}\n\n/**\n * Registration runs on its own client-owned deadline, so a timeout there means the relay did not\n * answer. Service proof, association, timeout, and socket failures all leave the relay unusable.\n */\nfunction registrationFailure(error: unknown): RelayFailure {\n\tconst failure = asRelayFailure(error, \"relay_unavailable\");\n\tif (failure.reason !== \"relay_expired\") return failure;\n\treturn new RelayFailure(\"relay_unavailable\", failure.message);\n}\n\n/** REJECTED and CLOSE abort carry no cause on the wire. Other controls here violate route order. */\nfunction routeControlReason(message: RelayControl): RelayFailureReason {\n\tif (message.type === \"REJECTED\") return \"relay_rejected\";\n\tif (message.type === \"CLOSE\" && message.body.mode === \"abort\") return \"relay_aborted\";\n\treturn \"relay_frame_invalid\";\n}\n\nfunction keyId(pin: string): string {\n\treturn relayBodyDigest(parseRelayEd25519PublicKey(pin).wireKey);\n}\n\nfunction endpoint(options: RelayPeerClientOptions): string {\n\tconst url = new URL(options.url);\n\tconst loopback = [\"127.0.0.1\", \"[::1]\"].includes(url.hostname);\n\tif (\n\t\t(url.protocol !== \"wss:\" && !(url.protocol === \"ws:\" && loopback && options.allowLoopbackWs)) ||\n\t\turl.username ||\n\t\turl.password ||\n\t\turl.search ||\n\t\turl.hash\n\t)\n\t\tthrow new Error(\"Invalid relay WebSocket endpoint\");\n\t// Disposable ws fixtures bind their audience to the same host/port with the wss scheme.\n\tconst secureOrigin = url.origin.replace(/^ws:/, \"wss:\");\n\tif (relayAudienceId(secureOrigin, keyId(options.servicePublicKey)) !== options.relayAudienceId)\n\t\tthrow new Error(\"Relay audience does not match the configured origin and service pin\");\n\treturn url.href;\n}\n\nclass Client implements RelayPeerClient {\n\tprivate readonly options: RelayPeerClientOptions;\n\tprivate readonly url: string;\n\tprivate readonly localKeyId: string;\n\tprivate readonly pairPacing: RelayPairPacing;\n\tprivate socket?: WebSocket;\n\tprivate socketClosed?: Deferred<void>;\n\t/**\n\t * Sockets already failed. A terminated socket can still deliver queued messages\n\t * and its close event, and routes created for the next socket must survive both.\n\t */\n\tprivate readonly failedSockets = new WeakSet<WebSocket>();\n\tprivate opening?: Deferred<void>;\n\tprivate setup?: Setup;\n\tprivate connecting?: Promise<void>;\n\tprivate registrationAbort?: AbortController;\n\tprivate registrationExpires = 0;\n\tprivate pendingBytes = 0;\n\tprivate readonly writes = new Set<(error?: Error) => void>();\n\tprivate readonly routes = new Map<string, Route>();\n\tprivate readonly retiredRoutes = new Set<string>();\n\tprivate readonly waiters = new Map<string, Deferred<void>>();\n\tprivate readonly nextPairOpen = new Map<string, number>();\n\tprivate closed = false;\n\n\tconstructor(options: RelayPeerClientOptions) {\n\t\tthis.options = { ...options, localIdentity: { ...options.localIdentity } };\n\t\tthis.pairPacing = options.pairPacing ?? nativePairPacing;\n\t\tthis.url = endpoint(options);\n\t\tthis.localKeyId = keyId(options.localIdentity.expectedPin);\n\t\tconst key = options.localIdentity.key;\n\t\tif (\n\t\t\t!(key instanceof KeyObject) ||\n\t\t\tkey.type !== \"private\" ||\n\t\t\tkey.asymmetricKeyType !== \"ed25519\"\n\t\t)\n\t\t\tthrow new Error(\"Relay client requires an existing Ed25519 private KeyObject\");\n\t\tconst publicKey = createPublicKey(key).export({ format: \"jwk\" });\n\t\tif (\n\t\t\tpublicKey.x !==\n\t\t\tBuffer.from(parseRelayEd25519PublicKey(options.localIdentity.expectedPin).rawKey).toString(\n\t\t\t\t\"base64url\",\n\t\t\t)\n\t\t)\n\t\t\tthrow new Error(\"Relay local identity mismatch\");\n\t\tconst path = options.externalPathname;\n\t\tif (\n\t\t\t!path.startsWith(\"/\") ||\n\t\t\tpath.startsWith(\"//\") ||\n\t\t\t/[\\s?#\\\\]/u.test(path) ||\n\t\t\t!path.endsWith(\"/v1/relay/admission-check\")\n\t\t)\n\t\t\tthrow new Error(\"Invalid externally signed admission pathname\");\n\t}\n\n\tprivate validate(peer?: string, pin?: string): void {\n\t\tif (this.closed || this.options.enabled !== true || !this.options.validateLocal())\n\t\t\tthrow new RelayFailure(\n\t\t\t\t\"relay_disabled\",\n\t\t\t\t\"Relay client disabled or local identity no longer current\",\n\t\t\t);\n\t\tif (peer !== undefined && this.options.resolvePeerPin(peer) !== pin)\n\t\t\tthrow new RelayFailure(\"relay_peer_revoked\", \"Relay peer pin no longer current\");\n\t}\n\n\tconnect(signal: AbortSignal, deadlineMs: number): Promise<void> {\n\t\treturn this.maintainRegistration(signal, deadlineMs);\n\t}\n\n\tasync maintainRegistration(signal: AbortSignal, deadlineMs: number): Promise<void> {\n\t\tthis.validate();\n\t\tthis.failClosingSocket();\n\t\tconst deadline = Math.min(deadlineMs, performance.now() + 30_000);\n\t\tif (!Number.isFinite(deadlineMs) || signal.aborted || deadline <= performance.now())\n\t\t\tthrow new RelayFailure(\"relay_expired\", \"Invalid relay setup lifetime\");\n\t\tif (\n\t\t\tthis.socket?.readyState === WebSocket.OPEN &&\n\t\t\tthis.registrationExpires - performance.now() >= 150_000\n\t\t)\n\t\t\treturn;\n\t\tif (!this.connecting) {\n\t\t\tconst registrationAbort = new AbortController();\n\t\t\tthis.registrationAbort = registrationAbort;\n\t\t\tconst operation = this.register(registrationAbort.signal, performance.now() + 30_000);\n\t\t\tthis.connecting = operation;\n\t\t\tvoid operation\n\t\t\t\t.finally(() => {\n\t\t\t\t\tif (this.connecting === operation) this.connecting = undefined;\n\t\t\t\t\tif (this.registrationAbort === registrationAbort) this.registrationAbort = undefined;\n\t\t\t\t})\n\t\t\t\t.catch(() => {});\n\t\t}\n\t\tawait wait(this.connecting, signal, deadline);\n\t}\n\n\tprivate async openSocket(signal: AbortSignal, deadline: number): Promise<void> {\n\t\tif (this.socket?.readyState === WebSocket.OPEN) return;\n\t\t// A failed socket is terminated at once but clears only on its close event,\n\t\t// so the next open waits for that within its own deadline instead of failing.\n\t\tif (this.socket) await wait(this.socketClosed?.promise ?? Promise.resolve(), signal, deadline);\n\t\tif (this.socket) throw new Error(\"Relay socket still closing\");\n\t\tconst webSocketOptions: ClientOptions & {\n\t\t\tmaxFragments: number;\n\t\t\tmaxBufferedChunks: number;\n\t\t\tcloseTimeout: number;\n\t\t} = {\n\t\t\tperMessageDeflate: false,\n\t\t\tautoPong: false,\n\t\t\tallowSynchronousEvents: false,\n\t\t\tcloseTimeout: 1500,\n\t\t\tmaxFragments: 32,\n\t\t\tmaxBufferedChunks: 256,\n\t\t\tmaxPayload: 65_558,\n\t\t\tfollowRedirects: false,\n\t\t\thandshakeTimeout: Math.max(1, deadline - performance.now()),\n\t\t};\n\t\tconst socket = new WebSocket(this.url, webSocketOptions);\n\t\tthis.socket = socket;\n\t\tconst socketClosed = deferred<void>();\n\t\tthis.socketClosed = socketClosed;\n\t\tconst opened = deferred<void>();\n\t\tthis.opening = opened;\n\t\tsocket.once(\"open\", () => opened.resolve());\n\t\tsocket.on(\"error\", () => {\n\t\t\topened.reject(new Error(\"Relay WebSocket failed\"));\n\t\t\tthis.failSocket(socket);\n\t\t});\n\t\tsocket.once(\"close\", () => {\n\t\t\tthis.failSocket(socket);\n\t\t\tif (this.socket !== socket) return;\n\t\t\tfor (const write of this.writes)\n\t\t\t\twrite(new RelayFailure(\"relay_unavailable\", \"Relay WebSocket closed\"));\n\t\t\tthis.retiredRoutes.clear();\n\t\t\tthis.socket = undefined;\n\t\t\tsocketClosed.resolve();\n\t\t});\n\t\tsocket.on(\"message\", (bytes, binary) => this.receive(socket, bytes, binary));\n\t\tsocket.on(\"ping\", () => this.failSocket(socket, \"relay_frame_invalid\"));\n\t\tsocket.on(\"pong\", () => this.failSocket(socket, \"relay_frame_invalid\"));\n\t\ttry {\n\t\t\tawait wait(opened.promise, signal, deadline);\n\t\t} finally {\n\t\t\tif (this.opening === opened) this.opening = undefined;\n\t\t}\n\t}\n\n\tprivate async register(signal: AbortSignal, deadline: number): Promise<void> {\n\t\ttry {\n\t\t\tawait this.openSocket(signal, deadline);\n\t\t\tthis.validate();\n\t\t\tconst setup: Setup = {\n\t\t\t\tsession: randomBytes(16).toString(\"hex\"),\n\t\t\t\tproof: deferred(),\n\t\t\t\tchallenge: deferred(),\n\t\t\t\tregistered: deferred(),\n\t\t\t\tproofReceived: false,\n\t\t\t\tregisterSent: false,\n\t\t\t};\n\t\t\tthis.setup = setup;\n\t\t\tconst started = performance.now();\n\t\t\tawait this.send({\n\t\t\t\tv: 1,\n\t\t\t\ttype: \"SERVICE_CHALLENGE\",\n\t\t\t\tsession: setup.session,\n\t\t\t\tbody: { audienceId: this.options.relayAudienceId },\n\t\t\t});\n\t\t\tconst proof = await wait(setup.proof.promise, signal, Math.min(deadline, started + 5000));\n\t\t\tif (\n\t\t\t\t!(await verifyRelayServiceProof({\n\t\t\t\t\taudienceId: this.options.relayAudienceId,\n\t\t\t\t\tchallengeId: setup.session,\n\t\t\t\t\tpublicKey: this.options.servicePublicKey,\n\t\t\t\t\tbody: proof.body,\n\t\t\t\t\tstartedAtMs: started,\n\t\t\t\t\tnowMs: performance.now(),\n\t\t\t\t\tdeadlineMs: deadline,\n\t\t\t\t}))\n\t\t\t)\n\t\t\t\tthrow new Error(\"Relay service proof invalid\");\n\t\t\tconst challenge = await wait(setup.challenge.promise, signal, deadline);\n\t\t\tthis.validate();\n\t\t\tconst packet = this.registrationPacket(challenge.session);\n\t\t\tsetup.registerSent = true;\n\t\t\tconst registrationStarted = performance.now();\n\t\t\tawait this.send({ v: 1, type: \"REGISTER\", session: challenge.session, body: packet });\n\t\t\tconst reply = await wait(setup.registered.promise, signal, deadline);\n\t\t\tthis.checkRegistration(reply);\n\t\t\tthis.validate();\n\t\t\tthis.registrationExpires = registrationStarted + reply.body.remainingMs;\n\t\t} catch (error) {\n\t\t\tif (this.socket) this.failSocket(this.socket);\n\t\t\tthrow registrationFailure(error);\n\t\t} finally {\n\t\t\tthis.setup = undefined;\n\t\t}\n\t}\n\n\tprivate registrationPacket(socketChallengeId: string): RelayCheckPacket {\n\t\tconst createdAt = Math.floor(Date.now() / 1000);\n\t\treturn this.signPacket(\n\t\t\tencodeRelayRegistrationBody({\n\t\t\t\tauthorityId: this.options.authorityId,\n\t\t\t\tgroupId: this.options.groupId,\n\t\t\t\tdeviceId: this.options.deviceId,\n\t\t\t\tkeyId: this.localKeyId,\n\t\t\t\trelayAudienceId: this.options.relayAudienceId,\n\t\t\t\tsocketChallengeId,\n\t\t\t\tcreatedAt,\n\t\t\t\tadmitBefore: createdAt + 30,\n\t\t\t}),\n\t\t\tcreatedAt,\n\t\t);\n\t}\n\n\tprivate checkRegistration(reply: ControlOf<\"REGISTERED\">): void {\n\t\tconst body = reply.body;\n\t\tif (\n\t\t\tbody.deviceId !== this.options.deviceId ||\n\t\t\tbody.keyId !== this.localKeyId ||\n\t\t\tbody.authorityId !== this.options.authorityId ||\n\t\t\tbody.realmId !== relayRealmId(this.options.authorityId, this.options.groupId)\n\t\t)\n\t\t\tthrow new Error(\"Relay socket registration association mismatch\");\n\t}\n\n\tprivate signPacket(bodyBytes: Uint8Array, createdAt: number): RelayCheckPacket {\n\t\tconst nonce = randomBytes(16).toString(\"hex\");\n\t\tconst timestamp = String(createdAt);\n\t\tconst canonical = [\n\t\t\t\"POST\",\n\t\t\tthis.options.externalPathname,\n\t\t\ttimestamp,\n\t\t\tnonce,\n\t\t\trelayBodyDigest(bodyBytes),\n\t\t].join(\"\\n\");\n\t\treturn encodeRelayCheckPacket({\n\t\t\tbodyBytes,\n\t\t\ttimestamp,\n\t\t\tnonce,\n\t\t\tsignatureBytes: sign(null, Buffer.from(canonical), this.options.localIdentity.key),\n\t\t});\n\t}\n\n\tprivate send(message: RelayControl | Uint8Array): Promise<void> {\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst socket = this.socket;\n\t\t\tconst bytes = message instanceof Uint8Array ? message : encodeRelayControl(message);\n\t\t\tconst length = Buffer.byteLength(bytes) + 14;\n\t\t\tif (\n\t\t\t\t!socket ||\n\t\t\t\tsocket.readyState !== WebSocket.OPEN ||\n\t\t\t\tthis.writes.size >= 16 ||\n\t\t\t\tMath.max(socket.bufferedAmount, this.pendingBytes) + length > 1024 * 1024\n\t\t\t) {\n\t\t\t\treject(new RelayFailure(\"relay_unavailable\", \"Relay WebSocket write capacity unavailable\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.pendingBytes += length;\n\t\t\tconst done = (error?: Error): void => {\n\t\t\t\tif (!this.writes.delete(done)) return;\n\t\t\t\tthis.pendingBytes -= length;\n\t\t\t\tif (error) reject(asRelayFailure(error, \"relay_unavailable\"));\n\t\t\t\telse resolve();\n\t\t\t};\n\t\t\tthis.writes.add(done);\n\t\t\ttry {\n\t\t\t\tsocket.send(bytes, { binary: message instanceof Uint8Array }, done);\n\t\t\t} catch {\n\t\t\t\tthis.failSocket(socket);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate receive(socket: WebSocket, data: RawData, binary: boolean): void {\n\t\tif (socket !== this.socket || this.failedSockets.has(socket)) return;\n\t\ttry {\n\t\t\tthis.validate();\n\t\t\tlet bytes: Uint8Array;\n\t\t\tif (Array.isArray(data)) bytes = Buffer.concat(data);\n\t\t\telse if (data instanceof ArrayBuffer) bytes = new Uint8Array(data);\n\t\t\telse bytes = data;\n\t\t\tif (binary) {\n\t\t\t\tconst frame = decodeRelayDataFrame(bytes);\n\t\t\t\tif (this.retiredRoutes.has(frame.sessionId)) return;\n\t\t\t\tconst route = this.routes.get(frame.sessionId);\n\t\t\t\tif (!route?.active) throw new Error(\"Relay DATA for unknown or unaccepted route\");\n\t\t\t\troute.raw.receive(frame.payload);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.control(decodeRelayControl(bytes));\n\t\t} catch (error) {\n\t\t\t// Untagged errors here are cleartext frame decode or ordering failures.\n\t\t\tthis.failSocket(socket, relayFailureReason(error, \"relay_frame_invalid\"));\n\t\t}\n\t}\n\n\tprivate control(message: RelayControl): void {\n\t\tif (this.connectionControl(message)) return;\n\t\tif (message.type === \"OPEN\") {\n\t\t\tthis.incoming(message);\n\t\t\treturn;\n\t\t}\n\t\tconst route = this.routes.get(message.session);\n\t\tif (!route) {\n\t\t\tif (message.type === \"ACCEPTED\" && this.retiredRoutes.has(message.session)) return;\n\t\t\tif (message.type === \"CLOSE\" || message.type === \"REJECTED\") return;\n\t\t\tthrow new Error(\"Unexpected relay control\");\n\t\t}\n\t\tif (message.type === \"ACCEPTED\" && route.side === \"source\" && route.opened && !route.active) {\n\t\t\tthis.rememberOpen(route.peer);\n\t\t\troute.active = true;\n\t\t\troute.acceptedAtMs = performance.now();\n\t\t\troute.accepted.resolve();\n\t\t} else if (message.type === \"CLOSE\" && message.body.mode === \"end\" && route.active)\n\t\t\troute.raw.receiveEnd();\n\t\telse\n\t\t\troute.raw.destroy(\n\t\t\t\tnew RelayFailure(routeControlReason(message), \"Relay route rejected or aborted\"),\n\t\t\t);\n\t}\n\n\tprivate connectionControl(message: RelayControl): boolean {\n\t\tconst setup = this.setup;\n\t\tif (\n\t\t\tmessage.type === \"SERVICE_PROOF\" &&\n\t\t\tsetup &&\n\t\t\t!setup.proofReceived &&\n\t\t\tmessage.session === setup.session\n\t\t) {\n\t\t\tsetup.proofReceived = true;\n\t\t\tsetup.proof.resolve(message);\n\t\t\treturn true;\n\t\t}\n\t\tif (message.type === \"SOCKET_CHALLENGE\" && setup?.proofReceived && !setup.challengeId) {\n\t\t\tsetup.challengeId = message.session;\n\t\t\tsetup.challenge.resolve(message);\n\t\t\treturn true;\n\t\t}\n\t\tif (\n\t\t\tmessage.type === \"REGISTERED\" &&\n\t\t\tsetup?.registerSent &&\n\t\t\tmessage.session === setup.challengeId\n\t\t) {\n\t\t\tsetup.registerSent = false;\n\t\t\tsetup.registered.resolve(message);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate failSocket(socket: WebSocket, reason: RelayFailureReason = \"relay_unavailable\"): void {\n\t\tif (this.socket !== socket || this.failedSockets.has(socket)) return;\n\t\tthis.failedSockets.add(socket);\n\t\tthis.registrationAbort?.abort();\n\t\tthis.registrationExpires = 0;\n\t\tconst error = new RelayFailure(reason, \"Relay WebSocket disconnected\");\n\t\tthis.opening?.reject(error);\n\t\tthis.setup?.proof.reject(error);\n\t\tthis.setup?.challenge.reject(error);\n\t\tthis.setup?.registered.reject(error);\n\t\tthis.endRoutes(error);\n\t\tsocket.terminate();\n\t}\n\n\t/**\n\t * A graceful close leaves the socket CLOSING, without an event, until the peer\n\t * ends TCP or closeTimeout passes. Fail it now, before a new route or\n\t * registration exists, so its later close event cannot end them.\n\t */\n\tprivate failClosingSocket(): void {\n\t\tconst socket = this.socket;\n\t\tif (\n\t\t\tsocket &&\n\t\t\tsocket.readyState !== WebSocket.CONNECTING &&\n\t\t\tsocket.readyState !== WebSocket.OPEN\n\t\t)\n\t\t\tthis.failSocket(socket);\n\t}\n\n\t/** Ends every route and capacity waiter, including any created while a failed socket closes. */\n\tprivate endRoutes(error: Error): void {\n\t\tfor (const route of this.routes.values()) route.raw.destroy(error);\n\t\tfor (const waiter of this.waiters.values()) waiter.reject(error);\n\t\tthis.waiters.clear();\n\t}\n\n\tfactory(peerDeviceId: string, currentPin: string): RelayPeerConnectionFactory {\n\t\tconst failures = createRelayFailureRecorder();\n\t\treturn {\n\t\t\topen: async ({ signal, deadlineMs }) => {\n\t\t\t\t// A caller can abort and return before this open settles, so record the abort at once.\n\t\t\t\tconst aborted = (): void => failures.record(relayAbortReason(signal, { secured: false }));\n\t\t\t\tsignal.addEventListener(\"abort\", aborted, { once: true });\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.open(peerDeviceId, currentPin, signal, deadlineMs, failures.record);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Routes record their own reason first. This covers failures before a route exists.\n\t\t\t\t\tfailures.record(relayFailureReason(error, \"relay_unavailable\"));\n\t\t\t\t\tthrow error;\n\t\t\t\t} finally {\n\t\t\t\t\tsignal.removeEventListener(\"abort\", aborted);\n\t\t\t\t}\n\t\t\t},\n\t\t\tfailureReason: failures.reason,\n\t\t};\n\t}\n\n\tprivate hasRoute(peer: string, side: Route[\"side\"]): boolean {\n\t\treturn [...this.routes.values()].some((route) => route.peer === peer && route.side === side);\n\t}\n\n\tprivate async capacity(peer: string, signal: AbortSignal, deadline: number): Promise<void> {\n\t\tif (!this.hasRoute(peer, \"source\") && this.routes.size < 4) return;\n\t\tif (this.waiters.has(peer) || this.waiters.size >= 4)\n\t\t\tthrow new RelayFailure(\"relay_unavailable\", \"Relay capacity exhausted\");\n\t\tconst waiter = deferred<void>();\n\t\tthis.waiters.set(peer, waiter);\n\t\ttry {\n\t\t\tawait wait(waiter.promise, signal, Math.min(deadline, performance.now() + 3000)).catch(\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\t// Only the local 3 s cap ends the wait with relay_expired while the caller is still\n\t\t\t\t\t// live and in time. Keep any other failure, such as a socket failure rejecting the waiter.\n\t\t\t\t\tconst capTimedOut =\n\t\t\t\t\t\terror instanceof RelayFailure &&\n\t\t\t\t\t\terror.reason === \"relay_expired\" &&\n\t\t\t\t\t\t!signal.aborted &&\n\t\t\t\t\t\tperformance.now() < deadline;\n\t\t\t\t\tif (!capTimedOut) throw error;\n\t\t\t\t\tthrow new RelayFailure(\"relay_unavailable\", \"Relay capacity exhausted\");\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (this.hasRoute(peer, \"source\") || this.routes.size >= 4)\n\t\t\t\tthrow new RelayFailure(\"relay_unavailable\", \"Relay capacity exhausted\");\n\t\t} finally {\n\t\t\tif (this.waiters.get(peer) === waiter) this.waiters.delete(peer);\n\t\t}\n\t}\n\n\tprivate createRoute(\n\t\tid: string,\n\t\tpeer: string,\n\t\tpin: string,\n\t\tside: Route[\"side\"],\n\t\tsignal: AbortSignal,\n\t\tdeadline: number,\n\t\tonFailure?: (reason: RelayFailureReason) => void,\n\t): Route {\n\t\tthis.validate(peer, pin);\n\t\tif (signal.aborted || deadline <= performance.now())\n\t\t\tthrow new RelayFailure(\"relay_expired\", \"Relay route lifetime expired\");\n\t\tif (\n\t\t\tthis.routes.has(id) ||\n\t\t\tthis.retiredRoutes.has(id) ||\n\t\t\tthis.routes.size >= 4 ||\n\t\t\tthis.retiredRoutes.size + this.routes.size >= MAX_SOCKET_SESSIONS ||\n\t\t\tthis.hasRoute(peer, side)\n\t\t)\n\t\t\tthrow new RelayFailure(\"relay_unavailable\", \"Relay route capacity exhausted\");\n\t\tconst cancel = new AbortController();\n\t\tconst abort = (): void => cancel.abort(signal.reason);\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\tif (signal.aborted) cancel.abort(signal.reason);\n\t\tconst raw = new RelayPeerTransport({\n\t\t\tsessionId: id,\n\t\t\tside,\n\t\t\tdeadlineMs: deadline,\n\t\t\tsignal: cancel.signal,\n\t\t\tvalidate: () => this.validate(peer, pin),\n\t\t\tsend: (message) => this.sendRouteMessage(message, { id, side }),\n\t\t\tterminate: () => {\n\t\t\t\tif (this.socket) this.failSocket(this.socket);\n\t\t\t},\n\t\t\tremove: ({ clean }) =>\n\t\t\t\tthis.removeRoute(id, () => {\n\t\t\t\t\tsignal.removeEventListener(\"abort\", abort);\n\t\t\t\t\tif (!clean) cancel.abort();\n\t\t\t\t}),\n\t\t\tonFailure,\n\t\t});\n\t\tconst route: Route = {\n\t\t\tid,\n\t\t\tsocket: this.socket,\n\t\t\tpeer,\n\t\t\tpin,\n\t\t\tside,\n\t\t\traw,\n\t\t\tcancel,\n\t\t\taccepted: deferred(),\n\t\t\tdeadline,\n\t\t\ttimer: setTimeout(() => cancel.abort(), Math.max(0, deadline - performance.now())),\n\t\t\tactive: false,\n\t\t\topened: false,\n\t\t\tacceptedAtMs: 0,\n\t\t};\n\t\troute.timer.unref();\n\t\tthis.routes.set(id, route);\n\t\treturn route;\n\t}\n\n\tprivate sendRouteMessage(\n\t\tmessage: RelayControl | Uint8Array,\n\t\t{ id, side }: Pick<Route, \"id\" | \"side\">,\n\t): Promise<void> {\n\t\t// A reserved source route is unknown to the relay until OPEN is submitted.\n\t\tif (\n\t\t\tside === \"source\" &&\n\t\t\t!this.routes.get(id)?.opened &&\n\t\t\t!(message instanceof Uint8Array) &&\n\t\t\tmessage.type === \"CLOSE\"\n\t\t)\n\t\t\treturn Promise.resolve();\n\t\treturn this.send(message);\n\t}\n\n\tprivate removeRoute(id: string, cleanup: () => void): void {\n\t\tconst route = this.routes.get(id);\n\t\tif (!route) return;\n\t\tif (route.socket === this.socket && this.socket?.readyState === WebSocket.OPEN)\n\t\t\tthis.retiredRoutes.add(id);\n\t\tthis.routes.delete(id);\n\t\tclearTimeout(route.timer);\n\t\tcleanup();\n\t\troute.accepted.reject(new Error(\"Relay route removed\"));\n\t\t// Never evict session IDs while late frames can still arrive on this socket.\n\t\tif (this.routes.size === 0 && this.retiredRoutes.size >= MAX_SOCKET_SESSIONS && this.socket)\n\t\t\tthis.failSocket(this.socket);\n\t\tthis.wakeWaiters();\n\t}\n\n\tprivate wakeWaiters(): void {\n\t\tlet capacity = 4 - this.routes.size;\n\t\tfor (const [peer, waiter] of this.waiters) {\n\t\t\tif (capacity <= 0) return;\n\t\t\tif (this.hasRoute(peer, \"source\")) continue;\n\t\t\tcapacity--;\n\t\t\twaiter.resolve();\n\t\t}\n\t}\n\n\tprivate async check(packet: RelayCheckPacket, deviceHeader: string, route: Route): Promise<void> {\n\t\tconst started = performance.now();\n\t\tconst bytes = await wait(\n\t\t\tthis.options.coordinator.check({ packet, deviceHeader, signal: route.cancel.signal }),\n\t\t\troute.cancel.signal,\n\t\t\troute.deadline,\n\t\t).catch((error: unknown) => {\n\t\t\tthrow asRelayFailure(error, \"relay_admission_failed\");\n\t\t});\n\t\tconst reply = bytes && readRelayAdmissionReply(bytes, packet);\n\t\t// The coordinator client returns null for both a denial and an unreachable coordinator.\n\t\tif (!reply)\n\t\t\tthrow new RelayFailure(\n\t\t\t\t\"relay_admission_failed\",\n\t\t\t\t\"Relay independent coordinator check denied\",\n\t\t\t);\n\t\tthis.validate(route.peer, route.pin);\n\t\troute.deadline = Math.min(route.deadline, started + reply.remainingMs);\n\t\tif (route.deadline <= performance.now())\n\t\t\tthrow new RelayFailure(\"relay_expired\", \"Relay admission expired in transit\");\n\t\tclearTimeout(route.timer);\n\t\troute.timer = setTimeout(() => route.cancel.abort(), route.deadline - performance.now());\n\t\troute.timer.unref();\n\t}\n\n\tprivate pairNow(): number {\n\t\tconst now = this.pairPacing.monotonicMs();\n\t\tif (!Number.isFinite(now))\n\t\t\tthrow new RelayFailure(\"relay_unavailable\", \"Invalid relay pair pacing clock\");\n\t\treturn now;\n\t}\n\n\tprivate rememberOpen(peer: string): void {\n\t\tconst now = this.pairNow();\n\t\tfor (const [id, deadline] of this.nextPairOpen)\n\t\t\tif (deadline <= now) this.nextPairOpen.delete(id);\n\t\tif (!this.nextPairOpen.has(peer) && this.nextPairOpen.size >= 128)\n\t\t\tthrow new RelayFailure(\"relay_unavailable\", \"Relay pacing capacity unavailable\");\n\t\t// Each direction receives half the pair's 20 opens/minute and burst of two.\n\t\t// Acceptance anchors the delay after the relay actually reserved the previous open.\n\t\tthis.nextPairOpen.set(peer, Math.max(this.nextPairOpen.get(peer) ?? 0, now + 6000));\n\t}\n\n\tprivate async pacePair(route: Route): Promise<void> {\n\t\tlet remaining = (this.nextPairOpen.get(route.peer) ?? 0) - this.pairNow();\n\t\twhile (remaining > 0) {\n\t\t\tconst cancelDelay = new AbortController();\n\t\t\ttry {\n\t\t\t\t// Keep native deadline/abort fences even when an injected delay ignores its signal.\n\t\t\t\tawait wait(\n\t\t\t\t\tthis.pairPacing.delay(Math.ceil(remaining), cancelDelay.signal),\n\t\t\t\t\troute.cancel.signal,\n\t\t\t\t\troute.deadline,\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\tcancelDelay.abort();\n\t\t\t}\n\t\t\tthis.validate(route.peer, route.pin);\n\t\t\tremaining = (this.nextPairOpen.get(route.peer) ?? 0) - this.pairNow();\n\t\t}\n\t}\n\n\tprivate async open(\n\t\tpeer: string,\n\t\tpin: string,\n\t\tsignal: AbortSignal,\n\t\tdeadlineMs: number,\n\t\trecord: (reason: RelayFailureReason) => void,\n\t): Promise<OwnedPeerHttpConnection> {\n\t\tif (!Number.isFinite(deadlineMs))\n\t\t\tthrow new RelayFailure(\"relay_expired\", \"Invalid relay exchange deadline\");\n\t\tconst deadline = Math.min(deadlineMs, performance.now() + 60_000);\n\t\tthis.validate(peer, pin);\n\t\tparseRelayEd25519PublicKey(pin);\n\t\tthis.failClosingSocket();\n\t\tif (this.hasRoute(peer, \"source\") || this.routes.size >= 4)\n\t\t\tawait this.capacity(peer, signal, deadline);\n\t\t// Reserve before registration yields, so concurrent invocations cannot bypass pair capacity.\n\t\tconst route = this.createRoute(\n\t\t\trandomBytes(16).toString(\"hex\"),\n\t\t\tpeer,\n\t\t\tpin,\n\t\t\t\"source\",\n\t\t\tsignal,\n\t\t\tdeadline,\n\t\t\trecord,\n\t\t);\n\t\t// The transport records its reason synchronously. This covers a route that ends otherwise.\n\t\tvoid route.raw.completion.catch(() => record(route.raw.failureReason ?? \"relay_unavailable\"));\n\t\ttry {\n\t\t\tawait this.maintainRegistration(route.cancel.signal, deadline);\n\t\t\tawait this.pacePair(route);\n\t\t\tconst prepared = prepareRelayNoiseInitiator(this.noiseOptions(route));\n\t\t\tconst opening = await wait(prepared.opening, route.cancel.signal, route.deadline);\n\t\t\tconst packets = this.admissionPackets(route, opening.digest);\n\t\t\tawait this.check(packets[0], this.options.deviceId, route);\n\t\t\tthis.validate(peer, pin);\n\t\t\troute.socket = this.socket;\n\t\t\troute.opened = true;\n\t\t\tawait this.send({\n\t\t\t\tv: 1,\n\t\t\t\ttype: \"OPEN\",\n\t\t\t\tsession: route.id,\n\t\t\t\tbody: { checks: [packets[1], packets[2]] },\n\t\t\t});\n\t\t\tthis.rememberOpen(peer);\n\t\t\tawait wait(route.accepted.promise, route.cancel.signal, route.deadline);\n\t\t\tthis.validate(peer, pin);\n\t\t\tprepared.release(route.acceptedAtMs);\n\t\t\tconst secured = await wait(prepared.authenticated, route.cancel.signal, route.deadline);\n\t\t\troute.raw.markSecured();\n\t\t\tthis.validate(peer, pin);\n\t\t\treturn ownRelayPeerConnection(route.raw, secured.duplex);\n\t\t} catch (error) {\n\t\t\troute.raw.destroy(relayPeerError(error));\n\t\t\tawait route.raw.completion.catch(() => {});\n\t\t\tthrow relayPeerError(error);\n\t\t}\n\t}\n\n\tprivate admissionPackets(\n\t\troute: Route,\n\t\tmessageADigest: string,\n\t): readonly [RelayCheckPacket, RelayCheckPacket, RelayCheckPacket] {\n\t\tconst createdAt = Math.floor(Date.now() / 1000);\n\t\tconst common: Omit<RelayAdmissionBody, \"role\"> = {\n\t\t\tauthorityId: this.options.authorityId,\n\t\t\tgroupId: this.options.groupId,\n\t\t\tsourceDeviceId: this.options.deviceId,\n\t\t\tsourceKeyId: this.localKeyId,\n\t\t\ttargetDeviceId: route.peer,\n\t\t\ttargetKeyId: keyId(route.pin),\n\t\t\trelayAudienceId: this.options.relayAudienceId,\n\t\t\trouteSessionId: route.id,\n\t\t\tmessageADigest,\n\t\t\tcreatedAt,\n\t\t\tadmitBefore: createdAt + 30,\n\t\t\trouteNotAfter: createdAt + 55,\n\t\t};\n\t\tconst packet = (role: RelayAdmissionBody[\"role\"]): RelayCheckPacket =>\n\t\t\tthis.signPacket(encodeRelayAdmissionBody({ role, ...common }), createdAt);\n\t\tconst packets = [packet(\"source\"), packet(\"relay\"), packet(\"responder\")] as const;\n\t\tif (new Set(packets.map((value) => value.nonce)).size !== 3)\n\t\t\tthrow new Error(\"Relay admission nonces must be distinct\");\n\t\treturn packets;\n\t}\n\n\tprivate noiseOptions(route: Route) {\n\t\treturn {\n\t\t\ttransport: route.raw,\n\t\t\tlocalIdentity: this.options.localIdentity,\n\t\t\texpectedRemotePin: route.pin,\n\t\t\tcontext: { transportLabel: 1 as const, sessionId: Buffer.from(route.id, \"hex\") },\n\t\t\tsignal: route.cancel.signal,\n\t\t\tdeadlineMs: route.deadline,\n\t\t};\n\t}\n\n\tprivate incoming(message: ControlOf<\"OPEN\">): void {\n\t\tlet route: Route;\n\t\ttry {\n\t\t\tif (this.registrationExpires <= performance.now())\n\t\t\t\tthrow new Error(\"Relay registration expired\");\n\t\t\tconst check = decodeRelayCheckPacket(message.body.checks[1]);\n\t\t\tif (check.kind !== \"admission\") throw new Error(\"Invalid relay admission\");\n\t\t\tconst body = check.value;\n\t\t\tconst pin = this.options.resolvePeerPin(body.sourceDeviceId);\n\t\t\tif (\n\t\t\t\t!pin ||\n\t\t\t\tbody.targetDeviceId !== this.options.deviceId ||\n\t\t\t\tbody.targetKeyId !== this.localKeyId ||\n\t\t\t\tbody.sourceKeyId !== keyId(pin) ||\n\t\t\t\tbody.authorityId !== this.options.authorityId ||\n\t\t\t\tbody.groupId !== this.options.groupId ||\n\t\t\t\tbody.relayAudienceId !== this.options.relayAudienceId\n\t\t\t)\n\t\t\t\tthrow new Error(\"Relay inbound tuple mismatch\");\n\t\t\troute = this.createRoute(\n\t\t\t\tmessage.session,\n\t\t\t\tbody.sourceDeviceId,\n\t\t\t\tpin,\n\t\t\t\t\"target\",\n\t\t\t\tnew AbortController().signal,\n\t\t\t\tperformance.now() + 60_000,\n\t\t\t);\n\t\t\troute.inboundStage = \"admission\";\n\t\t\tvoid this.acceptIncoming(route, message.body.checks[1], body.messageADigest).catch(\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tthis.reportInboundFailure(error, route);\n\t\t\t\t\troute.raw.destroy(relayPeerError(error));\n\t\t\t\t},\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthis.reportInboundFailure(error);\n\t\t\tvoid this.send({ v: 1, type: \"REJECTED\", session: message.session, body: {} }).catch(\n\t\t\t\t() => {},\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate reportInboundFailure(error: unknown, route?: Route): void {\n\t\tconst stage = route?.inboundStage ?? \"admission\";\n\t\t// Route cleanup can cancel the waiter before the HTTP handler rejects.\n\t\tconst originalError = route?.raw.errored ?? error;\n\t\tlet fallback: RelayFailureReason = \"relay_admission_failed\";\n\t\tif (stage === \"handshake\") fallback = \"relay_handshake_failed\";\n\t\tif (stage === \"http\") fallback = \"relay_record_invalid\";\n\t\tconst candidate = route?.raw.failureReason ?? relayFailureReason(originalError, fallback);\n\t\tconst reason = RELAY_FAILURE_REASONS.includes(candidate) ? candidate : fallback;\n\t\tlet httpCode: PeerHttpExchangeErrorCode | undefined;\n\t\tif (\n\t\t\toriginalError instanceof PeerHttpExchangeError &&\n\t\t\t[\"framing\", \"response_too_large\", \"deadline\", \"cancelled\", \"transport\", \"cleanup\"].includes(\n\t\t\t\toriginalError.code,\n\t\t\t)\n\t\t)\n\t\t\thttpCode = originalError.code;\n\t\ttry {\n\t\t\tthis.options.onInboundFailure?.({ stage, reason, ...(httpCode ? { httpCode } : {}) });\n\t\t} catch {\n\t\t\t// Diagnostics must not interrupt rejection, transport disposal, or socket cleanup.\n\t\t}\n\t}\n\n\tprivate async acceptIncoming(\n\t\troute: Route,\n\t\tpacket: RelayCheckPacket,\n\t\tmessageADigest: string,\n\t): Promise<void> {\n\t\tconst proof = await verifyRelayCheckProof({\n\t\t\tpacket,\n\t\t\texpected: { kind: \"admission\", role: \"responder\" },\n\t\t\tsigner: { deviceId: route.peer, publicKey: route.pin },\n\t\t\tdeviceHeader: route.peer,\n\t\t\texternalPathname: this.options.externalPathname,\n\t\t});\n\t\tif (!proof) throw new Error(\"Relay source admission signature invalid\");\n\t\tawait this.check(packet, route.peer, route);\n\t\tthis.validate(route.peer, route.pin);\n\t\troute.inboundStage = \"handshake\";\n\t\troute.active = true;\n\t\tconst acceptedAtMs = performance.now();\n\t\tawait this.send({ v: 1, type: \"ACCEPTED\", session: route.id, body: {} });\n\t\tconst secured = await acceptRelayNoiseResponder({\n\t\t\t...this.noiseOptions(route),\n\t\t\tverifiedMessageADigest: messageADigest,\n\t\t\tacceptedAtMs,\n\t\t});\n\t\troute.raw.markSecured();\n\t\tthis.validate(route.peer, route.pin);\n\t\tconst connection = ownRelayPeerConnection(route.raw, secured.duplex);\n\t\ttry {\n\t\t\troute.inboundStage = \"http\";\n\t\t\tconst context: RelayPeerContext = {\n\t\t\t\tpeerDeviceId: route.peer,\n\t\t\t\tpeerPin: route.pin,\n\t\t\t\tsessionId: route.id,\n\t\t\t\tdeadlineMs: route.deadline,\n\t\t\t\tsignal: route.cancel.signal,\n\t\t\t\trevalidate: () => this.validate(route.peer, route.pin),\n\t\t\t\tsetReceivingPartial: (options) => route.raw.setReceivingPartial(options),\n\t\t\t\tserve: (options) =>\n\t\t\t\t\tservePeerHttpConnection(connection, {\n\t\t\t\t\t\t...options,\n\t\t\t\t\t\tdeadlineMs: Math.min(options.deadlineMs ?? route.deadline, route.deadline),\n\t\t\t\t\t\tdispatch: async (request) => {\n\t\t\t\t\t\t\troute.raw.setReceivingPartial({ active: false });\n\t\t\t\t\t\t\tthis.validate(route.peer, route.pin);\n\t\t\t\t\t\t\treturn options.dispatch(request);\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t};\n\t\t\tawait wait(this.options.onInbound(connection, context), route.cancel.signal, route.deadline);\n\t\t\tawait wait(connection.completion, route.cancel.signal, route.deadline);\n\t\t} catch (error) {\n\t\t\tawait connection.dispose(relayPeerError(error));\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\trevalidate(): void {\n\t\ttry {\n\t\t\tthis.validate();\n\t\t} catch (error) {\n\t\t\tconst reason = relayFailureReason(error, \"relay_disabled\");\n\t\t\tif (this.socket) this.failSocket(this.socket, reason);\n\t\t\t// failSocket does nothing for a socket that already failed, so end routes here too.\n\t\t\tthis.endRoutes(new RelayFailure(reason, \"Relay client no longer trusted\"));\n\t\t\treturn;\n\t\t}\n\t\tfor (const route of this.routes.values()) {\n\t\t\ttry {\n\t\t\t\tthis.validate(route.peer, route.pin);\n\t\t\t} catch (error) {\n\t\t\t\troute.raw.destroy(relayPeerError(error));\n\t\t\t}\n\t\t}\n\t}\n\n\tasync close(): Promise<void> {\n\t\tthis.closed = true;\n\t\tconst registration = this.connecting;\n\t\tthis.registrationAbort?.abort();\n\t\tconst completions = [...this.routes.values()].map((route) => route.raw.completion);\n\t\tconst socketClosed = this.socketClosed?.promise ?? Promise.resolve();\n\t\tif (this.socket) this.failSocket(this.socket, \"relay_disabled\");\n\t\tthis.endRoutes(new RelayFailure(\"relay_disabled\", \"Relay client closed\"));\n\t\tawait Promise.all([\n\t\t\tPromise.allSettled([...completions, registration]),\n\t\t\twait(socketClosed, new AbortController().signal, performance.now() + 1500),\n\t\t]);\n\t}\n}\n\n/** Construction performs no I/O. Only explicit enabled clients can register or open routes. */\nexport function createRelayPeerClient(options: RelayPeerClientOptions): RelayPeerClient {\n\treturn new Client(options);\n}\n\nexport function isRelayPeerClient(value: unknown): value is RelayPeerClient {\n\treturn value instanceof Client;\n}\n"],"x_google_ignoreList":[16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA0BA,IAAM,KAAmB,cACnB,KAAkB,kBAClB,KAAmB;AAEzB,SAAS,KAAyB;CACjC,OAAO,GAAK,EAAe,GAAG,WAAW,WAAW,MAAM;AAC3D;AAUA,SAAS,KAAoC;CAG5C,OAFY,QAAQ,IAAI,wBAAwB,YAAY,MAChD,aAAmB,aACxB;AACR;AAMA,SAAS,GAAa,GAAsB;CAC3C,IAAI;EAEH,OADA,GAAa,SAAS,CAAC,CAAG,GAAG,EAAE,OAAO,OAAO,CAAC,GACvC;CACR,QAAQ;EACP,OAAO;CACR;AACD;AAMA,SAAS,KAAgC;CACpC,QAAQ,aAAa,YACrB,GAAa,MAAM,cACnB,QAAQ,IAAI,+BAA+B,OAC/C,QAAQ,KACP,0GACD;AACD;AAGA,SAAgB,GAAwB,GAAoB,GAA2B;CACtF,IAAI,QAAQ,aAAa,SAAS;EACjC,IAAI,CAAC,GAAa,aAAa,GAAG,OAAO;EACzC,IAAI;GAMH,OALA,GACC,eACA;IAAC;IAAS;IAAW;IAAoB;IAAW;IAAkB;IAAW;GAAQ,GACzF;IAAE,OAAO;IAAY,OAAO;KAAC;KAAQ;KAAQ;IAAM;GAAE,CACtD,GACO;EACR,QAAQ;GACP,OAAO;EACR;CACD;CACA,IAAI,QAAQ,aAAa,UAAU;EAClC,IAAI,CAAC,GAAa,UAAU,GAAG,OAA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