@private.me/xbind 3.0.1 → 3.0.2

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 (210) hide show
  1. package/README.md +55 -14
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1920 -1
  3. package/dist-standalone/_deps/shared/cjs/errors.js +729 -1
  4. package/dist-standalone/_deps/shared/cjs/index.js +463 -1
  5. package/dist-standalone/_deps/shared/cjs/types.js +315 -1
  6. package/dist-standalone/_deps/shared/errors.js +244 -1
  7. package/dist-standalone/_deps/shared/index.js +72 -1
  8. package/dist-standalone/_deps/shared/types.js +86 -1
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.js +659 -1
  47. package/dist-standalone/agent-sdk.js +328 -1
  48. package/dist-standalone/agent.js +1800 -1
  49. package/dist-standalone/approval.js +193 -1
  50. package/dist-standalone/async-iterators.js +382 -1
  51. package/dist-standalone/auth.js +219 -1
  52. package/dist-standalone/auto-accept.js +229 -1
  53. package/dist-standalone/backup-config.js +201 -1
  54. package/dist-standalone/backup.js +326 -1
  55. package/dist-standalone/batch-operations.js +388 -1
  56. package/dist-standalone/cancellation.js +477 -1
  57. package/dist-standalone/checkpoint.js +186 -1
  58. package/dist-standalone/circuit-breaker.js +468 -1
  59. package/dist-standalone/cjs/agent-call.js +701 -1
  60. package/dist-standalone/cjs/agent-sdk.js +332 -1
  61. package/dist-standalone/cjs/agent.js +1837 -1
  62. package/dist-standalone/cjs/approval.js +199 -1
  63. package/dist-standalone/cjs/async-iterators.js +392 -1
  64. package/dist-standalone/cjs/auth.js +225 -1
  65. package/dist-standalone/cjs/auto-accept.js +233 -1
  66. package/dist-standalone/cjs/backup-config.js +207 -1
  67. package/dist-standalone/cjs/backup.js +330 -1
  68. package/dist-standalone/cjs/batch-operations.js +397 -1
  69. package/dist-standalone/cjs/cancellation.js +490 -1
  70. package/dist-standalone/cjs/checkpoint.js +193 -1
  71. package/dist-standalone/cjs/circuit-breaker.js +476 -1
  72. package/dist-standalone/cjs/cli/init.js +492 -1
  73. package/dist-standalone/cjs/config-validation.js +522 -1
  74. package/dist-standalone/cjs/connect.js +312 -1
  75. package/dist-standalone/cjs/connection-pool.js +506 -1
  76. package/dist-standalone/cjs/correlation-id.js +339 -1
  77. package/dist-standalone/cjs/crypto-utils.js +176 -1
  78. package/dist-standalone/cjs/debug-mode.js +534 -1
  79. package/dist-standalone/cjs/did-document.js +101 -1
  80. package/dist-standalone/cjs/did-privateme.js +130 -1
  81. package/dist-standalone/cjs/did-web.js +201 -1
  82. package/dist-standalone/cjs/discovery.js +462 -1
  83. package/dist-standalone/cjs/dual-mode.js +251 -1
  84. package/dist-standalone/cjs/email-templates.js +313 -1
  85. package/dist-standalone/cjs/email-transport.js +239 -1
  86. package/dist-standalone/cjs/envelope.js +538 -1
  87. package/dist-standalone/cjs/errors.js +913 -1
  88. package/dist-standalone/cjs/event-emitter.js +461 -1
  89. package/dist-standalone/cjs/gateway-state.js +55 -1
  90. package/dist-standalone/cjs/gateway-transport.js +120 -1
  91. package/dist-standalone/cjs/graceful-degradation.js +403 -1
  92. package/dist-standalone/cjs/guardrails.js +223 -1
  93. package/dist-standalone/cjs/health-check.js +336 -1
  94. package/dist-standalone/cjs/http-compat.js +272 -1
  95. package/dist-standalone/cjs/http-status-map.js +571 -1
  96. package/dist-standalone/cjs/identity.js +645 -1
  97. package/dist-standalone/cjs/index.js +406 -1
  98. package/dist-standalone/cjs/invitation.js +421 -1
  99. package/dist-standalone/cjs/invite.js +328 -1
  100. package/dist-standalone/cjs/key-agreement.js +335 -1
  101. package/dist-standalone/cjs/lazy-init.js +300 -1
  102. package/dist-standalone/cjs/logger.js +291 -1
  103. package/dist-standalone/cjs/mdns-discovery.js +202 -1
  104. package/dist-standalone/cjs/nonce-store.js +80 -1
  105. package/dist-standalone/cjs/pairing-manager.js +223 -1
  106. package/dist-standalone/cjs/plugin-system.js +264 -1
  107. package/dist-standalone/cjs/plugins/logging.js +168 -1
  108. package/dist-standalone/cjs/plugins/metrics.js +181 -1
  109. package/dist-standalone/cjs/plugins/validation.js +302 -1
  110. package/dist-standalone/cjs/policy.js +320 -1
  111. package/dist-standalone/cjs/progress-callbacks.js +583 -1
  112. package/dist-standalone/cjs/redis-nonce-store.js +76 -1
  113. package/dist-standalone/cjs/registry-middleware.js +50 -1
  114. package/dist-standalone/cjs/retry-strategies.js +544 -1
  115. package/dist-standalone/cjs/retry-transport.js +102 -1
  116. package/dist-standalone/cjs/runtime/browser.js +533 -1
  117. package/dist-standalone/cjs/runtime/edge.js +526 -1
  118. package/dist-standalone/cjs/runtime/react-native.js +394 -1
  119. package/dist-standalone/cjs/security-policy.js +245 -1
  120. package/dist-standalone/cjs/serialization.js +1040 -1
  121. package/dist-standalone/cjs/split-channel.js +225 -1
  122. package/dist-standalone/cjs/subscription-proof.js +230 -1
  123. package/dist-standalone/cjs/succession.js +148 -1
  124. package/dist-standalone/cjs/timeouts.js +412 -1
  125. package/dist-standalone/cjs/trace-context.js +424 -1
  126. package/dist-standalone/cjs/trace-spans.js +495 -1
  127. package/dist-standalone/cjs/transport.js +63 -1
  128. package/dist-standalone/cjs/trust-registry.js +991 -1
  129. package/dist-standalone/cjs/types/error-response.js +56 -1
  130. package/dist-standalone/cjs/vault-auth.js +178 -1
  131. package/dist-standalone/cjs/vault-store-loader.js +194 -1
  132. package/dist-standalone/cjs/verify.js +25 -1
  133. package/dist-standalone/cjs/version-info.js +543 -1
  134. package/dist-standalone/cjs/xfetch.js +340 -1
  135. package/dist-standalone/cli/init.js +455 -1
  136. package/dist-standalone/cli/setup.js +514 -1
  137. package/dist-standalone/cli/types.js +27 -1
  138. package/dist-standalone/cli/xbind.js +148 -1
  139. package/dist-standalone/config-validation.js +513 -1
  140. package/dist-standalone/connect.js +274 -1
  141. package/dist-standalone/connection-pool.js +500 -1
  142. package/dist-standalone/correlation-id.js +326 -1
  143. package/dist-standalone/crypto-utils.js +157 -1
  144. package/dist-standalone/debug-mode.js +510 -1
  145. package/dist-standalone/did-document.js +96 -1
  146. package/dist-standalone/did-privateme.js +121 -1
  147. package/dist-standalone/did-web.js +196 -1
  148. package/dist-standalone/discovery.js +458 -1
  149. package/dist-standalone/dual-mode.js +247 -1
  150. package/dist-standalone/email-templates.js +309 -1
  151. package/dist-standalone/email-transport.js +232 -1
  152. package/dist-standalone/envelope.js +525 -1
  153. package/dist-standalone/errors.js +896 -1
  154. package/dist-standalone/event-emitter.js +456 -1
  155. package/dist-standalone/gateway-state.js +51 -1
  156. package/dist-standalone/gateway-transport.js +116 -1
  157. package/dist-standalone/graceful-degradation.js +396 -1
  158. package/dist-standalone/guardrails.js +216 -1
  159. package/dist-standalone/health-check.js +332 -1
  160. package/dist-standalone/http-compat.js +267 -1
  161. package/dist-standalone/http-status-map.js +561 -1
  162. package/dist-standalone/identity.js +619 -1
  163. package/dist-standalone/index.js +78 -1
  164. package/dist-standalone/invitation.js +415 -1
  165. package/dist-standalone/invite.js +324 -1
  166. package/dist-standalone/key-agreement.js +325 -1
  167. package/dist-standalone/lazy-init.js +295 -1
  168. package/dist-standalone/logger.js +285 -1
  169. package/dist-standalone/mdns-discovery.js +195 -1
  170. package/dist-standalone/nonce-store.js +76 -1
  171. package/dist-standalone/pairing-manager.js +219 -1
  172. package/dist-standalone/plugin-system.js +257 -1
  173. package/dist-standalone/plugins/logging.js +163 -1
  174. package/dist-standalone/plugins/metrics.js +176 -1
  175. package/dist-standalone/plugins/validation.js +297 -1
  176. package/dist-standalone/policy.js +315 -1
  177. package/dist-standalone/progress-callbacks.js +576 -1
  178. package/dist-standalone/redis-nonce-store.js +72 -1
  179. package/dist-standalone/registry-middleware.js +47 -1
  180. package/dist-standalone/retry-strategies.js +534 -1
  181. package/dist-standalone/retry-transport.js +98 -1
  182. package/dist-standalone/runtime/browser.js +516 -1
  183. package/dist-standalone/runtime/edge.js +511 -1
  184. package/dist-standalone/runtime/react-native.js +383 -1
  185. package/dist-standalone/security-policy.js +239 -1
  186. package/dist-standalone/serialization.js +1031 -1
  187. package/dist-standalone/split-channel.js +219 -1
  188. package/dist-standalone/subscription-proof.js +224 -1
  189. package/dist-standalone/succession.js +142 -1
  190. package/dist-standalone/timeouts.js +398 -1
  191. package/dist-standalone/trace-context.js +414 -1
  192. package/dist-standalone/trace-spans.js +488 -1
  193. package/dist-standalone/transport.js +59 -1
  194. package/dist-standalone/trust-registry.js +950 -1
  195. package/dist-standalone/types/error-response.js +52 -1
  196. package/dist-standalone/vault-auth.js +174 -1
  197. package/dist-standalone/vault-store-loader.js +187 -1
  198. package/dist-standalone/verify.js +16 -1
  199. package/dist-standalone/version-info.js +530 -1
  200. package/dist-standalone/xfetch.js +335 -1
  201. package/package.json +4 -13
  202. package/share1.dat +0 -0
  203. package/dist-standalone/_deps/mldsa-wasm/LICENSE +0 -24
  204. package/dist-standalone/_deps/mldsa-wasm/package.json +0 -46
  205. package/dist-standalone/_deps/shared/cjs/package.json +0 -1
  206. package/dist-standalone/_deps/ux-helpers/cjs/package.json +0 -1
  207. package/dist-standalone/_deps/xchange/cjs/package.json +0 -1
  208. package/dist-standalone/_deps/xregistry/cjs/package.json +0 -1
  209. package/dist-standalone/cjs/package.json +0 -3
  210. package/dist-standalone/package.json +0 -10
@@ -1 +1,538 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createEnvelope=createEnvelope,exports.createEnvelopeV2=createEnvelopeV2,exports.createEnvelopeV3=createEnvelopeV3,exports.createEnvelopeV4=createEnvelopeV4,exports.decryptPayload=decryptPayload,exports.serializeEnvelope=serializeEnvelope,exports.deserializeEnvelope=deserializeEnvelope,exports.validateEnvelope=validateEnvelope,exports.generateSharedKey=generateSharedKey,exports.createSignedEnvelope=createSignedEnvelope,exports.openSignedEnvelope=openSignedEnvelope;const shared_1=require("../_deps/shared/index.js"),crypto_utils_js_1=require("./crypto-utils.js"),identity_js_1=require("./identity.js"),NONCE_BYTES=16,AES_IV_BYTES=12,AES_ALGO="AES-GCM",KEM_CIPHERTEXT_BYTES=1088,ML_DSA65_SIG_BYTES=3309;function toArrayBuffer(e){const r=new ArrayBuffer(e.byteLength);return new Uint8Array(r).set(e),r}function createSignedData(e){const r=JSON.stringify({v:e.v,alg:e.alg,sender:e.sender,recipient:e.recipient,timestamp:e.timestamp,nonce:e.nonce,scope:e.scope,payload:e.payload});return(new TextEncoder).encode(r)}async function createEnvelope(e){const r=new Uint8Array(NONCE_BYTES);crypto.getRandomValues(r);const t=new Uint8Array(AES_IV_BYTES);let a;crypto.getRandomValues(t);try{const r=await crypto.subtle.encrypt({name:AES_ALGO,iv:toArrayBuffer(t)},e.sharedKey,toArrayBuffer(e.plaintext)),s=new Uint8Array(t.length+r.byteLength);s.set(t),s.set(new Uint8Array(r),t.length),a=s}catch{return(0,shared_1.err)("ENCRYPT_FAILED")}const s=Date.now(),n={v:1,alg:"Ed25519",sender:e.senderDid,recipient:e.recipientDid,timestamp:s,nonce:(0,crypto_utils_js_1.toBase64)(r),scope:e.scope,payload:(0,crypto_utils_js_1.toBase64)(a)},o=createSignedData(n),i=await(0,identity_js_1.sign)(e.privateKey,o);if(!i.ok)return(0,shared_1.err)("SIGN_FAILED");const _={...n,signature:(0,crypto_utils_js_1.toBase64)(i.value),...e.ephemeralPublicKey?{ephemeralPub:(0,crypto_utils_js_1.toBase64)(e.ephemeralPublicKey)}:{},...void 0!==e.shareIndex?{shareIndex:e.shareIndex,shareTotal:e.shareTotal,shareThreshold:e.shareThreshold,shareGroupId:e.shareGroupId,shareHmacKey:e.shareHmacKey,shareHmacSig:e.shareHmacSig}:{},protocol:"PRIVATE.ME/xBind/v3",documentationUrl:"https://private.me/docs/xbind.html"};return(0,shared_1.ok)(_)}async function createEnvelopeV2(e){const r=new Uint8Array(NONCE_BYTES);crypto.getRandomValues(r);const t=new Uint8Array(AES_IV_BYTES);let a;crypto.getRandomValues(t);try{const r=await crypto.subtle.encrypt({name:AES_ALGO,iv:toArrayBuffer(t)},e.sharedKey,toArrayBuffer(e.plaintext)),s=new Uint8Array(t.length+r.byteLength);s.set(t),s.set(new Uint8Array(r),t.length),a=s}catch{return(0,shared_1.err)("ENCRYPT_FAILED")}const s=Date.now(),n={v:2,alg:"Ed25519",sender:e.senderDid,recipient:e.recipientDid,timestamp:s,nonce:(0,crypto_utils_js_1.toBase64)(r),scope:e.scope,payload:(0,crypto_utils_js_1.toBase64)(a)},o=createSignedData(n),i=await(0,identity_js_1.sign)(e.privateKey,o);if(!i.ok)return(0,shared_1.err)("SIGN_FAILED");const _={...n,kem:"X25519-MLKEM768",signature:(0,crypto_utils_js_1.toBase64)(i.value),ephemeralPub:(0,crypto_utils_js_1.toBase64)(e.ephemeralPublicKey),kemCiphertext:(0,crypto_utils_js_1.toBase64)(e.kemCiphertext),...void 0!==e.shareIndex?{shareIndex:e.shareIndex,shareTotal:e.shareTotal,shareThreshold:e.shareThreshold,shareGroupId:e.shareGroupId,shareHmacKey:e.shareHmacKey,shareHmacSig:e.shareHmacSig}:{},protocol:"PRIVATE.ME/xBind/v3",documentationUrl:"https://private.me/docs/xbind.html"};return(0,shared_1.ok)(_)}async function createEnvelopeV3(e){const r=new Uint8Array(NONCE_BYTES);crypto.getRandomValues(r);const t=new Uint8Array(AES_IV_BYTES);let a;crypto.getRandomValues(t);try{const r=await crypto.subtle.encrypt({name:AES_ALGO,iv:toArrayBuffer(t)},e.sharedKey,toArrayBuffer(e.plaintext)),s=new Uint8Array(t.length+r.byteLength);s.set(t),s.set(new Uint8Array(r),t.length),a=s}catch{return(0,shared_1.err)("ENCRYPT_FAILED")}const s=Date.now(),n={v:3,alg:"Ed25519",sender:e.senderDid,recipient:e.recipientDid,timestamp:s,nonce:(0,crypto_utils_js_1.toBase64)(r),scope:e.scope,payload:(0,crypto_utils_js_1.toBase64)(a)},o=createSignedData(n),i=await(0,identity_js_1.sign)(e.privateKey,o);if(!i.ok)return(0,shared_1.err)("SIGN_FAILED");const _=await(0,identity_js_1.signMlDsa65)(e.mlDsaSecretKey,o);if(!_.ok)return(0,shared_1.err)("PQ_SIGN_FAILED");const c={...n,sig:"Ed25519+MLDSA65",kem:"X25519-MLKEM768",signature:(0,crypto_utils_js_1.toBase64)(i.value),pqSignature:(0,crypto_utils_js_1.toBase64)(_.value),ephemeralPub:(0,crypto_utils_js_1.toBase64)(e.ephemeralPublicKey),kemCiphertext:(0,crypto_utils_js_1.toBase64)(e.kemCiphertext),...void 0!==e.shareIndex?{shareIndex:e.shareIndex,shareTotal:e.shareTotal,shareThreshold:e.shareThreshold,shareGroupId:e.shareGroupId,shareHmacKey:e.shareHmacKey,shareHmacSig:e.shareHmacSig}:{},protocol:"PRIVATE.ME/xBind/v3",documentationUrl:"https://private.me/docs/xbind.html"};return(0,shared_1.ok)(c)}async function createEnvelopeV4(e){const r=new Uint8Array(NONCE_BYTES);crypto.getRandomValues(r);const t=Date.now(),a={v:4,alg:"Ed25519",sender:e.senderDid,recipient:e.recipientDid,timestamp:t,nonce:(0,crypto_utils_js_1.toBase64)(r),scope:e.scope,payload:(0,crypto_utils_js_1.toBase64)(e.shareData)},s=createSignedData(a),n=await(0,identity_js_1.sign)(e.privateKey,s);if(!n.ok)return(0,shared_1.err)("SIGN_FAILED");const o={...a,kem:"Xchange",signature:(0,crypto_utils_js_1.toBase64)(n.value),shareIndex:e.shareIndex,shareTotal:e.shareTotal,shareThreshold:e.shareThreshold,shareGroupId:e.shareGroupId,shareHmacKey:e.shareHmacKey,shareHmacSig:e.shareHmacSig,protocol:"PRIVATE.ME/xBind/v3",documentationUrl:"https://private.me/docs/xbind.html"};return(0,shared_1.ok)(o)}async function decryptPayload(e,r){try{const t=(0,crypto_utils_js_1.fromBase64)(e.payload),a=t.slice(0,AES_IV_BYTES),s=t.slice(AES_IV_BYTES),n=await crypto.subtle.decrypt({name:AES_ALGO,iv:toArrayBuffer(a)},r,toArrayBuffer(s));return(0,shared_1.ok)(new Uint8Array(n))}catch{return(0,shared_1.err)("DECRYPT_FAILED")}}function serializeEnvelope(e){return(new TextEncoder).encode(JSON.stringify(e))}function deserializeEnvelope(e){let r;try{r=JSON.parse((new TextDecoder).decode(e))}catch{return(0,shared_1.err)("PARSE_FAILED")}return validateEnvelope(r)}function validateEnvelope(e){if("object"!=typeof e||null===e)return(0,shared_1.err)("PARSE_FAILED");const r=e;if(1!==r.v&&2!==r.v&&3!==r.v&&4!==r.v)return(0,shared_1.err)("INVALID_VERSION");if("Ed25519"!==r.alg)return(0,shared_1.err)("INVALID_ALG");if("string"!=typeof r.sender||!r.sender.startsWith("did:"))return(0,shared_1.err)("INVALID_DID");if("string"!=typeof r.recipient||!r.recipient.startsWith("did:"))return(0,shared_1.err)("INVALID_DID");if("number"!=typeof r.timestamp)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.scope)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.payload)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.signature)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.nonce)return(0,shared_1.err)("INVALID_NONCE");try{if((0,crypto_utils_js_1.fromBase64)(r.nonce).length!==NONCE_BYTES)return(0,shared_1.err)("INVALID_NONCE")}catch{return(0,shared_1.err)("INVALID_NONCE")}if(void 0!==r.ephemeralPub&&"string"!=typeof r.ephemeralPub)return(0,shared_1.err)("INVALID_FIELDS");if(2===r.v){if("X25519-MLKEM768"!==r.kem)return(0,shared_1.err)("INVALID_KEM");if("string"!=typeof r.ephemeralPub)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.kemCiphertext)return(0,shared_1.err)("INVALID_FIELDS");try{if((0,crypto_utils_js_1.fromBase64)(r.kemCiphertext).length!==KEM_CIPHERTEXT_BYTES)return(0,shared_1.err)("INVALID_FIELDS")}catch{return(0,shared_1.err)("INVALID_FIELDS")}}if(3===r.v){if("Ed25519+MLDSA65"!==r.sig)return(0,shared_1.err)("INVALID_ALG");if("X25519-MLKEM768"!==r.kem)return(0,shared_1.err)("INVALID_KEM");if("string"!=typeof r.ephemeralPub)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.kemCiphertext)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.pqSignature)return(0,shared_1.err)("INVALID_FIELDS");try{if((0,crypto_utils_js_1.fromBase64)(r.kemCiphertext).length!==KEM_CIPHERTEXT_BYTES)return(0,shared_1.err)("INVALID_FIELDS")}catch{return(0,shared_1.err)("INVALID_FIELDS")}try{if((0,crypto_utils_js_1.fromBase64)(r.pqSignature).length!==ML_DSA65_SIG_BYTES)return(0,shared_1.err)("INVALID_FIELDS")}catch{return(0,shared_1.err)("INVALID_FIELDS")}}return 4===r.v?"Xchange"!==r.kem?(0,shared_1.err)("INVALID_KEM"):"number"!=typeof r.shareIndex||"number"!=typeof r.shareTotal||"number"!=typeof r.shareThreshold||"string"!=typeof r.shareGroupId||"string"!=typeof r.shareHmacKey||"string"!=typeof r.shareHmacSig?(0,shared_1.err)("INVALID_FIELDS"):(0,shared_1.ok)(r):void 0!==r.shareIndex&&"number"!=typeof r.shareIndex||void 0!==r.shareTotal&&"number"!=typeof r.shareTotal||void 0!==r.shareThreshold&&"number"!=typeof r.shareThreshold||void 0!==r.shareGroupId&&"string"!=typeof r.shareGroupId||void 0!==r.shareHmacKey&&"string"!=typeof r.shareHmacKey||void 0!==r.shareHmacSig&&"string"!=typeof r.shareHmacSig?(0,shared_1.err)("INVALID_FIELDS"):(0,shared_1.ok)(r)}async function generateSharedKey(){return crypto.subtle.generateKey({name:AES_ALGO,length:256},!0,["encrypt","decrypt"])}async function createSignedEnvelope(e){const r=new Uint8Array(NONCE_BYTES);crypto.getRandomValues(r);const t=Date.now(),a=(0,crypto_utils_js_1.toBase64)(e.plaintext),s=(0,crypto_utils_js_1.toBase64)(r),n={v:1,alg:"Ed25519",sender:e.senderDid,recipient:e.recipientDid,timestamp:t,nonce:s,scope:e.scope,payload:a},o=createSignedData(n),i=await(0,identity_js_1.sign)(e.privateKey,o);if(!i.ok)return(0,shared_1.err)("SIGN_FAILED");const _={...n,signature:(0,crypto_utils_js_1.toBase64)(i.value)};return(0,shared_1.ok)(_)}async function openSignedEnvelope(e,r){const t=(0,crypto_utils_js_1.fromBase64)(e.payload),a=(0,crypto_utils_js_1.fromBase64)(e.signature),s=JSON.stringify({v:e.v,alg:e.alg,sender:e.sender,recipient:e.recipient,timestamp:e.timestamp,nonce:e.nonce,scope:e.scope,payload:e.payload}),n=(new TextEncoder).encode(s),o=await(0,identity_js_1.verify)(r,a,n);return o.ok&&o.value?(0,shared_1.ok)(t):(0,shared_1.err)("VERIFY_FAILED")}
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createEnvelope = createEnvelope;
4
+ exports.createEnvelopeV2 = createEnvelopeV2;
5
+ exports.createEnvelopeV3 = createEnvelopeV3;
6
+ exports.createEnvelopeV4 = createEnvelopeV4;
7
+ exports.decryptPayload = decryptPayload;
8
+ exports.serializeEnvelope = serializeEnvelope;
9
+ exports.deserializeEnvelope = deserializeEnvelope;
10
+ exports.validateEnvelope = validateEnvelope;
11
+ exports.generateSharedKey = generateSharedKey;
12
+ exports.createSignedEnvelope = createSignedEnvelope;
13
+ exports.openSignedEnvelope = openSignedEnvelope;
14
+ const shared_1 = require("../_deps/shared/index.js");
15
+ const crypto_utils_js_1 = require("./crypto-utils.js");
16
+ const identity_js_1 = require("./identity.js");
17
+ /* ── Constants ── */
18
+ const NONCE_BYTES = 16;
19
+ const AES_IV_BYTES = 12;
20
+ const AES_ALGO = 'AES-GCM';
21
+ /** ML-KEM-768 ciphertext length in bytes. */
22
+ const KEM_CIPHERTEXT_BYTES = 1088;
23
+ /** ML-DSA-65 signature length in bytes. */
24
+ const ML_DSA65_SIG_BYTES = 3309;
25
+ /* ── Helpers ── */
26
+ /** Copy Uint8Array to fresh ArrayBuffer. */
27
+ function toArrayBuffer(data) {
28
+ const buf = new ArrayBuffer(data.byteLength);
29
+ new Uint8Array(buf).set(data);
30
+ return buf;
31
+ }
32
+ /**
33
+ * Create canonical representation of envelope fields for signing.
34
+ *
35
+ * SECURITY FIX (v1.1.3): Sign ALL envelope metadata (nonce, timestamp, sender,
36
+ * recipient, scope, payload) to prevent replay attacks via nonce substitution.
37
+ *
38
+ * Previous versions only signed the payload, allowing attackers to:
39
+ * 1. Capture an envelope
40
+ * 2. Change the nonce to a fresh value
41
+ * 3. Replay the message (signature still verified)
42
+ *
43
+ * Canonical format: UTF-8 JSON with sorted keys, no whitespace.
44
+ * Example: {"alg":"Ed25519","nonce":"...","payload":"...","recipient":"...","scope":"...","sender":"...","timestamp":1234567890,"v":1}
45
+ */
46
+ function createSignedData(envelope) {
47
+ // Create canonical JSON representation (sorted keys)
48
+ const canonical = JSON.stringify({
49
+ v: envelope.v,
50
+ alg: envelope.alg,
51
+ sender: envelope.sender,
52
+ recipient: envelope.recipient,
53
+ timestamp: envelope.timestamp,
54
+ nonce: envelope.nonce,
55
+ scope: envelope.scope,
56
+ payload: envelope.payload,
57
+ });
58
+ return new TextEncoder().encode(canonical);
59
+ }
60
+ /* ── Envelope Creation ── */
61
+ /**
62
+ * Create a signed, encrypted TransportEnvelope (version 1).
63
+ *
64
+ * Encrypt-then-sign: AES-256-GCM encrypts payload, Ed25519 signs ciphertext.
65
+ * All envelope metadata (nonce, timestamp, sender, recipient, scope) is included
66
+ * in the signature to prevent replay attacks.
67
+ *
68
+ * @param opts - Envelope creation options
69
+ * @returns Result containing the envelope or error
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * import { createEnvelope, generateSharedKey } from '@private.me/xbind';
74
+ *
75
+ * // Generate shared key (typically from ECDH key agreement)
76
+ * const sharedKey = await generateSharedKey(senderDid, recipientDid);
77
+ * if (!sharedKey.ok) throw new Error(sharedKey.error);
78
+ *
79
+ * // Create encrypted envelope
80
+ * const envelope = await createEnvelope({
81
+ * sender: 'did:key:z6Mk...',
82
+ * recipient: 'did:key:z6Mk...',
83
+ * plaintext: new TextEncoder().encode(JSON.stringify({ message: 'Hello' })),
84
+ * sharedKey: sharedKey.value,
85
+ * privateKey: senderPrivateKey,
86
+ * scope: 'read:messages'
87
+ * });
88
+ *
89
+ * if (envelope.ok) {
90
+ * console.log('Envelope created:', envelope.value);
91
+ * }
92
+ * ```
93
+ */
94
+ async function createEnvelope(opts) {
95
+ const nonce = new Uint8Array(NONCE_BYTES);
96
+ crypto.getRandomValues(nonce);
97
+ const iv = new Uint8Array(AES_IV_BYTES);
98
+ crypto.getRandomValues(iv);
99
+ let ciphertext;
100
+ try {
101
+ const encrypted = await crypto.subtle.encrypt({ name: AES_ALGO, iv: toArrayBuffer(iv) }, opts.sharedKey, toArrayBuffer(opts.plaintext));
102
+ const ivAndCipher = new Uint8Array(iv.length + encrypted.byteLength);
103
+ ivAndCipher.set(iv);
104
+ ivAndCipher.set(new Uint8Array(encrypted), iv.length);
105
+ ciphertext = ivAndCipher;
106
+ }
107
+ catch {
108
+ return (0, shared_1.err)('ENCRYPT_FAILED');
109
+ }
110
+ // SECURITY FIX (v1.1.3): Sign canonical representation of ENTIRE envelope
111
+ // (not just payload) to prevent replay attacks via nonce substitution
112
+ const timestamp = Date.now();
113
+ const envelopeFields = {
114
+ v: 1,
115
+ alg: 'Ed25519',
116
+ sender: opts.senderDid,
117
+ recipient: opts.recipientDid,
118
+ timestamp,
119
+ nonce: (0, crypto_utils_js_1.toBase64)(nonce),
120
+ scope: opts.scope,
121
+ payload: (0, crypto_utils_js_1.toBase64)(ciphertext),
122
+ };
123
+ const signedData = createSignedData(envelopeFields);
124
+ const sigResult = await (0, identity_js_1.sign)(opts.privateKey, signedData);
125
+ if (!sigResult.ok)
126
+ return (0, shared_1.err)('SIGN_FAILED');
127
+ const envelope = {
128
+ ...envelopeFields,
129
+ signature: (0, crypto_utils_js_1.toBase64)(sigResult.value),
130
+ ...(opts.ephemeralPublicKey
131
+ ? { ephemeralPub: (0, crypto_utils_js_1.toBase64)(opts.ephemeralPublicKey) }
132
+ : {}),
133
+ ...(opts.shareIndex !== undefined
134
+ ? {
135
+ shareIndex: opts.shareIndex,
136
+ shareTotal: opts.shareTotal,
137
+ shareThreshold: opts.shareThreshold,
138
+ shareGroupId: opts.shareGroupId,
139
+ shareHmacKey: opts.shareHmacKey,
140
+ shareHmacSig: opts.shareHmacSig,
141
+ }
142
+ : {}),
143
+ protocol: 'PRIVATE.ME/xBind/v3',
144
+ documentationUrl: 'https://private.me/docs/xbind.html',
145
+ };
146
+ return (0, shared_1.ok)(envelope);
147
+ }
148
+ /* ── V2 Envelope Creation ── */
149
+ /**
150
+ * Create a signed, encrypted TransportEnvelopeV2 with hybrid KEM.
151
+ *
152
+ * Same encrypt-then-sign as v1, but includes ML-KEM-768 ciphertext.
153
+ */
154
+ async function createEnvelopeV2(opts) {
155
+ const nonce = new Uint8Array(NONCE_BYTES);
156
+ crypto.getRandomValues(nonce);
157
+ const iv = new Uint8Array(AES_IV_BYTES);
158
+ crypto.getRandomValues(iv);
159
+ let ciphertext;
160
+ try {
161
+ const encrypted = await crypto.subtle.encrypt({ name: AES_ALGO, iv: toArrayBuffer(iv) }, opts.sharedKey, toArrayBuffer(opts.plaintext));
162
+ const ivAndCipher = new Uint8Array(iv.length + encrypted.byteLength);
163
+ ivAndCipher.set(iv);
164
+ ivAndCipher.set(new Uint8Array(encrypted), iv.length);
165
+ ciphertext = ivAndCipher;
166
+ }
167
+ catch {
168
+ return (0, shared_1.err)('ENCRYPT_FAILED');
169
+ }
170
+ // SECURITY FIX (v1.1.3): Sign canonical representation of ENTIRE envelope
171
+ const timestamp = Date.now();
172
+ const envelopeFields = {
173
+ v: 2,
174
+ alg: 'Ed25519',
175
+ sender: opts.senderDid,
176
+ recipient: opts.recipientDid,
177
+ timestamp,
178
+ nonce: (0, crypto_utils_js_1.toBase64)(nonce),
179
+ scope: opts.scope,
180
+ payload: (0, crypto_utils_js_1.toBase64)(ciphertext),
181
+ };
182
+ const signedData = createSignedData(envelopeFields);
183
+ const sigResult = await (0, identity_js_1.sign)(opts.privateKey, signedData);
184
+ if (!sigResult.ok)
185
+ return (0, shared_1.err)('SIGN_FAILED');
186
+ const envelope = {
187
+ ...envelopeFields,
188
+ kem: 'X25519-MLKEM768',
189
+ signature: (0, crypto_utils_js_1.toBase64)(sigResult.value),
190
+ ephemeralPub: (0, crypto_utils_js_1.toBase64)(opts.ephemeralPublicKey),
191
+ kemCiphertext: (0, crypto_utils_js_1.toBase64)(opts.kemCiphertext),
192
+ ...(opts.shareIndex !== undefined
193
+ ? {
194
+ shareIndex: opts.shareIndex,
195
+ shareTotal: opts.shareTotal,
196
+ shareThreshold: opts.shareThreshold,
197
+ shareGroupId: opts.shareGroupId,
198
+ shareHmacKey: opts.shareHmacKey,
199
+ shareHmacSig: opts.shareHmacSig,
200
+ }
201
+ : {}),
202
+ protocol: 'PRIVATE.ME/xBind/v3',
203
+ documentationUrl: 'https://private.me/docs/xbind.html',
204
+ };
205
+ return (0, shared_1.ok)(envelope);
206
+ }
207
+ /* ── V3 Envelope Creation ── */
208
+ /**
209
+ * Create a signed, encrypted TransportEnvelopeV3 with hybrid KEM + dual signatures.
210
+ *
211
+ * Encrypt-then-sign: AES-256-GCM encrypts payload, Ed25519 AND ML-DSA-65 sign ciphertext.
212
+ * Both signatures must verify for the envelope to be accepted.
213
+ */
214
+ async function createEnvelopeV3(opts) {
215
+ const nonce = new Uint8Array(NONCE_BYTES);
216
+ crypto.getRandomValues(nonce);
217
+ const iv = new Uint8Array(AES_IV_BYTES);
218
+ crypto.getRandomValues(iv);
219
+ let ciphertext;
220
+ try {
221
+ const encrypted = await crypto.subtle.encrypt({ name: AES_ALGO, iv: toArrayBuffer(iv) }, opts.sharedKey, toArrayBuffer(opts.plaintext));
222
+ const ivAndCipher = new Uint8Array(iv.length + encrypted.byteLength);
223
+ ivAndCipher.set(iv);
224
+ ivAndCipher.set(new Uint8Array(encrypted), iv.length);
225
+ ciphertext = ivAndCipher;
226
+ }
227
+ catch {
228
+ return (0, shared_1.err)('ENCRYPT_FAILED');
229
+ }
230
+ // SECURITY FIX (v1.1.3): Sign canonical representation of ENTIRE envelope
231
+ const timestamp = Date.now();
232
+ const envelopeFields = {
233
+ v: 3,
234
+ alg: 'Ed25519',
235
+ sender: opts.senderDid,
236
+ recipient: opts.recipientDid,
237
+ timestamp,
238
+ nonce: (0, crypto_utils_js_1.toBase64)(nonce),
239
+ scope: opts.scope,
240
+ payload: (0, crypto_utils_js_1.toBase64)(ciphertext),
241
+ };
242
+ const signedData = createSignedData(envelopeFields);
243
+ const sigResult = await (0, identity_js_1.sign)(opts.privateKey, signedData);
244
+ if (!sigResult.ok)
245
+ return (0, shared_1.err)('SIGN_FAILED');
246
+ const pqSigResult = await (0, identity_js_1.signMlDsa65)(opts.mlDsaSecretKey, signedData);
247
+ if (!pqSigResult.ok)
248
+ return (0, shared_1.err)('PQ_SIGN_FAILED');
249
+ const envelope = {
250
+ ...envelopeFields,
251
+ sig: 'Ed25519+MLDSA65',
252
+ kem: 'X25519-MLKEM768',
253
+ signature: (0, crypto_utils_js_1.toBase64)(sigResult.value),
254
+ pqSignature: (0, crypto_utils_js_1.toBase64)(pqSigResult.value),
255
+ ephemeralPub: (0, crypto_utils_js_1.toBase64)(opts.ephemeralPublicKey),
256
+ kemCiphertext: (0, crypto_utils_js_1.toBase64)(opts.kemCiphertext),
257
+ ...(opts.shareIndex !== undefined
258
+ ? {
259
+ shareIndex: opts.shareIndex,
260
+ shareTotal: opts.shareTotal,
261
+ shareThreshold: opts.shareThreshold,
262
+ shareGroupId: opts.shareGroupId,
263
+ shareHmacKey: opts.shareHmacKey,
264
+ shareHmacSig: opts.shareHmacSig,
265
+ }
266
+ : {}),
267
+ protocol: 'PRIVATE.ME/xBind/v3',
268
+ documentationUrl: 'https://private.me/docs/xbind.html',
269
+ };
270
+ return (0, shared_1.ok)(envelope);
271
+ }
272
+ /* ── Xchange Mode Envelope Creation ── */
273
+ /**
274
+ * Create a signed Xchange mode envelope (v4 wire format).
275
+ *
276
+ * Opt-in performance mode. No encryption — the share IS the payload.
277
+ * Ed25519 signs the raw share data for sender authentication.
278
+ * The XorIDA split provides confidentiality (information-theoretic).
279
+ */
280
+ async function createEnvelopeV4(opts) {
281
+ const nonce = new Uint8Array(NONCE_BYTES);
282
+ crypto.getRandomValues(nonce);
283
+ // SECURITY FIX (v1.1.3): Sign canonical representation of ENTIRE envelope
284
+ const timestamp = Date.now();
285
+ const envelopeFields = {
286
+ v: 4,
287
+ alg: 'Ed25519',
288
+ sender: opts.senderDid,
289
+ recipient: opts.recipientDid,
290
+ timestamp,
291
+ nonce: (0, crypto_utils_js_1.toBase64)(nonce),
292
+ scope: opts.scope,
293
+ payload: (0, crypto_utils_js_1.toBase64)(opts.shareData),
294
+ };
295
+ const signedData = createSignedData(envelopeFields);
296
+ const sigResult = await (0, identity_js_1.sign)(opts.privateKey, signedData);
297
+ if (!sigResult.ok)
298
+ return (0, shared_1.err)('SIGN_FAILED');
299
+ const envelope = {
300
+ ...envelopeFields,
301
+ kem: 'Xchange',
302
+ signature: (0, crypto_utils_js_1.toBase64)(sigResult.value),
303
+ shareIndex: opts.shareIndex,
304
+ shareTotal: opts.shareTotal,
305
+ shareThreshold: opts.shareThreshold,
306
+ shareGroupId: opts.shareGroupId,
307
+ shareHmacKey: opts.shareHmacKey,
308
+ shareHmacSig: opts.shareHmacSig,
309
+ protocol: 'PRIVATE.ME/xBind/v3',
310
+ documentationUrl: 'https://private.me/docs/xbind.html',
311
+ };
312
+ return (0, shared_1.ok)(envelope);
313
+ }
314
+ /* ── Decryption ── */
315
+ /**
316
+ * Decrypt the payload from a v1, v2, or v3 TransportEnvelope.
317
+ * Caller must verify signature before calling this.
318
+ */
319
+ async function decryptPayload(envelope, sharedKey) {
320
+ try {
321
+ const ciphertext = (0, crypto_utils_js_1.fromBase64)(envelope.payload);
322
+ const iv = ciphertext.slice(0, AES_IV_BYTES);
323
+ const data = ciphertext.slice(AES_IV_BYTES);
324
+ const decrypted = await crypto.subtle.decrypt({ name: AES_ALGO, iv: toArrayBuffer(iv) }, sharedKey, toArrayBuffer(data));
325
+ return (0, shared_1.ok)(new Uint8Array(decrypted));
326
+ }
327
+ catch {
328
+ return (0, shared_1.err)('DECRYPT_FAILED');
329
+ }
330
+ }
331
+ /* ── Serialization ── */
332
+ /** Serialize envelope to UTF-8 bytes. */
333
+ function serializeEnvelope(envelope) {
334
+ return new TextEncoder().encode(JSON.stringify(envelope));
335
+ }
336
+ /** Deserialize bytes to a validated v1 or v2 TransportEnvelope. */
337
+ function deserializeEnvelope(bytes) {
338
+ let parsed;
339
+ try {
340
+ parsed = JSON.parse(new TextDecoder().decode(bytes));
341
+ }
342
+ catch {
343
+ return (0, shared_1.err)('PARSE_FAILED');
344
+ }
345
+ return validateEnvelope(parsed);
346
+ }
347
+ /* ── Validation ── */
348
+ /** Validate a parsed object is a valid v1 or v2 TransportEnvelope. */
349
+ function validateEnvelope(obj) {
350
+ if (typeof obj !== 'object' || obj === null)
351
+ return (0, shared_1.err)('PARSE_FAILED');
352
+ const e = obj;
353
+ if (e['v'] !== 1 && e['v'] !== 2 && e['v'] !== 3 && e['v'] !== 4)
354
+ return (0, shared_1.err)('INVALID_VERSION');
355
+ if (e['alg'] !== 'Ed25519')
356
+ return (0, shared_1.err)('INVALID_ALG');
357
+ if (typeof e['sender'] !== 'string' || !e['sender'].startsWith('did:'))
358
+ return (0, shared_1.err)('INVALID_DID');
359
+ if (typeof e['recipient'] !== 'string' || !e['recipient'].startsWith('did:'))
360
+ return (0, shared_1.err)('INVALID_DID');
361
+ if (typeof e['timestamp'] !== 'number')
362
+ return (0, shared_1.err)('INVALID_FIELDS');
363
+ if (typeof e['scope'] !== 'string')
364
+ return (0, shared_1.err)('INVALID_FIELDS');
365
+ if (typeof e['payload'] !== 'string')
366
+ return (0, shared_1.err)('INVALID_FIELDS');
367
+ if (typeof e['signature'] !== 'string')
368
+ return (0, shared_1.err)('INVALID_FIELDS');
369
+ if (typeof e['nonce'] !== 'string')
370
+ return (0, shared_1.err)('INVALID_NONCE');
371
+ try {
372
+ const nonceBytes = (0, crypto_utils_js_1.fromBase64)(e['nonce']);
373
+ if (nonceBytes.length !== NONCE_BYTES)
374
+ return (0, shared_1.err)('INVALID_NONCE');
375
+ }
376
+ catch {
377
+ return (0, shared_1.err)('INVALID_NONCE');
378
+ }
379
+ if (e['ephemeralPub'] !== undefined && typeof e['ephemeralPub'] !== 'string') {
380
+ return (0, shared_1.err)('INVALID_FIELDS');
381
+ }
382
+ // V2-specific validation
383
+ if (e['v'] === 2) {
384
+ if (e['kem'] !== 'X25519-MLKEM768')
385
+ return (0, shared_1.err)('INVALID_KEM');
386
+ if (typeof e['ephemeralPub'] !== 'string')
387
+ return (0, shared_1.err)('INVALID_FIELDS');
388
+ if (typeof e['kemCiphertext'] !== 'string')
389
+ return (0, shared_1.err)('INVALID_FIELDS');
390
+ try {
391
+ const kemBytes = (0, crypto_utils_js_1.fromBase64)(e['kemCiphertext']);
392
+ if (kemBytes.length !== KEM_CIPHERTEXT_BYTES)
393
+ return (0, shared_1.err)('INVALID_FIELDS');
394
+ }
395
+ catch {
396
+ return (0, shared_1.err)('INVALID_FIELDS');
397
+ }
398
+ }
399
+ // V3-specific validation (hybrid KEM + dual signatures)
400
+ if (e['v'] === 3) {
401
+ if (e['sig'] !== 'Ed25519+MLDSA65')
402
+ return (0, shared_1.err)('INVALID_ALG');
403
+ if (e['kem'] !== 'X25519-MLKEM768')
404
+ return (0, shared_1.err)('INVALID_KEM');
405
+ if (typeof e['ephemeralPub'] !== 'string')
406
+ return (0, shared_1.err)('INVALID_FIELDS');
407
+ if (typeof e['kemCiphertext'] !== 'string')
408
+ return (0, shared_1.err)('INVALID_FIELDS');
409
+ if (typeof e['pqSignature'] !== 'string')
410
+ return (0, shared_1.err)('INVALID_FIELDS');
411
+ try {
412
+ const kemBytes = (0, crypto_utils_js_1.fromBase64)(e['kemCiphertext']);
413
+ if (kemBytes.length !== KEM_CIPHERTEXT_BYTES)
414
+ return (0, shared_1.err)('INVALID_FIELDS');
415
+ }
416
+ catch {
417
+ return (0, shared_1.err)('INVALID_FIELDS');
418
+ }
419
+ try {
420
+ const pqSigBytes = (0, crypto_utils_js_1.fromBase64)(e['pqSignature']);
421
+ if (pqSigBytes.length !== ML_DSA65_SIG_BYTES)
422
+ return (0, shared_1.err)('INVALID_FIELDS');
423
+ }
424
+ catch {
425
+ return (0, shared_1.err)('INVALID_FIELDS');
426
+ }
427
+ }
428
+ // V4-specific validation (Xchange — no encryption, share metadata required)
429
+ if (e['v'] === 4) {
430
+ if (e['kem'] !== 'Xchange')
431
+ return (0, shared_1.err)('INVALID_KEM');
432
+ if (typeof e['shareIndex'] !== 'number')
433
+ return (0, shared_1.err)('INVALID_FIELDS');
434
+ if (typeof e['shareTotal'] !== 'number')
435
+ return (0, shared_1.err)('INVALID_FIELDS');
436
+ if (typeof e['shareThreshold'] !== 'number')
437
+ return (0, shared_1.err)('INVALID_FIELDS');
438
+ if (typeof e['shareGroupId'] !== 'string')
439
+ return (0, shared_1.err)('INVALID_FIELDS');
440
+ if (typeof e['shareHmacKey'] !== 'string')
441
+ return (0, shared_1.err)('INVALID_FIELDS');
442
+ if (typeof e['shareHmacSig'] !== 'string')
443
+ return (0, shared_1.err)('INVALID_FIELDS');
444
+ return (0, shared_1.ok)(e);
445
+ }
446
+ if (e['shareIndex'] !== undefined && typeof e['shareIndex'] !== 'number') {
447
+ return (0, shared_1.err)('INVALID_FIELDS');
448
+ }
449
+ if (e['shareTotal'] !== undefined && typeof e['shareTotal'] !== 'number') {
450
+ return (0, shared_1.err)('INVALID_FIELDS');
451
+ }
452
+ if (e['shareThreshold'] !== undefined && typeof e['shareThreshold'] !== 'number') {
453
+ return (0, shared_1.err)('INVALID_FIELDS');
454
+ }
455
+ if (e['shareGroupId'] !== undefined && typeof e['shareGroupId'] !== 'string') {
456
+ return (0, shared_1.err)('INVALID_FIELDS');
457
+ }
458
+ if (e['shareHmacKey'] !== undefined && typeof e['shareHmacKey'] !== 'string') {
459
+ return (0, shared_1.err)('INVALID_FIELDS');
460
+ }
461
+ if (e['shareHmacSig'] !== undefined && typeof e['shareHmacSig'] !== 'string') {
462
+ return (0, shared_1.err)('INVALID_FIELDS');
463
+ }
464
+ return (0, shared_1.ok)(e);
465
+ }
466
+ /** Generate an AES-256-GCM key for envelope encryption. */
467
+ async function generateSharedKey() {
468
+ return crypto.subtle.generateKey({ name: AES_ALGO, length: 256 }, true, ['encrypt', 'decrypt']);
469
+ }
470
+ /* ── Signed (Unencrypted) Envelopes ── */
471
+ /**
472
+ * Create a signed but unencrypted TransportEnvelope.
473
+ *
474
+ * Payload is base64-encoded plaintext (NOT encrypted).
475
+ * Signature covers the raw plaintext bytes.
476
+ * Use for public announcements, audit logs, or telemetry where
477
+ * confidentiality is not required but integrity is.
478
+ *
479
+ * @param opts - Sender, recipient, scope, plaintext, and signing key.
480
+ * @returns Signed envelope or error.
481
+ */
482
+ async function createSignedEnvelope(opts) {
483
+ const nonce = new Uint8Array(NONCE_BYTES);
484
+ crypto.getRandomValues(nonce);
485
+ const timestamp = Date.now();
486
+ const payloadBase64 = (0, crypto_utils_js_1.toBase64)(opts.plaintext);
487
+ const nonceBase64 = (0, crypto_utils_js_1.toBase64)(nonce);
488
+ // SECURITY FIX (v1.1.3): Sign canonical representation of ENTIRE envelope
489
+ // (not just payload) to prevent replay attacks via nonce/timestamp mutation
490
+ const envelopeFields = {
491
+ v: 1,
492
+ alg: 'Ed25519',
493
+ sender: opts.senderDid,
494
+ recipient: opts.recipientDid,
495
+ timestamp,
496
+ nonce: nonceBase64,
497
+ scope: opts.scope,
498
+ payload: payloadBase64,
499
+ };
500
+ const signedData = createSignedData(envelopeFields);
501
+ const sigResult = await (0, identity_js_1.sign)(opts.privateKey, signedData);
502
+ if (!sigResult.ok)
503
+ return (0, shared_1.err)('SIGN_FAILED');
504
+ const envelope = {
505
+ ...envelopeFields,
506
+ signature: (0, crypto_utils_js_1.toBase64)(sigResult.value),
507
+ };
508
+ return (0, shared_1.ok)(envelope);
509
+ }
510
+ /**
511
+ * Verify signature on a signed (unencrypted) envelope and return plaintext.
512
+ *
513
+ * @param envelope - The signed envelope to verify.
514
+ * @param senderPublicKey - The sender's Ed25519 public key.
515
+ * @returns Plaintext bytes if signature is valid, error otherwise.
516
+ */
517
+ async function openSignedEnvelope(envelope, senderPublicKey) {
518
+ const payloadBytes = (0, crypto_utils_js_1.fromBase64)(envelope.payload);
519
+ const sigBytes = (0, crypto_utils_js_1.fromBase64)(envelope.signature);
520
+ // SECURITY FIX (v1.1.3): Verify canonical representation (not just payload)
521
+ const canonicalData = JSON.stringify({
522
+ v: envelope.v,
523
+ alg: envelope.alg,
524
+ sender: envelope.sender,
525
+ recipient: envelope.recipient,
526
+ timestamp: envelope.timestamp,
527
+ nonce: envelope.nonce,
528
+ scope: envelope.scope,
529
+ payload: envelope.payload,
530
+ });
531
+ const canonicalBytes = new TextEncoder().encode(canonicalData);
532
+ const valid = await (0, identity_js_1.verify)(senderPublicKey, sigBytes, canonicalBytes);
533
+ if (!valid.ok)
534
+ return (0, shared_1.err)('VERIFY_FAILED');
535
+ if (!valid.value)
536
+ return (0, shared_1.err)('VERIFY_FAILED');
537
+ return (0, shared_1.ok)(payloadBytes);
538
+ }